From 97e1063153fcf9f80108999edf383224cecc6ffc Mon Sep 17 00:00:00 2001 From: yansfil Date: Tue, 10 Nov 2026 19:39:57 +0900 Subject: [PATCH 1/7] fix: keep a pane's last look across a daemon restart and follow a new token in the page address Agent sleep dropped a pane's stamp, and the last look in it, whenever the engine listed no agent for the pane. A restarted engine lists an agent only once its program shows again, so an agent the operator had just read was put to sleep by its old conversation on the first decision after the restart. Stamps now go only when the engine's topology no longer holds the pane, as the read records already do. A page that reconnected to a restarted daemon with the old token was refused and stayed gone, and the address carrying the new token could not bring it back. The page now opens a new connection when the token in its address changes, and a refusal reaching a socket that was replaced ends nothing. --- docs/ARCHITECTURE.md | 1 + docs/TESTING.md | 2 +- hide-core/src/agent_sleep.rs | 43 ++++++++++++++-- hide-core/src/runtime/agent_sleep.rs | 20 ++++++-- hide-core/src/runtime/session.rs | 12 ++++- hide-core/src/runtime/tests/agent_sleep.rs | 35 +++++++++++++ web/src/ws.test.ts | 57 ++++++++++++++++++++++ web/src/ws.ts | 37 ++++++++++++-- 8 files changed, 189 insertions(+), 18 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 8c4663be0a..0b755977ce 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -780,6 +780,7 @@ The last look is stamped when a visit commits and once a minute while a pane is The hours count from the later of the agent's last conversation line and its last look (`PaneStamps::idle_since`). The last conversation line is the newest request or reply the session read proves (`last_conversation_at_unix_ms`), because a relaunch or an engine restart reports a state for a moment and moves the change stamp without adding a line to the conversation; on 2026-10-22 one app update restarted every idle agent's 24 hours that way. Until a session read proves a line, the change stamp stands in, so a restart only ever delays a sleep. +A pane's stamp, and the last look in it, is dropped only when the engine's topology no longer holds the pane, never because the agent list holds no agent for it: a restarted engine lists an agent only once its program shows again, and a stamp lost in that gap sleeps an agent the operator just read the moment the session read proves its old conversation (`AgentSleepStore::stamp`; the read records follow the same rule, `prune_read_records`). A wake stamps a last look, as a visit does, because the conversation it resumes is as old as the sleep and would make the agent due again at the next minute. A relaunch forgets an end that was in flight, because it cannot know whether it landed, and reads a wake that was in flight as still asleep until an agent appears in the pane. An in-pane sleep keeps the read axis's engine mark beside the ended agent's state sequence: the sequence identifies the ended agent only on that engine, because an engine restart starts its counter again. diff --git a/docs/TESTING.md b/docs/TESTING.md index af1aaf67b0..bc25f5dfe3 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -358,7 +358,7 @@ A piece that another open change is still building is marked as pending with the 7. **Restart through `daemon.restart()`, and leave the old page first.** `daemon.restart()` in `web/e2e/hided-fixture.ts` stops `hided` and starts it again on the same state folder and port, as a real restart does, and takes an optional callback to edit the state folder before the start; `web/e2e/sidebar-pr-start.spec.ts` restarts three times in one test. It uses `hide stop` on every system and preserves the own engine's holders for adoption; only final fixture cleanup sweeps their process trees. - A navigation that only changes the hash does not remount the connection, so the old page keeps its old token and socket and races the new one. + A navigation that only changes the hash does not remount the page: its connection follows the new token (`followToken` in `web/src/ws.ts`), but the page it keeps has the old page's state and may already have been refused with the old token, so a test that reopens the product goes through a fresh page. Go through `about:blank` before opening the new origin and token, as `openSettings` in `web/e2e/interface-language.spec.ts` does, and keep that step in one helper per spec. Why: the old page and the new token reconnect at the same time and either can win. `hide-e2e/reopen-after-restart-through-blank` fails a `goto` of `#token=` after `restart()` in the same function; a helper defined elsewhere and called after the restart is not seen, so keep the step in the helper. diff --git a/hide-core/src/agent_sleep.rs b/hide-core/src/agent_sleep.rs index a76a91dcd5..f01b64b527 100644 --- a/hide-core/src/agent_sleep.rs +++ b/hide-core/src/agent_sleep.rs @@ -562,11 +562,19 @@ impl AgentSleepStore { /// Moves each awake agent's change stamp on one machine when its state /// changed or it appeared, and drops the stamps of that machine's panes - /// that hold no agent now. Returns whether anything moved. + /// the engine's topology says are gone. Returns whether anything moved. + /// + /// A pane that holds no agent now keeps its stamp, and with it its last + /// look: a restarted engine lists an agent only once its program shows + /// again, so the agent list is empty or incomplete for a while and is + /// never an eviction source (as for the read records, + /// `agent_state::prune_read_records`). `live_pane_ids` is the topology + /// of the same read; none keeps every stamp. pub fn stamp( &mut self, agents: &[SidebarAgentSnapshot], scope: SleepScope<'_>, + live_pane_ids: Option<&HashSet>, now_unix_ms: u64, ) -> bool { let mut changed = false; @@ -605,6 +613,7 @@ impl AgentSleepStore { !scope.holds(pane_id) || present.contains(pane_id.as_str()) || self.records.contains_key(pane_id) + || live_pane_ids.is_none_or(|live| live.contains(pane_id)) }); changed | (self.stamps.len() != before) } @@ -839,7 +848,7 @@ mod tests { /// A store that first saw `agents` at time zero. fn stamped(agents: &[SidebarAgentSnapshot]) -> AgentSleepStore { let mut store = AgentSleepStore::default(); - store.stamp(agents, SleepScope::Core, 0); + store.stamp(agents, SleepScope::Core, None, 0); store } @@ -904,9 +913,9 @@ mod tests { let mut store = stamped(&agents); // A relaunch reports a state for a moment. agents[0].activity = "unknown".to_owned(); - assert!(store.stamp(&agents, SleepScope::Core, 20 * HOUR)); + assert!(store.stamp(&agents, SleepScope::Core, None, 20 * HOUR)); agents[0].activity = "stopped".to_owned(); - assert!(store.stamp(&agents, SleepScope::Core, 20 * HOUR)); + assert!(store.stamp(&agents, SleepScope::Core, None, 20 * HOUR)); assert!(due_at(&store, &agents, 25 * HOUR - 1).is_empty()); assert_eq!(due_at(&store, &agents, 25 * HOUR), ["w1:p1"]); @@ -918,12 +927,36 @@ mod tests { assert_eq!(due_at(&store, &agents, 64 * HOUR), ["w1:p1"]); } + #[test] + fn a_pane_without_an_agent_keeps_its_last_look_until_the_pane_itself_is_gone() { + let mut agents = [agent("w1:p1")]; + agents[0].last_conversation_at_unix_ms = Some(HOUR); + let mut store = stamped(&agents); + store.mark_seen(["w1:p1"], 10 * HOUR); + let live = HashSet::from(["w1:p1".to_owned()]); + + // A restarted engine lists an agent only once its program shows again. + assert!(!store.stamp(&[], SleepScope::Core, Some(&live), 11 * HOUR)); + agents[0].activity = "unknown".to_owned(); + assert!(store.stamp(&agents, SleepScope::Core, Some(&live), 12 * HOUR)); + agents[0].activity = "stopped".to_owned(); + assert!(store.stamp(&agents, SleepScope::Core, Some(&live), 13 * HOUR)); + assert!(due_at(&store, &agents, 34 * HOUR - 1).is_empty()); + assert_eq!(due_at(&store, &agents, 34 * HOUR), ["w1:p1"]); + + // No topology to judge by evicts nothing; one that lacks the pane does. + assert!(!store.stamp(&[], SleepScope::Core, None, 14 * HOUR)); + assert!(store.stamps.contains_key("w1:p1")); + assert!(store.stamp(&[], SleepScope::Core, Some(&HashSet::new()), 15 * HOUR)); + assert!(store.stamps.is_empty()); + } + #[test] fn without_a_conversation_read_a_state_change_restarts_the_clock() { let mut agents = [agent("w1:p1")]; let mut store = stamped(&agents); agents[0].completed = true; - assert!(store.stamp(&agents, SleepScope::Core, 20 * HOUR)); + assert!(store.stamp(&agents, SleepScope::Core, None, 20 * HOUR)); assert!(due_at(&store, &agents, 24 * HOUR).is_empty()); assert_eq!(due_at(&store, &agents, 44 * HOUR), ["w1:p1"]); } diff --git a/hide-core/src/runtime/agent_sleep.rs b/hide-core/src/runtime/agent_sleep.rs index 78fe3586f7..3e4afd38fe 100644 --- a/hide-core/src/runtime/agent_sleep.rs +++ b/hide-core/src/runtime/agent_sleep.rs @@ -266,9 +266,13 @@ impl Runtime { /// Marks the projected rows that sleep and moves each awake agent's /// change stamp. The stamps are persisted, never published. - pub(super) fn stamp_agent_sleep(&mut self, agents: &mut [SidebarAgentSnapshot]) { + pub(super) fn stamp_agent_sleep( + &mut self, + agents: &mut [SidebarAgentSnapshot], + live_pane_ids: Option<&HashSet>, + ) { self.confirm_dormant_wake(agents); - self.stamp_agent_sleep_in(agents, SleepScope::Core); + self.stamp_agent_sleep_in(agents, SleepScope::Core, live_pane_ids); } /// The same for the rows of another machine. @@ -276,14 +280,20 @@ impl Runtime { &mut self, device: &str, agents: &mut [SidebarAgentSnapshot], + live_pane_ids: &HashSet, ) { - self.stamp_agent_sleep_in(agents, SleepScope::Device(device)); + self.stamp_agent_sleep_in(agents, SleepScope::Device(device), Some(live_pane_ids)); } - fn stamp_agent_sleep_in(&mut self, agents: &mut [SidebarAgentSnapshot], scope: SleepScope<'_>) { + fn stamp_agent_sleep_in( + &mut self, + agents: &mut [SidebarAgentSnapshot], + scope: SleepScope<'_>, + live_pane_ids: Option<&HashSet>, + ) { let store = &mut self.snapshot.ui_state.agent_sleep; store.annotate(agents); - if store.stamp(agents, scope, unix_milliseconds()) { + if store.stamp(agents, scope, live_pane_ids, unix_milliseconds()) { self.persist_ui_state(); } } diff --git a/hide-core/src/runtime/session.rs b/hide-core/src/runtime/session.rs index 3a71a79248..f790c56447 100644 --- a/hide-core/src/runtime/session.rs +++ b/hide-core/src/runtime/session.rs @@ -2063,7 +2063,15 @@ impl Runtime { self.overlay_remote_pane_moves(target_id, session); // A node that dials this core sleeps as the core's own machine // does (PRD core-host-node-remote-core B13). - self.stamp_node_agent_sleep(target_id, &mut session.agents); + let live_pane_ids = session + .workspaces + .iter() + .flat_map(|workspace| workspace.checkouts.iter()) + .flat_map(|checkout| checkout.tabs.iter()) + .flat_map(|tab| tab.panes.iter()) + .map(|pane| pane.id.clone()) + .collect::>(); + self.stamp_node_agent_sleep(target_id, &mut session.agents, &live_pane_ids); self.lay_plan_reviews(target_id, &mut session.agents); read_changed = self.apply_remote_read_state(target_id, session); for workspace in &mut session.workspaces { @@ -3195,7 +3203,7 @@ impl Runtime { if let Some(mut agents) = agents { let held = Arc::clone(&self.herdr_held); let local = ReadRecordScope::Local(&held); - self.stamp_agent_sleep(&mut agents); + self.stamp_agent_sleep(&mut agents, live_pane_ids.as_ref()); self.place_agents_in_navigator(&mut agents); // The lineage is built before the read axis is applied, because // the read fingerprint carries what each row's descendants are diff --git a/hide-core/src/runtime/tests/agent_sleep.rs b/hide-core/src/runtime/tests/agent_sleep.rs index d7489599fb..2658d7420d 100644 --- a/hide-core/src/runtime/tests/agent_sleep.rs +++ b/hide-core/src/runtime/tests/agent_sleep.rs @@ -1931,6 +1931,41 @@ fn the_input_gate_follows_the_sleep_records_from_the_first_moment_of_the_end() { ); } +/// A restarted engine lists an agent only once its program shows again, so +/// the first reads after a daemon start hold none for a pane that has one: the +/// pane's last look, which keeps an old conversation from sleeping an agent the +/// operator just read, must outlive them (with-hide/hide-private#682). +#[test] +fn a_read_that_lists_no_agent_for_a_pane_keeps_the_panes_last_look() { + let (mut runtime, checkout_id) = live_tab_order_runtime(CHECKOUT); + runtime.ingest_session(Ok(session(Some(4)))); + assert!(runtime.dispatch_json(&focus_tab_event(&checkout_id, "w-order:t2"))); + let seen = |runtime: &Runtime| { + runtime + .snapshot() + .ui_state + .agent_sleep + .stamps + .get(SLEEPER) + .map(|stamps| stamps.seen_at_unix_ms) + }; + let looked = seen(&runtime).expect("the visit stamped the pane"); + assert!(looked > 0); + + runtime.ingest_session(Ok(session(None))); + assert_eq!(seen(&runtime), Some(looked), "the pane is still there"); + runtime.ingest_session(Ok(session(Some(1)))); + assert_eq!(seen(&runtime), Some(looked), "the agent is back"); + + let gone = tab_order_payload(CHECKOUT, &["w-order:t1"], &["w-order:t1"], "w-order:t1"); + runtime.ingest_session(Ok(gone)); + assert_eq!( + seen(&runtime), + None, + "a pane the topology lost takes its stamp" + ); +} + /// B12, D-12: a committed visit to the tab wakes the agent; another event /// in the same tab is not a visit, and a second wake starts nothing. #[test] diff --git a/web/src/ws.test.ts b/web/src/ws.test.ts index 8c540e4ea2..5bc69c919f 100644 --- a/web/src/ws.test.ts +++ b/web/src/ws.test.ts @@ -311,6 +311,63 @@ it("a window no move holds reconnects as reconnecting, and a move that stops sho shell.close(); }); +/** The address changes under an open page, as the host's next attach or a followed link does. */ +function addressNowCarries(token: string) { + window.history.replaceState(null, "", `#token=${token}`); + window.dispatchEvent(new HashChangeEvent("hashchange")); +} + +const tokenOf = (socket: FakeSocket) => (JSON.parse(socket.sent[0] ?? "{}") as { token: string }).token; + +// A restarted daemon has a new token. A page that reconnected with the old one +// is refused and gone (4001); the address that carries the new token, changed +// under the open page, draws it again without a reload. +it("a new token in the address draws a page the old token's refusal left gone", async () => { + const shell = connectShell({ onChunks: () => {}, onCopy: () => {} }); + const first = made(0); + first.open(); + first.frame({ type: "snapshot", payload: { revision: 5, rest: {} } }); + first.closeWith(1012, ""); + await vi.advanceTimersByTimeAsync(nextBackoff(BACKOFF_START_MS)); + const refused = made(1); + refused.open(); + expect(tokenOf(refused)).toBe("t"); + refused.closeWith(4001, "invalid_token"); + expect(useShellStore.getState().connection).toBe("gone"); + + addressNowCarries("t2"); + expect(FakeSocket.made).toHaveLength(3); + const again = made(2); + again.open(); + expect(tokenOf(again)).toBe("t2"); + again.frame({ type: "snapshot", payload: { revision: 1, rest: {} } }); + expect(useShellStore.getState().connection).toBe("live"); + shell.close(); +}); + +it("a refusal that reaches a socket the new token replaced does not end the window", async () => { + const shell = connectShell({ onChunks: () => {}, onCopy: () => {} }); + const old = made(0); + old.open(); + addressNowCarries("t2"); + const again = made(1); + again.open(); + again.frame({ type: "snapshot", payload: { revision: 1, rest: {} } }); + old.closeWith(4001, "invalid_token"); + await vi.advanceTimersByTimeAsync(nextBackoff(BACKOFF_START_MS)); + expect(useShellStore.getState().connection).toBe("live"); + expect(FakeSocket.made).toHaveLength(2); + shell.close(); +}); + +it("a page whose address keeps its token does not open another connection", () => { + const shell = connectShell({ onChunks: () => {}, onCopy: () => {} }); + made(0).open(); + addressNowCarries("t"); + expect(FakeSocket.made).toHaveLength(1); + shell.close(); +}); + // with-hide/hide-private#659: a program's copy reaches the window as its own // frame, handed over once, and never as a pane's output that a redraw or a // reconnect would replay. diff --git a/web/src/ws.ts b/web/src/ws.ts index c280c79ee2..04b9e517bc 100644 --- a/web/src/ws.ts +++ b/web/src/ws.ts @@ -1,7 +1,7 @@ import { receiveAgentNotice } from "./agentNotices"; import { configureAttachments, receiveAttachmentRefusal } from "./attachments"; import type { AgentNotice } from "./generated/hided-ws"; -import { connectionAfterHealthFails, nextBackoff } from "./connection"; +import { BACKOFF_START_MS, connectionAfterHealthFails, nextBackoff } from "./connection"; import { moveUnderWay, type MoveView } from "./coreMove"; import { clearPending, receiveBytes, receiveBytesError, receiveBytesRefusal } from "./fileBytes"; import { isOperatorFocus, numbered } from "./operatorFocus"; @@ -59,7 +59,7 @@ async function healthOk(): Promise { export function connectShell(handlers: Handlers): { dispatch: DispatchFn; sendBinary: (bytes: Uint8Array) => void; close: () => void; drop: () => void } { let socket: WebSocket | null = null; let closed = false; - let backoff = 500; + let backoff = BACKOFF_START_MS; let healthFails = 0; let accessReported = false; let revision = 0; @@ -72,6 +72,9 @@ export function connectShell(handlers: Handlers): { dispatch: DispatchFn; sendBi let terminalEpoch: string | null = null; let operatorFocusSequence = 0; let reconnectTimer: number | undefined; + // The token the current socket was opened with: the address is the page's + // credential, and a different one in it names a different daemon run. + let openedToken: string | null = null; // Decided once: the probe is a measurement seam, not a per-frame branch. const probing = probeEnabled(); @@ -137,6 +140,7 @@ export function connectShell(handlers: Handlers): { dispatch: DispatchFn; sendBi return; } useShellStore.getState().setConnection(socket ? (held() ? "moving" : "reconnecting") : "connecting"); + openedToken = token; const ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/ws`); // File bytes arrive as binary frames on this same socket; the header and // payload are split by the file-bytes reader, not by the snapshot store. @@ -275,21 +279,26 @@ export function connectShell(handlers: Handlers): { dispatch: DispatchFn; sendBi clearPending("socket_closed"); resetBrowserComments(); } - if (closed) return; + // A socket a newer one replaced (a new token in the address) ends + // without a say in the window's state: its refusal is the old token's. + if (closed || socket !== ws) return; if (event.code >= 4001 && event.code <= 4004) { useShellStore.getState().setConnection("gone", true); return; } - void scheduleReconnect(); + void scheduleReconnect(ws); }); ws.addEventListener("error", () => { ws.close(); }); }; - const scheduleReconnect = async () => { + const scheduleReconnect = async (ended: WebSocket) => { useShellStore.getState().setConnection(held() ? "moving" : "reconnecting"); const ok = await healthOk(); + // A new token in the address opened a connection while the health read + // was out: that one is the window's now, and a second would race it. + if (closed || socket !== ended) return; healthFails = ok ? 0 : healthFails + 1; const next = connectionAfterHealthFails(healthFails); if (next === "gone") { @@ -300,6 +309,23 @@ export function connectShell(handlers: Handlers): { dispatch: DispatchFn; sendBi reconnectTimer = window.setTimeout(open, backoff); }; + // A daemon that restarts gives its next run a new token, and the address + // that carries it is changed under a page that is already open (the host's + // next attach, a link followed in the same window). The new token is a new + // connection, from any state the old one ended in: a page the old token's + // refusal or a long outage left gone is drawn again, without a reload. + const followToken = () => { + const token = tokenFromLocation(); + if (closed || !token || token === openedToken) return; + if (reconnectTimer) window.clearTimeout(reconnectTimer); + backoff = BACKOFF_START_MS; + healthFails = 0; + const replaced = socket; + open(); + replaced?.close(); + }; + window.addEventListener("hashchange", followToken); + open(); configureAttachments({ dispatch, sendBinary }); return { @@ -309,6 +335,7 @@ export function connectShell(handlers: Handlers): { dispatch: DispatchFn; sendBi drop: () => socket?.close(), close: () => { closed = true; + window.removeEventListener("hashchange", followToken); if (reconnectTimer) window.clearTimeout(reconnectTimer); socket?.close(); }, From 057ccbe0cb6da5ed9764fd41b769b93c7f6905ab Mon Sep 17 00:00:00 2001 From: yansfil Date: Tue, 10 Nov 2026 19:40:21 +0900 Subject: [PATCH 2/7] test: repeat the restart specs twenty times without retries (temporary) --- .github/workflows/pr.yml | 5 +++-- .github/workflows/web-e2e.yml | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index b511209740..6f411334e6 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -755,7 +755,7 @@ jobs: lane: windows runner: windows-latest shards: 1 - grep: "@platform" + grep: "product usage defaults on" # The web shell is the same code on every operating system, so the whole # suite runs once, on Linux, where runners are plentiful. What differs by @@ -778,7 +778,8 @@ jobs: # 385 Linux tests total 3851.3 s; five shards plan at most 770.3 s, # six at most 641.9 s. Six is the smallest count within 720 s. # Test-work weights exclude setup/queues; the step still caps at 20 min. - shards: 6 + shards: 5 + grep: "a read row stays read|a draft whose tab a daemon restart lost|a View tab a daemon restart restores|the recent agent pane order survives|product usage defaults on" # The remote mailbox crate-boundary lane (hided/tests/it/remote_delivery.rs, # docs/TESTING.md), in `remote-mailbox.yml`. It has its own job because it was diff --git a/.github/workflows/web-e2e.yml b/.github/workflows/web-e2e.yml index cb94cb0f2b..7b1063118e 100644 --- a/.github/workflows/web-e2e.yml +++ b/.github/workflows/web-e2e.yml @@ -280,7 +280,7 @@ jobs: python3 scripts/e2e-shard.py check --table web/e2e/shard-durations.json --shard "$SHARD" "$list" "$RUNNER_TEMP/web-e2e-shard-list.txt" args+=(--test-list "$shard_file") fi - bash scripts/verify-web.sh web e2e "${args[@]}" + bash scripts/verify-web.sh web e2e "${args[@]}" --repeat-each 20 --retries 0 - name: Mint the development issues token # Development issues live in with-hide/hide-private (docs/TESTING.md, # Flaky tests); one App token reads this run here and files there. A run From 5cda98013d0074c42e0ab1254ab407ef87e79fa0 Mon Sep 17 00:00:00 2001 From: yansfil Date: Tue, 10 Nov 2026 21:16:32 +0900 Subject: [PATCH 3/7] test: wait for restored state across daemon restarts --- docs/TESTING.md | 4 ++++ web/e2e/hided-fixture.ts | 22 +++++++++++++++++++++- web/e2e/s3.spec.ts | 7 +++++-- 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/docs/TESTING.md b/docs/TESTING.md index bc25f5dfe3..ab97da12ee 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -358,11 +358,15 @@ A piece that another open change is still building is marked as pending with the 7. **Restart through `daemon.restart()`, and leave the old page first.** `daemon.restart()` in `web/e2e/hided-fixture.ts` stops `hided` and starts it again on the same state folder and port, as a real restart does, and takes an optional callback to edit the state folder before the start; `web/e2e/sidebar-pr-start.spec.ts` restarts three times in one test. It uses `hide stop` on every system and preserves the own engine's holders for adoption; only final fixture cleanup sweeps their process trees. + It returns only after its own WebSocket reads the core's connected engine and, when a saved checkout is selected, its restored Workspace view. + `/health` alone proves only that the listener is back; this shared snapshot boundary keeps restart callers from acting on an unresolved saved selection. A navigation that only changes the hash does not remount the page: its connection follows the new token (`followToken` in `web/src/ws.ts`), but the page it keeps has the old page's state and may already have been refused with the old token, so a test that reopens the product goes through a fresh page. Go through `about:blank` before opening the new origin and token, as `openSettings` in `web/e2e/interface-language.spec.ts` does, and keep that step in one helper per spec. Why: the old page and the new token reconnect at the same time and either can win. `hide-e2e/reopen-after-restart-through-blank` fails a `goto` of `#token=` after `restart()` in the same function; a helper defined elsewhere and called after the restart is not seen, so keep the step in the helper. A test whose subject is a surviving page reconnecting to the restarted daemon (`web/e2e/s3.spec.ts`, the two draft recovery tests) must not reload it, and says so in a line allow. + A restored editable draft needs an editable file: the View-tab draft test makes the parent folder unwritable to refuse atomic saves while keeping the file editable when the restarted node opens it. + Making that file itself read-only would correctly prevent the draft from being restored into it. 8. **Put a system difference in one fixture helper.** See [Operating-system differences belong to one fixture helper](#operating-system-differences-belong-to-one-fixture-helper); native home variables, executable names, the tool path and the no-op opener live in `web/e2e/platform-fixture.ts`, not in a `process.platform` branch in a spec. 9. **A retry is a label, not a fix.** diff --git a/web/e2e/hided-fixture.ts b/web/e2e/hided-fixture.ts index b89b67ded4..8a8cd1a196 100644 --- a/web/e2e/hided-fixture.ts +++ b/web/e2e/hided-fixture.ts @@ -10,6 +10,8 @@ import { linkFixtureTranscripts } from "./pane-fixture"; import { afterCleanup, ownUntilWorkerExit } from "./worker-owned"; import { bundledExecutable, linkBundle } from "./bundled-app"; import { endPaneHolders } from "./pane-holders.mjs"; +import { connectControl } from "./hided-control.mjs"; +import type { SnapshotRest } from "../src/snapshot"; import { endWindowsProcesses, fixtureExecutable, fixtureHomeEnv, fixtureLoginShellPath, fixtureOpenCommand, inheritedFixtureEnv, windowsProcessTree, type WindowsProcess } from "./platform-fixture"; /** @@ -268,7 +270,25 @@ async function launch(engine: DaemonEngine, label: string, dir: string, home: st await beforeStart?.(path.join(dir, "hide")); // The next daemon takes over the directory and its removal. disown(); - return launch(engine, label, dir, home, String(state.port), extraEnv, bundledAt); + const restarted = await launch(engine, label, dir, home, String(state.port), extraEnv, bundledAt); + try { + // /health proves the listener is back, not that the core has + // adopted the holders and resolved its saved Workspace. Keep + // every restart caller behind the same snapshot boundary. + const control = await connectControl(restarted); + try { + await control.until((rest) => { + const snapshot = rest as SnapshotRest; + return snapshot.status?.herdr?.state === "connected" + && (!snapshot.ui_state?.focused_checkout_id || Boolean(snapshot.workspace_view)); + }, "the restarted core's engine and saved Workspace"); + } finally { + control.close(); + } + return restarted; + } catch (error) { + throw afterCleanup(error, restarted.stop); + } }; return { pid: child.pid!, origin, token: state.token, home: fs.realpathSync(home), stateDir: path.join(dir, "hide"), hostId, node, stop, restart }; } diff --git a/web/e2e/s3.spec.ts b/web/e2e/s3.spec.ts index 92c06390e7..be33558b82 100644 --- a/web/e2e/s3.spec.ts +++ b/web/e2e/s3.spec.ts @@ -1756,7 +1756,10 @@ test("a View tab a daemon restart restores takes its unsaved draft back (S6 B19) const { file } = fixture; const original = fs.readFileSync(file, "utf8"); try { - fs.chmodSync(file, 0o444); + // Saving atomically needs a writable parent, but reopening the file + // must still yield an editable document. Making the file itself read-only + // prevents draft restoration once the restarted node reads its metadata. + fs.chmodSync(path.dirname(file), 0o555); const content = page.locator('[data-editor-codemirror] .cm-content'); await content.click(); await page.keyboard.press("ControlOrMeta+KeyA"); @@ -1775,7 +1778,7 @@ test("a View tab a daemon restart restores takes its unsaved draft back (S6 B19) await expect(page.locator("[data-draft-recovery]")).toHaveCount(0); expect(fs.readFileSync(file, "utf8")).toBe(original); } finally { - fs.chmodSync(file, 0o644); + fs.chmodSync(path.dirname(file), 0o755); close(fixture); } }); From f042278bb0032722f6d57cc35398e40e00ecf0c2 Mon Sep 17 00:00:00 2001 From: yansfil Date: Tue, 10 Nov 2026 21:30:03 +0900 Subject: [PATCH 4/7] test: keep restart fixture types independent of the renderer --- web/e2e/hided-fixture.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/web/e2e/hided-fixture.ts b/web/e2e/hided-fixture.ts index 8a8cd1a196..f19ebf7ab5 100644 --- a/web/e2e/hided-fixture.ts +++ b/web/e2e/hided-fixture.ts @@ -11,7 +11,6 @@ import { afterCleanup, ownUntilWorkerExit } from "./worker-owned"; import { bundledExecutable, linkBundle } from "./bundled-app"; import { endPaneHolders } from "./pane-holders.mjs"; import { connectControl } from "./hided-control.mjs"; -import type { SnapshotRest } from "../src/snapshot"; import { endWindowsProcesses, fixtureExecutable, fixtureHomeEnv, fixtureLoginShellPath, fixtureOpenCommand, inheritedFixtureEnv, windowsProcessTree, type WindowsProcess } from "./platform-fixture"; /** @@ -278,7 +277,13 @@ async function launch(engine: DaemonEngine, label: string, dir: string, home: st const control = await connectControl(restarted); try { await control.until((rest) => { - const snapshot = rest as SnapshotRest; + // This fixture is also compiled by the desktop host's + // non-JSX project; read just the wire fields needed here. + const snapshot = rest as { + status?: { herdr?: { state: string } }; + ui_state?: { focused_checkout_id?: string | null }; + workspace_view?: unknown; + }; return snapshot.status?.herdr?.state === "connected" && (!snapshot.ui_state?.focused_checkout_id || Boolean(snapshot.workspace_view)); }, "the restarted core's engine and saved Workspace"); From dfa72b37c0e707ed030d75667b0417a7b77812e1 Mon Sep 17 00:00:00 2001 From: yansfil Date: Tue, 10 Nov 2026 21:35:21 +0900 Subject: [PATCH 5/7] ci: restore standard web end-to-end coverage --- .github/workflows/pr.yml | 5 ++--- .github/workflows/web-e2e.yml | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 6f411334e6..b511209740 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -755,7 +755,7 @@ jobs: lane: windows runner: windows-latest shards: 1 - grep: "product usage defaults on" + grep: "@platform" # The web shell is the same code on every operating system, so the whole # suite runs once, on Linux, where runners are plentiful. What differs by @@ -778,8 +778,7 @@ jobs: # 385 Linux tests total 3851.3 s; five shards plan at most 770.3 s, # six at most 641.9 s. Six is the smallest count within 720 s. # Test-work weights exclude setup/queues; the step still caps at 20 min. - shards: 5 - grep: "a read row stays read|a draft whose tab a daemon restart lost|a View tab a daemon restart restores|the recent agent pane order survives|product usage defaults on" + shards: 6 # The remote mailbox crate-boundary lane (hided/tests/it/remote_delivery.rs, # docs/TESTING.md), in `remote-mailbox.yml`. It has its own job because it was diff --git a/.github/workflows/web-e2e.yml b/.github/workflows/web-e2e.yml index 7b1063118e..cb94cb0f2b 100644 --- a/.github/workflows/web-e2e.yml +++ b/.github/workflows/web-e2e.yml @@ -280,7 +280,7 @@ jobs: python3 scripts/e2e-shard.py check --table web/e2e/shard-durations.json --shard "$SHARD" "$list" "$RUNNER_TEMP/web-e2e-shard-list.txt" args+=(--test-list "$shard_file") fi - bash scripts/verify-web.sh web e2e "${args[@]}" --repeat-each 20 --retries 0 + bash scripts/verify-web.sh web e2e "${args[@]}" - name: Mint the development issues token # Development issues live in with-hide/hide-private (docs/TESTING.md, # Flaky tests); one App token reads this run here and files there. A run From e739be0c10c46c1e8c50efd8bae260bb6bd14267 Mon Sep 17 00:00:00 2001 From: yansfil Date: Tue, 10 Nov 2026 21:47:52 +0900 Subject: [PATCH 6/7] fix: end pending file reads before replacing a connection --- docs/ARCHITECTURE.md | 1 + web/src/ws.test.ts | 10 +++++++++- web/src/ws.ts | 11 +++++++++-- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0b755977ce..486e35013b 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -2533,6 +2533,7 @@ Schema 2 clients that request `snapshot_format: "semantic-rest-v1"` receive `res Omission retains a value, `null` clears an optional value and an empty array or map clears a collection; `workspace_view` is explicitly null when absent in this format. Without the capability, schema 2 keeps the supported complete-rest delta, including the omitted absent `workspace_view`; an unknown format is refused with `schema_mismatch` before snapshot delivery. A mismatched token, Origin, or schema version, or a ninth concurrent client, is closed with a reason code (`invalid_token`, `origin_not_allowed`, `schema_mismatch`, `client_limit`) and a diagnostic log line. +The web shell follows a new token in its address by retiring the previous socket's pending file reads with `socket_closed` and clearing its browser-comment state before opening the successor; the previous socket's late close cannot reject the successor's reads. After a valid handshake the daemon reads from the revision the client sent (`have_revision`, the cursor `Core::snapshot_delta_payload` takes), and then one delta frame per core notification burst. A client with cursor 0 gets a self-contained `snapshot`; a reconnecting client resumes with a `delta` that carries only what changed while it was away. When the core cannot serve the cursor, because the client's revision is ahead of the core's after a daemon restart, the daemon re-reads from zero and sends a `snapshot` (`server::classify_frame` owns that rule). diff --git a/web/src/ws.test.ts b/web/src/ws.test.ts index 5bc69c919f..44d950217b 100644 --- a/web/src/ws.test.ts +++ b/web/src/ws.test.ts @@ -345,18 +345,26 @@ it("a new token in the address draws a page the old token's refusal left gone", shell.close(); }); -it("a refusal that reaches a socket the new token replaced does not end the window", async () => { +it("a token replacement fails its old reads and a late refusal leaves the new reads alone", async () => { const shell = connectShell({ onChunks: () => {}, onCopy: () => {} }); + configureFileBytes(shell.dispatch); const old = made(0); old.open(); + const outcome = (read: Promise) => read.then(() => "answered", (error: Error) => error.message); + const oldRead = outcome(requestFileBytes("/repo/old.bin")); addressNowCarries("t2"); + expect(await oldRead).toBe("socket_closed"); const again = made(1); again.open(); again.frame({ type: "snapshot", payload: { revision: 1, rest: {} } }); + const newRead = outcome(requestFileBytes("/repo/new.bin")); + const request = JSON.parse(again.sent.at(-1)!) as { payload: { request_id: string } }; old.closeWith(4001, "invalid_token"); await vi.advanceTimersByTimeAsync(nextBackoff(BACKOFF_START_MS)); expect(useShellStore.getState().connection).toBe("live"); expect(FakeSocket.made).toHaveLength(2); + again.frame({ type: "file_bytes_error", payload: { request_id: request.payload.request_id, reason: "read_failed" } }); + expect(await newRead).toBe("read_failed"); shell.close(); }); diff --git a/web/src/ws.ts b/web/src/ws.ts index 04b9e517bc..d1bc60ba0f 100644 --- a/web/src/ws.ts +++ b/web/src/ws.ts @@ -132,6 +132,11 @@ export function connectShell(handlers: Handlers): { dispatch: DispatchFn; sendBi return connection === "moving" || (coreMove !== null && moveUnderWay(coreMove.state)); }; + const clearSocketState = () => { + clearPending("socket_closed"); + resetBrowserComments(); + }; + const open = () => { if (closed) return; const token = tokenFromLocation(); @@ -276,8 +281,7 @@ export function connectShell(handlers: Handlers): { dispatch: DispatchFn; sendBi // Only the socket that died fails its own reads; a stale socket's close // must not reject a read in flight on its successor. if (socket === ws) { - clearPending("socket_closed"); - resetBrowserComments(); + clearSocketState(); } // A socket a newer one replaced (a new token in the address) ends // without a say in the window's state: its refusal is the old token's. @@ -321,6 +325,9 @@ export function connectShell(handlers: Handlers): { dispatch: DispatchFn; sendBi backoff = BACKOFF_START_MS; healthFails = 0; const replaced = socket; + // Retire reads owned by the old socket before a successor can start + // any. Its eventual close must leave the successor's reads alone. + clearSocketState(); open(); replaced?.close(); }; From a30c900453d8a797812e3ee249d15abdb0f1c1fe Mon Sep 17 00:00:00 2001 From: yansfil Date: Tue, 10 Nov 2026 21:47:53 +0900 Subject: [PATCH 7/7] refactor: share remote pane topology across state projection --- hide-core/src/runtime.rs | 21 +++++++++++++-------- hide-core/src/runtime/agents.rs | 17 +++++------------ hide-core/src/runtime/session.rs | 11 ++--------- 3 files changed, 20 insertions(+), 29 deletions(-) diff --git a/hide-core/src/runtime.rs b/hide-core/src/runtime.rs index 62ce1908d7..3e042033d9 100644 --- a/hide-core/src/runtime.rs +++ b/hide-core/src/runtime.rs @@ -1028,6 +1028,18 @@ fn prune_pane_text_scales( scales.len() != before } +/// Every pane the remote topology holds, independent of agent detection or focus. +fn remote_live_pane_ids(session: &RemoteSessionSnapshot) -> HashSet { + session + .workspaces + .iter() + .flat_map(|workspace| workspace.checkouts.iter()) + .flat_map(|checkout| checkout.tabs.iter()) + .flat_map(|tab| tab.panes.iter()) + .map(|pane| pane.id.clone()) + .collect() +} + /// Every pane `session` lists, and the panes on screen: while its machine /// is in front, exactly the tabs its selected group shows. Without a core /// layout, the legacy engine-focused tab supplies the initial canvas. @@ -1036,14 +1048,7 @@ fn remote_terminal_pane_sets( target_is_active: bool, shown_tabs: Option<&[String]>, ) -> (HashSet, HashSet) { - let live_pane_ids = session - .workspaces - .iter() - .flat_map(|workspace| workspace.checkouts.iter()) - .flat_map(|checkout| checkout.tabs.iter()) - .flat_map(|tab| tab.panes.iter()) - .map(|pane| pane.id.clone()) - .collect::>(); + let live_pane_ids = remote_live_pane_ids(session); if !target_is_active { return (live_pane_ids, HashSet::new()); } diff --git a/hide-core/src/runtime/agents.rs b/hide-core/src/runtime/agents.rs index 26067494b5..a38f1d8cab 100644 --- a/hide-core/src/runtime/agents.rs +++ b/hide-core/src/runtime/agents.rs @@ -1711,16 +1711,9 @@ impl Runtime { &mut self, target_id: &str, session: &mut RemoteSessionSnapshot, + live_pane_ids: &HashSet, ) -> bool { let look = self.reading_device_look(target_id, session); - let live_pane_ids = session - .workspaces - .iter() - .flat_map(|workspace| workspace.checkouts.iter()) - .flat_map(|checkout| checkout.tabs.iter()) - .flat_map(|tab| tab.panes.iter()) - .map(|pane| pane.id.clone()) - .collect::>(); // The lineage comes first because the read fingerprint carries what // each row's descendants are doing, and that is only known once the // tree is built (PRD B5). @@ -1737,17 +1730,17 @@ impl Runtime { &mut session.agents, Some(target_id), ReadRecordScope::Remote(target_id), - Some(&live_pane_ids), + Some(live_pane_ids), ); self.apply_pane_launches( &mut session.agents, ReadRecordScope::Remote(target_id), - Some(&live_pane_ids), + Some(live_pane_ids), ); self.lay_start_prompts( &mut session.agents, ReadRecordScope::Remote(target_id), - Some(&live_pane_ids), + Some(live_pane_ids), ); self.lay_unseen_views(&mut session.agents); self.lay_human_turns(&mut session.agents); @@ -1759,7 +1752,7 @@ impl Runtime { let mut records = std::mem::take(&mut self.snapshot.ui_state.pane_read_records); let mut changes = crate::agent_state::prune_read_records( &mut records, - &live_pane_ids, + live_pane_ids, ReadRecordScope::Remote(target_id), ); let connection = self.read_connection(Some(target_id)); diff --git a/hide-core/src/runtime/session.rs b/hide-core/src/runtime/session.rs index f790c56447..064c5d2797 100644 --- a/hide-core/src/runtime/session.rs +++ b/hide-core/src/runtime/session.rs @@ -2063,17 +2063,10 @@ impl Runtime { self.overlay_remote_pane_moves(target_id, session); // A node that dials this core sleeps as the core's own machine // does (PRD core-host-node-remote-core B13). - let live_pane_ids = session - .workspaces - .iter() - .flat_map(|workspace| workspace.checkouts.iter()) - .flat_map(|checkout| checkout.tabs.iter()) - .flat_map(|tab| tab.panes.iter()) - .map(|pane| pane.id.clone()) - .collect::>(); + let live_pane_ids = remote_live_pane_ids(session); self.stamp_node_agent_sleep(target_id, &mut session.agents, &live_pane_ids); self.lay_plan_reviews(target_id, &mut session.agents); - read_changed = self.apply_remote_read_state(target_id, session); + read_changed = self.apply_remote_read_state(target_id, session, &live_pane_ids); for workspace in &mut session.workspaces { for checkout in &mut workspace.checkouts { for tab in &mut checkout.tabs {