Skip to content

The agent that grows with you

feat(desktop): hydrate structured session controls

Jerry Goochbfddf556bff4
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts
index 8c86f65d817..572e5c138e1 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts
@@ -20,6 +20,7 @@ import { handleDesktopBridgeEvent } from './desktop-bridge'
import { handleInputRequestEvent } from './input-requests'
import { handleLifecycleEvent } from './lifecycle'
import { handleMessageStreamEvent } from './message-stream'
+import { handleControlEvent } from './session-control'
import { handleSessionInfoEvent } from './session-info'
import { handleStatusEvent } from './status'
import { handleToolEvent } from './tools'
@@ -84,6 +85,7 @@ const PROVIDER_WAIT_SUPERSEDING_EVENT_TYPES = new Set([
const HANDLERS: GatewayEventHandler[] = [
handleLifecycleEvent,
handleSessionInfoEvent,
+ handleControlEvent,
handleMessageStreamEvent,
handleToolEvent,
handleInputRequestEvent,
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.test.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.test.ts
new file mode 100644
index 00000000000..db81acdab16
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it, vi } from 'vitest'
+
+const { refreshSupportedSessionControlAfterTurn } = vi.hoisted(() => ({
+ refreshSupportedSessionControlAfterTurn: vi.fn(async () => undefined)
+}))
+
+vi.mock('@/store/session-control', () => ({ refreshSupportedSessionControlAfterTurn }))
+
+import { handleMessageStreamEvent } from './message-stream'
+import type { GatewayEventContext } from './types'
+
+function context(type: string): GatewayEventContext {
+ return {
+ deps: {
+ activeGatewayProfile: 'default',
+ activeSessionIdRef: { current: 's1' },
+ appendAssistantDelta: vi.fn(),
+ appendReasoningDelta: vi.fn(),
+ compactedTurnRef: { current: new Set() },
+ completeAssistantMessage: vi.fn(),
+ failAssistantMessage: vi.fn(),
+ finalizeInterimAssistantMessage: vi.fn(),
+ flushQueuedDeltas: vi.fn(),
+ hydrateFromStoredSession: vi.fn(async () => undefined),
+ lastCwdInfoSessionRef: { current: null },
+ nativeSubagentSessionsRef: { current: new Set() },
+ queryClient: {} as GatewayEventContext['deps']['queryClient'],
+ refreshHermesConfig: vi.fn(async () => undefined),
+ scheduleSessionsRefresh: vi.fn(),
+ sessionInterrupted: vi.fn(() => false),
+ sessionStateByRuntimeIdRef: { current: new Map() },
+ updateSessionState: vi.fn(),
+ upsertToolCall: vi.fn()
+ },
+ event: { type },
+ explicitSid: 's1',
+ fromActiveSource: () => true,
+ isActiveEvent: false,
+ occurredAt: 1_700_000_100,
+ payload: { text: 'completed' },
+ scheduleConfigRefresh: vi.fn(),
+ sessionId: 's1'
+ }
+}
+
+describe('handleMessageStreamEvent session-control integration', () => {
+ it('refreshes only after message.complete, through the store seam', () => {
+ expect(handleMessageStreamEvent(context('message.delta'))).toBe(true)
+ expect(refreshSupportedSessionControlAfterTurn).not.toHaveBeenCalled()
+
+ expect(handleMessageStreamEvent(context('message.complete'))).toBe(true)
+ expect(refreshSupportedSessionControlAfterTurn).toHaveBeenCalledTimes(1)
+ expect(refreshSupportedSessionControlAfterTurn).toHaveBeenCalledWith('s1')
+ })
+})
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts
index 43be63e1905..97fb4a65a59 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts
@@ -14,6 +14,7 @@ import { flashPetActivity, markPetUnread, setPetActivity } from '@/store/pet'
import { clearAllPrompts } from '@/store/prompts'
import { providerWaitText, setSessionProviderWait } from '@/store/provider-wait'
import { setCurrentUsage, setTurnStartedAt } from '@/store/session'
+import { refreshSupportedSessionControlAfterTurn } from '@/store/session-control'
import { pruneFinishedSessionSubagents } from '@/store/subagents'
import { clearActiveSessionTodos } from '@/store/todos'
@@ -388,6 +389,10 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {
}
}
+ // Refresh only the structured-control sessions already proven capable.
+ // Initial hydration owns the unknown capability probe.
+ void refreshSupportedSessionControlAfterTurn(sessionId)
+
return true
}
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-control.test.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-control.test.ts
new file mode 100644
index 00000000000..6211e57b713
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-control.test.ts
@@ -0,0 +1,72 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import {
+ $sessionControlBySession,
+ resetSessionControlForTests,
+ type SessionControlSnapshot
+} from '@/store/session-control'
+
+import { handleControlEvent } from './session-control'
+import type { GatewayEventContext } from './types'
+
+const SNAPSHOT: SessionControlSnapshot = {
+ goal: null,
+ heartbeat: null,
+ loop: null,
+ revision: 'event-revision',
+ updated_at: 1_700_000_100
+}
+
+function context(overrides: Partial<GatewayEventContext> = {}): GatewayEventContext {
+ return {
+ deps: {} as GatewayEventContext['deps'],
+ event: { payload: { control: SNAPSHOT }, session_id: 'event-session', type: 'session.control.update' },
+ explicitSid: 'event-session',
+ fromActiveSource: () => true,
+ isActiveEvent: true,
+ occurredAt: 1_700_000_100,
+ payload: { control: SNAPSHOT } as GatewayEventContext['payload'],
+ scheduleConfigRefresh: vi.fn(),
+ sessionId: 'routed-session',
+ ...overrides
+ }
+}
+
+describe('handleControlEvent', () => {
+ afterEach(() => {
+ resetSessionControlForTests()
+ })
+
+ it('does not claim non-control events', () => {
+ expect(handleControlEvent(context({ event: { type: 'message.complete' } }))).toBe(false)
+ })
+
+ it('applies a valid event to the routed session and proves it supported', () => {
+ expect(handleControlEvent(context())).toBe(true)
+
+ expect($sessionControlBySession.get()).toMatchObject({
+ 'routed-session': { capability: 'supported', snapshot: { revision: 'event-revision' } }
+ })
+ expect($sessionControlBySession.get()['event-session']).toBeUndefined()
+ })
+
+ it('claims malformed control events without replacing the last good state', () => {
+ handleControlEvent(context())
+ const first = $sessionControlBySession.get()['routed-session']
+
+ expect(
+ handleControlEvent(
+ context({
+ payload: { control: { ...SNAPSHOT, updated_at: Number.POSITIVE_INFINITY } } as GatewayEventContext['payload']
+ })
+ )
+ ).toBe(true)
+
+ expect($sessionControlBySession.get()['routed-session']).toBe(first)
+ })
+
+ it('claims an unscoped control event without creating state', () => {
+ expect(handleControlEvent(context({ sessionId: null }))).toBe(true)
+ expect($sessionControlBySession.get()).toEqual({})
+ })
+})
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-control.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-control.ts
new file mode 100644
index 00000000000..7f9f27e4248
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-control.ts
@@ -0,0 +1,20 @@
+import { applySessionControlUpdate } from '@/store/session-control'
+
+import type { GatewayEventContext } from './types'
+
+export function handleControlEvent(ctx: GatewayEventContext): boolean {
+ const { event, payload, sessionId } = ctx
+
+ if (event.type !== 'session.control.update') {
+ return false
+ }
+
+ if (!sessionId) {
+ return true
+ }
+
+ const control = payload && typeof payload === 'object' ? (payload as { control?: unknown }).control : undefined
+ applySessionControlUpdate(sessionId, control)
+
+ return true
+}
diff --git a/apps/desktop/src/store/session-control.test.ts b/apps/desktop/src/store/session-control.test.ts
new file mode 100644
index 00000000000..c4cc9f1f72e
--- /dev/null
+++ b/apps/desktop/src/store/session-control.test.ts
@@ -0,0 +1,457 @@
+import { JsonRpcGatewayError } from '@hermes/shared'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const { refreshLegacyGoal } = vi.hoisted(() => ({ refreshLegacyGoal: vi.fn() }))
+
+vi.mock('./goals', async importOriginal => ({
+ ...(await importOriginal()),
+ refreshSessionGoal: refreshLegacyGoal
+}))
+
+import { $gateway } from './gateway'
+import { resetBackgroundPollingGuard } from './runtime-gone'
+import {
+ $sessionControlBySession,
+ applySessionControlSnapshot,
+ applySessionControlUpdate,
+ clearSessionControl,
+ parseSessionControlSnapshot,
+ refreshSessionControl,
+ refreshSupportedSessionControlAfterTurn,
+ resetSessionControlAfterGatewayRebind,
+ resetSessionControlForTests,
+ runSessionControlAction,
+ type SessionControlSnapshot
+} from './session-control'
+
+const FULL_SNAPSHOT: SessionControlSnapshot = {
+ goal: {
+ contract: {
+ boundaries: 'desktop store only',
+ constraints: 'do not lose state',
+ outcome: 'session control is hydrated',
+ stop_when: 'a human decision is required',
+ verification: 'focused tests pass'
+ },
+ created_at: 1_700_000_000,
+ gates: [{ attempts: 0, command: 'npm test', last_exit_code: null, max_retries: 2, timeout_seconds: 60 }],
+ max_turns: 20,
+ status: 'active',
+ subgoals: ['write tests', 'repair state'],
+ title: 'Repair session control',
+ turns_used: 3,
+ updated_at: 1_700_000_100,
+ wait_barrier: { reason: 'waiting for deploy', type: 'until', until_at: 1_700_000_200 }
+ },
+ heartbeat: {
+ created_at: 1_700_000_000,
+ fire_count: 5,
+ interval_seconds: 600,
+ last_fired_at: 1_700_000_100,
+ prompt: 'check health',
+ status: 'active'
+ },
+ loop: {
+ awaiting_response: false,
+ created_at: 1_700_000_000,
+ current_delay: 300,
+ deferred_by_goal: false,
+ interval_seconds: 300,
+ last_fired_at: 1_700_000_100,
+ max_ticks: 10,
+ mode: 'interval',
+ next_due_at: 1_700_000_400,
+ prompt: 'check build status',
+ status: 'active',
+ ticks_fired: 3,
+ times: 3,
+ until: ''
+ },
+ revision: 'revision-1',
+ updated_at: 1_700_000_100
+}
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ let reject!: (error: unknown) => void
+
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise
+ reject = rejectPromise
+ })
+
+ return { promise, reject, resolve }
+}
+
+function useGateway(request: (method: string, params: Record<string, unknown>) => Promise<unknown>): void {
+ $gateway.set({ request } as never)
+}
+
+describe('session-control store', () => {
+ beforeEach(() => {
+ refreshLegacyGoal.mockReset()
+ resetSessionControlForTests()
+ })
+
+ afterEach(() => {
+ $gateway.set(null as never)
+ resetBackgroundPollingGuard()
+ resetSessionControlForTests()
+ })
+
+ it('parses the exact persisted goal, loop, heartbeat, and wait-barrier shapes into fresh data', () => {
+ const parsed = parseSessionControlSnapshot(FULL_SNAPSHOT)
+
+ expect(parsed).toEqual(FULL_SNAPSHOT)
+ expect(parsed).not.toBe(FULL_SNAPSHOT)
+ expect(parsed!.goal).not.toBe(FULL_SNAPSHOT.goal)
+ expect(parsed!.goal!.contract).not.toBe(FULL_SNAPSHOT.goal!.contract)
+ expect(parsed!.loop!.mode).toBe('interval')
+ expect(parsed!.goal!.wait_barrier).toEqual({ reason: 'waiting for deploy', type: 'until', until_at: 1_700_000_200 })
+ })
+
+ it.each([
+ ['unknown goal status', { ...FULL_SNAPSHOT, goal: { ...FULL_SNAPSHOT.goal!, status: 'waiting' } }],
+ ['non-finite top-level timestamp', { ...FULL_SNAPSHOT, updated_at: Number.NaN }],
+ ['malformed goal contract', { ...FULL_SNAPSHOT, goal: { ...FULL_SNAPSHOT.goal!, contract: { outcome: 3 } } }],
+ [
+ 'gate output that is not in the allowlisted summary',
+ {
+ ...FULL_SNAPSHOT,
+ goal: { ...FULL_SNAPSHOT.goal!, gates: [{ ...FULL_SNAPSHOT.goal!.gates[0], last_output_tail: 'leak' }] }
+ }
+ ],
+ [
+ 'wait target that does not match its discriminator',
+ { ...FULL_SNAPSHOT, goal: { ...FULL_SNAPSHOT.goal!, wait_barrier: { reason: 'pid', target: '7', type: 'pid' } } }
+ ],
+ ['unknown loop mode', { ...FULL_SNAPSHOT, loop: { ...FULL_SNAPSHOT.loop!, mode: 'fixed' } }],
+ ['malformed heartbeat', { ...FULL_SNAPSHOT, heartbeat: { ...FULL_SNAPSHOT.heartbeat!, fire_count: 'five' } }],
+ ['unknown top-level field', { ...FULL_SNAPSHOT, unsupported: true }]
+ ])('rejects %s without accepting a partial snapshot', (_name, value) => {
+ expect(parseSessionControlSnapshot(value)).toBeNull()
+ })
+
+ it('preserves entry and snapshot identity for a same-revision snapshot with no other state change', () => {
+ applySessionControlSnapshot('s1', FULL_SNAPSHOT)
+ const first = $sessionControlBySession.get().s1
+
+ applySessionControlSnapshot('s1', { ...FULL_SNAPSHOT })
+ const second = $sessionControlBySession.get().s1
+
+ expect(second).toBe(first)
+ expect(second!.snapshot).toBe(first!.snapshot)
+ })
+
+ it('creates foreground loading state and leaves background hydration visually quiet', async () => {
+ const first = deferred<unknown>()
+ const request = vi.fn(() => first.promise)
+ useGateway(request)
+
+ const foreground = refreshSessionControl('s1')
+ expect($sessionControlBySession.get().s1).toMatchObject({
+ capability: 'unknown',
+ error: null,
+ loading: true,
+ pendingAction: null
+ })
+ first.resolve({ control: FULL_SNAPSHOT })
+ await foreground
+
+ const second = deferred<unknown>()
+ request.mockImplementationOnce(() => second.promise)
+ const background = refreshSessionControl('s1', { background: true })
+
+ expect($sessionControlBySession.get().s1).toMatchObject({ capability: 'supported', loading: false })
+ second.resolve({ control: { ...FULL_SNAPSHOT, revision: 'background-revision' } })
+ await background
+ })
+
+ it('falls back once on the unsupported transition and suppresses future compatibility retries', async () => {
+ const request = vi.fn(async () => {
+ throw new JsonRpcGatewayError('method not found', { code: -32601 })
+ })
+
+ useGateway(request)
+
+ await refreshSessionControl('s1')
+ await refreshSessionControl('s1')
+
+ expect($sessionControlBySession.get().s1).toMatchObject({
+ capability: 'unsupported',
+ loading: false,
+ snapshot: null
+ })
+ expect(refreshLegacyGoal).toHaveBeenCalledTimes(1)
+ expect(refreshLegacyGoal).toHaveBeenCalledWith('s1')
+ expect(request).toHaveBeenCalledTimes(1)
+ })
+
+ it('lets a precise gateway-rebind seam make an unsupported session probeable again', async () => {
+ useGateway(
+ vi.fn(async () => {
+ throw new JsonRpcGatewayError('method not found', { code: -32601 })
+ })
+ )
+ await refreshSessionControl('s1')
+
+ resetSessionControlAfterGatewayRebind()
+ expect($sessionControlBySession.get().s1).toMatchObject({ capability: 'unknown', loading: false })
+
+ const request = vi.fn(async () => ({ control: FULL_SNAPSHOT }))
+ useGateway(request)
+ await refreshSessionControl('s1')
+ expect(request).toHaveBeenCalledTimes(1)
+ expect($sessionControlBySession.get().s1!.capability).toBe('supported')
+ })
+
+ it('retains the last good snapshot and reports a bounded ordinary read error', async () => {
+ applySessionControlSnapshot('s1', FULL_SNAPSHOT)
+ const message = 'x'.repeat(500)
+ useGateway(
+ vi.fn(async () => {
+ throw new Error(message)
+ })
+ )
+
+ await expect(refreshSessionControl('s1', { background: true })).resolves.toBeDefined()
+
+ const entry = $sessionControlBySession.get().s1!
+ expect(entry.snapshot!.revision).toBe(FULL_SNAPSHOT.revision)
+ expect(entry.capability).toBe('supported')
+ expect(entry.error).toHaveLength(240)
+ expect(entry.loading).toBe(false)
+ })
+
+ it('marks a session gone without publishing an ordinary hydration error', async () => {
+ useGateway(
+ vi.fn(async () => {
+ throw new JsonRpcGatewayError('session not found', { code: 4001 })
+ })
+ )
+
+ await refreshSessionControl('gone')
+ expect($sessionControlBySession.get().gone).toMatchObject({ error: null, loading: false })
+ })
+
+ it('rejects a session-gone action truthfully while clearing only its pending state', async () => {
+ applySessionControlSnapshot('s1', FULL_SNAPSHOT)
+ useGateway(
+ vi.fn(async () => {
+ throw new JsonRpcGatewayError('session not found', { code: 4001 })
+ })
+ )
+
+ await expect(runSessionControlAction('s1', 'goal.pause')).rejects.toThrow('session not found')
+ expect($sessionControlBySession.get().s1).toMatchObject({ error: null, pendingAction: null })
+ expect($sessionControlBySession.get().s1!.snapshot!.revision).toBe(FULL_SNAPSHOT.revision)
+ })
+
+ it('makes an event-first session supported and leaves malformed events as a no-op', () => {
+ applySessionControlUpdate('s1', FULL_SNAPSHOT)
+ const first = $sessionControlBySession.get().s1
+
+ applySessionControlUpdate('s1', { ...FULL_SNAPSHOT, loop: { ...FULL_SNAPSHOT.loop!, mode: 'fixed' } })
+
+ expect(first).toMatchObject({ capability: 'supported', pendingAction: null })
+ expect($sessionControlBySession.get().s1).toBe(first)
+ })
+
+ it('submits only the requested action and exposes its pending state on that session', async () => {
+ const response = deferred<unknown>()
+ const request = vi.fn(() => response.promise)
+ useGateway(request)
+
+ const action = runSessionControlAction('s1', 'subgoal.add', { text: 'verify hydration' })
+ expect($sessionControlBySession.get().s1).toMatchObject({
+ capability: 'unknown',
+ loading: false,
+ pendingAction: 'subgoal.add'
+ })
+ expect($sessionControlBySession.get().s2).toBeUndefined()
+ expect(request).toHaveBeenCalledWith('session.control', {
+ action: 'subgoal.add',
+ args: { text: 'verify hydration' },
+ session_id: 's1'
+ })
+
+ response.resolve({
+ control: { ...FULL_SNAPSHOT, revision: 'action-revision' },
+ dispatch: { display: null, message: null, notice: null, output: 'added', type: 'exec' }
+ })
+
+ await expect(action).resolves.toEqual({ display: null, message: null, notice: null, output: 'added', type: 'exec' })
+ expect($sessionControlBySession.get().s1).toMatchObject({
+ capability: 'supported',
+ error: null,
+ pendingAction: null
+ })
+ })
+
+ it('rejects a failed action truthfully while retaining the good snapshot and clearing its pending state', async () => {
+ applySessionControlSnapshot('s1', FULL_SNAPSHOT)
+ useGateway(
+ vi.fn(async () => {
+ throw new Error('backend unavailable')
+ })
+ )
+
+ await expect(runSessionControlAction('s1', 'goal.pause')).rejects.toThrow('backend unavailable')
+
+ expect($sessionControlBySession.get().s1).toMatchObject({ error: 'backend unavailable', pendingAction: null })
+ expect($sessionControlBySession.get().s1!.snapshot!.revision).toBe(FULL_SNAPSHOT.revision)
+ })
+
+ it('rejects malformed action data without promoting an unknown capability', async () => {
+ useGateway(
+ vi.fn(async () => ({
+ control: FULL_SNAPSHOT,
+ dispatch: { display: null, message: null, notice: null, output: null, type: 'unknown' }
+ }))
+ )
+
+ await expect(runSessionControlAction('s1', 'goal.pause')).rejects.toThrow('Invalid session.control action response')
+ expect($sessionControlBySession.get().s1).toMatchObject({
+ capability: 'unknown',
+ pendingAction: null,
+ snapshot: null
+ })
+ })
+
+ it('does not let a late read overwrite a newer event', async () => {
+ const slow = deferred<unknown>()
+ useGateway(vi.fn(() => slow.promise))
+
+ const read = refreshSessionControl('s1')
+ applySessionControlUpdate('s1', { ...FULL_SNAPSHOT, revision: 'event-newer' })
+ slow.resolve({ control: { ...FULL_SNAPSHOT, revision: 'read-stale' } })
+ await read
+
+ expect($sessionControlBySession.get().s1!.snapshot!.revision).toBe('event-newer')
+ })
+
+ it('does not let a late read overwrite a newer action response', async () => {
+ const slow = deferred<unknown>()
+
+ const request = vi
+ .fn()
+ .mockImplementationOnce(() => slow.promise)
+ .mockResolvedValueOnce({
+ control: { ...FULL_SNAPSHOT, revision: 'action-newer' },
+ dispatch: { display: null, message: null, notice: null, output: 'paused', type: 'exec' }
+ })
+
+ useGateway(request)
+
+ const read = refreshSessionControl('s1')
+ await runSessionControlAction('s1', 'goal.pause')
+ slow.resolve({ control: { ...FULL_SNAPSHOT, revision: 'read-stale' } })
+ await read
+
+ expect($sessionControlBySession.get().s1!.snapshot!.revision).toBe('action-newer')
+ })
+
+ it('does not let a late read repopulate a cleared session', async () => {
+ const slow = deferred<unknown>()
+ useGateway(vi.fn(() => slow.promise))
+
+ const read = refreshSessionControl('s1')
+ clearSessionControl('s1')
+ slow.resolve({ control: FULL_SNAPSHOT })
+ await read
+
+ expect($sessionControlBySession.get().s1).toBeUndefined()
+ })
+
+ it('does not let an older read overwrite a newer read', async () => {
+ const slow = deferred<unknown>()
+ const fast = deferred<unknown>()
+
+ const request = vi
+ .fn()
+ .mockImplementationOnce(() => slow.promise)
+ .mockImplementationOnce(() => fast.promise)
+
+ useGateway(request)
+
+ const older = refreshSessionControl('s1')
+ const newer = refreshSessionControl('s1')
+ fast.resolve({ control: { ...FULL_SNAPSHOT, revision: 'newer-read' } })
+ await newer
+ slow.resolve({ control: { ...FULL_SNAPSHOT, revision: 'older-read' } })
+ await older
+
+ expect($sessionControlBySession.get().s1!.snapshot!.revision).toBe('newer-read')
+ })
+
+ it('does not let a late post-turn refresh overwrite a newer event', async () => {
+ applySessionControlSnapshot('s1', FULL_SNAPSHOT)
+ const slow = deferred<unknown>()
+ useGateway(vi.fn(() => slow.promise))
+
+ const refresh = refreshSupportedSessionControlAfterTurn('s1')
+ applySessionControlUpdate('s1', { ...FULL_SNAPSHOT, revision: 'event-newer' })
+ slow.resolve({ control: { ...FULL_SNAPSHOT, revision: 'post-turn-stale' } })
+ await refresh
+
+ expect($sessionControlBySession.get().s1!.snapshot!.revision).toBe('event-newer')
+ })
+
+ it('skips post-turn refreshes until the session is known to support the control RPC', async () => {
+ const request = vi.fn(async () => ({ control: FULL_SNAPSHOT }))
+ useGateway(request)
+
+ await refreshSupportedSessionControlAfterTurn('unknown')
+ expect(request).not.toHaveBeenCalled()
+
+ applySessionControlUpdate('unsupported', FULL_SNAPSHOT)
+ useGateway(
+ vi.fn(async () => {
+ throw new JsonRpcGatewayError('method not found', { code: -32601 })
+ })
+ )
+ await refreshSessionControl('unsupported')
+
+ const unsupportedRequest = vi.fn(async () => ({ control: FULL_SNAPSHOT }))
+ useGateway(unsupportedRequest)
+ await refreshSupportedSessionControlAfterTurn('unsupported')
+ expect(unsupportedRequest).not.toHaveBeenCalled()
+ })
+
+ it('returns a valid stale action dispatch without letting it overwrite a newer event', async () => {
+ const slow = deferred<unknown>()
+ useGateway(vi.fn(() => slow.promise))
+
+ const action = runSessionControlAction('s1', 'goal.pause')
+ applySessionControlUpdate('s1', { ...FULL_SNAPSHOT, revision: 'event-newer' })
+ slow.resolve({
+ control: { ...FULL_SNAPSHOT, revision: 'action-stale' },
+ dispatch: { display: null, message: null, notice: null, output: 'paused', type: 'exec' }
+ })
+
+ await expect(action).resolves.toMatchObject({ output: 'paused', type: 'exec' })
+ expect($sessionControlBySession.get().s1!.snapshot!.revision).toBe('event-newer')
+ })
+
+ it('does not schedule a timer or poller while hydrating or dispatching control state', async () => {
+ const setIntervalSpy = vi.spyOn(globalThis, 'setInterval')
+ const setTimeoutSpy = vi.spyOn(globalThis, 'setTimeout')
+ useGateway(
+ vi.fn(async method =>
+ method === 'session.control.read'
+ ? { control: FULL_SNAPSHOT }
+ : {
+ control: FULL_SNAPSHOT,
+ dispatch: { display: null, message: null, notice: null, output: null, type: 'exec' }
+ }
+ )
+ )
+
+ await refreshSessionControl('s1')
+ await runSessionControlAction('s1', 'goal.pause')
+ await refreshSupportedSessionControlAfterTurn('s1')
+
+ expect(setIntervalSpy).not.toHaveBeenCalled()
+ expect(setTimeoutSpy).not.toHaveBeenCalled()
+ })
+})
diff --git a/apps/desktop/src/store/session-control.ts b/apps/desktop/src/store/session-control.ts
new file mode 100644
index 00000000000..9e474300901
--- /dev/null
+++ b/apps/desktop/src/store/session-control.ts
@@ -0,0 +1,838 @@
+import { atom } from 'nanostores'
+
+import { $gateway } from './gateway'
+import { refreshSessionGoal } from './goals'
+import { isSessionGone, isSessionGoneForBackgroundPolling, markSessionGone } from './runtime-gone'
+import { ambientRequestFor } from './session-gone-latch'
+import { requestForOwnedSession } from './session-states'
+
+export type SessionControlGoalStatus = 'active' | 'done' | 'paused'
+export type SessionControlLoopMode = 'interval' | 'self_paced'
+export type SessionControlLoopStatus = 'active' | 'done' | 'paused'
+export type SessionControlHeartbeatStatus = 'active' | 'paused'
+
+export interface SessionControlGoalContract {
+ boundaries: string
+ constraints: string
+ outcome: string
+ stop_when: string
+ verification: string
+}
+
+export interface SessionControlGate {
+ attempts: number
+ command: string
+ last_exit_code: number | null
+ max_retries: number
+ timeout_seconds: number
+}
+
+export type SessionControlWaitBarrier =
+ | { reason: string; type: 'until'; until_at: number }
+ | { reason: string; target: string; type: 'session' }
+ | { reason: string; target: number; type: 'pid' }
+
+export interface SessionControlGoal {
+ contract: SessionControlGoalContract
+ gates: SessionControlGate[]
+ last_reason?: string
+ last_verdict?: 'blocked' | 'continue' | 'done' | 'skipped' | 'wait'
+ max_turns: number
+ paused_reason?: string
+ status: SessionControlGoalStatus
+ subgoals: string[]
+ title: string
+ turns_used: number
+ updated_at?: number
+ wait_barrier?: SessionControlWaitBarrier
+ created_at?: number
+}
+
+export interface SessionControlLoop {
+ awaiting_response: boolean
+ created_at: number
+ current_delay: number
+ deferred_by_goal: boolean
+ interval_seconds: number
+ last_fired_at: number
+ last_stop_reason?: string
+ max_ticks: number
+ mode: SessionControlLoopMode
+ next_due_at: number
+ paused_reason?: string
+ prompt: string
+ status: SessionControlLoopStatus
+ ticks_fired: number
+ times: number
+ until: string
+}
+
+export interface SessionControlHeartbeat {
+ created_at: number
+ fire_count: number
+ interval_seconds: number
+ last_fired_at: number
+ prompt: string
+ status: SessionControlHeartbeatStatus
+}
+
+export interface SessionControlSnapshot {
+ goal: SessionControlGoal | null
+ heartbeat: SessionControlHeartbeat | null
+ loop: SessionControlLoop | null
+ revision: string
+ updated_at: number
+}
+
+export type SessionControlAction =
+ | 'goal.clear'
+ | 'goal.pause'
+ | 'goal.resume'
+ | 'goal.unwait'
+ | 'heartbeat.clear'
+ | 'heartbeat.pause'
+ | 'heartbeat.resume'
+ | 'loop.pause'
+ | 'loop.resume'
+ | 'loop.stop'
+ | 'subgoal.add'
+ | 'subgoal.clear'
+ | 'subgoal.remove'
+
+export type SessionControlActionArgs = { index: number } | { text: string }
+
+export interface SessionControlDispatch {
+ display: string | null
+ message: string | null
+ notice: string | null
+ output: string | null
+ type: 'exec' | 'send'
+}
+
+export interface SessionControlEntry {
+ capability: 'unknown' | 'supported' | 'unsupported'
+ error: string | null
+ loading: boolean
+ pendingAction: SessionControlAction | null
+ snapshot: SessionControlSnapshot | null
+}
+
+interface RefreshOptions {
+ background?: boolean
+}
+
+type UnknownRecord = Record<string, unknown>
+
+const GOAL_STATUSES = new Set<SessionControlGoalStatus>(['active', 'done', 'paused'])
+
+const GOAL_VERDICTS = new Set<NonNullable<SessionControlGoal['last_verdict']>>([
+ 'blocked',
+ 'continue',
+ 'done',
+ 'skipped',
+ 'wait'
+])
+
+const LOOP_MODES = new Set<SessionControlLoopMode>(['interval', 'self_paced'])
+const LOOP_STATUSES = new Set<SessionControlLoopStatus>(['active', 'done', 'paused'])
+const HEARTBEAT_STATUSES = new Set<SessionControlHeartbeatStatus>(['active', 'paused'])
+const DISPATCH_TYPES = new Set<SessionControlDispatch['type']>(['exec', 'send'])
+const ERROR_LIMIT = 240
+
+const versions = new Map<string, number>()
+
+export const $sessionControlBySession = atom<Record<string, SessionControlEntry>>({})
+
+function isRecord(value: unknown): value is UnknownRecord {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+}
+
+function hasOwn(value: UnknownRecord, key: string): boolean {
+ return Object.prototype.hasOwnProperty.call(value, key)
+}
+
+function hasExactFields(value: UnknownRecord, required: string[], optional: string[] = []): boolean {
+ const allowed = new Set([...required, ...optional])
+
+ return required.every(key => hasOwn(value, key)) && Object.keys(value).every(key => allowed.has(key))
+}
+
+function isFiniteNumber(value: unknown): value is number {
+ return typeof value === 'number' && Number.isFinite(value)
+}
+
+function isInteger(value: unknown): value is number {
+ return Number.isInteger(value)
+}
+
+function hasOptionalStrings(value: UnknownRecord, keys: string[]): boolean {
+ return keys.every(key => !hasOwn(value, key) || typeof value[key] === 'string')
+}
+
+function parseGoalContract(value: unknown): SessionControlGoalContract | null {
+ if (
+ !isRecord(value) ||
+ !hasExactFields(value, ['outcome', 'verification', 'constraints', 'boundaries', 'stop_when'])
+ ) {
+ return null
+ }
+
+ if (
+ typeof value.outcome !== 'string' ||
+ typeof value.verification !== 'string' ||
+ typeof value.constraints !== 'string' ||
+ typeof value.boundaries !== 'string' ||
+ typeof value.stop_when !== 'string'
+ ) {
+ return null
+ }
+
+ return {
+ boundaries: value.boundaries,
+ constraints: value.constraints,
+ outcome: value.outcome,
+ stop_when: value.stop_when,
+ verification: value.verification
+ }
+}
+
+function parseGate(value: unknown): SessionControlGate | null {
+ if (
+ !isRecord(value) ||
+ !hasExactFields(value, ['command', 'timeout_seconds', 'max_retries', 'attempts', 'last_exit_code'])
+ ) {
+ return null
+ }
+
+ if (
+ typeof value.command !== 'string' ||
+ !isInteger(value.timeout_seconds) ||
+ !isInteger(value.max_retries) ||
+ !isInteger(value.attempts) ||
+ (value.last_exit_code !== null && !isInteger(value.last_exit_code))
+ ) {
+ return null
+ }
+
+ return {
+ attempts: value.attempts,
+ command: value.command,
+ last_exit_code: value.last_exit_code,
+ max_retries: value.max_retries,
+ timeout_seconds: value.timeout_seconds
+ }
+}
+
+function parseWaitBarrier(value: unknown): SessionControlWaitBarrier | null {
+ if (!isRecord(value) || typeof value.type !== 'string') {
+ return null
+ }
+
+ if (value.type === 'until') {
+ if (
+ !hasExactFields(value, ['type', 'until_at', 'reason']) ||
+ !isFiniteNumber(value.until_at) ||
+ typeof value.reason !== 'string'
+ ) {
+ return null
+ }
+
+ return { reason: value.reason, type: 'until', until_at: value.until_at }
+ }
+
+ if (value.type === 'session') {
+ if (
+ !hasExactFields(value, ['type', 'target', 'reason']) ||
+ typeof value.target !== 'string' ||
+ typeof value.reason !== 'string'
+ ) {
+ return null
+ }
+
+ return { reason: value.reason, target: value.target, type: 'session' }
+ }
+
+ if (value.type === 'pid') {
+ if (
+ !hasExactFields(value, ['type', 'target', 'reason']) ||
+ !isInteger(value.target) ||
+ typeof value.reason !== 'string'
+ ) {
+ return null
+ }
+
+ return { reason: value.reason, target: value.target, type: 'pid' }
+ }
+
+ return null
+}
+
+function parseGoal(value: unknown): SessionControlGoal | null {
+ const required = ['title', 'status', 'turns_used', 'max_turns', 'contract', 'subgoals', 'gates']
+ const optional = ['created_at', 'updated_at', 'paused_reason', 'last_verdict', 'last_reason', 'wait_barrier']
+
+ if (!isRecord(value) || !hasExactFields(value, required, optional)) {
+ return null
+ }
+
+ if (
+ typeof value.title !== 'string' ||
+ typeof value.status !== 'string' ||
+ !GOAL_STATUSES.has(value.status as SessionControlGoalStatus) ||
+ !isInteger(value.turns_used) ||
+ !isInteger(value.max_turns) ||
+ !Array.isArray(value.subgoals) ||
+ !value.subgoals.every(subgoal => typeof subgoal === 'string') ||
+ !Array.isArray(value.gates) ||
+ !hasOptionalStrings(value, ['paused_reason', 'last_reason']) ||
+ (hasOwn(value, 'created_at') && !isFiniteNumber(value.created_at)) ||
+ (hasOwn(value, 'updated_at') && !isFiniteNumber(value.updated_at)) ||
+ (hasOwn(value, 'last_verdict') &&
+ (typeof value.last_verdict !== 'string' ||
+ !GOAL_VERDICTS.has(value.last_verdict as NonNullable<SessionControlGoal['last_verdict']>)))
+ ) {
+ return null
+ }
+
+ const contract = parseGoalContract(value.contract)
+ const parsedGates = value.gates.map(parseGate)
+ const waitBarrier = hasOwn(value, 'wait_barrier') ? parseWaitBarrier(value.wait_barrier) : undefined
+
+ if (!contract || parsedGates.some(gate => gate === null) || (hasOwn(value, 'wait_barrier') && !waitBarrier)) {
+ return null
+ }
+
+ const gates = parsedGates.filter((gate): gate is SessionControlGate => gate !== null)
+
+ const goal: SessionControlGoal = {
+ contract,
+ gates,
+ max_turns: value.max_turns,
+ status: value.status as SessionControlGoalStatus,
+ subgoals: [...value.subgoals],
+ title: value.title,
+ turns_used: value.turns_used
+ }
+
+ if (hasOwn(value, 'created_at')) {
+ goal.created_at = value.created_at as number
+ }
+
+ if (hasOwn(value, 'updated_at')) {
+ goal.updated_at = value.updated_at as number
+ }
+
+ if (hasOwn(value, 'paused_reason')) {
+ goal.paused_reason = value.paused_reason as string
+ }
+
+ if (hasOwn(value, 'last_reason')) {
+ goal.last_reason = value.last_reason as string
+ }
+
+ if (hasOwn(value, 'last_verdict')) {
+ goal.last_verdict = value.last_verdict as SessionControlGoal['last_verdict']
+ }
+
+ if (waitBarrier) {
+ goal.wait_barrier = waitBarrier
+ }
+
+ return goal
+}
+
+function parseLoop(value: unknown): SessionControlLoop | null {
+ const required = [
+ 'prompt',
+ 'status',
+ 'mode',
+ 'interval_seconds',
+ 'current_delay',
+ 'times',
+ 'until',
+ 'max_ticks',
+ 'ticks_fired',
+ 'created_at',
+ 'last_fired_at',
+ 'next_due_at',
+ 'awaiting_response',
+ 'deferred_by_goal'
+ ]
+
+ if (!isRecord(value) || !hasExactFields(value, required, ['paused_reason', 'last_stop_reason'])) {
+ return null
+ }
+
+ if (
+ typeof value.prompt !== 'string' ||
+ typeof value.status !== 'string' ||
+ !LOOP_STATUSES.has(value.status as SessionControlLoopStatus) ||
+ typeof value.mode !== 'string' ||
+ !LOOP_MODES.has(value.mode as SessionControlLoopMode) ||
+ !isFiniteNumber(value.interval_seconds) ||
+ !isFiniteNumber(value.current_delay) ||
+ !isInteger(value.times) ||
+ typeof value.until !== 'string' ||
+ !isInteger(value.max_ticks) ||
+ !isInteger(value.ticks_fired) ||
+ !isFiniteNumber(value.created_at) ||
+ !isFiniteNumber(value.last_fired_at) ||
+ !isFiniteNumber(value.next_due_at) ||
+ typeof value.awaiting_response !== 'boolean' ||
+ typeof value.deferred_by_goal !== 'boolean' ||
+ !hasOptionalStrings(value, ['paused_reason', 'last_stop_reason'])
+ ) {
+ return null
+ }
+
+ const loop: SessionControlLoop = {
+ awaiting_response: value.awaiting_response,
+ created_at: value.created_at,
+ current_delay: value.current_delay,
+ deferred_by_goal: value.deferred_by_goal,
+ interval_seconds: value.interval_seconds,
+ last_fired_at: value.last_fired_at,
+ max_ticks: value.max_ticks,
+ mode: value.mode as SessionControlLoopMode,
+ next_due_at: value.next_due_at,
+ prompt: value.prompt,
+ status: value.status as SessionControlLoopStatus,
+ ticks_fired: value.ticks_fired,
+ times: value.times,
+ until: value.until
+ }
+
+ if (hasOwn(value, 'paused_reason')) {
+ loop.paused_reason = value.paused_reason as string
+ }
+
+ if (hasOwn(value, 'last_stop_reason')) {
+ loop.last_stop_reason = value.last_stop_reason as string
+ }
+
+ return loop
+}
+
+function parseHeartbeat(value: unknown): SessionControlHeartbeat | null {
+ const required = ['prompt', 'status', 'interval_seconds', 'created_at', 'last_fired_at', 'fire_count']
+
+ if (!isRecord(value) || !hasExactFields(value, required)) {
+ return null
+ }
+
+ if (
+ typeof value.prompt !== 'string' ||
+ typeof value.status !== 'string' ||
+ !HEARTBEAT_STATUSES.has(value.status as SessionControlHeartbeatStatus) ||
+ !isInteger(value.interval_seconds) ||
+ !isFiniteNumber(value.created_at) ||
+ !isFiniteNumber(value.last_fired_at) ||
+ !isInteger(value.fire_count)
+ ) {
+ return null
+ }
+
+ return {
+ created_at: value.created_at,
+ fire_count: value.fire_count,
+ interval_seconds: value.interval_seconds,
+ last_fired_at: value.last_fired_at,
+ prompt: value.prompt,
+ status: value.status as SessionControlHeartbeatStatus
+ }
+}
+
+/** Parses the stable allowlisted backend shape into fresh renderer-owned data. */
+export function parseSessionControlSnapshot(value: unknown): SessionControlSnapshot | null {
+ if (!isRecord(value) || !hasExactFields(value, ['goal', 'loop', 'heartbeat', 'revision', 'updated_at'])) {
+ return null
+ }
+
+ if (typeof value.revision !== 'string' || !isFiniteNumber(value.updated_at)) {
+ return null
+ }
+
+ const goal = value.goal === null ? null : parseGoal(value.goal)
+ const loop = value.loop === null ? null : parseLoop(value.loop)
+ const heartbeat = value.heartbeat === null ? null : parseHeartbeat(value.heartbeat)
+
+ if ((value.goal !== null && !goal) || (value.loop !== null && !loop) || (value.heartbeat !== null && !heartbeat)) {
+ return null
+ }
+
+ return { goal, heartbeat, loop, revision: value.revision, updated_at: value.updated_at }
+}
+
+function parseSessionControlDispatch(value: unknown): SessionControlDispatch | null {
+ if (!isRecord(value) || !hasExactFields(value, ['type', 'output', 'notice', 'message', 'display'])) {
+ return null
+ }
+
+ if (
+ typeof value.type !== 'string' ||
+ !DISPATCH_TYPES.has(value.type as SessionControlDispatch['type']) ||
+ ![value.output, value.notice, value.message, value.display].every(
+ field => field === null || typeof field === 'string'
+ )
+ ) {
+ return null
+ }
+
+ return {
+ display: value.display as string | null,
+ message: value.message as string | null,
+ notice: value.notice as string | null,
+ output: value.output as string | null,
+ type: value.type as SessionControlDispatch['type']
+ }
+}
+
+function emptyEntry(): SessionControlEntry {
+ return { capability: 'unknown', error: null, loading: false, pendingAction: null, snapshot: null }
+}
+
+function currentVersion(sessionId: string): number {
+ return versions.get(sessionId) ?? 0
+}
+
+function advanceVersion(sessionId: string): number {
+ const next = currentVersion(sessionId) + 1
+ versions.set(sessionId, next)
+
+ return next
+}
+
+function isCurrent(sessionId: string, token: number): boolean {
+ return currentVersion(sessionId) === token
+}
+
+function sameEntry(first: SessionControlEntry, second: SessionControlEntry): boolean {
+ return (
+ first.capability === second.capability &&
+ first.error === second.error &&
+ first.loading === second.loading &&
+ first.pendingAction === second.pendingAction &&
+ first.snapshot === second.snapshot
+ )
+}
+
+function publishEntry(sessionId: string, next: SessionControlEntry): SessionControlEntry {
+ const entries = $sessionControlBySession.get()
+ const current = entries[sessionId]
+
+ if (current && sameEntry(current, next)) {
+ return current
+ }
+
+ $sessionControlBySession.set({ ...entries, [sessionId]: next })
+
+ return next
+}
+
+function applyParsedSnapshot(sessionId: string, snapshot: SessionControlSnapshot): SessionControlEntry {
+ advanceVersion(sessionId)
+ const current = $sessionControlBySession.get()[sessionId] ?? emptyEntry()
+ const nextSnapshot = current.snapshot?.revision === snapshot.revision ? current.snapshot : snapshot
+
+ return publishEntry(sessionId, {
+ capability: 'supported',
+ error: null,
+ loading: false,
+ pendingAction: null,
+ snapshot: nextSnapshot
+ })
+}
+
+/** Applies a valid read/action snapshot and marks its session as supported. */
+export function applySessionControlSnapshot(sessionId: string, rawSnapshot: unknown): SessionControlEntry | undefined {
+ if (!sessionId) {
+ return undefined
+ }
+
+ const snapshot = parseSessionControlSnapshot(rawSnapshot)
+
+ return snapshot ? applyParsedSnapshot(sessionId, snapshot) : undefined
+}
+
+/** Applies an event update; invalid updates are deliberately a claimed no-op. */
+export function applySessionControlUpdate(sessionId: string, rawSnapshot: unknown): SessionControlEntry | undefined {
+ return applySessionControlSnapshot(sessionId, rawSnapshot)
+}
+
+export function clearSessionControl(sessionId: string): void {
+ if (!sessionId) {
+ return
+ }
+
+ advanceVersion(sessionId)
+ const entries = $sessionControlBySession.get()
+
+ if (!(sessionId in entries)) {
+ return
+ }
+
+ const { [sessionId]: _removed, ...remaining } = entries
+ $sessionControlBySession.set(remaining)
+}
+
+/** Lets an explicitly rebound gateway probe backends that were unsupported on its predecessor. */
+export function resetSessionControlAfterGatewayRebind(): void {
+ const entries = $sessionControlBySession.get()
+ let changed = false
+ const nextEntries: Record<string, SessionControlEntry> = {}
+
+ for (const [sessionId, entry] of Object.entries(entries)) {
+ advanceVersion(sessionId)
+
+ if (entry.capability === 'unsupported') {
+ nextEntries[sessionId] = { ...entry, capability: 'unknown', error: null, loading: false, pendingAction: null }
+ changed = true
+ } else {
+ nextEntries[sessionId] = entry
+ }
+ }
+
+ if (changed) {
+ $sessionControlBySession.set(nextEntries)
+ }
+}
+
+/** Narrow reset seam for tests; production reconnect behavior remains explicitly owned by its caller. */
+export function resetSessionControlForTests(): void {
+ for (const sessionId of new Set([...versions.keys(), ...Object.keys($sessionControlBySession.get())])) {
+ advanceVersion(sessionId)
+ }
+
+ $sessionControlBySession.set({})
+ versions.clear()
+}
+
+function beginRead(sessionId: string, background: boolean): number {
+ const token = advanceVersion(sessionId)
+ const current = $sessionControlBySession.get()[sessionId] ?? emptyEntry()
+
+ publishEntry(sessionId, {
+ ...current,
+ error: null,
+ loading: background ? current.loading : true
+ })
+
+ return token
+}
+
+function beginAction(sessionId: string, action: SessionControlAction): number {
+ const token = advanceVersion(sessionId)
+ const current = $sessionControlBySession.get()[sessionId] ?? emptyEntry()
+
+ publishEntry(sessionId, {
+ ...current,
+ error: null,
+ loading: false,
+ pendingAction: action
+ })
+
+ return token
+}
+
+function boundedError(error: unknown): string {
+ const message =
+ error instanceof Error
+ ? error.message
+ : isRecord(error) && typeof error.message === 'string'
+ ? error.message
+ : 'Session control request failed'
+
+ return message.trim().slice(0, ERROR_LIMIT) || 'Session control request failed'
+}
+
+function publishFailure(sessionId: string, token: number, error: unknown, clearPendingAction: boolean): void {
+ if (!isCurrent(sessionId, token)) {
+ return
+ }
+
+ const current = $sessionControlBySession.get()[sessionId] ?? emptyEntry()
+ publishEntry(sessionId, {
+ ...current,
+ error: boundedError(error),
+ loading: false,
+ pendingAction: clearPendingAction ? null : current.pendingAction
+ })
+}
+
+function finishGoneRequest(sessionId: string, token: number, clearPendingAction: boolean): void {
+ if (!isCurrent(sessionId, token)) {
+ return
+ }
+
+ markSessionGone(sessionId)
+ const current = $sessionControlBySession.get()[sessionId] ?? emptyEntry()
+ publishEntry(sessionId, {
+ ...current,
+ loading: false,
+ pendingAction: clearPendingAction ? null : current.pendingAction
+ })
+}
+
+function markUnsupported(sessionId: string, token: number): boolean {
+ if (!isCurrent(sessionId, token)) {
+ return false
+ }
+
+ const current = $sessionControlBySession.get()[sessionId] ?? emptyEntry()
+
+ if (current.capability === 'unsupported') {
+ return false
+ }
+
+ advanceVersion(sessionId)
+ publishEntry(sessionId, {
+ ...current,
+ capability: 'unsupported',
+ error: null,
+ loading: false,
+ pendingAction: null
+ })
+
+ return true
+}
+
+function isMethodNotFound(error: unknown): boolean {
+ if (isRecord(error) && error.code === -32601) {
+ return true
+ }
+
+ const message =
+ error instanceof Error ? error.message : isRecord(error) && typeof error.message === 'string' ? error.message : ''
+
+ return message.toLowerCase().includes('method not found') || message.toLowerCase().includes('method-not-found')
+}
+
+/** Hydrates one session's structured controls; background refreshes never flash a loading state. */
+export async function refreshSessionControl(
+ sessionId: string,
+ options: RefreshOptions = {}
+): Promise<SessionControlEntry | undefined> {
+ const existing = $sessionControlBySession.get()[sessionId]
+
+ if (!sessionId || existing?.capability === 'unsupported' || isSessionGone(sessionId)) {
+ return existing
+ }
+
+ const gateway = $gateway.get()
+
+ if (!gateway) {
+ return existing
+ }
+
+ const token = beginRead(sessionId, Boolean(options.background))
+
+ try {
+ const response = await requestForOwnedSession<unknown>(
+ sessionId,
+ ambientRequestFor(gateway),
+ 'session.control.read',
+ { session_id: sessionId }
+ )
+
+ if (!isCurrent(sessionId, token)) {
+ return $sessionControlBySession.get()[sessionId]
+ }
+
+ const snapshot = isRecord(response) ? parseSessionControlSnapshot(response.control) : null
+
+ if (!snapshot) {
+ publishFailure(sessionId, token, new Error('Invalid session.control.read response'), false)
+
+ return $sessionControlBySession.get()[sessionId]
+ }
+
+ return applyParsedSnapshot(sessionId, snapshot)
+ } catch (error) {
+ if (!isCurrent(sessionId, token)) {
+ return $sessionControlBySession.get()[sessionId]
+ }
+
+ if (isMethodNotFound(error)) {
+ const transitioned = markUnsupported(sessionId, token)
+
+ if (transitioned) {
+ await refreshSessionGoal(sessionId)
+ }
+
+ return $sessionControlBySession.get()[sessionId]
+ }
+
+ if (isSessionGoneForBackgroundPolling(error)) {
+ finishGoneRequest(sessionId, token, false)
+
+ return $sessionControlBySession.get()[sessionId]
+ }
+
+ publishFailure(sessionId, token, error, false)
+
+ return $sessionControlBySession.get()[sessionId]
+ }
+}
+
+/** Runs an allowlisted backend control action; callers own any composer/UI dispatch. */
+export async function runSessionControlAction(
+ sessionId: string,
+ action: SessionControlAction,
+ args?: SessionControlActionArgs
+): Promise<SessionControlDispatch> {
+ if (!sessionId) {
+ throw new Error('A session id is required for session control')
+ }
+
+ if (isSessionGone(sessionId)) {
+ throw new Error('Session not found')
+ }
+
+ const gateway = $gateway.get()
+
+ if (!gateway) {
+ throw new Error('Session control gateway is unavailable')
+ }
+
+ const token = beginAction(sessionId, action)
+
+ try {
+ const response = await requestForOwnedSession<unknown>(sessionId, ambientRequestFor(gateway), 'session.control', {
+ action,
+ args: args ?? {},
+ session_id: sessionId
+ })
+
+ const snapshot = isRecord(response) ? parseSessionControlSnapshot(response.control) : null
+ const dispatch = isRecord(response) ? parseSessionControlDispatch(response.dispatch) : null
+
+ if (!snapshot || !dispatch) {
+ const error = new Error('Invalid session.control action response')
+ publishFailure(sessionId, token, error, true)
+ throw error
+ }
+
+ if (isCurrent(sessionId, token)) {
+ applyParsedSnapshot(sessionId, snapshot)
+ }
+
+ return dispatch
+ } catch (error) {
+ if (isSessionGoneForBackgroundPolling(error)) {
+ finishGoneRequest(sessionId, token, true)
+ } else {
+ publishFailure(sessionId, token, error, true)
+ }
+
+ throw error
+ }
+}
+
+/** Refreshes only sessions already proven to support the structured-control RPC. */
+export async function refreshSupportedSessionControlAfterTurn(sessionId: string): Promise<void> {
+ if (!sessionId || $sessionControlBySession.get()[sessionId]?.capability !== 'supported') {
+ return
+ }
+
+ await refreshSessionControl(sessionId, { background: true })
+}