use std::fs::{self, File}; use std::io::{self, BufWriter, Read, Seek, SeekFrom, Write}; #[cfg(unix)] use std::os::unix::fs::MetadataExt; use std::path::{Path, PathBuf}; use std::sync::mpsc::{self, SyncSender, TrySendError}; use std::sync::{Arc, Mutex}; use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use std::collections::VecDeque; use serde::{Deserialize, Serialize}; /// The reason a deliberately empty voice prompt records on its discard. pub const VOICE_PROMPT_NOTHING_REASON: &str = "voice prompt asked nothing"; #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(tag = "kind", rename_all = "snake_case")] pub enum VoiceEvent { SessionStarted { timestamp_ms: u64, }, State { timestamp_ms: u64, state: VoiceState, device: String, }, Transcript { timestamp_ms: u64, phase: TranscriptPhase, latency_ms: u32, text: String, }, Command { timestamp_ms: u64, heard: String, command: Option, outcome: CommandOutcome, #[serde(default)] context: String, }, Dictation { timestamp_ms: u64, phase: DictationPhase, #[serde(default)] text: String, #[serde(default, skip_serializing_if = "Option::is_none")] processing: Option, /// Why a press was discarded as a chord: `key`, `hid-key`, `mouse`, or /// `extra-modifier`. Absent for other phases and short taps. #[serde(default, skip_serializing_if = "Option::is_none")] reason: Option, }, /// The foreground application. Never the page address: this log is a /// plain file, and a running list of pages is browsing history. Context { timestamp_ms: u64, application: Option, }, ApiServerStarted { timestamp_ms: u64, port: u16, }, ApiServerStopped { timestamp_ms: u64, }, ApiAuthFailed { timestamp_ms: u64, method: String, path: String, }, } impl VoiceEvent { pub fn timestamp_ms(&self) -> u64 { match self { Self::SessionStarted { timestamp_ms } | Self::State { timestamp_ms, .. } | Self::Transcript { timestamp_ms, .. } | Self::Command { timestamp_ms, .. } | Self::Dictation { timestamp_ms, .. } | Self::Context { timestamp_ms, .. } | Self::ApiServerStarted { timestamp_ms, .. } | Self::ApiServerStopped { timestamp_ms } | Self::ApiAuthFailed { timestamp_ms, .. } => *timestamp_ms, } } pub fn kind(&self) -> &'static str { match self { Self::SessionStarted { .. } => "session_started", Self::State { .. } => "state", Self::Transcript { .. } => "transcript", Self::Command { .. } => "command", Self::Dictation { .. } => "dictation", Self::Context { .. } => "context", Self::ApiServerStarted { .. } => "api_server_started", Self::ApiServerStopped { .. } => "api_server_stopped", Self::ApiAuthFailed { .. } => "api_auth_failed", } } } #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub enum VoiceState { Sleeping, Listening, Dictating, Transcribing, Stopping, } #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub enum DictationPhase { Started, Discarded, Cancelled, Transcribing, /// The paste shortcut was sent. No platform confirms that the focused /// application accepted it, so this does not prove the text landed. Pasted, /// No paste chord was sent: the text stayed on the clipboard, because the /// window in front could not take one (the Windows desktop or a taskbar), /// or Labs › Copy dictation only is on. Copied, /// `hex dictation stop --print` received the text instead of a paste. Printed, Edited, VoiceAction, // Retained so activity readers can decode records written by older releases. Logged, Repasted, MeetingPasted, Failed(String), } #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] pub struct DictationProcessing { pub profile: String, pub latency_ms: u64, /// The OpenCode rewrite model this processing ran against, as /// `provider/id`: the one that answered, or on failure the one the request /// asked for. Absent when no model was named (OpenCode's own default /// answered, or an automatic choice failed before any model answered), /// for the on-device Apple Intelligence cleanup pass, and in events /// written before the model was recorded. #[serde(default, skip_serializing_if = "Option::is_none")] pub model: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub fallback: Option, } #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub enum CommandOutcome { Ignored, Woke, Slept, Submitted, Executed, Failed(String), } #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub enum TranscriptPhase { Started, Updated, Completed, } #[derive(Clone)] pub struct EventLog { inner: Arc, } struct EventLogInner { sender: Option>, error: Arc>>, worker: Option>, } enum WriterMessage { Event(VoiceEvent), Flush(mpsc::SyncSender>), } pub struct EventReader { path: PathBuf, offset: u64, pending: Vec, discarding_record: bool, events: VecDeque, current_context: Option>, /// The file's first bytes when last read. The log trim /// (`desktop::log_trim`) moves newer lines to the front in place, so a /// changed head means the offset no longer points into the same records. head: Vec, #[cfg(unix)] file_id: Option<(u64, u64)>, } const EVENT_RETENTION: usize = 1_024; const EVENT_WRITER_CAPACITY: usize = 1_024; const EVENT_READ_BUFFER_BYTES: usize = 16 * 1024; const HEAD_BYTES: usize = 64; // This is an observation-reader limit, not a limit on capture or persisted output. const MAX_EVENT_RECORD_BYTES: usize = 1024 * 1024; impl EventLog { pub fn create(path: &Path) -> io::Result { if let Some(parent) = path.parent() { fs::create_dir_all(parent)?; } let file = crate::app_paths::open_private_append(path)?; let (sender, receiver) = mpsc::sync_channel(EVENT_WRITER_CAPACITY); let error = Arc::new(Mutex::new(None)); let worker_error = error.clone(); let worker = thread::Builder::new() .name("event-writer".into()) .spawn(move || run_event_writer(BufWriter::new(file), receiver, worker_error))?; Ok(Self { inner: Arc::new(EventLogInner { sender: Some(sender), error, worker: Some(worker), }), }) } pub fn emit(&self, event: &VoiceEvent) -> io::Result<()> { self.check_error()?; let sender = self .inner .sender .as_ref() .ok_or_else(|| io::Error::new(io::ErrorKind::BrokenPipe, "event writer stopped"))?; match sender.try_send(WriterMessage::Event(event.without_words())) { Ok(()) => Ok(()), Err(TrySendError::Full(WriterMessage::Event(event))) if event.is_replaceable() => { Ok(()) } Err(TrySendError::Full(message)) => sender .send(message) .map_err(|_| self.writer_stopped_error()), Err(TrySendError::Disconnected(_)) => Err(self.writer_stopped_error()), } } pub fn flush(&self) -> io::Result<()> { self.check_error()?; let (reply, flushed) = mpsc::sync_channel(0); self.inner .sender .as_ref() .ok_or_else(|| self.writer_stopped_error())? .send(WriterMessage::Flush(reply)) .map_err(|_| self.writer_stopped_error())?; match flushed.recv().map_err(|_| self.writer_stopped_error())? { Some((kind, message)) => Err(io::Error::new(kind, message)), None => Ok(()), } } /// Like [`Self::flush`], but gives up after `deadline`, so quitting /// never waits on a stalled disk. pub fn flush_within(&self, deadline: Duration) -> io::Result<()> { self.check_error()?; let started = Instant::now(); let sender = self .inner .sender .as_ref() .ok_or_else(|| self.writer_stopped_error())?; let (reply, flushed) = mpsc::sync_channel(1); let mut message = WriterMessage::Flush(reply); loop { match sender.try_send(message) { Ok(()) => break, Err(TrySendError::Full(returned)) if started.elapsed() < deadline => { message = returned; thread::sleep(Duration::from_millis(5)); } Err(TrySendError::Full(_)) => { return Err(io::Error::new( io::ErrorKind::TimedOut, "event log flush timed out", )); } Err(TrySendError::Disconnected(_)) => return Err(self.writer_stopped_error()), } } match flushed.recv_timeout(deadline.saturating_sub(started.elapsed())) { Ok(Some((kind, message))) => Err(io::Error::new(kind, message)), Ok(None) => Ok(()), Err(mpsc::RecvTimeoutError::Timeout) => Err(io::Error::new( io::ErrorKind::TimedOut, "event log flush timed out", )), Err(mpsc::RecvTimeoutError::Disconnected) => Err(self.writer_stopped_error()), } } fn check_error(&self) -> io::Result<()> { match self .inner .error .lock() .unwrap_or_else(|error| error.into_inner()) .as_ref() { Some((kind, message)) => Err(io::Error::new(*kind, message.clone())), None => Ok(()), } } fn writer_stopped_error(&self) -> io::Error { self.check_error() .err() .unwrap_or_else(|| io::Error::new(io::ErrorKind::BrokenPipe, "event writer stopped")) } pub fn dictation(&self, phase: DictationPhase, text: impl Into) -> io::Result<()> { self.emit(&VoiceEvent::Dictation { timestamp_ms: now_ms(), phase, text: text.into(), processing: None, reason: None, }) } /// A capture discarded as a chord, with its cause when known. pub fn discarded_dictation(&self, reason: Option<&str>) -> io::Result<()> { self.emit(&VoiceEvent::Dictation { timestamp_ms: now_ms(), phase: DictationPhase::Discarded, text: String::new(), processing: None, reason: reason.map(Into::into), }) } /// A voice prompt that deliberately asked nothing. #[cfg_attr(not(any(target_os = "linux", target_os = "windows")), allow(dead_code))] pub fn discarded_voice_prompt(&self) -> io::Result<()> { self.discarded_dictation(Some(VOICE_PROMPT_NOTHING_REASON)) } /// A recording shortcut whose microphone failed kept the audio delivered /// before the loss; it is transcribed and copied instead of pasted. pub fn salvaged_dictation(&self) -> io::Result<()> { self.emit(&VoiceEvent::Dictation { timestamp_ms: now_ms(), phase: DictationPhase::Transcribing, text: String::new(), processing: None, reason: Some("microphone-lost".into()), }) } pub fn processed_dictation( &self, phase: DictationPhase, text: impl Into, processing: Option, ) -> io::Result<()> { self.emit(&VoiceEvent::Dictation { timestamp_ms: now_ms(), phase, text: text.into(), processing, reason: None, }) } } impl VoiceEvent { /// The event as it is written: what was said stays out of the log. The /// log is a plain file kept for diagnosis, never trimmed by History's /// retention or Clear all, and `hex logs` prints it, so dictated words /// live only in History. fn without_words(&self) -> Self { let mut event = self.clone(); match &mut event { Self::Transcript { text, .. } | Self::Dictation { text, .. } => text.clear(), Self::Command { heard, .. } => heard.clear(), _ => {} } event } fn is_replaceable(&self) -> bool { matches!( self, Self::Transcript { phase: TranscriptPhase::Started | TranscriptPhase::Updated, .. } | Self::Context { .. } ) } } impl Drop for EventLogInner { fn drop(&mut self) { self.sender.take(); if let Some(worker) = self.worker.take() { let _ = worker.join(); } } } fn run_event_writer( mut writer: BufWriter, receiver: mpsc::Receiver, error: Arc>>, ) { let record_error = |result: io::Result<()>| -> Option<(io::ErrorKind, String)> { let write_error = result.err()?; let failure = (write_error.kind(), write_error.to_string()); *error.lock().unwrap_or_else(|error| error.into_inner()) = Some(failure.clone()); Some(failure) }; while let Ok(message) = receiver.recv() { match message { WriterMessage::Event(event) => { let result = serde_json::to_writer(&mut writer, &event) .map_err(io::Error::other) .and_then(|()| writer.write_all(b"\n")) .and_then(|()| writer.flush()); if record_error(result).is_some() { break; } } WriterMessage::Flush(reply) => { let failure = record_error(writer.flush()); let failed = failure.is_some(); let _ = reply.send(failure); if failed { break; } } } } let _ = writer.flush(); } impl EventReader { pub fn open(path: impl Into) -> Self { Self { path: path.into(), offset: 0, pending: Vec::new(), discarding_record: false, events: VecDeque::new(), current_context: None, head: Vec::new(), #[cfg(unix)] file_id: None, } } pub fn refresh(&mut self) -> io::Result<()> { let mut file = match File::open(&self.path) { Ok(file) => file, Err(error) if error.kind() == io::ErrorKind::NotFound => { self.reset(); return Ok(()); } Err(error) => return Err(error), }; let metadata = file.metadata()?; if metadata.len() < self.offset { self.reset(); } #[cfg(unix)] { let file_id = (metadata.dev(), metadata.ino()); if self.file_id.is_some_and(|current| current != file_id) { self.reset(); } self.file_id = Some(file_id); } let mut head = Vec::with_capacity(HEAD_BYTES); (&mut file).take(HEAD_BYTES as u64).read_to_end(&mut head)?; if !head.starts_with(&self.head) { self.reset(); } self.head = head; file.seek(SeekFrom::Start(self.offset))?; // Read this snapshot only: a busy writer must not keep refresh chasing EOF. let mut appended = file.take(metadata.len() - self.offset); let mut buffer = [0; EVENT_READ_BUFFER_BYTES]; loop { let count = match appended.read(&mut buffer) { Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, result => result?, }; if count == 0 { break; } self.offset += count as u64; self.read_records(&buffer[..count]); } Ok(()) } fn read_records(&mut self, bytes: &[u8]) { for part in bytes.split_inclusive(|byte| *byte == b'\n') { let complete = part.last() == Some(&b'\n'); let text = if complete { &part[..part.len() - 1] } else { part }; if !self.discarding_record { if self.pending.len() + text.len() > MAX_EVENT_RECORD_BYTES { self.pending.clear(); self.discarding_record = true; } else { self.pending.extend_from_slice(text); } } if complete { if !self.discarding_record && let Ok(event) = serde_json::from_slice(&self.pending) { self.push(event); } self.pending.clear(); self.discarding_record = false; } } } pub fn events(&self) -> &VecDeque { &self.events } /// Takes the events read so far, so the next `refresh` yields only newer ones. pub fn drain(&mut self) -> impl Iterator + '_ { self.events.drain(..) } pub fn recent(&self, limit: usize) -> Vec { self.events.iter().rev().take(limit).cloned().collect() } /// The foreground app from the latest context event, even one older /// than the retained events. pub fn current_context(&self) -> Option<&Option> { self.current_context.as_ref() } pub fn path(&self) -> &Path { &self.path } fn push(&mut self, event: VoiceEvent) { if matches!(event, VoiceEvent::SessionStarted { .. }) { self.events.clear(); self.current_context = None; } if let VoiceEvent::Context { application, .. } = &event { self.current_context = Some(application.clone()); } self.events.push_back(event); while self.events.len() > EVENT_RETENTION { self.events.pop_front(); } } fn reset(&mut self) { self.offset = 0; self.pending.clear(); self.discarding_record = false; self.events.clear(); self.current_context = None; self.head.clear(); #[cfg(unix)] { self.file_id = None; } } } pub fn now_ms() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or_default() .as_millis() as u64 } #[cfg(test)] mod tests { use super::*; use std::fs::OpenOptions; #[test] fn structural_event_equality_preserves_serialized_identity() { let fixtures = serde_json::json!([ {"kind": "session_started", "timestamp_ms": 42}, {"kind": "state", "timestamp_ms": 42, "state": "listening", "device": "Test"}, {"kind": "transcript", "timestamp_ms": 42, "phase": "completed", "latency_ms": 73, "text": "olá"}, {"kind": "transcript", "timestamp_ms": 42, "phase": "completed", "latency_ms": 73, "text": "other"}, {"kind": "command", "timestamp_ms": 42, "heard": "alpha", "command": null, "outcome": "ignored"}, {"kind": "command", "timestamp_ms": 42, "heard": "alpha", "command": "example", "outcome": {"failed": "é"}, "context": "Test"}, {"kind": "dictation", "timestamp_ms": 42, "phase": "pasted", "text": "olá"}, {"kind": "dictation", "timestamp_ms": 42, "phase": "pasted", "text": "olá", "processing": {"profile": "example", "latency_ms": 321}}, {"kind": "dictation", "timestamp_ms": 42, "phase": "pasted", "text": "olá", "processing": {"profile": "example", "latency_ms": 321, "fallback": "timeout"}}, {"kind": "dictation", "timestamp_ms": 42, "phase": {"failed": "timeout"}}, {"kind": "context", "timestamp_ms": 42, "application": null}, {"kind": "context", "timestamp_ms": 42, "application": "Test"}, {"kind": "api_server_started", "timestamp_ms": 42, "port": 12345}, {"kind": "api_server_stopped", "timestamp_ms": 42}, {"kind": "api_auth_failed", "timestamp_ms": 42, "method": "POST", "path": "/transcribe"} ]); let events: Vec = serde_json::from_value(fixtures).unwrap(); for left in &events { let serialized = serde_json::to_string(left).unwrap(); let decoded: VoiceEvent = serde_json::from_str(&serialized).unwrap(); assert_eq!(left, &decoded); for right in &events { assert_eq!( left == right, serialized == serde_json::to_string(right).unwrap(), "{left:?} vs {right:?}", ); } } } #[test] fn events_round_trip_through_ndjson() { let event = VoiceEvent::Transcript { timestamp_ms: 42, phase: TranscriptPhase::Completed, latency_ms: 73, text: "Open Zed".into(), }; let json = serde_json::to_string(&event).unwrap(); let decoded: VoiceEvent = serde_json::from_str(&json).unwrap(); assert!(matches!( decoded, VoiceEvent::Transcript { timestamp_ms: 42, phase: TranscriptPhase::Completed, latency_ms: 73, ref text, } if text == "Open Zed" )); } #[test] fn dictation_processing_observation_round_trips() { let event = VoiceEvent::Dictation { timestamp_ms: 42, phase: DictationPhase::Pasted, text: "Processed text".into(), processing: Some(DictationProcessing { profile: "slack".into(), latency_ms: 321, model: Some("anthropic/claude-haiku-4-5".into()), fallback: Some("deadline exceeded".into()), }), reason: None, }; let decoded: VoiceEvent = serde_json::from_str(&serde_json::to_string(&event).unwrap()).unwrap(); assert!(matches!( decoded, VoiceEvent::Dictation { processing: Some(DictationProcessing { profile, latency_ms: 321, model: Some(model), fallback: Some(fallback), }), .. } if profile == "slack" && model == "anthropic/claude-haiku-4-5" && fallback == "deadline exceeded" )); } /// Events and History entries written before the model was recorded still /// decode, and name no model. #[test] fn dictation_processing_without_a_model_still_decodes() { let decoded: DictationProcessing = serde_json::from_str(r#"{"profile":"slack","latency_ms":321}"#).unwrap(); assert_eq!(decoded.model, None); assert_eq!(decoded.fallback, None); assert_eq!( serde_json::to_string(&decoded).unwrap(), r#"{"profile":"slack","latency_ms":321}"# ); } #[test] fn discard_reason_is_additive() { let old: VoiceEvent = serde_json::from_str( r#"{"kind":"dictation","timestamp_ms":1,"phase":"discarded","text":""}"#, ) .unwrap(); assert!(matches!(old, VoiceEvent::Dictation { reason: None, .. })); let event = VoiceEvent::Dictation { timestamp_ms: 1, phase: DictationPhase::Discarded, text: String::new(), processing: None, reason: Some("hid-key".into()), }; let json = serde_json::to_string(&event).unwrap(); assert!(json.contains(r#""reason":"hid-key""#), "{json}"); assert_eq!(serde_json::from_str::(&json).unwrap(), event); let without = serde_json::to_string(&VoiceEvent::Dictation { timestamp_ms: 1, phase: DictationPhase::Discarded, text: String::new(), processing: None, reason: None, }) .unwrap(); assert!(!without.contains("reason"), "{without}"); } #[test] fn reopening_log_preserves_existing_events() { let path = std::env::temp_dir().join(format!( "hex-events-{}-{}.ndjson", std::process::id(), now_ms() )); let event = VoiceEvent::State { timestamp_ms: 1, state: VoiceState::Listening, device: "test".into(), }; EventLog::create(&path).unwrap().emit(&event).unwrap(); EventLog::create(&path).unwrap().emit(&event).unwrap(); assert_eq!(fs::read_to_string(&path).unwrap().lines().count(), 2); fs::remove_file(path).unwrap(); } #[test] fn reader_tails_complete_records_and_resets_at_session_boundaries() { let path = std::env::temp_dir().join(format!( "hex-event-reader-{}-{}.ndjson", std::process::id(), now_ms() )); let mut reader = EventReader::open(&path); fs::write( &path, concat!( "{\"kind\":\"context\",\"timestamp_ms\":1,\"application\":\"Zed\",\"browser_url\":null}\n", "{\"kind\":\"state\",\"timestamp_ms\":2,\"state\":\"listening\",\"device\":\"Test\"}" ), ) .unwrap(); reader.refresh().unwrap(); assert_eq!(reader.events().len(), 1); assert_eq!(reader.current_context().cloned(), Some(Some("Zed".into()))); let mut file = OpenOptions::new().append(true).open(&path).unwrap(); writeln!(file).unwrap(); writeln!(file, "{{\"kind\":\"session_started\",\"timestamp_ms\":3}}",).unwrap(); writeln!( file, "{{\"kind\":\"state\",\"timestamp_ms\":4,\"state\":\"dictating\",\"device\":\"Test\"}}" ) .unwrap(); reader.refresh().unwrap(); assert_eq!(reader.events().len(), 2); assert!(matches!( reader.events().front(), Some(VoiceEvent::SessionStarted { timestamp_ms: 3 }) )); assert_eq!(reader.current_context(), None); fs::remove_file(path).unwrap(); } #[cfg(unix)] #[test] fn the_log_is_private() { use std::os::unix::fs::PermissionsExt; let directory = std::env::temp_dir().join(format!( "hex-private-log-{}-{}", std::process::id(), now_ms() )); fs::create_dir(&directory).unwrap(); let mode = |path: &Path| fs::metadata(path).unwrap().permissions().mode() & 0o777; let new = directory.join("new.ndjson"); drop(EventLog::create(&new).unwrap()); assert_eq!(mode(&new), 0o600); let older = directory.join("live.ndjson"); fs::write(&older, "").unwrap(); fs::set_permissions(&older, fs::Permissions::from_mode(0o644)).unwrap(); drop(EventLog::create(&older).unwrap()); assert_eq!(mode(&older), 0o600); fs::remove_dir_all(directory).unwrap(); } #[test] fn the_log_never_keeps_what_was_said() { let path = std::env::temp_dir().join(format!( "hex-no-words-{}-{}.ndjson", std::process::id(), now_ms() )); let log = EventLog::create(&path).unwrap(); log.emit(&VoiceEvent::Transcript { timestamp_ms: 1, phase: TranscriptPhase::Completed, latency_ms: 5, text: "my bank pin is 4321".into(), }) .unwrap(); log.dictation(DictationPhase::Pasted, "my bank pin is 4321") .unwrap(); log.flush().unwrap(); let written = fs::read_to_string(&path).unwrap(); assert_eq!(written.lines().count(), 2); // A digit sequence can occur inside a millisecond timestamp, so check // the words instead. assert!(!written.contains("bank pin"), "{written}"); fs::remove_file(path).unwrap(); } #[test] fn a_reader_starts_over_when_the_log_is_trimmed_under_it() { let path = std::env::temp_dir().join(format!( "hex-trimmed-reader-{}-{}.ndjson", std::process::id(), now_ms() )); let line = |timestamp_ms: u64| { format!( "{{\"kind\":\"api_server_stopped\",\"timestamp_ms\":{}}}\n", 100 + timestamp_ms ) }; fs::write(&path, (1..=4).map(line).collect::()).unwrap(); let mut reader = EventReader::open(&path); reader.refresh().unwrap(); assert_eq!(reader.offset, fs::metadata(&path).unwrap().len()); // Newer lines arrive, then a trim keeps the newest ones from the front, // so the file stays longer than the reader's offset. let trimmed: String = (5..=12).map(line).collect(); fs::write(&path, &trimmed).unwrap(); assert!(trimmed.len() as u64 > reader.offset); reader.refresh().unwrap(); // Read again from the start: exactly the trimmed file's events, none // left from before the trim and none taken from its middle. assert_eq!(reader.offset, trimmed.len() as u64); assert_eq!(reader.events().len(), 8); assert!(matches!( reader.events().front(), Some(VoiceEvent::ApiServerStopped { timestamp_ms: 105 }) )); fs::remove_file(path).unwrap(); } #[test] fn a_bounded_flush_writes_every_queued_event() { let path = std::env::temp_dir().join(format!( "hex-bounded-flush-{}-{}.ndjson", std::process::id(), now_ms() )); let log = EventLog::create(&path).unwrap(); for timestamp_ms in 1..=500 { log.dictation(DictationPhase::Pasted, format!("{timestamp_ms}")) .unwrap(); } log.flush_within(Duration::from_secs(5)).unwrap(); assert_eq!(fs::read_to_string(&path).unwrap().lines().count(), 500); fs::remove_file(path).unwrap(); } #[test] fn reader_streams_large_logs_and_keeps_context_outside_the_retained_rows() { let path = std::env::temp_dir().join(format!( "hex-large-event-reader-{}-{}.ndjson", std::process::id(), now_ms() )); let log = EventLog::create(&path).unwrap(); log.emit(&VoiceEvent::Context { timestamp_ms: 0, application: Some("Fixture".into()), }) .unwrap(); for timestamp_ms in 1..=2048 { log.emit(&VoiceEvent::ApiAuthFailed { timestamp_ms, method: "POST".into(), path: "é".repeat(100), }) .unwrap(); } log.flush().unwrap(); let mut reader = EventReader::open(&path); reader.refresh().unwrap(); assert_eq!(reader.offset, fs::metadata(&path).unwrap().len()); assert_eq!(reader.events().len(), EVENT_RETENTION); assert_eq!(reader.current_context(), Some(&Some("Fixture".into()))); assert!(matches!( reader.events().back(), Some(VoiceEvent::ApiAuthFailed { timestamp_ms: 2048, .. }) )); // Scratch space follows one record, never the size of the file. assert!(reader.pending.capacity() <= EVENT_READ_BUFFER_BYTES); drop(log); fs::remove_file(path).unwrap(); } #[test] fn reader_skips_oversized_records_through_their_newline_and_recovers() { let path = std::env::temp_dir().join(format!( "hex-oversized-event-reader-{}-{}.ndjson", std::process::id(), now_ms() )); fs::write(&path, vec![b'x'; MAX_EVENT_RECORD_BYTES + 1]).unwrap(); let mut reader = EventReader::open(&path); reader.refresh().unwrap(); assert!(reader.discarding_record); assert!(reader.pending.is_empty()); assert!(reader.pending.capacity() <= MAX_EVENT_RECORD_BYTES); let mut file = OpenOptions::new().append(true).open(&path).unwrap(); // A valid-looking suffix of the oversized line must not become an event. writeln!(file, "{{\"kind\":\"session_started\",\"timestamp_ms\":1}}").unwrap(); write!( file, "{{\"kind\":\"context\",\"timestamp_ms\":2,\"application\":\"caf" ) .unwrap(); file.write_all(&[0xc3]).unwrap(); reader.refresh().unwrap(); assert!(reader.events().is_empty()); assert!(!reader.discarding_record); file.write_all(b"\xa9\",\"browser_url\":null}\r\n").unwrap(); reader.refresh().unwrap(); assert_eq!(reader.current_context(), Some(&Some("café".into()))); assert_eq!(reader.events().len(), 1); fs::remove_file(path).unwrap(); } #[test] #[cfg_attr(windows, ignore = "replacement detection uses Unix file identity")] fn reader_resets_partial_record_state_on_truncation_and_replacement() { let path = std::env::temp_dir().join(format!( "hex-replaced-event-reader-{}-{}.ndjson", std::process::id(), now_ms() )); let mut reader = EventReader::open(&path); fs::write(&path, vec![b'x'; MAX_EVENT_RECORD_BYTES + 1]).unwrap(); reader.refresh().unwrap(); fs::write( &path, b"{\"kind\":\"session_started\",\"timestamp_ms\":3}\n", ) .unwrap(); reader.refresh().unwrap(); assert!(matches!( reader.events().front(), Some(VoiceEvent::SessionStarted { timestamp_ms: 3 }) )); let replacement = path.with_extension("replacement"); fs::write( &replacement, b"{\"kind\":\"session_started\",\"timestamp_ms\":4}\n", ) .unwrap(); fs::rename(replacement, &path).unwrap(); reader.refresh().unwrap(); assert!(matches!( reader.events().front(), Some(VoiceEvent::SessionStarted { timestamp_ms: 4 }) )); fs::remove_file(path).unwrap(); } }