feat(agent-dashboard): persist hook status across Orca restart (#1480)

* feat(agent-dashboard): persist hook status across Orca restart

Hydrates the hook server's per-pane lastStatusByPaneKey from
userData/agent-hooks/last-status.json before binding the HTTP listener,
mirrors mutations to disk via a 250ms trailing debounce, and flushes
synchronously on stop(). Renderer dismissals fan out a new
agentStatus:drop IPC so the on-disk file evicts the entry and a
relaunch cannot resurrect it. Adds a bounded bootstrap queue in
useIpcEvents so events replayed by setListener() during window creation
are not dropped while App.tsx is still hydrating tabsByWorktree.

Gated on settings.experimentalAgentDashboard. Done, blocked, and quiet
working rows now all survive across restart.

Co-authored-by: Orca <help@stably.ai>

* fix(agent-dashboard): harden hook persistence IPC and gate-off deletion

Address review findings on the retention-restart branch:

- Wrap agentStatus:getSnapshot and agentStatus:drop IPC handlers in
  try/catch so a throw cannot surface as an unhandled invoke rejection
  (silent startup-hydration failure) or crash main from a fire-and-
  forget listener.
- runStatusPersist no longer permanently suppresses gate-off deletion
  retries on transient unlink errors (e.g. EPERM); deletedOnDisable
  now flips only on success or ENOENT.
- Tighten tests: stale-version-hydrate now asserts the warn message
  content; getSnapshot test uses toEqual; drop-handler test rejects
  null/{}/[] in addition to the prior bad inputs.

Co-authored-by: Orca <help@stably.ai>

* fix(agent-dashboard): bound on-disk hydrate growth and reject tabId/paneKey drift

- Drop hydrate entries older than 7 days (HYDRATE_MAX_AGE_MS) so stale
  rows from worktrees archived weeks ago do not pile up forever. PTY-
  teardown eviction handles closed panes; the TTL covers daemon-restored
  PTYs that never re-attach and crash-recovery paths.
- Reject hydrate entries whose `tabId` field diverges from the paneKey's
  tab segment. Cheap defensive add against future renamer/shape drift.

Doc updated to move TTL out of the follow-ups list (now in scope).
Tests: new "drops hydrate entries older than the TTL cutoff" and "drops
a hydrate entry whose tabId disagrees with the paneKey prefix"; existing
hydrate fixtures now use a `recentTs()` helper instead of fixed 2023
timestamps.

Co-authored-by: Orca <help@stably.ai>

* fix(agent-dashboard): post-review polish on hook status persistence

Apply review-fix corrections on the agent-dashboard restart-persistence
work:

- Split dropStatusEntry from clearPaneState so renderer-driven dismiss
  IPC no longer wipes lastPromptByPaneKey/lastToolByPaneKey for a
  still-alive pane.
- Validate paneKey shape at the IPC boundary (isValidPaneKey).
- Let getSnapshot errors propagate instead of silently returning [] —
  matches the renderer's existing .catch and avoids masking a broken
  persistence path.
- Trust main's authoritative timing.stateStartedAt unconditionally on
  same-state pings; fall back to existing only when timing is absent.
- Use strict < on the snapshot/live updatedAt guard so two events in
  the same millisecond don't drop the second one (a <= guard regressed
  two existing slice tests).
- Don't reset snapshotRequestedForReadyWindow in the catch handler;
  combined with the per-store-update subscriber it would retry-storm
  on persistent IPC failure.
- scheduleStatusPersist now resets the timer on each call (true
  trailing-edge debounce) instead of leading-edge throttle.
- Fix doc references that named clearPaneState in dismiss/IPC context
  where the implementation uses dropStatusEntry; add type-level JSDoc
  on AgentStatusIpcPayload.

109/109 in-scope tests pass.

Co-authored-by: Orca <help@stably.ai>

* fix(agent-dashboard): clean stale on-disk entries during hydrate

- Defensive `lastStatusByPaneKey.clear()` at top of `hydrateLastStatusFromDisk` keeps repeat-start() calls from silently merging prior-session state.
- When sanitize drops entries (drift, TTL, schema), log a single `[agent-hooks] last-status hydrate dropped N entries (kept M)` warn and synchronously rewrite the file. Pre-fix, stale entries stayed on disk until a fresh hook event triggered a debounced write — users who hadn't run an agent in 8+ days would re-drop the same entries every cold boot.
- Prime `lastWrittenJson` from the raw on-disk bytes (instead of re-serializing) when hydration is lossless — robust against future shape drift in `serializeStatusFile`.
- `LAST_STATUS_FILE_VERSION = 2` comment now records why v1 was skipped (in-flight branch shape).
- IPC test mock uses `vi.importActual` for `isValidPaneKey` so it stays in sync with the real validator.

Co-authored-by: Orca <help@stably.ai>

* fix(agent-dashboard): persist acknowledgedAgentsByPaneKey across restart

Without this, agent rows the user already visited come back bold every relaunch now that the rows themselves survive restart (per docs/agent-dashboard-retention-restart.md). Hydrate sanitizes input field-by-field (rejects null/non-object/array, prototype-pollution keys, non-finite/non-positive values) and applies a 7-day TTL paralleling HYDRATE_MAX_AGE_MS in agent-hooks/server.ts so hard-quit/crash paths can't grow the persisted map forever.

Co-authored-by: Orca <help@stably.ai>

* docs(agent-dashboard): drop in-tree retention/restart design doc

Doc was a working artifact for this branch; the rationale lives in commit
history and the comments next to the persistence/hydrate code. Scrubs the
three call-site references that named it.

Co-authored-by: Orca <help@stably.ai>

