diff --git a/Cargo.lock b/Cargo.lock index 19cfba4e5..e58ad3b40 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -14212,6 +14212,7 @@ dependencies = [ "anyhow", "cpal 0.17.3", "hound", + "ort", "parakeet-rs", "reqwest", "rubato", diff --git a/crates/doc/src/transcript_delta.rs b/crates/doc/src/transcript_delta.rs index a0d94abb1..adb781548 100644 --- a/crates/doc/src/transcript_delta.rs +++ b/crates/doc/src/transcript_delta.rs @@ -209,12 +209,38 @@ pub enum TranscriptFrame { append: Vec, #[serde(default)] remove: Vec, + /// Parts of an entry replaced or added, the entry otherwise as it + /// was: a tool call arriving or finishing in a long reply sends that + /// call alone, not the reply. Only to a consumer that asked for them + /// (`DiffOptions::part_patches`); never sent empty, so an older + /// reader never sees the field. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + parts: Vec, /// Expected transcript length after applying this frame — the desync /// tripwire: a consumer that lands elsewhere resubscribes for a reset. count: usize, }, } +/// One part of entry `entry` set at `at` (from 0): a part there replaced (the +/// same part, changed), or one added at its end (`at` its part count). `len` +/// is the entry's part count after the frame's patches (desync tripwire). +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PartPatch { + pub entry: String, + pub at: usize, + pub part: MessagePart, + pub len: usize, +} + +/// What a consumer of `WatchDocMessages` takes beyond the original frames. +#[derive(Debug, Clone, Copy, Default)] +pub struct DiffOptions { + /// Part patches (`TranscriptFrame::Delta::parts`) for an entry whose + /// header and part order are unchanged, rather than the entry whole. + pub part_patches: bool, +} + /// An inserted or replaced entry, positioned after `after` (`None` = head). /// Anchors are prior upserts of the same frame or unchanged entries, so /// applying upserts in frame order always finds them settled. @@ -247,8 +273,8 @@ impl TranscriptFrame { pub fn is_empty_delta(&self) -> bool { matches!( self, - Self::Delta { upsert, append, remove, .. } - if upsert.is_empty() && append.is_empty() && remove.is_empty() + Self::Delta { upsert, append, remove, parts, .. } + if upsert.is_empty() && append.is_empty() && remove.is_empty() && parts.is_empty() ) } } @@ -296,6 +322,38 @@ fn try_text_append(prev: &SessionMessageEntry, next: &SessionMessageEntry) -> Op append } +/// When `next` is `prev` with some of its parts changed in place (each the +/// same part, by id) and/or parts added at its end, its header the same: those +/// parts alone, as patches. `None` for any other change (a part removed or +/// moved, the status or duration changed): the entry is sent whole. +fn try_part_patches(prev: &SessionMessageEntry, next: &SessionMessageEntry) -> Option> { + if prev.id != next.id + || prev.role != next.role + || prev.created_at != next.created_at + || prev.device_id != next.device_id + || prev.status != next.status + || prev.continuation_of != next.continuation_of + || prev.duration_ms != next.duration_ms + || next.parts.len() < prev.parts.len() + { + return None; + } + let mut patches = Vec::new(); + for (at, n) in next.parts.iter().enumerate() { + match prev.parts.get(at) { + Some(p) if p == n => {} + Some(p) if p.id() != n.id() => return None, + _ => patches.push(PartPatch { + entry: next.id.clone(), + at, + part: n.clone(), + len: next.parts.len(), + }), + } + } + Some(patches) +} + /// Diff two transcript states into a frame. An entry is upserted when it is /// new, its content changed, or its predecessor changed (a Loro list merge can /// interleave a remote entry mid-list). Falls back to `Reset` when the delta @@ -303,6 +361,16 @@ fn try_text_append(prev: &SessionMessageEntry, next: &SessionMessageEntry) -> Op pub fn diff_transcript( prev: &[SessionMessageEntry], next: &[SessionMessageEntry], +) -> TranscriptFrame { + diff_transcript_with(prev, next, DiffOptions::default()) +} + +/// `diff_transcript`, with what the consumer takes beyond the original +/// frames (`options`). +pub fn diff_transcript_with( + prev: &[SessionMessageEntry], + next: &[SessionMessageEntry], + options: DiffOptions, ) -> TranscriptFrame { let prev_by_id: std::collections::HashMap<&str, (usize, &SessionMessageEntry)> = prev .iter() @@ -319,6 +387,7 @@ pub fn diff_transcript( let mut upsert = Vec::new(); let mut append = Vec::new(); + let mut parts = Vec::new(); for (i, entry) in next.iter().enumerate() { let after = i.checked_sub(1).map(|p| next[p].id.as_str()); match prev_by_id.get(entry.id.as_str()) { @@ -333,6 +402,13 @@ pub fn diff_transcript( append.push(text_append); continue; } + if options.part_patches + && prev_after == after + && let Some(patches) = try_part_patches(prev_entry, entry) + { + parts.extend(patches); + continue; + } upsert.push(TranscriptUpsert { after: after.map(str::to_string), entry: entry.clone(), @@ -353,6 +429,7 @@ pub fn diff_transcript( upsert, append, remove, + parts, count: next.len(), } } @@ -377,6 +454,7 @@ pub fn apply_transcript_frame( upsert, append, remove, + parts, count, } => { if !remove.is_empty() { @@ -428,6 +506,33 @@ pub fn apply_transcript_frame( ))); } } + for PartPatch { + entry, + at, + part, + len, + } in parts + { + let Some(target) = current.iter_mut().find(|e| e.id == entry) else { + return Err(TranscriptDesync(format!("missing patch entry {entry}"))); + }; + let have = target.parts.len(); + if at < have && target.parts[at].id() == part.id() { + target.parts[at] = part; + } else if at == have { + target.parts.push(part); + } else { + return Err(TranscriptDesync(format!( + "patch out of place on {entry}#{at}" + ))); + } + if target.parts.len() > len { + return Err(TranscriptDesync(format!( + "patch length mismatch on {entry}: have {}, expected {len}", + target.parts.len() + ))); + } + } if current.len() != count { return Err(TranscriptDesync(format!( "count mismatch: have {}, expected {count}", @@ -567,12 +672,103 @@ mod tests { len: 99, }], remove: vec![], + parts: vec![], count: 1, }; let mut current = vec![entry("a", "hello")]; assert!(apply_transcript_frame(&mut current, frame).is_err()); } + fn tool(id: &str, output: Option<&str>) -> MessagePart { + MessagePart::Tool { + id: id.into(), + call: serde_json::from_value(serde_json::json!({ "kind": "exec", "command": "ls" })).unwrap(), + is_error: false, + resolved: output.is_some(), + output: output.map(Into::into), + diff: None, + output_ref: None, + output_bytes: None, + diff_ref: None, + diff_stats: None, + subagent_ref: None, + subagent_status: None, + subagent_tail: None, + } + } + + fn working(calls: &[MessagePart]) -> SessionMessageEntry { + let mut e = entry("b", ""); + e.parts = calls.to_vec(); + e.status = Some(crate::parts::MessageStatus::Streaming); + e + } + + /// A call arriving and another finishing in a long reply: asked for, + /// those two parts alone travel; not asked for, the entry whole, as ever. + #[test] + fn a_reply_s_changed_parts_travel_alone_when_asked_for() { + let a = entry("a", "prompt"); + let calls: Vec<_> = (0..50).map(|i| tool(&format!("t{i}"), Some("ok"))).collect(); + let b0 = working(&[calls.clone(), vec![tool("t50", None)]].concat()); + let b1 = working(&[calls, vec![tool("t50", Some("done")), tool("t51", None)]].concat()); + let options = DiffOptions { part_patches: true }; + let frame = diff_transcript_with(&[a.clone(), b0.clone()], &[a.clone(), b1.clone()], options); + match &frame { + TranscriptFrame::Delta { upsert, parts, .. } => { + assert!(upsert.is_empty(), "the entry isn't sent whole"); + let at: Vec<_> = parts.iter().map(|p| (p.at, p.part.id().to_owned())).collect(); + assert_eq!(at, vec![(50, "t50".into()), (51, "t51".into())]); + } + other => panic!("expected delta, got {other:?}"), + } + let json = serde_json::to_value(&frame).unwrap(); + let mut current = vec![a.clone(), b0.clone()]; + apply_transcript_frame(&mut current, serde_json::from_value(json).unwrap()).unwrap(); + assert_eq!(current, vec![a.clone(), b1.clone()]); + // Not asked for: whole, and no `parts` field on the wire. + let frame = diff_transcript(&[a.clone(), b0.clone()], &[a.clone(), b1.clone()]); + let json = serde_json::to_value(&frame).unwrap(); + assert!(json.get("parts").is_none(), "{json}"); + assert_eq!(json["upsert"].as_array().map(Vec::len), Some(1)); + apply(&[a.clone(), b0], &[a, b1]); + } + + /// A change parts can't say (the reply settling, a part going) is the + /// entry whole even when they're asked for. + #[test] + fn other_changes_send_the_entry_whole() { + let b0 = working(&[tool("t0", None), tool("t1", None)]); + let mut settled = b0.clone(); + settled.status = Some(crate::parts::MessageStatus::Complete); + let fewer = working(&[tool("t0", None)]); + let moved = working(&[tool("t1", None), tool("t0", None)]); + let options = DiffOptions { part_patches: true }; + for next in [settled, fewer, moved] { + let frame = diff_transcript_with(std::slice::from_ref(&b0), std::slice::from_ref(&next), options); + match &frame { + TranscriptFrame::Delta { upsert, parts, .. } => { + assert_eq!(upsert.len(), 1); + assert!(parts.is_empty()); + } + other => panic!("expected delta, got {other:?}"), + } + } + } + + #[test] + fn a_patch_out_of_place_is_desync() { + let frame = TranscriptFrame::Delta { + upsert: vec![], + append: vec![], + remove: vec![], + parts: vec![PartPatch { entry: "b".into(), at: 5, part: tool("t5", None), len: 6 }], + count: 1, + }; + let mut current = vec![working(&[tool("t0", None)])]; + assert!(apply_transcript_frame(&mut current, frame).is_err()); + } + #[test] fn large_change_falls_back_to_reset() { let prev: Vec<_> = (0..10).map(|i| entry(&format!("p{i}"), "x")).collect(); @@ -592,6 +788,7 @@ mod tests { }], append: vec![], remove: vec![], + parts: vec![], count: 2, }; let mut current = Vec::new(); diff --git a/crates/engine/src/doc_host.rs b/crates/engine/src/doc_host.rs index 3df2c4c58..2e90ef3fb 100644 --- a/crates/engine/src/doc_host.rs +++ b/crates/engine/src/doc_host.rs @@ -393,6 +393,20 @@ impl Drop for TransferProgressGuard<'_> { /// is never delayed. const DEGRADE_GRACE: std::time::Duration = std::time::Duration::from_secs(4); +/// How often the connectivity monitor looks once the posture has held +/// healthy for [`CONNECTIVITY_SETTLE_TICKS`] seconds. A fresh degradation is +/// then seen up to this late, on top of its [`DEGRADE_GRACE`]; recovery from +/// one is still seen within a second, as the monitor looks every second +/// while anything is degraded. +const CONNECTIVITY_STEADY: std::time::Duration = std::time::Duration::from_secs(5); +const CONNECTIVITY_SETTLE_TICKS: u32 = 3; + +/// Nothing degraded: local, or connected with every open chat connected. +fn connectivity_healthy(posture: &zeron_proto::Connectivity) -> bool { + use zeron_proto::ConnectivityState as S; + matches!(posture.state, S::Connected | S::Disabled) && posture.chats.iter().all(|chat| chat.connected) +} + /// One tracked degradation source in [`DegradeGrace`]. enum GraceKey<'a> { OsPath, @@ -439,6 +453,11 @@ impl DegradeGrace { now.duration_since(since) >= DEGRADE_GRACE } + /// A degradation is being timed: the report may change with time alone. + fn timing(&self) -> bool { + self.os_path.is_some() || self.registry.is_some() || !self.chats.is_empty() + } + /// Drop timers for chats that no longer have open docs. fn retain_chats(&mut self, keep: impl Fn(&str) -> bool) { self.chats.retain(|id, _| keep(id)); @@ -517,6 +536,17 @@ pub(crate) fn queued_message_prompt(text: &str, attachments: &[String]) -> Strin format!("{body}{trailer}") } +/// What a queue row says: its words, or for files with no words, what a run +/// of them says. A row needs text on every device (one without is refused and +/// dropped as read), so files alone must not come to an empty one. +fn queued_row_text(text: &str, has_files: bool) -> &str { + if has_files && text.trim().is_empty() { + ATTACHMENT_ONLY_PROMPT + } else { + text + } +} + fn queue_text_hash(text: &str) -> String { format!("{:x}", Sha256::digest(text.as_bytes())) } @@ -1544,6 +1574,10 @@ impl DocHost { /// Materialize one authoritative local document without acquiring a network /// connection. Durable publication is installed before exposing any writer. pub fn open_local(&self, chat_id: &str) -> Result, EngineError> { + // A chat with no id has no room to sync with: it dialed one forever. + if chat_id.is_empty() { + return Err(EngineError::Other("a chat needs an id".into())); + } // The registry names the sync room generation (docs/chat2-sync.md // M2): absent row / absent field = legacy s2. Read it BEFORE the // cached-handle check — a cached s2-mode handle for a chat another @@ -3393,10 +3427,13 @@ impl DocHost { } /// The connectivity stream: current posture first, then every change. - /// Lazily starts a monitor — a 1s recompute over in-memory stats - /// (atomics + small locks), published only when the value changes. The - /// retry countdown renders client-side from `retry_at_ms`, so quiet - /// periods emit nothing at all. + /// Lazily starts a monitor — a recompute over in-memory stats (atomics + + /// small locks), published only when the value changes: every second + /// while it's changing, degraded or timing a degradation's grace, and + /// every [`CONNECTIVITY_STEADY`] once it has held healthy (or local) for + /// a few seconds, so a settled engine isn't woken each second to find + /// nothing changed. The retry countdown renders client-side from + /// `retry_at_ms`, so quiet periods emit nothing at all. pub fn watch_connectivity(&self) -> watch::Receiver { let tx = self .inner @@ -3408,12 +3445,17 @@ impl DocHost { { let host = self.clone(); self.spawn_worker(async move { - let mut tick = tokio::time::interval(std::time::Duration::from_secs(1)); - tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + let mut held = 0u32; loop { - tick.tick().await; + let wait = if held >= CONNECTIVITY_SETTLE_TICKS { + CONNECTIVITY_STEADY + } else { + std::time::Duration::from_secs(1) + }; + tokio::time::sleep(wait).await; let next = host.compute_connectivity(); - if let Some(tx) = host.inner.connectivity.get() { + let healthy = connectivity_healthy(&next); + let changed = host.inner.connectivity.get().is_some_and(|tx| { tx.send_if_modified(|cur| { if *cur == next { false @@ -3421,8 +3463,10 @@ impl DocHost { *cur = next; true } - }); - } + }) + }); + let timing = lock(&host.inner.connectivity_grace).timing(); + held = if changed || timing || !healthy { 0 } else { held.saturating_add(1) }; } }); } @@ -3721,7 +3765,7 @@ impl DocHost { let id = new_id(); handle.doc.push_queued(&QueuedMessage { id: id.clone(), - text: text.to_string(), + text: queued_row_text(text, !attachments.is_empty()).to_string(), attachments, hold_for_turn_end, issued_by: self.inner.config.device_id.clone(), @@ -4078,7 +4122,10 @@ impl DocHost { } let replacement = match action { - FinishQueueEditAction::Commit => Some(text.unwrap_or_default()), + FinishQueueEditAction::Commit => Some(queued_row_text( + text.unwrap_or_default(), + attachments.map_or(!item.attachments.is_empty(), |kept| !kept.is_empty()), + )), FinishQueueEditAction::Cancel | FinishQueueEditAction::ReleaseUnchanged => None, FinishQueueEditAction::Discard => Some(""), }; @@ -5420,9 +5467,17 @@ impl DocHost { self.arm_attachment_wait(handle); return; // preserve order; UploadCommit / the wait timer re-kick } + // In-flight claim, as for an execute: between the mark and + // the outcome, a racing drain's dead-command sweep would + // otherwise take this for a crash and write its own reason. + if !lock(&self.inner.executing).insert(entry.id.clone()) { + skipped.insert(entry.id.clone()); + continue; + } if let Err(err) = self.inner.store.mark_processed(&entry.id) { tracing::error!(chat = %handle.chat_id, error = %err, "processed-ledger write failed; halting drain"); + lock(&self.inner.executing).remove(&entry.id); return; } tracing::warn!(chat = %handle.chat_id, command = %entry.id, @@ -5433,6 +5488,7 @@ impl DocHost { SessionCommandStatus::Rejected, Some("attachments never arrived"), ); + lock(&self.inner.executing).remove(&entry.id); continue; } } @@ -5565,11 +5621,17 @@ impl DocHost { return; }; for path in attachments.iter_mut() { - if let Some(abs) = uploads.resolve_pending(path) { + if let Some(abs) = uploads.localize(path) { *prompt = prompt.replace(path.as_str(), &abs); *path = abs; } } + // Paths only the prompt names (older clients sent no list). + for path in crate::uploads::attachment_lines_in(&prompt.clone()) { + if let Some(abs) = uploads.localize(&path) { + *prompt = prompt.replace(path.as_str(), &abs); + } + } } /// A queue row's `pending://` refs whose bytes are not on this device @@ -5601,8 +5663,8 @@ impl DocHost { return prompt.to_string(); }; let mut out = prompt.to_string(); - for r in crate::uploads::pending_refs_in(prompt) { - if let Some(abs) = uploads.resolve_pending(&r) { + for r in crate::uploads::attachment_lines_in(prompt) { + if let Some(abs) = uploads.localize(&r) { out = out.replace(&r, &abs); } } @@ -5775,7 +5837,17 @@ impl DocHost { tracing::warn!(chat = %chat_id, error = %err, "run-config backfill failed"); } } - if sessions.defers_to_turn_end(chat_id, Some((harness, &request))) { + // Sent before the turn now running had started: the sender never + // saw that turn, so it can't be a steer into it. Two messages sent + // to a sleeping machine (or an offline host) start one turn + // each; steering the second into the first cut the first off with + // an empty reply. + // Only when an earlier send started that turn: nothing else changes. + let sent_before_turn = sessions + .turn_started_ms(chat_id) + .is_some_and(|started| entry.issued_at < started) + && self.live_turn_sent_earlier(handle, entry, message_id); + if sent_before_turn || sessions.defers_to_turn_end(chat_id, Some((harness, &request))) { self.hold_until_turn_end( handle, message_id, @@ -5944,6 +6016,36 @@ impl DocHost { /// Park a prompt for a turn-boundary agent in the visible queue instead /// of its mailbox, keeping the message id so the transcript entry written /// at delivery is the same message. Steers lead ordinary rows. + /// The running turn is the latest message in the transcript, sent as a run no + /// later than `entry` and not `entry`'s own: a second send that went out while + /// the host was away, now arriving behind the first. + fn live_turn_sent_earlier( + &self, + handle: &Arc, + entry: &SessionCommandEntry, + message_id: &str, + ) -> bool { + let Some(live) = handle.doc.read_entries().ok().and_then(|entries| { + entries + .iter() + .rev() + .find(|e| e.role == MessageRole::User) + .map(|e| e.id.clone()) + }) else { + return false; + }; + if live == message_id { + return false; + } + handle.doc.read_commands().is_ok_and(|commands| { + commands.iter().any(|c| { + c.id != entry.id + && c.issued_at <= entry.issued_at + && matches!(&c.payload, SessionCommandPayload::Run { message_id, .. } if *message_id == live) + }) + }) + } + fn hold_until_turn_end( &self, handle: &Arc, @@ -6099,9 +6201,15 @@ impl DocHost { async fn capture_source_context(&self, cwd: &str) -> Option { let repos = self.inner.repos.get()?; let path = Path::new(cwd); - let identity = repos.checkout_identity(path).await.ok()?; - let branch = repos.current_branch(path).await.ok()?; - let head_sha = repos.head_sha(path).await.ok().flatten(); + // Three `git` processes: side by side, not one after another. + let (identity, branch, head_sha) = tokio::join!( + repos.checkout_identity(path), + repos.current_branch(path), + repos.head_sha(path), + ); + let identity = identity.ok()?; + let branch = branch.ok()?; + let head_sha = head_sha.ok().flatten(); Some(ConversationSourceContext { checkout_id: identity.id, repo_root: identity.root.to_string_lossy().into_owned(), @@ -6113,10 +6221,13 @@ impl DocHost { } /// Every fresh harness dispatch crosses this boundary, including - /// steer/input fallbacks and crash recovery. Capture immediately before - /// dispatch so the conversation records the checkout the harness will - /// actually observe, rather than whichever checkout state was current on - /// an earlier turn. + /// steer/input fallbacks and crash recovery. The conversation records + /// the checkout the harness will actually observe, rather than whichever + /// checkout state was current on an earlier turn: read as the dispatch + /// starts, beside it rather than before it. Its `git` processes took + /// ~25 ms (M5 Max; more on slower Macs) in front of every agent start, + /// and the agent reads nothing of its checkout for far longer than that + /// (its own startup is ~250 ms before its first request). pub(crate) async fn dispatch_with_source_context( &self, sessions: &SessionsEngine, @@ -6143,11 +6254,21 @@ impl DocHost { request.env.entry(name).or_insert(value); } } - if let Some(workspace) = self.workspace() - && let Some(context) = self.capture_source_context(&request.cwd).await - && let Err(err) = workspace.set_chat_source_context(chat_id, &context) - { - tracing::warn!(chat = %chat_id, error = %err, "conversation source stamp failed"); + // Stamped on a task of its own: the drain resolves the command as + // soon as the run is dispatched, never behind the `git` processes. + if self.workspace().is_some() { + let host = self.clone(); + let chat_id = chat_id.to_owned(); + let cwd = request.cwd.clone(); + self.spawn_worker(async move { + if let Some(workspace) = host.workspace() + && let Some(context) = host.capture_source_context(&cwd).await + && let Err(err) = workspace.set_chat_source_context(&chat_id, &context) + { + tracing::warn!(chat = %chat_id, error = %err, "conversation source stamp failed"); + } + tracing::debug!(target: "first_word", chat = %chat_id, "source context: stamped"); + }); } sessions .dispatch(chat_id, harness, request, message_id) @@ -7229,6 +7350,26 @@ mod publication_eviction_tests { host.shutdown_workers().await; } + #[tokio::test] + async fn a_chat_without_an_id_is_never_opened() { + let dir = tempfile::tempdir().unwrap(); + let store = Arc::new(DocsStore::open(dir.path()).unwrap()); + let host = DocHost::new( + store.clone(), + DocHostConfig { + device_id: "writer".into(), + default_harness: HarnessId::Mock, + edge: Some(EdgeConfig::with_static_token("http://127.0.0.1:1", "test")), + }, + ); + assert!(host.open("").is_err()); + assert!(host.open_local("").is_err()); + let steer = SessionCommandPayload::Steer { prompt: "hi".into(), message_id: None }; + assert!(host.queue_command_with_transfers("", steer, Vec::new()).is_err()); + assert!(lock(&host.inner.handles).is_empty()); + host.shutdown_workers().await; + } + #[tokio::test] async fn salvage_inspection_does_not_open_healthy_or_unrecoverable_chats() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/engine/src/home_index.rs b/crates/engine/src/home_index.rs index 5e89a97da..e97d8b182 100644 --- a/crates/engine/src/home_index.rs +++ b/crates/engine/src/home_index.rs @@ -8,16 +8,274 @@ //! folders, hidden folders and dependency folders altogether. It holds no //! file contents, so home has no content search. -use std::path::Path; -use std::sync::Mutex; +//! +//! The walk is bounded and never polls. Its workers share a queue of folders +//! and sleep on a condition variable while it's empty, so a worker held up +//! in one folder costs the others nothing (the `ignore` crate's parallel +//! walker had its idle workers wake every millisecond until all were done: +//! one `open()` that never returned, a macOS privacy prompt nobody answers +//! for Desktop or Documents, kept ~4,000 wakeups a second going for good). +//! It ends at [`WALK_DEADLINE`] with what it has, or when cancelled (the new +//! project picker closed); a folder still being read then is skipped by +//! later walks until that read returns, so a stuck folder holds one thread, +//! not one per walk. + +use std::collections::{HashSet, VecDeque}; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; -use std::time::Instant; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError, Weak}; +use std::time::{Duration, Instant}; use crate::workspace_search::{NameKinds, NameMatch, normalize_name_query}; /// Paths kept at most; a larger home answers from the first ones walked. pub const MAX_ENTRIES: usize = 250_000; +/// A walk answers with what it has found by then. +pub const WALK_DEADLINE: Duration = Duration::from_secs(20); + +/// Folders above this depth (home's own folders, and theirs) that aren't +/// repositories are listed one by one, each child a unit of its own, so the +/// workers share a home whose projects sit under one folder. A repository, +/// or anything deeper, is walked whole by one worker with its ignore files. +const EXPAND_DEPTH: usize = 3; + +/// Folders a walk that ended left a worker reading (see the module docs). +static STALLED: Mutex>> = Mutex::new(None); + +fn stalled() -> MutexGuard<'static, Option>> { + STALLED.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// Stops a walk: it returns at once with what it has. +#[derive(Default)] +pub struct WalkCancel { + cancelled: AtomicBool, + walk: Mutex>, +} + +impl WalkCancel { + pub fn cancel(&self) { + self.cancelled.store(true, Ordering::SeqCst); + if let Some(walk) = self + .walk + .lock() + .unwrap_or_else(PoisonError::into_inner) + .upgrade() + { + walk.quit(); + } + } + + pub fn is_cancelled(&self) -> bool { + self.cancelled.load(Ordering::SeqCst) + } +} + +struct Unit { + dir: PathBuf, + /// Below home: 1 for home's own folders. + depth: usize, +} + +#[derive(Default)] +struct Queue { + units: VecDeque, + /// Workers inside a unit. + active: usize, + /// Folders a worker is inside now. + reading: HashSet, + quit: bool, +} + +/// One walk's shared state. Workers hold it until they leave, which a +/// worker stuck in `open()` does only once that returns. +struct Walk { + home: PathBuf, + queue: Mutex, + changed: Condvar, + /// `queue.quit`, read without the lock between entries. + stop: AtomicBool, + found: Mutex>, + /// Folders skipped as stalled by an earlier walk. + skip: HashSet, + /// The protected folders are read too (`PROTECTED_ROOTS`). + protected: bool, + /// Times an idle worker woke (tests: idle workers must not poll). + #[cfg(test)] + wakes: std::sync::atomic::AtomicUsize, +} + +impl Walk { + fn queue(&self) -> MutexGuard<'_, Queue> { + self.queue.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn quit(&self) { + self.stop.store(true, Ordering::SeqCst); + self.queue().quit = true; + self.changed.notify_all(); + } + + fn quitting(&self) -> bool { + self.stop.load(Ordering::Relaxed) + } + + fn push(&self, unit: Unit) { + if self.skip.contains(&unit.dir) { + tracing::info!(dir = %unit.dir.display(), "home walk: skipping a folder an earlier walk is still reading"); + return; + } + self.queue().units.push_back(unit); + self.changed.notify_one(); + } + + /// Keep `items`; `false` once the walk has enough. + fn keep(&self, items: &mut Vec) -> bool { + let mut found = self.found.lock().unwrap_or_else(PoisonError::into_inner); + found.append(items); + if found.len() >= MAX_ENTRIES { + drop(found); + self.quit(); + return false; + } + true + } + + /// A worker: units until the queue is empty with nobody working (the + /// walk is done) or the walk quits; asleep while it waits. + fn work(self: Arc) { + loop { + let unit = { + let mut queue = self.queue(); + loop { + if queue.quit { + return; + } + if let Some(unit) = queue.units.pop_front() { + queue.active += 1; + queue.reading.insert(unit.dir.clone()); + break unit; + } + if queue.active == 0 { + // Done: wake the others and the walk's owner. + self.changed.notify_all(); + return; + } + queue = self + .changed + .wait(queue) + .unwrap_or_else(PoisonError::into_inner); + #[cfg(test)] + self.wakes.fetch_add(1, Ordering::Relaxed); + } + }; + self.visit(&unit); + let quit = { + let mut queue = self.queue(); + queue.active -= 1; + queue.reading.remove(&unit.dir); + if queue.active == 0 && queue.units.is_empty() { + self.changed.notify_all(); + } + queue.quit + }; + // A walk that ended while this folder was read marked it stalled. + if let Some(stalled) = stalled().as_mut() + && stalled.remove(&unit.dir) + { + tracing::info!(dir = %unit.dir.display(), "home walk: a stalled folder read returned"); + } + if quit { + return; + } + } + } + + fn visit(&self, unit: &Unit) { + #[cfg(test)] + tests::held(&unit.dir); + let mut items = Vec::new(); + if unit.depth < EXPAND_DEPTH && !unit.dir.join(".git").exists() { + let Ok(listing) = std::fs::read_dir(&unit.dir) else { + return; + }; + for entry in listing { + if self.quitting() { + return; + } + let Ok(entry) = entry else { continue }; + let name = entry.file_name().to_string_lossy().into_owned(); + if name.starts_with('.') { + continue; + } + let is_dir = entry.file_type().is_ok_and(|kind| kind.is_dir()); + let depth = unit.depth + 1; + if is_dir && skipped(&name, depth, self.protected, || entry.metadata().ok()) { + continue; + } + let path = entry.path(); + if let Some(home_path) = self.home_path(&path, is_dir) { + items.push(home_path); + } + if is_dir { + self.push(Unit { dir: path, depth }); + } + } + self.keep(&mut items); + return; + } + let base = unit.depth; + let protected = self.protected; + let walk = ignore::WalkBuilder::new(&unit.dir) + .hidden(true) + .follow_links(false) + .git_ignore(true) + .git_global(true) + .git_exclude(true) + .ignore(true) + .parents(false) + .filter_entry(move |entry| { + entry.depth() == 0 + || !entry.file_type().is_some_and(|kind| kind.is_dir()) + || !skipped( + &entry.file_name().to_string_lossy().to_lowercase(), + base + entry.depth(), + protected, + || entry.metadata().ok(), + ) + }) + .build(); + for entry in walk { + if self.quitting() { + return; + } + let Ok(entry) = entry else { continue }; + if entry.depth() == 0 { + continue; + } + let is_dir = entry.file_type().is_some_and(|kind| kind.is_dir()); + if let Some(home_path) = self.home_path(entry.path(), is_dir) { + items.push(home_path); + } + if items.len() >= 512 && !self.keep(&mut items) { + return; + } + } + self.keep(&mut items); + } + + fn home_path(&self, path: &Path, is_dir: bool) -> Option { + let relative = path.strip_prefix(&self.home).ok()?; + let path = relative.to_string_lossy().replace('\\', "/"); + Some(HomePath { + lower: path.to_lowercase(), + path, + is_dir, + }) + } +} + /// Folders directly under home that a cloud client syncs (matched without /// case; OneDrive's business folders read "OneDrive - Contoso"). const CLOUD_ROOT_PREFIXES: &[&str] = &[ @@ -38,12 +296,26 @@ const CLOUD_ROOT_PREFIXES: &[&str] = &[ /// Provider clients (`CloudStorage`). const MACHINE_ROOTS: &[&str] = &["library", "appdata", "applications"]; +/// Folders directly under a Mac's home that hold media libraries (Photos', +/// Music's, TV's), never projects: never walked. Reading them asks the person +/// for access to their photos and music, for a folder search. +#[cfg(target_os = "macos")] +const MEDIA_ROOTS: &[&str] = &["pictures", "music", "movies"]; + +/// Folders directly under a Mac's home that its privacy protection guards: +/// read only for a walk that asks for them (`protected`), as someone searches +/// (`WorkspaceSearch`), so that opening New project asks nobody for access. +#[cfg(target_os = "macos")] +const PROTECTED_ROOTS: &[&str] = &["desktop", "documents", "downloads"]; + /// Dependency and cache folders, at any depth. const SKIPPED_DIRS: &[&str] = &["node_modules", "__pycache__", "venv", "site-packages"]; pub struct HomeIndex { entries: Vec, pub built: Instant, + /// The protected folders were read (`PROTECTED_ROOTS`; always, off macOS). + pub protected: bool, } struct HomePath { @@ -54,61 +326,93 @@ struct HomePath { } impl HomeIndex { - /// Walk `home` (canonical). `cancelled` stops the walk early. - pub fn build(home: &Path, cancelled: &AtomicBool) -> Self { + /// Walk `home` (canonical), for at most [`WALK_DEADLINE`]. `cancel` + /// stops the walk early. + pub fn build(home: &Path, cancel: &WalkCancel) -> Self { + Self::build_within(home, cancel, WALK_DEADLINE, true) + } + + /// [`Self::build`], the protected folders read only if `protected`. + pub fn build_for(home: &Path, cancel: &WalkCancel, protected: bool) -> Self { + Self::build_within(home, cancel, WALK_DEADLINE, protected) + } + + fn build_within(home: &Path, cancel: &WalkCancel, deadline: Duration, protected: bool) -> Self { + let protected = protected || !cfg!(target_os = "macos"); let threads = std::thread::available_parallelism() .map(|n| n.get().min(8)) .unwrap_or(4); - let collected: Mutex> = Mutex::new(Vec::new()); - ignore::WalkBuilder::new(home) - .hidden(true) - .follow_links(false) - .git_ignore(true) - .git_global(true) - .git_exclude(true) - .ignore(true) - .parents(false) - .threads(threads) - .filter_entry(|entry| entry.depth() == 0 || !skipped(entry)) - .build_parallel() - .run(|| { - let collected = &collected; - let mut batch = Batch { - items: Vec::new(), - sink: collected, - }; - Box::new(move |entry| { - if cancelled.load(Ordering::Relaxed) { - return ignore::WalkState::Quit; - } - let Ok(entry) = entry else { - return ignore::WalkState::Continue; - }; - if entry.depth() == 0 { - return ignore::WalkState::Continue; - } - let Ok(relative) = entry.path().strip_prefix(home) else { - return ignore::WalkState::Continue; - }; - let path = relative.to_string_lossy().replace('\\', "/"); - batch.items.push(HomePath { - lower: path.to_lowercase(), - path, - is_dir: entry.file_type().is_some_and(|kind| kind.is_dir()), - }); - if batch.items.len() >= 512 && batch.flush() >= MAX_ENTRIES { - return ignore::WalkState::Quit; - } - ignore::WalkState::Continue - }) - }); - let mut entries = collected - .into_inner() - .unwrap_or_else(std::sync::PoisonError::into_inner); + let walk = Arc::new(Walk { + home: home.to_path_buf(), + queue: Mutex::new(Queue::default()), + changed: Condvar::new(), + stop: AtomicBool::new(false), + found: Mutex::new(Vec::new()), + skip: stalled().clone().unwrap_or_default(), + protected, + #[cfg(test)] + wakes: Default::default(), + }); + #[cfg(test)] + tests::LAST_WALK.with(|last| *last.borrow_mut() = Arc::downgrade(&walk)); + *cancel.walk.lock().unwrap_or_else(PoisonError::into_inner) = Arc::downgrade(&walk); + if cancel.is_cancelled() { + return Self { + entries: Vec::new(), + built: Instant::now(), + protected, + }; + } + walk.push(Unit { + dir: home.to_path_buf(), + depth: 0, + }); + let mut spawned = 0; + for _ in 0..threads { + let worker = walk.clone(); + match std::thread::Builder::new() + .name("workspace-search-home-walk".into()) + .spawn(move || worker.work()) + { + Ok(_) => spawned += 1, + Err(error) => tracing::warn!(%error, "home walk worker did not start"), + } + } + if spawned > 0 { + let ends = Instant::now() + deadline; + let mut queue = walk.queue(); + while !queue.quit && (queue.active > 0 || !queue.units.is_empty()) { + let left = ends.saturating_duration_since(Instant::now()); + if left.is_zero() { + break; + } + queue = walk + .changed + .wait_timeout(queue, left) + .unwrap_or_else(PoisonError::into_inner) + .0; + } + // Past the deadline (or cancelled): folders still being read + // are skipped by later walks until their reads return. + if !queue.reading.is_empty() { + tracing::warn!( + folders = ?queue.reading, + "home walk: answering without folders whose listing hasn't returned" + ); + stalled() + .get_or_insert_with(HashSet::new) + .extend(queue.reading.iter().cloned()); + } + drop(queue); + walk.quit(); + } + let mut entries = + std::mem::take(&mut *walk.found.lock().unwrap_or_else(PoisonError::into_inner)); entries.truncate(MAX_ENTRIES); Self { entries, built: Instant::now(), + protected, } } @@ -172,47 +476,33 @@ impl HomeIndex { } } -struct Batch<'a> { - items: Vec, - sink: &'a Mutex>, -} - -impl Batch<'_> { - /// Move the batch into the shared list; returns the list's length. - fn flush(&mut self) -> usize { - let mut all = self - .sink - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - all.append(&mut self.items); - all.len() - } -} - -impl Drop for Batch<'_> { - fn drop(&mut self) { - if !self.items.is_empty() { - self.flush(); - } - } -} - fn depth(path: &str) -> usize { path.matches('/').count() } -/// Folders the walk never enters. Only folders are checked: listing a -/// cloud-only file's name downloads nothing, while listing a cloud-only -/// folder fetches its contents. -fn skipped(entry: &ignore::DirEntry) -> bool { - if !entry.file_type().is_some_and(|kind| kind.is_dir()) { - return false; - } - let name = entry.file_name().to_string_lossy().to_lowercase(); +/// Folders the walk never enters (`name` a folder's, `depth` below home). +/// Only folders are checked: listing a cloud-only file's name downloads +/// nothing, while listing a cloud-only folder fetches its contents. +fn skipped( + name: &str, + depth: usize, + protected: bool, + metadata: impl FnOnce() -> Option, +) -> bool { + let name = name.to_lowercase(); if name == ".git" || SKIPPED_DIRS.contains(&name.as_str()) { return true; } - if entry.depth() == 1 + #[cfg(target_os = "macos")] + if depth == 1 + && (MEDIA_ROOTS.contains(&name.as_str()) + || (!protected && PROTECTED_ROOTS.contains(&name.as_str()))) + { + return true; + } + #[cfg(not(target_os = "macos"))] + let _ = protected; + if depth == 1 && (MACHINE_ROOTS.contains(&name.as_str()) || CLOUD_ROOT_PREFIXES.iter().any(|prefix| { name == *prefix @@ -223,9 +513,7 @@ fn skipped(entry: &ignore::DirEntry) -> bool { { return true; } - entry - .metadata() - .is_ok_and(|metadata| is_cloud_placeholder(&metadata)) + metadata().is_some_and(|metadata| is_cloud_placeholder(&metadata)) } /// A folder whose contents a cloud client fetches on first listing. @@ -295,7 +583,7 @@ mod tests { ".config/plan.md", "boxes/plan.md", ]); - let index = HomeIndex::build(&root, &AtomicBool::new(false)); + let index = HomeIndex::build(&root, &WalkCancel::default()); assert_eq!( paths(&index, "plan", NameKinds::Files), ["boxes/plan.md", "dev/notes/plan.md"] @@ -310,7 +598,7 @@ mod tests { "dev/comet-notes.md", "x/comets/a.rs", ]); - let index = HomeIndex::build(&root, &AtomicBool::new(false)); + let index = HomeIndex::build(&root, &WalkCancel::default()); assert_eq!( paths(&index, "comet", NameKinds::Directories), ["comet", "dev/comet", "x/comets", "dev/comet/src"] @@ -330,4 +618,233 @@ mod tests { ] ); } + + thread_local! { + pub(super) static LAST_WALK: std::cell::RefCell> = + const { std::cell::RefCell::new(Weak::new()) }; + } + + /// Folders whose read waits until released, as `open()` waits on a + /// privacy prompt nobody answers. + type Gate = Arc<(Mutex, Condvar)>; + type Entered = Arc; + static HELD: Mutex> = Mutex::new(Vec::new()); + + pub(super) fn held(dir: &Path) { + let gate = HELD + .lock() + .unwrap() + .iter() + .find(|(held, _, _)| held == dir) + .map(|(_, gate, entered)| (gate.clone(), entered.clone())); + if let Some((gate, entered)) = gate { + entered.fetch_add(1, Ordering::SeqCst); + let (open, changed) = &*gate; + let mut open = open.lock().unwrap(); + while !*open { + open = changed.wait(open).unwrap(); + } + } + } + + fn hold( + dir: &Path, + ) -> ( + Arc<(Mutex, Condvar)>, + Arc, + ) { + let gate = Arc::new((Mutex::new(false), Condvar::new())); + let entered = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + HELD.lock() + .unwrap() + .push((dir.to_path_buf(), gate.clone(), entered.clone())); + (gate, entered) + } + + fn release(gate: &(Mutex, Condvar)) { + *gate.0.lock().unwrap() = true; + gate.1.notify_all(); + } + + /// A Mac's media libraries are never walked; its protected folders only + /// by a walk that asks for them (someone searching). + #[cfg(target_os = "macos")] + #[test] + fn media_folders_are_never_read_and_protected_ones_only_when_asked() { + let (_dir, root) = home(&[ + "Documents/proj/plan.md", + "Desktop/plan.md", + "Downloads/plan.md", + "Pictures/Photos Library.photoslibrary/plan.md", + "Music/plan.md", + "Movies/plan.md", + "dev/plan.md", + ]); + let opened = HomeIndex::build_for(&root, &WalkCancel::default(), false); + assert!(!opened.protected); + assert_eq!(paths(&opened, "plan", NameKinds::Files), ["dev/plan.md"]); + let searched = HomeIndex::build_for(&root, &WalkCancel::default(), true); + assert!(searched.protected); + assert_eq!( + paths(&searched, "plan", NameKinds::Files), + [ + "dev/plan.md", + "Desktop/plan.md", + "Downloads/plan.md", + "Documents/proj/plan.md" + ] + ); + } + + /// One folder never answers: the walk answers at its deadline with the + /// rest, its idle workers sleep instead of polling, and later walks skip + /// that folder (no second thread stuck in it) until its read returns. + #[test] + fn a_folder_that_never_answers_neither_holds_the_walk_nor_keeps_it_awake() { + let (_dir, root) = home(&[ + "Documents/proj/plan.md", + "dev/app/src/main.rs", + "dev/notes/plan.md", + "Work/song.txt", + ]); + let stuck = root.join("Documents"); + let (gate, entered) = hold(&stuck); + + let started = Instant::now(); + let index = HomeIndex::build_within( + &root, + &WalkCancel::default(), + Duration::from_millis(300), + true, + ); + let walk = LAST_WALK + .with(|last| last.borrow().upgrade()) + .expect("the stuck worker holds the walk"); + assert!( + started.elapsed() < Duration::from_secs(3), + "answered at its deadline" + ); + assert_eq!( + paths(&index, "plan", NameKinds::Files), + ["dev/notes/plan.md"] + ); + assert_eq!(paths(&index, "song", NameKinds::Files), ["Work/song.txt"]); + assert!(stalled().as_ref().is_some_and(|s| s.contains(&stuck))); + // While it waited out the stuck folder, idle workers slept (a + // polling worker wakes ~300 times in 300 ms). + assert!( + walk.wakes.load(Ordering::Relaxed) < 50, + "{} wakes", + walk.wakes.load(Ordering::Relaxed) + ); + + // The walk is over: its free workers left; nothing wakes while the + // stuck one waits. + let wakes = walk.wakes.load(Ordering::Relaxed); + std::thread::sleep(Duration::from_millis(300)); + assert!( + walk.wakes.load(Ordering::Relaxed) - wakes <= 1, + "idle workers must sleep, not poll" + ); + assert_eq!( + Arc::strong_count(&walk), + 2, + "only the stuck worker is left (and this test)" + ); + drop(walk); + + // A second walk doesn't send another thread into it. + let index = + HomeIndex::build_within(&root, &WalkCancel::default(), Duration::from_secs(5), true); + assert_eq!( + entered.load(Ordering::SeqCst), + 1, + "skipped while still stuck" + ); + assert_eq!( + paths(&index, "plan", NameKinds::Files), + ["dev/notes/plan.md"] + ); + + // Its read returns: the next walk reads it again. + release(&gate); + let deadline = Instant::now() + Duration::from_secs(5); + while stalled().as_ref().is_some_and(|s| s.contains(&stuck)) { + assert!( + Instant::now() < deadline, + "the returned read clears the stall" + ); + std::thread::sleep(Duration::from_millis(10)); + } + let index = + HomeIndex::build_within(&root, &WalkCancel::default(), Duration::from_secs(5), true); + assert_eq!( + paths(&index, "plan", NameKinds::Files), + ["dev/notes/plan.md", "Documents/proj/plan.md"] + ); + } + + /// Closing the picker cancels a walk at once, stuck folder or not. + #[test] + fn a_cancel_ends_the_walk_at_once() { + let (_dir, root) = home(&["Desktop/a.txt", "dev/b.txt"]); + let stuck = root.join("Desktop"); + let (gate, _) = hold(&stuck); + let cancel = Arc::new(WalkCancel::default()); + let canceller = cancel.clone(); + let started = Instant::now(); + let timer = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(100)); + canceller.cancel(); + }); + let _ = HomeIndex::build_within(&root, &cancel, Duration::from_secs(30), true); + assert!( + started.elapsed() < Duration::from_secs(5), + "cancel ended the walk" + ); + timer.join().unwrap(); + release(&gate); + } + + /// Repositories keep their ignore files, at any depth. + #[test] + fn a_repository_keeps_its_ignore_files() { + let (_dir, root) = home(&[ + "code/work/app/.git/", + "code/work/app/.gitignore", + "code/work/app/src/lib.rs", + "code/work/app/target/debug/lib.rs", + "solo/.git/", + "solo/.gitignore", + "solo/dist/lib.rs", + "solo/lib.rs", + ]); + std::fs::write(root.join("code/work/app/.gitignore"), "target/\n").unwrap(); + std::fs::write(root.join("solo/.gitignore"), "dist/\n").unwrap(); + let index = HomeIndex::build(&root, &WalkCancel::default()); + assert_eq!( + paths(&index, "lib.rs", NameKinds::Files), + ["solo/lib.rs", "code/work/app/src/lib.rs"] + ); + } +} + +// (macOS: it reads the process's footprint with proc_pid_rusage.) +#[cfg(all(test, target_os = "macos"))] +mod bench { + /// `HOME_WALK_BENCH= cargo test -p zeron-engine --lib home_walk_bench -- --ignored --nocapture` + #[test] + #[ignore] + fn home_walk_bench() { + let root = std::fs::canonicalize(std::env::var("HOME_WALK_BENCH").unwrap()).unwrap(); + for _ in 0..3 { + let started = std::time::Instant::now(); + let index = super::HomeIndex::build(&root, &Default::default()); + println!( + "WALK entries={} ms={}", + index.len(), + started.elapsed().as_millis() + ); + } + } } diff --git a/crates/engine/src/rpc.rs b/crates/engine/src/rpc.rs index 458252502..d3c5c5be2 100644 --- a/crates/engine/src/rpc.rs +++ b/crates/engine/src/rpc.rs @@ -2197,14 +2197,96 @@ where .boxed() } +/// Whether a watch asked for changes only (`{"changes": true}`): opt-in, +/// so older viewports keep the whole list on every change. +fn wants_changes(params: &serde_json::Value) -> bool { + params.get("changes").and_then(|v| v.as_bool()).unwrap_or(false) +} + +/// What a keyed list stream last sent: its keys in order, and each row. +type SentRows = (Vec, std::collections::HashMap); + +/// A list of rows keyed by `key` (`id`, or a session's `chatId`) as change +/// frames: the whole list first, as [`watch_stream`] sends it; then, per +/// change, only what moved: `{"changed": [row…], "removed": [key…]}`, plus +/// `"order": [key…]` when the keys' order isn't what it was. A change that +/// leaves every row as it was sends nothing. Applying a frame (replace or +/// add each changed row, drop the removed, then order by `order` if sent) +/// gives exactly the list the whole-list stream would have sent. +/// +/// The whole chat list is ~0.4 MB with a few hundred chats, and one field +/// of one row (a seen mark, a heartbeat) changing sent and parsed it all, +/// in every window on every device. +fn keyed_changes_stream(rx: watch::Receiver>, key: &'static str) -> BoxStream<'static, serde_json::Value> +where + T: serde::Serialize + Send + Sync + 'static, +{ + futures::stream::unfold((rx, None::), move |(mut rx, mut last)| async move { + loop { + if last.is_some() { + rx.changed().await.ok()?; + } + let rows: Vec = { + let borrowed = rx.borrow_and_update(); + borrowed.iter().filter_map(|row| serde_json::to_value(row).ok()).collect() + }; + let (frame, sent) = keyed_frame(rows, key, last.take()); + last = Some(sent); + if let Some(frame) = frame { + return Some((frame, (rx, last))); + } + } + }) + .boxed() +} + +/// `rows` as the frame that follows `last` (`None`: nothing changed), and +/// what's been sent once it is. No `last`: the whole list. +fn keyed_frame(rows: Vec, key: &str, last: Option) -> (Option, SentRows) { + let keys: Vec = rows + .iter() + .map(|row| row.get(key).and_then(|v| v.as_str()).unwrap_or_default().to_owned()) + .collect(); + let Some((last_keys, mut last_rows)) = last else { + let by_key = keys.iter().cloned().zip(rows.iter().cloned()).collect(); + return (Some(serde_json::Value::Array(rows)), (keys, by_key)); + }; + let mut changed = Vec::new(); + let mut now_rows = std::collections::HashMap::with_capacity(rows.len()); + for (k, row) in keys.iter().zip(rows) { + if last_rows.remove(k).as_ref() != Some(&row) { + changed.push(row.clone()); + } + now_rows.insert(k.clone(), row); + } + let removed: Vec<&String> = last_keys.iter().filter(|k| !now_rows.contains_key(*k)).collect(); + // (The order applying the rest gives: the rows kept where they were, + // new ones after. Sent only when the list's isn't that.) + let kept = last_keys.iter().filter(|k| now_rows.contains_key(*k)); + let was: std::collections::HashSet<&String> = last_keys.iter().collect(); + let added = keys.iter().filter(|k| !was.contains(k)); + let reordered = !kept.chain(added).eq(keys.iter()); + if changed.is_empty() && removed.is_empty() && !reordered { + return (None, (keys, now_rows)); + } + let mut frame = serde_json::json!({ "changed": changed, "removed": removed }); + if reordered { + frame["order"] = serde_json::json!(keys); + } + (Some(frame), (keys, now_rows)) +} + /// The transcript watch as delta frames (`zeron_doc::transcript_delta`): a /// full `reset` first, then only changed entries per commit — the whole-Vec /// serialization here was the per-tick cost that scaled with transcript size. +/// (`options`: what the watcher asked for beyond the original frames: a long +/// reply's changed parts alone, `partPatches`.) fn doc_messages_stream( rx: watch::Receiver, doc: std::sync::Arc, + options: zeron_doc::DiffOptions, ) -> BoxStream<'static, serde_json::Value> { - use zeron_doc::transcript_delta::{TranscriptFrame, diff_transcript}; + use zeron_doc::transcript_delta::{TranscriptFrame, diff_transcript_with}; futures::stream::unfold( ( rx, @@ -2213,7 +2295,7 @@ fn doc_messages_stream( None, zeron_doc::TranscriptBaseline::default(), ), - |(mut rx, mut prev, doc, mut previous_usage, mut opening_baseline)| async move { + move |(mut rx, mut prev, doc, mut previous_usage, mut opening_baseline)| async move { loop { if prev.is_some() { rx.changed().await.ok()?; @@ -2223,7 +2305,7 @@ fn doc_messages_stream( let current = rx.borrow_and_update().clone(); let frame = match prev.as_ref() { None => TranscriptFrame::reset(¤t.entries), - Some(prev) => diff_transcript(&prev.entries, ¤t.entries), + Some(prev) => diff_transcript_with(&prev.entries, ¤t.entries, options), }; let replay_baseline = match prev.as_ref() { None => { @@ -2334,6 +2416,7 @@ async fn windowed_doc_messages_stream( async fn opening_doc_messages_stream( host: crate::doc_host::DocHost, chat_id: String, + options: zeron_doc::DiffOptions, ) -> Result, RpcError> { let (handle, preview) = tokio::task::spawn_blocking(move || { let handle = host.open(&chat_id)?; @@ -2356,7 +2439,7 @@ async fn opening_doc_messages_stream( let full = futures::stream::once(async move { match tokio::task::spawn_blocking(move || (handle.watch_messages(), handle.doc_arc())).await { - Ok((rx, doc)) => doc_messages_stream(rx, doc), + Ok((rx, doc)) => doc_messages_stream(rx, doc, options), Err(error) => { tracing::warn!(%error, "transcript opening failed"); futures::stream::empty().boxed() @@ -2980,6 +3063,14 @@ impl RpcService for EngineRpc { .get("openingTail") .and_then(|v| v.as_bool()) .unwrap_or(false); + // Opt-in too: a reply's changed parts alone (`parts` frames), + // for a viewport that applies them. + let options = zeron_doc::DiffOptions { + part_patches: params + .get("partPatches") + .and_then(|v| v.as_bool()) + .unwrap_or(false), + }; let window = params .get("window") .filter(|v| !v.is_null()) @@ -2997,13 +3088,13 @@ impl RpcService for EngineRpc { // exactly as long as the stream. let interest = self.diff_sync.retain_chat(&p.chat_id); let stream = if opening_tail { - opening_doc_messages_stream(self.doc_host.clone(), p.chat_id).await? + opening_doc_messages_stream(self.doc_host.clone(), p.chat_id, options).await? } else { let handle = self .doc_host .open(&p.chat_id) .map_err(|e| RpcError::Failed(e.to_string()))?; - doc_messages_stream(handle.watch_messages(), handle.doc_arc()) + doc_messages_stream(handle.watch_messages(), handle.doc_arc(), options) }; Ok(RpcReply::Stream( stream @@ -3289,12 +3380,18 @@ impl RpcService for EngineRpc { }); Ok(RpcReply::Stream(Box::pin(stream))) } + methods::WATCH_CHATS if wants_changes(¶ms) => Ok(RpcReply::Stream( + keyed_changes_stream(self.workspace.watch_chats(), "id"), + )), methods::WATCH_CHATS => { Ok(RpcReply::Stream(watch_stream(self.workspace.watch_chats()))) } methods::WATCH_SIDEBAR_PREFERENCES => Ok(RpcReply::Stream(watch_stream( self.workspace.watch_sidebar_preferences(), ))), + methods::WATCH_DEVICES if wants_changes(¶ms) => Ok(RpcReply::Stream( + keyed_changes_stream(self.workspace.watch_devices(), "id"), + )), methods::WATCH_DEVICES => Ok(RpcReply::Stream(watch_stream( self.workspace.watch_devices(), ))), @@ -3309,6 +3406,9 @@ impl RpcService for EngineRpc { let merged = self .workspace .merged_sessions_watch(self.sessions.watch_sessions()); + if wants_changes(¶ms) { + return Ok(RpcReply::Stream(keyed_changes_stream(merged, "chatId"))); + } Ok(RpcReply::Stream(watch_stream(merged))) } methods::LOCAL_DEVICE => { @@ -4831,6 +4931,71 @@ impl RpcService for EngineRpc { mod tests { use super::*; + /// What a viewport does with a keyed list frame: the list it shows after. + fn apply_frame(list: &[serde_json::Value], frame: &serde_json::Value, key: &str) -> Vec { + if let Some(whole) = frame.as_array() { + return whole.clone(); + } + let id = |row: &serde_json::Value| row[key].as_str().unwrap_or_default().to_owned(); + let removed: Vec<&str> = frame["removed"].as_array().unwrap().iter().filter_map(|k| k.as_str()).collect(); + let mut rows: Vec = list.iter().filter(|row| !removed.contains(&id(row).as_str())).cloned().collect(); + for row in frame["changed"].as_array().unwrap() { + match rows.iter_mut().find(|r| id(r) == id(row)) { + Some(slot) => *slot = row.clone(), + None => rows.push(row.clone()), + } + } + if let Some(order) = frame["order"].as_array() { + rows = order.iter().filter_map(|k| rows.iter().find(|r| id(r) == k.as_str().unwrap()).cloned()).collect(); + } + rows + } + + /// `{"changes": true}`: the whole list once, then only the rows that + /// changed (a seen mark on one chat sends that chat, not all of them), + /// nothing for a change that changed no row, and, applied in order, + /// always the very list the whole-list stream sends. + #[test] + fn a_keyed_watch_sends_only_the_rows_that_changed() { + use serde_json::json; + let lists = [ + json!([{ "id": "a", "seen": 1 }, { "id": "b", "seen": 1 }, { "id": "c", "seen": 1 }]), + json!([{ "id": "a", "seen": 1 }, { "id": "b", "seen": 2 }, { "id": "c", "seen": 1 }]), + json!([{ "id": "a", "seen": 1 }, { "id": "b", "seen": 2 }, { "id": "c", "seen": 1 }]), + json!([{ "id": "c", "seen": 1 }, { "id": "a", "seen": 1 }, { "id": "d", "seen": 0 }]), + json!([]), + ]; + let mut sent = None; + let mut shown: Vec = Vec::new(); + let mut frames = Vec::new(); + for list in &lists { + let rows = list.as_array().unwrap().clone(); + let (frame, now) = keyed_frame(rows, "id", sent.take()); + sent = Some(now); + if let Some(frame) = &frame { + shown = apply_frame(&shown, frame, "id"); + } + assert_eq!(&serde_json::Value::Array(shown.clone()), list); + frames.push(frame); + } + assert!(frames[0].as_ref().unwrap().is_array(), "the whole list first"); + assert_eq!(frames[1], Some(json!({ "changed": [{ "id": "b", "seen": 2 }], "removed": [] }))); + assert_eq!(frames[2], None, "nothing changed: nothing sent"); + assert_eq!( + frames[3], + Some(json!({ "changed": [{ "id": "d", "seen": 0 }], "removed": ["b"], "order": ["c", "a", "d"] })) + ); + assert_eq!(frames[4], Some(json!({ "changed": [], "removed": ["c", "a", "d"] }))); + } + + /// Without asking, a watch is the whole list, as older viewports read it. + #[test] + fn changes_are_opt_in() { + assert!(!wants_changes(&serde_json::json!({}))); + assert!(!wants_changes(&serde_json::Value::Null)); + assert!(wants_changes(&serde_json::json!({ "changes": true }))); + } + #[tokio::test] async fn voice_owner_is_shared_across_services_and_shutdown_retires_it() { let temp = tempfile::tempdir().unwrap(); @@ -5309,7 +5474,7 @@ mod tests { locked_rx.recv().unwrap(); let opening = tokio::time::timeout( Duration::from_secs(2), - opening_doc_messages_stream(host.clone(), "whale".into()), + opening_doc_messages_stream(host.clone(), "whale".into(), Default::default()), ) .await; release_tx.send(()).unwrap(); @@ -5704,7 +5869,7 @@ mod context_usage_tests { let handle = host.open("replay-chat").unwrap(); let sink = crate::chat2_host::EngineChatSink::new(&handle.doc_arc(), store, "replay-chat") .with_handle(Arc::downgrade(&handle)); - let mut stream = doc_messages_stream(handle.watch_messages(), handle.doc_arc()); + let mut stream = doc_messages_stream(handle.watch_messages(), handle.doc_arc(), Default::default()); let first: zeron_doc::TranscriptUpdate = serde_json::from_value(stream.next().await.unwrap()).unwrap(); assert!(first.replay_baseline.unwrap().entries.is_empty()); @@ -5801,7 +5966,7 @@ mod context_usage_tests { update.replay_baseline.is_none(), "live updates must not resend the history watermark" ); - let mut reopened = doc_messages_stream(handle.watch_messages(), handle.doc_arc()); + let mut reopened = doc_messages_stream(handle.watch_messages(), handle.doc_arc(), Default::default()); let opening: zeron_doc::TranscriptUpdate = serde_json::from_value(reopened.next().await.unwrap()).unwrap(); assert_eq!( @@ -5829,7 +5994,7 @@ mod context_usage_tests { let handle = host.open("interleaved").unwrap(); let sink = crate::chat2_host::EngineChatSink::new(&handle.doc_arc(), store, "interleaved") .with_handle(Arc::downgrade(&handle)); - let mut stream = doc_messages_stream(handle.watch_messages(), handle.doc_arc()); + let mut stream = doc_messages_stream(handle.watch_messages(), handle.doc_arc(), Default::default()); stream.next().await.unwrap(); let source = zeron_doc::SessionDoc::init("interleaved").unwrap(); sink.apply_checkpoint(&source.export_snapshot().unwrap(), 0) @@ -5921,7 +6086,7 @@ mod context_usage_tests { .unwrap(); // Cached content exists before the first watcher and never enters // the changed-parts tracker. It may not have been painted yet. - let mut first = doc_messages_stream(handle.watch_messages(), handle.doc_arc()); + let mut first = doc_messages_stream(handle.watch_messages(), handle.doc_arc(), Default::default()); let opening: zeron_doc::TranscriptUpdate = serde_json::from_value(first.next().await.unwrap()).unwrap(); assert_eq!( @@ -5942,7 +6107,7 @@ mod context_usage_tests { assert!(update.replay_baseline.is_none()); // A later subscriber sees a longer historical prefix, but must not // change the first subscriber's ongoing live animation. - let mut second = doc_messages_stream(handle.watch_messages(), handle.doc_arc()); + let mut second = doc_messages_stream(handle.watch_messages(), handle.doc_arc(), Default::default()); let opening: zeron_doc::TranscriptUpdate = serde_json::from_value(second.next().await.unwrap()).unwrap(); assert_eq!( @@ -6006,7 +6171,7 @@ mod context_usage_tests { id: "body".into(), text: text.into(), }; - let mut stream = doc_messages_stream(handle.watch_messages(), handle.doc_arc()); + let mut stream = doc_messages_stream(handle.watch_messages(), handle.doc_arc(), Default::default()); stream.next().await.unwrap(); writer.sync(&[part("live")]).unwrap(); sink.apply_row(&source.export_snapshot().unwrap(), 1); @@ -6017,7 +6182,7 @@ mod context_usage_tests { .unwrap(); drop(stream); // No unwatched commit clears provenance before the new attach. - let mut stream = doc_messages_stream(handle.watch_messages(), handle.doc_arc()); + let mut stream = doc_messages_stream(handle.watch_messages(), handle.doc_arc(), Default::default()); stream.next().await.unwrap(); writer.sync(&[part("live plus recovered")]).unwrap(); sink.apply_replay_row(&source.export_snapshot().unwrap(), 2); @@ -6035,6 +6200,72 @@ mod context_usage_tests { host.shutdown_workers().await; } + /// A long reply's calls arriving and finishing: a watcher that asked for + /// part patches gets the changed calls alone; one that didn't, the reply + /// whole as ever. Both end with the same transcript. + #[tokio::test] + async fn part_patches_carry_a_reply_s_changed_calls_alone_when_asked_for() { + use crate::doc_host::{DocHost, DocHostConfig}; + use zeron_sync::chat_client::ChatDocSink; + let dir = tempfile::tempdir().unwrap(); + let store = Arc::new(zeron_sync::DocsStore::open(dir.path()).unwrap()); + let host = DocHost::new( + store.clone(), + DocHostConfig { + device_id: "viewer".into(), + default_harness: zeron_proto::HarnessId::Mock, + edge: None, + }, + ); + let handle = host.open("parts").unwrap(); + let sink = crate::chat2_host::EngineChatSink::new(&handle.doc_arc(), store, "parts") + .with_handle(Arc::downgrade(&handle)); + let source = zeron_doc::SessionDoc::init("parts").unwrap(); + let mut writer = zeron_doc::SegmentWriter::begin(&source, "reply", "host", 0).unwrap(); + let call = |i: usize, output: Option<&str>| -> zeron_doc::MessagePart { + serde_json::from_value(serde_json::json!({ + "kind": "tool", "id": format!("t{i}"), + "call": { "kind": "exec", "command": format!("echo {i}") }, + "resolved": output.is_some(), "output": output, + })) + .unwrap() + }; + let mut calls: Vec<_> = (0..40).map(|i| call(i, Some("ok"))).collect(); + calls.push(call(40, None)); + writer.sync(&calls).unwrap(); + sink.apply_row(&source.export_snapshot().unwrap(), 1); + let options = zeron_doc::DiffOptions { part_patches: true }; + let mut patched = doc_messages_stream(handle.watch_messages(), handle.doc_arc(), options); + let mut whole = doc_messages_stream(handle.watch_messages(), handle.doc_arc(), Default::default()); + async fn next(stream: &mut BoxStream<'static, serde_json::Value>) -> serde_json::Value { + tokio::time::timeout(std::time::Duration::from_secs(2), stream.next()) + .await + .unwrap() + .unwrap() + } + let read = |value: serde_json::Value| serde_json::from_value::(value).unwrap(); + let (mut a, mut b) = (vec![], vec![]); + zeron_doc::apply_transcript_frame(&mut a, read(next(&mut patched).await).frame).unwrap(); + zeron_doc::apply_transcript_frame(&mut b, read(next(&mut whole).await).frame).unwrap(); + // The call in flight finishes, and the next arrives. + calls[40] = call(40, Some("done")); + calls.push(call(41, None)); + writer.sync(&calls).unwrap(); + sink.apply_row(&source.export_snapshot().unwrap(), 2); + let value = next(&mut patched).await; + assert!(value.get("upsert").is_none_or(|u| u.as_array().is_some_and(Vec::is_empty)), "{value}"); + let ids: Vec<_> = value["parts"].as_array().unwrap().iter().map(|p| p["part"]["id"].as_str().unwrap().to_owned()).collect(); + assert_eq!(ids, ["t40", "t41"]); + zeron_doc::apply_transcript_frame(&mut a, read(value).frame).unwrap(); + let value = next(&mut whole).await; + assert!(value.get("parts").is_none(), "{value}"); + assert_eq!(value["upsert"].as_array().map(Vec::len), Some(1)); + zeron_doc::apply_transcript_frame(&mut b, read(value).frame).unwrap(); + assert_eq!(a, b); + assert_eq!(a[0].parts.len(), 42); + host.shutdown_workers().await; + } + #[tokio::test] async fn context_only_commits_reach_remote_watch_and_reconnect() { let host = zeron_doc::SessionDoc::init("context-chat").unwrap(); @@ -6047,7 +6278,7 @@ mod context_usage_tests { .import(&host.export_snapshot().unwrap()) .unwrap(); let (tx, rx) = watch::channel(crate::doc_host::TranscriptSnapshot::default()); - let mut stream = doc_messages_stream(rx, remote.clone()); + let mut stream = doc_messages_stream(rx, remote.clone(), Default::default()); let first = stream.next().await.unwrap(); assert_eq!(first["contextUsage"]["tokens"], 42000); assert!(first.get("reset").is_some()); @@ -6069,7 +6300,7 @@ mod context_usage_tests { .unwrap(); assert_eq!(update["contextUsage"]["tokens"], 0); assert_eq!(update["contextUsage"]["window"], 200000); - let mut reconnect = doc_messages_stream(tx.subscribe(), remote.clone()); + let mut reconnect = doc_messages_stream(tx.subscribe(), remote.clone(), Default::default()); assert_eq!( reconnect.next().await.unwrap()["contextUsage"], update["contextUsage"] diff --git a/crates/engine/src/run_journal.rs b/crates/engine/src/run_journal.rs index fb11255f8..b87c3b495 100644 --- a/crates/engine/src/run_journal.rs +++ b/crates/engine/src/run_journal.rs @@ -9,12 +9,24 @@ //! //! Bounded-window compaction is deferred (whole file kept for now, per M2 scope); a torn //! trailing line from a crash mid-write is tolerated everywhere. +//! +//! Lines are written in batches: a streaming agent sends tens of events a second, and +//! a `write` each (under the one lock every chat's appends share) was a large part of +//! a streaming engine's work. An event waits in memory for [`FLUSH_AFTER`] while +//! appends keep coming (or until [`RunJournal::flush`], which a run calls with each doc +//! commit), a turn's `Done` is written at once, and every read writes what's waiting +//! first. What the last appends left waiting (a turn's usage after its `Done`) a +//! flusher thread writes [`IDLE_FLUSH`] later: it sleeps while nothing waits. +//! +//! A write that fails keeps what didn't reach the file to retry with the next write, +//! so a passing failure leaves no gap; only past [`MAX_PENDING`] is it dropped, and +//! that is logged as an error. use std::collections::HashMap; use std::fs::{File, OpenOptions}; use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; -use std::sync::{Mutex, MutexGuard, PoisonError}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; use serde::{Deserialize, Serialize}; @@ -34,34 +46,186 @@ struct JournalLine { event: AgentEvent, } +/// A [`JournalLine`] to write, borrowing its event. +#[derive(Serialize)] +struct JournalLineRef<'a> { + seq: u64, + event: &'a AgentEvent, +} + +/// The longest an appended line waits in memory before it's written. +const FLUSH_AFTER: std::time::Duration = std::time::Duration::from_millis(100); +/// Lines waiting past this many bytes are written at once. +const FLUSH_BYTES: usize = 64 * 1024; +/// The longest a line waits when no append follows it (the flusher thread). +const IDLE_FLUSH: std::time::Duration = std::time::Duration::from_secs(1); +/// What a chat's journal keeps to retry while its writes fail; past it, what waits is +/// dropped (a gap in the journal, logged as an error). +const MAX_PENDING: usize = 8 * 1024 * 1024; + struct ChatJournal { file: File, next_seq: u64, /// True when the file ends without a newline (torn write) — the next append /// starts with one so the torn line stays isolated. needs_newline: bool, + /// Lines appended and not yet written, and since when (or since the last failed + /// write of them, which the flusher retries from). + pending: Vec, + pending_since: Option, + /// The last write failed (logged once until one succeeds). + failing: bool, +} + +impl ChatJournal { + /// Write what's waiting. A failure keeps the unwritten rest to retry (it + /// continues the line it stopped in, so nothing is torn or written twice) and + /// is `Ok`; `Err` only when lines were dropped, past [`MAX_PENDING`]. + fn write_pending(&mut self, chat: &str) -> Result<(), JournalError> { + if self.pending.is_empty() { + return Ok(()); + } + let mut written = 0; + let result = loop { + match self.file.write(&self.pending[written..]) { + Ok(0) => break Err(std::io::Error::from(std::io::ErrorKind::WriteZero)), + Ok(n) => { + written += n; + if written == self.pending.len() { + break Ok(()); + } + } + Err(err) if err.kind() == std::io::ErrorKind::Interrupted => {} + Err(err) => break Err(err), + } + }; + self.pending.drain(..written); + let Err(err) = result else { + self.pending_since = None; + if std::mem::take(&mut self.failing) { + tracing::info!(chat = %chat, "journal writes recovered"); + } + return Ok(()); + }; + if self.pending.len() <= MAX_PENDING { + if !std::mem::replace(&mut self.failing, true) { + tracing::warn!(chat = %chat, error = %err, waiting = self.pending.len(), "journal write failed; retrying"); + } + // Retried by the next append, or the flusher a while from now. + self.pending_since = Some(std::time::Instant::now()); + return Ok(()); + } + let lost = self.pending.iter().filter(|b| **b == b'\n').count(); + self.pending.clear(); + self.pending_since = None; + // What reached the file may end mid-line: the next append starts with a + // newline, so that torn line stays isolated. + self.needs_newline = true; + tracing::error!(chat = %chat, error = %err, lost, "journal write failed; events dropped"); + Err(err.into()) + } } /// Append-only JSONL journal store, one file per chat. pub struct RunJournal { dir: PathBuf, + shared: Arc, + flusher: Option>, +} + +/// What the journal shares with its flusher thread. +struct Shared { open_files: Mutex>, + /// Lines started waiting, or the journal closed. + wake: Condvar, + closed: std::sync::atomic::AtomicBool, +} + +impl Shared { + fn lock(&self) -> MutexGuard<'_, HashMap> { + self.open_files + .lock() + .unwrap_or_else(PoisonError::into_inner) + } + + /// The flusher: writes what has waited [`IDLE_FLUSH`] with no append to take it + /// along; asleep while nothing waits. + fn flush_idle(&self) { + use std::sync::atomic::Ordering; + let mut files = self.lock(); + while !self.closed.load(Ordering::SeqCst) { + let now = std::time::Instant::now(); + let mut next: Option = None; + for (chat, journal) in files.iter_mut() { + let Some(since) = journal.pending_since else { + continue; + }; + if since + IDLE_FLUSH <= now { + // (A drop is logged where it happens.) + let _ = journal.write_pending(chat); + } + if let Some(since) = journal.pending_since { + let due = since + IDLE_FLUSH; + next = Some(next.map_or(due, |next| next.min(due))); + } + } + files = match next { + Some(due) => { + self.wake + .wait_timeout(files, due.saturating_duration_since(now)) + .unwrap_or_else(PoisonError::into_inner) + .0 + } + None => self + .wake + .wait(files) + .unwrap_or_else(PoisonError::into_inner), + }; + } + } +} + +impl Drop for RunJournal { + fn drop(&mut self) { + self.shared + .closed + .store(true, std::sync::atomic::Ordering::SeqCst); + { + // (Under the lock: the flusher is waiting, or sees `closed` first.) + let _files = self.lock(); + self.shared.wake.notify_all(); + } + if let Some(flusher) = self.flusher.take() { + let _ = flusher.join(); + } + self.flush_all(); + } } impl RunJournal { pub fn open(dir: impl AsRef) -> Result { let dir = dir.as_ref().to_path_buf(); std::fs::create_dir_all(&dir)?; + let shared = Arc::new(Shared { + open_files: Mutex::new(HashMap::new()), + wake: Condvar::new(), + closed: std::sync::atomic::AtomicBool::new(false), + }); + let flusher = { + let shared = shared.clone(); + std::thread::Builder::new() + .name("journal-flush".into()) + .spawn(move || shared.flush_idle())? + }; Ok(Self { dir, - open_files: Mutex::new(HashMap::new()), + shared, + flusher: Some(flusher), }) } fn lock(&self) -> MutexGuard<'_, HashMap> { - self.open_files - .lock() - .unwrap_or_else(PoisonError::into_inner) + self.shared.lock() } fn path_for(&self, chat_id: &str) -> PathBuf { @@ -106,6 +270,14 @@ impl RunJournal { // comfortably exceeds concurrent runs, so eviction stays rare. const OPEN_FILE_CAP: usize = 16; if files.len() >= OPEN_FILE_CAP { + for (chat, journal) in files.iter_mut() { + // (A failure is logged by the write; what still waits is lost + // with the entry, as an error.) + let _ = journal.write_pending(chat); + if !journal.pending.is_empty() { + tracing::error!(chat = %chat, bytes = journal.pending.len(), "journal closed with unwritten events"); + } + } files.clear(); } let path = self.path_for(chat_id); @@ -117,6 +289,9 @@ impl RunJournal { file, next_seq, needs_newline, + pending: Vec::new(), + pending_since: None, + failing: false, }, ); } @@ -127,23 +302,45 @@ impl RunJournal { ))); }; let seq = journal.next_seq; - let line = serde_json::to_string(&JournalLine { - seq, - event: event.clone(), - })?; - let mut buf = Vec::with_capacity(line.len() + 2); - if journal.needs_newline { - buf.push(b'\n'); + let line = serde_json::to_vec(&JournalLineRef { seq, event })?; + if journal.pending.is_empty() { + if std::mem::take(&mut journal.needs_newline) { + journal.pending.push(b'\n'); + } + journal.pending_since = Some(std::time::Instant::now()); + // The flusher writes it if no append comes to. + self.shared.wake.notify_one(); } - buf.extend_from_slice(line.as_bytes()); - buf.push(b'\n'); - journal.file.write_all(&buf)?; - journal.file.flush()?; - journal.needs_newline = false; + journal.pending.extend_from_slice(&line); + journal.pending.push(b'\n'); journal.next_seq = seq + 1; + let due = matches!(event, AgentEvent::Done { .. }) + || journal.pending.len() >= FLUSH_BYTES + || journal + .pending_since + .is_some_and(|since| since.elapsed() >= FLUSH_AFTER); + if due { + journal.write_pending(chat_id)?; + } Ok(seq) } + /// Write what's waiting of a chat's journal (a run calls this with each + /// doc commit, so the journal is never behind its transcript). + pub fn flush(&self, chat_id: &str) { + if let Some(journal) = self.lock().get_mut(chat_id) { + // (A failure is logged by the write.) + let _ = journal.write_pending(chat_id); + } + } + + /// Write what's waiting of every chat's journal. + pub fn flush_all(&self) { + for (chat, journal) in self.lock().iter_mut() { + let _ = journal.write_pending(chat); + } + } + /// Events with `seq > after_seq`, in order. A cursor ahead of the last issued seq is /// from a previous era (file replaced) — falls back to a full replay, mirroring godspeed. pub fn replay( @@ -151,6 +348,7 @@ impl RunJournal { chat_id: &str, after_seq: u64, ) -> Result, JournalError> { + self.flush(chat_id); let path = self.path_for(chat_id); if !path.exists() { return Ok(Vec::new()); @@ -163,6 +361,7 @@ impl RunJournal { /// The last event in a chat's journal, if any (ignores a torn tail line). pub fn last_event(&self, chat_id: &str) -> Result, JournalError> { + self.flush(chat_id); last_valid_line(&self.path_for(chat_id)) } @@ -173,12 +372,14 @@ impl RunJournal { &self, chat_id: &str, ) -> Result>, JournalError> { + self.flush(chat_id); RevEvents::open(&self.path_for(chat_id)) } /// Crash-recovery scan: chat ids whose journal's last event is NOT a `Done` — their /// runs died mid-stream and need recovery (stamp `aborted`, close the journal). pub fn stale_sessions(&self) -> Result, JournalError> { + self.flush_all(); let mut stale = Vec::new(); for entry in std::fs::read_dir(&self.dir)? { let entry = entry?; @@ -446,6 +647,93 @@ mod tests { assert_eq!(journal.replay("chat-1", 99).unwrap().len(), 3); } + /// The lines on disk, read without the journal (whose reads write what + /// waits first). + fn on_disk(dir: &Path, chat: &str) -> Vec { + read_lines(&dir.join(format!("{chat}.jsonl"))) + .unwrap() + .into_iter() + .map(|(seq, _)| seq) + .collect() + } + + /// A turn's usage comes after its `Done`, and then nothing: it reaches + /// the file within a second or so, with no append or read to take it. + #[test] + fn an_event_left_waiting_is_written_without_another_append() { + let dir = tempfile::tempdir().unwrap(); + let journal = RunJournal::open(dir.path()).unwrap(); + journal.append("chat-1", &text("a")).unwrap(); + journal.append("chat-1", &done()).unwrap(); + journal.append("chat-1", &text("usage")).unwrap(); + assert_eq!(on_disk(dir.path(), "chat-1"), vec![1, 2], "batched still"); + let deadline = std::time::Instant::now() + IDLE_FLUSH * 5; + while on_disk(dir.path(), "chat-1") != vec![1, 2, 3] { + assert!( + std::time::Instant::now() < deadline, + "the waiting event was never written" + ); + std::thread::sleep(std::time::Duration::from_millis(50)); + } + } + + /// Writes that fail keep what waits and retry it: once the file takes + /// writes again, every event is there, in order, with no gap. + #[cfg(unix)] + #[test] + fn a_failed_write_is_retried_not_left_as_a_gap() { + let dir = tempfile::tempdir().unwrap(); + let journal = RunJournal::open(dir.path()).unwrap(); + journal.append("chat-1", &text("a")).unwrap(); + journal.flush("chat-1"); + let path = dir.path().join("chat-1.jsonl"); + // A handle that can't write: every write fails (EBADF). + let writable = { + let mut files = journal.lock(); + let entry = files.get_mut("chat-1").unwrap(); + std::mem::replace(&mut entry.file, File::open(&path).unwrap()) + }; + assert_eq!(journal.append("chat-1", &text("b")).unwrap(), 2); + assert_eq!( + journal.append("chat-1", &done()).unwrap(), + 3, + "kept to retry" + ); + journal.flush("chat-1"); + assert_eq!(on_disk(dir.path(), "chat-1"), vec![1]); + journal.lock().get_mut("chat-1").unwrap().file = writable; + assert_eq!(journal.append("chat-1", &text("c")).unwrap(), 4); + journal.flush("chat-1"); + assert_eq!(on_disk(dir.path(), "chat-1"), vec![1, 2, 3, 4]); + } + + /// Past [`MAX_PENDING`] what waits is dropped: reported as an error, and + /// the journal goes on from a fresh line. + #[cfg(unix)] + #[test] + fn a_write_failing_past_the_cap_reports_the_drop() { + let dir = tempfile::tempdir().unwrap(); + let journal = RunJournal::open(dir.path()).unwrap(); + journal.append("chat-1", &text("a")).unwrap(); + journal.flush("chat-1"); + let path = dir.path().join("chat-1.jsonl"); + let writable = { + let mut files = journal.lock(); + let entry = files.get_mut("chat-1").unwrap(); + std::mem::replace(&mut entry.file, File::open(&path).unwrap()) + }; + let big = "x".repeat(1024 * 1024); + let mut failed = false; + for _ in 0..(MAX_PENDING / big.len() + 2) { + failed |= journal.append("chat-1", &text(&big)).is_err(); + } + assert!(failed, "the drop was not reported"); + journal.lock().get_mut("chat-1").unwrap().file = writable; + let next = journal.append("chat-1", &done()).unwrap(); + journal.flush("chat-1"); + assert_eq!(on_disk(dir.path(), "chat-1").last(), Some(&next)); + } + #[test] fn seq_continues_across_reopen() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/engine/src/sessions.rs b/crates/engine/src/sessions.rs index 1fb66b455..760053bf1 100644 --- a/crates/engine/src/sessions.rs +++ b/crates/engine/src/sessions.rs @@ -656,6 +656,15 @@ impl SessionsEngine { /// question it is still owed an answer to (see [`is_active`]). A persistent /// session parked BETWEEN turns is not: it holds a warm child with nothing /// outstanding, and takes the next prompt straight through its mailbox. + /// When the turn now running started (epoch millis), while one is. + pub fn turn_started_ms(&self, chat_id: &str) -> Option { + lock(&self.inner.statuses) + .get(chat_id) + .filter(|session| is_active(session)) + .and_then(|session| session.started_at) + .map(|started| started.timestamp_millis()) + } + pub fn turn_in_flight(&self, chat_id: &str) -> bool { lock(&self.inner.statuses) .get(chat_id) @@ -1468,6 +1477,11 @@ impl SessionsEngine { /// under their own ids. Otherwise, or when the stop doesn't settle, it /// is an ordinary steer ([`Self::steer_at`]), read at the next step /// boundary. Nothing here tears a runtime down. + /// + /// A message from another chat never stops the turn: Claude Code words + /// every interrupt as the person rejecting the tool call and telling the + /// agent to stop and wait, so the agent would take the other chat's + /// message as an order to stop. It waits for the step boundary instead. pub(crate) async fn steer_now( &self, chat_id: &str, @@ -1476,7 +1490,11 @@ impl SessionsEngine { message_id: Option, issued_at: i64, ) -> Result { - if self.steer_stops_tool(chat_id) && self.stop_turn_keeping_runtime(chat_id).await { + let from_another_chat = zeron_proto::agent_messages::agent_message_sender(prompt).is_some(); + if !from_another_chat + && self.steer_stops_tool(chat_id) + && self.stop_turn_keeping_runtime(chat_id).await + { let earlier = lock(&self.inner.runs) .get(chat_id) .map(|h| std::mem::take(&mut *lock(&h.redeliver))) @@ -1931,6 +1949,8 @@ impl SessionsEngine { tracing::warn!(chat = %chat_id, error = %err, "shutdown interrupt failed"); } } + // Lines still waiting to be written (`run_journal`'s batching). + self.inner.journal.flush_all(); } fn is_live(&self, chat_id: &str, run_id: &str) -> bool { @@ -2761,6 +2781,17 @@ fn is_chat_spawn(id: &str, folded: &[MessagePart], doc: &SessionDoc) -> bool { }) || doc.has_subagent_spawn(id) } +/// When to commit what just changed: at once, unless a commit went out less than a +/// window ago, then a window after it. The same at most one per window as waiting a +/// window every time, without making the first change after a pause wait. +fn next_commit(last: Option) -> tokio::time::Instant { + let now = tokio::time::Instant::now(); + match last { + Some(at) => (at + std::time::Duration::from_millis(STREAM_COMMIT_MS)).max(now), + None => now, + } +} + /// Test-only instrumentation: how often `drive_run`'s coalesced commit branch /// fires. The sink-dirty regression test proves the branch ticks once per /// commit window instead of spinning on a deadline left in the past. @@ -3529,6 +3560,9 @@ async fn drive_run( let mut writer: Option> = None; let mut dirty = false; let mut flush_at = tokio::time::Instant::now(); + // Commits are at most one per window, but the first after a quiet spell goes at + // once: a turn's first token and a steer's echo don't wait out a window. + let mut last_flush: Option = None; // Set when the engine interrupts the run: the harness gets this long to end its own // stream (its token was cancelled); past it, a terminal Done is synthesized. let mut interrupt_deadline: Option = None; @@ -3903,6 +3937,7 @@ async fn drive_run( FLUSH_TICKS.with(|t| t.set(t.get() + 1)); // Coalesced STREAM_COMMIT_MS tick: one doc commit per window // (parent + any dirty subagent docs). + last_flush = Some(tokio::time::Instant::now()); if dirty { if let Err(err) = sync_segment( doc_ref, &mut writer, &entry_id, &device_id, segment_started, &folded, @@ -3914,6 +3949,8 @@ async fn drive_run( for sink in subagents.values_mut() { sink.flush(&device_id); } + // The journal keeps up with the transcript it backs. + inner.journal.flush(&chat_id); continue; } // Turn-quiesce watchdog (see the knob above). Armed only when the @@ -4123,8 +4160,7 @@ async fn drive_run( zeron_doc::fold_event_into_parts(&mut folded, &event); if !dirty { dirty = true; - flush_at = tokio::time::Instant::now() - + std::time::Duration::from_millis(STREAM_COMMIT_MS); + flush_at = next_commit(last_flush); } } // Open the sink lazily; an open failure degrades to chip-only. @@ -4192,8 +4228,7 @@ async fn drive_run( // fire the commit branch on every event instead of once per // STREAM_COMMIT_MS window. if was_clean && !dirty && flush_at <= tokio::time::Instant::now() { - flush_at = tokio::time::Instant::now() - + std::time::Duration::from_millis(STREAM_COMMIT_MS); + flush_at = next_commit(last_flush); } if done { let status = match sub_event.as_ref() { @@ -4824,8 +4859,7 @@ async fn drive_run( if !folded.is_empty() && !dirty { dirty = true; - flush_at = - tokio::time::Instant::now() + std::time::Duration::from_millis(STREAM_COMMIT_MS); + flush_at = next_commit(last_flush); } }; @@ -4927,6 +4961,19 @@ async fn drive_run( mod tests { use super::*; + #[tokio::test(start_paused = true)] + async fn the_first_change_after_a_pause_commits_at_once_and_a_stream_stays_paced() { + let window = std::time::Duration::from_millis(STREAM_COMMIT_MS); + let start = tokio::time::Instant::now(); + assert_eq!(next_commit(None), start, "a turn's first token"); + assert_eq!(next_commit(Some(start)), start + window, "just committed: a window on"); + tokio::time::advance(window * 3).await; + assert_eq!(next_commit(Some(start)), tokio::time::Instant::now(), "quiet since"); + tokio::time::advance(window / 2).await; + let recent = tokio::time::Instant::now() - window / 4; + assert_eq!(next_commit(Some(recent)), recent + window); + } + #[test] fn the_mcp_server_leaves_preview_tools_out_without_a_window() { let windowed = diff --git a/crates/engine/src/terminals.rs b/crates/engine/src/terminals.rs index 5c7f65cb6..8c6f24674 100644 --- a/crates/engine/src/terminals.rs +++ b/crates/engine/src/terminals.rs @@ -252,7 +252,7 @@ fn forget_launching_multiplexer(cmd: &mut CommandBuilder) { /// The user's interactive shell: `$SHELL`, else the platform default. fn selected_shell() -> String { if cfg!(windows) { - return std::env::var("COMSPEC").unwrap_or_else(|_| "powershell.exe".into()); + return windows_shell(|name| std::env::var_os(name), |path| path.is_file()); } std::env::var("SHELL") .ok() @@ -266,6 +266,44 @@ fn selected_shell() -> String { }) } +/// Windows' interactive shell: PowerShell 7 (`pwsh.exe` on `PATH`), else +/// the Windows PowerShell every Windows has, else `%COMSPEC%` (cmd.exe). +/// PowerShell, not cmd: its prompt ends in a space and PSReadLine colours +/// what's typed, as a terminal on macOS or Linux does. +fn windows_shell( + var: impl Fn(&str) -> Option, + exists: impl Fn(&std::path::Path) -> bool, +) -> String { + let pwsh = var("PATH") + .into_iter() + .flat_map(|path| std::env::split_paths(&path).collect::>()) + .map(|dir| dir.join("pwsh.exe")) + .find(|path| exists(path)); + let windows_powershell = var("SystemRoot") + .map(|root| { + std::path::PathBuf::from(root) + .join("System32") + .join("WindowsPowerShell") + .join("v1.0") + .join("powershell.exe") + }) + .filter(|path| exists(path)); + pwsh.or(windows_powershell) + .map(|path| path.to_string_lossy().into_owned()) + .or_else(|| var("COMSPEC").map(|comspec| comspec.to_string_lossy().into_owned())) + .unwrap_or_else(|| "cmd.exe".into()) +} + +/// Whether `shell` is PowerShell (7's `pwsh` or Windows PowerShell), which +/// prints a banner as it starts unless told `-NoLogo`. Its last part, split +/// at either slash: a Windows path reads the same wherever it's asked +/// (`std::path` splits at `\` only on Windows, and the tests run on all). +fn is_powershell(shell: &str) -> bool { + let file = shell.rsplit(['/', '\\']).next().unwrap_or(shell); + let stem = file.rsplit_once('.').map_or(file, |(stem, _)| stem); + matches!(stem.to_ascii_lowercase().as_str(), "pwsh" | "powershell") +} + impl Terminals { /// Requires a tokio runtime (spawns the exited-session reaper). pub fn new() -> Self { @@ -1085,6 +1123,50 @@ mod windows_tests { }); } + /// An engine the app started ignores Ctrl+C (its own process group), as + /// this test makes itself: Ctrl+C in its terminal still interrupts what + /// the shell runs. + #[test] + fn ctrl_c_interrupts_a_program_though_the_engine_ignores_it() { + use windows_sys::Win32::System::Console::SetConsoleCtrlHandler; + // SAFETY: a null handler with TRUE sets this process's ignore flag, + // as CREATE_NEW_PROCESS_GROUP does for a detached engine. + unsafe { SetConsoleCtrlHandler(None, 1) }; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + runtime.block_on(async { + let tmp = tempfile::tempdir().unwrap(); + let terminals = Terminals::new(); + let terminal = terminals + .open_with_shell( + tmp.path().to_str().unwrap(), + 80, + 24, + Some(powershell().to_str().unwrap()), + ) + .unwrap(); + wait_for_shell_prompt(&terminals, &terminal.id).await; + let mut rx = terminals.subscribe(&terminal.id, None).unwrap(); + let mut events = Vec::new(); + write_line(&terminals, &terminal.id, "ping -t localhost"); + collect_until(&mut rx, &mut events, |events| { + decoded(events).contains("Reply from") + }) + .await; + terminals + .write(&terminal.id, &BASE64.encode("\u{3}")) + .unwrap(); + // Interrupted, ping sums up what it sent; left running, it never does. + collect_until(&mut rx, &mut events, |events| { + decoded(events).contains("Ping statistics") + }) + .await; + terminals.close(&terminal.id).unwrap(); + }); + } + fn powershell() -> PathBuf { let path = PathBuf::from(std::env::var_os("SystemRoot").expect("SystemRoot is set")) .join("System32") @@ -1431,6 +1513,69 @@ mod windows_tests { } } +#[cfg(test)] +mod windows_shell_tests { + use super::{is_powershell, windows_shell}; + use std::ffi::OsString; + use std::path::{Path, PathBuf}; + + const ROOT: &str = "root"; + + fn env(path: &[&str], comspec: Option<&str>) -> impl Fn(&str) -> Option { + let path = std::env::join_paths(path.iter().map(PathBuf::from)).unwrap(); + let comspec = comspec.map(OsString::from); + move |name| match name { + "PATH" => Some(path.clone()), + "SystemRoot" => Some(ROOT.into()), + "COMSPEC" => comspec.clone(), + _ => None, + } + } + + fn windows_powershell() -> PathBuf { + Path::new(ROOT) + .join("System32") + .join("WindowsPowerShell") + .join("v1.0") + .join("powershell.exe") + } + + #[test] + fn powershell_7_on_path_comes_first() { + let pwsh = Path::new("pwsh7").join("pwsh.exe"); + let shell = windows_shell(env(&["other", "pwsh7"], Some("cmd.exe")), |p| { + p == pwsh || p == windows_powershell() + }); + assert_eq!(shell, pwsh.to_string_lossy()); + } + + #[test] + fn windows_powershell_without_powershell_7() { + let shell = windows_shell(env(&["other"], Some("cmd.exe")), |p| { + p == windows_powershell() + }); + assert_eq!(shell, windows_powershell().to_string_lossy()); + } + + #[test] + fn comspec_when_there_is_no_powershell() { + assert_eq!( + windows_shell(env(&["other"], Some("C:\\cmd.exe")), |_| false), + "C:\\cmd.exe" + ); + assert_eq!(windows_shell(env(&[], None), |_| false), "cmd.exe"); + } + + #[test] + fn powershell_is_told_no_logo() { + assert!(is_powershell(r"C:\Program Files\PowerShell\7\pwsh.exe")); + assert!(is_powershell("powershell.exe")); + assert!(is_powershell("PWSH")); + assert!(!is_powershell(r"C:\WINDOWS\system32\cmd.exe")); + assert!(!is_powershell("/bin/zsh")); + } +} + #[cfg(all(test, unix))] mod initial_command_tests { use super::*; diff --git a/crates/engine/src/terminals/windows.rs b/crates/engine/src/terminals/windows.rs index 21e387128..649b6cf2f 100644 --- a/crates/engine/src/terminals/windows.rs +++ b/crates/engine/src/terminals/windows.rs @@ -12,6 +12,7 @@ use portable_pty::{Child, ChildKiller, CommandBuilder, ExitStatus, MasterPty, Pt use windows_sys::Win32::Foundation::{INVALID_HANDLE_VALUE, WAIT_OBJECT_0, WAIT_TIMEOUT}; use windows_sys::Win32::System::Console::{ COORD, ClosePseudoConsole, CreatePseudoConsole, HPCON, ResizePseudoConsole, + SetConsoleCtrlHandler, }; use windows_sys::Win32::System::Pipes::CreatePipe; use windows_sys::Win32::System::Threading::{ @@ -386,7 +387,12 @@ pub(super) fn open( let executable = wide(executable.as_os_str())?; let mut command = vec![b'"' as u16]; command.extend_from_slice(&executable[..executable.len() - 1]); - command.extend([b'"' as u16, 0]); + command.push(b'"' as u16); + // PowerShell's prompt alone, as cmd's: no banner on every tab. + if super::is_powershell(shell) { + command.extend(" -NoLogo".encode_utf16()); + } + command.push(0); let cwd = wide(OsStr::new(&plain_current_dir(cwd)?))?; let mut environment = std::collections::BTreeMap::new(); let env_key = |key: &OsStr| -> OsString { @@ -448,6 +454,15 @@ pub(super) fn open( startup.StartupInfo.hStdError = INVALID_HANDLE_VALUE; startup.lpAttributeList = attrs.ptr(); let mut info = PROCESS_INFORMATION::default(); + // The app starts the engine in a process group of its own (crates/launch + // `spawn_detached`, CREATE_NEW_PROCESS_GROUP), which ignores Ctrl+C, and + // a process inherits that from the one creating it: the shell, and what + // it runs, ignored it too, so Ctrl+C in a terminal tab reached the shell as + // a key and never interrupted `ping -t`. Normal handling is put back first, + // as any process started otherwise has it; the engine has no console of + // its own for a Ctrl+C to come from. + // SAFETY: a null handler with FALSE only clears this process's flag. + unsafe { SetConsoleCtrlHandler(None, 0) }; // SAFETY: all buffers and the initialized attribute list remain alive through // CreateProcessW. Job membership is established as part of creation, even // if the owner exits before this call returns. Suspension is only for the diff --git a/crates/engine/src/uploads.rs b/crates/engine/src/uploads.rs index 311c3cde7..19664a7c6 100644 --- a/crates/engine/src/uploads.rs +++ b/crates/engine/src/uploads.rs @@ -81,6 +81,38 @@ pub fn pending_refs_in(text: &str) -> Vec { }) .collect() } +/// Every path listed on a text's attachment-ref lines (`- …`), refs or not. +pub fn attachment_lines_in(text: &str) -> Vec { + let Some(at) = text.find("Attached images (local files") else { + return Vec::new(); + }; + text[at..] + .lines() + .skip(1) + .filter_map(|line| { + let path = line.trim_start().strip_prefix("- ")?.trim(); + (!path.is_empty()).then(|| path.to_string()) + }) + .collect() +} + +/// The last component of `path` in either separator: a path made on another +/// device keeps its own (`C:\Users\…\x.png` read on macOS, or the reverse). +fn foreign_file_name(path: &str) -> &str { + path.rsplit(['/', '\\']).next().unwrap_or(path) +} + +/// Whether `name` is a committed upload's (`{id8}-{sanitized name}`). +fn is_upload_name(name: &str) -> bool { + let Some((id8, rest)) = name.split_once('-') else { + return false; + }; + id8.len() == 8 + && id8.chars().all(|c| c.is_ascii_alphanumeric()) + && !rest.is_empty() + && sanitize(name) == name +} + /// Hard cap on an assembled file. const MAX_BYTES: u64 = 32 * 1024 * 1024; /// Multiple of 3 so independent base64 chunks concatenate losslessly. @@ -234,6 +266,42 @@ impl Uploads { .join(format!("{id8}-{}", sanitize(file_name))) } + /// This device's own copy of an upload named by a path made elsewhere: + /// another device's or another OS user's uploads dir (its absolute path + /// means nothing here), whose bytes were also committed here under the + /// same deterministic `{id8}-{name}`. `None` when `path` is readable as it + /// is, isn't an upload's, or this device has no such file. + pub fn local_copy(&self, path: &str) -> Option { + if is_pending_ref(path) || Path::new(path).is_file() { + return None; + } + let name = foreign_file_name(path); + if !is_upload_name(name) { + return None; + } + let read_roots = self + .inner + .read_only_roots + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone(); + std::iter::once(self.inner.dir.clone()) + .chain(read_roots) + .map(|root| root.join(name)) + .find(|candidate| candidate.is_file()) + .map(|found| found.to_string_lossy().to_string()) + } + + /// A path the agent can open on THIS device: a landed `pending://` ref's + /// file, this device's copy of an upload named by another's path, else + /// the path as given. + pub fn localize(&self, path: &str) -> Option { + if is_pending_ref(path) { + return self.resolve_pending(path); + } + self.local_copy(path) + } + /// Resolve a `pending://` ref against this device's uploads dir. /// `Some(absolute)` iff the bytes have landed here. pub fn resolve_pending(&self, path: &str) -> Option { @@ -329,9 +397,14 @@ impl Uploads { // Queued-attachment refs resolve against this device's uploads dir // (present only once the transfer landed) — then jail as usual. let resolved_ref; + // (So does an upload named by another device's or user's path, by + // this device's copy of it.) let path = if is_pending_ref(path) { resolved_ref = self.resolve_pending(path).ok_or_else(outside)?; resolved_ref.as_str() + } else if let Some(local) = self.local_copy(path) { + resolved_ref = local; + resolved_ref.as_str() } else { path }; @@ -693,12 +766,17 @@ mod tests { ("sky.hdr".to_owned(), b"hdr".to_vec()), ]; uploads.store_visual_assets("v:abc", &assets).unwrap(); - let script = uploads.store_visual("v:abc", "return ui.text 'hi'").unwrap(); + let script = uploads + .store_visual("v:abc", "return ui.text 'hi'") + .unwrap(); let stem = script.strip_suffix("-visual.luau").unwrap(); let names: Vec = serde_json::from_slice(&std::fs::read(format!("{stem}-assets.json")).unwrap()).unwrap(); assert_eq!(names, ["prism.glb", "sky.hdr"]); - assert_eq!(std::fs::read(format!("{stem}-asset-sky.hdr")).unwrap(), b"hdr"); + assert_eq!( + std::fs::read(format!("{stem}-asset-sky.hdr")).unwrap(), + b"hdr" + ); uploads.remove_visual("v:abc"); assert_eq!(std::fs::read_dir(uploads.dir()).unwrap().count(), 0); } @@ -829,6 +907,78 @@ mod tests { assert_eq!(uploads.resolve_pending(&r), Some(committed)); } + /// One upload committed here, as `{id8}-image.png`. + fn committed_here(uploads: &Uploads) -> String { + uploads + .append( + "2fbd2b3b-9c1e", + &BASE64.encode(b"\x89PNG\r\n\x1a\n"), + Some(0), + ) + .unwrap(); + uploads.commit("2fbd2b3b-9c1e", "image.png").unwrap() + } + + #[test] + fn another_users_windows_path_finds_this_devices_copy() { + let dir = tempfile::tempdir().unwrap(); + let uploads = Uploads::new(dir.path()); + let here = committed_here(&uploads); + let theirs = r"C:\Users\ADMIN\AppData\Local\Zeron\uploads\2fbd2b3b-image.png"; + assert_eq!(uploads.local_copy(theirs), Some(here.clone())); + assert_eq!(uploads.localize(theirs), Some(here.clone())); + // Forward slashes too (another Mac's, or a Windows path written so). + let other = "/Users/someone/.zeron/uploads/2fbd2b3b-image.png"; + assert_eq!(uploads.local_copy(other), Some(here.clone())); + let mixed = "C:/Users/ADMIN/AppData/Local/Zeron/uploads/2fbd2b3b-image.png"; + assert_eq!(uploads.local_copy(mixed), Some(here)); + } + + #[test] + fn a_path_that_reads_here_or_isnt_an_upload_is_left_alone() { + let dir = tempfile::tempdir().unwrap(); + let uploads = Uploads::new(dir.path()); + let here = committed_here(&uploads); + assert_eq!(uploads.local_copy(&here), None, "already this device's"); + assert_eq!( + uploads.local_copy(r"C:\Users\ADMIN\Pictures\image.png"), + None + ); + assert_eq!( + uploads.local_copy(r"C:\Users\ADMIN\uploads\0badf00d-image.png"), + None + ); + assert_eq!( + uploads.local_copy(r"C:\Users\ADMIN\uploads\2fbd2b3b-image (1).png"), + None + ); + assert_eq!(uploads.local_copy(r"C:\x\..\2fbd2b3b-image.png\.."), None); + } + + #[test] + fn another_users_path_reads_back_from_this_devices_copy() { + let dir = tempfile::tempdir().unwrap(); + let uploads = Uploads::new(dir.path()); + committed_here(&uploads); + let theirs = r"C:\Users\ADMIN\AppData\Local\Zeron\uploads\2fbd2b3b-image.png"; + let chunk = uploads.read_chunk(theirs, 0, &[]).unwrap(); + assert_eq!(chunk.name, "2fbd2b3b-image.png"); + assert_eq!(BASE64.decode(chunk.data).unwrap(), b"\x89PNG\r\n\x1a\n"); + } + + #[test] + fn attachment_lines_are_every_listed_path() { + let text = "Look\n\nAttached images (local files — open them to view):\n- C:\\Users\\ADMIN\\uploads\\2fbd2b3b-image.png\n- pending://u2/c.png"; + assert_eq!( + attachment_lines_in(text), + vec![ + "C:\\Users\\ADMIN\\uploads\\2fbd2b3b-image.png".to_string(), + "pending://u2/c.png".to_string() + ] + ); + assert!(attachment_lines_in("- a list item with no trailer").is_empty()); + } + #[test] fn pending_refs_in_scans_ref_lines_only() { let text = "See the attached image(s).\n\nAttached images (local files — open them to view):\n- pending://u1/a b.png\n- /abs/other.png\n- pending://u2/c.png"; @@ -1304,7 +1454,11 @@ impl Uploads { /// Store the files a visual's script uses, beside it: each as /// `{id}-asset-{name}`, and `{id}-assets.json` listing their names /// (clients find it from the script's path). - pub fn store_visual_assets(&self, id: &str, assets: &[(String, Vec)]) -> Result<(), EngineError> { + pub fn store_visual_assets( + &self, + id: &str, + assets: &[(String, Vec)], + ) -> Result<(), EngineError> { use std::io::Write; if assets.is_empty() { return Ok(()); @@ -1330,7 +1484,8 @@ impl Uploads { written.push(file); names.push(name); } - let manifest = serde_json::to_vec(&names).map_err(|err| EngineError::Other(err.to_string()))?; + let manifest = + serde_json::to_vec(&names).map_err(|err| EngineError::Other(err.to_string()))?; write(&format!("{id}-assets.json"), &manifest) })(); if stored.is_err() { @@ -1351,7 +1506,9 @@ impl Uploads { .and_then(|bytes| serde_json::from_slice::>(&bytes).ok()) { for name in names { - let _ = std::fs::remove_file(self.dir().join(format!("{id}-asset-{}", sanitize(&name)))); + let _ = std::fs::remove_file( + self.dir().join(format!("{id}-asset-{}", sanitize(&name))), + ); } } let _ = std::fs::remove_file(manifest); diff --git a/crates/engine/src/workspace_host.rs b/crates/engine/src/workspace_host.rs index 4be24f5dd..5109b0a87 100644 --- a/crates/engine/src/workspace_host.rs +++ b/crates/engine/src/workspace_host.rs @@ -71,6 +71,24 @@ const PRESENCE_FRESH_MS: i64 = 45_000; /// run for devices whose heartbeat is stale, so the steady state (healthy /// room, fresh beats) sends no extra traffic. const RELAY_PROBE_INTERVAL_MS: u64 = 30_000; +/// How often to ask the relay about a device last heard from `quiet_ms` ago. +/// A device that just went quiet is most likely a starved heartbeat (what the +/// probe exists to catch), so it's asked every [`RELAY_PROBE_INTERVAL_MS`]; one +/// gone for hours or days (a closed laptop, a Cloud machine asleep) is +/// genuinely offline, and asking every 30 s, for each such device on the +/// account, was most of a signed-in engine's idle network work. Its coming +/// back is heard from its own heartbeat and boot stamp, not from this probe. +fn relay_probe_every(quiet_ms: i64) -> std::time::Duration { + const MINUTE: i64 = 60_000; + let secs = match quiet_ms { + ms if ms < 10 * MINUTE => RELAY_PROBE_INTERVAL_MS / 1000, + ms if ms < 60 * MINUTE => 120, + ms if ms < 24 * 60 * MINUTE => 300, + _ => 600, + }; + std::time::Duration::from_secs(secs) +} + /// Per-request timeout for a relay-status probe. const RELAY_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5); /// Debounce window for local snapshot saves after a change. @@ -1761,6 +1779,8 @@ async fn relay_probe_task(weak: Weak) { tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); tick.tick().await; // consume the immediate first tick let client = reqwest::Client::new(); + // When each device was last probed (epoch ms). + let mut probed: std::collections::HashMap = std::collections::HashMap::new(); loop { tick.tick().await; let Some(inner) = weak.upgrade() else { return }; @@ -1774,16 +1794,32 @@ async fn relay_probe_task(weak: Weak) { continue; }; let seen = lock(&inner.presence_seen); + // (Deleted devices aren't listed: a retired Cloud machine is never asked.) + probed.retain(|id, _| devices.iter().any(|d| &d.id == id)); devices .into_iter() .filter(|d| d.id != self_id) .filter(|d| { - seen.get(&d.id) - .is_none_or(|ms| now.saturating_sub(*ms) >= PRESENCE_FRESH_MS) + let heard = seen + .get(&d.id) + .copied() + .into_iter() + .chain(d.last_seen_at.map(|at| at.timestamp_millis())) + .max(); + if heard.is_some_and(|ms| now.saturating_sub(ms) < PRESENCE_FRESH_MS) { + return false; + } + let quiet = heard.map_or(i64::MAX, |ms| now.saturating_sub(ms)); + probed.get(&d.id).is_none_or(|at| { + now.saturating_sub(*at) >= relay_probe_every(quiet).as_millis() as i64 + }) }) .map(|d| d.id) .collect() }; + for id in &stale { + probed.insert(id.clone(), now); + } drop(inner); if stale.is_empty() { continue; @@ -1833,6 +1869,11 @@ async fn relay_probe_task(weak: Weak) { /// and refreshes presence every [`PRESENCE_INTERVAL_MS`]. Holds only a weak /// handle so a dropped host tears the task down. async fn workspace_task(weak: Weak, mut changed_rx: watch::Receiver) { + // Presence is other devices' and ours to them, through the edge: a + // local profile (no edge, this device alone) has none to refresh. + let synced = weak + .upgrade() + .is_some_and(|inner| inner.config.edge.is_some()); let mut presence = tokio::time::interval(std::time::Duration::from_millis(PRESENCE_INTERVAL_MS)); presence.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); @@ -1861,7 +1902,7 @@ async fn workspace_task(weak: Weak, mut changed_rx: watch::R tracing::warn!(%error, "registry snapshot worker failed"); } } - _ = presence.tick() => { + _ = presence.tick(), if synced => { let Some(inner) = weak.upgrade() else { break }; inner.presence_tick(); // Re-publish on the same cadence: remote heartbeats decay when a @@ -2043,7 +2084,18 @@ fn validate_lifecycle_change( #[cfg(test)] mod tests { - use super::{device_name_on_boot, linked_worktree_root}; + + #[test] + fn relay_probes_slow_down_with_how_long_a_device_has_been_gone() { + let minute = 60_000; + assert_eq!(relay_probe_every(0).as_secs(), 30); + assert_eq!(relay_probe_every(9 * minute).as_secs(), 30); + assert_eq!(relay_probe_every(30 * minute).as_secs(), 120); + assert_eq!(relay_probe_every(5 * 60 * minute).as_secs(), 300); + assert_eq!(relay_probe_every(3 * 24 * 60 * minute).as_secs(), 600); + assert_eq!(relay_probe_every(i64::MAX).as_secs(), 600, "never heard from"); + } + use super::{device_name_on_boot, linked_worktree_root, relay_probe_every}; #[tokio::test] async fn registry_http_sync_retains_dns_cause() { diff --git a/crates/engine/src/workspace_search.rs b/crates/engine/src/workspace_search.rs index 25db7bf10..b607a3311 100644 --- a/crates/engine/src/workspace_search.rs +++ b/crates/engine/src/workspace_search.rs @@ -17,7 +17,6 @@ use std::borrow::Cow; use std::collections::HashMap; use std::path::{Path, PathBuf}; -use std::sync::atomic::AtomicBool; use std::sync::{Arc, Condvar, Mutex, Weak}; use std::time::{Duration, Instant}; @@ -153,7 +152,9 @@ struct Entry { struct HomeEntry { index: Option>, /// A walk is running; `cancel` stops it when the index is dropped. - building: Option>, + building: Option>, + /// The running walk reads the protected folders too. + building_protected: bool, last_used: Option, warmed: bool, } @@ -189,7 +190,9 @@ impl WorkspaceSearch { /// Start (or keep alive) the index for a chat's `root`. pub fn warm(&self, root: &Path) -> Result { if self.is_home(root) { - return Ok(match self.home_index(root, true, Duration::ZERO) { + // (Warming asks for no protected folder: opening a chat in home + // asks nobody for access; a search there does.) + return Ok(match self.home_index(root, true, Duration::ZERO, false) { Some(_) => IndexState::Ready, None => IndexState::Building, }); @@ -226,13 +229,19 @@ impl WorkspaceSearch { wait: Duration, ) -> Result { if self.is_home(root) { - let index = self.home_index(root, false, wait); + // Someone searching: the protected folders are read for it + // (`HomeIndex::build_for`); an index without them answers + // meanwhile, flagged as still indexing. + let protected = !query.trim().is_empty(); + let index = self.home_index(root, false, wait, protected); return Ok(NameSearch { matches: index .as_ref() .map(|index| index.search(query, limit, kinds)) .unwrap_or_default(), - indexing: index.is_none(), + indexing: index + .as_ref() + .is_none_or(|index| protected && !index.protected), }); } let query = normalize_name_query(query); @@ -457,36 +466,55 @@ impl WorkspaceSearch { /// Home's index, walking it in the background when missing or stale; /// waits up to `wait` for a first walk. `warm`: a chat is asking. - fn home_index(&self, root: &Path, warm: bool, wait: Duration) -> Option> { + /// `protected`: the walk is to read the protected folders too + /// (`HomeIndex::build_for`): someone is searching. + fn home_index( + &self, + root: &Path, + warm: bool, + wait: Duration, + protected: bool, + ) -> Option> { self.start_reaper(); let now = (self.inner.clock)(); let mut home = lock(&self.inner.home_index); home.last_used = Some(now); home.warmed |= warm; + let short = |index: &HomeIndex| protected && !index.protected; let stale = home .index .as_ref() - .is_none_or(|index| index.built.elapsed() >= HOME_REFRESH); - if stale && home.building.is_none() { - let cancel = Arc::new(AtomicBool::new(false)); + .is_none_or(|index| index.built.elapsed() >= HOME_REFRESH || short(index)); + // (A walk without them, under way, gives way to one with them.) + let walking_short = home.building.is_some() && protected && !home.building_protected; + if stale && (home.building.is_none() || walking_short) { + if let Some(cancel) = home.building.take() { + cancel.cancel(); + } + // (A refresh keeps what the index read: once someone searched, + // the protected folders stay in it.) + let protected = protected || home.index.as_ref().is_some_and(|index| index.protected); + let cancel = Arc::new(crate::home_index::WalkCancel::default()); home.building = Some(cancel.clone()); + home.building_protected = protected; let inner = Arc::downgrade(&self.inner); let root = root.to_path_buf(); let spawned = std::thread::Builder::new() .name("workspace-search-home".into()) - .spawn(move || build_home(inner, root, cancel)); + .spawn(move || build_home(inner, root, cancel, protected)); if let Err(error) = spawned { home.building = None; tracing::warn!(%error, "home search index did not start"); } } - if home.index.is_none() && home.building.is_some() && !wait.is_zero() { + let waiting = |home: &HomeEntry| { + home.building.is_some() && home.index.as_deref().is_none_or(|index| short(index)) + }; + if waiting(&home) && !wait.is_zero() { home = self .inner .home_built - .wait_timeout_while(home, wait, |home| { - home.index.is_none() && home.building.is_some() - }) + .wait_timeout_while(home, wait, |home| waiting(home)) .unwrap_or_else(std::sync::PoisonError::into_inner) .0; } @@ -500,7 +528,7 @@ impl WorkspaceSearch { return false; } if let Some(cancel) = home.building.take() { - cancel.store(true, std::sync::atomic::Ordering::Relaxed); + cancel.cancel(); } *home = HomeEntry::default(); self.inner.home_built.notify_all(); @@ -557,9 +585,14 @@ impl WorkspaceSearch { } } -fn build_home(inner: Weak, root: PathBuf, cancel: Arc) { +fn build_home( + inner: Weak, + root: PathBuf, + cancel: Arc, + protected: bool, +) { let started = Instant::now(); - let index = HomeIndex::build(&root, &cancel); + let index = HomeIndex::build_for(&root, &cancel, protected); let Some(inner) = inner.upgrade() else { return; }; @@ -575,6 +608,7 @@ fn build_home(inner: Weak, root: PathBuf, cancel: Arc) { tracing::info!( root = %root.display(), entries = index.len(), + protected = index.protected, scan_ms = started.elapsed().as_millis() as u64, "workspace search home index scanned" ); @@ -992,6 +1026,55 @@ mod tests { assert_eq!(search.live(), 0); } + /// Opening New project (an empty query) and a chat in home (a warm) + /// read no protected folder; the first search does, and answers as still + /// indexing until it has; later refreshes keep them. + #[cfg(target_os = "macos")] + #[test] + fn home_reads_the_protected_folders_only_once_someone_searches() { + let (_dir, home) = folder(&[ + ("dev/plan.md", b""), + ("Documents/proj/plan.md", b""), + ("Music/plan.md", b""), + ]); + let search = WorkspaceSearch::with_clock(Arc::new(Instant::now), false, Some(home.clone())); + let paths = |found: &NameSearch| -> Vec { + found.matches.iter().map(|m| m.path.clone()).collect() + }; + // The picker opening: an empty query, no protected folder read. + search.warm(&home).unwrap(); + let opened = search + .search_names_within(&home, "", 20, NameKinds::Directories, NAME_SCAN_WAIT) + .unwrap(); + assert!(!opened.indexing); + assert!( + !lock(&search.inner.home_index) + .index + .as_ref() + .is_some_and(|index| index.protected) + ); + // A search: the protected folders are read (never Music). + let deadline = Instant::now() + Duration::from_secs(5); + let found = loop { + let found = search + .search_names_within(&home, "plan", 20, NameKinds::Files, NAME_SCAN_WAIT) + .unwrap(); + if !found.indexing { + break found; + } + assert!(Instant::now() < deadline, "the search's walk finished"); + }; + assert_eq!(paths(&found), ["dev/plan.md", "Documents/proj/plan.md"]); + // A warm after it keeps what the index read. + search.warm(&home).unwrap(); + assert!( + lock(&search.inner.home_index) + .index + .as_ref() + .is_some_and(|index| index.protected) + ); + } + #[test] fn content_search_rejects_blank_queries_without_searching() { let (_dir, root) = folder(&[("notes.md", b" \n")]); diff --git a/crates/engine/tests/device_routing.rs b/crates/engine/tests/device_routing.rs index bac5c5179..3b9e6cfcd 100644 --- a/crates/engine/tests/device_routing.rs +++ b/crates/engine/tests/device_routing.rs @@ -24,7 +24,7 @@ use tokio_tungstenite::tungstenite::handshake::server::{ Request as WsRequest, Response as WsResponse, }; -use zeron_doc::SessionCommandPayload; +use zeron_doc::{SessionCommandEntry, SessionCommandPayload, SessionCommandStatus}; use zeron_engine::{ BranchHeadContext, ChangeRequestError, CheckoutChangeRequestLookup, CheckoutChangeRequests, CheckoutSourceContext, EngineCore, HarnessRegistry, @@ -1873,6 +1873,273 @@ async fn remote_target_without_links_fails_clearly() { core.shutdown().await; } +/// A screenshot alone, sent from another device while the host's turn runs: +/// its bytes go up to the host through the relay, then that device's own +/// engine writes the queue row (`QueueMessage` isn't routed, the row syncs). +/// It used to refuse there, the files already on the host, and the app said +/// "Your message didn't send". +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn files_with_no_words_queued_on_another_device_reach_the_host() { + const CHAT: &str = "chat-files-alone"; + let (relay_url, _relay) = fake_device_room().await; + let dirs = tempfile::tempdir().expect("tempdir"); + let core_b = assemble(&dirs.path().join("b"), "device-b"); + let core_a = assemble(&dirs.path().join("a"), "device-a"); + for core in [&core_a, &core_b] { + core.workspace + .create_chat(CHAT, None, Some("device-b"), None, None) + .expect("create chat"); + core.workspace + .rename_chat(CHAT, "Pre-titled") + .expect("avoid auto-title run"); + } + let _host = core_b.start_host_relay(&relay_url); + let mut link_config = + LinkCacheConfig::new(relay_url, Arc::new(StaticToken("test-user".into()))); + link_config.probe_timeout = Duration::from_secs(5); + core_a.set_links(LinkCache::new(link_config)); + let client = zeron_rpc::memory_client(core_a.rpc_service()); + + // The bytes, up to the host through the relay, as the app's `upload`. + let deadline = tokio::time::Instant::now() + Duration::from_secs(15); + loop { + let sent = client + .call( + methods::UPLOAD_CHUNK, + serde_json::json!({ + "uploadId": "up-1", + "seq": 0, + "data": BASE64.encode(b"\x89PNG\r\n\x1a\n"), + "targetDeviceId": "device-b", + }), + ) + .await; + match sent { + Ok(_) => break, + Err(error) => { + assert!( + tokio::time::Instant::now() < deadline, + "relay never came up: {error}" + ); + tokio::time::sleep(Duration::from_millis(200)).await; + } + } + } + let committed = client + .call( + methods::UPLOAD_COMMIT, + serde_json::json!({ + "uploadId": "up-1", + "fileName": "shot.png", + "targetDeviceId": "device-b", + }), + ) + .await + .expect("the upload lands on the host"); + let on_host = committed["path"] + .as_str() + .expect("its path there") + .to_owned(); + + // Then the row, on this device's engine: the call that said no. + client + .call( + methods::QUEUE_MESSAGE, + serde_json::json!({ + "chatId": CHAT, + "text": "", + "attachments": [on_host.clone()], + "holdForTurnEnd": true, + }), + ) + .await + .expect("files with no words are queued"); + + // The row as it syncs to the host (no edge here: put there by hand). + let rows = core_a + .doc_host + .open(CHAT) + .expect("A chat") + .doc() + .read_queue() + .expect("A queue"); + assert_eq!(rows.len(), 1, "the row survives being read back"); + let on_b = core_b.doc_host.open(CHAT).expect("B chat"); + on_b.doc().push_queued(&rows[0]).expect("row reaches B"); + + // Sent from here, or by the host's own drain, which may have it first: + // what counts is what the host then runs. + client + .call( + methods::SEND_QUEUED_MESSAGE_NOW, + serde_json::json!({ + "chatId": CHAT, + "id": rows[0].id, + "targetDeviceId": "device-b", + }), + ) + .await + .expect("send-now reaches B"); + let deadline = tokio::time::Instant::now() + Duration::from_secs(10); + loop { + let prompt = on_b + .doc() + .read_entries() + .expect("B transcript") + .into_iter() + .find(|e| e.role == zeron_doc::MessageRole::User) + .map(|e| format!("{:?}", e.parts)); + if let Some(prompt) = prompt { + assert!( + prompt.contains("See the attached image(s)."), + "got: {prompt}" + ); + assert!(prompt.contains(&on_host), "got: {prompt}"); + break; + } + assert!(tokio::time::Instant::now() < deadline, "B never sent it"); + tokio::time::sleep(Duration::from_millis(50)).await; + } + core_a.shutdown().await; + core_b.shutdown().await; +} + +/// A run sent from another device (or another Windows user's engine on the +/// same PC) names its picture by the sender's own uploads path. Its bytes +/// went to the host too, under the same upload id: the host's agent must get +/// the host's copy, never `C:\Users\ADMIN\…` from a chat running as another +/// user (2026-11-07, "the AI can't read the attached images"). +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_run_from_another_device_names_the_hosts_copy_of_its_upload() { + const CHAT: &str = "chat-foreign-path"; + const THEIRS: &str = r"C:\Users\ADMIN\AppData\Local\Zeron\uploads\2fbd2b3b-image.png"; + let (relay_url, _relay) = fake_device_room().await; + let dirs = tempfile::tempdir().expect("tempdir"); + let core_b = assemble(&dirs.path().join("b"), "device-b"); + let core_a = assemble(&dirs.path().join("a"), "device-a"); + for core in [&core_a, &core_b] { + core.workspace + .create_chat(CHAT, None, Some("device-b"), None, None) + .expect("create chat"); + core.workspace + .rename_chat(CHAT, "Pre-titled") + .expect("avoid auto-title run"); + } + let _host = core_b.start_host_relay(&relay_url); + let mut link_config = + LinkCacheConfig::new(relay_url, Arc::new(StaticToken("test-user".into()))); + link_config.probe_timeout = Duration::from_secs(5); + core_a.set_links(LinkCache::new(link_config)); + let client = zeron_rpc::memory_client(core_a.rpc_service()); + + // The bytes reach the host through the relay. + let deadline = tokio::time::Instant::now() + Duration::from_secs(15); + loop { + let sent = client + .call( + methods::UPLOAD_CHUNK, + serde_json::json!({ + "uploadId": "2fbd2b3b-9c1e", + "seq": 0, + "data": BASE64.encode(b"\x89PNG\r\n\x1a\n"), + "targetDeviceId": "device-b", + }), + ) + .await; + match sent { + Ok(_) => break, + Err(error) => { + assert!( + tokio::time::Instant::now() < deadline, + "relay never came up: {error}" + ); + tokio::time::sleep(Duration::from_millis(200)).await; + } + } + } + let committed = client + .call( + methods::UPLOAD_COMMIT, + serde_json::json!({ + "uploadId": "2fbd2b3b-9c1e", + "fileName": "image.png", + "targetDeviceId": "device-b", + }), + ) + .await + .expect("the upload lands on the host"); + let on_host = committed["path"] + .as_str() + .expect("its path there") + .to_owned(); + + // The run, as the sender wrote it, arrives over the relay. + let prompt = format!( + "Can u double check this?\n\nAttached images (local files — open them to view):\n- {THEIRS}" + ); + let entry = SessionCommandEntry { + id: "cmd-foreign-1".into(), + payload: SessionCommandPayload::Run { + request: RunRequest { + instance: None, + mcp: None, + prompt, + harness: None, + model: None, + reasoning: None, + model_options: serde_json::Map::new(), + cwd: "~".into(), + sandbox: SandboxLevel::WorkspaceWrite, + auto_approve: true, + access: Default::default(), + attachments: vec![THEIRS.into()], + worktree: None, + resume: None, + env: Default::default(), + }, + message_id: "m-foreign-1".into(), + }, + issued_by: "device-a".into(), + issued_at: chrono::Utc::now().timestamp_millis(), + based_on: None, + expires_at: None, + status: SessionCommandStatus::Pending, + resolution: None, + }; + core_b + .doc_host + .ingest_relayed_command(CHAT, entry) + .await + .expect("B takes the relayed run"); + + let on_b = core_b.doc_host.open(CHAT).expect("B chat"); + let deadline = tokio::time::Instant::now() + Duration::from_secs(10); + let said = loop { + let user = on_b + .doc() + .read_entries() + .expect("B transcript") + .into_iter() + .find(|e| e.id == "m-foreign-1") + .map(|e| format!("{:?}", e.parts)); + if let Some(said) = user { + break said; + } + assert!(tokio::time::Instant::now() < deadline, "B never ran it"); + tokio::time::sleep(Duration::from_millis(50)).await; + }; + assert!( + said.contains(&on_host.replace('\\', "\\\\")) || said.contains(&on_host), + "got: {said}" + ); + assert!( + !said.contains("ADMIN"), + "the sender's path reached the agent: {said}" + ); + core_a.shutdown().await; + core_b.shutdown().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn queue_watch_and_single_consumption_route_to_the_remote_chat_host() { let (relay_url, _relay) = fake_device_room().await; diff --git a/crates/engine/tests/e2e.rs b/crates/engine/tests/e2e.rs index 543019bca..9dc64da44 100644 --- a/crates/engine/tests/e2e.rs +++ b/crates/engine/tests/e2e.rs @@ -1326,6 +1326,8 @@ async fn recover_stale_journal_settles_chips_in_completed_local_entries() { }, ) .unwrap(); + // Written out before the engine opens its own journal: appends batch. + drop(journal); let doc = SessionDoc::init(CHAT).unwrap(); for (id, device) in [("local", device_id), ("remote", "other-device")] { doc.push_message(&SessionMessageEntry { diff --git a/crates/engine/tests/launch_agents.rs b/crates/engine/tests/launch_agents.rs new file mode 100644 index 000000000..d0d5c7f81 --- /dev/null +++ b/crates/engine/tests/launch_agents.rs @@ -0,0 +1,286 @@ +//! An engine that starts over chats whose agents were parked idle starts no +//! agent for them: each is resumed when its next message comes (ademark A5, +//! "seeded state, just launched, no agent running"). Only a turn that was +//! cut off mid-way is real work, and that one is picked back up. +//! +//! The harness is a persistent agent per `run()` (a spawn): it answers a +//! prompt and stays up, parked, for the next one; a prompt with `hold` stays +//! in flight. + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use async_trait::async_trait; +use futures::StreamExt; +use futures::stream::BoxStream; +use tokio::sync::mpsc; + +use zeron_engine::{EngineCore, HarnessRegistry}; +use zeron_harness::{Harness, HarnessError, RunControls}; +use zeron_proto::{ + AgentEvent, DoneStatus, HarnessId, Model, ReasoningLevel, RunRequest, SandboxLevel, + SessionStatus, SteeringMode, +}; + +#[derive(Default)] +struct Ledger { + spawns: AtomicUsize, + /// Each spawn: its chat's first prompt and its `resume`. + runs: Mutex)>>, +} + +struct Agent { + ledger: Arc, +} + +fn done() -> AgentEvent { + AgentEvent::Done { + status: DoneStatus::Completed, + result: None, + error: None, + session_id: Some("provider-session".into()), + } +} + +#[async_trait] +impl Harness for Agent { + fn id(&self) -> HarnessId { + HarnessId::Mock + } + fn display_name(&self) -> &str { + "Agent" + } + fn supports_steering(&self) -> bool { + true + } + fn steering_mode(&self) -> SteeringMode { + SteeringMode::StepBoundary + } + fn reasoning_levels(&self) -> &[ReasoningLevel] { + &[ReasoningLevel::Medium] + } + fn deterministic_turn_end(&self) -> bool { + true + } + async fn models(&self) -> Result, HarnessError> { + Ok(vec![]) + } + async fn run( + &self, + request: RunRequest, + mut controls: RunControls, + ) -> Result>, HarnessError> { + self.ledger.spawns.fetch_add(1, Ordering::SeqCst); + self.ledger + .runs + .lock() + .unwrap() + .push((request.prompt.clone(), request.resume.clone())); + let (tx, rx) = mpsc::channel::>(64); + tokio::spawn(async move { + let send = |event: AgentEvent| { + let tx = tx.clone(); + async move { tx.send(Ok(event)).await.is_ok() } + }; + let _ = send(AgentEvent::SessionStarted { + harness: HarnessId::Mock, + model: "agent".into(), + tools: vec![], + cwd: request.cwd.clone(), + session_id: "provider-session".into(), + assistant_message_id: "a0".into(), + }) + .await; + let _ = send(AgentEvent::TextDelta { + text: format!("on it: {}", request.prompt), + }) + .await; + if !request.prompt.contains("hold") && !send(done()).await { + return; + } + loop { + tokio::select! { + _ = controls.interrupt.cancelled() => { + let _ = tx.send(Ok(AgentEvent::Done { + status: DoneStatus::Interrupted, + result: None, + error: None, + session_id: None, + })).await; + return; + } + steer = controls.steering.recv() => { + let Some(steer) = steer else { return }; + let boundary = AgentEvent::Steered { + assistant_message_id: None, + next_assistant_message_id: None, + }; + if !send(boundary).await + || !send(AgentEvent::TextDelta { text: format!("on it: {}", steer.prompt) }).await + || !send(done()).await + { + return; + } + } + } + } + }); + Ok( + futures::stream::unfold(rx, |mut rx| async move { rx.recv().await.map(|e| (e, rx)) }) + .boxed(), + ) + } +} + +fn assemble(dir: &std::path::Path, ledger: &Arc) -> EngineCore { + let registry = HarnessRegistry::new(); + registry.register(Arc::new(Agent { + ledger: ledger.clone(), + })); + let core = EngineCore::assemble(dir, Arc::new(registry), HarnessId::Mock, None) + .expect("engine core assembles"); + core.sessions.set_ipc_port(27699); + core +} + +fn request(prompt: &str) -> RunRequest { + RunRequest { + mcp: None, + env: Default::default(), + prompt: prompt.into(), + harness: Some(HarnessId::Mock), + instance: None, + model: Some("agent-1".into()), + reasoning: Some(ReasoningLevel::Medium), + model_options: Default::default(), + cwd: "/tmp".into(), + sandbox: SandboxLevel::WorkspaceWrite, + auto_approve: true, + access: Default::default(), + attachments: Vec::new(), + worktree: None, + resume: None, + } +} + +async fn wait_for(mut predicate: impl FnMut() -> bool, what: &str) { + let deadline = tokio::time::Instant::now() + Duration::from_secs(15); + while !predicate() { + assert!( + tokio::time::Instant::now() < deadline, + "timed out waiting for {what}" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } +} + +const SEEDED: [&str; 5] = ["seed-0", "seed-1", "seed-2", "seed-3", "seed-4"]; + +/// Five chats, each with a finished turn and its agent parked. +async fn seed(core: &EngineCore, ledger: &Ledger) { + for chat in SEEDED { + core.sessions + .dispatch(chat, HarnessId::Mock, request("seed prompt"), None) + .await + .unwrap(); + } + wait_for( + || { + SEEDED.iter().all(|chat| { + core.sessions.session_status(chat).map(|s| s.status) == Some(SessionStatus::Idle) + }) && ledger.spawns.load(Ordering::SeqCst) == SEEDED.len() + }, + "the seeded turns to park", + ) + .await; + assert!( + SEEDED + .iter() + .all(|chat| core.sessions.live_run_steerable(chat)) + ); +} + +/// Launch: recover, then three minutes with nothing sent. +async fn launch(dir: &std::path::Path) -> (EngineCore, Arc) { + let ledger = Arc::new(Ledger::default()); + let core = assemble(dir, &ledger); + core.sessions.recover_stale().unwrap(); + tokio::time::sleep(Duration::from_secs(3)).await; + (core, ledger) +} + +/// The next message, once launched: one agent, resuming the chat's session. +async fn next_message_resumes(core: &EngineCore, ledger: &Ledger) { + core.sessions + .dispatch("seed-2", HarnessId::Mock, request("next message"), None) + .await + .unwrap(); + wait_for( + || ledger.spawns.load(Ordering::SeqCst) == 1, + "the next message's agent", + ) + .await; + assert_eq!( + ledger.runs.lock().unwrap()[0], + ( + "next message".to_owned(), + Some("provider-session".to_owned()) + ), + "it resumes the chat's own session" + ); +} + +#[tokio::test] +async fn parked_agents_are_not_restarted_after_a_shutdown() { + let tmp = tempfile::tempdir().unwrap(); + { + let ledger = Arc::new(Ledger::default()); + let core = assemble(tmp.path(), &ledger); + seed(&core, &ledger).await; + core.shutdown().await; + } + let (core, ledger) = launch(tmp.path()).await; + assert_eq!( + ledger.spawns.load(Ordering::SeqCst), + 0, + "an agent started at launch" + ); + assert!( + SEEDED + .iter() + .all(|chat| !core.sessions.live_run_steerable(chat)) + ); + next_message_resumes(&core, &ledger).await; + core.sessions.shutdown().await; +} + +#[test] +fn parked_agents_are_not_restarted_after_a_crash() { + let tmp = tempfile::tempdir().unwrap(); + // The engine dies with its agents parked: its runtime goes without a + // shutdown, as a kill -9 leaves it (journals open, nothing closed). + let seeding = tokio::runtime::Runtime::new().unwrap(); + seeding.block_on(async { + let ledger = Arc::new(Ledger::default()); + let core = assemble(tmp.path(), &ledger); + seed(&core, &ledger).await; + // Let the debounced doc saves land, as minutes of rest would. + tokio::time::sleep(Duration::from_millis(1500)).await; + // Gone without its shutdown (its data dir let go, as a dead + // process's is). + drop(core); + }); + seeding.shutdown_background(); + let launching = tokio::runtime::Runtime::new().unwrap(); + launching.block_on(async { + let (core, ledger) = launch(tmp.path()).await; + assert_eq!( + ledger.spawns.load(Ordering::SeqCst), + 0, + "an agent started at launch" + ); + next_message_resumes(&core, &ledger).await; + core.sessions.shutdown().await; + }); +} diff --git a/crates/engine/tests/message_queue.rs b/crates/engine/tests/message_queue.rs index 754e32843..c3217fb06 100644 --- a/crates/engine/tests/message_queue.rs +++ b/crates/engine/tests/message_queue.rs @@ -1955,6 +1955,77 @@ async fn a_send_during_a_turn_boundary_turn_waits_for_the_turn_end() { core.shutdown().await; } +/// Two messages sent while the host was away (a Cloud machine asleep): by the +/// time the second is read, the first has just started a turn. The sender never +/// saw that turn, so the second waits for it and is a turn of its own, rather +/// than a steer that cut the first off with an empty reply. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_send_issued_before_the_running_turn_started_is_the_next_turn_not_a_steer() { + let (core, harness, prompts) = setup(SteeringMode::StepBoundary).await; + core.doc_host + .queue_message(CHAT, "opening", Vec::new()) + .expect("queue opening"); + wait_for(|| prompts.lock().unwrap().len() == 1, "the opening turn").await; + let template = core.sessions.last_request(CHAT).expect("a request"); + let deadline = tokio::time::Instant::now() + Duration::from_secs(10); + while core.sessions.turn_in_flight(CHAT) { + assert!(tokio::time::Instant::now() < deadline, "the opening turn never ended"); + let _ = harness.finish.send(()); + tokio::time::sleep(Duration::from_millis(5)).await; + } + + // Both sent a minute ago, two seconds apart, while the host was away. + let sent = |id: &str, prompt: &str, ago_ms: i64| { + let mut request = template.clone(); + request.prompt = prompt.into(); + let issued_at = chrono::Utc::now().timestamp_millis() - ago_ms; + zeron_doc::SessionCommandEntry { + id: format!("cmd-{id}"), + payload: SessionCommandPayload::Run { + message_id: format!("m-{id}"), + request, + }, + issued_by: "phone".into(), + issued_at, + based_on: None, + expires_at: Some(issued_at + 3_600_000), + status: zeron_doc::SessionCommandStatus::Pending, + resolution: None, + } + }; + let doc = core.doc_host.open(CHAT).unwrap(); + doc.doc() + .queue_command(&sent("first", "first, sent while away", 60_000)) + .unwrap(); + doc.doc() + .queue_command(&sent("second", "second, sent while away", 58_000)) + .unwrap(); + core.doc_host.enqueue_wakeup(CHAT).expect("wake the host"); + wait_for( + || queue_texts(&core) == vec!["second, sent while away"], + "the second to wait for the first turn", + ) + .await; + assert_eq!( + *prompts.lock().unwrap(), + vec!["opening", "first, sent while away"], + "the second was steered into the first turn" + ); + + let deadline = tokio::time::Instant::now() + Duration::from_secs(10); + while prompts.lock().unwrap().len() < 3 { + assert!(tokio::time::Instant::now() < deadline, "the second never ran"); + let _ = harness.finish.send(()); + tokio::time::sleep(Duration::from_millis(5)).await; + } + assert_eq!( + *prompts.lock().unwrap(), + vec!["opening", "first, sent while away", "second, sent while away"] + ); + let _ = harness.finish.send(()); + core.shutdown().await; +} + /// An agent that reads input mid-turn still gets a plain send immediately. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_send_during_a_mid_turn_steerable_turn_steers_it_immediately() { diff --git a/crates/engine/tests/queue_attachments.rs b/crates/engine/tests/queue_attachments.rs index 28f700320..eca34d90a 100644 --- a/crates/engine/tests/queue_attachments.rs +++ b/crates/engine/tests/queue_attachments.rs @@ -13,6 +13,9 @@ use futures::StreamExt; use futures::stream::BoxStream; use tokio::sync::mpsc; +use zeron_engine::doc_host::{ + BeginQueueEditOutcome, FinishQueueEditAction, FinishQueueEditOutcome, +}; use zeron_engine::{EngineCore, HarnessRegistry}; use zeron_harness::{Harness, HarnessError, RunControls}; use zeron_proto::{ @@ -343,3 +346,195 @@ async fn a_row_with_files_sent_now_or_drained_keeps_them() { assert_eq!(read_for(&rig, "after the turn").unwrap().1, files); rig.core.sessions.shutdown().await; } + +/// Files alone, sent while a turn runs: the app's `QueueMessage` has no +/// words to give. It goes as a run's does, and never comes back refused +/// (2026-11-07: a screenshot said "Your message didn't send", twice). +#[tokio::test] +async fn files_with_no_words_queue_and_reach_the_agent() { + let rig = rig(); + running(&rig).await; + let files = files(&rig); + let client = zeron_rpc::memory_client(rig.core.rpc_service()); + client + .call( + zeron_rpc::methods::QUEUE_MESSAGE, + serde_json::json!({ + "chatId": CHAT, + "text": "", + "attachments": files, + "holdForTurnEnd": true, + }), + ) + .await + .expect("a message of files alone is queued"); + assert_eq!(queued(&rig), 1, "it waits in the queue, its files with it"); + rig.ledger.release.notify_one(); + wait_for( + || read_for(&rig, "See the attached image(s).").is_some(), + "the drain", + ) + .await; + assert_eq!( + read_for(&rig, "See the attached image(s).").unwrap().1, + files + ); + rig.core.sessions.shutdown().await; +} + +/// Still refused: nothing at all. +#[tokio::test] +async fn a_message_with_no_words_and_no_files_is_refused() { + let rig = rig(); + assert!( + rig.core + .doc_host + .queue_message_with_behavior(CHAT, " ", Vec::new(), true) + .is_err() + ); + rig.core.sessions.shutdown().await; +} + +async fn edit_lease(rig: &Rig, id: &str) -> (String, String) { + let BeginQueueEditOutcome::Acquired { + lease_id, + base_text_hash, + .. + } = rig + .core + .doc_host + .begin_queued_message_edit(CHAT, id, "phone", "view-1") + .await + .unwrap() + else { + panic!("the edit is acquired"); + }; + (lease_id, base_text_hash) +} + +/// An edit that clears the words of a row keeping its files leaves the row; +/// taking the files off as well is how it goes. +#[tokio::test] +async fn clearing_the_words_of_a_row_with_files_keeps_it() { + let rig = rig(); + running(&rig).await; + let files = files(&rig); + let id = queue(&rig, "look at these", files.clone()); + let (lease, hash) = edit_lease(&rig, &id).await; + assert!(matches!( + rig.core + .doc_host + .finish_queued_message_edit_with_attachments( + CHAT, + &id, + &lease, + FinishQueueEditAction::Commit, + Some(""), + Some(&hash), + Some(&files), + ) + .await + .unwrap(), + FinishQueueEditOutcome::Committed + )); + let rows = rig + .core + .doc_host + .open(CHAT) + .unwrap() + .doc() + .read_queue() + .unwrap(); + assert_eq!(rows.len(), 1, "the row stays"); + assert_eq!(rows[0].text, "See the attached image(s)."); + assert_eq!(rows[0].attachments, files); + + let (lease, hash) = edit_lease(&rig, &id).await; + rig.core + .doc_host + .finish_queued_message_edit_with_attachments( + CHAT, + &id, + &lease, + FinishQueueEditAction::Commit, + Some(""), + Some(&hash), + Some(&[]), + ) + .await + .unwrap(); + assert_eq!(queued(&rig), 0, "no words and no files: it goes"); + rig.core.sessions.shutdown().await; +} + +/// Another Windows user's (or device's) path for an upload this device also +/// holds: what reached the agent on 2026-11-07 as `C:\Users\ADMIN\…`, from a +/// chat running as `HP MEDIA`. +const THEIRS: &str = r"C:\Users\ADMIN\AppData\Local\Zeron\uploads\2fbd2b3b-image.png"; + +/// The same upload committed on this device: its path here. +async fn committed_here(rig: &Rig) -> String { + let client = zeron_rpc::memory_client(rig.core.rpc_service()); + client + .call( + zeron_rpc::methods::UPLOAD_CHUNK, + serde_json::json!({ + "uploadId": "2fbd2b3b-9c1e", + "seq": 0, + "data": base64::engine::general_purpose::STANDARD.encode(b"\x89PNG\r\n\x1a\n"), + }), + ) + .await + .unwrap(); + let reply = client + .call( + zeron_rpc::methods::UPLOAD_COMMIT, + serde_json::json!({ "uploadId": "2fbd2b3b-9c1e", "fileName": "image.png" }), + ) + .await + .unwrap(); + reply["path"].as_str().unwrap().to_owned() +} + +#[tokio::test] +async fn a_row_naming_another_users_path_reaches_the_agent_by_this_devices_copy() { + let rig = rig(); + running(&rig).await; + let here = committed_here(&rig).await; + // Steered in. + let id = queue(&rig, "steered with it", vec![THEIRS.into()]); + assert!(rig.core.doc_host.steer_queued_now(CHAT, &id).await.unwrap()); + wait_for(|| read_for(&rig, "steered with it").is_some(), "the steer").await; + let (prompt, got) = read_for(&rig, "steered with it").unwrap(); + assert_eq!(got, vec![here.clone()]); + assert!( + prompt.contains(&here) && !prompt.contains("ADMIN"), + "got: {prompt}" + ); + // Drained at the turn's end. + queue(&rig, "drained with it", vec![THEIRS.into()]); + rig.ledger.release.notify_one(); + wait_for(|| read_for(&rig, "drained with it").is_some(), "the drain").await; + let (prompt, got) = read_for(&rig, "drained with it").unwrap(); + assert_eq!(got, vec![here.clone()]); + assert!( + prompt.contains(&here) && !prompt.contains("ADMIN"), + "got: {prompt}" + ); + rig.core.sessions.shutdown().await; +} + +#[tokio::test] +async fn a_path_this_device_cant_place_goes_as_it_was() { + let rig = rig(); + running(&rig).await; + // No copy here: nothing to rebase it to. + let id = queue(&rig, "nothing here", vec![THEIRS.into()]); + assert!(rig.core.doc_host.steer_queued_now(CHAT, &id).await.unwrap()); + wait_for(|| read_for(&rig, "nothing here").is_some(), "the steer").await; + assert_eq!( + read_for(&rig, "nothing here").unwrap().1, + vec![THEIRS.to_string()] + ); + rig.core.sessions.shutdown().await; +} diff --git a/crates/engine/tests/steer_now.rs b/crates/engine/tests/steer_now.rs index 2ae5db3c9..b5ed60d44 100644 --- a/crates/engine/tests/steer_now.rs +++ b/crates/engine/tests/steer_now.rs @@ -4,7 +4,8 @@ //! first: the command ends, the runtime and its background work stay, and //! the steer starts the next turn in that same runtime. Steers sent before //! it, which the stop cancels, go again first. Agents that haven't opted -//! in (`Harness::steer_stops_tool`) keep the step-boundary wait. +//! in (`Harness::steer_stops_tool`) keep the step-boundary wait, and so does +//! a message from another chat. use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; @@ -435,3 +436,51 @@ async fn a_steer_with_no_command_running_stops_nothing() { assert_eq!(rig.ledger.kills.load(Ordering::SeqCst), 0); rig.core.sessions.shutdown().await; } + +/// Claude Code tells the agent the person rejected the call and to stop and +/// wait whenever a turn is interrupted, so a message from another chat that +/// stopped the command would read as an order to stop. It waits for the +/// command instead, as `send_message` promises. +#[tokio::test] +async fn a_message_from_another_chat_never_stops_the_command() { + let rig = rig(true); + let turn = running_a_command(&rig).await; + wait_for( + || rig.core.sessions.steer_stops_tool(CHAT), + "the command to be open", + ) + .await; + let message = + zeron_proto::agent_messages::agent_message("Coordinator (139d8682)", "139d8682", "status?"); + steer(&rig, &message, "m-agent"); + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!(read(&rig).len(), 1, "it waits for the command"); + assert_eq!( + rig.ledger.stops.load(Ordering::SeqCst), + 0, + "nothing stopped" + ); + rig.ledger.release.notify_one(); + wait_for( + || read(&rig).iter().any(|p| p.ends_with("status?")), + "the message at the step boundary", + ) + .await; + wait_for( + || status(&rig.core) == Some(SessionStatus::Idle), + "the turn to end", + ) + .await; + assert_eq!(rig.ledger.stops.load(Ordering::SeqCst), 0); + assert_eq!(rig.ledger.kills.load(Ordering::SeqCst), 0); + assert!(turn.background_live(), "its background work still runs"); + let doc = rig.core.doc_host.open(CHAT).unwrap(); + let entries = doc.doc().read_entries().unwrap(); + assert!( + !entries + .iter() + .any(|e| e.status == Some(MessageStatus::Aborted)), + "the command's turn was not stopped" + ); + rig.core.sessions.shutdown().await; +} diff --git a/crates/engine/tests/terminal_query_order.rs b/crates/engine/tests/terminal_query_order.rs new file mode 100644 index 000000000..ad311ea8f --- /dev/null +++ b/crates/engine/tests/terminal_query_order.rs @@ -0,0 +1,207 @@ +//! A viewer that answers terminal queries itself (zgx's terminal, through +//! `zeron-zgx terminal-bridge`) writes each answer as its own WriteTerminal +//! call, in the order the program asked. The program must read them in that +//! order: termenv (gh, glamour, lipgloss) asks for the background (OSC 11) +//! and then the cursor (CSI 6n), and takes a cursor report first as "no +//! OSC 11": it stops reading, and the colour answer that follows is read as +//! typed keys (gh's prompt: "unexpected escape sequence from terminal: +//! ['\x1b' ']']", and `;22R` left in the shell). +//! +//! Over the engine's own RPC dispatch (the memory transport is the same loop +//! as the WebSocket's), a program in the PTY asks as termenv does, a viewer +//! answers as Ghostty does (two writes, back to back, the moment it sees the +//! query), and the program records which answer came first and how long each +//! took. (A Perl script, as Perl is on every Unix runner.) +#![cfg(unix)] + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use base64::Engine as _; +use base64::engine::general_purpose::STANDARD as BASE64; +use serde_json::{Value, json}; +use zeron_engine::EngineCore; +use zeron_rpc::methods; + +const ROUNDS: usize = 300; +const QUERY: &[u8] = b"\x1b]11;?\x1b\\\x1b[6n"; +const COLOR: &[u8] = b"\x1b]11;rgb:1e1e/1e1e/1e1e\x1b\\"; +const CURSOR: &[u8] = b"\x1b[22;50R"; + +/// termenv's query, `ROUNDS` times: each answer read a byte at a time, the +/// first required to be the colour's (as `termStatusReport`), each timed. +const PROBE: &str = r#" +use strict; +use warnings; +use Time::HiRes qw(time sleep); +system("stty raw -echo") == 0 or die "stty"; +sub byte { + my ($deadline) = @_; + my $left = $deadline - time(); + return undef if $left <= 0; + my $rin = ''; + vec($rin, fileno(STDIN), 1) = 1; + return undef unless select(my $rout = $rin, undef, undef, $left) > 0; + my $b; + return undef unless sysread(STDIN, $b, 1) == 1; + return $b; +} +sub answer { + my ($deadline) = @_; + while (1) { + my $b = byte($deadline); + return undef unless defined $b; + last if $b eq "\e"; + } + my $kind = byte($deadline); + return undef unless defined $kind; + my $got = "\e$kind"; + while (length($got) < 64) { + my $b = byte($deadline); + return undef unless defined $b; + $got .= $b; + return $got if $kind eq ']' && ($b eq "\a" || substr($got, -2) eq "\e\\"); + return $got if $kind eq '[' && $b eq 'R'; + } + return $got; +} +my ($ordered, $misordered, $lost) = (0, 0, 0); +my (@color, @cursor); +for (1 .. $ARGV[0]) { + my $start = time(); + syswrite(STDOUT, "\e]11;?\e\\\e[6n"); + my $deadline = $start + 2; + my $first = answer($deadline); + my $t1 = time(); + my $second = defined $first ? answer($deadline) : undef; + my $t2 = time(); + if (!defined $first || !defined $second) { + $lost++; + } elsif (substr($first, 0, 2) eq "\e]") { + $ordered++; push @color, ($t1 - $start) * 1e3; push @cursor, ($t2 - $start) * 1e3; + } else { + $misordered++; push @cursor, ($t1 - $start) * 1e3; push @color, ($t2 - $start) * 1e3; + } + sleep(0.002); +} +system("stty sane"); +sub pct { my ($q, @x) = @_; return -1 unless @x; @x = sort { $a <=> $b } @x; my $i = int($q * @x); $i = $#x if $i > $#x; return $x[$i]; } +sub most { my @x = @_; return -1 unless @x; my $m = $x[0]; for (@x) { $m = $_ if $_ > $m } return $m; } +printf "\r\nPROBE ordered=%d misordered=%d lost=%d color_p50=%.2f color_p99=%.2f color_max=%.2f cursor_p50=%.2f cursor_max=%.2f\r\n", + $ordered, $misordered, $lost, pct(.5, @color), pct(.99, @color), most(@color), pct(.5, @cursor), most(@cursor); +"#; + +fn frame(id: u64, method: &str, params: Value) -> String { + json!({ "id": id, "method": method, "params": params }).to_string() +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_self_answering_viewer_s_answers_reach_the_program_in_order() { + let tmp = tempfile::tempdir().expect("tempdir"); + let data = tmp.path().join("data"); + std::fs::create_dir_all(&data).expect("data dir"); + let core = EngineCore::assemble( + &data, + Arc::new(zeron_engine::HarnessRegistry::new()), + zeron_proto::HarnessId::Mock, + None, + ) + .expect("engine assembles"); + let probe = tmp.path().join("probe.pl"); + std::fs::write(&probe, PROBE).expect("probe"); + let session = core + .terminals + .open_with_shell(&tmp.path().to_string_lossy(), 80, 24, Some("/bin/sh")) + .expect("open sh"); + // Closed however the test ends: its reader would keep the test running. + struct Close<'a>(&'a zeron_engine::Terminals, String); + impl Drop for Close<'_> { + fn drop(&mut self) { + let _ = self.0.close(&self.1); + } + } + let _close = Close(&core.terminals, session.id.clone()); + + // The bridge's connection: raw frames, as it sends them. + let (to_server, server_in) = tokio::sync::mpsc::channel::(1024); + let (server_out, mut from_server) = tokio::sync::mpsc::channel::(1024); + tokio::spawn(zeron_rpc::serve_connection( + core.rpc_service(), + server_out, + server_in, + )); + to_server + .send(frame( + 1, + methods::SUBSCRIBE_TERMINAL, + json!({ "terminalId": session.id, "hostReplies": false }), + )) + .await + .unwrap(); + let mut next = 2u64; + let write = |next: &mut u64, bytes: &[u8]| { + let line = frame( + *next, + methods::WRITE_TERMINAL, + json!({ "terminalId": session.id, "data": BASE64.encode(bytes) }), + ); + *next += 1; + line + }; + let command = format!("perl {} {ROUNDS}\n", probe.display()); + to_server + .send(write(&mut next, command.as_bytes())) + .await + .unwrap(); + + // The viewer: each query answered as it's seen, as two writes. + let mut output: Vec = Vec::new(); + let mut scanned = 0usize; + let deadline = Instant::now() + Duration::from_secs(120); + let summary = loop { + let left = deadline.saturating_duration_since(Instant::now()); + let line = tokio::time::timeout(left, from_server.recv()) + .await + .expect("the probe finishes in time") + .expect("the connection stays up"); + for line in line.lines().filter(|l| !l.trim().is_empty()) { + let frame: Value = serde_json::from_str(line).expect("a frame"); + if frame["id"].as_u64() != Some(1) || frame["item"]["type"] != "data" { + continue; + } + let bytes = BASE64 + .decode(frame["item"]["data"].as_str().unwrap()) + .unwrap(); + output.extend_from_slice(&bytes); + } + while let Some(at) = output[scanned..] + .windows(QUERY.len()) + .position(|w| w == QUERY) + { + scanned += at + QUERY.len(); + to_server.send(write(&mut next, COLOR)).await.unwrap(); + to_server.send(write(&mut next, CURSOR)).await.unwrap(); + } + let text = String::from_utf8_lossy(&output); + if let Some(at) = text.find("PROBE ordered=") + && let Some(end) = text[at..].find('\n') + { + break text[at..at + end].trim().to_owned(); + } + }; + eprintln!("{summary}"); + let field = |name: &str| -> usize { + summary + .split_whitespace() + .find_map(|kv| kv.strip_prefix(&format!("{name}="))) + .and_then(|v| v.parse().ok()) + .unwrap_or(usize::MAX) + }; + assert_eq!(field("lost"), 0, "every query answered: {summary}"); + assert_eq!( + field("misordered"), + 0, + "the colour answer read before the cursor's every time: {summary}" + ); + assert_eq!(field("ordered"), ROUNDS, "{summary}"); +} diff --git a/crates/harness/src/bounded_file.rs b/crates/harness/src/bounded_file.rs new file mode 100644 index 000000000..11a8fa07d --- /dev/null +++ b/crates/harness/src/bounded_file.rs @@ -0,0 +1,121 @@ +//! Reading a small file that someone else may have put in place: a config +//! file in a cloned repository, a CLI's cache. A path checked first and +//! read after can be a symlink to `/dev/zero` (read forever) or a FIFO +//! (open blocks until a writer comes), or be swapped for one in between, so +//! the checks are made on the open handle and the read itself is bounded. + +use std::io::Read; +use std::path::Path; + +/// `path`'s bytes when it is a regular file of at most `max` bytes (a +/// symlink to one is followed). A FIFO or device is refused without +/// blocking, and a file over `max` (or one growing past it as it is read) +/// is refused once `max + 1` bytes are in: `InvalidInput` and +/// `FileTooLarge` errors respectively; a missing file is `NotFound`. +pub fn read(path: &Path, max: u64) -> std::io::Result> { + let (file, len) = open(path, max)?; + let mut bytes = Vec::with_capacity(len as usize); + file.take(max.saturating_add(1)).read_to_end(&mut bytes)?; + if bytes.len() as u64 > max { + return Err(too_large()); + } + Ok(bytes) +} + +/// [`read`] as UTF-8 text. +pub fn read_to_string(path: &Path, max: u64) -> std::io::Result { + String::from_utf8(read(path, max)?) + .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err)) +} + +/// `path` opened for a streamed read, refused as [`read`] refuses it, with +/// its length when opened. Read it through `take(max + 1)` (or check what +/// came in) if it may grow meanwhile. +pub fn open(path: &Path, max: u64) -> std::io::Result<(std::fs::File, u64)> { + let mut options = std::fs::OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + // A FIFO opened for reading blocks until a writer appears; a + // terminal would become the controlling one. + options.custom_flags(libc::O_NONBLOCK | libc::O_NOCTTY); + } + let file = options.open(path)?; + // What was opened, not what the path named a moment before. + let meta = file.metadata()?; + if !meta.is_file() { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "not a regular file", + )); + } + if meta.len() > max { + return Err(too_large()); + } + // (O_NONBLOCK changes nothing for a regular file's reads.) + Ok((file, meta.len())) +} + +fn too_large() -> std::io::Error { + std::io::Error::new(std::io::ErrorKind::FileTooLarge, "file too large") +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use std::time::{Duration, Instant}; + + /// Runs `read` on another thread, failing the test if it hangs. + fn read_promptly(path: &Path, max: u64) -> std::io::Result> { + let path = path.to_path_buf(); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = tx.send(read(&path, max)); + }); + rx.recv_timeout(Duration::from_secs(5)) + .expect("the read hung") + } + + #[test] + fn a_regular_file_within_the_limit_is_read() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("a.json"); + std::fs::write(&path, b"{}").unwrap(); + assert_eq!(read(&path, 2).unwrap(), b"{}"); + assert_eq!( + read(&path, 1).unwrap_err().kind(), + std::io::ErrorKind::FileTooLarge + ); + // A symlink to a regular file still reads. + let link = dir.path().join("link.json"); + std::os::unix::fs::symlink(&path, &link).unwrap(); + assert_eq!(read(&link, 16).unwrap(), b"{}"); + assert_eq!( + read(&dir.path().join("missing"), 16).unwrap_err().kind(), + std::io::ErrorKind::NotFound + ); + } + + #[test] + fn a_symlink_to_dev_zero_is_refused_promptly() { + let dir = tempfile::tempdir().unwrap(); + let link = dir.path().join(".mcp.json"); + std::os::unix::fs::symlink("/dev/zero", &link).unwrap(); + let started = Instant::now(); + let err = read_promptly(&link, 1024 * 1024).unwrap_err(); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput); + assert!(started.elapsed() < Duration::from_secs(1)); + } + + #[test] + fn a_fifo_is_refused_without_waiting_for_a_writer() { + let dir = tempfile::tempdir().unwrap(); + let fifo = dir.path().join("settings.json"); + let c_path = std::ffi::CString::new(fifo.as_os_str().as_encoded_bytes()).unwrap(); + // SAFETY: a valid NUL-terminated path. + assert_eq!(unsafe { libc::mkfifo(c_path.as_ptr(), 0o600) }, 0); + let err = read_promptly(&fifo, 1024).unwrap_err(); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput); + } +} diff --git a/crates/harness/src/claude/catalog.rs b/crates/harness/src/claude/catalog.rs index 53b07aff6..e81abbfa8 100644 --- a/crates/harness/src/claude/catalog.rs +++ b/crates/harness/src/claude/catalog.rs @@ -2,7 +2,8 @@ //! `packages/harness/src/claude.ts` (which itself mirrors Claude Code's own //! picker via t3code's catalog). //! -//! Runtime initialize discovery appends concrete model ids to this curated list. +//! Runtime initialize discovery appends concrete model ids to this curated list +//! and fills ID-only labels for configured models with discovered display names. //! Curated rows retain their labels, effort ladders, and option sets because the //! CLI can under-report supported modes. The shared initialize probe also supplies //! slash commands and is cached by credential and binary context. @@ -104,6 +105,17 @@ pub(crate) fn context_window() -> ModelOption { } } +/// The Context Window select for models whose plain id already runs with the +/// 1M window (the Fable models, Opus 4.7+, Sonnet 5+). Left unset, they run +/// at 1M, so the select says so; 200K is an explicit choice that the launch +/// enforces with `CLAUDE_CODE_DISABLE_1M_CONTEXT` (zeronsh/zeron#1083). +fn native_1m_context_window() -> ModelOption { + ModelOption { + default_choice: "1m".into(), + ..context_window() + } +} + const FULL_LADDER: &[ReasoningLevel] = &[ ReasoningLevel::Low, ReasoningLevel::Medium, @@ -253,6 +265,7 @@ fn models_with_settings(path: &std::path::Path) -> Vec { [ "ANTHROPIC_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", + "ANTHROPIC_DEFAULT_FABLE_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", @@ -288,6 +301,7 @@ fn settings_models_keep_manifest_and_full_ladder() { &path, serde_json::json!({"model":"gateway/model", "env": { "ANTHROPIC_MODEL":"gateway/model", "ANTHROPIC_SMALL_FAST_MODEL":"fast", + "ANTHROPIC_DEFAULT_FABLE_MODEL":"gateway/astra", "ANTHROPIC_DEFAULT_OPUS_MODEL":"opus", "ANTHROPIC_DEFAULT_SONNET_MODEL":"sonnet", "ANTHROPIC_DEFAULT_HAIKU_MODEL":"haiku" }}) @@ -296,7 +310,8 @@ fn settings_models_keep_manifest_and_full_ladder() { .unwrap(); let models = models_with_settings(&path); assert_eq!(&models[..static_models().len()], static_models()); - assert_eq!(models.len(), static_models().len() + 5); + assert_eq!(models.len(), static_models().len() + 6); + assert!(models.iter().any(|model| model.id == "gateway/astra")); for model in &models[static_models().len()..] { assert_eq!(model.label, model.id); assert_eq!(model.reasoning_levels, FULL_LADDER); @@ -305,11 +320,20 @@ fn settings_models_keep_manifest_and_full_ladder() { assert_eq!(models_with_settings(&path), static_models()); } -/// Overlay only new concrete model IDs; curated metadata remains authoritative. +/// Append new concrete model IDs and fill ID-only labels on existing rows; +/// curated metadata remains authoritative. pub(super) fn with_discovered_models( mut models: Vec, response: &serde_json::Value, ) -> Result, crate::HarnessError> { + fn entry_text<'a>(entry: &'a serde_json::Value, key: &str) -> Option<&'a str> { + entry + .get(key) + .and_then(serde_json::Value::as_str) + .map(str::trim) + .filter(|v| !v.is_empty()) + } + let entries = response .get("response") .and_then(|v| v.get("models")) @@ -318,19 +342,28 @@ pub(super) fn with_discovered_models( .ok_or_else(|| { crate::HarnessError::Protocol("Claude returned an empty model catalog".into()) })?; + // Alias rows can precede the concrete row and carry generic names such as + // "Default (recommended)". Prefer concrete names regardless of entry order. + let mut concrete_labels = std::collections::HashMap::new(); + for entry in entries { + if let Some(id) = entry_text(entry, "value") + && entry_text(entry, "resolvedModel").is_none_or(|resolved| resolved == id) + && let Some(label) = entry_text(entry, "displayName") + { + concrete_labels.entry(id).or_insert(label); + } + } let mut default = None; let mut valid = false; for entry in entries { - let text = |key: &str| { - entry - .get(key) - .and_then(serde_json::Value::as_str) - .map(str::trim) - .filter(|v| !v.is_empty()) - }; + let text = |key: &str| entry_text(entry, key); let Some(id) = text("resolvedModel").or_else(|| text("value")) else { continue; }; + let label = concrete_labels + .get(id) + .copied() + .or_else(|| text("displayName")); // Bare aliases cannot become persisted selections. Prefer resolvedModel. if matches!( id.strip_suffix("[1m]").unwrap_or(id), @@ -347,7 +380,12 @@ pub(super) fn with_discovered_models( if text("value") == Some("default") { default = Some(id.to_owned()); } - if models.iter().any(|model| model.id == id) { + if let Some(model) = models.iter_mut().find(|model| model.id == id) { + if model.label == model.id + && let Some(label) = label + { + model.label = label.into(); + } continue; } let mut ladder = Vec::new(); @@ -375,7 +413,7 @@ pub(super) fn with_discovered_models( } models.push(Model { id: id.into(), - label: text("displayName").unwrap_or(id).into(), + label: label.unwrap_or(id).into(), description: text("description").map(str::to_owned), reasoning_levels: ladder, options: vec![], @@ -417,21 +455,21 @@ pub fn static_models() -> Vec { "Fable 5.1", "Most intelligent model for building agents", FULL_LADDER, - vec![context_window()], + vec![native_1m_context_window()], ), model( "claude-fable-5", "Fable 5", "Previous generation Fable", FULL_LADDER, - vec![context_window()], + vec![native_1m_context_window()], ), model( "claude-opus-5-5", "Opus 5.5", "Best for everyday, complex tasks", FULL_LADDER, - vec![context_window(), toggle("fastMode", "Fast Mode")], + vec![native_1m_context_window(), toggle("fastMode", "Fast Mode")], ), model( "claude-opus-4-8", @@ -452,7 +490,7 @@ pub fn static_models() -> Vec { "Sonnet 5", "Balanced speed and intelligence", XHIGH_LADDER, - vec![context_window()], + vec![native_1m_context_window()], ), model( "claude-haiku-4-5", @@ -468,6 +506,110 @@ pub fn static_models() -> Vec { mod tests { use super::*; + #[test] + fn discovered_names_complete_configured_models_without_replacing_metadata() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("settings.json"); + std::fs::write( + &path, + serde_json::json!({"model":"gateway/sol", "env": { + "ANTHROPIC_DEFAULT_FABLE_MODEL":"gateway/astra", + "ANTHROPIC_DEFAULT_OPUS_MODEL":"gateway/sol", + "ANTHROPIC_DEFAULT_SONNET_MODEL":"gateway/terra", + "ANTHROPIC_DEFAULT_HAIKU_MODEL":"gateway/luna" + }}) + .to_string(), + ) + .unwrap(); + let configured = models_with_settings(&path); + let response = serde_json::json!({"response":{"models":[ + {"value":"default", "resolvedModel":"gateway/sol", "displayName":"Default (recommended)", "supportedEffortLevels":["low"]}, + {"value":"gateway/sol", "displayName":" GPT Sol "}, + {"value":"gateway/sol", "displayName":"Another Sol label"}, + {"value":"gateway/terra", "displayName":"GPT Terra"}, + {"value":"gateway/luna", "displayName":"GPT Luna"}, + {"value":"gateway/astra", "displayName":"GPT Astra"}, + {"value":"gateway/new", "displayName":"New gateway model"}, + {"value":"claude-opus-5-5", "displayName":"Opus", "supportedEffortLevels":["low"]} + ]}}); + let models = with_discovered_models(configured.clone(), &response).unwrap(); + for (id, label) in [ + ("gateway/sol", "GPT Sol"), + ("gateway/terra", "GPT Terra"), + ("gateway/luna", "GPT Luna"), + ("gateway/astra", "GPT Astra"), + ] { + let mut expected = configured.iter().find(|m| m.id == id).unwrap().clone(); + expected.label = label.into(); + assert_eq!(models.iter().find(|m| m.id == id), Some(&expected)); + assert_eq!(models.iter().filter(|m| m.id == id).count(), 1); + } + assert_eq!(models[0].id, "gateway/sol"); + assert_eq!( + models.iter().find(|m| m.id == "gateway/new").unwrap().label, + "New gateway model" + ); + for curated in static_models() { + assert_eq!(models.iter().find(|m| m.id == curated.id), Some(&curated)); + } + } + + #[test] + fn concrete_names_take_priority_over_alias_names_in_either_order() { + let alias = serde_json::json!({ + "value":"default", "resolvedModel":"gateway/sol", + "displayName":"Default (recommended)" + }); + let concrete = serde_json::json!({ + "value":"gateway/sol", "resolvedModel":"gateway/sol", + "displayName":"GPT Sol" + }); + for entries in [ + vec![alias.clone(), concrete.clone()], + vec![concrete, alias.clone()], + ] { + let response = serde_json::json!({"response":{"models":entries}}); + for configured in [ + vec![], + vec![model("gateway/sol", "gateway/sol", "", FULL_LADDER, vec![])], + ] { + let models = with_discovered_models(configured, &response).unwrap(); + assert_eq!(models.len(), 1); + assert_eq!(models[0].id, "gateway/sol"); + assert_eq!(models[0].label, "GPT Sol"); + } + } + // An alias still provides a fallback name when no concrete name exists. + let response = serde_json::json!({"response":{"models":[ + alias, + {"value":"gateway/sol", "displayName":" "} + ]}}); + let models = with_discovered_models(vec![], &response).unwrap(); + assert_eq!(models[0].label, "Default (recommended)"); + } + + #[test] + fn missing_discovered_names_preserve_the_configured_id_label() { + let configured = vec![model( + "gateway/model", + "gateway/model", + "", + FULL_LADDER, + vec![], + )]; + for entry in [ + serde_json::json!({"value":"gateway/model"}), + serde_json::json!({"value":"gateway/model", "displayName":" "}), + serde_json::json!({"value":"gateway/model", "displayName":null}), + ] { + let response = serde_json::json!({"response":{"models":[entry]}}); + assert_eq!( + with_discovered_models(configured.clone(), &response).unwrap(), + configured + ); + } + } + #[test] fn effort_maps_special_modes() { assert_eq!(to_effort(None, None), None); diff --git a/crates/harness/src/claude/mod.rs b/crates/harness/src/claude/mod.rs index abd489646..63904d622 100644 --- a/crates/harness/src/claude/mod.rs +++ b/crates/harness/src/claude/mod.rs @@ -134,6 +134,24 @@ fn model_arg(request: &RunRequest) -> Option { }) } +/// Whether this run must really be limited to a 200K window. The model id +/// alone cannot do it: models such as `claude-opus-5-5` run 1M under their +/// plain id, so the "200K" choice only held for ids that happen to default to +/// 200K (zeronsh/zeron#1083). The CLI's `CLAUDE_CODE_DISABLE_1M_CONTEXT` +/// makes it resolve a 200K window (verified on 2.1.319: `modelUsage.contextWindow` +/// 1000000 -> 200000), and its own autocompact then works from that window. +/// It is read at launch, so changing it needs a fresh process. +/// +/// Only an explicit 200K choice sets it. Unset, a model keeps the window the +/// CLI gives it (1M for the long-context rows, whose select defaults to 1M). +fn caps_context_at_200k(request: &RunRequest) -> bool { + request + .model_options + .get("contextWindow") + .and_then(Value::as_str) + .is_some_and(|window| window.eq_ignore_ascii_case("200k")) +} + /// Every flag-layer setting a request launches with, for /// `apply_flag_settings` on a live process: `null` drops the override back /// to the user's own settings, exactly as a launch without the flag @@ -291,6 +309,19 @@ impl ClaudeHarness { // stream-json`) forwards its own subagents' text too, which only // adds tagged frames to its stream. cmd.env("CLAUDE_CODE_FORWARD_SUBAGENT_TEXT", "1"); + // No session title of the CLI's own. Godspeed titles chats itself and + // nothing reads the CLI's title, but in stream-json mode the CLI + // sends one more Haiku request to name every session whose first + // prompt is 10+ characters: the chat's run, and every titling run + // too (its prompt is long), ~4.3 KB each on every new chat. The + // variable latches the CLI's titling as done (2.1.322 `hhi()`); it + // also leaves the process title and terminal tab alone, which a + // piped CLI never shows anyway. A `claude` the run starts inherits it. + cmd.env("CLAUDE_CODE_DISABLE_TERMINAL_TITLE", "1"); + // "200K" really limits the window (see `caps_context_at_200k`). + if caps_context_at_200k(request) { + cmd.env("CLAUDE_CODE_DISABLE_1M_CONTEXT", "1"); + } cmd.args(Self::launch_args(request)); crate::apply_run_env(&mut cmd, &request.env, crate::run_cwd(&request)); // Newer Claude models emit no readable thinking text unless a @@ -601,7 +632,9 @@ impl Harness for ClaudeHarness { /// Same launch arguments and cwd. The CLI ignores the sandbox level, and /// option spellings that launch the same flags are the same runtime. fn same_runtime(&self, live: &RunRequest, next: &RunRequest) -> bool { - live.cwd == next.cwd && Self::launch_args(live) == Self::launch_args(next) + live.cwd == next.cwd + && Self::launch_args(live) == Self::launch_args(next) + && caps_context_at_200k(live) == caps_context_at_200k(next) } /// Model, context window, effort, fast mode, thinking and ultracode all /// change on the live process (`set_model`, `apply_flag_settings`), and @@ -613,6 +646,8 @@ impl Harness for ClaudeHarness { live.cwd == next.cwd && bypass(live) == bypass(next) && live.writable_roots() == next.writable_roots() + // The 200K limit is an environment variable of the process. + && caps_context_at_200k(live) == caps_context_at_200k(next) } /// Credential and executable identity scopes both initialize and catalog caches. @@ -2445,6 +2480,65 @@ mod tests { assert!(updated["questions"].is_array()); } + fn with_options(model: &str, options: Value) -> RunRequest { + RunRequest { + instance: None, + mcp: None, + prompt: "hi".into(), + harness: None, + model: Some(model.into()), + reasoning: None, + model_options: options.as_object().cloned().unwrap_or_default(), + cwd: String::new(), + sandbox: zeron_proto::SandboxLevel::WorkspaceWrite, + auto_approve: false, + attachments: Vec::new(), + worktree: None, + resume: None, + access: None, + env: Default::default(), + } + } + + #[test] + fn the_200k_choice_limits_the_window_through_the_cli() { + // Only an explicit 200K choice caps; unset keeps the CLI's window + // (1M on Opus 5.5), which is what its select now shows as default. + let chosen = with_options("claude-opus-5-5", json!({"contextWindow": "200k"})); + let unset = with_options("claude-opus-5-5", json!({})); + assert!(caps_context_at_200k(&chosen)); + assert!(!caps_context_at_200k(&unset)); + assert!(catalog::static_models().iter().any(|m| m.id == "claude-opus-5-5" + && m.options + .iter() + .any(|o| o.id == "contextWindow" && o.default_choice == "1m"))); + // 1M keeps the `[1m]` id and never the limit. + let one_m = with_options("claude-opus-5-5", json!({"contextWindow": "1m"})); + assert!(!caps_context_at_200k(&one_m)); + assert_eq!(model_arg(&one_m).as_deref(), Some("claude-opus-5-5[1m]")); + // A model without the option is left to the CLI. + assert!(!caps_context_at_200k(&with_options("claude-haiku-4-5", json!({})))); + // The limit is a launch environment variable, so a change relaunches. + let harness = ClaudeHarness::new(); + assert!(!harness.same_runtime(&chosen, &one_m)); + assert!(!harness.reconfigures_in_place(&chosen, &one_m)); + assert!(!harness.reconfigures_in_place(&one_m, &chosen)); + // Same `--model` and flags; only the 200K limit differs. + assert!(!harness.same_runtime(&chosen, &unset)); + assert!(harness.same_runtime(&unset, &with_options("claude-opus-5-5", json!({})))); + // The command carries it. + let env_of = |r: &RunRequest| { + let cmd = harness.build_command(&PathBuf::from("claude"), r, false); + cmd.as_std() + .get_envs() + .find(|(k, _)| *k == "CLAUDE_CODE_DISABLE_1M_CONTEXT") + .and_then(|(_, v)| v.map(|v| v.to_string_lossy().into_owned())) + }; + assert_eq!(env_of(&chosen).as_deref(), Some("1")); + assert_eq!(env_of(&one_m), None); + assert_eq!(env_of(&unset), None); + } + #[test] fn run_environment_forwards_subagent_text_and_leaves_the_launching_session() { let request = RunRequest { @@ -2471,6 +2565,14 @@ mod tests { .find(|(key, _)| *key == "CLAUDE_CODE_FORWARD_SUBAGENT_TEXT") .and_then(|(_, value)| value.map(|v| v.to_os_string())); assert_eq!(value.as_deref(), Some(std::ffi::OsStr::new("1"))); + // No Haiku session-title request of the CLI's own: Godspeed titles + // chats itself. + let title = cmd + .as_std_mut() + .get_envs() + .find(|(key, _)| *key == "CLAUDE_CODE_DISABLE_TERMINAL_TITLE") + .and_then(|(_, value)| value.map(|v| v.to_os_string())); + assert_eq!(title.as_deref(), Some(std::ffi::OsStr::new("1"))); // A Claude Code session that launched Godspeed exports these; a run // that inherits them joins that session. for key in [ diff --git a/crates/harness/src/lib.rs b/crates/harness/src/lib.rs index 9a4ed50c4..7f33d28aa 100644 --- a/crates/harness/src/lib.rs +++ b/crates/harness/src/lib.rs @@ -324,6 +324,7 @@ pub mod acp_registry; pub(crate) mod adapter_install; pub mod approval; pub mod archive_install; +pub mod bounded_file; pub mod build_env; mod catalog; mod catalog_failure; diff --git a/crates/harness/src/model_context.rs b/crates/harness/src/model_context.rs index 9bc11ef8a..7c01cb7b0 100644 --- a/crates/harness/src/model_context.rs +++ b/crates/harness/src/model_context.rs @@ -150,18 +150,32 @@ fn hash_files<'a>( ) -> Result<(), HarnessError> { for path in files { field(hash, path.as_os_str().as_encoded_bytes()); - match std::fs::read(path) { + // Some of these sit in the project (`opencode.json` up its tree), a + // repository anyone may have written: one that is a FIFO or a + // symlink to `/dev/zero` is refused, never read. + match crate::bounded_file::read(path, MAX_HASHED_FILE) { Ok(bytes) => { hash.update([1]); field(hash, &bytes); } Err(e) if e.kind() == std::io::ErrorKind::NotFound => hash.update([0]), + Err(e) + if matches!( + e.kind(), + std::io::ErrorKind::InvalidInput | std::io::ErrorKind::FileTooLarge + ) => + { + hash.update([2]); + } Err(e) => return Err(e.into()), } } Ok(()) } +/// The most of one config or credentials file hashed. +const MAX_HASHED_FILE: u64 = 16 * 1024 * 1024; + impl ModelContext { pub(crate) fn key(&self) -> [u8; 32] { Sha256::digest(self.hash.as_bytes()).into() @@ -193,4 +207,27 @@ mod tests { std::fs::remove_file(&file).unwrap(); assert_eq!(key(), missing); } + + /// A project's `opencode.json` that is a symlink to `/dev/zero` or a + /// FIFO is hashed as unreadable at once, never read. + #[cfg(unix)] + #[test] + fn a_config_that_is_a_device_or_a_fifo_is_not_read() { + let dir = tempfile::tempdir().unwrap(); + let zero = dir.path().join("opencode.json"); + std::os::unix::fs::symlink("/dev/zero", &zero).unwrap(); + let fifo = dir.path().join("opencode.jsonc"); + let c_path = std::ffi::CString::new(fifo.as_os_str().as_encoded_bytes()).unwrap(); + // SAFETY: a valid NUL-terminated path. + assert_eq!(unsafe { libc::mkfifo(c_path.as_ptr(), 0o600) }, 0); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let mut hash = Sha256::new(); + let _ = tx.send(hash_files(&mut hash, [zero, fifo].iter()).is_ok()); + }); + assert!( + rx.recv_timeout(std::time::Duration::from_secs(5)) + .expect("hashing the project's config hung") + ); + } } diff --git a/crates/harness/src/pi/catalog.rs b/crates/harness/src/pi/catalog.rs index be54aac47..ecb4bd8ff 100644 --- a/crates/harness/src/pi/catalog.rs +++ b/crates/harness/src/pi/catalog.rs @@ -17,15 +17,24 @@ pub(super) async fn models(process: &mut Process) -> Result, HarnessE .query(json!({"type":"get_available_models"}), &mut backlog) .await?; let mut result = vec![]; + let mut refused = None; for model in data["models"].as_array().into_iter().flatten() { let provider = string(model, "provider"); let id = string(model, "id"); - process - .query( + // Pi can list a model it then refuses (an extension that hides it a + // moment after startup). Skip that model; a broken process aborts. + if let Err(error) = process + .try_query( json!({"type":"set_model","provider":provider,"modelId":id}), &mut backlog, ) - .await?; + .await? + { + tracing::warn!(model = %format!("{provider}/{id}"), %error, "Pi refused a listed model; skipping it"); + refused.get_or_insert(error); + backlog.clear(); + continue; + } let supported = process .query( json!({"type":"get_available_thinking_levels"}), @@ -41,7 +50,10 @@ pub(super) async fn models(process: &mut Process) -> Result, HarnessE }); backlog.clear(); } - Ok(result) + match refused { + Some(error) if result.is_empty() => Err(error), + _ => Ok(result), + } } fn thinking_option(data: &Value) -> Vec { if !data["levels"] diff --git a/crates/harness/src/pi/mod.rs b/crates/harness/src/pi/mod.rs index 6b469a126..4b910d4c7 100644 --- a/crates/harness/src/pi/mod.rs +++ b/crates/harness/src/pi/mod.rs @@ -219,11 +219,20 @@ impl Process { command: Value, backlog: &mut Vec, ) -> Result { + self.try_query(command, backlog).await? + } + /// [`Self::query`], keeping Pi's own refusal (the inner `Err`) apart + /// from a broken process or pipe (the outer `Err`). + async fn try_query( + &mut self, + command: Value, + backlog: &mut Vec, + ) -> Result, HarnessError> { let id = self.transport.client.request(command)?; loop { let frame = self.next().await?; if frame["type"] == "response" && frame["id"] == id { - return response_data(frame); + return Ok(response_data(frame)); } if frame["type"] == "extension_ui_request" { self.dialogs.request(self.transport.client.clone(), &frame); diff --git a/crates/harness/tests/model_catalog.rs b/crates/harness/tests/model_catalog.rs index b8741faa3..cc467e3fe 100644 --- a/crates/harness/tests/model_catalog.rs +++ b/crates/harness/tests/model_catalog.rs @@ -219,3 +219,59 @@ fn each_spec_hashes_its_auth_file_contents() { String::from_utf8_lossy(&result.stdout) ); } + +/// A Pi that lists `state.models` and refuses `set_model` for those in +/// `state.refuse`; it exits on `set_model` for those in `state.crash`. +fn pi_binary(root: &Path) -> std::path::PathBuf { + use std::os::unix::fs::PermissionsExt; + let path = root.join("pi"); + std::fs::write(&path, r#"#!/usr/bin/python3 +import json, pathlib, sys +root = pathlib.Path(__file__).parent +if '--version' in sys.argv: + print('1.2.3') + sys.exit(0) +state = json.loads((root / 'state.json').read_text()) +for line in sys.stdin: + request = json.loads(line) + if 'id' not in request or 'type' not in request: continue + kind, data, ok, error = request['type'], {}, True, None + if kind == 'get_available_models': + data = {'models':[{'id':m,'provider':'fixture','name':m} for m in state['models']]} + if kind == 'get_available_thinking_levels': data = {'levels':['off']} + if kind == 'set_model': + if request['modelId'] in state.get('crash', []): sys.exit(1) + if request['modelId'] in state.get('refuse', []): + ok, error = False, 'Model not found: fixture/' + request['modelId'] + print(json.dumps({'id':request['id'],'type':'response','command':kind,'success':ok,'data':data,'error':error}), flush=True) +"#).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + path +} + +#[tokio::test] +async fn pi_discovery_skips_a_listed_model_that_set_model_refuses() { + let dir = tempfile::tempdir().unwrap(); + let binary = pi_binary(dir.path()); + let state = dir.path().join("state.json"); + let catalog = |json: &str| { + std::fs::write(&state, json).unwrap(); + // A fresh harness each time: no catalog cached from a previous case. + zeron_harness::PiHarness::new().with_executable(&binary) + }; + + let harness = catalog(r#"{"models":["first","gone","last"],"refuse":["gone"]}"#); + let found = harness.model_catalog(true).await.unwrap(); + assert_eq!(found.source, "live"); + let ids: Vec<_> = found.models.iter().map(|m| m.id.as_str()).collect(); + assert_eq!(ids, ["fixture/first", "fixture/last"]); + + // Every model refused: Pi's own reason, not an empty catalog. + let harness = catalog(r#"{"models":["a","b"],"refuse":["a","b"]}"#); + let error = harness.model_catalog(true).await.unwrap_err().to_string(); + assert!(error.contains("Model not found: fixture/a"), "{error}"); + + // Pi dying mid-discovery fails it, never a partial catalog. + let harness = catalog(r#"{"models":["first","boom","last"],"crash":["boom"]}"#); + assert!(harness.model_catalog(true).await.is_err()); +} diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index c57fe5874..b95fe9a73 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -497,6 +497,14 @@ chart5, chart6 (series, in order; \ chart1 is the accent). They follow the reader's theme, light or dark, on frosted glass or an opaque \ surface, so never assume a background color.\n\ \n\ +Hover must not move the page. A visual sits in a transcript, so anything you show only while the \ +pointer is on something (a custom readout, a detail line, a hint, a row's or canvas's hover state) must \ +not change the visual's height, or everything under it jumps as the pointer crosses it. Reserve its \ +space at rest (a placeholder or an empty line of the same height, e.g. ui.text { s.picked or \" \" }), \ +or draw it where it takes no layout space (inside a ui.canvas with g.pointer, or a scene point's hint). \ +Don't add or remove nodes, or lengthen text onto another line, on hover. ui.chart's hover readout \ +never changes the chart's height.\n\ +\n\ Style, enforced: layout nodes have no fill, border, shadow, padding, or font props. A visual is part \ of the reply, not a widget, so lay content directly on the chat with type, spacing, and alignment: no \ cards, tiles, boxed panels, banners, or canvas backgrounds. Stats are a row of plain ui.stat figures; \ diff --git a/crates/mobile/src/layout/rows.rs b/crates/mobile/src/layout/rows.rs index bb94a326a..41a1aeb1c 100644 --- a/crates/mobile/src/layout/rows.rs +++ b/crates/mobile/src/layout/rows.rs @@ -602,7 +602,10 @@ impl RowBuilder { let chipped = |path: &str| mentions.iter().any(|mention| mention.names_attachment(path)); let previews: Vec<(u32, String)> = mentions .iter() - .filter(|mention| mention.is_image) + .filter(|mention| { + mention.is_image + || zeron_proto::attachment_mentions::is_image_path(&mention.label) + }) .filter_map(|mention| { let image = parsed.images.iter().find(|image| mention.names_attachment(&image.path))?; Some((mention.index, image.path.clone())) @@ -698,14 +701,18 @@ fn user_chips(body: &str, previews: &[(u32, String)]) -> Vec { icon: if invocation.prefix() == '/' { "command" } else { "wand.and.stars" }.to_owned(), open: None, })); - chips.extend(zeron_proto::attachment_mentions::attachment_mentions(body).into_iter().map(|mention| UserChip { - range: mention.range, - icon: if mention.is_image { "photo".to_owned() } else { file_icon_asset(&mention.label) }, - open: previews - .iter() - .find(|(index, _)| mention.is_image && *index == mention.index) - .map(|(_, reference)| image_preview_link(reference)), - label: mention.label, + chips.extend(zeron_proto::attachment_mentions::attachment_mentions(body).into_iter().map(|mention| { + let is_image = mention.is_image + || zeron_proto::attachment_mentions::is_image_path(&mention.label); + UserChip { + range: mention.range, + icon: if is_image { "photo".to_owned() } else { file_icon_asset(&mention.label) }, + open: previews + .iter() + .find(|(index, _)| is_image && *index == mention.index) + .map(|(_, reference)| image_preview_link(reference)), + label: mention.label, + } })); chips.sort_by_key(|chip| chip.range.start); // Links never nest; drop any overlap rather than paint two chips at once. diff --git a/crates/preview/src/catalog.rs b/crates/preview/src/catalog.rs index 2c211e516..c171497f7 100644 --- a/crates/preview/src/catalog.rs +++ b/crates/preview/src/catalog.rs @@ -477,6 +477,7 @@ mod tests { started_at: pid as u64, address: ([127, 0, 0, 1], port).into(), zeron_owned: true, + test_run: false, } } #[test] diff --git a/crates/preview/src/discovery.rs b/crates/preview/src/discovery.rs index 0ee2977ca..92cf433a3 100644 --- a/crates/preview/src/discovery.rs +++ b/crates/preview/src/discovery.rs @@ -1,6 +1,7 @@ //! Observe only this user's listeners. HTTP probes run only after project //! ownership has been established from the process's actual working directory -//! and commands performing authentication have been excluded. +//! and commands performing authentication, and test runs with their fixture +//! servers, have been excluded. use std::{ collections::HashMap, net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}, @@ -18,6 +19,10 @@ pub struct Listener { pub started_at: u64, pub address: SocketAddr, pub zeron_owned: bool, + /// An ancestor of its process (up to this engine's own children) runs a + /// test runner ([`is_test_command`]): a fixture server the test spawned, + /// never probed. Its own command is checked by [`Self::is_test_run`]. + pub test_run: bool, } impl Listener { @@ -49,6 +54,160 @@ impl Listener { ) }) } + + /// A test suite's listener: its own command runs tests, or an ancestor's + /// does ([`Self::test_run`]). Test suites start scripted fixture servers + /// on loopback that answer a fixed number of connections; a probe would + /// take one of them and fail the test, so these are never connected to. + pub(crate) fn is_test_run(&self) -> bool { + self.test_run || is_test_command(&self.args) + } +} + +/// Programs that are test runners whatever their arguments. +const TEST_RUNNERS: &[&str] = &[ + "vitest", + "jest", + "mocha", + "_mocha", + "pytest", + "py.test", + "cargo-nextest", +]; +/// Test runners' packages, as a path's `node_modules/` (a runner's +/// own entry point or a worker it forks, run by `node`). +const TEST_RUNNER_PACKAGES: &[&str] = &[ + "vitest", + "@vitest", + "jest", + "jest-cli", + "jest-worker", + "@jest", + "mocha", +]; +/// Programs that run the next word as the command: `npx vitest`, +/// `python3 -m pytest`, `node /…/npm test`, `uv run pytest`. +const LAUNCHERS: &[&str] = &[ + "node", "nodejs", "npx", "bunx", "pnpx", "tsx", "ts-node", "env", "uv", "poetry", "pipenv", + "exec", "x", "dlx", "run", "sh", "bash", "zsh", +]; + +/// A program word's name: its file name, lowercased, without a script or +/// executable extension (`/…/node_modules/.bin/vitest.cmd` → `vitest`, +/// `/…/npm-cli.js` → `npm-cli`). +fn program_name(word: &str) -> String { + let name = Path::new(word) + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or(word) + .to_lowercase(); + for extension in [".js", ".mjs", ".cjs", ".ts", ".mts", ".exe", ".cmd"] { + if let Some(stem) = name.strip_suffix(extension) { + return stem.to_owned(); + } + } + name +} + +fn is_python(name: &str) -> bool { + name.strip_prefix("python") + .is_some_and(|version| version.chars().all(|c| c.is_ascii_digit() || c == '.')) +} + +/// A Rust test binary: cargo builds tests (unit and integration alike) into +/// `/[/]/deps/-<16 hex digits>`, and runs +/// them from there; binaries an app runs (`cargo run`) sit one level up. +fn is_rust_test_binary(program: &str) -> bool { + let path = Path::new(program); + if path.parent().and_then(Path::file_name) != Some(std::ffi::OsStr::new("deps")) { + return false; + } + let hashed = path + .file_name() + .and_then(|n| n.to_str()) + .map(|n| n.strip_suffix(".exe").unwrap_or(n)) + .and_then(|n| n.rsplit_once('-')) + .is_some_and(|(_, hash)| hash.len() == 16 && hash.chars().all(|c| c.is_ascii_hexdigit())); + hashed || path.components().any(|c| c.as_os_str() == "target") +} + +/// Whether `args` (a process's command line) runs tests: a Rust test binary +/// or libtest's flags, `cargo test`/`cargo nextest`, `go test` and its +/// `*.test` binaries, `bun test`, `deno test`, `npm|pnpm|yarn|bun [run] test`, +/// vitest, jest, mocha or pytest. Whole words and path components only, never +/// substrings: `node -e "require('vitest')"` or a project folder named +/// `tests` is no test run. Arguments after `--` belong to the program a +/// launcher runs, not to it, and are not read. +pub fn is_test_command(args: &[String]) -> bool { + let Some(program) = args.first() else { + return false; + }; + if is_rust_test_binary(program) + || args + .iter() + .take_while(|arg| *arg != "--") + .any(|arg| arg == "--test-threads" || arg.starts_with("--test-threads=")) + { + return true; + } + // Go's test binaries: `go test` builds `.test` and runs it. + if Path::new(program) + .file_name() + .and_then(|n| n.to_str()) + .and_then(|n| n.strip_suffix(".test")) + .is_some_and(|stem| !stem.is_empty()) + { + return true; + } + // The command's words: its arguments up to `--`, flags (and cargo's + // `+toolchain`) left out. + let words: Vec<&str> = args + .iter() + .map(String::as_str) + .take_while(|arg| *arg != "--") + .filter(|arg| !arg.starts_with('-') && !arg.starts_with('+')) + .collect(); + let names: Vec = words.iter().map(|word| program_name(word)).collect(); + let script = |name: Option<&String>| { + name.is_some_and(|name| name == "test" || name.starts_with("test:")) + }; + for (i, name) in names.iter().enumerate() { + // A word naming a program: the first, or one a launcher runs. + let command = + i == 0 || LAUNCHERS.contains(&names[i - 1].as_str()) || is_python(&names[i - 1]); + if command && TEST_RUNNERS.contains(&name.as_str()) { + return true; + } + let path = Path::new(words[i]); + let mut components = path + .components() + .map(|c| c.as_os_str().to_str().unwrap_or("")); + let mut previous = ""; + let in_runner_package = components.any(|component| { + let found = previous == "node_modules" && TEST_RUNNER_PACKAGES.contains(&component); + previous = component; + found + }); + if in_runner_package { + return true; + } + let next = names.get(i + 1); + let tested = match name.as_str() { + "cargo" => next.is_some_and(|n| matches!(n.as_str(), "test" | "t" | "nextest")), + "go" | "deno" => next.is_some_and(|n| n == "test"), + "npm" | "npm-cli" | "pnpm" | "yarn" | "bun" => { + script(next) + || (name.starts_with("npm") && next.is_some_and(|n| n == "t")) + || (next.is_some_and(|n| n == "run" || n == "run-script") + && script(names.get(i + 2))) + } + _ => false, + }; + if tested { + return true; + } + } + false } /// Preserve a useful framework label without advertising process arguments, @@ -157,6 +316,49 @@ fn mark_descendants(listeners: &mut [Listener], parents: &HashMap, own } } +/// Flags each listener whose process has an ancestor running tests +/// ([`is_test_command`]): a fixture server is often a plain python/node child +/// of the test. The walk stops at this engine's own children (an agent, a +/// terminal's shell): an agent may carry its prompt in its arguments ("run +/// npm test, then start the dev server"), and everything it starts would be +/// hidden for its lifetime. +fn mark_test_runs( + listeners: &mut [Listener], + parents: &HashMap, + commands: &HashMap>, +) { + let engine = std::process::id(); + let mut verdicts: HashMap = HashMap::new(); + for listener in listeners { + let Some(&first) = parents.get(&listener.pid) else { + continue; + }; + let mut pid = first; + for _ in 0..64 { + if pid <= 1 || pid == engine { + break; + } + let Some(&parent) = parents.get(&pid) else { + break; + }; + if parent == engine { + break; + } + let test = *verdicts + .entry(pid) + .or_insert_with(|| commands.get(&pid).is_some_and(|args| is_test_command(args))); + if test { + listener.test_run = true; + break; + } + if parent == pid { + break; + } + pid = parent; + } + } +} + /// Process start in ms since the epoch, derived the same way for the scanner /// and for [`same_process`] so the two agree exactly. #[cfg(target_os = "linux")] @@ -222,6 +424,7 @@ pub fn listeners() -> Vec { let uid = unsafe { libc::geteuid() }; let mut result = Vec::new(); let mut parents = HashMap::new(); + let mut commands = HashMap::new(); let Ok(processes) = fs::read_dir("/proc") else { return result; }; @@ -244,16 +447,17 @@ pub fn listeners() -> Vec { continue; }; parents.insert(pid, parent); - let Ok(cwd) = fs::read_link(path.join("cwd")) else { - continue; - }; - let started_at = linux_started_at(&fields, boot, ticks); let args = fs::read(path.join("cmdline")) .unwrap_or_default() .split(|b| *b == 0) .filter(|b| !b.is_empty()) .map(|b| String::from_utf8_lossy(b).into_owned()) .collect::>(); + commands.insert(pid, args.clone()); + let Ok(cwd) = fs::read_link(path.join("cwd")) else { + continue; + }; + let started_at = linux_started_at(&fields, boot, ticks); let Ok(fds) = fs::read_dir(path.join("fd")) else { continue; }; @@ -277,11 +481,13 @@ pub fn listeners() -> Vec { started_at, address, zeron_owned: false, + test_run: false, }); } } } mark_descendants(&mut result, &parents, std::process::id()); + mark_test_runs(&mut result, &parents, &commands); result.sort_by_key(|l| (l.address, l.pid)); result.dedup_by_key(|l| (l.address, l.pid)); result @@ -438,10 +644,16 @@ pub fn listeners() -> Vec { started_at: *started_at, address, zeron_owned: false, + test_run: false, }); } } mark_descendants(&mut result, &parents, std::process::id()); + let commands: HashMap> = processes + .into_iter() + .map(|(pid, (_, _, args))| (pid, args)) + .collect(); + mark_test_runs(&mut result, &parents, &commands); result } @@ -457,6 +669,182 @@ pub fn same_process(_pid: u32, _started_at: u64) -> bool { #[cfg(test)] mod tests { use super::*; + fn listener_of(pid: u32) -> Listener { + Listener { + pid, + parent: 0, + cwd: "/project".into(), + args: Vec::new(), + started_at: 0, + address: "127.0.0.1:3000".parse().unwrap(), + zeron_owned: false, + test_run: false, + } + } + /// A fixture's own command says nothing; the test runner above it does. + /// The walk stops at this engine's own children, whose arguments (an + /// agent's prompt) are never judged. + #[test] + fn a_listener_under_a_test_runner_is_a_test_run() { + let engine = std::process::id(); + let args = |words: &[&str]| words.iter().map(|w| (*w).to_string()).collect::>(); + // engine -> agent (prompt mentions `npm test`) -> runner -> fixture + // engine -> agent -> shell -> dev server + let parents = HashMap::from([(10, engine), (11, 10), (12, 11), (20, 10), (21, 20)]); + let commands = HashMap::from([ + (10, args(&["claude", "-p", "run", "npm", "test"])), + (11, args(&["npx", "vitest", "run"])), + (12, args(&["python3", "fixture.py"])), + (20, args(&["bash"])), + (21, args(&["vite"])), + ]); + let mut listeners = vec![ + Listener { + parent: 11, + ..listener_of(12) + }, + Listener { + parent: 20, + ..listener_of(21) + }, + Listener { + parent: engine, + ..listener_of(10) + }, + ]; + mark_test_runs(&mut listeners, &parents, &commands); + let verdicts: Vec<_> = listeners.iter().map(|l| (l.pid, l.test_run)).collect(); + assert_eq!(verdicts, vec![(12, true), (21, false), (10, false)]); + } + #[test] + fn test_runs_are_not_preview_candidates() { + let listener = |args: &[&str]| Listener { + args: args.iter().map(|arg| (*arg).into()).collect(), + ..listener_of(1) + }; + for args in [ + // Rust: a test binary (unit or integration), libtest's flags, + // cargo and nextest themselves. + vec!["/work/app/target/debug/deps/app-0123456789abcdef"], + vec![ + "/work/app/target/debug/deps/api_tests-89ab01cd23ef4567", + "--nocapture", + ], + vec!["/tmp/cargo-target/aarch64-apple-darwin/release/deps/app-0123456789abcdef"], + vec!["/work/app/target/debug/deps/fixtures"], + vec!["/work/app/target/debug/app", "--test-threads=1"], + vec!["./runner", "--test-threads", "4"], + vec!["cargo", "test"], + vec![ + "/Users/me/.cargo/bin/cargo", + "+nightly", + "test", + "-p", + "api", + ], + vec!["cargo", "t"], + vec!["cargo", "nextest", "run"], + vec!["/Users/me/.cargo/bin/cargo-nextest", "nextest", "run"], + // JavaScript. + vec!["bun", "test"], + vec!["/Users/me/.bun/bin/bun", "test", "--watch"], + vec!["bun", "run", "test"], + vec!["npm", "test"], + vec!["npm", "t"], + vec!["node", "/usr/local/bin/npm", "run", "test:unit"], + vec![ + "node", + "/usr/local/lib/node_modules/npm/bin/npm-cli.js", + "test", + ], + vec!["pnpm", "test"], + vec!["pnpm", "run", "test"], + vec!["yarn", "test"], + vec!["yarn", "run", "test:e2e"], + vec!["vitest"], + vec!["vitest", "run"], + vec!["node", "/work/app/node_modules/.bin/vitest", "run"], + vec!["node", "/work/app/node_modules/vitest/vitest.mjs", "run"], + vec![ + "node", + "/work/app/node_modules/vitest/dist/workers/forks.js", + ], + vec!["npx", "vitest"], + vec!["bunx", "jest"], + vec!["jest", "--runInBand"], + vec![ + "node", + "--expose-gc", + "/work/app/node_modules/jest/bin/jest.js", + ], + vec![ + "/usr/local/bin/node", + "/work/app/node_modules/jest-worker/build/workers/processChild.js", + ], + vec!["mocha", "test/**/*.spec.js"], + vec!["node", "/work/app/node_modules/mocha/bin/_mocha"], + vec!["deno", "test", "--allow-net"], + // Python and Go. + vec!["pytest", "-x", "tests/"], + vec!["/work/app/.venv/bin/pytest"], + vec!["python3", "-m", "pytest", "-k", "fixture"], + vec!["/usr/bin/python3.12", "-m", "pytest"], + vec!["uv", "run", "pytest"], + vec!["py.test"], + vec!["go", "test", "./..."], + vec!["/tmp/go-build2214/b001/server.test", "-test.v"], + ] { + assert!(listener(&args).is_test_run(), "{args:?}"); + } + for args in [ + vec![], + // Dev servers stay eligible. + vec!["vite"], + vec![ + "node", + "/work/app/node_modules/vite/bin/vite.js", + "--port", + "5173", + ], + vec!["node", "/work/app/node_modules/.bin/next", "dev"], + vec!["next", "dev"], + vec!["next-server"], + vec!["bun", "run", "dev"], + vec!["bun", "--hot", "server.ts"], + vec!["npm", "run", "dev"], + vec!["npm", "start"], + vec!["pnpm", "dev"], + vec!["yarn", "start"], + vec!["python", "-m", "http.server", "8000"], + vec!["python3", "manage.py", "runserver"], + vec!["deno", "run", "-A", "main.ts"], + vec!["go", "run", "./cmd/server"], + vec!["/work/app/target/debug/server"], + vec!["cargo", "run", "--bin", "server"], + vec!["cargo", "watch", "-x", "run"], + // Whole words and path components, not substrings. + vec!["node", "-e", "require('vitest')"], + vec!["node", "/work/tests/server.js"], + vec!["node", "/work/app/test/fixtures/server.js"], + vec!["node", "/work/vitest-demo/server.js"], + vec!["node", "/work/jest/server.js"], + vec!["python3", "/work/pytest_plugins/serve.py"], + vec!["node", "server.js", "--", "--test-threads", "1"], + vec!["./serve", "--mode", "test"], + vec!["/work/app/target/debug/deps"], + vec!["/work/app/deps/server"], + vec!["/work/.test"], + ] { + assert!(!listener(&args).is_test_run(), "{args:?}"); + } + // An ancestor found running tests counts too. + let fixture = Listener { + args: vec!["python3".into(), "fixture.py".into()], + test_run: true, + ..listener_of(1) + }; + assert!(fixture.is_test_run()); + } #[test] fn authentication_commands_are_not_preview_candidates() { let listener = |args: &[&str]| Listener { @@ -467,6 +855,7 @@ mod tests { started_at: 1, address: "127.0.0.1:3000".parse().unwrap(), zeron_owned: true, + test_run: false, }; for args in [ vec!["/usr/bin/infisical", "login"], diff --git a/crates/preview/src/service.rs b/crates/preview/src/service.rs index 4714fb9bf..02b28ce46 100644 --- a/crates/preview/src/service.rs +++ b/crates/preview/src/service.rs @@ -26,10 +26,28 @@ use tokio_util::sync::CancellationToken; /// cycle already proves the same process still owns the same port. Sockets /// that did not answer HTTP (a server bound but not yet serving) are retried /// with a capped exponential backoff instead of on every cycle. +/// +/// Nor is a socket probed before it has stayed up [`PROBE_SETTLE`]: a test +/// suite's fixture server answers a scripted number of connections and is +/// gone in moments, and a probe taking one of them fails the test. #[derive(Default)] pub(crate) struct ProbeMemory { verdicts: HashMap<(u32, u64, SocketAddr), Verdict>, + /// When each listed socket was first seen by a scan. + first_seen: HashMap<(u32, u64, SocketAddr), Instant>, } +/// How long a listener must have stayed up (seen by an earlier scan, this +/// long before) before discovery connects to it. A test's fixture server +/// lives for its test, milliseconds to a second or two, while a dev server +/// stays up for minutes or hours, so 3 s spares nearly every fixture (those +/// of test runners Godspeed recognises are never probed at all: +/// [`discovery::Listener::is_test_run`]) and costs a dev server about 3 s +/// before it is listed. It is above [`ACTIVE_SCAN`], so a listener is never +/// probed by the scan right after the one that first saw it. +const PROBE_SETTLE: Duration = Duration::from_secs(3); +/// The least wait before the scan that probes a listener done settling +/// (its time may have come while this scan probed others). +const SETTLED_RESCAN_MIN: Duration = Duration::from_millis(100); enum Verdict { Http, NotHttp { @@ -69,8 +87,16 @@ pub(crate) fn scan_delay( const NOT_HTTP_INITIAL_BACKOFF: Duration = Duration::from_secs(4); const NOT_HTTP_MAX_BACKOFF: Duration = Duration::from_secs(60); -/// (servers already confirmed HTTP, listeners to probe this cycle) -type Planned = (Vec<(T, discovery::Listener)>, Vec<(T, discovery::Listener)>); +/// One cycle's candidates, sorted by [`ProbeMemory::plan`]. +pub(crate) struct Planned { + /// Servers already confirmed HTTP. + pub known: Vec<(T, discovery::Listener)>, + /// Listeners to probe this cycle. + pub probe: Vec<(T, discovery::Listener)>, + /// When the first listener still settling ([`PROBE_SETTLE`]) may be + /// probed: the scan after that lists it. + pub settling_until: Option, +} fn probe_key(listener: &discovery::Listener) -> (u32, u64, SocketAddr) { (listener.pid, listener.started_at, listener.address) @@ -78,8 +104,10 @@ fn probe_key(listener: &discovery::Listener) -> (u32, u64, SocketAddr) { impl ProbeMemory { /// Splits this cycle's candidates into servers already known to speak - /// HTTP and listeners that need a probe now. Verdicts for sockets that - /// are no longer listed are forgotten so a reused port is probed afresh. + /// HTTP, listeners that need a probe now, and listeners not up long + /// enough to probe yet ([`PROBE_SETTLE`]). Sockets that are no longer + /// listed are forgotten (their verdicts and when they were first seen) + /// so a reused port is probed afresh, after settling afresh. pub(crate) fn plan( &mut self, candidates: Vec<(T, discovery::Listener)>, @@ -88,16 +116,31 @@ impl ProbeMemory { let present: std::collections::HashSet<_> = candidates.iter().map(|(_, l)| probe_key(l)).collect(); self.verdicts.retain(|key, _| present.contains(key)); - let mut known = Vec::new(); - let mut probe = Vec::new(); + self.first_seen.retain(|key, _| present.contains(key)); + let mut planned = Planned { + known: Vec::new(), + probe: Vec::new(), + settling_until: None, + }; for candidate in candidates { - match self.verdicts.get(&probe_key(&candidate.1)) { - Some(Verdict::Http) => known.push(candidate), + let key = probe_key(&candidate.1); + // First seen by this scan: an earlier one must have seen it too, + // PROBE_SETTLE before, for it to be probed. + let eligible = *self.first_seen.entry(key).or_insert(now) + PROBE_SETTLE; + match self.verdicts.get(&key) { + Some(Verdict::Http) => planned.known.push(candidate), Some(Verdict::NotHttp { retry_at, .. }) if *retry_at > now => {} - _ => probe.push(candidate), + _ if eligible > now => { + planned.settling_until = Some( + planned + .settling_until + .map_or(eligible, |until| until.min(eligible)), + ); + } + _ => planned.probe.push(candidate), } } - (known, probe) + planned } pub(crate) fn record(&mut self, listener: &discovery::Listener, http: bool, now: Instant) { let key = probe_key(listener); @@ -360,6 +403,7 @@ impl PreviewService { l.address.port() != zeron_proto::PREVIEW_PROXY_PORT && l.pid != std::process::id() && !l.is_authentication_command() + && !l.is_test_run() }) .filter_map(|listener| { roots @@ -372,7 +416,11 @@ impl PreviewService { }) .await .unwrap_or_default(); - let (mut servers, probe) = memory.plan(candidates, Instant::now()); + let Planned { + known: mut servers, + probe, + settling_until, + } = memory.plan(candidates, Instant::now()); let probed: Vec<_> = stream::iter(probe) .map(|(root, listener)| async move { let http = discovery::is_http(listener.address).await; @@ -391,9 +439,20 @@ impl PreviewService { if let Err(error) = catalog.replace_local(servers) { tracing::warn!(%error, "could not update preview services"); } + settling_until }; - tokio::select! { _ = stop.cancelled() => break, _ = scan => {} } - let delay = service.scan_delay(); + let settling_until = + tokio::select! { _ = stop.cancelled() => break, until = scan => until }; + let mut delay = service.scan_delay(); + // A listener waiting out PROBE_SETTLE is probed by the first + // scan after it may be, however slow the cadence is. + if let Some(until) = settling_until { + delay = delay.min( + until + .saturating_duration_since(Instant::now()) + .max(SETTLED_RESCAN_MIN), + ); + } tokio::select! { _ = stop.cancelled() => break, _ = tokio::time::sleep(delay) => {} @@ -478,6 +537,7 @@ mod tests { started_at: 1_000, address: ([127, 0, 0, 1], port).into(), zeron_owned: false, + test_run: false, } } #[test] @@ -512,53 +572,146 @@ mod tests { assert_eq!(service.scan_delay(), QUIET_SCAN); } + fn at(t0: Instant, secs: u64) -> Instant { + t0 + Duration::from_secs(secs) + } #[test] fn a_confirmed_http_server_is_never_probed_again() { let mut memory = ProbeMemory::default(); let t0 = Instant::now(); - let (known, probe) = memory.plan(vec![((), listener(7, 8081))], t0); - assert!(known.is_empty()); - assert_eq!(probe.len(), 1); - memory.record(&probe[0].1, true, t0); - for cycle in 1..1_000u64 { - let now = t0 + Duration::from_secs(2 * cycle); - let (known, probe) = memory.plan(vec![((), listener(7, 8081))], now); - assert_eq!(known.len(), 1, "cycle {cycle} must reuse the verdict"); - assert!(probe.is_empty(), "cycle {cycle} must not send a request"); + let planned = memory.plan(vec![((), listener(7, 8081))], t0); + assert!( + planned.known.is_empty() && planned.probe.is_empty(), + "settling" + ); + let planned = memory.plan(vec![((), listener(7, 8081))], at(t0, 3)); + assert!(planned.known.is_empty()); + assert_eq!(planned.probe.len(), 1); + memory.record(&planned.probe[0].1, true, at(t0, 3)); + for cycle in 2..1_000u64 { + let now = at(t0, 2 * cycle); + let planned = memory.plan(vec![((), listener(7, 8081))], now); + assert_eq!( + planned.known.len(), + 1, + "cycle {cycle} must reuse the verdict" + ); + assert!( + planned.probe.is_empty(), + "cycle {cycle} must not send a request" + ); + assert_eq!(planned.settling_until, None); } } #[test] fn non_http_listeners_back_off_and_reused_ports_are_probed_afresh() { let mut memory = ProbeMemory::default(); let t0 = Instant::now(); - let (_, probe) = memory.plan(vec![((), listener(7, 8081))], t0); - memory.record(&probe[0].1, false, t0); - let (_, probe) = memory.plan(vec![((), listener(7, 8081))], t0 + Duration::from_secs(2)); - assert!(probe.is_empty(), "the very next cycle is skipped"); - let (_, probe) = memory.plan(vec![((), listener(7, 8081))], t0 + Duration::from_secs(5)); - assert_eq!(probe.len(), 1, "retried after the initial backoff"); - memory.record(&probe[0].1, false, t0 + Duration::from_secs(5)); - let (_, probe) = memory.plan(vec![((), listener(7, 8081))], t0 + Duration::from_secs(10)); - assert!(probe.is_empty(), "backoff doubled"); - // A different process on the same port carries no verdict over. - let (_, probe) = memory.plan(vec![((), listener(8, 8081))], t0 + Duration::from_secs(10)); - assert_eq!(probe.len(), 1); - // The original socket, once absent, is forgotten and re-probed on return. - memory.record(&probe[0].1, true, t0); - let (known, probe) = - memory.plan(vec![((), listener(7, 8081))], t0 + Duration::from_secs(11)); - assert!(known.is_empty()); - assert_eq!(probe.len(), 1); + let probe = |memory: &mut ProbeMemory, pid, secs| { + memory + .plan(vec![((), listener(pid, 8081))], at(t0, secs)) + .probe + }; + assert!(probe(&mut memory, 7, 0).is_empty(), "settling"); + let probed = probe(&mut memory, 7, 3); + assert_eq!(probed.len(), 1); + memory.record(&probed[0].1, false, at(t0, 3)); + assert!( + probe(&mut memory, 7, 5).is_empty(), + "the very next cycle is skipped" + ); + let probed = probe(&mut memory, 7, 8); + assert_eq!(probed.len(), 1, "retried after the initial backoff"); + memory.record(&probed[0].1, false, at(t0, 8)); + assert!(probe(&mut memory, 7, 13).is_empty(), "backoff doubled"); + // A different process on the same port carries nothing over: no + // verdict, and not the time the first was seen either. + assert!( + probe(&mut memory, 8, 13).is_empty(), + "a new listener settles first" + ); + let probed = probe(&mut memory, 8, 16); + assert_eq!(probed.len(), 1); + memory.record(&probed[0].1, true, at(t0, 16)); + // The original socket, once absent, is forgotten: settled and + // probed afresh on its return. + assert!(probe(&mut memory, 7, 17).is_empty()); + let planned = memory.plan(vec![((), listener(7, 8081))], at(t0, 20)); + assert!(planned.known.is_empty()); + assert_eq!(planned.probe.len(), 1); + } + /// A listener is probed only once it has stayed up PROBE_SETTLE: seen by + /// an earlier scan that long ago. A test's fixture server, up for a + /// moment, is never connected to. + #[test] + fn listeners_are_probed_only_once_they_have_stayed_up() { + let t0 = Instant::now(); + // Seen once, however late the scan: an earlier scan must have seen it. + let mut memory = ProbeMemory::default(); + let planned = memory.plan(vec![((), listener(7, 8081))], at(t0, 60)); + assert!(planned.probe.is_empty()); + assert_eq!(planned.settling_until, Some(at(t0, 60) + PROBE_SETTLE)); + // A fixture up across two scans, gone by the third: never probed. + let mut memory = ProbeMemory::default(); + for secs in [0, 2] { + assert!( + memory + .plan(vec![((), listener(7, 8081))], at(t0, secs)) + .probe + .is_empty() + ); + } + let planned = memory.plan(Vec::<((), _)>::new(), at(t0, 4)); + assert!(planned.probe.is_empty() && planned.settling_until.is_none()); + // Back again (the next test's fixture on the same port, say): it + // settles afresh, not from when the first was seen. + assert!( + memory + .plan(vec![((), listener(7, 8081))], at(t0, 6)) + .probe + .is_empty() + ); + assert!( + memory + .plan(vec![((), listener(7, 8081))], at(t0, 8)) + .probe + .is_empty() + ); + assert_eq!( + memory + .plan(vec![((), listener(7, 8081))], at(t0, 9)) + .probe + .len(), + 1 + ); + // Just short of PROBE_SETTLE is not enough; the earliest listener + // still settling says when the next scan is due. + let mut memory = ProbeMemory::default(); + memory.plan(vec![((), listener(7, 8081))], t0); + let both = || vec![((), listener(7, 8081)), ((), listener(9, 8082))]; + let planned = memory.plan(both(), at(t0, 2)); + assert_eq!(planned.settling_until, Some(t0 + PROBE_SETTLE)); + let planned = memory.plan(both(), t0 + PROBE_SETTLE - Duration::from_millis(1)); + assert!(planned.probe.is_empty()); + let planned = memory.plan(both(), t0 + PROBE_SETTLE); + assert_eq!(planned.probe.len(), 1); + assert_eq!(planned.probe[0].1.pid, 7); + assert_eq!(planned.settling_until, Some(at(t0, 2) + PROBE_SETTLE)); + assert!( + PROBE_SETTLE > ACTIVE_SCAN, + "never the scan right after the first sighting" + ); } #[test] fn backoff_is_capped() { let mut memory = ProbeMemory::default(); let mut now = Instant::now(); + memory.plan(vec![((), listener(7, 8081))], now); for _ in 0..20 { memory.record(&listener(7, 8081), false, now); now += NOT_HTTP_MAX_BACKOFF; } - let (_, probe) = memory.plan(vec![((), listener(7, 8081))], now); + let probe = memory.plan(vec![((), listener(7, 8081))], now).probe; assert_eq!(probe.len(), 1, "still retried once per max backoff"); } } diff --git a/crates/preview/tests/coordinator.rs b/crates/preview/tests/coordinator.rs index ba9e77d25..73d4a5512 100644 --- a/crates/preview/tests/coordinator.rs +++ b/crates/preview/tests/coordinator.rs @@ -51,7 +51,7 @@ async fn authenticated_coordinator_pairs_devices_for_large_http_preview() { for _ in 0..512 { socket.write_all(&[42;8192]).await.unwrap(); } socket.shutdown().await.unwrap(); }); - host.replace_local(vec![("/work/project".into(),Listener { pid:std::process::id(),parent:1,cwd:"/work/project".into(),args:vec!["node".into(),"vite".into()],started_at:1,address,zeron_owned:true })]).unwrap(); + host.replace_local(vec![("/work/project".into(),Listener { pid:std::process::id(),parent:1,cwd:"/work/project".into(),args:vec!["node".into(),"vite".into()],started_at:1,address,zeron_owned:true,test_run:false })]).unwrap(); let host_backend = Arc::new(Backend(host.clone())); let viewer_backend = Arc::new(Backend(viewer.clone())); let (host_peers, host_output) = Peers::new("host".into(),host_backend,stop.child_token()); let (viewer_peers, viewer_output) = Peers::new("viewer".into(),viewer_backend.clone(),stop.child_token()); diff --git a/crates/preview/tests/discovery.rs b/crates/preview/tests/discovery.rs index 3d511e77c..e8a43a1d0 100644 --- a/crates/preview/tests/discovery.rs +++ b/crates/preview/tests/discovery.rs @@ -34,8 +34,11 @@ fn launch(cwd: &std::path::Path, http: bool) -> Child { .unwrap(), ) } +/// How long discovery may take to list a server: a listener is probed only +/// once it has stayed up 3 s, and a busy machine slows every scan. +const CONVERGE: Duration = Duration::from_secs(30); async fn wait(service: &PreviewService, expected_pid: Option) { - tokio::time::timeout(Duration::from_secs(12), async { + tokio::time::timeout(CONVERGE, async { loop { let services = service.catalog().snapshot().services; if match expected_pid { diff --git a/crates/preview/tests/leak.rs b/crates/preview/tests/leak.rs index 9efbb1b0c..2fa1ac82f 100644 --- a/crates/preview/tests/leak.rs +++ b/crates/preview/tests/leak.rs @@ -174,6 +174,7 @@ async fn remote_preview_churn_does_not_accumulate_tasks_or_memory() { started_at: 1, address: ([127, 0, 0, 1], backend_port).into(), zeron_owned: true, + test_run: false, }, )]) .unwrap(); diff --git a/crates/preview/tests/proxy.rs b/crates/preview/tests/proxy.rs index 3ce14a772..8b3912e4d 100644 --- a/crates/preview/tests/proxy.rs +++ b/crates/preview/tests/proxy.rs @@ -160,6 +160,7 @@ fn observe(catalog: &Catalog, port: u16, pid: u32) { started_at: pid as u64, address: ([127, 0, 0, 1], port).into(), zeron_owned: true, + test_run: false, }, )]) .unwrap(); diff --git a/crates/rpc/src/device_room.rs b/crates/rpc/src/device_room.rs index 94a61c8e7..963cabb3f 100644 --- a/crates/rpc/src/device_room.rs +++ b/crates/rpc/src/device_room.rs @@ -456,9 +456,10 @@ fn jitter() -> Duration { /// ([`serve_connection`]); its replies are pumped back as `{to: connId}` frames. /// /// Teardown is by channel closure, NOT task abort: dropping `in_tx` ends the dispatch -/// loop, which aborts its in-flight request tasks (streams included); their reply senders -/// drop and the pump task drains out. Aborting the dispatch loop directly would strand -/// the request tasks it spawned. +/// loop, which aborts its in-flight request tasks (streams included) and lets each +/// terminal's input lane finish what was already sent; their reply senders drop and the +/// pump task drains out. Aborting the dispatch loop directly would strand the request +/// tasks it spawned. struct VirtualConn { in_tx: mpsc::Sender, } diff --git a/crates/rpc/src/server.rs b/crates/rpc/src/server.rs index 11196acc3..3bc3f4b14 100644 --- a/crates/rpc/src/server.rs +++ b/crates/rpc/src/server.rs @@ -13,14 +13,48 @@ use tokio_tungstenite::tungstenite::http::StatusCode; use crate::{ClientFrame, RpcError, RpcReply, RpcService, ServerFrame}; +/// The terminal a call must take effect in order for: its input and size. +/// Each other call runs on a task of its own, and tasks spawned back to back +/// start in no set order (tokio runs the newest first), so two writes would +/// reach the terminal swapped: keys typed or pasted out of order, and a +/// viewer's answers to a program's queries (a colour, then the cursor) read +/// the wrong way round, the rest left as typed keys. +fn ordered(method: &str, params: &serde_json::Value) -> Option { + matches!( + method, + crate::methods::WRITE_TERMINAL | crate::methods::RESIZE_TERMINAL + ) + .then(|| params["terminalId"].as_str().unwrap_or_default().to_owned()) +} + +/// One terminal's [`ordered`] calls, in the order the connection sent them. +type Lane = mpsc::UnboundedSender<(u64, String, serde_json::Value)>; + +/// Runs a lane's calls one after another; each answer is sent beside it, so +/// a client slow to read answers doesn't hold the next write back. Ends once +/// its sender is gone and what was queued has run. +fn lane(service: Arc, out: mpsc::Sender) -> Lane { + let (lane, mut queued) = mpsc::unbounded_channel::<(u64, String, serde_json::Value)>(); + tokio::spawn(async move { + while let Some((id, method, params)) = queued.recv().await { + let result = service.handle(&method, params).await; + tokio::spawn(respond(out.clone(), id, method, result)); + } + }); + lane +} + /// Serve one connection: read client frames from `inbound`, write server frames to `out`. -/// Returns when `inbound` closes; all in-flight request tasks are aborted on exit. +/// Returns when `inbound` closes; all in-flight request tasks are aborted on exit, but +/// a terminal's input already sent still goes in ([`ordered`] calls: one lane a +/// terminal, each one after another in the order sent, beside the rest). pub async fn serve_connection( service: Arc, out: mpsc::Sender, mut inbound: mpsc::Receiver, ) { let mut running: HashMap = HashMap::new(); + let mut lanes: HashMap = HashMap::new(); while let Some(payload) = inbound.recv().await { // ndjson: a transport may batch several frames per message. for line in payload.lines() { @@ -46,6 +80,13 @@ pub async fn serve_connection( tracing::warn!(id = frame.id, "rpc: frame has neither method nor cancel"); continue; }; + if let Some(terminal) = ordered(&method, &frame.params) { + let queue = lanes + .entry(terminal) + .or_insert_with(|| lane(service.clone(), out.clone())); + let _ = queue.send((frame.id, method, frame.params)); + continue; + } let task = tokio::spawn(handle_request( service.clone(), out.clone(), @@ -59,6 +100,8 @@ pub async fn serve_connection( for (_, task) in running { task.abort(); } + // (Each lane ends once what was queued has gone in.) + drop(lanes); } async fn handle_request( @@ -67,6 +110,17 @@ async fn handle_request( id: u64, method: String, params: serde_json::Value, +) { + let result = service.handle(&method, params).await; + respond(out, id, method, result).await; +} + +/// Send a call's answer: its value, its stream's items, or its error. +async fn respond( + out: mpsc::Sender, + id: u64, + method: String, + result: Result, ) { let send = |frame: ServerFrame| { let out = out.clone(); @@ -80,7 +134,7 @@ async fn handle_request( } } }; - match service.handle(&method, params).await { + match result { Ok(RpcReply::Value(value)) => { let _ = send(ServerFrame { id, @@ -335,3 +389,117 @@ async fn serve_ws_socket(stream: TcpStream, service: Arc) { serve_connection(service, out_tx, in_rx).await; pump.abort(); } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Mutex; + use std::time::Duration; + + /// Records the order calls reach it in, by terminal; a call for the + /// terminal "stuck" never finishes (a write to a program that never + /// reads). + struct Recorder(Mutex>); + + #[async_trait::async_trait] + impl RpcService for Recorder { + async fn handle( + &self, + _method: &str, + params: serde_json::Value, + ) -> Result { + let terminal = params["terminalId"].as_str().unwrap_or_default().to_owned(); + if terminal == "stuck" { + std::future::pending::<()>().await; + } + // (A call that yields first, as a real one may.) + tokio::task::yield_now().await; + let n = params["n"].as_u64().unwrap_or_default(); + self.0.lock().unwrap().push((terminal, n)); + Ok(RpcReply::Value(serde_json::json!({}))) + } + } + + fn connect() -> (Arc, mpsc::Sender, mpsc::Receiver) { + let recorder = Arc::new(Recorder(Mutex::new(Vec::new()))); + let (to_server, server_in) = mpsc::channel::(4096); + let (server_out, from_server) = mpsc::channel::(4096); + tokio::spawn(serve_connection(recorder.clone(), server_out, server_in)); + (recorder, to_server, from_server) + } + + fn call(id: u64, method: &str, terminal: &str, n: u64) -> String { + serde_json::json!({ "id": id, "method": method, "params": { "terminalId": terminal, "n": n } }) + .to_string() + } + + fn seen(recorder: &Recorder, terminal: &str) -> Vec { + let calls = recorder.0.lock().unwrap(); + calls.iter().filter(|(t, _)| t == terminal).map(|(_, n)| *n).collect() + } + + /// A terminal's input and size reach the service in the order sent, + /// however many come back to back, two terminals' interleaved. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_terminal_s_writes_and_resizes_arrive_in_the_order_sent() { + let (recorder, to_server, mut from_server) = connect(); + const CALLS: u64 = 400; + for n in 0..CALLS { + let method = if n % 7 == 3 { + crate::methods::RESIZE_TERMINAL + } else { + crate::methods::WRITE_TERMINAL + }; + let terminal = if n % 3 == 0 { "b" } else { "a" }; + to_server.send(call(n + 1, method, terminal, n)).await.unwrap(); + } + for _ in 0..CALLS { + tokio::time::timeout(Duration::from_secs(10), from_server.recv()) + .await + .expect("every call answered") + .expect("connection up"); + } + assert_eq!(seen(&recorder, "a"), (0..CALLS).filter(|n| n % 3 != 0).collect::>()); + assert_eq!(seen(&recorder, "b"), (0..CALLS).filter(|n| n % 3 == 0).collect::>()); + } + + /// A write that never finishes holds back its own terminal only. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_stuck_terminal_holds_back_no_other() { + let (recorder, to_server, mut from_server) = connect(); + let write = crate::methods::WRITE_TERMINAL; + to_server.send(call(1, write, "stuck", 0)).await.unwrap(); + to_server.send(call(2, write, "stuck", 1)).await.unwrap(); + for n in 0..20 { + to_server.send(call(10 + n, write, "free", n)).await.unwrap(); + } + for _ in 0..20 { + tokio::time::timeout(Duration::from_secs(10), from_server.recv()) + .await + .expect("the free terminal's calls answered") + .expect("connection up"); + } + assert_eq!(seen(&recorder, "free"), (0..20).collect::>()); + assert!(seen(&recorder, "stuck").is_empty()); + } + + /// Input sent just before the connection ends still goes in, in order. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn input_sent_before_the_connection_ends_still_goes_in() { + let (recorder, to_server, from_server) = connect(); + for n in 0..50 { + to_server + .send(call(n + 1, crate::methods::WRITE_TERMINAL, "a", n)) + .await + .unwrap(); + } + drop(to_server); + drop(from_server); + let deadline = tokio::time::Instant::now() + Duration::from_secs(10); + while seen(&recorder, "a").len() < 50 { + assert!(tokio::time::Instant::now() < deadline, "{:?}", seen(&recorder, "a")); + tokio::time::sleep(Duration::from_millis(5)).await; + } + assert_eq!(seen(&recorder, "a"), (0..50).collect::>()); + } +} diff --git a/crates/ui/src/state.rs b/crates/ui/src/state.rs index a8a0d7e9f..da7d20f6d 100644 --- a/crates/ui/src/state.rs +++ b/crates/ui/src/state.rs @@ -6083,6 +6083,7 @@ mod tests { upsert: Vec::new(), append: Vec::new(), remove: Vec::new(), + parts: Vec::new(), count: 0, }) .expect("empty delta"); diff --git a/crates/visual/src/tests.rs b/crates/visual/src/tests.rs index 01278b757..042e52c64 100644 --- a/crates/visual/src/tests.rs +++ b/crates/visual/src/tests.rs @@ -282,6 +282,25 @@ fn record_rows_without_column_keys_are_an_error() { assert!(error.to_string().contains("needs a key"), "{error}"); } +// show_visual's hover advice, as written there, checks clean: a line kept +// for what a pick shows, the same height before and after. +#[test] +fn the_hover_advice_example_checks_clean() { + check( + r#" + local s = ui.state { picked = false } + return function() + return ui.column { gap = 8, + ui.row { hover = true, on_click = function() s.picked = "us-east, 182 ms" end, ui.text "us-east" }, + ui.text { s.picked or " " }, + } + end + "#, + 1, + ) + .unwrap(); +} + #[test] fn check_exercises_every_control_and_reports_where_it_broke() { let report = check( diff --git a/crates/voice/Cargo.toml b/crates/voice/Cargo.toml index 0730ba7a6..f55e7258d 100644 --- a/crates/voice/Cargo.toml +++ b/crates/voice/Cargo.toml @@ -7,7 +7,12 @@ publish.workspace = true [dependencies] anyhow.workspace = true -parakeet-rs = "=0.3.8" +parakeet-rs = { version = "=0.3.8", default-features = false, features = ["cpu", "api-28"] } +# Omit ort's default `copy-dylibs` feature: ort-sys 2.0.0-rc.13 assumes the +# pre-Rust-1.100 `target//build/-/out` layout and panics on +# Windows under Cargo 1.100's `build///out` layout. Windows links the +# system DirectML/DX12 libraries and does not bundle ort dylibs. +ort = { version = "=2.0.0-rc.13", default-features = false, features = ["std", "ndarray", "tracing", "download-binaries", "tls-native", "api-27"] } cpal = "=0.17.3" rubato = "=0.16.2" reqwest.workspace = true diff --git a/docs/godspeed/UPSTREAM.md b/docs/godspeed/UPSTREAM.md index 9385b0223..8dfe8e4ad 100644 --- a/docs/godspeed/UPSTREAM.md +++ b/docs/godspeed/UPSTREAM.md @@ -3,7 +3,7 @@ Godspeed ports Zeron's commits instead of merging them: the rebrand touches most files, so a raw merge conflicts everywhere. Each ported commit carries a trailer `Upstream: zeronsh/zeron@`. -Synced through: zeronsh/zeron@7437e3e9 (2026-11-11) +Synced through: zeronsh/zeron@fbb4083a4 (2026-11-25) Deferred, waiting on the owner's call (not ported; revisit before porting anything that builds on them): - cc7da5c2 "Zeron Cloud, provider switching, and the phone model picker" (#966): 369 files, @@ -115,6 +115,159 @@ Deferred, waiting on the owner's call (not ported; revisit before porting anythi - Partly ported: 68c7ea28 (long chats on other devices) keeps Godspeed's relay without per-conn device checks and its own turn status report; respond_to_input still reads the whole transcript when it names a question older than the newest. +- Deferred 2026-11-17 (7437e3e9..09766b39: 888 commits, 627 non-merge, 333 of them + `apps/zgx` only). 20 ported, the rest deferred or skipped. Full list: + `git log --no-merges 7437e3e9..09766b39`. + - zgx-only, deferred with zgx: every `apps/zgx` commit, zgx dictation (d9fbc6e5, + 17c30f63, 3d513729, cf6dda0e, 86105fa5, 63774eef), the engine `plugins` API + (8e582ffc, 9bfdac98, 02a8ad24, b5f053f2, cdbd99f6, b2688c29, 564da441, e9a956ec, + a11374a6, c7020611, 99056a1f, 89a8f081, 8ea7bf8c, 8a91a02d, adcac463, 1ff869f7, + 91d8a010), zgx Cloud and launch (08f06796, fe0f4f26, c44c6cf6, 0731c9e7). + - Durable Cloud, R2 attachments and Cloud wakes (built on cc7da5c2): e3c83bd8, 029fea30, + de157638, 6c4d8a0e, ae03b84a, c1eebcbc, 9c5ade8b, 9de23cf8, 415f1f24, 10019ccd, + 8085dc59, 9742ffcd, 7537ba9d, 6c19e751, ff655e0e, dc8ae9dc, 1372e45d, 6da445f5, + c9b08217, 84f24f36, 321f14a1, 6bd35c92, d0a451a0, 451822be, db606643, d911ca96, + d96f4af7, a6839b28, 6e8b4c8a and 5b3f50b3 (keep every send until removed), 3324f850 + and 2569857b (damaged chat store rebuilt), c7ea42df, 5ebeef3d, 538fd2b0, 9f43edfe, + c10b5ac3 (banners; Godspeed has no engine `desktop_notify`). + - The relay layer (chat generation 3, `chat2_host`) and everything built on it, + including the snapshot-delta and registry write series: a9883e58, cbee9590, adb3a9ed, + 4fa6fb26, 17bb92de, 3c45b6d3, 2a56dca5, f85f3444, 83004279, eb2ff018, ba79b4df, + 25ece15a, f2197ca0, d2dce83c, d46de0ea, cee503f5, 0a49ea3e, f9608906, 93da4b72, + 6e473538, bf2c8e94, 09811cf5, 20bd70a5, bff39897, ec959a2f, 12c03242, 4257eb8c, + bee81e89, ea2c29cc, f295d210, a3f6c352, d1d862f3, fe5f24a8, 5528c750, 631622ed, + bb247410, e9e78b38, 3182a970, fe70ba30, 5f0f79d1, b987c50e, 2f2be538, d3391b2c, + a0eca081, e8abc385, ba533912, aec924c1, 09b2c76b, 5ac47758, a2497307, 7c553f43, + 8602f872, cb3b88a0, 398cdabb, 5f299638, 4fc08058, 7ff0c663, a6336cb0, 7748351f, + cd3d0020, 29ad3524, c004d547, ebf1c437, 6f4e0e51, a18277f5, b306399c, 3fb3dbbc, + 1783a9e1, 705b3084, bd0c5329, 6248f098, df4eecfe, 91033835, 8ada39b7, b36652c7, + 7a062eeb, 95d7bfc0, b9cf705c, da3ec3f4, fa55493f, 98199a5b, 41417142, e6b95954, + 952ec8a3, 3510f868, bd379611, 3ea858b9, 1a7dc2e4. + - Update transaction and beta channel (with a8d1dc6e): e9d377c0, 645290f7, 080a3c39, + 644961c8, b5ebb7c7, dde81854, 132bc5f1, 68cc6347, 108b4444, a0a4efcc, 71144518, + bb9ba180, 989c418c, ee37cc50, 7f01dad0, 6bf63430. + - Worth dedicated ports (standalone, but conflict with Godspeed's own design): + - 9290078c (deleting a chat ends its run and takes its children): conflicts with + Godspeed's session wake/upsert, title regeneration and run start; also wires + plugins and Cloud machine deletion. + - 61d91d37 (preview scan via libproc instead of lsof/ps): Godspeed's + `discovery.rs` differs; ~400 lines of FFI. + - device_stats MCP tool: e1525b28, 325f478a, d45a30af. + - Tool result images: c17262cf, bce5f058, a2115820, 3ef287e2, 204f9ca2, 1e910d91, + 067b9e7d, a4401fef. + - Model picker provider names and Claude model ordering: f545d1d7, 33cc9d4e, + d8f9a1ad, 60d85b85, 80b3d416, f5d0530e, f224da9e; hosted model list 7a1f03f7. + - Provider accounts for Pi/OpenCode/Hermes, API keys: a26f5f4c, 6c7b1ac2, 24cae278, + 3d07f58d, 4ec5b50c, 59b2f1c4, adc82e90. + - Upstream's Auto access mode: 4b983c6c, e934f876, 31ac609b (Godspeed has its own + `Auto`; see 1295d577). + - A project's name and icon belong to its repository: 446e4343, 04d5f345. + - c1168b6b (a send taken before the open chat's publish): ported alone, its test + still saw a send in a 3,000-entry chat wait 195 ms vs 17 ms; it needs the read + cache series above (4fc08058, 398cdabb, b36652c7) to pay off. Its test e6b95954 + goes with it. + - A revived turn waits for the IPC port: 3b434a68, a1847745, 69e03cbc, b6b79ab3, + 003b4feb, fd3bb08c (need `deferred.rs` and run recovery from 2e151ca6). + - iOS/Android: 2e5a678a, 5986bf3b (Activity; need a02a326b), fe8be7fe, 1bc3bcdc, + bindings regenerations 263fd8d8, 4e4faa64, f852eab0. + - Partly ported: 6ab00cf5 without the provider-switch hold (cc7da5c2); 75fbbbb6's + test without the deferred a2113ac8 Tool fields; 50ba9b78 with its test rewritten for + Godspeed's access model; ac1700f2 without its update-status test hunks. + - Skipped: version bumps (854248bd, 51d069c7, 53fa1720, 8f75cc28, 0733d73d, 703500ee, + 464377bb, 82502ace, 2d480e9f, e48dcbed, 55a5c392), edge-only, CI and release + scripts, relay design docs, d0c77e9c (`apps/zeron`), 7cf2ba66 (zgx exe icon), + 0f9a7500 (`crates/cli` log rotation; Godspeed has no `crates/cli`), 2252f736 (fixes a + codex `account_id` check Godspeed doesn't have; see adf87317), 58236762 (Linux + release LTO), 749ed748 (a test for upstream's generic + `TranscriptFrame::reset`, which Godspeed's isn't). +- Deferred 2026-11-18 (09766b39..c58f65e8: 150 commits, 124 non-merge, 49 of them + `apps/zgx` only, deferred with zgx). 13 ported, the rest below. + - Agents' Godspeed tools served from the engine over Streamable HTTP, not a process per + agent: c48876c38, with 4f95a9bd6 and 509857e4f (endpoint limits), 5b5d6a04b (no token + on the command line) and 4b0f499ef (no fsync of the private MCP config). Godspeed + still passes `--mcp-config` on the command line and has no `mcp/src/http.rs`. + - Idle agent stop (an idle agent process ends after 2 min, 30 s when no window shows + its chat): c987be092, 519fec249, dd48d0360, ed0f2729d, 89b6f7baa, 94bb83933, + 74cd87f16, 7c6f3e6b8. Conflicts in sessions.rs/process.rs; worth a dedicated port. + - Warm starts (an agent launched while the first message is typed): 4941b7b90, + 7661575d4, 9e44ed8f5, e737faf46 (need `managed.rs`; the UI half is zgx). + - Agents die with their engine (pid registry, PR_SET_PDEATHSIG): f558b51af. Worth a + dedicated port; builds on the Claude refresh lock (dd0c36fa). + - The idle engine series (one wall-clock beat grid in `zeron_sync::wake`, OS wake + notices, sleeping reapers and watchers): 9a11f98d7, 39277756e, 357cf2813, bd579e57d, + 413382fc7, a881538ca, 025bec869, 9237a0390, 7c8fa5edc, 18fc4b086, a9b4790e1 (relay + layer), 8f8f39cff (needs 61d91d37), 20dadc810 and 69768a512 (upstream's tagged + allocator wrapper), 8a8cdc607 and 7654168e6 (`idle_rig` needs `connect_ipc`). + Ported from it: 45b79a8f1, 98924b823, c19d45922 (by hand), f1ecad286, 445f70a00. + - Keep running after quit: 758e7a7a1, ebb7dd048 (zgx setting, engine `keep_running.rs`). + - Titles and `first_word` tracing: 9c80a0e1c, dd460b304, 82ce7506f, e068e04a7 (need + `wake_trace` and upstream's title trigger). + - Commands on other devices, Cloud isolation: eb42145a9, 41135ffcb, 198324c09, + c8ea12ceb, 7ca6d8577, 5a63a5803, 85d2dc3a7, e8069c403, 6069c35c9, 8206fe614 (need + `agent_gate.rs`, the background band and Cloud). + - b0e62255d (keep chats on this device while signed in): its engine half has no + setting in Godspeed's UI yet. + - c58f65e8a (iOS sidebar hide button): Godspeed's iOS toolbar (inbox, board) differs. + - Partly ported: f38065825 brought only `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` (its MCP + instructions rewrite is Zeron's text); 8815fb235 brought `bounded_file` and the + model-context hash only (its other readers aren't in Godspeed); e51676b29 without + the deferred `tool_exchange`; 6191678a6 without its cut-off-turn test (Godspeed + doesn't revive a turn cut off by a graceful shutdown). + - Skipped: fee8cfa1b (upstream retires the GPUI app, which is Godspeed's), 8b2f4b02b + (landing), 85c1fe2b0 (version bump), bc1ecbb3f and 4e86e6bcc (3 warm docs, then + back to 12: no net change), 9a6c3d9e3 and f0ab203f6 (mock `/longthread`, `/stream` + bench modes for Zeron's ademark rig). +- Deferred 2026-11-20 (c58f65e8..2e3513c6: 24 commits, 20 non-merge, 8 of them + `apps/zgx` only, deferred with zgx: cef90597, 4aac725b, 2c965d7a, b1064c1b, 774dd72e, + c5f65ea0, e393c4a8, 4820dd83). 1 ported (bc14b5b1, by hand), the rest below. + - d3a76091e (a long chat reopened with rows held sends its newest entries first): + builds on the deferred snapshot-delta series (`entry_sum`, `orderSum`, `known`). + - e66369f48 (reopening a remote chat asks the room and its host for what it missed): + the relay layer (`chat_relay.rs`). + - 17d777fa0 (Grok Auto mapped to Grok Build's auto mode, Full access always-approve, + reviewer's reason on approvals): built on upstream's Auto access mode (4b983c6c). + - 890c4527e (Antigravity 1.5.0 hardening: step-boundary steering, stall watchdog, + effort ladder, corrupt-session recovery, Neon thoughts; plus queued provider/model + switches and the provider-switch seam): its tests and engine half need provider + switching (cc7da5c2) and run recovery (2e151ca6). The Antigravity harness half is + worth a dedicated port. + - 8c5549ecb (Cloud: every built-in agent with every local login): Cloud (cc7da5c2). + - Partly ported: bc14b5b12 brought the 3 s probe settle and test-run exclusion; its + "environment read empty" half is about upstream's origin-marker cache, which + Godspeed's cwd-based discovery doesn't have. + - Skipped: version bumps (c7f63a53, 29ec0489, 22eb085c, 5ac8d75a), 81cbda60 (CI apt + retry), 8fe624f8 (edge credit rate config). +- Deferred 2026-11-21 (2e3513c6..46f18fe4: 19 commits, 10 non-merge; `apps/zgx` only, + deferred with zgx: 2c8001a8, 9fb81caa, 3f5381c1, 0dbdf725, 613accb2). 1 ported (865308ff, + voice ort features), the rest below. + - 21ec6f8b3 (Antigravity dynamic updates, opt-in Code Mode for Codex and Muse): +916 + lines over 100 files, half of them zgx; the engine half edits `warm_start.rs` (warm + starts, deferred) and builds on the deferred Antigravity hardening (890c4527e). Its + new proto field touches every engine/harness test initializer. Port with 890c4527e. + - Skipped: version bumps (b7b1e2d3, 26000a74), 46f18fe4 (Cloud install script, edge). +- Deferred 2026-11-25 (b2ee6d1b..fbb4083a4: 33 commits, 30 non-merge). Nothing ported. + - MCP servers (vault connections, engine gateway/OAuth/presets, per-agent "only Zeron's + MCP servers", agents asking for MCP changes): d5ff0b1ad, 2f4768659, 848750301, 0150fde8e, + 60a7980b3, 173ae0b1c, a2fa2d757, fcaa7f04e, 1c46da29e, 38bc732b6, 20ce01edb, f4c151c84. + They need the VaultConnections Durable Object and `warm_start.rs`/`managed.rs`, which + Godspeed doesn't have. Worth a dedicated port as one feature if the owner wants MCP management. + 3c3eed924 (switch off Codex plugins' MCP servers) hangs off that per-agent switch. + fbde94408 (`zeron mcp` CLI) also needs `crates/cli`. + - Antigravity unified CLI cbbab5067 and its Windows fix ed97f42ec: these need + `credentials.rs`, `agent_accounts` and `acp/ccpa_thoughts.rs` (890c4527e chain). + - Cloud: 8801bf815 (Providers for Cloud), c765f256c (`managed.rs` wake tools). + - `apps/zgx` only, deferred with zgx: a94e4e7dc, 9e9dff3b4, 0777a30a2, 39118ef52, + 768b25a86, 53a4637a6, fbb4083a4. + - Skipped: version bumps e081e38e1, 296461969, 82a58c5f6, e56940314; c4b09b659 (edge). +- Deferred 2026-11-23 (46f18fe4..b2ee6d1b: 19 commits, 17 non-merge). Ported b5cfaaccd (Pi + set_model refusal) and the `crates/mobile` half of 8141d7d9e (image-named attachment chips). + - e595626b0 (Antigravity disconnects in Cloud Runner): the engine half is Cloud + (`credentials.rs`, antigravity_proxy); the harness half needs the CCPA thoughts proxy + (`acp/ccpa_thoughts.rs`) from the deferred Antigravity hardening (890c4527e). Port with it. + - aad53585e (Cloud delegates childKind): Cloud. + - `apps/zgx` only, deferred with zgx: 66d025b24, 7662482bf, e131c1ba0, 80b78c1e8, + 2fcd150ea, e88155990, 225078f9e, 7b2eae9f7, 55ca07782, 838478e24. + - Skipped: version bumps (b289003b7, b2ee6d1b9), aec10cd12 (docs rewritten for ZGX). - Partly ported (2026-11-02): 2500e8b3 brought only the Muse crash-exit race fix. Its CI restructure (single ci.yml with admission/reuse, nextest profile, merged `tests/misc` binaries) is Zeron's CI; its term-link race fix needs the deferred `zeron-term-link` crate