Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(relay): agent:status-snapshot so a joining tab starts with the host's states

review115f3684b8da
diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.ts
index 591108360..1d63ed134 100644
--- a/src/core/agent-status-mirror.ts
+++ b/src/core/agent-status-mirror.ts
@@ -2270,6 +2270,15 @@ export function mirrorEntry(nodeId: string): MirrorEntry | undefined {
return state.get(nodeId)
}
+/**
+ * Every mirror entry, as a fresh array of `[nodeId, entry]` — the `agent:status-snapshot` a late
+ * relay tab starts from reads it (core/agent-status-snapshot.ts). Read-only by contract, like
+ * `mirrorEntry`: the array is a copy, the entries are the live ones.
+ */
+export function mirrorEntries(): ReadonlyArray<readonly [string, Readonly<MirrorEntry>]> {
+ return [...state]
+}
+
/**
* Every node whose CURRENT agent session is `sessionId` (usually one; a session resumed in two nodes
* is two). Read-only peek: the relay access policies attribute a `context:update` — keyed by the
diff --git a/src/core/agent-status-snapshot.test.ts b/src/core/agent-status-snapshot.test.ts
new file mode 100644
index 000000000..3979882af
--- /dev/null
+++ b/src/core/agent-status-snapshot.test.ts
@@ -0,0 +1,69 @@
+// `agent:status-snapshot` — what a relay tab that joins late reads to start from the host's states
+// (bug D). Built from the agent-status mirror, registered by both shells.
+import { afterEach, describe, expect, it } from 'vitest'
+import { AGENT_STATUS_SNAPSHOT_MAX } from '../shared/agent-status-snapshot'
+import { IPC } from '../shared/ipc'
+import type { CorePlatform } from './platform'
+import { _resetForTest, recordAgentEvent, type MirrorEntry } from './agent-status-mirror'
+import { buildAgentStatusSnapshot, registerAgentStatusSnapshotIpc } from './agent-status-snapshot'
+
+const account = { configDir: '/home/u/.claude', accountId: null, known: false }
+
+const ENTRIES: Array<[string, MirrorEntry]> = [
+ ['live', { state: 'working', agentId: 'claude', sessionId: 's-live', account, updatedAt: 300, stateVerified: true }],
+ ['expired', { agentId: 'codex', sessionId: 's-expired', updatedAt: 200, stateExpired: true }],
+ ['restored', { state: 'done', agentId: 'claude', sessionId: 's-restored', updatedAt: 100, restored: true, stateVerified: false }]
+]
+
+const entry = (nodeId: string) => {
+ const e = buildAgentStatusSnapshot(ENTRIES).find((x) => x.nodeId === nodeId)
+ if (!e) throw new Error(`no snapshot entry for ${nodeId}`)
+ return e
+}
+
+afterEach(() => _resetForTest())
+
+describe('buildAgentStatusSnapshot', () => {
+ it('maps mirror entries to snapshot entries', () => {
+ // Only the five fields a joiner's store takes travel: no proof, no clock, no inbox ticket.
+ expect(entry('live')).toEqual({ nodeId: 'live', state: 'working', agentId: 'claude', sessionId: 's-live', account })
+ })
+
+ it('omits state for identity-only and restored entries', () => {
+ expect(entry('expired').state).toBeUndefined()
+ expect(entry('restored').state).toBeUndefined()
+ expect(entry('expired').sessionId).toBe('s-expired') // identity still travels
+ expect(entry('expired').agentId).toBe('codex')
+ expect(entry('restored').sessionId).toBe('s-restored')
+ expect('state' in entry('restored')).toBe(false)
+ })
+
+ it('keeps the newest AGENT_STATUS_SNAPSHOT_MAX entries by updatedAt', () => {
+ const many: Array<[string, MirrorEntry]> = []
+ // Inserted oldest-last, so a cap that kept insertion order would keep the wrong end.
+ for (let i = AGENT_STATUS_SNAPSHOT_MAX + 50; i > 0; i--) {
+ many.push([`n${i}`, { state: 'done', agentId: 'claude', updatedAt: i }])
+ }
+ const out = buildAgentStatusSnapshot(many)
+ expect(out).toHaveLength(AGENT_STATUS_SNAPSHOT_MAX)
+ const ids = new Set(out.map((e) => e.nodeId))
+ expect(ids.has(`n${AGENT_STATUS_SNAPSHOT_MAX + 50}`)).toBe(true) // the newest
+ expect(ids.has('n51')).toBe(true) // the oldest one kept
+ expect(ids.has('n50')).toBe(false) // the newest one dropped
+ })
+
+ it('registers agent:status-snapshot on the platform', async () => {
+ const handlers = new Map<string, (...args: unknown[]) => unknown>()
+ const platform = { handle: (ch: string, fn: (...args: unknown[]) => unknown) => void handlers.set(ch, fn) } as unknown as CorePlatform
+ registerAgentStatusSnapshotIpc(platform)
+ expect([...handlers.keys()]).toEqual([IPC.agentStatusSnapshot])
+ // The default read is the REAL mirror, as each shell's hook events left it.
+ recordAgentEvent({ nodeId: 'term-a', agentId: 'claude', kind: 'state', state: 'working', sessionId: 's1', newTurn: true })
+ expect(await handlers.get(IPC.agentStatusSnapshot)!()).toEqual([
+ { nodeId: 'term-a', state: 'working', agentId: 'claude', sessionId: 's1' }
+ ])
+ // An injected read replaces it.
+ registerAgentStatusSnapshotIpc(platform, () => [{ nodeId: 'x' }])
+ expect(await handlers.get(IPC.agentStatusSnapshot)!()).toEqual([{ nodeId: 'x' }])
+ })
+})
diff --git a/src/core/agent-status-snapshot.ts b/src/core/agent-status-snapshot.ts
new file mode 100644
index 000000000..4309c8195
--- /dev/null
+++ b/src/core/agent-status-snapshot.ts
@@ -0,0 +1,39 @@
+// `agent:status-snapshot` — the host's agent states as they stand, read off the agent-status mirror
+// for a relay tab that joins after the host already saw events (bug D). Registered by BOTH shells;
+// the response is narrowed for a non-editor by `narrowResponseForRole` (relay/access-policy.ts).
+import { AGENT_STATUS_SNAPSHOT_MAX, type AgentStatusSnapshotEntry } from '../shared/agent-status-snapshot'
+import { IPC } from '../shared/ipc'
+import { mirrorEntries, type MirrorEntry } from './agent-status-mirror'
+import type { CorePlatform } from './platform'
+
+/**
+ * The snapshot of `entries`: the newest `AGENT_STATUS_SNAPSHOT_MAX` by `updatedAt`, each reduced to
+ * the fields a joiner's store takes. Pure.
+ *
+ * `state` is left out for an identity-only entry (`stateExpired`) and for one restored from disk
+ * (`restored`): neither is an observation made this run, and a joiner shown a 6-hour-old `working`
+ * would read it as live. Their identity (agent, session, account) still travels — that is what lets
+ * the joiner's chat view and account chip find the node's session.
+ */
+export function buildAgentStatusSnapshot(
+ entries: Iterable<readonly [string, Readonly<MirrorEntry>]>
+): AgentStatusSnapshotEntry[] {
+ const sorted = [...entries].sort((a, b) => b[1].updatedAt - a[1].updatedAt).slice(0, AGENT_STATUS_SNAPSHOT_MAX)
+ return sorted.map(([nodeId, e]) => {
+ const out: AgentStatusSnapshotEntry = { nodeId }
+ if (e.state !== undefined && !e.stateExpired && !e.restored) out.state = e.state
+ if (e.agentId !== undefined) out.agentId = e.agentId
+ if (e.sessionId !== undefined) out.sessionId = e.sessionId
+ if (e.account !== undefined) out.account = e.account
+ return out
+ })
+}
+
+/** Serve `agent:status-snapshot` on `platform`; `read` defaults to the live mirror. */
+export function registerAgentStatusSnapshotIpc(
+ platform: CorePlatform,
+ read: () => AgentStatusSnapshotEntry[] = () => buildAgentStatusSnapshot(mirrorEntries())
+): void {
+ // No arguments: a peer's are ignored rather than handed to `read`.
+ platform.handle(IPC.agentStatusSnapshot, () => read())
+}
diff --git a/src/core/relay/access-policy.test.ts b/src/core/relay/access-policy.test.ts
index eede255f0..fd0f0754e 100644
--- a/src/core/relay/access-policy.test.ts
+++ b/src/core/relay/access-policy.test.ts
@@ -616,6 +616,22 @@ describe('narrowResponseForRole', () => {
const r = { anything: 1 }
expect(narrowResponseForRole(IPC.fsRead, r, ctx('viewer'))).toBe(r)
})
+ // The agent-status snapshot names every node the host's mirror holds, keyed by node, with its
+ // session id and account: a non-editor gets the shared nodes' entries only, as with `agent:status`.
+ const NODE = 'n1'
+ const viewerCtx = ctx('viewer')
+ it('narrowResponseForRole trims agent:status-snapshot to shared nodes', () => {
+ const out = narrowResponseForRole(IPC.agentStatusSnapshot, [{ nodeId: NODE }, { nodeId: 'other' }], viewerCtx)
+ expect(out).toEqual([{ nodeId: NODE }])
+ expect(narrowResponseForRole(IPC.agentStatusSnapshot, [{ nodeId: 'n2', state: 'working' }], ctx('commenter'))).toEqual([])
+ expect(narrowResponseForRole(IPC.agentStatusSnapshot, 'garbage', viewerCtx)).toEqual([])
+ const all = [{ nodeId: NODE }, { nodeId: 'other' }]
+ expect(narrowResponseForRole(IPC.agentStatusSnapshot, all, ctx('editor'))).toBe(all)
+ })
+ it('a viewer and a commenter may call agent:status-snapshot', () => {
+ expect(decideAccess('req', IPC.agentStatusSnapshot, [], ctx('viewer'))).toEqual({ allow: true })
+ expect(decideAccess('req', IPC.agentStatusSnapshot, [], ctx('commenter'))).toEqual({ allow: true })
+ })
})
// C1 / R43. `git show <ref>:<p>` resolves a bare <p> against the REPOSITORY'S TOP LEVEL, not the cwd:
diff --git a/src/core/relay/access-policy.ts b/src/core/relay/access-policy.ts
index cdc3ab06c..61c18acd3 100644
--- a/src/core/relay/access-policy.ts
+++ b/src/core/relay/access-policy.ts
@@ -267,6 +267,8 @@ export const VIEW: Readonly<Record<string, Check>> = Object.freeze({
[IPC.gitHistory]: gitView(),
// The RESPONSE is trimmed by narrowResponseForRole (it is a response, not an event).
[IPC.agentSubagentSnapshot]: pass,
+ // Same: the host's per-node agent states for a late joiner, trimmed to the shared nodes.
+ [IPC.agentStatusSnapshot]: pass,
[IPC.presenceHello]: pass,
[IPC.presenceCursor]: pass,
[IPC.presenceFocus]: pass,
@@ -640,15 +642,20 @@ export function filterOutboundEvent(json: string, ctx: AccessContext, subagentOw
return false
}
+/** The snapshot responses keyed by node, trimmed to the shared nodes for a non-editor: the subagent
+ * snapshot (every running subagent's task text) and the agent-status snapshot (every node's state,
+ * session id and account). */
+const NODE_KEYED_SNAPSHOTS: ReadonlySet<string> = new Set([IPC.agentSubagentSnapshot, IPC.agentStatusSnapshot])
+
/**
- * A response the peer asked for that no argument check can narrow. Only the subagent snapshot today:
- * it holds every running subagent's task text, keyed by node. Editors and every other method pass
- * through unchanged. Wire it into the host's `narrowResponse` hook.
+ * A response the peer asked for that no argument check can narrow: the node-keyed snapshots above,
+ * and the workspace with its exec fields removed. Editors and every other method pass through
+ * unchanged. Wire it into the host's `narrowResponse` hook.
*/
export function narrowResponseForRole(method: string, result: unknown, ctx: AccessContext): unknown {
if (isEditor(ctx.role)) return result
if (method === IPC.workspaceLoad) return redactWorkspaceExec(result)
- if (method !== IPC.agentSubagentSnapshot) return result
+ if (!NODE_KEYED_SNAPSHOTS.has(method)) return result
return Array.isArray(result) ? result.filter((e) => sharedNode(field(e, 'nodeId'), ctx)) : []
}
diff --git a/src/core/relay/scoped-guest-policy.test.ts b/src/core/relay/scoped-guest-policy.test.ts
index fecfd80b0..802a4fff6 100644
--- a/src/core/relay/scoped-guest-policy.test.ts
+++ b/src/core/relay/scoped-guest-policy.test.ts
@@ -410,6 +410,14 @@ describe('scoped guest — what it receives', () => {
// A hosted team's shared set: a viewer of a hosted team receives it, a Team Access guest never.
expect(filterScopedEvent(ev(IPC.relayHostedSharedChanged, { projectIds: ['alpha', 'beta'] }), s, owners)).toBe(false)
})
+ it("a scoped guest's snapshot holds only its project's nodes", () => {
+ const hooks = scopedGuestHooks('alpha', deps())
+ const session = null as never
+ const mine = 'a1'
+ const theirs = 'b1'
+ expect(allowed(IPC.agentStatusSnapshot)).toBe(true)
+ expect(hooks.narrowResponse!(session, IPC.agentStatusSnapshot, [{ nodeId: mine }, { nodeId: theirs }])).toEqual([{ nodeId: mine }])
+ })
it('delivers terminal bytes only for the shared project\'s sessions', () => {
const hooks = scopedGuestHooks('alpha', deps())
const got: string[] = []
diff --git a/src/core/relay/scoped-guest-policy.ts b/src/core/relay/scoped-guest-policy.ts
index 4dd1519d1..d79cea959 100644
--- a/src/core/relay/scoped-guest-policy.ts
+++ b/src/core/relay/scoped-guest-policy.ts
@@ -481,8 +481,9 @@ export const SCOPED: Readonly<Record<string, Check>> = Object.freeze({
[IPC.githubIssuesPullChecks]: projectArg0,
[IPC.githubProjectAvatar]: projectArg0,
- // Agent status actions, per node. The subagent snapshot's RESPONSE is narrowed below.
+ // Agent status actions, per node. The two snapshots' RESPONSES are narrowed below.
[IPC.agentSubagentSnapshot]: pass,
+ [IPC.agentStatusSnapshot]: pass,
[IPC.agentHibernated]: nodeField0,
[IPC.agentAnswerPermission]: nodeField0,
[IPC.agentAckDone]: nodeArg0,
@@ -689,7 +690,7 @@ export function filterScopedEvent(json: string, s: Scope, owners: SubagentOwners
/**
* The hooks that make a Team Access session bound to `projectId` a boundary. Every peer message is
* judged by `SCOPED` (inbound), `filterScopedEvent` / terminal-frame attribution (outbound), and the
- * subagent snapshot is narrowed to the shared project's nodes.
+ * subagent and agent-status snapshots are narrowed to the shared project's nodes.
*/
export function scopedGuestHooks(projectId: string, deps: ScopedGuestDeps): RelayHostHooks {
const s = makeScope(projectId, deps)
diff --git a/src/main/index.ts b/src/main/index.ts
index e349dd0d5..404312bed 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -5,6 +5,7 @@ import { createRemoteContextEnsure } from '../core/remote-context-ensure'
import { isKnownRemoteCodexAccount } from '../core/remote-ssh/codex-home'
import { createRemoteCodexContext, type RemoteCodexContextTarget } from '../core/remote-ssh/codex-context'
import { subagentReplay } from '../core/subagent-replay'
+import { registerAgentStatusSnapshotIpc } from '../core/agent-status-snapshot'
import { grokHomeDir, grokSessionDir, grokSessionsDir } from '../core/agents/grok-paths'
import { join, resolve, posix } from 'path'
import { startSessionNameSweep, displayNodeTitle } from '../core/session-name-sweep'
@@ -3532,6 +3533,8 @@ app.whenReady().then(async () => {
// (phone Inbox archives the card) and re-sends an 'end' live-update so the paired phone dismisses
// its lingering DONE Live Activity. Fire-and-forget; the mirror no-ops with no unresolved done.
corePlatform.handle(IPC.agentSubagentSnapshot, () => subagentReplay.snapshot())
+ // The host's per-node agent states off the mirror, for a relay tab that joins late (bug D).
+ registerAgentStatusSnapshotIpc(corePlatform)
corePlatform.handle(IPC.agentAckDone, (nodeId: string) => {
ackDone(nodeId)
})
diff --git a/src/preload/index.ts b/src/preload/index.ts
index e033eea97..2a611e815 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -978,6 +978,7 @@ const api: NodeTerminalApi = {
ipcRenderer.on(IPC.agentStatus, handler)
return () => ipcRenderer.removeListener(IPC.agentStatus, handler)
}, () => ipcRenderer.invoke(IPC.agentSubagentSnapshot), listener),
+ agentStatusSnapshot: () => ipcRenderer.invoke(IPC.agentStatusSnapshot),
reportHibernated: (nodeId, on) => ipcRenderer.send(IPC.agentHibernated, { nodeId, on }),
seedAgentIdentity: (entries) => ipcRenderer.send(IPC.agentSeedIdentity, entries),
onAgentWake: (listener) => {
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index b9550ae89..b1be4255d 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -132,6 +132,7 @@ export function buildStubApi(): Omit<
| 'canvas'
| 'dialog'
| 'onAgentStatus'
+ | 'agentStatusSnapshot'
| 'onSubagentActivity'
| 'onUnreadClear'
| 'answerPermission'
@@ -774,6 +775,7 @@ export function buildStubApi(): Omit<
| 'canvas'
| 'dialog'
| 'onAgentStatus'
+ | 'agentStatusSnapshot'
| 'onSubagentActivity'
| 'onUnreadClear'
| 'answerPermission'
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 345217ae4..a90941bd4 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -1,5 +1,6 @@
import type { ChatCatalog } from '@shared/chat-catalog'
import type { NormalizedAgentEvent } from '../../shared/agents/normalize'
+import type { AgentStatusSnapshotEntry } from '../../shared/agent-status-snapshot'
import { subscribeAgentReplay } from '../../shared/agent-replay-subscription'
import type { DesktopWallpaper, WallpaperStill } from '../../shared/wallpaper'
import type { AlertSoundSaveResult } from '../../shared/alert-sound'
@@ -841,6 +842,7 @@ export function buildAgentApi(
): Pick<
NodeTerminalApi,
| 'onAgentStatus'
+ | 'agentStatusSnapshot'
| 'onSubagentActivity'
| 'onUnreadClear'
| 'answerPermission'
@@ -857,6 +859,9 @@ export function buildAgentApi(
(cb) => client.subscribe(IPC.agentStatus, cb as Listener),
() => client.request(IPC.agentSubagentSnapshot) as Promise<NormalizedAgentEvent[]>, listener
),
+ // REAL request: the core's mirror answers it, so a browser tab (and, through relay-api's spread,
+ // a relay tab, whose host narrows it for a non-editor) starts from the states the host holds.
+ agentStatusSnapshot: () => client.request(IPC.agentStatusSnapshot) as Promise<AgentStatusSnapshotEntry[]>,
// REAL forward: the Server Edition writes its own agent-status mirror, and the phone reads it
// over its SSH browse path — a browser canvas hibernating a node must reach that file too.
reportHibernated: (nodeId, on) => {
diff --git a/src/renderer/session/relay-agent-status.test.ts b/src/renderer/session/relay-agent-status.test.ts
index 05973a633..ae45a6bba 100644
--- a/src/renderer/session/relay-agent-status.test.ts
+++ b/src/renderer/session/relay-agent-status.test.ts
@@ -4,6 +4,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { NormalizedAgentEvent } from '@shared/agents/normalize'
import type { NodeTerminalApi } from '@shared/types'
+import type { AgentStatusSnapshotEntry } from '@shared/agent-status-snapshot'
import { createAgentStatusSession, STALE_WORKING_MS, type AgentNodeStatus } from '../state/agentStatus'
import { applyAgentEvent } from '../state/applyAgentEvent'
import { useAgentNodes } from '../state/agentNodes'
@@ -26,21 +27,46 @@ const ev = (over: Partial<NormalizedAgentEvent> = {}): NormalizedAgentEvent => (
const working = ev({ state: 'working', newTurn: true, task: 'hello', sessionId: 's1' })
const doneEvent = ev({ state: 'done', lastMessage: 'all green' })
-/** A relay api whose only member is `onAgentStatus`: it keeps the listener and hands back a spy. */
+/** A relay api with the two members the wiring uses: `onAgentStatus` keeps the listener and hands
+ * back a spy; `agentStatusSnapshot` returns a promise the test settles (`resolve` / `reject`).
+ * `order` records the calls, so the test can see the subscription comes first. */
function fakeApi() {
let cb: ((e: NormalizedAgentEvent) => void) | null = null
const unsub = vi.fn()
- const api: Pick<NodeTerminalApi, 'onAgentStatus'> = {
+ const order: string[] = []
+ let settle: { resolve: (v: AgentStatusSnapshotEntry[]) => void; reject: (e: unknown) => void } | null = null
+ const api: Pick<NodeTerminalApi, 'onAgentStatus' | 'agentStatusSnapshot'> = {
onAgentStatus: vi.fn((listener: (e: NormalizedAgentEvent) => void) => {
+ order.push('subscribe')
cb = listener
return unsub
+ }),
+ agentStatusSnapshot: vi.fn(() => {
+ order.push('snapshot')
+ return new Promise<AgentStatusSnapshotEntry[]>((resolve, reject) => {
+ settle = { resolve, reject }
+ })
})
}
const fire = (e: NormalizedAgentEvent): void => {
if (!cb) throw new Error('nothing subscribed')
cb(e)
}
- return { api, unsub, fire }
+ const resolve = (entries: AgentStatusSnapshotEntry[]): void => {
+ if (!settle) throw new Error('no snapshot was asked for')
+ settle.resolve(entries)
+ }
+ const reject = (err: unknown): void => {
+ if (!settle) throw new Error('no snapshot was asked for')
+ settle.reject(err)
+ }
+ return { api, unsub, fire, order, resolve, reject }
+}
+
+/** Let a settled snapshot promise run its handlers. */
+const flush = async (): Promise<void> => {
+ await Promise.resolve()
+ await Promise.resolve()
}
let status: ReturnType<typeof createAgentStatusSession>
@@ -221,6 +247,113 @@ describe('wireRelayAgentStatus', () => {
})
})
+describe('wireRelayAgentStatus — the snapshot a late joiner starts from', () => {
+ const byIdOf = () => status.store.getState().byId
+ const doneFor = (nodeId: string): NormalizedAgentEvent => ev({ nodeId, state: 'done', lastMessage: 'ok' })
+
+ it('asks for the snapshot after subscribing, and applies it', async () => {
+ const { api, order, resolve } = fakeApi()
+ const stop = wireRelayAgentStatus(api, status, { hasFocus: () => false })
+ expect(order).toEqual(['subscribe', 'snapshot'])
+ resolve([{ nodeId: 'a', state: 'working', agentId: 'claude', sessionId: 's' }])
+ await flush()
+ const byId = byIdOf()
+ expect(byId.a.state).toBe('working')
+ expect(byId.a.agentId).toBe('claude')
+ expect(byId.a.sessionId).toBe('s')
+ // No clock: the joiner saw no transition, and a stamped one would claim it did.
+ expect(byId.a.lastEventAt).toBeUndefined()
+ expect(byId.a.stateAt).toBeUndefined()
+ expect(byId.a.lastSeen).toBeUndefined()
+ expect(byId.a.unread).toBe(false)
+ stop()
+ })
+
+ it('a live event that lands before the snapshot is not overwritten by it', async () => {
+ const { api, fire, resolve } = fakeApi()
+ const stop = wireRelayAgentStatus(api, status, { hasFocus: () => false })
+ const set = vi.spyOn(status.store, 'setState')
+ fire(doneFor('a'))
+ set.mockClear()
+ resolve([
+ { nodeId: 'a', state: 'working', sessionId: 'stale' },
+ { nodeId: 'b', state: 'blocked', agentId: 'codex' }
+ ])
+ await flush()
+ const byId = byIdOf()
+ expect(byId.a.state).toBe('done')
+ expect(byId.a.sessionId).toBeUndefined()
+ expect(byId.a.unread).toBe(true) // the live finish's own mark, kept
+ // The untouched node is written, and the whole snapshot is ONE store write.
+ expect(byId.b.state).toBe('blocked')
+ expect(set).toHaveBeenCalledTimes(1)
+ stop()
+ })
+
+ it('an entry without state writes identity only', async () => {
+ const { api, resolve } = fakeApi()
+ const stop = wireRelayAgentStatus(api, status, { hasFocus: () => false })
+ const account = { configDir: '/home/u/.claude-2', accountId: 'acc-2', known: true }
+ // Already known here (unread, a session title) before the snapshot lands: the merge keeps it.
+ status.store.setState({ byId: { a: { unread: true, session: 'kept title' } } })
+ resolve([{ nodeId: 'a', agentId: 'claude', sessionId: 's-old', account }])
+ await flush()
+ const a = byIdOf().a
+ expect(a.state).toBeUndefined()
+ expect('state' in a).toBe(false)
+ expect(a.sessionId).toBe('s-old')
+ expect(a.agentId).toBe('claude')
+ // The host's account label is another machine's, exactly as a live relay event records it.
+ expect(a.account).toEqual({ ...account, remote: true })
+ expect(a.unread).toBe(true)
+ expect(a.session).toBe('kept title')
+ stop()
+ })
+
+ it('a snapshot that resolves after teardown writes nothing', async () => {
+ const { api, resolve } = fakeApi()
+ const stop = wireRelayAgentStatus(api, status, { hasFocus: () => false })
+ stop()
+ resolve([{ nodeId: 'a', state: 'working', agentId: 'claude' }])
+ await flush()
+ expect(byIdOf()).toEqual({})
+ })
+
+ it('a rejected snapshot is ignored', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const { api, fire, reject } = fakeApi()
+ const stop = wireRelayAgentStatus(api, status, { hasFocus: () => false })
+ fire(working)
+ const before = structuredClone(byIdOf())
+ // An older host has no handler for the channel.
+ reject(Object.assign(new Error('no handler for agent:status-snapshot'), { code: 'E_NO_HANDLER' }))
+ await flush()
+ expect(byIdOf()).toEqual(before)
+ expect(warn).toHaveBeenCalledTimes(1)
+ // A rejection that lands after teardown says nothing: the session is gone, not the host's handler.
+ warn.mockClear()
+ const late = fakeApi()
+ const stopLate = wireRelayAgentStatus(late.api, status, { hasFocus: () => false })
+ stopLate()
+ late.reject(new Error('carrier closed'))
+ await flush()
+ expect(warn).not.toHaveBeenCalled()
+ stop()
+ })
+
+ it('a replayed subagent start does not hold the node out of the snapshot', async () => {
+ // onAgentStatus replays the host's running subagents into the same listener at subscribe time;
+ // a subagent event carries no state, so it is no fresher evidence than the snapshot.
+ const { api, fire, resolve } = fakeApi()
+ const stop = wireRelayAgentStatus(api, status, { hasFocus: () => false })
+ fire(ev({ nodeId: 'a', kind: 'subagent-start', toolUseId: 't-1', taskLabel: 'look around' }))
+ resolve([{ nodeId: 'a', state: 'working', agentId: 'claude', sessionId: 's' }])
+ await flush()
+ expect(byIdOf().a.state).toBe('working')
+ stop()
+ })
+})
+
/** The byId table with only `account.remote` removed — everything else must match exactly. */
function stripAccountRemote(byId: Record<string, AgentNodeStatus>): Record<string, AgentNodeStatus> {
const out: Record<string, AgentNodeStatus> = {}
diff --git a/src/renderer/session/relay-agent-status.ts b/src/renderer/session/relay-agent-status.ts
index c9e93030f..9162a7fb0 100644
--- a/src/renderer/session/relay-agent-status.ts
+++ b/src/renderer/session/relay-agent-status.ts
@@ -14,9 +14,17 @@
// • no subagent cards (`nodes = null`) and no `onSubagentActivity` subscription.
// What it keeps: the unread mark for BOTH alert kinds unless this window is focused on that node
// (Canvas's `watching` rule), and the 60 s stale-working sweep, run on this session's store.
+//
+// A tab that joins after the host already saw events would start blank, since state events are
+// not replayed. So right AFTER subscribing it asks the host for `agent:status-snapshot` (the host's
+// mirror, narrowed to the shared nodes for a non-editor) and writes the entries no live event has
+// touched in the meantime (`applyAgentStatusSnapshot`). A host without the channel rejects; the tab
+// then simply starts from the live events, as before.
+import type { StoreApi } from 'zustand'
+import type { AgentStatusSnapshotEntry } from '@shared/agent-status-snapshot'
import type { NodeTerminalApi } from '@shared/types'
-import type { AgentStatusSession } from '../state/agentStatus'
+import type { AgentNodeStatus, AgentStatusSession, AgentStatusStore } from '../state/agentStatus'
import { applyAgentEvent } from '../state/applyAgentEvent'
/** The Canvas sweep interval for the default store's stale-working decay. */
@@ -29,20 +37,63 @@ export interface RelayAgentStatusDeps {
sweepMs?: number
}
-/** Subscribe `api.onAgentStatus` into `status` until the returned teardown runs. */
+/**
+ * Write the entries no live event has touched; never stamps a clock. Returns how many it wrote.
+ *
+ * One `setState` for the whole snapshot. Each entry merges only the fields it carries (`state`,
+ * `agentId`, `sessionId`, `account`) onto whatever the node already has, so an identity-only entry
+ * (no `state`) leaves the state alone and `unread` is kept (default `false`). `lastEventAt`,
+ * `stateAt` and `lastSeen` are NEVER set: the joiner saw no transition, a fabricated clock would
+ * claim one, and the sidebar sorts a missing clock last. The account is recorded as another
+ * machine's (`remote: true`), exactly as the live relay events record it.
+ */
+export function applyAgentStatusSnapshot(
+ status: Pick<StoreApi<AgentStatusStore>, 'getState' | 'setState'>,
+ entries: readonly AgentStatusSnapshotEntry[],
+ liveSeen: ReadonlySet<string>
+): number {
+ if (!Array.isArray(entries)) return 0
+ const prev = status.getState().byId
+ // Collected as pairs and built with `Object.fromEntries`, which defines own properties: a node id
+ // is the host's string, and an assignment to `byId['__proto__']` would set a prototype instead.
+ const writes = new Map<string, AgentNodeStatus>()
+ for (const entry of entries) {
+ const nodeId = entry?.nodeId
+ if (typeof nodeId !== 'string' || !nodeId || liveSeen.has(nodeId)) continue
+ const existing = writes.get(nodeId) ?? (Object.hasOwn(prev, nodeId) ? prev[nodeId] : undefined)
+ const merged: AgentNodeStatus = { ...existing, unread: existing?.unread ?? false }
+ if (entry.state !== undefined) merged.state = entry.state
+ if (entry.agentId !== undefined) merged.agentId = entry.agentId
+ if (entry.sessionId !== undefined) merged.sessionId = entry.sessionId
+ if (entry.account !== undefined) merged.account = { ...entry.account, remote: true }
+ writes.set(nodeId, merged)
+ }
+ if (writes.size > 0) status.setState({ byId: Object.fromEntries([...Object.entries(prev), ...writes]) })
+ return writes.size
+}
+
+/** Subscribe `api.onAgentStatus` into `status` until the returned teardown runs, then ask the host
+ * for the states it already holds (`agentStatusSnapshot`). */
export function wireRelayAgentStatus(
- api: Pick<NodeTerminalApi, 'onAgentStatus'>,
+ api: Pick<NodeTerminalApi, 'onAgentStatus' | 'agentStatusSnapshot'>,
status: AgentStatusSession,
deps: RelayAgentStatusDeps = {}
): () => void {
const hasFocus = deps.hasFocus ?? (() => typeof document !== 'undefined' && document.hasFocus())
const store = status.store
// Set by the teardown. A frame the RpcClient delivers after the session went offline or was
- // disposed must write nothing, and neither may a sweep tick that was already queued.
+ // disposed must write nothing, and neither may a sweep tick that was already queued, nor a
+ // snapshot answered after it.
let disposed = false
+ // Every node a live event touched before the snapshot landed: its live state is newer than (or
+ // as new as) anything the snapshot says, so the snapshot leaves it alone. Subagent events are not
+ // counted: they carry no state, and onAgentStatus replays the host's running subagents into this
+ // same listener at subscribe time, which would otherwise hold exactly the busiest nodes blank.
+ const liveSeen = new Set<string>()
const unsubscribe = api.onAgentStatus((e) => {
if (disposed) return
+ if (e.kind !== 'subagent-start' && e.kind !== 'subagent-end') liveSeen.add(e.nodeId)
const { nodeId, alert } = applyAgentEvent(store, null, e, { observationRemote: true })
if (!alert) return
// Canvas's `watching` gate: unread unless the user is actively in this node's terminal.
@@ -50,6 +101,18 @@ export function wireRelayAgentStatus(
if (!watching) store.getState().markUnread(nodeId)
})
+ // After subscribing, so no event falls between the snapshot and the stream.
+ api.agentStatusSnapshot().then(
+ (entries) => {
+ if (!disposed) applyAgentStatusSnapshot(store, entries, liveSeen)
+ },
+ (err: unknown) => {
+ // An older host has no handler: start from the live events alone, as before. A rejection
+ // after teardown (the carrier closed under the request) is the session ending, not news.
+ if (!disposed) console.warn('[relay] agent:status-snapshot unavailable; starting from live events only', err)
+ }
+ )
+
const sweep = setInterval(() => {
if (!disposed) store.getState().sweepStaleWorking()
}, deps.sweepMs ?? SWEEP_MS)
diff --git a/src/renderer/session/relay-tab.test.ts b/src/renderer/session/relay-tab.test.ts
index 522ff81bd..8332238ac 100644
--- a/src/renderer/session/relay-tab.test.ts
+++ b/src/renderer/session/relay-tab.test.ts
@@ -47,12 +47,14 @@ function fakeRelayClient() {
/** A bridged relay api whose `pty.create` is a spy — this is what `LocalTransport(api)` must hit.
* `presenceUnsub` is what the session's held presence teardown calls (onSync's unsubscribe), so a
* drop that "runs the presence teardown" is observable in node env. `agentStatusUnsub` is the same
- * for the session's agent-status subscription (`onAgentStatus`). */
+ * for the session's agent-status subscription (`onAgentStatus`); `agentStatusSnapshot` answers an
+ * empty snapshot, as a host with nothing running does. */
function fakeBridgedApi(ws: Workspace = { version: 2, activeProjectId: '', projects: [] }) {
const ptyCreate = vi.fn().mockResolvedValue({ sessionId: 's1', fresh: false })
const presenceUnsub = vi.fn()
const agentStatusUnsub = vi.fn()
const onAgentStatus = vi.fn(() => agentStatusUnsub)
+ const agentStatusSnapshot = vi.fn().mockResolvedValue([])
const workspaceLoad = vi.fn().mockResolvedValue(ws)
const api = {
marker: 'relay-bridged',
@@ -64,6 +66,7 @@ function fakeBridgedApi(ws: Workspace = { version: 2, activeProjectId: '', proje
onPeer: vi.fn(() => () => {}),
},
onAgentStatus,
+ agentStatusSnapshot,
} as unknown as NodeTerminalApi
return { api, ptyCreate, presenceUnsub, workspaceLoad, onAgentStatus, agentStatusUnsub }
}
diff --git a/src/server/index.ts b/src/server/index.ts
index 1caccc4f1..8a15cd5f9 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -1,4 +1,5 @@
import { subagentReplay } from '../core/subagent-replay'
+import { registerAgentStatusSnapshotIpc } from '../core/agent-status-snapshot'
import fs from 'fs'
import { readAgentSessionName } from '../core/agent-session-name'
import { startSessionNameSweep, displayNodeTitle } from '../core/session-name-sweep'
@@ -656,6 +657,8 @@ export async function startServer(
// inbox event(s) + re-sends an 'end' live-update so the paired phone dismisses its lingering DONE
// Live Activity. Fire-and-forget; no-op with no unresolved done.
platform.handle(IPC.agentSubagentSnapshot, () => subagentReplay.snapshot())
+ // The host's per-node agent states off the mirror, for a relay tab that joins late (parity with desktop).
+ registerAgentStatusSnapshotIpc(platform)
platform.handle(IPC.agentAckDone, (nodeId: string) => {
ackDone(nodeId)
})
diff --git a/src/shared/agent-status-snapshot.ts b/src/shared/agent-status-snapshot.ts
new file mode 100644
index 000000000..f22d8e603
--- /dev/null
+++ b/src/shared/agent-status-snapshot.ts
@@ -0,0 +1,25 @@
+/**
+ * `agent:status-snapshot` — the host's agent states as they stand, for a relay tab that joins late.
+ *
+ * A team tab only hears `agent:status` events from the moment it subscribes, so a node that went
+ * `working` before the tab joined stayed blank until its next hook event (bug D). The joiner now
+ * subscribes FIRST, then asks for this snapshot, and writes only the nodes no live event has touched.
+ *
+ * Built from the host's agent-status mirror (`core/agent-status-snapshot.ts`) and view-filtered for a
+ * Viewer, Commenter or scoped guest by `sharedNode`, exactly like `agent:status` itself.
+ */
+import type { AgentId } from './agents/config'
+import type { AgentState } from './agents/normalize'
+import type { ObservedClaudeAccount } from './types'
+
+export interface AgentStatusSnapshotEntry {
+ nodeId: string
+ /** Absent = unknown: identity-only (stateExpired) or restored from disk. */
+ state?: AgentState
+ agentId?: AgentId
+ sessionId?: string
+ account?: ObservedClaudeAccount
+}
+
+/** At most this many entries, the newest by the mirror's `updatedAt`. */
+export const AGENT_STATUS_SNAPSHOT_MAX = 2000
diff --git a/src/shared/hosted-access.ts b/src/shared/hosted-access.ts
index c66000e9a..ec26cbdf9 100644
--- a/src/shared/hosted-access.ts
+++ b/src/shared/hosted-access.ts
@@ -32,6 +32,7 @@ export const HOSTED_VIEW_METHODS: readonly string[] = Object.freeze([
IPC.gitShowFile,
IPC.gitHistory,
IPC.agentSubagentSnapshot,
+ IPC.agentStatusSnapshot,
IPC.presenceHello,
IPC.presenceCursor,
IPC.presenceFocus,
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 214dc6244..5282004eb 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -182,6 +182,11 @@ export const IPC = {
canvasTrackpadGesture: 'canvas:trackpad-gesture',
agentStatus: 'agent:status',
agentSubagentSnapshot: 'agent:subagent-snapshot',
+ /** Renderer → main/server: the host's current per-node agent states, read off the agent-status
+ * mirror (`AgentStatusSnapshotEntry[]`, shared/agent-status-snapshot.ts). A relay tab asks right
+ * after subscribing to `agent:status`, so a node that went working before it joined is not blank.
+ * The response is view-filtered for non-editors like `agent:status` (access-policy.ts). */
+ agentStatusSnapshot: 'agent:status-snapshot',
/** Renderer → main/server: answer a held Claude permission hook (deterministic approvals).
* Payload: `{ nodeId, pendingId, decision: 'allow'|'deny' }`; resolves boolean. See
* docs/hook-reply-approvals.md. */
diff --git a/src/shared/types.ts b/src/shared/types.ts
index bf845851a..560289500 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1,6 +1,7 @@
import type { ChatPromptResult, EmptyPromptResult, TextDeliveryResult } from './text-delivery'
import type { PushWebhookMinted, PushWebhookResult, PushWebhookTokenInfo } from './push-webhook'
import type { IdentitySeedEntry } from './agent-identity-seed'
+import type { AgentStatusSnapshotEntry } from './agent-status-snapshot'
import type { WhiteboardFile, WhiteboardSaveResult } from './whiteboard'
import type { PrWaitHold } from './pr-wait'
import type { SessionBackend } from './session-backend'
@@ -4759,6 +4760,11 @@ export interface NodeTerminalApi {
onUnreadClear(listener: (nodeId: string) => void): () => void
/** Fires on each normalized agent hook event (working/done/waiting/subagent/…). Returns unsubscribe. */
onAgentStatus(listener: (e: NormalizedAgentEvent) => void): () => void
+ /** The core's per-node agent states as they stand now, read off its agent-status mirror (newest
+ * `AGENT_STATUS_SNAPSHOT_MAX`; no `state` for an identity-only or restored entry). A relay tab asks
+ * right after subscribing to `onAgentStatus`, so it does not start blank; a non-editor peer gets
+ * the shared nodes only. Rejects on a core that predates the channel. */
+ agentStatusSnapshot(): Promise<AgentStatusSnapshotEntry[]>
/** Report a node's Eco hibernation flag to the core (the renderer owns the flag; the core only
* mirrors it into the agent-status file so the phone can render SLEEPING). Fire-and-forget;
* called on every `setHibernated` change and replayed for the persisted set at boot. */
diff --git a/test/acceptance/hosted-relay-agent-status.test.ts b/test/acceptance/hosted-relay-agent-status.test.ts
index abc57714c..82ce9ae8f 100644
--- a/test/acceptance/hosted-relay-agent-status.test.ts
+++ b/test/acceptance/hosted-relay-agent-status.test.ts
@@ -16,7 +16,10 @@
*
* Each relay session subscribes its own api's `onAgentStatus` (`wireRelayAgentStatus`, wired in
* `openRelayTab`) into its own store; the default-store test pins that none of it leaks into the
- * local user's store or its persisted keys.
+ * local user's store or its persisted keys. Right after subscribing it asks for
+ * `agent:status-snapshot`, which the carrier answers from the REAL mirror the hooks fed, narrowed for
+ * the peer's role exactly as the host's `narrowResponse` hook does, so a tab that joins late starts
+ * from the host's states.
*
* Runs in the NODE environment with a real jsdom window installed by hand (`installDom`), not in
* vitest's jsdom environment: that one loads modules through Vite's client transform, which
@@ -28,8 +31,9 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi }
import { JSDOM } from 'jsdom'
import { ServerPlatform } from '../../src/server/platform-server'
import { wireAgentStatus } from '../../src/server/agent-status'
-import { _resetForTest } from '../../src/core/agent-status-mirror'
-import { wrapSinkForRole, type AccessContext } from '../../src/core/relay/access-policy'
+import { _resetForTest, mirrorEntries } from '../../src/core/agent-status-mirror'
+import { buildAgentStatusSnapshot } from '../../src/core/agent-status-snapshot'
+import { narrowResponseForRole, wrapSinkForRole, type AccessContext } from '../../src/core/relay/access-policy'
import { testTmpDir } from '../../src/core/test-tmp'
import { normalizeClaude, type NormalizedAgentEvent } from '../../src/shared/agents/normalize'
import { IPC } from '../../src/shared/ipc'
@@ -41,6 +45,8 @@ import { getSessionStores, resetSessionsForTest } from '../../src/renderer/sessi
import { useAgentStatus } from '../../src/renderer/state/agentStatus'
const NODE = 'term-musuoygd-979507b8'
+/** A node the host runs in a project it does not share. */
+const PRIVATE_NODE = 'term-private-1'
const PROJECT = 'proj-alpha'
const ctxFor = (role: AccessContext['role']): AccessContext => ({
@@ -59,10 +65,13 @@ type ClosedListener = Parameters<RelayClientApi['onClosed']>[1]
/** The joiner's carrier for ONE connection. Records every frame the joiner sends (`sent`), answers
* the requests a hosted tab makes at open the way the host's handlers would (anything else gets
* `null`), and stands in for the preload's `relayClient.onClosed` for this connection so a test
- * can drop it (`drop`). */
+ * can drop it (`drop`). `agent:status-snapshot` is answered from the real mirror, computed when the
+ * request arrives; `holdSnapshot()` keeps that answer in transit until `releaseSnapshot()`. */
class HostTransport implements FrameTransport {
sent: Array<{ t: string; id?: number; method?: string }> = []
private msgCb: ((data: string | Uint8Array) => void) | null = null
+ private snapshotHeld = false
+ private heldSnapshots: Array<() => void> = []
/** Every live `relayClient.onClosed` listener for this connection, in registration order — the
* RpcClient's carrier-closed hook among them, as `RelayFrameTransport.onClose` rides it. */
private closedListeners: ClosedListener[] = []
@@ -83,6 +92,14 @@ class HostTransport implements FrameTransport {
const m = JSON.parse(json) as { t: string; id?: number; method?: string }
this.sent.push(m)
if (m.t !== 'req') return
+ if (m.method === IPC.agentStatusSnapshot) {
+ // The host's handler, then its narrowResponse hook for this peer's role.
+ const result = narrowResponseForRole(IPC.agentStatusSnapshot, buildAgentStatusSnapshot(mirrorEntries()), ctxFor(this.role))
+ const answer = (): void => this.emit(JSON.stringify({ t: 'res', id: m.id, ok: true, result }))
+ if (this.snapshotHeld) this.heldSnapshots.push(answer)
+ else queueMicrotask(answer)
+ return
+ }
const result =
m.method === IPC.relayHostedSelf
? { role: this.role, label: '', hostLabel: 'srv' }
@@ -95,6 +112,19 @@ class HostTransport implements FrameTransport {
: null
queueMicrotask(() => this.emit(JSON.stringify({ t: 'res', id: m.id, ok: true, result })))
}
+ /** Keep every `agent:status-snapshot` answer in transit (already computed) until released. */
+ holdSnapshot(): void {
+ this.snapshotHeld = true
+ }
+ /** Deliver the held snapshot answers, and answer later ones at once again. */
+ releaseSnapshot(): void {
+ this.snapshotHeld = false
+ for (const answer of this.heldSnapshots.splice(0)) answer()
+ }
+ /** How many `agent:status-snapshot` requests the joiner put on this carrier. */
+ snapshotRequests(): number {
+ return this.sent.filter((f) => f.t === 'req' && f.method === IPC.agentStatusSnapshot).length
+ }
onMessage(cb: (data: string | Uint8Array) => void): void {
this.msgCb = cb
}
@@ -153,11 +183,16 @@ interface Peer {
interface Harness {
/** Fire one claude hook POST at the host core, exactly as the hook server hands it to the shell. */
- hook(payload: Record<string, unknown>): void
+ hook(payload: Record<string, unknown>, nodeId?: string): void
/** Drop the VIEWER's relay connection (main reports it closed). */
drop(): void
+ /** Join one more peer to the same host, on a carrier of its own (disposed after the test).
+ * `before` runs on that carrier before the tab opens. */
+ join(role: AccessContext['role'], conn: string, before?: (t: HostTransport) => void): Promise<Peer>
owner: Peer
viewer: Peer
+ /** The peers `join` added. */
+ extra: Peer[]
}
let h: Harness
@@ -179,8 +214,14 @@ afterAll(() => {
dom.window.close()
})
-async function joinAs(platform: ServerPlatform, role: AccessContext['role'], conn: string): Promise<Peer> {
+async function joinAs(
+ platform: ServerPlatform,
+ role: AccessContext['role'],
+ conn: string,
+ before?: (t: HostTransport) => void
+): Promise<Peer> {
const t = new HostTransport(role, hostWorkspace())
+ before?.(t)
// The host side of the peer: the hosted service attaches the relay sink, wrapped for the role.
platform.attach(
wrapSinkForRole(
@@ -230,15 +271,22 @@ beforeEach(async () => {
})
const owner = await joinAs(platform, 'owner', 'conn-owner')
const viewer = await joinAs(platform, 'viewer', 'conn-viewer')
+ const extra: Peer[] = []
h = {
- hook: (payload) => {
- raw?.('claude', NODE, payload, { verified: false })
- const e = normalizeClaude({ nodeId: NODE, agentId: 'claude', payload })
+ hook: (payload, nodeId = NODE) => {
+ raw?.('claude', nodeId, payload, { verified: false })
+ const e = normalizeClaude({ nodeId, agentId: 'claude', payload })
if (e) normalized?.(e)
},
drop: () => viewer.t.drop(),
+ join: async (role, conn, before) => {
+ const peer = await joinAs(platform, role, conn, before)
+ extra.push(peer)
+ return peer
+ },
owner,
- viewer
+ viewer,
+ extra
}
// Harness guard: a relay session's store is never the default one, or the default-store test
// below would contradict the per-session ones.
@@ -248,6 +296,7 @@ beforeEach(async () => {
afterEach(() => {
h.owner.tab.dispose()
h.viewer.tab.dispose()
+ for (const peer of h.extra) peer.tab.dispose()
resetSessionsForTest()
_resetForTest()
vi.restoreAllMocks()
@@ -320,4 +369,66 @@ describe('hosted team tab: agent status reaches the relay session', () => {
await settle()
expect(relayStore(h.viewer.tab).getState().byId[NODE]).toBeUndefined()
})
+
+ it('a tab that joins after the host saw working shows working', async () => {
+ h.hook(working)
+ h.hook(working, PRIVATE_NODE) // a node in a project the host does not share
+ await settle()
+ // Both are in the host's mirror, so the viewer's missing PRIVATE_NODE below is the narrowing.
+ expect(mirrorEntries().map(([id]) => id).sort()).toEqual([NODE, PRIVATE_NODE].sort())
+ let carrier: HostTransport | undefined
+ const late = await h.join('viewer', 'conn-late', (t) => {
+ carrier = t
+ t.holdSnapshot()
+ })
+ await settle()
+ // Asked once, on its own carrier; until the answer lands the tab knows nothing.
+ expect(carrier!.snapshotRequests()).toBe(1)
+ expect(relayStore(late.tab).getState().byId[NODE]).toBeUndefined()
+ carrier!.releaseSnapshot()
+ await settle()
+ const a = relayStore(late.tab).getState().byId[NODE]
+ expect(a?.state).toBe('working')
+ expect(a?.agentId).toBe('claude')
+ expect(a?.sessionId).toBe('s1')
+ expect(a?.unread).toBe(false)
+ // The joiner saw no transition: no clock is claimed for one.
+ expect(a?.lastEventAt).toBeUndefined()
+ expect(a?.stateAt).toBeUndefined()
+ // A viewer's snapshot holds the shared nodes only.
+ expect(relayStore(late.tab).getState().byId[PRIVATE_NODE]).toBeUndefined()
+ })
+
+ it('a live event the host sends while the snapshot is in flight wins over it', async () => {
+ h.hook(working)
+ await settle()
+ let carrier: HostTransport | undefined
+ const late = await h.join('viewer', 'conn-race', (t) => {
+ carrier = t
+ t.holdSnapshot()
+ })
+ await settle()
+ // The snapshot (computed as the request arrived: working) is still in transit when the turn ends.
+ h.hook(done)
+ await settle()
+ expect(relayStore(late.tab).getState().byId[NODE]?.state).toBe('done')
+ carrier!.releaseSnapshot()
+ await settle()
+ expect(relayStore(late.tab).getState().byId[NODE]?.state).toBe('done')
+ expect(relayStore(late.tab).getState().byId[NODE]?.unread).toBe(true)
+ })
+
+ it('a reconnected session asks for a fresh snapshot', async () => {
+ h.hook(working)
+ await settle()
+ expect(h.viewer.t.snapshotRequests()).toBe(1)
+ h.drop() // handleRelayDrop → takeSessionOffline: the tab reads unknown
+ expect(relayStore(h.viewer.tab).getState().byId[NODE]).toBeUndefined()
+ // The reconnect is a fresh connection and a fresh session (reconnectRelayTab → mount).
+ const back = await h.join('viewer', 'conn-viewer-2')
+ await settle()
+ expect(h.viewer.t.snapshotRequests() + back.t.snapshotRequests()).toBe(2)
+ // No hook fired since the drop: the working the tab shows again is the fresh snapshot's.
+ expect(relayStore(back.tab).getState().byId[NODE]?.state).toBe('working')
+ })
})