---------

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Brennan Benson
2026-05-11 10:40:32 -07:00
committed by GitHub
co-authored by Orca
parent 68892b667c
commit 9b8324efb8
19 changed files with 1981 additions and 174 deletions
+427 -27
View File
@@ -74,17 +74,21 @@ describe('AgentHookServer listener replay', () => {
server.setListener(listener)
expect(listener).toHaveBeenCalledTimes(1)
expect(listener).toHaveBeenCalledWith({
paneKey: PANE,
tabId: 'tab-1',
worktreeId: 'wt-1',
connectionId: null,
payload: expect.objectContaining({
state: 'working',
prompt: 'replay me',
agentType: 'claude'
expect(listener).toHaveBeenCalledWith(
expect.objectContaining({
paneKey: PANE,
tabId: 'tab-1',
worktreeId: 'wt-1',
connectionId: null,
receivedAt: expect.any(Number),
stateStartedAt: expect.any(Number),
payload: expect.objectContaining({
state: 'working',
prompt: 'replay me',
agentType: 'claude'
})
})
})
)
} finally {
server.stop()
}
@@ -149,17 +153,21 @@ describe('AgentHookServer listener replay', () => {
const listener = vi.fn()
server.setListener(listener)
expect(listener).toHaveBeenCalledWith({
paneKey: PANE,
tabId: 'tab-1',
worktreeId: 'repo::/tmp/worktree with "quotes"',
connectionId: null,
payload: expect.objectContaining({
state: 'working',
prompt: 'form encoded',
agentType: 'claude'
expect(listener).toHaveBeenCalledWith(
expect.objectContaining({
paneKey: PANE,
tabId: 'tab-1',
worktreeId: 'repo::/tmp/worktree with "quotes"',
connectionId: null,
receivedAt: expect.any(Number),
stateStartedAt: expect.any(Number),
payload: expect.objectContaining({
state: 'working',
prompt: 'form encoded',
agentType: 'claude'
})
})
})
)
} finally {
server.stop()
}
@@ -1206,6 +1214,394 @@ describe('Endpoint file lifecycle', () => {
})
})
describe('Last-status persistence', () => {
let userDataPath: string
beforeEach(() => {
userDataPath = mkdtempSync(join(tmpdir(), 'orca-laststatus-'))
})
afterEach(() => {
rmSync(userDataPath, { recursive: true, force: true })
})
function lastStatusPath(): string {
return join(userDataPath, 'agent-hooks', 'last-status.json')
}
// Why: hydrate now drops entries older than 7d (HYDRATE_MAX_AGE_MS). Use
// a recent-but-not-Date.now() timestamp in fixtures so the tests assert
// hydration behavior rather than racing the wall clock.
function recentTs(offsetMs = 0): number {
return Date.now() - 60 * 60 * 1000 + offsetMs
}
async function postHookEvent(
server: AgentHookServer,
body: Body,
path: string = '/hook/claude'
): Promise<Response> {
const env = server.buildPtyEnv()
return fetch(`http://127.0.0.1:${env.ORCA_AGENT_HOOK_PORT}${path}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Orca-Agent-Hook-Token': env.ORCA_AGENT_HOOK_TOKEN
},
body: JSON.stringify(body)
})
}
it('writes last-status.json after a hook event', async () => {
const server = new AgentHookServer()
await server.start({
env: 'production',
userDataPath
})
try {
await postHookEvent(
server,
buildBody({ hook_event_name: 'UserPromptSubmit', prompt: 'persist me' })
)
// Synchronous flush via stop() captures the trailing-debounced write.
server.flushStatusPersistSync()
expect(existsSync(lastStatusPath())).toBe(true)
const file = JSON.parse(readFileSync(lastStatusPath(), 'utf8'))
expect(file.version).toBe(2)
expect(file.entries[PANE]).toMatchObject({
paneKey: PANE,
tabId: 'tab-1',
worktreeId: 'wt-1',
receivedAt: expect.any(Number),
stateStartedAt: expect.any(Number),
payload: expect.objectContaining({ state: 'working', prompt: 'persist me' })
})
} finally {
server.stop()
}
})
it('hydrates last-status.json into the cache before listener registration', async () => {
// Pre-populate the file directly to simulate a prior session.
mkdirSync(join(userDataPath, 'agent-hooks'), { recursive: true })
const receivedAt = recentTs()
const stateStartedAt = recentTs(-1000)
const fileContents = {
version: 2,
entries: {
[PANE]: {
paneKey: PANE,
tabId: 'tab-1',
worktreeId: 'wt-1',
receivedAt,
stateStartedAt,
payload: {
state: 'done',
prompt: 'survived restart',
agentType: 'claude'
}
}
}
}
writeFileSync(lastStatusPath(), JSON.stringify(fileContents), 'utf8')
const server = new AgentHookServer()
await server.start({
env: 'production',
userDataPath
})
try {
const listener = vi.fn()
server.setListener(listener)
expect(listener).toHaveBeenCalledTimes(1)
expect(listener).toHaveBeenCalledWith(
expect.objectContaining({
paneKey: PANE,
tabId: 'tab-1',
worktreeId: 'wt-1',
receivedAt,
stateStartedAt,
payload: expect.objectContaining({
state: 'done',
prompt: 'survived restart',
agentType: 'claude'
})
})
)
expect(server.getStatusSnapshot()).toEqual([
expect.objectContaining({
paneKey: PANE,
tabId: 'tab-1',
worktreeId: 'wt-1',
receivedAt,
stateStartedAt,
state: 'done',
prompt: 'survived restart',
agentType: 'claude'
})
])
} finally {
server.stop()
}
})
it('treats a corrupt file as empty hydration without throwing', async () => {
mkdirSync(join(userDataPath, 'agent-hooks'), { recursive: true })
writeFileSync(lastStatusPath(), 'not-json{{', 'utf8')
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
const server = new AgentHookServer()
await server.start({
env: 'production',
userDataPath
})
try {
const listener = vi.fn()
server.setListener(listener)
expect(listener).not.toHaveBeenCalled()
expect(warnSpy).toHaveBeenCalled()
} finally {
server.stop()
warnSpy.mockRestore()
}
})
it('rejects a stale version mismatch on hydrate', async () => {
mkdirSync(join(userDataPath, 'agent-hooks'), { recursive: true })
writeFileSync(
lastStatusPath(),
JSON.stringify({
version: 1,
entries: {
[PANE]: {
paneKey: PANE,
receivedAt: 1_700_000_000_000,
stateStartedAt: 1_699_999_999_000,
payload: { state: 'done', prompt: 'old version', agentType: 'claude' }
}
}
}),
'utf8'
)
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
const server = new AgentHookServer()
await server.start({
env: 'production',
userDataPath
})
try {
const listener = vi.fn()
server.setListener(listener)
expect(listener).not.toHaveBeenCalled()
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('version mismatch'))
} finally {
server.stop()
warnSpy.mockRestore()
}
})
it('drops entries with malformed paneKeys but keeps valid ones', async () => {
mkdirSync(join(userDataPath, 'agent-hooks'), { recursive: true })
writeFileSync(
lastStatusPath(),
JSON.stringify({
version: 2,
entries: {
// Missing colon — drop.
'no-colon': {
paneKey: 'no-colon',
receivedAt: 1_700_000_000_000,
stateStartedAt: 1_699_999_999_000,
payload: { state: 'done', prompt: 'bad', agentType: 'claude' }
},
// Embedded paneKey mismatch — drop.
[PANE]: {
paneKey: 'tab-x:99',
receivedAt: 1_700_000_000_000,
stateStartedAt: 1_699_999_999_000,
payload: { state: 'done', prompt: 'mismatch', agentType: 'claude' }
},
// Valid.
'tab-good:0': {
paneKey: 'tab-good:0',
tabId: 'tab-good',
receivedAt: recentTs(),
stateStartedAt: recentTs(-1000),
payload: { state: 'done', prompt: 'survived', agentType: 'claude' }
}
}
}),
'utf8'
)
const server = new AgentHookServer()
await server.start({
env: 'production',
userDataPath
})
try {
const listener = vi.fn()
server.setListener(listener)
expect(listener).toHaveBeenCalledTimes(1)
expect(listener).toHaveBeenCalledWith(
expect.objectContaining({
paneKey: 'tab-good:0',
payload: expect.objectContaining({ prompt: 'survived' })
})
)
} finally {
server.stop()
}
})
it('drops hydrate entries older than the TTL cutoff', async () => {
mkdirSync(join(userDataPath, 'agent-hooks'), { recursive: true })
const eightDaysAgoMs = Date.now() - 8 * 24 * 60 * 60 * 1000
writeFileSync(
lastStatusPath(),
JSON.stringify({
version: 2,
entries: {
// Stale — should be dropped.
'tab-old:0': {
paneKey: 'tab-old:0',
tabId: 'tab-old',
receivedAt: eightDaysAgoMs,
stateStartedAt: eightDaysAgoMs - 1000,
payload: { state: 'done', prompt: 'old', agentType: 'claude' }
},
// Recent — should survive.
'tab-fresh:0': {
paneKey: 'tab-fresh:0',
tabId: 'tab-fresh',
receivedAt: recentTs(),
stateStartedAt: recentTs(-1000),
payload: { state: 'done', prompt: 'fresh', agentType: 'claude' }
}
}
}),
'utf8'
)
const server = new AgentHookServer()
await server.start({
env: 'production',
userDataPath
})
try {
const snapshot = server.getStatusSnapshot()
expect(snapshot.map((e) => e.paneKey)).toEqual(['tab-fresh:0'])
} finally {
server.stop()
}
})
it('drops a hydrate entry whose tabId disagrees with the paneKey prefix', async () => {
mkdirSync(join(userDataPath, 'agent-hooks'), { recursive: true })
writeFileSync(
lastStatusPath(),
JSON.stringify({
version: 2,
entries: {
'tab-A:0': {
paneKey: 'tab-A:0',
// Why: deliberately divergent — paneKey says tab-A, the entry
// claims tab-B. Sanitizer must drop rather than hydrate this
// inconsistent row.
tabId: 'tab-B',
receivedAt: recentTs(),
stateStartedAt: recentTs(-1000),
payload: { state: 'done', prompt: 'mismatch', agentType: 'claude' }
}
}
}),
'utf8'
)
const server = new AgentHookServer()
await server.start({
env: 'production',
userDataPath
})
try {
expect(server.getStatusSnapshot()).toEqual([])
} finally {
server.stop()
}
})
it('clearPaneState evicts the entry from the on-disk file', async () => {
const server = new AgentHookServer()
await server.start({
env: 'production',
userDataPath
})
try {
await postHookEvent(
server,
buildBody({ hook_event_name: 'UserPromptSubmit', prompt: 'about to drop' })
)
server.flushStatusPersistSync()
let parsed = JSON.parse(readFileSync(lastStatusPath(), 'utf8'))
expect(parsed.entries[PANE]).toBeTruthy()
server.clearPaneState(PANE)
server.flushStatusPersistSync()
parsed = JSON.parse(readFileSync(lastStatusPath(), 'utf8'))
expect(parsed.entries[PANE]).toBeUndefined()
} finally {
server.stop()
}
})
it('skips a write when the serialized contents are byte-identical to the previous write', async () => {
const server = new AgentHookServer()
await server.start({
env: 'production',
userDataPath
})
try {
await postHookEvent(
server,
buildBody({ hook_event_name: 'UserPromptSubmit', prompt: 'first' })
)
server.flushStatusPersistSync()
const firstMtime = statSync(lastStatusPath()).mtimeMs
// Why: a no-op clearPaneState on a paneKey not in the cache is a
// mutation site that should NOT trigger a redundant write. (clear was
// designed to bail when nothing was evicted.)
server.clearPaneState('non-existent:0')
server.flushStatusPersistSync()
// Touch back to the same mtime would let the test pass spuriously, so
// assert no rewrite happened by checking that mtime is unchanged after
// a forced sync flush.
const secondMtime = statSync(lastStatusPath()).mtimeMs
expect(secondMtime).toBe(firstMtime)
} finally {
server.stop()
}
})
it('stop() flushes pending debounced writes synchronously', async () => {
const server = new AgentHookServer()
await server.start({
env: 'production',
userDataPath
})
try {
await postHookEvent(
server,
buildBody({ hook_event_name: 'UserPromptSubmit', prompt: 'flush me' })
)
// Note: do NOT call flushStatusPersistSync explicitly — let stop() do it.
} finally {
server.stop()
}
// Why: file written even though we never explicitly flushed before stop —
// stop() must synchronously drain the pending trailing-debounced timer.
expect(existsSync(lastStatusPath())).toBe(true)
const parsed = JSON.parse(readFileSync(lastStatusPath(), 'utf8'))
expect(parsed.entries[PANE]?.payload?.prompt).toBe('flush me')
})
})
describe('AgentHookServer ingestRemote', () => {
it('stamps connectionId and forwards a valid relay envelope to the listener', () => {
const server = new AgentHookServer()
@@ -1219,13 +1615,17 @@ describe('AgentHookServer ingestRemote', () => {
server.setListener(listener)
server.ingestRemote({ paneKey: PANE, tabId: 'tab-1', worktreeId: 'wt-1', payload }, 'conn-1')
expect(listener).toHaveBeenCalledTimes(1)
expect(listener).toHaveBeenCalledWith({
paneKey: PANE,
tabId: 'tab-1',
worktreeId: 'wt-1',
connectionId: 'conn-1',
payload
})
expect(listener).toHaveBeenCalledWith(
expect.objectContaining({
paneKey: PANE,
tabId: 'tab-1',
worktreeId: 'wt-1',
connectionId: 'conn-1',
receivedAt: expect.any(Number),
stateStartedAt: expect.any(Number),
payload
})
)
})
it('drops envelopes whose payload state is not in AGENT_STATUS_STATES', () => {
+408 -10
View File
@@ -1,3 +1,4 @@
/* eslint-disable max-lines -- Why: this file owns the loopback HTTP adapter, the on-disk last-status persistence layer (hydrate, sanitize, TTL, atomic write, drop), and the relay ingest path in one place so the cache lifecycle (set → schedule → drain) lives next to the surfaces that mutate it. Splitting would force mutual `private` accessor scaffolding for a single class. */
// Why: this module is the Orca-main-process adapter for the shared
// agent-hook listener pipeline (`src/shared/agent-hook-listener.ts`). The
// listener internals (request parsing, payload normalization, endpoint-file
@@ -7,8 +8,11 @@
// - the IPC fanout (setListener / lastStatusByPaneKey replay)
// - the `ingestRemote` entry point that bypasses HTTP for relay-forwarded
// events (see docs/design/agent-status-over-ssh.md §5)
// - the on-disk last-status cache (`last-status.json`) that survives
// Orca restart so retained dashboard rows reappear on relaunch
import { createServer, type IncomingMessage, type ServerResponse } from 'http'
import { randomUUID } from 'crypto'
import { chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'fs'
import { join } from 'path'
import { ORCA_HOOK_PROTOCOL_VERSION } from '../../shared/agent-hook-types'
@@ -28,10 +32,151 @@ import {
type HookListenerState
} from '../../shared/agent-hook-listener'
import type { AgentHookSource } from '../../shared/agent-hook-relay'
import { normalizeAgentStatusPayload } from '../../shared/agent-status-types'
import {
type AgentStatusIpcPayload,
normalizeAgentStatusPayload
} from '../../shared/agent-status-types'
export type { AgentHookSource }
// Why: server-process-only enrichment of the shared event payload. The shared
// listener emits `AgentHookEventPayload` (the bare event shape). For
// persistence and the dashboard's "did the agent transition since I last
// looked?" comparison, we attach `receivedAt` (when the latest event arrived
// for this pane) and `stateStartedAt` (when the current state first appeared).
// Stored in `state.lastStatusByPaneKey` via assignability — `AgentHookEventPayload`
// is the declared map value, and the extra fields ride along untouched because
// the shared module only writes/clears, never reads.
type EnrichedAgentHookEventPayload = AgentHookEventPayload & {
receivedAt: number
stateStartedAt: number
}
// Why: name of the on-disk cache that survives Orca restart. Lives next to
// the endpoint file in userData/agent-hooks/ so all hook-server-owned cross-
// restart artifacts stay co-located.
const LAST_STATUS_FILE_NAME = 'last-status.json'
// Why: starts at 2 (not 1) because pre-merge dev iterations of this branch
// wrote a v1 shape with no receivedAt / stateStartedAt. Bumping to 2 means a
// developer who upgrades from an in-flight branch sees an empty hydration
// once instead of partially-typed legacy entries. New file format; never
// shipped to users at v1. A mismatched version is treated as a corrupt file
// (silent empty hydration).
const LAST_STATUS_FILE_VERSION = 2
// Why: trailing-edge debounce so a burst of hook events from a multi-agent
// run produces one disk write instead of N. The latency budget matches other
// hook-server batching; quit-time uses flushStatusPersistSync() for the
// guaranteed final flush.
const STATUS_PERSIST_DEBOUNCE_MS = 250
// Why: bound the on-disk file's growth across many sessions. PTY-teardown
// eviction handles closed panes, but daemon-restored PTYs that never re-attach
// and crash-recovery paths where teardown never fires can leave entries
// pinned forever. 7 days matches the user-visible "still relevant?" horizon —
// older entries have almost certainly been resolved or abandoned and should
// not resurrect on hydrate.
const HYDRATE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000
type LastStatusFile = {
version: number
entries: Record<string, EnrichedAgentHookEventPayload>
}
// Why: paneKey is `${tabId}:${paneId}` — exactly one ':' with non-empty
// segments on either side. Used both at write time (defensive) and at
// hydrate time (drop on mismatch).
export function isValidPaneKey(value: unknown): value is string {
if (typeof value !== 'string' || value.length === 0) {
return false
}
const colon = value.indexOf(':')
if (colon <= 0 || colon === value.length - 1) {
return false
}
// Why: exactly one colon. Anything weirder is corruption.
return !value.includes(':', colon + 1)
}
function sanitizeHydratedEntry(
paneKey: string,
rawEntry: unknown
): EnrichedAgentHookEventPayload | null {
if (!isValidPaneKey(paneKey)) {
return null
}
if (typeof rawEntry !== 'object' || rawEntry === null) {
return null
}
const record = rawEntry as Record<string, unknown>
if (record.paneKey !== paneKey) {
return null
}
const tabId = record.tabId
if (tabId !== undefined && (typeof tabId !== 'string' || tabId.length === 0)) {
return null
}
// Why: paneKey is `${tabId}:${paneId}`; a stored entry whose tabId field
// diverges from the key's tab segment is corruption (renamer bug, manual
// edit, future shape drift). Drop instead of hydrating an inconsistent row.
if (typeof tabId === 'string' && tabId !== paneKey.slice(0, paneKey.indexOf(':'))) {
return null
}
const worktreeId = record.worktreeId
if (worktreeId !== undefined && (typeof worktreeId !== 'string' || worktreeId.length === 0)) {
return null
}
const receivedAt = record.receivedAt
if (typeof receivedAt !== 'number' || !Number.isFinite(receivedAt) || receivedAt <= 0) {
return null
}
const stateStartedAt = record.stateStartedAt
if (
typeof stateStartedAt !== 'number' ||
!Number.isFinite(stateStartedAt) ||
stateStartedAt <= 0
) {
return null
}
// Why: connectionId is allowed to be null (local) or string (relay). Any
// other shape is rejected so the post-merge typed surface stays honest.
const connectionIdRaw = record.connectionId
let connectionId: string | null
if (connectionIdRaw === null || connectionIdRaw === undefined) {
connectionId = null
} else if (typeof connectionIdRaw === 'string') {
connectionId = connectionIdRaw
} else {
return null
}
const payload = normalizeAgentStatusPayload(record.payload)
if (!payload) {
return null
}
return {
paneKey,
tabId: typeof tabId === 'string' ? tabId : undefined,
worktreeId: typeof worktreeId === 'string' ? worktreeId : undefined,
connectionId,
payload,
receivedAt,
stateStartedAt
}
}
function toAgentStatusIpcPayload(entry: EnrichedAgentHookEventPayload): AgentStatusIpcPayload {
return {
paneKey: entry.paneKey,
tabId: entry.tabId,
worktreeId: entry.worktreeId,
connectionId: entry.connectionId,
receivedAt: entry.receivedAt,
stateStartedAt: entry.stateStartedAt,
...entry.payload
}
}
export class AgentHookServer {
private server: ReturnType<typeof createServer> | null = null
private port = 0
@@ -40,7 +185,7 @@ export class AgentHookServer {
// the server can detect dev vs. prod cross-talk. Set at start() from the
// caller's knowledge of whether this is a packaged build.
private env = 'production'
private onAgentStatus: ((payload: AgentHookEventPayload) => void) | null = null
private onAgentStatus: ((payload: EnrichedAgentHookEventPayload) => void) | null = null
// Why: directory that holds the on-disk endpoint file. Set via start()'s
// `userDataPath` option so the class has no direct Electron dependency
// (keeps it mockable in the vitest node environment).
@@ -51,8 +196,20 @@ export class AgentHookServer {
// by paneKey). Held on the instance instead of as module-level Maps so
// tests can spin up multiple servers without state cross-contamination.
private state: HookListenerState = createHookListenerState()
// Why: full path to the on-disk last-status cache. Set in start() from
// userDataPath. Null when the server runs without a userDataPath (e.g.
// tests that skip the userDataPath option) — in that case, persistence is
// a no-op and only in-memory replay applies.
private lastStatusFilePath: string | null = null
// Why: trailing-edge debounce timer. Captured per-instance so multiple
// server instances in the same process (tests) don't share state.
private statusPersistTimer: ReturnType<typeof setTimeout> | null = null
// Why: identity check — skip writes when the JSON-stringified contents
// exactly match the last successful disk write. Cheap protection against
// re-firing trailing timers when nothing changed.
private lastWrittenJson: string | null = null
setListener(listener: ((payload: AgentHookEventPayload) => void) | null): void {
setListener(listener: ((payload: EnrichedAgentHookEventPayload) => void) | null): void {
this.onAgentStatus = listener
if (!listener) {
return
@@ -61,13 +218,42 @@ export class AgentHookServer {
// starve subsequent panes from being replayed.
for (const payload of this.state.lastStatusByPaneKey.values()) {
try {
listener(payload)
// Why: cache values are stored as enriched payloads (with receivedAt /
// stateStartedAt). The map's declared element type from the shared
// listener is the bare AgentHookEventPayload because the shared module
// never reads from this map; only this class does, and only enriched
// values are ever inserted.
listener(payload as EnrichedAgentHookEventPayload)
} catch (err) {
console.error('[agent-hooks] replay listener threw', err)
}
}
}
/** Snapshot of the current cached statuses, in the IPC-shaped form the
* renderer consumes. Used by the `agentStatus:getSnapshot` IPC after
* workspace tabs have hydrated, so the dashboard catches up on any
* hook events that fired during startup. */
getStatusSnapshot(): AgentStatusIpcPayload[] {
return Array.from(this.state.lastStatusByPaneKey.values(), (entry) =>
toAgentStatusIpcPayload(entry as EnrichedAgentHookEventPayload)
)
}
private attachStatusTiming(payload: AgentHookEventPayload): EnrichedAgentHookEventPayload {
const now = Date.now()
const previous = this.state.lastStatusByPaneKey.get(payload.paneKey) as
| EnrichedAgentHookEventPayload
| undefined
const stateStartedAt =
previous && previous.payload.state === payload.payload.state ? previous.stateStartedAt : now
return {
...payload,
receivedAt: now,
stateStartedAt
}
}
/** Ingest a payload that arrived over the relay JSON-RPC channel rather
* than the local HTTP server. `connectionId` is the SshChannelMultiplexer
* identity Orca holds (the wire envelope carries connectionId: null and
@@ -144,8 +330,10 @@ export class AgentHookServer {
connectionId: trimmedConnectionId,
payload: normalizedPayload
}
this.state.lastStatusByPaneKey.set(paneKey, event)
this.onAgentStatus?.(event)
const enriched = this.attachStatusTiming(event)
this.state.lastStatusByPaneKey.set(paneKey, enriched)
this.scheduleStatusPersist()
this.onAgentStatus?.(enriched)
}
async start(options?: { env?: string; userDataPath?: string }): Promise<void> {
@@ -159,9 +347,18 @@ export class AgentHookServer {
if (options?.userDataPath) {
this.endpointDir = join(options.userDataPath, 'agent-hooks')
this.endpointFilePathCache = join(this.endpointDir, getEndpointFileName())
this.lastStatusFilePath = join(this.endpointDir, LAST_STATUS_FILE_NAME)
}
this.token = randomUUID()
this.endpointFileWritten = false
this.lastWrittenJson = null
// Why: hydrate before binding the HTTP listener so any new hook POST
// (which goes through state.lastStatusByPaneKey.set) runs against an
// already-populated map. The renderer later pulls this map as a snapshot
// after workspace tabs are hydrated.
if (this.lastStatusFilePath) {
this.hydrateLastStatusFromDisk()
}
this.server = createServer(async (req: IncomingMessage, res: ServerResponse) => {
if (req.method !== 'POST') {
res.writeHead(404)
@@ -192,10 +389,12 @@ export class AgentHookServer {
return
}
const payload = normalizeHookPayload(this.state, source, body, this.env)
if (payload) {
this.state.lastStatusByPaneKey.set(payload.paneKey, payload)
this.onAgentStatus?.(payload)
const normalized = normalizeHookPayload(this.state, source, body, this.env)
if (normalized) {
const enriched = this.attachStatusTiming(normalized)
this.state.lastStatusByPaneKey.set(enriched.paneKey, enriched)
this.scheduleStatusPersist()
this.onAgentStatus?.(enriched)
}
res.writeHead(204)
@@ -234,6 +433,12 @@ export class AgentHookServer {
}
stop(): void {
// Why: flush any pending debounced write to disk BEFORE we clear the
// in-memory map. Quit-time state must be captured even if the trailing
// timer was scheduled but had not yet fired; otherwise a multi-agent
// run that ended its last hook event <250 ms before quit would lose
// that final delta on relaunch.
this.flushStatusPersistSync()
this.server?.close()
this.server = null
this.port = 0
@@ -246,11 +451,36 @@ export class AgentHookServer {
this.endpointDir = null
this.endpointFilePathCache = null
this.endpointFileWritten = false
this.lastStatusFilePath = null
this.lastWrittenJson = null
clearAllListenerCaches(this.state)
}
/** Why: invoked from the renderer-driven agentStatus:drop IPC when a user
* dismisses a still-active pane's status row. We must NOT wipe
* lastPromptByPaneKey or lastToolByPaneKey here — the pane's agent may
* still be alive, and the next hook event would otherwise arrive with an
* empty prompt and missing tool snapshot until a fresh UserPromptSubmit
* lands. clearPaneState (which wipes all three caches) is the right shape
* only for PTY-teardown. */
dropStatusEntry(paneKey: string): void {
if (!this.state.lastStatusByPaneKey.has(paneKey)) {
return
}
this.state.lastStatusByPaneKey.delete(paneKey)
this.scheduleStatusPersist()
}
clearPaneState(paneKey: string): void {
// Why: only schedule a write when we actually evicted a status entry —
// dropping prompt/tool caches for a pane that never produced a hook
// event does not change the on-disk file, and skipping the write avoids
// re-stat'ing on every dead-pane teardown.
const hadStatus = this.state.lastStatusByPaneKey.has(paneKey)
clearPaneCacheState(this.state, paneKey)
if (hadStatus) {
this.scheduleStatusPersist()
}
}
buildPtyEnv(): Record<string, string> {
@@ -274,6 +504,11 @@ export class AgentHookServer {
return this.endpointFilePathCache
}
/** Test/diagnostic accessor for the on-disk last-status file path. */
get lastStatusPath(): string | null {
return this.lastStatusFilePath
}
private maybeWriteEndpointFile(): void {
if (!this.endpointDir || !this.endpointFilePathCache) {
return
@@ -287,6 +522,169 @@ export class AgentHookServer {
})
this.endpointFileWritten = ok
}
private hydrateLastStatusFromDisk(): void {
if (!this.lastStatusFilePath) {
return
}
// Why: defensive — keeps hydrate idempotent against repeated start()
// calls; production callers always have an empty map here, but a future
// re-start path must not silently merge prior-session state.
this.state.lastStatusByPaneKey.clear()
let raw: string
try {
raw = readFileSync(this.lastStatusFilePath, 'utf8')
} catch (err) {
// Why: missing file is the common case (first launch).
// Other errors (EACCES, etc.) degrade to empty hydration with a single
// warn so the dashboard renders normally.
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
console.warn('[agent-hooks] failed to read last-status file:', err)
}
return
}
let parsed: unknown
try {
parsed = JSON.parse(raw)
} catch {
console.warn('[agent-hooks] last-status file is not valid JSON; ignoring')
return
}
if (typeof parsed !== 'object' || parsed === null) {
console.warn('[agent-hooks] last-status file is not an object; ignoring')
return
}
const file = parsed as Partial<LastStatusFile>
if (file.version !== LAST_STATUS_FILE_VERSION) {
console.warn(
`[agent-hooks] last-status file version mismatch (${String(
file.version
)} != ${LAST_STATUS_FILE_VERSION}); ignoring`
)
return
}
const entries = file.entries
if (typeof entries !== 'object' || entries === null) {
console.warn('[agent-hooks] last-status file entries missing or wrong shape; ignoring')
return
}
let hydrated = 0
let dropped = 0
// Why: bound disk growth — drop anything older than HYDRATE_MAX_AGE_MS so
// entries from worktrees archived weeks ago do not pile up forever. Use
// Date.now() once to keep the cutoff consistent across all entries this
// tick.
const ttlCutoff = Date.now() - HYDRATE_MAX_AGE_MS
for (const [paneKey, rawEntry] of Object.entries(entries)) {
const entry = sanitizeHydratedEntry(paneKey, rawEntry)
if (entry && entry.receivedAt >= ttlCutoff) {
this.state.lastStatusByPaneKey.set(paneKey, entry)
hydrated += 1
} else {
dropped += 1
}
}
if (dropped > 0) {
console.warn(
`[agent-hooks] last-status hydrate dropped ${dropped} entries (kept ${hydrated})`
)
}
if (hydrated > 0 && dropped === 0) {
// Why: prime from the raw on-disk bytes (not a re-serialization) so the
// dedup is robust against future shape drift in serializeStatusFile.
// Only prime when hydration was lossless — if entries were dropped
// during sanitize, the in-memory map diverges from the on-disk bytes.
this.lastWrittenJson = raw
} else if (dropped > 0) {
// Why: clean the stale on-disk file now so a user who has not run an
// agent in 8+ days does not re-drop the same entries on every cold
// boot. Synchronous variant is safe at start time and avoids
// unref'd-timer-during-quit edge cases.
this.runStatusPersist()
}
}
private serializeStatusFile(): string {
const entries: Record<string, EnrichedAgentHookEventPayload> = {}
for (const [paneKey, payload] of this.state.lastStatusByPaneKey) {
// Why: defensive — never persist invalid keys even if they slipped
// into the in-memory map somehow. Same invariant the hydrate path
// enforces.
if (!isValidPaneKey(paneKey)) {
continue
}
entries[paneKey] = payload as EnrichedAgentHookEventPayload
}
const file: LastStatusFile = { version: LAST_STATUS_FILE_VERSION, entries }
return JSON.stringify(file)
}
private scheduleStatusPersist(): void {
if (!this.lastStatusFilePath) {
return
}
// Why: each call resets the timer; the disk write fires
// STATUS_PERSIST_DEBOUNCE_MS after the LAST event in the burst.
if (this.statusPersistTimer) {
clearTimeout(this.statusPersistTimer)
}
this.statusPersistTimer = setTimeout(() => {
this.statusPersistTimer = null
this.runStatusPersist()
}, STATUS_PERSIST_DEBOUNCE_MS)
// Why: don't keep the event loop alive just for a status flush — quit
// already triggers flushStatusPersistSync(). On Node 12+ unref() is a
// no-op when called on an already-unref'd timer.
if (typeof this.statusPersistTimer.unref === 'function') {
this.statusPersistTimer.unref()
}
}
flushStatusPersistSync(): void {
if (this.statusPersistTimer) {
clearTimeout(this.statusPersistTimer)
this.statusPersistTimer = null
}
if (!this.lastStatusFilePath) {
return
}
this.runStatusPersist()
}
private runStatusPersist(): void {
if (!this.lastStatusFilePath || !this.endpointDir) {
return
}
const json = this.serializeStatusFile()
if (json === this.lastWrittenJson) {
return
}
const tmpPath = join(this.endpointDir, `.last-status-${process.pid}-${randomUUID()}.tmp`)
let tmpWritten = false
try {
mkdirSync(this.endpointDir, { recursive: true, mode: 0o700 })
if (process.platform !== 'win32') {
try {
chmodSync(this.endpointDir, 0o700)
} catch {
// best-effort
}
}
writeFileSync(tmpPath, json, { mode: 0o600 })
tmpWritten = true
renameSync(tmpPath, this.lastStatusFilePath)
this.lastWrittenJson = json
} catch (err) {
console.warn('[agent-hooks] failed to write last-status file:', err)
if (tmpWritten) {
try {
unlinkSync(tmpPath)
} catch {
// tmp already gone
}
}
}
}
}
export const agentHookServer = new AgentHookServer()
+27 -23
View File
@@ -276,30 +276,34 @@ function openMainWindow(): BrowserWindow {
}
})
mainWindow = window
agentHookServer.setListener(({ paneKey, tabId, worktreeId, connectionId, payload }) => {
if (mainWindow?.isDestroyed()) {
return
agentHookServer.setListener(
({ paneKey, tabId, worktreeId, connectionId, payload, receivedAt, stateStartedAt }) => {
if (mainWindow?.isDestroyed()) {
return
}
mainWindow?.webContents.send('agentStatus:set', {
...payload,
paneKey,
tabId,
worktreeId,
connectionId,
receivedAt,
stateStartedAt
})
// Why: cursor-agent's OSC title stays "Cursor Agent" for the whole turn,
// and opencode's stays bare "OpenCode" — neither carries a working/idle
// signal the title heuristic can read. Synthesize an OSC title update
// from the hook state and inject it into the pane's data stream so the
// existing renderer-side title tracker (which drives the sidebar
// spinner, unread badge, and worktree status dot for every other agent)
// lights up for these panes too. Braille prefix → working keyword path;
// "action required" → permission; bare label → idle.
const profile = SYNTHETIC_TITLE_PROFILES[payload.agentType ?? '']
if (profile) {
driveSyntheticTitleFromHook(paneKey, payload.state, profile)
}
}
mainWindow?.webContents.send('agentStatus:set', {
...payload,
paneKey,
tabId,
worktreeId,
connectionId
})
// Why: cursor-agent's OSC title stays "Cursor Agent" for the whole turn,
// and opencode's stays bare "OpenCode" — neither carries a working/idle
// signal the title heuristic can read. Synthesize an OSC title update
// from the hook state and inject it into the pane's data stream so the
// existing renderer-side title tracker (which drives the sidebar
// spinner, unread badge, and worktree status dot for every other agent)
// lights up for these panes too. Braille prefix → working keyword path;
// "action required" → permission; bare label → idle.
const profile = SYNTHETIC_TITLE_PROFILES[payload.agentType ?? '']
if (profile) {
driveSyntheticTitleFromHook(paneKey, payload.state, profile)
}
})
)
return window
}
+123
View File
@@ -0,0 +1,123 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type * as AgentHookServerModule from '../agent-hooks/server'
// Why: cover the agentStatus:drop IPC handler — it must propagate the
// renderer dismissal to dropStatusEntry so the on-disk last-status file
// evicts the entry.
const dropStatusEntry = vi.fn()
const getStatusSnapshot = vi.fn()
const onHandlers = new Map<string, (event: unknown, ...args: unknown[]) => void>()
const handleHandlers = new Map<string, (event: unknown, ...args: unknown[]) => unknown>()
const removeHandler = vi.fn()
const removeAllListeners = vi.fn()
vi.mock('electron', () => ({
ipcMain: {
handle: (channel: string, handler: (event: unknown, ...args: unknown[]) => unknown) => {
handleHandlers.set(channel, handler)
},
on: (channel: string, handler: (event: unknown, ...args: unknown[]) => void) => {
onHandlers.set(channel, handler)
},
removeHandler,
removeAllListeners
}
}))
vi.mock('../agent-hooks/server', async () => {
// Why: import the real isValidPaneKey so this test stays in sync with any
// tightening of the validator (length cap, character allow-list, etc).
const actual = await vi.importActual<typeof AgentHookServerModule>('../agent-hooks/server')
return {
...actual,
agentHookServer: {
dropStatusEntry,
getStatusSnapshot
}
}
})
vi.mock('../claude/hook-service', () => ({
claudeHookService: { getStatus: vi.fn(() => ({ agent: 'claude', state: 'absent' })) }
}))
vi.mock('../codex/hook-service', () => ({
codexHookService: { getStatus: vi.fn(() => ({ agent: 'codex', state: 'absent' })) }
}))
vi.mock('../gemini/hook-service', () => ({
geminiHookService: { getStatus: vi.fn(() => ({ agent: 'gemini', state: 'absent' })) }
}))
vi.mock('../cursor/hook-service', () => ({
cursorHookService: { getStatus: vi.fn(() => ({ agent: 'cursor', state: 'absent' })) }
}))
beforeEach(() => {
dropStatusEntry.mockReset()
getStatusSnapshot.mockReset()
onHandlers.clear()
handleHandlers.clear()
removeHandler.mockReset()
removeAllListeners.mockReset()
})
afterEach(() => {
vi.resetModules()
})
describe('agentStatus:getSnapshot IPC', () => {
it('returns the hook cache snapshot', async () => {
const snapshot = [
{
paneKey: 'tab-1:0',
state: 'done',
prompt: 'p',
agentType: 'claude',
receivedAt: 1_700_000_000_000,
stateStartedAt: 1_699_999_999_000
}
]
getStatusSnapshot.mockReturnValue(snapshot)
const { registerAgentHookHandlers } = await import('./agent-hooks')
registerAgentHookHandlers()
const handler = handleHandlers.get('agentStatus:getSnapshot')
expect(handler).toBeDefined()
expect(handler!({})).toEqual(snapshot)
})
})
describe('agentStatus:drop IPC', () => {
it('forwards drop to dropStatusEntry', async () => {
const { registerAgentHookHandlers } = await import('./agent-hooks')
registerAgentHookHandlers()
const handler = onHandlers.get('agentStatus:drop')
expect(handler).toBeDefined()
handler!({}, 'tab-1:0')
expect(dropStatusEntry).toHaveBeenCalledWith('tab-1:0')
})
it('rejects non-string paneKey (defensive against a malformed renderer message)', async () => {
const { registerAgentHookHandlers } = await import('./agent-hooks')
registerAgentHookHandlers()
const handler = onHandlers.get('agentStatus:drop')!
const bad: unknown[] = [
123,
undefined,
'',
null,
{},
[],
'no-colon', // missing colon — rejected by isValidPaneKey
':leading', // empty tabId half
'trailing:', // empty paneId half
'a:b:c' // multiple colons
]
for (const value of bad) {
expect(() => handler({}, value)).not.toThrow()
}
expect(dropStatusEntry).not.toHaveBeenCalled()
})
})
+27
View File
@@ -1,5 +1,7 @@
import { ipcMain } from 'electron'
import type { AgentHookInstallStatus } from '../../shared/agent-hook-types'
import type { AgentStatusIpcPayload } from '../../shared/agent-status-types'
import { agentHookServer, isValidPaneKey } from '../agent-hooks/server'
import { claudeHookService } from '../claude/hook-service'
import { codexHookService } from '../codex/hook-service'
import { geminiHookService } from '../gemini/hook-service'
@@ -20,6 +22,31 @@ export function registerAgentHookHandlers(): void {
ipcMain.removeHandler('agentHooks:codexStatus')
ipcMain.removeHandler('agentHooks:geminiStatus')
ipcMain.removeHandler('agentHooks:cursorStatus')
ipcMain.removeHandler('agentStatus:getSnapshot')
// Why: agentStatus:drop is sent fire-and-forget from the renderer via
// ipcRenderer.send(); we listen with ipcMain.on (not handle) so we don't
// round-trip a response. Removing first keeps re-registration safe even
// though the module-level registered guard already prevents re-entry today.
ipcMain.removeAllListeners('agentStatus:drop')
ipcMain.on('agentStatus:drop', (_event, paneKey: unknown) => {
if (typeof paneKey !== 'string' || !isValidPaneKey(paneKey)) {
return
}
try {
// Why: dropStatusEntry (not clearPaneState) is correct here — the user is
// dismissing a status row, not tearing down a PTY. clearPaneState would also
// wipe the per-pane prompt/tool caches, which the next hook event for that
// (still-alive) pane needs to render a coherent row.
agentHookServer.dropStatusEntry(paneKey)
} catch (err) {
console.warn('[agent-hooks] dropStatusEntry failed:', err)
}
})
ipcMain.handle('agentStatus:getSnapshot', (): AgentStatusIpcPayload[] => {
// Why: the renderer pulls this after workspace hydration, so startup cannot
// lose replayed statuses while its local store is still empty.
return agentHookServer.getStatusSnapshot()
})
// Why: errors from getStatus() (fs permission denied, homedir resolution
// failure, etc.) must be reported inline via state:'error' so the sidebar can
+7 -20
View File
@@ -122,7 +122,7 @@ import type { ElectronAPI } from '@electron-toolkit/preload'
import type { CliInstallStatus } from '../shared/cli-install-types'
import type { E2EConfig } from '../shared/e2e-config'
import type { AgentHookInstallStatus } from '../shared/agent-hook-types'
import type { AgentStatusState } from '../shared/agent-status-types'
import type { AgentStatusIpcPayload } from '../shared/agent-status-types'
import type { RuntimeStatus, RuntimeSyncWindowGraph } from '../shared/runtime-types'
import type {
DeveloperPermissionId,
@@ -1232,25 +1232,12 @@ export type PreloadApi = {
}
agentStatus: {
/** Listen for agent status updates forwarded from native hook receivers. */
onSet: (
callback: (data: {
paneKey: string
tabId?: string
worktreeId?: string
// Why: stamped by main from the SshChannelMultiplexer the event
// arrived on (or null for local). The renderer uses it to drop
// in-flight events when an SSH connection tears down — see
// docs/design/agent-status-over-ssh.md §5.
connectionId: string | null
state: AgentStatusState
prompt?: string
agentType?: string
toolName?: string
toolInput?: string
lastAssistantMessage?: string
interrupted?: boolean
}) => void
) => () => void
onSet: (callback: (data: AgentStatusIpcPayload) => void) => () => void
/** Return the current main-process hook cache after renderer hydration. */
getSnapshot: () => Promise<AgentStatusIpcPayload[]>
/** Drop a paneKey from the main-process hook cache and the on-disk
* last-status file. Fire-and-forget. */
drop: (paneKey: string) => void
}
mobile: {
listNetworkInterfaces: () => Promise<{
+16 -36
View File
@@ -70,7 +70,7 @@ import type {
PortForwardEntry,
DetectedPort
} from '../shared/ssh-types'
import type { AgentStatusState } from '../shared/agent-status-types'
import type { AgentStatusIpcPayload } from '../shared/agent-status-types'
import type { TelemetryConsentState } from '../shared/telemetry-consent-types'
import type { RefreshAgentsResult } from './api-types'
import type { AgentKind, LaunchSource, RequestKind } from '../shared/telemetry-events'
@@ -2301,43 +2301,23 @@ const api = {
agentStatus: {
/** Listen for agent status updates forwarded from native hook receivers. */
onSet: (
callback: (data: {
paneKey: string
tabId?: string
worktreeId?: string
// Why: stamped by main from the SshChannelMultiplexer the event
// arrived on (or null for local). The renderer uses it to drop
// in-flight events when an SSH connection tears down — see
// docs/design/agent-status-over-ssh.md §5.
connectionId: string | null
state: AgentStatusState
prompt?: string
agentType?: string
toolName?: string
toolInput?: string
lastAssistantMessage?: string
interrupted?: boolean
}) => void
): (() => void) => {
const listener = (
_event: Electron.IpcRendererEvent,
data: {
paneKey: string
tabId?: string
worktreeId?: string
connectionId: string | null
state: AgentStatusState
prompt?: string
agentType?: string
toolName?: string
toolInput?: string
lastAssistantMessage?: string
interrupted?: boolean
}
) => callback(data)
onSet: (callback: (data: AgentStatusIpcPayload) => void): (() => void) => {
const listener = (_event: Electron.IpcRendererEvent, data: AgentStatusIpcPayload) =>
callback(data)
ipcRenderer.on('agentStatus:set', listener)
return () => ipcRenderer.removeListener('agentStatus:set', listener)
},
/** Pull the current cached hook statuses after renderer workspace-session
* hydration. This avoids losing startup replays before the renderer
* knows which tabs exist. */
getSnapshot: (): Promise<AgentStatusIpcPayload[]> =>
ipcRenderer.invoke('agentStatus:getSnapshot'),
/** Drop the cached hook status for a paneKey on both sides — main-process
* cache (lastStatusByPaneKey) and on-disk last-status file. Fired from
* the renderer when the user dismisses a retained row so a relaunch
* cannot resurrect it. Fire-and-forget; no response. */
drop: (paneKey: string): void => {
ipcRenderer.send('agentStatus:drop', paneKey)
}
}
}
+10 -2
View File
@@ -189,6 +189,7 @@ function App(): React.JSX.Element {
const showActiveOnly = useAppStore((s) => s.showActiveOnly)
const hideDefaultBranchWorkspace = useAppStore((s) => s.hideDefaultBranchWorkspace)
const filterRepoIds = useAppStore((s) => s.filterRepoIds)
const acknowledgedAgentsByPaneKey = useAppStore((s) => s.acknowledgedAgentsByPaneKey)
const persistedUIReady = useAppStore((s) => s.persistedUIReady)
const rightSidebarWidth = useAppStore((s) => s.rightSidebarWidth)
const rightSidebarOpen = useAppStore((s) => s.rightSidebarOpen)
@@ -490,7 +491,13 @@ function App(): React.JSX.Element {
sortBy,
showActiveOnly,
hideDefaultBranchWorkspace,
filterRepoIds
filterRepoIds,
// Why: rides the same debounced save so dashboard auto-acks (which fire
// on focus/visibility) and the in-memory ack cleanup paths in
// agent-status.ts (close/dismiss) both flow to disk through map
// identity changes. Without persisting, agent rows that survive
// restart come back bold even when the user had already visited them.
acknowledgedAgentsByPaneKey
})
}, 150)
@@ -503,7 +510,8 @@ function App(): React.JSX.Element {
sortBy,
showActiveOnly,
hideDefaultBranchWorkspace,
filterRepoIds
filterRepoIds,
acknowledgedAgentsByPaneKey
])
// Apply theme to document
+378
View File
@@ -88,6 +88,7 @@ describe('useIpcEvents updater integration', () => {
vi.doMock('../store', () => ({
useAppStore: {
subscribe: vi.fn(() => () => {}),
getState: () => ({
setUpdateStatus,
fetchRepos: vi.fn(),
@@ -316,6 +317,7 @@ describe('useIpcEvents updater integration', () => {
vi.doMock('../store', () => ({
useAppStore: {
subscribe: vi.fn(() => () => {}),
getState: () => storeState,
setState: vi.fn((updater: (state: typeof storeState) => typeof storeState) =>
updater(storeState)
@@ -483,6 +485,7 @@ describe('useIpcEvents updater integration', () => {
vi.doMock('../store', () => ({
useAppStore: {
subscribe: vi.fn(() => () => {}),
getState: () => ({
setUpdateStatus: vi.fn(),
createTab,
@@ -687,6 +690,7 @@ describe('useIpcEvents browser tab close routing', () => {
vi.doMock('../store', () => ({
useAppStore: {
subscribe: vi.fn(() => () => {}),
getState: () => ({
setUpdateStatus: vi.fn(),
fetchRepos: vi.fn(),
@@ -885,6 +889,7 @@ describe('useIpcEvents browser tab close routing', () => {
vi.doMock('../store', () => ({
useAppStore: {
subscribe: vi.fn(() => () => {}),
getState: () => ({
setUpdateStatus: vi.fn(),
fetchRepos: vi.fn(),
@@ -1082,6 +1087,7 @@ describe('useIpcEvents browser tab close routing', () => {
vi.doMock('../store', () => ({
useAppStore: {
subscribe: vi.fn(() => () => {}),
getState: () => ({
setUpdateStatus: vi.fn(),
fetchRepos: vi.fn(),
@@ -1295,6 +1301,7 @@ describe('useIpcEvents CLI-created worktree activation', () => {
vi.doMock('../store', () => ({
useAppStore: {
subscribe: vi.fn(() => () => {}),
getState: () => ({
fetchRepos: vi.fn(),
fetchWorktrees,
@@ -1475,3 +1482,374 @@ describe('useIpcEvents CLI-created worktree activation', () => {
expect(activateAndRevealWorktree).toHaveBeenCalledWith('wt-new', { setup })
})
})
// Why: end-to-end exercise of startup agent-status restoration through
// useIpcEvents itself. The main process owns the durable cache; the renderer
// pulls a snapshot only after workspace tabs are ready so startup pushes
// cannot be lost while local state is still empty.
describe('useIpcEvents agent status snapshot integration', () => {
type AgentStatusSetData = {
paneKey: string
tabId?: string
worktreeId?: string
state: 'working' | 'blocked' | 'waiting' | 'done'
prompt?: string
agentType?: string
toolName?: string
toolInput?: string
lastAssistantMessage?: string
interrupted?: boolean
receivedAt: number
stateStartedAt: number
}
type StoreLike = Record<string, unknown>
type StoreSubscribeListener = (state: StoreLike) => void
function buildStoreState(overrides: StoreLike): StoreLike {
// Why: copy the defensive set of getState() fields the hook touches during
// mount so individual tests only need to override workspaceSessionReady,
// tabsByWorktree, and setAgentStatus.
return {
setUpdateStatus: vi.fn(),
fetchRepos: vi.fn(),
fetchWorktrees: vi.fn(),
setActiveView: vi.fn(),
activeModal: null,
closeModal: vi.fn(),
openModal: vi.fn(),
activeWorktreeId: 'wt-1',
activeView: 'terminal',
setActiveRepo: vi.fn(),
setActiveWorktree: vi.fn(),
revealWorktreeInSidebar: vi.fn(),
setIsFullScreen: vi.fn(),
updateBrowserTabPageState: vi.fn(),
activeTabType: 'terminal',
editorFontZoomLevel: 0,
setEditorFontZoomLevel: vi.fn(),
setRateLimitsFromPush: vi.fn(),
updateWorktreeBaseStatus: vi.fn(),
updateWorktreeRemoteBranchConflict: vi.fn(),
setSshConnectionState: vi.fn(),
setSshTargetLabels: vi.fn(),
setPortForwards: vi.fn(),
clearPortForwards: vi.fn(),
setDetectedPorts: vi.fn(),
enqueueSshCredentialRequest: vi.fn(),
removeSshCredentialRequest: vi.fn(),
clearTabPtyId: vi.fn(),
runtimePaneTitlesByTabId: {},
tabsByWorktree: {},
workspaceSessionReady: false,
settings: { terminalFontSize: 13 },
...overrides
}
}
function buildWindowApi(args: {
onSet: (cb: (data: AgentStatusSetData) => void) => () => void
getSnapshot?: () => Promise<AgentStatusSetData[]>
drop?: (paneKey: string) => void
}): Record<string, unknown> {
return {
api: {
repos: { onChanged: () => () => {} },
worktrees: {
onChanged: () => () => {},
onBaseStatus: () => () => {},
onRemoteBranchConflict: () => () => {}
},
ui: {
onOpenSettings: () => () => {},
onToggleLeftSidebar: () => () => {},
onToggleRightSidebar: () => () => {},
onToggleWorktreePalette: () => () => {},
onOpenQuickOpen: () => () => {},
onOpenNewWorkspace: () => () => {},
onJumpToWorktreeIndex: () => () => {},
onWorktreeHistoryNavigate: () => () => {},
onActivateWorktree: () => () => {},
onCreateTerminal: () => () => {},
onRequestTerminalCreate: () => () => {},
replyTerminalCreate: () => {},
onSplitTerminal: () => () => {},
onRenameTerminal: () => () => {},
onFocusTerminal: () => () => {},
onCloseTerminal: () => () => {},
onSleepWorktree: () => () => {},
onNewBrowserTab: () => () => {},
onRequestTabCreate: () => () => {},
replyTabCreate: () => {},
onRequestTabClose: () => () => {},
replyTabClose: () => {},
onRequestTabSetProfile: () => () => {},
replyTabSetProfile: () => {},
onNewTerminalTab: () => () => {},
onCloseActiveTab: () => () => {},
onSwitchTab: () => () => {},
onSwitchTabAcrossAllTypes: () => () => {},
onSwitchTerminalTab: () => () => {},
onToggleStatusBar: () => () => {},
onFullscreenChanged: () => () => {},
onTerminalZoom: () => () => {},
getZoomLevel: () => 0,
set: vi.fn()
},
settings: { onChanged: () => () => {} },
updater: {
getStatus: () => Promise.resolve({ state: 'idle' }),
onStatus: () => () => {},
onClearDismissal: () => () => {}
},
browser: {
onGuestLoadFailed: () => () => {},
onPaneFocus: () => () => {},
onOpenLinkInOrcaTab: () => () => {},
onNavigationUpdate: () => () => {},
onActivateView: () => () => {}
},
rateLimits: {
get: () => Promise.resolve({ limits: {}, lastUpdatedAt: Date.now() }),
onUpdate: () => () => {}
},
runtime: {
getTerminalFitOverrides: () => Promise.resolve([]),
onTerminalFitOverrideChanged: () => () => {},
onTerminalDriverChanged: () => () => {}
},
ssh: {
listTargets: () => Promise.resolve([]),
listPortForwards: () => Promise.resolve([]),
listDetectedPorts: () => Promise.resolve([]),
getState: () => Promise.resolve(null),
onStateChanged: () => () => {},
onCredentialRequest: () => () => {},
onCredentialResolved: () => () => {},
onPortForwardsChanged: () => () => {},
onDetectedPortsChanged: () => () => {}
},
agentStatus: {
onSet: args.onSet,
getSnapshot: args.getSnapshot ?? vi.fn(() => Promise.resolve([])),
drop: args.drop ?? vi.fn()
}
}
}
}
function stubReactSyncEffect(): void {
vi.doMock('react', async () => {
const actual = await vi.importActual<typeof ReactModule>('react')
return {
...actual,
useEffect: (effect: () => void | (() => void)) => {
effect()
}
}
})
}
function stubAuxiliaryModules(): void {
vi.doMock('@/lib/ui-zoom', () => ({ applyUIZoom: vi.fn() }))
vi.doMock('@/lib/worktree-activation', () => ({
activateAndRevealWorktree: vi.fn(),
ensureWorktreeHasInitialTerminal: vi.fn()
}))
vi.doMock('@/components/sidebar/visible-worktrees', () => ({
getVisibleWorktreeIds: () => []
}))
vi.doMock('@/lib/editor-font-zoom', () => ({
nextEditorFontZoomLevel: vi.fn(() => 0),
computeEditorFontSize: vi.fn(() => 13)
}))
vi.doMock('@/components/settings/SettingsConstants', () => ({
zoomLevelToPercent: vi.fn(() => 100),
ZOOM_MIN: -3,
ZOOM_MAX: 3
}))
vi.doMock('@/lib/zoom-events', () => ({ dispatchZoomLevelChanged: vi.fn() }))
}
beforeEach(() => {
vi.resetModules()
vi.unstubAllGlobals()
})
it('ignores early push events but applies the main-process snapshot after readiness', async () => {
const setAgentStatus = vi.fn()
const getSnapshot = vi.fn(() =>
Promise.resolve([
{
paneKey: 'tab-future:0',
state: 'working' as const,
prompt: 'p',
agentType: 'claude',
receivedAt: 1_700_000_000_000,
stateStartedAt: 1_699_999_999_000
}
])
)
const onSetListenerRef: { current: ((data: AgentStatusSetData) => void) | null } = {
current: null
}
const subscribeListenerRef: { current: StoreSubscribeListener | null } = { current: null }
const storeState: StoreLike = buildStoreState({
setAgentStatus,
tabsByWorktree: {},
workspaceSessionReady: false
})
stubReactSyncEffect()
vi.doMock('../store', () => ({
useAppStore: {
subscribe: vi.fn((listener: StoreSubscribeListener) => {
subscribeListenerRef.current = listener
return () => {
subscribeListenerRef.current = null
}
}),
getState: () => storeState
}
}))
stubAuxiliaryModules()
vi.stubGlobal(
'window',
buildWindowApi({
getSnapshot,
onSet: (cb) => {
onSetListenerRef.current = cb
return () => {}
}
})
)
const { useIpcEvents } = await import('./useIpcEvents')
useIpcEvents()
await Promise.resolve()
if (typeof onSetListenerRef.current !== 'function') {
throw new Error('Expected agentStatus.onSet listener to be registered')
}
// Fire an event for an unknown paneKey while not ready — must NOT call setAgentStatus.
onSetListenerRef.current({
paneKey: 'tab-future:0',
state: 'working',
prompt: 'p',
agentType: 'claude',
receivedAt: 1_700_000_000_100,
stateStartedAt: 1_699_999_999_100
})
expect(setAgentStatus).not.toHaveBeenCalled()
expect(getSnapshot).not.toHaveBeenCalled()
storeState.workspaceSessionReady = true
storeState.tabsByWorktree = {
'wt-1': [{ id: 'tab-future', ptyId: 'pty-1', worktreeId: 'wt-1', title: 'Future Tab' }]
}
if (typeof subscribeListenerRef.current !== 'function') {
throw new Error('Expected useAppStore.subscribe listener to be registered')
}
subscribeListenerRef.current(storeState)
await Promise.resolve()
expect(setAgentStatus).toHaveBeenCalledTimes(1)
expect(setAgentStatus).toHaveBeenCalledWith(
'tab-future:0',
expect.objectContaining({ state: 'working', prompt: 'p', agentType: 'claude' }),
'Future Tab',
{ updatedAt: 1_700_000_000_000, stateStartedAt: 1_699_999_999_000 }
)
})
it('pulls the snapshot once workspace session is ready even before settings load', async () => {
const setAgentStatus = vi.fn()
const getSnapshot = vi.fn(() => Promise.resolve([]))
const subscribeListenerRef: { current: StoreSubscribeListener | null } = { current: null }
const storeState: StoreLike = buildStoreState({
setAgentStatus,
tabsByWorktree: {},
workspaceSessionReady: true,
settings: null
})
stubReactSyncEffect()
vi.doMock('../store', () => ({
useAppStore: {
subscribe: vi.fn((listener: StoreSubscribeListener) => {
subscribeListenerRef.current = listener
return () => {
subscribeListenerRef.current = null
}
}),
getState: () => storeState
}
}))
stubAuxiliaryModules()
vi.stubGlobal(
'window',
buildWindowApi({
getSnapshot,
onSet: () => () => {}
})
)
const { useIpcEvents } = await import('./useIpcEvents')
useIpcEvents()
await Promise.resolve()
expect(getSnapshot).toHaveBeenCalledTimes(1)
expect(setAgentStatus).not.toHaveBeenCalled()
})
it('silently discards snapshot entries whose tabs are still unknown', async () => {
const setAgentStatus = vi.fn()
const getSnapshot = vi.fn(() =>
Promise.resolve([
{
paneKey: 'tab-orphan:0',
state: 'done' as const,
prompt: 'p',
agentType: 'claude',
receivedAt: 1_700_000_000_000,
stateStartedAt: 1_699_999_999_000
}
])
)
const storeState: StoreLike = buildStoreState({
setAgentStatus,
tabsByWorktree: {
'wt-1': [{ id: 'tab-other', ptyId: 'pty-1', worktreeId: 'wt-1', title: 'Other' }]
},
workspaceSessionReady: true
})
stubReactSyncEffect()
vi.doMock('../store', () => ({
useAppStore: {
subscribe: vi.fn(() => () => {}),
getState: () => storeState
}
}))
stubAuxiliaryModules()
vi.stubGlobal(
'window',
buildWindowApi({
getSnapshot,
onSet: () => () => {}
})
)
const { useIpcEvents } = await import('./useIpcEvents')
useIpcEvents()
await Promise.resolve()
await Promise.resolve()
expect(setAgentStatus).not.toHaveBeenCalled()
})
})
+84 -32
View File
@@ -19,7 +19,10 @@ import {
handleSwitchTabAcrossAllTypes,
handleSwitchTerminalTab
} from './ipc-tab-switch'
import { normalizeAgentStatusPayload } from '../../../shared/agent-status-types'
import {
normalizeAgentStatusPayload,
type AgentStatusIpcPayload
} from '../../../shared/agent-status-types'
import { isGitRepoKind } from '../../../shared/repo-kind'
import { focusTerminalTabSurface } from '@/lib/focus-terminal-tab-surface'
import { setFitOverride, hydrateOverrides } from '@/lib/pane-manager/mobile-fit-overrides'
@@ -846,42 +849,91 @@ export function useIpcEvents(): void {
// Why: agent status arrives from native hook receivers in the main process.
// Re-parse it here so the renderer enforces the same normalization rules
// (state enum, field truncation) regardless of whether the source was a
// hook callback or an OSC fallback path.
// hook callback or an OSC fallback path. Startup pushes are ignored until
// workspace session hydration finishes; the snapshot pull below replays the
// main-process cache after tab identity is available.
const applyAgentStatus = (data: AgentStatusIpcPayload): void => {
const store = useAppStore.getState()
if (!store.workspaceSessionReady) {
return
}
const payload = normalizeAgentStatusPayload({
state: data.state,
prompt: data.prompt,
agentType: data.agentType,
toolName: data.toolName,
toolInput: data.toolInput,
lastAssistantMessage: data.lastAssistantMessage,
interrupted: data.interrupted
})
if (!payload) {
return
}
const { exists, title } = resolvePaneKey(store, data.paneKey)
if (!exists) {
return
}
store.setAgentStatus(data.paneKey, payload, title, {
updatedAt: data.receivedAt,
stateStartedAt: data.stateStartedAt
})
}
let snapshotRequestedForReadyWindow = false
let snapshotRequestId = 0
const requestAgentStatusSnapshotIfReady = (): void => {
const store = useAppStore.getState()
if (!store.workspaceSessionReady) {
snapshotRequestedForReadyWindow = false
return
}
if (snapshotRequestedForReadyWindow) {
return
}
const getSnapshot = window.api.agentStatus.getSnapshot
if (typeof getSnapshot !== 'function') {
return
}
snapshotRequestedForReadyWindow = true
const requestId = ++snapshotRequestId
void getSnapshot()
.then((entries) => {
if (requestId !== snapshotRequestId) {
return
}
const current = useAppStore.getState()
if (!current.workspaceSessionReady) {
return
}
for (const entry of entries) {
applyAgentStatus(entry)
}
})
.catch((err) => {
// Why: keep snapshotRequestedForReadyWindow latched on failure. The
// store subscriber below fires on every update (including high-rate
// PTY ticks), so resetting the flag here would turn a persistent IPC
// failure into an unbounded retry storm. One warning per ready
// window is sufficient; the flag still clears when
// workspaceSessionReady toggles off, so a fresh workspace re-ready
// cycle will retry.
console.warn('[agent-status] failed to load startup snapshot:', err)
})
}
unsubs.push(
window.api.agentStatus.onSet((data) => {
const store = useAppStore.getState()
// Why: the IPC payload is already a structured object — pass it
// straight to the object-input normalizer instead of round-tripping
// through JSON.stringify/JSON.parse. Hook events can fire many times
// per second during a tool-use run, so this avoids the per-event
// serialization cost.
const payload = normalizeAgentStatusPayload({
state: data.state,
prompt: data.prompt,
agentType: data.agentType,
toolName: data.toolName,
toolInput: data.toolInput,
lastAssistantMessage: data.lastAssistantMessage,
interrupted: data.interrupted
})
if (!payload) {
return
}
// Why: resolve tab existence and terminal title in a single pass.
// Previously the code walked store.tabsByWorktree twice — once to
// look up the tab-level title (when the pane-level title was
// missing) and again for the explicit tabExists check. A paneKey
// that no longer resolves to a live tab belongs to a pane that has
// already been torn down; dropping here prevents orphan entries
// from accumulating in agentStatusByPaneKey.
const { exists, title } = resolvePaneKey(store, data.paneKey)
if (!exists) {
return
}
store.setAgentStatus(data.paneKey, payload, title)
applyAgentStatus(data)
})
)
// Why: the main hook server is the durable source of truth. Pull a
// snapshot only after workspace tabs are ready, so early startup pushes
// can be safely ignored instead of buffered against partially hydrated
// renderer state.
requestAgentStatusSnapshotIfReady()
unsubs.push(useAppStore.subscribe(() => requestAgentStatusSnapshotIfReady()))
// Why: hydrate mobile-fit overrides before terminal panes run their first
// attach/fit logic, so a renderer reload doesn't undo active mobile fits.
void window.api.runtime.getTerminalFitOverrides().then((overrides) => {
@@ -0,0 +1,120 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { type AgentStatusEntry } from '../../../../shared/agent-status-types'
import type { TerminalTab } from '../../../../shared/types'
import type { RetainedAgentEntry } from './agent-status'
import { createTestStore } from './store-test-helpers'
// Why: dropAgentStatus and dismissRetainedAgentsByWorktree mirror the renderer-
// side dismissal to the main-process hook cache via window.api.agentStatus.drop
// so the on-disk last-status file evicts dismissed paneKeys. Without this, a
// dismissed row would re-appear after Orca restart from the hydrated cache.
const originalWindow = (globalThis as { window?: unknown }).window
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
if (originalWindow === undefined) {
delete (globalThis as { window?: unknown }).window
} else {
;(globalThis as { window?: unknown }).window = originalWindow
}
})
function stubWindowApi(): { drop: ReturnType<typeof vi.fn> } {
const drop = vi.fn()
;(globalThis as { window?: unknown }).window = {
api: { agentStatus: { drop } }
}
return { drop }
}
describe('dropAgentStatus → IPC fan-out', () => {
it('fires window.api.agentStatus.drop exactly once after a live-entry drop', () => {
const { drop } = stubWindowApi()
const store = createTestStore()
store
.getState()
.setAgentStatus('tab-1:0', { state: 'working', prompt: 'p', agentType: 'claude' })
store.getState().dropAgentStatus('tab-1:0')
expect(drop).toHaveBeenCalledTimes(1)
expect(drop).toHaveBeenCalledWith('tab-1:0')
})
it('still fires drop on a no-op dismissal so a stale on-disk entry is cleaned up defensively', () => {
// Why: the renderer cannot know whether the main-process cache has an
// entry for this paneKey (it might have one from a hydrated session). A
// no-op renderer dismissal must still propagate so stale on-disk state
// is purged; the main-process dropStatusEntry is itself idempotent.
const { drop } = stubWindowApi()
const store = createTestStore()
store.getState().dropAgentStatus('tab-missing:0')
expect(drop).toHaveBeenCalledTimes(1)
expect(drop).toHaveBeenCalledWith('tab-missing:0')
})
it('idempotent: repeated drops on the same paneKey fire the IPC each time', () => {
// Why: the renderer keeps drop() side-effect free relative to its own
// state — sending an extra IPC for an already-dropped paneKey is safe
// because main-side dropStatusEntry is a no-op when the entry is gone.
// Asserting this contract documents the renderer's hands-off posture.
const { drop } = stubWindowApi()
const store = createTestStore()
store
.getState()
.setAgentStatus('tab-1:0', { state: 'working', prompt: 'p', agentType: 'claude' })
store.getState().dropAgentStatus('tab-1:0')
store.getState().dropAgentStatus('tab-1:0')
expect(drop).toHaveBeenCalledTimes(2)
})
})
describe('dismissRetainedAgentsByWorktree → IPC fan-out', () => {
it('fires drop once per dismissed paneKey under the worktree', () => {
const { drop } = stubWindowApi()
const store = createTestStore()
const now = Date.now()
function makeRetained(paneKey: string, worktreeId: string): RetainedAgentEntry {
const entry: AgentStatusEntry = {
state: 'done',
prompt: '',
updatedAt: now,
stateStartedAt: now,
paneKey,
stateHistory: []
}
return {
entry,
worktreeId,
tab: { id: paneKey.split(':')[0], title: 'claude' } as unknown as TerminalTab,
agentType: 'claude',
startedAt: now
}
}
store
.getState()
.retainAgents([
makeRetained('tab-a:0', 'wt-target'),
makeRetained('tab-b:0', 'wt-target'),
makeRetained('tab-c:0', 'wt-other')
])
store.getState().dismissRetainedAgentsByWorktree('wt-target')
expect(drop).toHaveBeenCalledTimes(2)
const calls = drop.mock.calls.map((c) => c[0]).sort()
expect(calls).toEqual(['tab-a:0', 'tab-b:0'])
// Why: the other worktree's retained row must remain.
expect(store.getState().retainedAgentsByPaneKey['tab-c:0']).toBeDefined()
})
it('does not fire IPC when no retained entries match the worktree', () => {
const { drop } = stubWindowApi()
const store = createTestStore()
store.getState().dismissRetainedAgentsByWorktree('wt-empty')
expect(drop).not.toHaveBeenCalled()
})
})
@@ -42,12 +42,9 @@ export function createFreshnessScheduler(deps: FreshnessSchedulerDeps): Freshnes
// the timer forever because the bump doesn't clear them from the map
// (retention is intentional so freshness-aware selectors can decay).
//
// Invariant: the agent-status slice always writes `updatedAt = Date.now()`
// on insert/update (see `setAgentStatus` in agent-status.ts), so a
// newly-scheduled entry cannot already be stale here. If that invariant
// ever breaks (e.g. persistence rehydrate, IPC-synced backdated entries),
// the scheduler would silently no-op and miss the epoch bump — revisit
// this filter at that time.
// Snapshot hydration can insert already-stale entries. Those need no
// future timer: the setAgentStatus write already bumped the epoch, so
// freshness-aware selectors can decay them immediately on that render.
for (const entry of entries) {
const expiryAt = entry.updatedAt + AGENT_STATUS_STALE_AFTER_MS
if (expiryAt > now) {
@@ -1,3 +1,4 @@
/* eslint-disable max-lines -- Why: this file is the umbrella suite for the agent-status slice (freshness, tool/assistant fields, stateStartedAt, retention + prefix sweep). Splitting by sub-area would scatter shared helpers (createTestStore, fake timers); narrower edge-cases live in sibling agent-status-*.test.ts files already. */
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
AGENT_STATUS_STALE_AFTER_MS,
@@ -193,6 +194,54 @@ describe('agent status stateStartedAt', () => {
expect(entry.stateHistory[0].state).toBe('working')
expect(entry.stateHistory[0].startedAt).toBe(workingStart)
})
it('uses IPC snapshot timing instead of restamping restored entries as fresh', () => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-04-09T12:00:00.000Z'))
const store = createTestStore()
store
.getState()
.setAgentStatus(
'tab-1:1',
{ state: 'working', prompt: 'p1', agentType: 'claude' },
'claude',
{
updatedAt: new Date('2026-04-09T10:00:00.000Z').getTime(),
stateStartedAt: new Date('2026-04-09T09:55:00.000Z').getTime()
}
)
const entry = store.getState().agentStatusByPaneKey['tab-1:1']
expect(entry.updatedAt).toBe(new Date('2026-04-09T10:00:00.000Z').getTime())
expect(entry.stateStartedAt).toBe(new Date('2026-04-09T09:55:00.000Z').getTime())
})
it('ignores an older snapshot when a newer live event already updated the pane', () => {
vi.useFakeTimers()
const store = createTestStore()
store
.getState()
.setAgentStatus(
'tab-1:1',
{ state: 'working', prompt: 'fresh', agentType: 'claude' },
'claude',
{ updatedAt: 2_000, stateStartedAt: 2_000 }
)
store
.getState()
.setAgentStatus(
'tab-1:1',
{ state: 'done', prompt: 'stale', agentType: 'claude' },
'claude',
{ updatedAt: 1_000, stateStartedAt: 1_000 }
)
const entry = store.getState().agentStatusByPaneKey['tab-1:1']
expect(entry.state).toBe('working')
expect(entry.prompt).toBe('fresh')
expect(entry.updatedAt).toBe(2_000)
})
})
describe('agent status retention + prefix sweep', () => {
+46 -14
View File
@@ -51,7 +51,8 @@ export type AgentStatusSlice = {
setAgentStatus: (
paneKey: string,
payload: ParsedAgentStatusPayload,
terminalTitle?: string
terminalTitle?: string,
timing?: { updatedAt?: number; stateStartedAt?: number }
) => void
/** Remove a single entry (e.g., when a pane's terminal exits). */
@@ -145,9 +146,16 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
retainedAgentsByPaneKey: {},
retentionSuppressedPaneKeys: {},
setAgentStatus: (paneKey, payload, terminalTitle) => {
setAgentStatus: (paneKey, payload, terminalTitle, timing) => {
const updatedAt = timing?.updatedAt ?? Date.now()
set((s) => {
const existing = s.agentStatusByPaneKey[paneKey]
// Why: snapshots and live pushes share receivedAt from the same main-side
// lastStatusByPaneKey.set, so equal timestamps carry identical data. Strict <
// preserves live-after-live updates that land in the same millisecond.
if (existing && updatedAt < existing.updatedAt) {
return s
}
// Why: terminalTitle is identity-like — it labels the pane itself, not
// the current turn's activity. Preserve the prior value when a ping
// omits it so the pane label does not flicker out between hook events.
@@ -182,13 +190,14 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
}
}
const now = Date.now()
// Why: stateStartedAt anchors to the first time this state was
// reported. Carry forward the prior value on tool/prompt pings within
// the same state so stateHistory[].startedAt reflects true state-onset
// (see AgentStatusEntry.stateStartedAt docs).
// Why: prefer main's authoritative stateStartedAt when provided — main's
// attachStatusTiming preserves it across same-state pings (server.ts) and
// persists it across restart. Fall back to existing.stateStartedAt only when
// main did not send timing (legacy callers / OSC fallback path), and to
// updatedAt for a brand-new pane.
const stateStartedAt =
existing && existing.state === payload.state ? existing.stateStartedAt : now
timing?.stateStartedAt ??
(existing && existing.state === payload.state ? existing.stateStartedAt : updatedAt)
// Why: tool/assistant fields come pre-merged from the main-process
// cache (see `resolveToolState` in server.ts), so the payload always
@@ -198,7 +207,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
const entry: AgentStatusEntry = {
state: payload.state,
prompt: payload.prompt,
updatedAt: now,
updatedAt,
stateStartedAt,
// Why: unlike tool/prompt/assistant fields (which legitimately clear on a
// fresh turn), agentType is the agent's identity for the pane — it does
@@ -234,14 +243,15 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
// 1. `state` transitions — sort score is a function of state.
// 2. Freshness transitions (stale → fresh) — `computeSmartScoreFromSignals`
// in smart-sort.ts filters entries through
// `isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS)`
// `isExplicitAgentStatusFresh(entry, updatedAt, AGENT_STATUS_STALE_AFTER_MS)`
// (30-min TTL). A stale entry that refreshes with the SAME state
// goes from "not contributing" to contributing +60 (working) or
// +35 (blocked/waiting) to the score — order must update. The new
// entry below always has `updatedAt = now`, so it is fresh; we
// only need to detect the stale→fresh flip on `existing`.
// +35 (blocked/waiting) to the score — order must update. Snapshot
// hydration can pass an older updatedAt; in that case the entry is
// still stored with its true age, and selectors will immediately
// decay it if it is already stale.
const wasFresh =
!!existing && isExplicitAgentStatusFresh(existing, now, AGENT_STATUS_STALE_AFTER_MS)
!!existing && isExplicitAgentStatusFresh(existing, updatedAt, AGENT_STATUS_STALE_AFTER_MS)
const sortRelevantChange = !existing || existing.state !== payload.state || !wasFresh
// Why: a new status event means the agent is live again — lift any
// one-shot retention suppressor so the row can be retained normally
@@ -442,6 +452,15 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
if (liveExisted) {
queueMicrotask(() => freshness.schedule())
}
// Why: propagate the dismissal to the main-process hook cache so the
// on-disk last-status file evicts this paneKey on the next debounced
// write. Without this, the main process would re-hydrate the dismissed
// entry on the next launch and the row would re-appear. Fire-and-forget.
// Why: the typeof window guard keeps the slice usable from the
// node test environment, where window is undefined.
if (typeof window !== 'undefined') {
window.api?.agentStatus?.drop?.(paneKey)
}
},
dropAgentStatusByTabPrefix: (tabIdPrefix) => {
@@ -685,6 +704,13 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
},
dismissRetainedAgentsByWorktree: (worktreeId) => {
// Why: collect inside set so we capture the exact paneKeys removed
// (worktree filter is applied here). After the synchronous set()
// returns, fan out a window.api.agentStatus.drop per removed key so
// the main-process hook cache (and on-disk last-status file) eviction
// matches the renderer's removal. Without this, the on-disk cache
// would resurrect the dismissed rows on the next launch.
const dismissedPaneKeys: string[] = []
set((s) => {
let changed = false
const next: Record<string, RetainedAgentEntry> = {}
@@ -703,6 +729,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
for (const [key, ra] of Object.entries(s.retainedAgentsByPaneKey)) {
if (ra.worktreeId === worktreeId) {
changed = true
dismissedPaneKeys.push(key)
if (key in s.agentStatusByPaneKey && !(key in s.retentionSuppressedPaneKeys)) {
toSuppress.push(key)
}
@@ -725,6 +752,11 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
retentionSuppressedPaneKeys: nextSuppressed
}
})
if (typeof window !== 'undefined') {
for (const paneKey of dismissedPaneKeys) {
window.api?.agentStatus?.drop?.(paneKey)
}
}
},
pruneRetainedAgents: (validWorktreeIds) => {
+177
View File
@@ -1,3 +1,4 @@
/* eslint-disable max-lines */
import { createStore, type StoreApi } from 'zustand/vanilla'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { getDefaultUIState } from '../../../../shared/constants'
@@ -199,6 +200,182 @@ describe('createUISlice hydratePersistedUI', () => {
})
})
it('restores acknowledgedAgentsByPaneKey from persisted UI state', () => {
const now = 1_700_000_000_000
vi.useFakeTimers()
vi.setSystemTime(now)
try {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
acknowledgedAgentsByPaneKey: { 'tab-a:0': now, 'tab-b:1': now - 5_000 }
})
)
expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({
'tab-a:0': now,
'tab-b:1': now - 5_000
})
} finally {
vi.useRealTimers()
}
})
it('falls back to an empty ack map when persisted UI omits acknowledgedAgentsByPaneKey', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(makePersistedUI())
expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({})
})
it('falls back to an empty ack map when persisted acknowledgedAgentsByPaneKey is null', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
acknowledgedAgentsByPaneKey:
null as unknown as PersistedUIState['acknowledgedAgentsByPaneKey']
})
)
expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({})
})
it('falls back to an empty ack map when persisted acknowledgedAgentsByPaneKey is a string', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
acknowledgedAgentsByPaneKey:
'oops' as unknown as PersistedUIState['acknowledgedAgentsByPaneKey']
})
)
expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({})
})
it('falls back to an empty ack map when persisted acknowledgedAgentsByPaneKey is an array', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
acknowledgedAgentsByPaneKey: [
'a',
'b'
] as unknown as PersistedUIState['acknowledgedAgentsByPaneKey']
})
)
expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({})
})
it('drops non-number / non-finite / non-positive entries from acknowledgedAgentsByPaneKey', () => {
const now = 1_700_000_000_000
vi.useFakeTimers()
vi.setSystemTime(now)
try {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
acknowledgedAgentsByPaneKey: {
'tab-a:0': now,
'tab-b:1': now - 1000,
'tab-c:2': 'not-a-number',
'tab-d:3': Number.NaN,
'tab-e:4': Number.POSITIVE_INFINITY,
'tab-f:5': -1
} as unknown as Record<string, number>
})
)
expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({
'tab-a:0': now,
'tab-b:1': now - 1000
})
} finally {
vi.useRealTimers()
}
})
it('prunes acknowledgedAgentsByPaneKey entries older than the 7-day TTL during hydration', () => {
// HYDRATE_MAX_AGE_MS lives in src/renderer/src/store/slices/ui.ts and matches
// the constant in src/main/agent-hooks/server.ts.
const SEVEN_DAYS_MS = 7 * 24 * 60 * 60 * 1000
const now = 1_700_000_000_000
vi.useFakeTimers()
vi.setSystemTime(now)
try {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
acknowledgedAgentsByPaneKey: {
'tab-recent:0': now,
'tab-old:1': now - SEVEN_DAYS_MS - 1
}
})
)
expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({
'tab-recent:0': now
})
} finally {
// The shared afterEach restores mocks/globals but not timers, so clean up
// here to avoid leaking fake timers into subsequent tests.
vi.useRealTimers()
}
})
it('drops prototype-pollution keys from acknowledgedAgentsByPaneKey during hydration', () => {
const now = 1_700_000_000_000
vi.useFakeTimers()
vi.setSystemTime(now)
try {
const store = createUIStore()
const malicious: Record<string, number> = {}
// Object.defineProperty so these land as own enumerable properties rather
// than getting silently re-routed to Object.prototype by the JS engine.
Object.defineProperty(malicious, '__proto__', {
value: now,
enumerable: true,
configurable: true,
writable: true
})
Object.defineProperty(malicious, 'constructor', {
value: now,
enumerable: true,
configurable: true,
writable: true
})
Object.defineProperty(malicious, 'prototype', {
value: now,
enumerable: true,
configurable: true,
writable: true
})
malicious['tab-safe:0'] = now
store.getState().hydratePersistedUI(
makePersistedUI({
acknowledgedAgentsByPaneKey: malicious
})
)
expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({
'tab-safe:0': now
})
} finally {
vi.useRealTimers()
}
})
it('merges and persists partial task resume updates', () => {
const setUI = vi.fn().mockResolvedValue(undefined)
vi.stubGlobal('window', { api: { ui: { set: setUI } } })
+47 -3
View File
@@ -76,6 +76,12 @@ const MAX_LEFT_SIDEBAR_WIDTH = 500
// cap on wide displays. Use a large hard ceiling purely as a safety net for
// corrupted/manually-edited values rather than as a product limit.
const MAX_RIGHT_SIDEBAR_WIDTH = 4000
// Why: bound disk growth for acknowledgedAgentsByPaneKey across hard quits —
// in-session cleanup (agent-status.ts) prunes on pane lifecycle, but crash/
// forced-kill paths leave entries pinned. Mirrors HYDRATE_MAX_AGE_MS in
// src/main/agent-hooks/server.ts for parallel reasoning with the sibling
// hook-status entries these acks pair with.
const HYDRATE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000
const VALID_TASK_PRESETS = new Set<TaskViewPresetId>([
'all',
'issues',
@@ -111,6 +117,34 @@ function sanitizePersistedSidebarWidth(width: unknown, fallback: number, maxWidt
return Math.min(maxWidth, Math.max(MIN_SIDEBAR_WIDTH, width))
}
// Why: persisted JSON can be tampered with or carry legacy/corrupt shapes.
// Reject arrays (typeof [] === 'object'), prototype-pollution keys, and
// non-positive-finite values; drop entries past the TTL so hard-quit leaks
// don't accumulate forever.
function sanitizeAcknowledgedAgentsByPaneKey(value: unknown): Record<string, number> {
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
return {}
}
const cutoff = Date.now() - HYDRATE_MAX_AGE_MS
const out: Record<string, number> = {}
for (const [key, ackAt] of Object.entries(value as Record<string, unknown>)) {
if (typeof key !== 'string') {
continue
}
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
continue
}
if (typeof ackAt !== 'number' || !Number.isFinite(ackAt) || ackAt <= 0) {
continue
}
if (ackAt < cutoff) {
continue
}
out[key] = ackAt
}
return out
}
function sanitizeTaskResumeState(value: unknown): TaskResumeState | undefined {
if (!value || typeof value !== 'object') {
return undefined
@@ -154,9 +188,9 @@ export type UISlice = {
* the user clicks an agent row or its parent workspace card from the
* dashboard. A row is considered unvisited when no ack exists OR the
* agent's current stateStartedAt is newer than the last ack (i.e. the
* agent has transitioned state since the user last saw it). Session-only
* — restart resets everyone to unvisited, which is harmless since the
* first visit after launch is a legitimate "need to see" moment. */
* agent has transitioned state since the user last saw it). Persisted
* via PersistedUIState because agent rows themselves now survive restart —
* without this, rows you'd already visited come back bold on relaunch. */
acknowledgedAgentsByPaneKey: Record<string, number>
acknowledgeAgents: (paneKeys: string[]) => void
/** Per-worktree collapsed state for the inline agents section shown inside
@@ -746,6 +780,16 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
ui.trustedOrcaHooks ?? {},
validRepoIds
),
// Why: restore visited-row acks alongside the persisted hook entries
// they pair with. Stale acks for paneKeys whose tab/PTY no longer
// exists are inert (no row references them); a paneKey reuse stamps a
// fresh stateStartedAt that beats the old ack via the ackAt <
// stateStartedAt comparison in WorktreeCardAgents. Sanitizer drops
// entries past HYDRATE_MAX_AGE_MS so hard-quit/crash paths that miss
// the in-session cleanup in agent-status.ts can't accumulate forever.
acknowledgedAgentsByPaneKey: sanitizeAcknowledgedAgentsByPaneKey(
ui.acknowledgedAgentsByPaneKey
),
persistedUIReady: true
}
}),
+22
View File
@@ -103,6 +103,28 @@ export type AgentStatusPayload = {
*/
export type ParsedAgentStatusPayload = Omit<AgentStatusPayload, 'prompt'> & { prompt: string }
/**
* Wire shape for agent-status IPC. Both the push channel `agentStatus:set` and the
* pull channel `agentStatus:getSnapshot` produce this shape so renderer call sites
* can apply entries through a single `setAgentStatus` path. Flattens the parsed
* payload onto pane identity + timing because the renderer's slice expects them
* destructured.
*/
export type AgentStatusIpcPayload = ParsedAgentStatusPayload & {
paneKey: string
tabId?: string
worktreeId?: string
/** Identifies the SSH connection the event arrived on, or null for local.
* Stamped only on the remote-ingest path (Orca's `ingestRemote`); the
* HTTP path always sets null because it cannot know which mux a request
* came from. See docs/design/agent-status-over-ssh.md §5. */
connectionId: string | null
/** Timestamp (ms) when the hook server received this latest status event. */
receivedAt: number
/** Timestamp (ms) when the current state first appeared for this pane. */
stateStartedAt: number
}
/** Maximum character length for the prompt field. Truncated on parse. */
export const AGENT_STATUS_MAX_FIELD_LENGTH = 200
/** Maximum character length for the toolName field. */
+2 -1
View File
@@ -292,7 +292,8 @@ export function getDefaultUIState(): PersistedUIState {
statusBarVisible: true,
dismissedUpdateVersion: null,
lastUpdateCheckAt: null,
trustedOrcaHooks: {}
trustedOrcaHooks: {},
acknowledgedAgentsByPaneKey: {}
}
}
+8
View File
@@ -1461,6 +1461,14 @@ export type PersistedUIState = {
/** Once the user has seen the "your sessions won't be interrupted"
* reassurance card, we never show it again. */
updateReassuranceSeen?: boolean
/** Per-paneKey "user has visited this row" timestamps, used by the inline
* agents list to mute rows the user has already seen. Persisted because
* agent rows themselves now survive restart; without persisting acks too,
* rows you'd already clicked come back bold on relaunch. Stale entries
* keyed on dead panes are inert: a future paneKey reuse stamps a fresh
* stateStartedAt that beats the old ack via the existing comparison in
* WorktreeCardAgents. Renderer-owned, written through ui:set. */
acknowledgedAgentsByPaneKey?: Record<string, number>
/** URL to navigate to when a new browser tab is opened. Null means blank tab.
* Phase 3 will expand this to a full BrowserSessionProfile per workspace. */
browserDefaultUrl?: string | null