Agent status changes stop republishing the whole session graph (#42104)

* Remove finished-agent retention and keep sleeping status with panes

* Fix legacy pane projection and sleeping-agent regression fixtures

* Cover sleeping display-only status in parked terminal coverage

* Keep pane conversation identity only across continuous agent observations

* Remove duplicate import and keep sleep fixtures type checked

* Preserve conversation boundaries across replays and inherited clocks

* Cover conversation map stability across a large status batch

* Bound conversation capacity work to changed pane owners

* Pass capacity classifiers their layout input directly

* Finalize conversation provenance once per status batch

* Keep paired snapshot tests focused on observable outcomes

* Type the conversation provenance test fixtures explicitly

* Consolidate agent session imports after main merge

* Preserve provider replacement evidence when resetting conversation continuity

* Separate retention deletion from sleeping agent display

* Restore migration row bucket comparison

* Skip unusable pane identities before title ownership lookups

* Refresh conversation titles when their owning pane changes

* Update completion test sound mock after module move

* Keep finished agent status with sleeping panes and update agents by key

* Forward sleeping pane status and scope paired tab updates

* Preserve keyed selectors and compiler invalidation through final checks

* Keep bound store hooks visible to the compiler and measure published links

* Install provenance measurement before factory capture

* Use a static store hook and name presentation metadata once

* Preserve keyed freshness and atomic agent status publication

* Preserve remote folder dashboard regression after suite retirement

* Model pane wake before live identity reobservation in regression

* Share keyed row transactions and finish main integration

* Align runtime fixtures with keyed agent status reads

* Keep status projections addressed and activity summaries current

* Retire empty workspace status summaries after their source leaves

* Use the standard store fixture for parked terminal graph tests

* Align status fixtures with app types and a fixed test clock

* test: capture stored terminal render failure details

* Read terminal titles and completion prompts from keyed agent status

* Compose foreground agent state in worktree test stores

* test: complete lineage list agent state fixture

* Keep sleeping completion when retiring process authority

* Run durable agent-hook status tests with Node SQLite

* Preserve sleeping Done when renderer retires its process

* Update terminal fixtures for process retirement

* Spike addressed renderer agent status publication

* Join status only against admitted mobile membership

* Scope status membership reconciliation and observe bindings by key

* Cover status admission and scoped replica recovery

* Name the status replica runtime owner type

* Read sleeping pane resume sources by key

* Bind sleep capture fixture to its live panes

* Bound status replica retirement and recover interrupted publication

* Pass the pane tree to the sleep capture fixture graph

* fix(status): skip non-UUID leaves, release phone frames on headless restore, avoid unbound tree scan

- Graph status bindings and replica membership skip leaves that can't carry a status row instead of throwing.
- The pre-seed phone gate only holds frames for the renderer generation that owes the seed; restoring headless authority redelivers the held worktrees.
- Status capture skips the leaf count when the tab has no terminal, and counts saved leaves only up to two.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(status): release held phone frames whenever the unseeded renderer loses the graph

Desktop builds without a headless fallback mark the graph unavailable but keep the renderer generation, so the pre-seed gate stayed shut until a window reopened.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* perf(status): reuse the capped saved-leaf count per immutable layout

Status churn on an unmounted tab with only a tab-level terminal no longer descends a deep saved split tree on every change.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* Preserve accepted completion identity through sleep

* Pass a nullable title to the status classifier

* Resolve accepted host status once and preserve delivery order

* Drop published sleep status when its host owner retires

* Use the supported remote completion test envelope

* Preserve published activity when filling completed status

* Update imports for main module moves

* Remove an unreachable native chat owner comparison

* Read host and unread card inputs by address instead of per root

A host-scoped sidebar card re-read every root's row and acknowledgement on
any store write, so one card with many sleeping roots paid for other
workspaces' updates. Card host filtering, the summary pill's unread state
and the workspace unread gate now first compare the workspace's projected
row revision and the changed keys of the tab-keyed layout/PTY maps and
the acknowledgement record. Only an addressed change re-reads the roots.
Acknowledge and unacknowledge annotate their writes so readers can skip
keys they don't show.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* Correct sleeping pane test imports after module moves

* Combine duplicate subscription test imports

* Record addressed acknowledgement deletions on row drops

* Type subscription fixture key set for string readers

* Keep accepted updates complete after observer failures

* Seed the send picker with its SSH terminal identity

* Correct status publication imports after preload module move

* perf(layout): skip unused normalization reports in pane commands (#42615)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* Clarify cleanup pinning and ignored-file protection (#42616)

* test: remove 55 low-value suites and assertion driver (#42605)

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>

* fix(skills): skip Claude sync scratch folders during skill discovery (#42610)

Claude Code parks replaced skill copies in `.trash` and in-progress syncs
in `.staging` under its skills roots. Discovery walked into both, so each
synced skill showed up as duplicates. Prune those directory names in the
native file walk and in the generated WSL `find` command.

Co-authored-by: Neil <4138956+nwparker@users.noreply.github.com>

* test: remove 78 low-value suites and trim redundant cases (#42621)

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>

* Keep a host card's unchanged agent rows after filtering out another host's pane

Re-lineage clones every row once a host-scoped card filters a row out, so an unrelated pane's status write rebuilt the card's row array and re-ran its signal and rollup memos. Reuse unchanged rows as main's sidebar row selector does.

* Document the runtime stub cast in the status admission test

* Await graph publication in the phone projection status tests

* Share the renderer status binding check and move graph tab-id validation out of the window graph

Main's async graph publication grew session-window-graph past the 300-line limit; the binding predicate now has one owner beside its capture path.

* Seed the Copy Session ID shortcut test through keyed agent status

* Restore the reviewed status binding checks and move the remount check instead

Keeps the capture path's lookup behind its UUID and changed-worktree guards; the window graph stays under the line limit by moving the PTY remount check to the graph promotion base.

* Seed the graph payload partition test through keyed agent status

* fix(agent-status): retry status publication after a failed or superseded graph sync

An inactive sender now asks for a graph sync on each status change (base got this
retry from agentStatusEpoch in the sync key), and a superseded ack parks the sender
until the next accepted graph instead of stopping it.

* fix(agent-status): don't stage status changes while a snapshot is pending

A parked sender kept tombstones for every removed occupant; the next snapshot
recaptures every row and main clears its replica on snapshot.

* fix(agent-status): don't start renderer status publication in paired web clients

The web stub answers every batch with superseded; with superseded now re-arming
on each accepted graph, a web sender would resend snapshots and request graph
syncs for nothing.

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Jinjing <6427696+AmethystLiang@users.noreply.github.com>
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Co-authored-by: OrcaWin <alpha-eng@stably.ai>
Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
Co-authored-by: BingZ <zzb@gxsmjx.com>
Co-authored-by: Neil <4138956+nwparker@users.noreply.github.com>
(cherry picked from commit 47ef2ab264)
This commit is contained in:
Brennan Benson
2026-11-16 01:59:02 -05:00
committed by Jinwoo-H
parent 6317c00d1a
commit 409c31885c
45 changed files with 1863 additions and 175 deletions
+1
View File
@@ -23,6 +23,7 @@
"../src/cli/runtime/connection/runtime-pid-liveness.ts",
"../src/renderer/src/store/slices/worktrees/create/worktree-create-payload.ts",
"../src/renderer/src/runtime/repo-hooks/orca-hook-trust.ts",
"../src/renderer/src/runtime/agent-status/renderer-status-sender.ts",
"../src/renderer/src/components/browser-pane/navigate/browser-page-download-activity.ts",
"../src/renderer/src/components/browser-pane/host-guest/browser-guest-activity.ts",
"../src/renderer/src/components/browser-pane/host-guest/browser-guest-page-retention.ts",
@@ -0,0 +1,49 @@
import { beforeEach, expect, it, vi } from 'vitest'
const { handleMock, fromWebContentsMock } = vi.hoisted(() => ({
handleMock: vi.fn(),
fromWebContentsMock: vi.fn()
}))
vi.mock('electron', () => ({
BrowserWindow: {
fromWebContents: fromWebContentsMock
},
ipcMain: {
handle: handleMock,
on: vi.fn(),
removeAllListeners: vi.fn(),
removeHandler: vi.fn()
}
}))
import { registerRuntimeHandlers } from './runtime'
beforeEach(() => {
handleMock.mockReset()
fromWebContentsMock.mockReset()
})
it('admits status only from the current main frame without establishing graph authority', () => {
const runtime = { syncRendererAgentStatus: vi.fn().mockReturnValue({ accepted: true }) }
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the status channel calls only syncRendererAgentStatus on this runtime.
registerRuntimeHandlers(runtime as never)
const handler = handleMock.mock.calls.find(
([channel]) => channel === 'runtime:syncAgentStatus'
)![1]
const frame = { generation: 2 }
const sender = { mainFrame: frame }
const batch = { type: 'snapshot', epoch: 'renderer', seq: 1, rows: [] }
fromWebContentsMock.mockReturnValue({ id: 17 })
expect(handler({ sender, senderFrame: { generation: 1 } }, batch)).toEqual({
accepted: false,
reason: 'superseded'
})
expect(runtime.syncRendererAgentStatus).not.toHaveBeenCalled()
expect(handler({ sender, senderFrame: frame }, batch)).toEqual({ accepted: true })
expect(runtime.syncRendererAgentStatus).toHaveBeenCalledWith(17, batch)
fromWebContentsMock.mockReturnValue(null)
expect(handler({ sender, senderFrame: frame }, batch)).toEqual({
accepted: false,
reason: 'superseded'
})
})
+10
View File
@@ -1,3 +1,4 @@
import type { RendererStatusPublication } from '../../shared/agent-status/renderer-status-publication'
import { BrowserWindow, ipcMain } from 'electron'
import type { OrcaRuntimeService } from '../runtime/orca-runtime'
import type {
@@ -81,6 +82,15 @@ export function registerRuntimeHandlers(runtime: OrcaRuntimeService): void {
}
)
ipcMain.removeHandler('runtime:syncAgentStatus')
ipcMain.handle('runtime:syncAgentStatus', (event, batch: RendererStatusPublication) => {
const window = BrowserWindow.fromWebContents(event.sender)
if (!window || event.senderFrame !== event.sender.mainFrame) {
return { accepted: false, reason: 'superseded' }
}
return runtime.syncRendererAgentStatus(window.id, batch)
})
ipcMain.handle('runtime:getStatus', async (): Promise<RuntimeStatus> => {
// Match status.get's capped name wait; later reads pick up a lookup that is still running.
await runtime.machineNameReady()
@@ -0,0 +1,229 @@
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { RendererStatusSender } from '../../../renderer/src/runtime/agent-status/renderer-status-sender'
import type { RendererStatusPublication } from '../../../shared/agent-status/renderer-status-publication'
import type { RuntimeMobileSessionTabsResult } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts'
import { publishHeadlessRuntimeGraph } from './headless-runtime-graph'
vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: false }))
await import('../orca-runtime-tests/runtime-test-module-registration.spec')
const { electronMocks } = await import('../orca-runtime-test-mocks/setup.spec')
const { OrcaRuntimeService } = await import('../orca-runtime')
await import('../orca-runtime-tests/orca-runtime-test-lifecycle.spec')
const {
HEADLESS_LEAF_ID,
TEST_WORKTREE_ID,
makeRuntimeStoreWithWorkspaceSession,
makeWorkspaceSessionWithHeadlessTerminal
} = await import('../orca-runtime-tests/orca-runtime-test-fixtures.spec')
beforeEach(() => {
vi.useFakeTimers()
electronMocks.BrowserWindow.fromId.mockReturnValue({ isDestroyed: () => false })
})
afterEach(() => vi.useRealTimers())
it('publishes only the affected phone frame with increasing versions and excludes other publishers', async () => {
const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession(
makeWorkspaceSessionWithHeadlessTerminal()
)
const runtime = new OrcaRuntimeService(runtimeStore)
runtime.attachWindow(1)
const paneKey = `host-tab:${HEADLESS_LEAF_ID}`
const frames: RuntimeMobileSessionTabsResult[] = []
const stop = runtime.onMobileSessionTabsChanged(
(frame) => frames.push(frame),
undefined,
'mobile'
)
const publish = (version: number, title: string, epoch = 'renderer') =>
runtime.syncWindowGraph(1, {
rendererGeneration: epoch,
tabs: [],
leaves: [],
mobileSessionTabs: [
{
worktree: TEST_WORKTREE_ID,
publicationEpoch: epoch,
snapshotVersion: version,
activeGroupId: null,
activeTabId: null,
activeTabType: null,
tabs: [
{
type: 'terminal',
id: `host-tab::${HEADLESS_LEAF_ID}`,
parentTabId: 'host-tab',
leafId: HEADLESS_LEAF_ID,
ptyId: null,
title: 'Claude',
isActive: true,
statusSuppressionTitle: title
}
]
}
]
})
const status = {
paneKey,
leafId: HEADLESS_LEAF_ID,
rendererPtyId: null,
row: {
state: 'blocked' as const,
prompt: 'Approve the change',
agentType: 'claude',
paneKey,
updatedAt: Date.now(),
stateStartedAt: Date.now(),
stateHistory: []
}
}
try {
await publish(1, 'Claude')
await vi.advanceTimersByTimeAsync(100)
expect(frames).toEqual([])
expect(
runtime.syncRendererAgentStatus(2, {
type: 'snapshot',
epoch: 'renderer',
seq: 1,
rows: [status]
})
).toEqual({ accepted: false, reason: 'superseded' })
expect(
runtime.syncRendererAgentStatus(1, { type: 'snapshot', epoch: 'old', seq: 1, rows: [status] })
).toEqual({ accepted: false, reason: 'superseded' })
runtime.syncRendererAgentStatus(1, {
type: 'snapshot',
epoch: 'renderer',
seq: 1,
rows: [status]
})
await vi.advanceTimersByTimeAsync(100)
expect(frames.map((frame) => frame.worktree)).toEqual([TEST_WORKTREE_ID])
expect(frames[0].tabs[0]).toMatchObject({
agentStatus: { state: 'blocked', prompt: 'Approve the change' }
})
expect(frames[0].tabs[0]).not.toHaveProperty('statusSuppressionTitle')
const statusVersion = frames[0].snapshotVersion
await publish(2, 'claude agents')
await vi.advanceTimersByTimeAsync(100)
expect(frames.at(-1)!.tabs[0]).not.toHaveProperty('agentStatus')
expect(frames.at(-1)!.snapshotVersion).toBeGreaterThan(statusVersion)
await publish(3, 'Claude')
await vi.advanceTimersByTimeAsync(100)
expect(frames.at(-1)!.tabs[0]).toMatchObject({ agentStatus: { prompt: 'Approve the change' } })
frames.length = 0
await publish(1, 'Claude', 'replacement')
await vi.advanceTimersByTimeAsync(100)
expect(frames).toEqual([])
runtime.syncRendererAgentStatus(1, {
type: 'snapshot',
epoch: 'replacement',
seq: 1,
rows: [status]
})
await vi.advanceTimersByTimeAsync(100)
expect(frames).toHaveLength(1)
expect(frames[0].tabs[0]).toMatchObject({ agentStatus: { prompt: 'Approve the change' } })
const batches: RendererStatusPublication[] = []
let settle: (() => void) | undefined
let current = status
const sender = new RendererStatusSender(
'replacement',
() => current,
() => [paneKey],
(batch) => {
batches.push(batch)
if (batches.length === 1) {
return new Promise((resolve) => {
settle = () => resolve(runtime.syncRendererAgentStatus(1, batch))
})
}
return Promise.resolve(runtime.syncRendererAgentStatus(1, batch))
},
{ seq: 1 }
)
try {
sender.graphAccepted()
await vi.advanceTimersByTimeAsync(16)
const fence = runtime.markRendererReloading(1)!
settle!()
await Promise.resolve()
current = { ...status, row: { ...status.row, prompt: 'While reloading' } }
sender.changed(new Set([paneKey]))
expect(runtime.markRendererReloadCancelled(1, fence)).toBe(true)
await vi.advanceTimersByTimeAsync(300)
expect(batches[1]).toMatchObject({
type: 'snapshot',
rows: [{ row: { prompt: 'While reloading' } }]
})
expect(frames.at(-1)!.tabs[0]).toMatchObject({ agentStatus: { prompt: 'While reloading' } })
current = { ...status, row: { ...status.row, prompt: 'Current turn' } }
sender.changed(new Set([paneKey]))
await vi.advanceTimersByTimeAsync(100)
expect(batches[2].type).toBe('changes')
expect(frames.at(-1)!.tabs[0]).toMatchObject({ agentStatus: { prompt: 'Current turn' } })
} finally {
sender.stop()
}
} finally {
stop()
}
})
it.each([true, false])(
'releases held phone frames when the unseeded desktop closes (headless %s)',
async (headless) => {
const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession(
makeWorkspaceSessionWithHeadlessTerminal()
)
const runtime = new OrcaRuntimeService(runtimeStore)
if (headless) {
publishHeadlessRuntimeGraph(runtime)
}
runtime.attachWindow(1)
const frames: RuntimeMobileSessionTabsResult[] = []
const stop = runtime.onMobileSessionTabsChanged(
(frame) => frames.push(frame),
undefined,
'mobile'
)
try {
await runtime.syncWindowGraph(1, {
rendererGeneration: 'renderer',
tabs: [],
leaves: [],
mobileSessionTabs: [
{
worktree: TEST_WORKTREE_ID,
publicationEpoch: 'renderer',
snapshotVersion: 1,
activeGroupId: null,
activeTabId: null,
activeTabType: null,
tabs: [
{
type: 'terminal',
id: `host-tab::${HEADLESS_LEAF_ID}`,
parentTabId: 'host-tab',
leafId: HEADLESS_LEAF_ID,
ptyId: null,
title: 'Claude',
isActive: true,
statusSuppressionTitle: 'Claude'
}
]
}
]
})
await vi.advanceTimersByTimeAsync(100)
expect(frames).toEqual([])
runtime.markGraphUnavailable(1)
await vi.advanceTimersByTimeAsync(100)
expect(frames.map((frame) => frame.worktree)).toContain(TEST_WORKTREE_ID)
} finally {
stop()
}
}
)
@@ -0,0 +1,258 @@
import { describe, expect, it } from 'vitest'
import { RendererStatusReplica, type RendererStatusMember } from './renderer-status-replica'
import type { AgentStatusEntry } from '../../../shared/agent-status/contracts/agent-status-types'
const row: AgentStatusEntry = {
paneKey: 'tab:leaf',
state: 'working',
prompt: 'Build it',
stateStartedAt: 10,
updatedAt: 20,
stateHistory: []
}
const member = (pty: string | null, title = 'Claude'): RendererStatusMember => ({
paneKey: 'tab:leaf',
leafId: 'leaf',
rendererPtyId: pty,
worktreeId: 'workspace',
statusSuppressionTitle: title
})
const members = (pty: string | null, title?: string) => new Map([['tab:leaf', member(pty, title)]])
const record = (pty: string | null, prompt: string) => ({ ...member(pty), row: { ...row, prompt } })
function reconcile(replica: RendererStatusReplica, incoming: Map<string, RendererStatusMember>) {
return replica.reconcileGraph(incoming, new Set(['workspace']))
}
describe('renderer status / graph join', () => {
it('joins an initial snapshot and an incoming occupant without reviving the retired occupant', () => {
const replica = new RendererStatusReplica()
replica.beginEpoch('renderer')
replica.apply({ type: 'snapshot', epoch: 'renderer', seq: 1, rows: [record('A', 'first')] })
expect(replica.get('tab:leaf')).toBeUndefined()
const control = { ...member('control'), paneKey: 'control:leaf', worktreeId: 'other' }
replica.reconcileGraph(
new Map([...members('A'), ['control:leaf', control]]),
new Set(['workspace', 'other'])
)
replica.apply({
type: 'changes',
epoch: 'renderer',
seq: 2,
rows: [{ ...control, row: { ...row, paneKey: 'control:leaf', prompt: 'untouched' } }]
})
expect(replica.get('tab:leaf')?.row?.prompt).toBe('first')
replica.apply({ type: 'changes', epoch: 'renderer', seq: 3, rows: [record('B', 'next')] })
expect(replica.get('tab:leaf')?.row?.prompt).toBe('first')
reconcile(replica, members('B'))
expect(replica.get('tab:leaf')?.row?.prompt).toBe('next')
replica.apply({ type: 'changes', epoch: 'renderer', seq: 4, rows: [record('A', 'late')] })
expect(replica.get('tab:leaf')?.row?.prompt).toBe('next')
replica.apply({ type: 'changes', epoch: 'renderer', seq: 5, rows: [record('C', 'future')] })
reconcile(replica, new Map())
replica.apply({ type: 'changes', epoch: 'renderer', seq: 6, rows: [record('B', 'closed')] })
reconcile(replica, members('B'))
expect(replica.get('tab:leaf')?.row).toBeUndefined()
reconcile(replica, members('C'))
expect(replica.get('tab:leaf')?.row).toBeUndefined()
expect(replica.get('control:leaf')?.row?.prompt).toBe('untouched')
})
it('preserves unbound and remounted rows and re-shapes title changes without another status write', () => {
const replica = new RendererStatusReplica()
replica.beginEpoch('renderer')
reconcile(replica, members(null))
replica.apply({ type: 'snapshot', epoch: 'renderer', seq: 1, rows: [record(null, 'unbound')] })
reconcile(replica, members('A'))
expect(replica.get('tab:leaf')?.row?.prompt).toBe('unbound')
replica.apply({ type: 'changes', epoch: 'renderer', seq: 2, rows: [record('A', 'bound')] })
reconcile(replica, members(null))
expect(replica.get('tab:leaf')?.row?.prompt).toBe('bound')
reconcile(replica, members('A'))
expect(replica.get('tab:leaf')?.row?.prompt).toBe('bound')
reconcile(replica, members('A', 'claude agents'))
expect(replica.get('tab:leaf')?.row).toBeUndefined()
reconcile(replica, members('A', 'Claude'))
expect(replica.get('tab:leaf')?.row?.prompt).toBe('bound')
reconcile(replica, members(null))
replica.apply({ type: 'changes', epoch: 'renderer', seq: 3, rows: [record('B', 'bound')] })
reconcile(replica, members('B'))
expect(replica.get('tab:leaf')?.row?.prompt).toBe('bound')
})
it('requests a replacement snapshot on pending overflow while retaining the newest future occupant', () => {
const replica = new RendererStatusReplica()
replica.beginEpoch('renderer')
const overflow = replica.apply({
type: 'snapshot',
epoch: 'renderer',
seq: 1,
rows: Array.from({ length: 2049 }, (_, index) => record(`future-${index}`, `turn-${index}`))
})
expect(overflow).toMatchObject({ accepted: true, snapshotRequired: true })
reconcile(replica, members('future-0'))
expect(replica.get('tab:leaf')?.row).toBeUndefined()
reconcile(replica, members('future-2048'))
expect(replica.get('tab:leaf')?.row?.prompt).toBe('turn-2048')
replica.apply({ type: 'snapshot', epoch: 'renderer', seq: 2, rows: [] })
expect(replica.get('tab:leaf')?.row).toBeUndefined()
})
it('requires a snapshot on a gap and replaces only the current publisher scope', () => {
const replica = new RendererStatusReplica()
replica.beginEpoch('renderer')
reconcile(replica, members('A'))
replica.apply({ type: 'snapshot', epoch: 'renderer', seq: 1, rows: [record('A', 'first')] })
expect(
replica.apply({ type: 'changes', epoch: 'renderer', seq: 3, rows: [record('A', 'gap')] })
).toMatchObject({ accepted: false, snapshotRequired: true })
expect(replica.get('tab:leaf')?.row?.prompt).toBe('first')
replica.apply({ type: 'snapshot', epoch: 'renderer', seq: 4, rows: [] })
expect(replica.get('tab:leaf')?.row).toBeUndefined()
replica.beginEpoch('replacement')
replica.apply({ type: 'snapshot', epoch: 'renderer', seq: 5, rows: [record('A', 'old')] })
expect(replica.get('tab:leaf')?.row).toBeUndefined()
reconcile(replica, members(null))
replica.apply({
type: 'snapshot',
epoch: 'replacement',
seq: 1,
rows: [record(null, 'current')]
})
reconcile(replica, members('Y'))
expect(replica.get('tab:leaf')?.row?.prompt).toBe('current')
})
})
// The resource bound is a requested regression contract, including recovery debt.
it.each([100, 1000])('releases retirement debt across 20 turnover cycles at %i panes', (width) => {
const replica = new RendererStatusReplica()
replica.beginEpoch('renderer')
let seq = 0
replica.apply({ type: 'snapshot', epoch: 'renderer', seq: ++seq, rows: [] })
for (let cycle = 0; cycle < 20; cycle++) {
const fleet = new Map(
Array.from({ length: width }, (_, index) => {
const item = { ...member(`A-${cycle}`), paneKey: `tab-${cycle}-${index}:leaf` }
return [item.paneKey, item] as const
})
)
reconcile(replica, fleet)
replica.apply({
type: 'changes',
epoch: 'renderer',
seq: ++seq,
rows: [...fleet.values()].map((item) => ({ ...item, row }))
})
const future = [...fleet.values()].map((item) => ({
...item,
rendererPtyId: `B-${cycle}`,
row: { ...row, prompt: 'future' }
}))
replica.apply({ type: 'changes', epoch: 'renderer', seq: ++seq, rows: future })
reconcile(replica, new Map(future.map((item) => [item.paneKey, item])))
replica.apply({
type: 'changes',
epoch: 'renderer',
seq: ++seq,
rows: [...fleet.values()].map((item) => ({ ...item, row: { ...row, prompt: 'late' } }))
})
for (const item of fleet.values()) {
expect(replica.get(item.paneKey)?.row?.prompt).toBe('future')
}
replica.apply({
type: 'changes',
epoch: 'renderer',
seq: ++seq,
rows: [...fleet.values()].map((item) => ({ ...item, row: null }))
})
expect(replica).toHaveProperty('retired.size', 0)
reconcile(replica, new Map())
replica.apply({
type: 'changes',
epoch: 'renderer',
seq: ++seq,
rows: future.map((item) => ({ ...item, row: null }))
})
replica.apply({ type: 'snapshot', epoch: 'renderer', seq: ++seq, rows: [] })
for (const table of [
'retired',
'rows',
'pending',
'pendingByPane',
'members',
'membersByWorktree',
'active',
'bound'
]) {
expect(replica).toHaveProperty(`${table}.size`, 0)
}
}
})
it.each([100, 1000])(
'settles healthy close debt without snapshots at %i panes, in either graph order',
(width) => {
const replica = new RendererStatusReplica()
replica.beginEpoch('renderer')
let seq = 0
replica.apply({ type: 'snapshot', epoch: 'renderer', seq: ++seq, rows: [] })
for (let cycle = 0; cycle < 20; cycle++) {
const fleet = new Map(
Array.from({ length: width }, (_, index) => {
const item = { ...member(`A-${cycle}`), paneKey: `tab-${cycle}-${index}:leaf` }
return [item.paneKey, item] as const
})
)
reconcile(replica, fleet)
const rows = [...fleet.values()].map((item) => ({
...item,
row: { ...row, paneKey: item.paneKey }
}))
const tombstones = rows.map((item) => ({ ...item, row: null }))
replica.apply({
type: 'changes',
epoch: 'renderer',
seq: ++seq,
rows: rows.map((item) => ({ ...item, rendererPtyId: null }))
})
replica.apply({ type: 'changes', epoch: 'renderer', seq: ++seq, rows })
expect(replica).toHaveProperty('rows.size', width)
if (cycle % 2 === 0) {
reconcile(replica, new Map())
replica.apply({ type: 'changes', epoch: 'renderer', seq: ++seq, rows: tombstones })
} else {
replica.apply({ type: 'changes', epoch: 'renderer', seq: ++seq, rows: tombstones })
reconcile(replica, new Map())
}
for (const table of [
'retired',
'rows',
'pending',
'pendingByPane',
'members',
'membersByWorktree',
'active',
'bound'
]) {
expect(replica).toHaveProperty(`${table}.size`, 0)
}
}
reconcile(replica, members(null))
replica.apply({
type: 'changes',
epoch: 'renderer',
seq: ++seq,
rows: [record(null, 'unbound')]
})
reconcile(replica, members('A'))
reconcile(replica, new Map())
replica.apply({
type: 'changes',
epoch: 'renderer',
seq: ++seq,
rows: [{ ...record('A', ''), row: null }]
})
expect(replica).toHaveProperty('retired.size', 0)
}
)
@@ -0,0 +1,255 @@
import type { OrcaRuntimeWithRuntimeId } from '../construction/runtime-identity-state'
import type { AgentStatusEntry } from '../../../shared/agent-status/contracts/agent-status-types'
import {
rendererStatusOccupantKey,
type RendererStatusOccupant,
type RendererStatusPublication,
type RendererStatusRecord,
type RendererStatusAck
} from '../../../shared/agent-status/renderer-status-publication'
import { shapeMobileTerminalStatus } from '../../../shared/agent-status/mobile-terminal-status-shaping'
export type RendererStatusMember = RendererStatusOccupant & {
worktreeId: string
statusSuppressionTitle: string
}
/** Read replica only; graph membership and accepted renderer rows remain separate inputs. */
export class RendererStatusReplica {
private epoch: string | null = null
private seq = 0
private seeded = false
private members = new Map<string, RendererStatusMember>()
private membersByWorktree = new Map<string, Set<string>>()
private pendingByPane = new Map<string, Set<string>>()
private rows = new Map<string, RendererStatusRecord>()
private pending = new Map<string, RendererStatusRecord>()
private retired = new Set<string>()
private active = new Map<string, string>()
private bound = new Map<string, string>()
beginEpoch(epoch: string): void {
if (this.epoch === epoch) {
return
}
this.epoch = epoch
this.seq = 0
this.seeded = false
this.rows.clear()
this.pending.clear()
this.retired.clear()
this.active.clear()
this.bound.clear()
this.pendingByPane.clear()
}
/** Only the generation that owes the seed holds phone frames; losing authority releases them. */
awaitingSnapshot(worktreeId: string, generation: string | null): boolean {
return generation === this.epoch && !this.seeded && this.membersByWorktree.has(worktreeId)
}
unseededWorktrees(): Iterable<string> {
return this.seeded ? [] : this.membersByWorktree.keys()
}
*membersForWorktree(worktreeId: string): IterableIterator<RendererStatusMember> {
for (const key of this.membersByWorktree.get(worktreeId) ?? []) {
yield this.members.get(key)!
}
}
reconcileGraph(
incoming: Map<string, RendererStatusMember>,
worktrees: ReadonlySet<string>
): Set<string> {
const changed = new Set<string>()
for (const worktreeId of worktrees) {
const previous = this.membersByWorktree.get(worktreeId) ?? new Set<string>()
for (const paneKey of previous) {
const old = this.members.get(paneKey)!
const next = incoming.get(paneKey)
const priorPty = this.bound.get(paneKey) ?? old.rendererPtyId
if (
!next ||
old.leafId !== next.leafId ||
(priorPty !== null && next.rendererPtyId !== null && priorPty !== next.rendererPtyId)
) {
const key = rendererStatusOccupantKey({ ...old, rendererPtyId: priorPty })
const unbound = rendererStatusOccupantKey({ ...old, rendererPtyId: null })
this.retireOutstanding(key, paneKey)
this.retireOutstanding(unbound, paneKey)
if (this.active.get(paneKey) === key || this.active.get(paneKey) === unbound) {
this.active.delete(paneKey)
}
if (!next) {
for (const pendingKey of this.pendingByPane.get(paneKey) ?? []) {
this.retireOutstanding(pendingKey, paneKey)
}
this.pendingByPane.delete(paneKey)
const active = this.active.get(paneKey)
if (active) {
this.retireOutstanding(active, paneKey)
this.active.delete(paneKey)
}
this.bound.delete(paneKey)
}
}
if (
!next ||
old.rendererPtyId !== next.rendererPtyId ||
old.statusSuppressionTitle !== next.statusSuppressionTitle
) {
changed.add(worktreeId)
}
this.members.delete(paneKey)
}
this.membersByWorktree.delete(worktreeId)
}
for (const [paneKey, member] of incoming) {
this.members.set(paneKey, member)
const keys = this.membersByWorktree.get(member.worktreeId) ?? new Set<string>()
keys.add(paneKey)
this.membersByWorktree.set(member.worktreeId, keys)
if (member.rendererPtyId !== null) {
this.bound.set(paneKey, member.rendererPtyId)
}
const activeKey = this.active.get(paneKey)
const active = activeKey ? this.rows.get(activeKey) : undefined
if (active && !this.matches(active, member)) {
this.rows.delete(activeKey!)
this.active.delete(paneKey)
this.setPending(activeKey!, active)
}
for (const key of this.pendingByPane.get(paneKey) ?? []) {
const record = this.pending.get(key)!
if (this.matches(record, member)) {
this.deletePending(key, paneKey)
this.setActive(key, record)
changed.add(member.worktreeId)
}
}
}
return changed
}
private setActive(key: string, record: RendererStatusRecord): void {
const previous = this.active.get(record.paneKey)
if (previous !== undefined) {
this.rows.delete(previous)
}
this.rows.set(key, record)
this.active.set(record.paneKey, key)
}
private retireOutstanding(key: string, paneKey: string): void {
// An ordered tombstone already settled an absent row; graph removal creates no new debt.
if ((this.active.get(paneKey) === key && this.rows.has(key)) || this.pending.has(key)) {
this.retired.add(key)
}
this.rows.delete(key)
this.deletePending(key, paneKey)
}
private deletePending(key: string, paneKey: string): void {
this.pending.delete(key)
const keys = this.pendingByPane.get(paneKey)
keys?.delete(key)
if (!keys?.size) {
this.pendingByPane.delete(paneKey)
}
}
private setPending(key: string, record: RendererStatusRecord): void {
this.pending.set(key, record)
const keys = this.pendingByPane.get(record.paneKey) ?? new Set<string>()
keys.add(key)
this.pendingByPane.set(record.paneKey, keys)
}
private matches(row: RendererStatusOccupant, member: RendererStatusMember): boolean {
return (
row.leafId === member.leafId &&
(row.rendererPtyId === null ||
member.rendererPtyId === null ||
row.rendererPtyId === member.rendererPtyId)
)
}
apply(batch: RendererStatusPublication): RendererStatusAck & { worktrees: Set<string> } {
const worktrees = new Set<string>()
if (batch.epoch !== this.epoch || !Number.isSafeInteger(batch.seq) || batch.seq <= this.seq) {
return { accepted: false, worktrees }
}
if (batch.type !== 'snapshot' && (!this.seeded || batch.seq !== this.seq + 1)) {
return { accepted: false, snapshotRequired: true, worktrees }
}
if (batch.type === 'snapshot') {
for (const worktreeId of this.membersByWorktree.keys()) {
worktrees.add(worktreeId)
}
this.retired.clear()
this.rows.clear()
this.active.clear()
this.pending.clear()
this.pendingByPane.clear()
this.seeded = true
}
this.seq = batch.seq
let snapshotRequired = false
for (const record of batch.rows) {
const key = rendererStatusOccupantKey(record)
if (record.row !== null && this.retired.has(key)) {
continue
}
const member = this.members.get(record.paneKey)
this.rows.delete(key)
this.deletePending(key, record.paneKey)
if (record.row === null) {
this.retired.delete(key)
this.retired.delete(rendererStatusOccupantKey({ ...record, rendererPtyId: null }))
if (this.active.get(record.paneKey) === key) {
this.active.delete(record.paneKey)
}
if (member && this.matches(record, member)) {
worktrees.add(member.worktreeId)
}
continue
}
if (member && this.matches(record, member)) {
this.setActive(key, record)
worktrees.add(member.worktreeId)
} else {
this.setPending(key, record)
if (this.pending.size > 2048) {
const oldest = this.pending.entries().next().value!
this.deletePending(oldest[0], oldest[1].paneKey)
snapshotRequired = true
}
}
}
return { accepted: true, ...(snapshotRequired ? { snapshotRequired } : {}), worktrees }
}
get(paneKey: string): { row: AgentStatusEntry | undefined } | undefined {
const member = this.members.get(paneKey)
if (!member) {
return undefined
}
const key = this.active.get(paneKey)
return {
row: shapeMobileTerminalStatus(
key ? (this.rows.get(key)?.row ?? undefined) : undefined,
member.statusSuppressionTitle
)
}
}
}
const replicas = new WeakMap<OrcaRuntimeWithRuntimeId, RendererStatusReplica>()
export function rendererStatusReplica(runtime: OrcaRuntimeWithRuntimeId): RendererStatusReplica {
let replica = replicas.get(runtime)
if (!replica) {
replicas.set(runtime, (replica = new RendererStatusReplica()))
}
return replica
}
@@ -0,0 +1,12 @@
import type { RuntimeSyncedTab } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts'
/** The runtime indexes graph tabs by bare id, so duplicate ids cannot be routed safely. */
export function assertUniqueRuntimeGraphTabIds(tabs: readonly RuntimeSyncedTab[]): void {
const seen = new Set<string>()
for (const tab of tabs) {
if (seen.has(tab.tabId)) {
throw new Error('duplicate_runtime_tab_id')
}
seen.add(tab.tabId)
}
}
@@ -77,6 +77,7 @@ export abstract class OrcaRuntimeWithTransitionGraphReloadToTerminalState extend
this.clearPtyIncarnationHandles()
this.terminalWaiters.rejectAll('terminal_handle_stale')
this.refreshWritableFlags()
this.releaseUnseededPhoneFrames()
}
protected shouldRestoreHeadlessGraph(windowId: number): boolean {
@@ -98,6 +99,7 @@ export abstract class OrcaRuntimeWithTransitionGraphReloadToTerminalState extend
this.terminalWaiters.rejectAll('terminal_handle_stale')
this.refreshWritableFlags()
this.markSessionTabsInventoryPublished()
this.releaseUnseededPhoneFrames()
if (ORCA_LAYOUT_OWNER_IS_MAIN) {
this.headlessGraphFallbackAvailable = true
startedMainTerminalSurfaces(this)?.republish({ force: true })
@@ -31,6 +31,18 @@ export abstract class OrcaRuntimeWithAttachWindow extends OrcaRuntimeWithNotifyS
protected abstract mainDecidesLiveness(worktreeId: string): boolean
// Remounts briefly clear ptyId; retain the live handle paired clients still use (#23759).
protected isLeafRemountingLivePty(
ptyId: string,
incomingPtyIds: ReadonlySet<string | null>
): boolean {
return (
!incomingPtyIds.has(ptyId) &&
this.controllerKnowsPtyIsLive(ptyId) &&
this.getPtyLivenessVerdict(ptyId)?.status !== 'exited'
)
}
/** Main-owned panes do not prove liveness or override certified exits; terminal records decide (L80). */
protected graphLeafConnected(ptyId: string | null, worktreeId: string): boolean {
if (ptyId === null || this.getPtyLivenessVerdict(ptyId)?.status === 'exited') {
@@ -4,8 +4,16 @@ import { OrcaRuntimeWithSessionTitleAuthority } from '../session-tabs/session-ti
import type { RuntimeRendererReloadFence } from './renderer-reload-fence'
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch'
import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts'
import { rendererStatusReplica } from './renderer-status-replica'
export abstract class OrcaRuntimeWithHasTerminalsForWorktree extends OrcaRuntimeWithSessionTitleAuthority {
/** Phone frames held for an unseeded renderer's snapshot are owed once it loses authority. */
protected releaseUnseededPhoneFrames(): void {
for (const worktreeId of rendererStatusReplica(this).unseededWorktrees()) {
this.scheduleMobileSessionTabsChanged(worktreeId)
}
}
protected abstract assertStableReadyGraph(
...args: Parameters<TransitionGraphReloadToTerminalStateMethods['assertStableReadyGraph']>
): ReturnType<TransitionGraphReloadToTerminalStateMethods['assertStableReadyGraph']>
@@ -217,6 +225,7 @@ export abstract class OrcaRuntimeWithHasTerminalsForWorktree extends OrcaRuntime
this.clearPtyIncarnationHandles()
// Keep pre-allocated CLI handles for reconnect adoption.
this.terminalWaiters.rejectAll('terminal_handle_stale')
this.releaseUnseededPhoneFrames()
this.republishSessionTitleAuthorityChanges(titleAuthority, this.republishBrowserSessionTabs())
}
@@ -1,10 +1,11 @@
import { OrcaRuntimeWithAdmitWindowPublisher } from './session-window-publisher'
import type {
RuntimeRendererSyncWindowGraph,
RuntimeSyncedTab,
RuntimeSyncWindowGraph,
RuntimeSyncWindowGraphResult
} from '../../../shared/remote-runtime/session-graph/runtime-session-contracts'
import { assertUniqueRuntimeGraphTabIds } from './runtime-graph-tab-ids'
import { isTerminalLeafId, makePaneKey } from '../../../shared/workspace-layout/stable-pane-id'
import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts'
import type { RuntimeLeafRecord } from '../terminal/records/runtime-terminal-state-records'
@@ -13,35 +14,12 @@ import { assertBrowserPageInventoryFrames } from '../session-tabs/mobile-session
type Graph = RuntimeSyncWindowGraph
/** The runtime indexes graph tabs by bare id, so duplicate ids cannot be routed safely. */
function assertUniqueRuntimeGraphTabIds(tabs: readonly RuntimeSyncedTab[]): void {
const seen = new Set<string>()
for (const tab of tabs) {
if (seen.has(tab.tabId)) {
throw new Error('duplicate_runtime_tab_id')
}
seen.add(tab.tabId)
}
}
export abstract class OrcaRuntimeWithSyncWindowGraph extends OrcaRuntimeWithAdmitWindowPublisher {
/** Layout-owner builds: main's panes in place of the window's (session-tabs-inventory.ts). */
protected abstract withMainSurfaces(windowId: number, graph: Graph): Graph
declare protected terminalGroupGridSizes?: RuntimeSyncWindowGraph['terminalGroupGridSizes']
declare protected singleGroupWorkspaceGridSize?: RuntimeSyncWindowGraph['singleGroupWorkspaceGridSize']
// Remounts briefly clear ptyId; retain the live handle paired clients still use (#23759).
private isLeafRemountingLivePty(
ptyId: string,
incomingPtyIds: ReadonlySet<string | null>
): boolean {
return (
!incomingPtyIds.has(ptyId) &&
this.controllerKnowsPtyIsLive(ptyId) &&
this.getPtyLivenessVerdict(ptyId)?.status !== 'exited'
)
}
shouldRelayTerminalBrowserOpens(): boolean {
return this.authoritativeWindowId === HEADLESS_RUNTIME_WINDOW_ID
}
@@ -57,6 +35,7 @@ export abstract class OrcaRuntimeWithSyncWindowGraph extends OrcaRuntimeWithAdmi
const rendererGeneration = this.admitWindowPublisher(windowId, graph)
const previousTitleAuthority = this.captureSessionTitleAuthority()
const publishedMobileSessionTabs = graph.mobileSessionTabs
const rendererGraph = graph
if (windowId === HEADLESS_RUNTIME_WINDOW_ID) {
this.headlessGraphFallbackAvailable = true
this.servesHeadlessGraph = true
@@ -89,6 +68,10 @@ export abstract class OrcaRuntimeWithSyncWindowGraph extends OrcaRuntimeWithAdmi
publishedMobileSessionTabs
)
const nextLeaves = new Map<string, RuntimeLeafRecord>()
const rendererBindings =
graph === rendererGraph
? new Map<string, string | null>()
: this.captureRendererStatusBindings(rendererGraph, changedMobileWorktrees)
const graphSyncedAt = this.nextTitleObservationSequence()
// Stamp this graph's surfaces; newer records survive until the next statement (pty-recorded-surface-topology.ts).
// Exempt the one-shot headless placeholder: it names no renderer panes and cannot re-stamp later claims (#18191).
@@ -109,6 +92,14 @@ export abstract class OrcaRuntimeWithSyncWindowGraph extends OrcaRuntimeWithAdmi
}
const leafKey = this.getLeafKey(leaf.tabId, leaf.leafId)
const existing = this.leaves.get(leafKey)
// Why: status rows are keyed by UUID leaf ids; older or mirrored leaves can't carry one.
if (
graph === rendererGraph &&
isTerminalLeafId(leaf.leafId) &&
(changedMobileWorktrees.has(leaf.worktreeId) || existing?.ptyId !== leaf.ptyId)
) {
rendererBindings.set(makePaneKey(leaf.tabId, leaf.leafId), leaf.ptyId)
}
const ptyId =
leaf.ptyId === null &&
existing?.ptyId &&
@@ -269,6 +260,14 @@ export abstract class OrcaRuntimeWithSyncWindowGraph extends OrcaRuntimeWithAdmi
if (rendererGeneration !== undefined) {
this.rendererGeneration = rendererGeneration
}
if (typeof rendererGeneration === 'string') {
this.reconcileRendererStatusMembership(
rendererGeneration,
rendererGraph,
rendererBindings,
changedMobileWorktrees
)
}
this.republishSessionTitleAuthorityChanges(previousTitleAuthority, changedMobileWorktrees)
for (const worktreeId of changedMobileWorktrees) {
if (this.mobileSessionTabsByWorktree.has(worktreeId)) {
@@ -1,3 +1,9 @@
import { rendererStatusReplica, type RendererStatusMember } from './renderer-status-replica'
import { isTerminalLeafId, makePaneKey } from '../../../shared/workspace-layout/stable-pane-id'
import type {
RendererStatusPublication,
RendererStatusAck
} from '../../../shared/agent-status/renderer-status-publication'
import { OrcaRuntimeWithAttachWindow } from './session-graph-promotion'
import type {
RuntimeRendererSyncWindowGraph,
@@ -6,6 +12,124 @@ import type {
import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts'
export abstract class OrcaRuntimeWithAdmitWindowPublisher extends OrcaRuntimeWithAttachWindow {
syncRendererAgentStatus(windowId: number, batch: RendererStatusPublication): RendererStatusAck {
if (windowId !== this.authoritativeWindowId || this.rendererGeneration !== batch.epoch) {
return { accepted: false, reason: 'superseded' }
}
if (this.graphStatus !== 'ready') {
return { accepted: false, reason: 'not-ready' }
}
const { worktrees, ...ack } = rendererStatusReplica(this).apply(batch)
for (const worktreeId of worktrees) {
const snapshot = this.mobileSessionTabsByWorktree.get(worktreeId)
if (!snapshot) {
continue
}
// Status changes invalidate only this phone frame; graph hydration and activity stay idle.
this.mobileSessionTabsByWorktree.set(worktreeId, {
...snapshot,
snapshotVersion: snapshot.snapshotVersion + 1
})
this.scheduleMobileSessionTabsChanged(worktreeId)
}
return ack
}
protected captureRendererStatusBindings(
graph: RuntimeSyncWindowGraph,
worktrees: ReadonlySet<string>
): Map<string, string | null> {
const bindings = new Map<string, string | null>()
for (const leaf of graph.leaves) {
if (
isTerminalLeafId(leaf.leafId) &&
(worktrees.has(leaf.worktreeId) ||
this.leaves.get(this.getLeafKey(leaf.tabId, leaf.leafId))?.ptyId !== leaf.ptyId)
) {
bindings.set(makePaneKey(leaf.tabId, leaf.leafId), leaf.ptyId)
}
}
return bindings
}
protected reconcileRendererStatusMembership(
rendererGeneration: string,
graph: RuntimeSyncWindowGraph,
rawBindings: ReadonlyMap<string, string | null>,
changedMobileWorktrees: Set<string>
): void {
const replica = rendererStatusReplica(this)
replica.beginEpoch(rendererGeneration)
const members = new Map<string, RendererStatusMember>()
const reconciled = new Set(changedMobileWorktrees)
const retained = new Set(changedMobileWorktrees)
for (const snapshot of graph.mobileSessionTabs ?? []) {
if (!reconciled.has(snapshot.worktree)) {
continue
}
retained.delete(snapshot.worktree)
const accepted = this.acceptedRendererMobileSnapshotByWorktree.get(snapshot.worktree)
if (
!accepted ||
accepted.publicationEpoch !== snapshot.publicationEpoch ||
accepted.rendererVersion !== snapshot.snapshotVersion
) {
if (accepted) {
reconciled.delete(snapshot.worktree)
}
continue
}
const storedIds = new Set(
this.mobileSessionTabsByWorktree.get(snapshot.worktree)?.tabs.map((tab) => tab.id)
)
for (const tab of snapshot.tabs) {
if (tab.type !== 'terminal' || !storedIds.has(tab.id) || !isTerminalLeafId(tab.leafId)) {
continue
}
const paneKey = makePaneKey(tab.parentTabId, tab.leafId)
members.set(paneKey, {
paneKey,
leafId: tab.leafId,
worktreeId: snapshot.worktree,
rendererPtyId: rawBindings.has(paneKey) ? rawBindings.get(paneKey)! : (tab.ptyId ?? null),
statusSuppressionTitle: tab.statusSuppressionTitle ?? ''
})
}
}
for (const worktreeId of retained) {
const stored = this.mobileSessionTabsByWorktree.get(worktreeId)
const storedKeys = new Set<string>(
stored?.tabs.flatMap((tab) =>
tab.type === 'terminal' && isTerminalLeafId(tab.leafId)
? [makePaneKey(tab.parentTabId, tab.leafId)]
: []
)
)
for (const member of replica.membersForWorktree(worktreeId)) {
if (storedKeys.has(member.paneKey)) {
members.set(member.paneKey, {
...member,
rendererPtyId: rawBindings.has(member.paneKey)
? rawBindings.get(member.paneKey)!
: member.rendererPtyId
})
}
}
}
for (const worktreeId of replica.reconcileGraph(members, reconciled)) {
if (!changedMobileWorktrees.has(worktreeId)) {
const stored = this.mobileSessionTabsByWorktree.get(worktreeId)
if (stored) {
this.mobileSessionTabsByWorktree.set(worktreeId, {
...stored,
snapshotVersion: stored.snapshotVersion + 1
})
}
}
changedMobileWorktrees.add(worktreeId)
}
}
protected admitWindowPublisher(
windowId: number,
graph: RuntimeSyncWindowGraph | RuntimeRendererSyncWindowGraph
@@ -1,3 +1,4 @@
import { rendererStatusReplica } from '../../session-graph/renderer-status-replica'
import { selectFreshAgentRowForMobileTab } from '../../workspaces/process-listing/runtime-hook-agent-row-selection'
import { OrcaRuntimeWithSavedConversationTitlePublication } from '../../session-tabs/saved-conversation-title-publication'
import type { TabGroupLayoutNode } from '../../../../shared/tab-types'
@@ -127,6 +128,8 @@ export abstract class OrcaRuntimeWithPruneMobileSessionTabGroupLayout extends Or
protected getMobileSessionProjectionHost(): RuntimeMobileSessionProjectionHost {
return {
getRendererStatus: (paneKey) =>
this.authoritativeWindowId !== 0 ? rendererStatusReplica(this).get(paneKey) : undefined,
tabs: this.tabs,
leaves: this.leaves,
ptysById: this.ptysById,
@@ -20,6 +20,7 @@ import type {
import type { TitleDisplayClear } from '../../workspaces/process-listing/runtime-worktree-status-projection'
export type RuntimeMobileSessionProjectionHost = {
getRendererStatus?(paneKey: string): { row: AgentStatusEntry | undefined } | undefined
tabs: ReadonlyMap<string, RuntimeSyncedTab>
leaves: ReadonlyMap<string, RuntimeLeafRecord>
ptysById: ReadonlyMap<string, RuntimePtyWorktreeRecord>
@@ -62,7 +62,8 @@ export function projectRuntimeMobileSessionTabs(
const claimedLivePtyIds = new Set<string>()
const isPtyLive = (ptyId: string): boolean =>
host.getPtyAvailability(ptyId) ?? host.ptysById.get(ptyId)?.connected ?? false
for (const tab of snapshot.tabs) {
for (const snapshotTab of snapshot.tabs) {
let tab = snapshotTab
if (tab.type === 'browser') {
const liveTab = tab.browserPageId ? liveBrowserTabsByPageId.get(tab.browserPageId) : undefined
if (!liveTab && !host.isRendererOwnedMobileBrowserTab(snapshot, tab)) {
@@ -109,6 +110,10 @@ export function projectRuntimeMobileSessionTabs(
const paneKey = isTerminalLeafId(tab.leafId)
? makePaneKey(tab.parentTabId, tab.leafId)
: `${tab.parentTabId}:${legacyPaneId ?? tab.leafId}`
const replicaStatus = host.getRendererStatus?.(paneKey)
if (replicaStatus) {
tab = { ...tab, agentStatus: replicaStatus.row }
}
const mobileStatusPty = livePty ?? pty
// Use one main hook lookup for both headless title ownership and status to prevent divergence.
const retainedAgentStatus = host.getRetainedStatus(
@@ -72,6 +72,9 @@ function withWindowFacts(
...(!isNamed(row) && !isNamed(windowRow) ? { title: windowRow.title } : {}),
...(windowRow.terminalTheme ? { terminalTheme: windowRow.terminalTheme } : {}),
...(windowRow.agentStatus !== undefined ? { agentStatus: windowRow.agentStatus } : {}),
...(windowRow.statusSuppressionTitle !== undefined
? { statusSuppressionTitle: windowRow.statusSuppressionTitle }
: {}),
...(keepsWindowPtyId(row.ptyId, windowRow.ptyId, rules) ? { ptyId: windowRow.ptyId } : {}),
...(windowRow.launchDraft !== undefined ? { launchDraft: windowRow.launchDraft } : {}),
// Main's row holds the saved name; only the window resolves it.
@@ -1,3 +1,4 @@
import { rendererStatusReplica } from '../session-graph/renderer-status-replica'
import type {
ClientHostedPageObservation,
MobileSessionTabSubscription
@@ -41,6 +42,14 @@ export abstract class RuntimeMobileSessionTabSubscriptions extends RuntimeWorksp
sequence: number,
delivery?: 'reconciliation'
): void {
// A new graph epoch cannot send a status-less phone frame before its seed snapshot.
if (
subscription.clientKind === 'mobile' &&
this.graphStatus !== 'unavailable' &&
rendererStatusReplica(this).awaitingSnapshot(frame.worktree, this.rendererGeneration)
) {
return
}
subscription.listener(frame, sequence, delivery)
if (
subscription.observation === 'caller' ||
+5
View File
@@ -1,3 +1,7 @@
import type {
RendererStatusPublication,
RendererStatusAck
} from '../../../shared/agent-status/renderer-status-publication'
import type {
CrewSubscriptionAttemptArgs,
CrewSubscriptionAttemptCallbacks,
@@ -34,6 +38,7 @@ export type RuntimeEnvironmentSubscriptionHandle = {
export type RuntimeApi = {
runtime: {
syncAgentStatus: (batch: RendererStatusPublication) => Promise<RendererStatusAck>
syncWindowGraph: (
graph: RuntimeRendererSyncWindowGraph
) => Promise<RuntimeSyncWindowGraphResult>
@@ -1,3 +1,7 @@
import type {
RendererStatusPublication,
RendererStatusAck
} from '../../../shared/agent-status/renderer-status-publication'
import { ipcRenderer } from 'electron'
import type { ClientHostedBrowserRowsEvent } from '../../../shared/browser/client-hosting/client-hosted-browser-rows'
import type { SidebarInputsChangedEvent } from '../../../shared/sidebar-list/feed/sidebar-inputs-feed-contract'
@@ -12,6 +16,8 @@ import type { RuntimeEnvironmentSubscriptionHandle } from '../../runtime/runtime
import type { PreloadApi } from '../../api-types'
export const runtimeApi = {
syncAgentStatus: (batch: RendererStatusPublication): Promise<RendererStatusAck> =>
ipcRenderer.invoke('runtime:syncAgentStatus', batch),
syncWindowGraph: (graph: RuntimeRendererSyncWindowGraph): Promise<RuntimeSyncWindowGraphResult> =>
ipcRenderer.invoke('runtime:syncWindowGraph', graph),
getStatus: (): Promise<RuntimeStatus> => ipcRenderer.invoke('runtime:getStatus'),
@@ -1,3 +1,4 @@
import { startRendererStatusPublication } from '../runtime/agent-status/renderer-status-publication'
import { useEffect } from 'react'
import { getSystemPrefersDarkSnapshot } from '../hooks/theme/use-system-prefers-dark'
import {
@@ -11,6 +12,7 @@ import {
setRuntimeGraphSyncEnabled
} from '../runtime/sync-runtime-graph/graph-sync-scheduler'
import { useAppStore } from '../store'
import { isPairedWebClientWindow } from './chrome/desktop-window-chrome'
/** Keeps the mobile runtime graph republished as the store's session-visible state changes. */
export function useRuntimeGraphSync(): void {
@@ -71,8 +73,14 @@ export function useRuntimeGraphSync(): void {
)
useEffect(() => {
// Why: a paired web client has no local main to publish status to.
const stopStatusPublication =
workspaceSessionReady && !isPairedWebClientWindow()
? startRendererStatusPublication(useAppStore, scheduleRuntimeGraphSync)
: undefined
setRuntimeGraphSyncEnabled(workspaceSessionReady)
return () => {
stopStatusPublication?.()
setRuntimeGraphSyncEnabled(false)
}
}, [workspaceSessionReady])
@@ -29,18 +29,7 @@ export function resolveNativeChatActiveLayoutLeafId(
return layout.root?.type === 'leaf' ? layout.root.leafId : null
}
export function isNativeChatTabWideFallbackSafe(
layout: TerminalLayoutSnapshot | null | undefined
): boolean {
if (!layout?.root) {
return true
}
if (layout.root.type === 'split') {
return false
}
// A stale active id can still name the removed sibling, so tab-wide evidence must wait for collapse.
return !layout.activeLeafId || layout.activeLeafId === layout.root.leafId
}
export { isTerminalTabWideFallbackSafe as isNativeChatTabWideFallbackSafe } from '../../../../../../shared/agent-status/mobile-terminal-status-shaping'
/** Tab-wide evidence applies only to the original sole pane, never split siblings. */
export function nativeChatLeafOwnsTabWideEvidence(args: {
@@ -0,0 +1,78 @@
import type { AppState } from '@/store/types'
import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id'
import {
findRegisteredTerminalTab,
subscribeMountedTerminalTabChanges
} from '../hosted-terminals/mounted-surfaces/mounted-terminal-tab-registry'
import {
countSavedTerminalLeavesUpToTwo,
rendererTerminalBinding,
isWebOnlyMirroredTerminalTab
} from '../sync-runtime-graph/mobile-session-surfaces'
import { mobilePublicationEpoch } from '../sync-runtime-graph/graph-state'
import { RendererStatusSender } from './renderer-status-sender'
const publicationCursor = { seq: 0 }
let sender: RendererStatusSender | undefined
export function rendererStatusGraphAccepted(): void {
sender?.graphAccepted()
}
export function startRendererStatusPublication(
store: { getState(): AppState },
requestGraphSync: () => void
): () => void {
const publication = new RendererStatusSender(
mobilePublicationEpoch,
(key) => {
const state = store.getState()
const row = state.agentStatusByPaneKey.get(key)
const identity = parsePaneKey(key)
if (!row || !identity) {
return null
}
const source = state.agentStatusByPaneKey.projection.mobileSource(key, identity.tabId)
if (!source) {
return null
}
const layout = state.terminalLayoutsByTabId[identity.tabId]
// Why: web-only mirrors keep their host's existing status publication path.
if (isWebOnlyMirroredTerminalTab(source.tab, layout)) {
return null
}
const mounted = findRegisteredTerminalTab(identity.tabId, source.worktreeId)?.tab
const numericId = mounted?.getManager()?.getNumericIdForLeaf(identity.leafId)
const rendererPtyId = rendererTerminalBinding(
numericId ?? null,
numericId == null ? null : mounted!.getPtyIdForPane(numericId),
layout?.ptyIdsByLeafId?.[identity.leafId],
() => countSavedTerminalLeavesUpToTwo(layout),
source.tab.ptyId
)
return { paneKey: key, leafId: identity.leafId, rendererPtyId, row }
},
() => store.getState().agentStatusByPaneKey.keys(),
(batch) => window.api.runtime.syncAgentStatus(batch),
publicationCursor,
requestGraphSync
)
sender = publication
const unsubscribeRows = store
.getState()
.agentStatusByPaneKey.subscribeChanges((keys) => publication.changed(keys))
const changedTab = (tabId: string): void =>
publication.changed(new Set(store.getState().agentStatusByPaneKey.keysForTab(tabId)))
const unsubscribeMounts = subscribeMountedTerminalTabChanges((tab) => {
if (tab) {
changedTab(tab.tabId)
}
})
return () => {
unsubscribeRows()
unsubscribeMounts()
publication.stop()
if (sender === publication) {
sender = undefined
}
}
}
@@ -0,0 +1,127 @@
import { beforeEach, afterEach, expect, it, vi } from 'vitest'
import { RendererStatusSender } from './renderer-status-sender'
import type {
RendererStatusAck,
RendererStatusPublication,
RendererStatusRecord
} from '../../../../shared/agent-status/renderer-status-publication'
beforeEach(() => vi.useFakeTimers())
afterEach(() => {
vi.clearAllTimers()
vi.useRealTimers()
})
it('preserves post-capture changes and binding removals across an in-flight snapshot and resync', async () => {
let current: RendererStatusRecord = {
paneKey: 'tab:leaf',
leafId: 'leaf',
rendererPtyId: 'A',
row: {
state: 'working',
prompt: 'first',
updatedAt: 10,
stateStartedAt: 10,
stateHistory: [],
paneKey: 'tab:leaf'
}
}
const batches: RendererStatusPublication[] = []
let acknowledge: ((ack: RendererStatusAck) => void) | undefined
const cursor = { seq: 0 }
const sender = new RendererStatusSender(
'renderer',
() => current,
() => ['tab:leaf'],
(batch) => {
batches.push(batch)
return new Promise((resolve) => {
acknowledge = resolve
})
},
cursor
)
sender.graphAccepted()
await vi.advanceTimersByTimeAsync(16)
current = { ...current, rendererPtyId: 'B', row: { ...current.row!, prompt: 'latest' } }
sender.changed(new Set(['tab:leaf']))
acknowledge!({ accepted: true })
await vi.advanceTimersByTimeAsync(16)
expect(batches.map((batch) => [batch.type, batch.seq])).toEqual([
['snapshot', 1],
['changes', 2]
])
expect(batches[0].rows[0].row?.prompt).toBe('first')
expect(
batches[1].rows.map((record) => [record.rendererPtyId, record.row?.prompt ?? null])
).toEqual([
['A', null],
['B', 'latest']
])
acknowledge!({ accepted: false, snapshotRequired: true })
await vi.advanceTimersToNextTimerAsync()
expect(batches[2]).toMatchObject({
type: 'snapshot',
seq: 3,
rows: [{ rendererPtyId: 'B', row: { prompt: 'latest' } }]
})
acknowledge!({ accepted: true })
sender.stop()
const restarted = new RendererStatusSender(
'renderer',
() => current,
() => ['tab:leaf'],
async (batch) => {
batches.push(batch)
return { accepted: true }
},
cursor
)
restarted.graphAccepted()
await vi.advanceTimersByTimeAsync(16)
expect(batches[3]).toMatchObject({ type: 'snapshot', seq: 4 })
restarted.stop()
})
it('recovers a rejected Promise with a snapshot and re-arms a superseded sender on the next accepted graph', async () => {
const batches: RendererStatusPublication[] = []
let attempt = 0
const send = vi.fn(async (batch: RendererStatusPublication): Promise<RendererStatusAck> => {
batches.push(batch)
if (++attempt === 1) {
throw new Error('IPC unavailable')
}
return attempt === 3 ? { accepted: false, reason: 'superseded' } : { accepted: true }
})
const requestGraph = vi.fn()
const sender = new RendererStatusSender(
'old',
() => null,
() => [],
send,
{ seq: 0 },
requestGraph
)
sender.changed(null)
expect(requestGraph).toHaveBeenCalledTimes(1)
sender.graphAccepted()
await vi.advanceTimersToNextTimerAsync()
await vi.advanceTimersToNextTimerAsync()
expect(batches.map((batch) => batch.type)).toEqual(['snapshot', 'snapshot'])
sender.changed(null)
expect(requestGraph).toHaveBeenCalledTimes(1)
await vi.advanceTimersToNextTimerAsync()
sender.changed(null)
await vi.runAllTimersAsync()
expect(send).toHaveBeenCalledTimes(3)
expect(requestGraph).toHaveBeenCalledTimes(2)
sender.graphAccepted()
await vi.runAllTimersAsync()
expect(batches.map((batch) => batch.type)).toEqual([
'snapshot',
'snapshot',
'snapshot',
'snapshot'
])
sender.stop()
})
@@ -0,0 +1,142 @@
import type {
RendererStatusAck,
RendererStatusPublication,
RendererStatusRecord
} from '../../../../shared/agent-status/renderer-status-publication'
import { rendererStatusOccupantKey } from '../../../../shared/agent-status/renderer-status-publication'
/** One in-flight batch; mutations after capture stay queued under a later sequence. */
export class RendererStatusSender {
private pending = new Map<string, RendererStatusRecord>()
private last = new Map<string, RendererStatusRecord>()
private snapshot = true
private timer: ReturnType<typeof setTimeout> | undefined
private inFlight = false
private active = false
private stopped = false
private retryDelay = 0
constructor(
private readonly epoch: string,
private readonly capture: (key: string) => RendererStatusRecord | null,
private readonly keys: () => Iterable<string>,
private readonly send: (batch: RendererStatusPublication) => Promise<RendererStatusAck>,
private readonly cursor = { seq: 0 },
private readonly requestGraph: () => void = () => undefined
) {}
graphAccepted(): void {
if (this.stopped) {
return
}
this.active = true
this.schedule()
}
changed(keys: ReadonlySet<string> | null): void {
if (this.stopped) {
return
}
// Why: a pending snapshot recaptures every row, so staging would only pile up while parked.
if (keys === null || this.snapshot) {
this.snapshot = true
} else {
for (const key of keys) {
this.stage(key)
}
}
// Why: only an accepted graph sync activates the sender, so a failed or rejected one must be retried.
if (!this.active) {
this.requestGraph()
}
this.schedule()
}
private stage(key: string): void {
const current = this.capture(key)
const previous = this.last.get(key)
if (
previous &&
(!current || rendererStatusOccupantKey(previous) !== rendererStatusOccupantKey(current))
) {
this.pending.set(rendererStatusOccupantKey(previous), { ...previous, row: null })
}
if (current) {
this.pending.set(rendererStatusOccupantKey(current), current)
this.last.set(key, current)
} else {
this.last.delete(key)
}
}
private schedule(): void {
if (
!this.active ||
this.stopped ||
this.inFlight ||
this.timer ||
(!this.snapshot && !this.pending.size)
) {
return
}
// Hidden renderers still publish; animation frames may be suspended indefinitely.
this.timer = setTimeout(
() => {
this.timer = undefined
void this.flush()
},
Math.max(16, this.retryDelay)
)
}
private async flush(): Promise<void> {
const snapshot = this.snapshot
this.snapshot = false
let rows: RendererStatusRecord[]
if (snapshot) {
rows = []
this.last.clear()
for (const key of this.keys()) {
const record = this.capture(key)
if (record) {
rows.push(record)
this.last.set(key, record)
}
}
} else {
rows = [...this.pending.values()]
}
this.pending.clear()
this.inFlight = true
try {
const ack = await this.send({
type: snapshot ? 'snapshot' : 'changes',
epoch: this.epoch,
seq: ++this.cursor.seq,
rows
})
if (!ack.accepted && ack.reason === 'superseded') {
this.active = false
this.snapshot = true
return
}
this.retryDelay = ack.accepted ? 0 : Math.min(2000, (this.retryDelay || 50) * 2)
if (ack.snapshotRequired || !ack.accepted) {
this.snapshot = true
}
} catch {
this.retryDelay = Math.min(2000, (this.retryDelay || 50) * 2)
this.snapshot = true
} finally {
this.inFlight = false
this.schedule()
}
}
stop(): void {
this.stopped = true
clearTimeout(this.timer)
this.pending.clear()
this.last.clear()
}
}
@@ -18,16 +18,18 @@ export type RegisteredTerminalTabKey = string
const registeredTabs = new Map<RegisteredTerminalTabKey, RegisteredTerminalTab>()
const tabRegisteredAt = new Map<RegisteredTerminalTabKey, number>()
const changeListeners = new Set<() => void>()
const changeListeners = new Set<(tab?: RegisteredTerminalTab) => void>()
function notifyMountedTerminalTabsChanged(): void {
function notifyMountedTerminalTabsChanged(tab: RegisteredTerminalTab): void {
for (const listener of changeListeners) {
listener()
listener(tab)
}
}
/** Called on mount, unmount, and an explicit leaf focus. */
export function subscribeMountedTerminalTabChanges(listener: () => void): () => void {
export function subscribeMountedTerminalTabChanges(
listener: (tab?: RegisteredTerminalTab) => void
): () => void {
changeListeners.add(listener)
return () => {
changeListeners.delete(listener)
@@ -86,7 +88,7 @@ export function registerRuntimeTerminalTab(tab: RegisteredTerminalTab): () => vo
const key = registeredTerminalTabKey(tab.worktreeId, tab.tabId)
registeredTabs.set(key, tab)
tabRegisteredAt.set(key, Date.now())
notifyMountedTerminalTabsChanged()
notifyMountedTerminalTabsChanged(tab)
return () => {
// React can mount a replacement before the old effect cleans up.
if (registeredTabs.get(key) !== tab) {
@@ -94,7 +96,7 @@ export function registerRuntimeTerminalTab(tab: RegisteredTerminalTab): () => vo
}
registeredTabs.delete(key)
tabRegisteredAt.delete(key)
notifyMountedTerminalTabsChanged()
notifyMountedTerminalTabsChanged(tab)
}
}
@@ -131,6 +133,6 @@ export function focusRuntimeTerminalSurface(
manager.setActivePane(resolution.numericPaneId, {
focus: !paneIsCoveredByNativeChat(requestedPane)
})
notifyMountedTerminalTabsChanged()
notifyMountedTerminalTabsChanged(registered!)
return true
}
@@ -1,56 +0,0 @@
import type { AppState } from '@/store/types'
import type { AgentMainAgentStatus } from '../../../../shared/agent-status/lifecycle/main-agent-status'
import { programStatusFacetContent } from '../../../../shared/program-status/facet'
const AGENT_STATUS_SYNC_UPDATED_AT_BUCKET_MS = 30_000
function mainAgentKey(mainAgent: AgentMainAgentStatus | undefined) {
return mainAgent ? [mainAgent.state, mainAgent.outcome ?? null, mainAgent.stateStartedAt] : null
}
export function serializeAgentStatusEntry(
paneKey: string,
entry: NonNullable<ReturnType<AppState['agentStatusByPaneKey']['get']>>
): string {
return JSON.stringify({
paneKey,
paneSleep: entry.paneSleep ?? null,
entryPaneKey: entry.paneKey,
state: entry.state,
workingMode: entry.workingMode ?? null,
prompt: entry.prompt,
updatedAtBucket: Math.floor(entry.updatedAt / AGENT_STATUS_SYNC_UPDATED_AT_BUCKET_MS),
stateStartedAt: entry.stateStartedAt,
turnStartedAt: entry.turnStartedAt ?? null,
turnEndedAt: entry.turnEndedAt ?? null,
turnEndDisposition: entry.turnEndDisposition ?? null,
agentType: entry.agentType ?? null,
terminalTitle: entry.terminalTitle ?? null,
stateHistory: entry.stateHistory.map((history) => ({
state: history.state,
prompt: history.prompt,
startedAt: history.startedAt,
interrupted: history.interrupted ?? null,
mainAgent: mainAgentKey(history.mainAgent)
})),
toolName: entry.toolName ?? null,
toolInput: entry.toolInput ?? null,
// Include the prompt so a newly captured question re-fires mobile publication.
interactivePrompt: entry.interactivePrompt ?? null,
lastAssistantMessage: entry.lastAssistantMessage ?? null,
lastAssistantMessageIsToolOutput: entry.lastAssistantMessageIsToolOutput ?? null,
interrupted: entry.interrupted ?? null,
// A failure changes the verdict and leaves `interrupted` as it was.
mainAgent: mainAgentKey(entry.mainAgent),
programStatus: entry.programStatus ? programStatusFacetContent(entry.programStatus) : null,
// Undefined drops out of the JSON; null (host can name it, has not yet) stays distinct.
orcaSessionId: entry.orcaSessionId
})
}
/** Equality token is advanced at the accepted-key publication seam, never by rescanning rows. */
export function buildRuntimeMobileAgentStatusProjection(
agentStatusByPaneKey: AppState['agentStatusByPaneKey']
): object {
return agentStatusByPaneKey.mobileToken
}
@@ -1,3 +1,4 @@
import { rendererStatusGraphAccepted } from '../agent-status/renderer-status-publication'
import { getEagerPtyBufferHandle } from '@/components/terminal-pane/pty-transport/delivery/pty-dispatcher'
import { warnTerminalLifecycleAnomaly } from '@/components/terminal-pane/layout/reconciliation/terminal-lifecycle-diagnostics'
import {
@@ -231,6 +232,7 @@ export async function syncRuntimeGraph(): Promise<void> {
try {
const result = await window.api.runtime.syncWindowGraph(graph)
rendererStatusGraphAccepted()
graphState.publishedTerminalGroupGridSizesKey = JSON.stringify(gridSizes ?? null)
graphState.publishedProjectSectionCatalog =
projectSectionCatalog ?? graphState.publishedProjectSectionCatalog
@@ -1,4 +1,3 @@
import { acceptedAgentStatuses } from '@/store/slices/agent-status/accepted-agent-statuses'
import type { MobileProjectSectionCatalog } from '../../../../shared/mobile-project-sections-contract'
import { createNonSecureContextUuid as createBrowserUuid } from '../../../../shared/identifiers/non-secure-context-uuid'
import type { AppState } from '@/store/types'
@@ -21,8 +20,6 @@ export const EMPTY_ACTIVE_BROWSER_TAB_ID_BY_WORKTREE: AppState['activeBrowserTab
export const EMPTY_BROWSER_TABS_BY_WORKTREE: AppState['browserTabsByWorktree'] = {}
export const EMPTY_BROWSER_PAGES_BY_WORKSPACE: AppState['browserPagesByWorkspace'] = {}
export const EMPTY_LAYOUT_BY_WORKTREE: AppState['layoutByWorktree'] = {}
export const EMPTY_AGENT_STATUS_BY_PANE_KEY: AppState['agentStatusByPaneKey'] =
acceptedAgentStatuses()
export const EMPTY_NARROWED_BY_KEY: ReadonlyMap<string, never> = new Map<string, never>()
export const EMPTY_WORKTREE_TERMINAL_TABS: AppState['tabsByWorktree'][string] = []
export const EMPTY_WORKTREE_BROWSER_WORKSPACES: AppState['browserTabsByWorktree'][string] = []
@@ -175,7 +175,6 @@ export function canReuseMobileSessionSnapshot(
narrowedEntriesEqual(previous.terminalLayoutByTabId, next.terminalLayoutByTabId) &&
narrowedEntriesEqual(previous.paneTitlesByTabId, next.paneTitlesByTabId) &&
narrowedEntriesEqual(previous.launchDraftByPaneKey, next.launchDraftByPaneKey) &&
narrowedEntriesEqual(previous.agentStatusByPaneKey, next.agentStatusByPaneKey) &&
narrowedEntriesEqual(previous.editorDraftVersionByFileId, next.editorDraftVersionByFileId) &&
narrowedEntriesEqual(previous.pagesByBrowserWorkspaceId, next.pagesByBrowserWorkspaceId) &&
narrowedEntriesEqual(
@@ -21,7 +21,6 @@ import {
graphState
} from './graph-state'
import type {
MobileSessionAgentStatusByWorktree,
MobileSessionPublicationInputs,
MobileSessionWorktreeInputs,
OpenFileIndexes
@@ -113,13 +112,6 @@ export function excludeCrossPlacedEditorFiles(
return result
}
export function buildMobileSessionAgentStatusByWorktree(
agentStatusByPaneKey: AppState['agentStatusByPaneKey'],
_tabsByWorktree: AppState['tabsByWorktree']
): MobileSessionAgentStatusByWorktree {
return agentStatusByPaneKey.projection.mobileSnapshots(agentStatusByPaneKey)
}
// Bare IDs collide across hosts (STA-4343); ambiguous ownership omits identity so main uses generation fences rather than blanks mobile.
function resolveWorktreeInstanceId(state: AppState, worktreeId: string): string | undefined {
const rows = getIndexedWorktreesById(selectWorktreesByRepo(state) ?? {}, worktreeId)
@@ -193,8 +185,6 @@ export function buildMobileSessionWorktreeInputs(
mountedSurfaceCaptureByTabId,
launchDraftByTabId: narrowRecordByKeys(state.nativeChatLaunchDraftByTabId, terminalTabIds)
}),
agentStatusByPaneKey:
publication.agentStatusByWorktreeId.get(worktreeId) ?? EMPTY_NARROWED_BY_KEY,
editorDraftVersionByFileId: narrowMapByKeys(
publication.editorDraftVersionByFileId,
openFileIds
@@ -7,7 +7,6 @@ import {
mobilePublicationEpoch
} from './graph-state'
import {
buildMobileSessionAgentStatusByWorktree,
buildMobileSessionWorktreeInputs,
getOpenFileIndexes,
excludeCrossPlacedEditorFiles
@@ -55,10 +54,6 @@ export function buildMobileSessionTabSnapshots(
browserTabsByWorktree,
openFileIndexes,
editorDraftVersionByFileId: getEditorDraftVersionByFileId(state.editorDrafts, state.openFiles),
agentStatusByWorktreeId: buildMobileSessionAgentStatusByWorktree(
state.agentStatusByPaneKey ?? {},
state.tabsByWorktree
),
generatedTitlesEnabled: state.settings?.tabAutoGenerateTitle === true,
terminalTheme: getMobileTerminalTheme(state, systemPrefersDark)
}
@@ -46,6 +46,54 @@ export function getRuntimeLeafIdsForTerminal(
return []
}
export function rendererTerminalBinding(
numericPaneId: number | null,
livePtyId: string | null | undefined,
savedPtyId: string | null | undefined,
leafCount: number | (() => number),
tabPtyId: string | null | undefined
): string | null {
if (numericPaneId !== null) {
return livePtyId ?? savedPtyId ?? null
}
if (savedPtyId != null) {
return savedPtyId
}
if (tabPtyId == null) {
return null
}
return (typeof leafCount === 'function' ? leafCount() : leafCount) === 1 ? tabPtyId : null
}
const savedTerminalLeafCountByRoot = new WeakMap<object, number>()
/** Saved terminal leaves counted up to 2: the binding only asks "exactly one?". */
export function countSavedTerminalLeavesUpToTwo(
savedLayout: AppState['terminalLayoutsByTabId'][string] | undefined
): number {
const root = savedLayout?.root
if (!root) {
return 0
}
// Why: saved layouts are immutable store values, so status churn reuses the count.
const cached = savedTerminalLeafCountByRoot.get(root)
if (cached !== undefined) {
return cached
}
let count = 0
const stack = [root]
while (stack.length > 0 && count < 2) {
const node = stack.pop()!
if (node.type === 'leaf') {
count += isTerminalLeafId(node.leafId) ? 1 : 0
} else {
stack.push(node.second, node.first)
}
}
savedTerminalLeafCountByRoot.set(root, count)
return count
}
export function resolveMobileTabWideAgentHintLeafId(
capture: MountedTerminalSurfaceCapture | undefined,
savedLayout: AppState['terminalLayoutsByTabId'][string] | undefined
@@ -8,10 +8,10 @@ import {
nativeChatLaunchAgentForLeaf
} from '../../components/native-chat/pane/routing/native-chat-leaf-routing'
import type { MobileSessionWorktreeInputs } from './types'
import { isClaudeManagementTitle } from '../../../../shared/agent-status/title/agent-title-core'
import { isTerminalLeafId, makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id'
import {
mobileTerminalSurfaceId,
rendererTerminalBinding,
getRuntimeLeafIdsForTerminal,
resolveMobileTabWideAgentHintLeafId,
isUnifiedTabActiveInActiveGroup
@@ -62,10 +62,13 @@ export function buildMobileTerminalSurfaceTabs(
return leafIds.map((leafId) => {
const numericPaneId = capture?.numericPaneIdByLeafId.get(leafId) ?? null
const ptyId =
numericPaneId === null
? (savedPtyIdsByLeafId[leafId] ?? (leafIds.length === 1 ? terminal.ptyId : null))
: (capture?.ptyIdByNumericPaneId.get(numericPaneId) ?? savedPtyIdsByLeafId[leafId] ?? null)
const ptyId = rendererTerminalBinding(
numericPaneId,
numericPaneId === null ? null : capture?.ptyIdByNumericPaneId.get(numericPaneId),
savedPtyIdsByLeafId[leafId],
leafIds.length,
terminal.ptyId
)
const legacyPaneId = numericPaneId === null ? /^pane:(\d+)$/.exec(leafId)?.[1] : null
const paneTitle =
numericPaneId !== null
@@ -85,10 +88,6 @@ export function buildMobileTerminalSurfaceTabs(
)
: (leafTitle ?? 'Terminal')
const agentStatusTitle = leafTitle ?? (tabWideFallbackSafe ? terminal.title : '') ?? ''
const agentStatus =
paneKey && !isClaudeManagementTitle(agentStatusTitle)
? inputs.agentStatusByPaneKey.get(paneKey)
: undefined
const launchAgent = nativeChatLaunchAgentForLeaf({
launchAgent: terminal.launchAgent,
launchAgentLeafId,
@@ -123,7 +122,7 @@ export function buildMobileTerminalSurfaceTabs(
leafId,
ptyId,
...(inputs.terminalTheme ? { terminalTheme: inputs.terminalTheme } : {}),
...(agentStatus ? { agentStatus } : {}),
statusSuppressionTitle: agentStatusTitle,
...(launchAgent ? { launchAgent } : {}),
...(publishedLaunchDraft
? {
@@ -1,12 +1,10 @@
import { getSystemPrefersDark } from '@/lib/terminal/appearance/terminal-theme'
import {
EMPTY_ACTIVE_BROWSER_TAB_ID_BY_WORKTREE,
EMPTY_AGENT_STATUS_BY_PANE_KEY,
EMPTY_BROWSER_PAGES_BY_WORKSPACE,
EMPTY_BROWSER_TABS_BY_WORKTREE,
EMPTY_LAYOUT_BY_WORKTREE
} from './graph-state'
import { buildRuntimeMobileAgentStatusProjection } from './agent-status-projection'
import {
buildRuntimeMobileBrowserProjection,
buildRuntimeMobileEditorDraftsProjection,
@@ -61,9 +59,7 @@ export function canSkipRuntimeMobileSessionSyncKeyBuild(
state.terminalLayoutsByTabId === previousState.terminalLayoutsByTabId &&
state.runtimePaneTitlesByTabId === previousState.runtimePaneTitlesByTabId &&
state.nativeChatLaunchDraftByTabId === previousState.nativeChatLaunchDraftByTabId &&
selectFolderWorkspaces(state) === selectFolderWorkspaces(previousState) &&
state.agentStatusEpoch === previousState.agentStatusEpoch &&
state.agentStatusByPaneKey === previousState.agentStatusByPaneKey
selectFolderWorkspaces(state) === selectFolderWorkspaces(previousState)
)
}
@@ -77,16 +73,12 @@ export function getRuntimeMobileSessionSyncKey(
const themeSystemPrefersDark = getTerminalThemeSystemPrefersDark(state, systemPrefersDark)
const browserTabsByWorktree = getBrowserTabsByWorktree(state)
const browserPagesByWorkspace = getBrowserPagesByWorkspace(state)
const agentStatusByPaneKey = state.agentStatusByPaneKey ?? EMPTY_AGENT_STATUS_BY_PANE_KEY
const previousBrowserTabsByWorktree = previousState
? getBrowserTabsByWorktree(previousState)
: EMPTY_BROWSER_TABS_BY_WORKTREE
const previousBrowserPagesByWorkspace = previousState
? getBrowserPagesByWorkspace(previousState)
: EMPTY_BROWSER_PAGES_BY_WORKSPACE
const previousAgentStatusByPaneKey = previousState
? (previousState.agentStatusByPaneKey ?? EMPTY_AGENT_STATUS_BY_PANE_KEY)
: EMPTY_AGENT_STATUS_BY_PANE_KEY
return {
terminalLayoutsByTabId: state.terminalLayoutsByTabId,
runtimePaneTitlesByTabId: state.runtimePaneTitlesByTabId,
@@ -104,11 +96,6 @@ export function getRuntimeMobileSessionSyncKey(
activeTabId: state.activeTabId,
activeBrowserTabIdByWorktree:
state.activeBrowserTabIdByWorktree ?? EMPTY_ACTIVE_BROWSER_TAB_ID_BY_WORKTREE,
agentStatusEpoch: state.agentStatusEpoch ?? 0,
agentStatusProjection:
canReusePrevious && agentStatusByPaneKey === previousAgentStatusByPaneKey
? previousKey.agentStatusProjection
: buildRuntimeMobileAgentStatusProjection(agentStatusByPaneKey),
generatedTabTitlesEnabled: state.settings?.tabAutoGenerateTitle === true,
systemPrefersDark: themeSystemPrefersDark,
terminalThemeProjection:
@@ -178,8 +165,6 @@ export function runtimeMobileSessionSyncKeysEqual(
a.activeTabTypeByWorktree === b.activeTabTypeByWorktree &&
a.activeTabId === b.activeTabId &&
a.activeBrowserTabIdByWorktree === b.activeBrowserTabIdByWorktree &&
a.agentStatusEpoch === b.agentStatusEpoch &&
a.agentStatusProjection === b.agentStatusProjection &&
a.generatedTabTitlesEnabled === b.generatedTabTitlesEnabled &&
a.systemPrefersDark === b.systemPrefersDark &&
a.terminalThemeProjection === b.terminalThemeProjection &&
@@ -0,0 +1,154 @@
import { acceptedAgentStatuses } from '@/store/slices/agent-status/accepted-agent-statuses'
import { expect, it } from 'vitest'
import { buildMobileSessionTabSnapshots } from './mobile-session-snapshots'
import { registerRuntimeTerminalTab } from '../hosted-terminals/mounted-surfaces/mounted-terminal-tab-registry'
import type { AppState } from '../../store/types'
// Distinct ids per test: the snapshot memo is module state shared in this file.
const MOUNTED_WT = 'repo::/mounted-wt-0'
const CONTROL_WT = 'repo::/mounted-wt-1'
const MOUNTED_LEAF_ID = 'aaaaaaaa-1111-4111-8111-111111111111'
const SPLIT_LEAF_ID = 'bbbbbbbb-1111-4111-8111-111111111111'
function makeMountedState(tabIdPrefix: string): {
state: AppState
mountedTabId: string
} {
const mountedTabId = `${tabIdPrefix}-term-0`
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: snapshot publication reads only this fixture's populated state fields.
const state = {
tabsByWorktree: {
[MOUNTED_WT]: [
{
id: mountedTabId,
customTitle: null,
ptyId: null,
title: 'Agent mounted'
}
],
[CONTROL_WT]: [
{ id: `${tabIdPrefix}-term-1`, title: 'Agent control', customTitle: null, ptyId: null }
]
},
terminalLayoutsByTabId: {
[mountedTabId]: {
root: { type: 'leaf', leafId: MOUNTED_LEAF_ID },
activeLeafId: MOUNTED_LEAF_ID,
expandedLeafId: null,
ptyIdsByLeafId: { [MOUNTED_LEAF_ID]: 'pty-saved-1' }
}
},
runtimePaneTitlesByTabId: {},
groupsByWorktree: {},
activeGroupIdByWorktree: {},
unifiedTabsByWorktree: {},
tabBarOrderByWorktree: {},
activeFileId: null,
activeFileIdByWorktree: {},
openFiles: [],
editorDrafts: {},
activeTabId: null,
agentStatusByPaneKey: acceptedAgentStatuses(Object.entries({})),
browserTabsByWorktree: {}
} as unknown as AppState
return {
state,
mountedTabId
}
}
function makeLiveSurface(tabId: string): {
registration: Parameters<typeof registerRuntimeTerminalTab>[0]
setPtyId: (paneId: number, ptyId: string) => void
addPane: (paneId: number, leafId: string) => void
} {
const panes = [{ id: 1, leafId: MOUNTED_LEAF_ID }]
const ptyIdByPaneId = new Map<number, string | null>([[1, 'pty-live-1']])
const manager = {
getPanes: () => panes.map((pane) => ({ ...pane })),
getActivePane: () => panes[0] ?? null,
getLeafId: (paneId: number) => panes.find((pane) => pane.id === paneId)?.leafId ?? null,
getNumericIdForLeaf: (leafId: string) =>
panes.find((pane) => pane.leafId === leafId)?.id ?? null
}
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this surface supplies the manager and PTY readers used by snapshot publication.
const registration = {
tabId,
worktreeId: MOUNTED_WT,
getManager: () => manager,
getContainer: () => null,
getPtyIdForPane: (paneId: number) => ptyIdByPaneId.get(paneId) ?? null,
getTabWideAgentHintLeafId: () => MOUNTED_LEAF_ID
} as unknown as Parameters<typeof registerRuntimeTerminalTab>[0]
return {
registration,
setPtyId: (paneId, ptyId) => {
ptyIdByPaneId.set(paneId, ptyId)
},
addPane: (paneId, leafId) => {
panes.push({ id: paneId, leafId })
ptyIdByPaneId.set(paneId, `pty-live-${paneId}`)
}
}
}
function snapshotsByWorktree(
state: AppState
): Map<string, ReturnType<typeof buildMobileSessionTabSnapshots>[number]> {
return new Map(
buildMobileSessionTabSnapshots(state).map((snapshot) => [snapshot.worktree, snapshot])
)
}
it('keeps the exact status suppression title through pane, saved, tab and split fallback changes', async () => {
const { shapeMobileTerminalStatus } =
await import('../../../../shared/agent-status/mobile-terminal-status-shaping')
const { state, mountedTabId } = makeMountedState('suppression')
const entry = {
paneKey: `${mountedTabId}:${MOUNTED_LEAF_ID}`,
state: 'working' as const,
prompt: 'keep this turn',
updatedAt: 20,
stateStartedAt: 10,
stateHistory: []
}
const surface = makeLiveSurface(mountedTabId)
const unregister = registerRuntimeTerminalTab(surface.registration)
const shown = () => {
const tab = snapshotsByWorktree(state).get(MOUNTED_WT)!.tabs[0]
if (tab.type !== 'terminal') {
throw new Error('expected terminal surface')
}
expect(tab.agentStatus).toBeUndefined()
return shapeMobileTerminalStatus(entry, tab.statusSuppressionTitle!)?.prompt
}
try {
state.tabsByWorktree = {
...state.tabsByWorktree,
[MOUNTED_WT]: [{ ...state.tabsByWorktree[MOUNTED_WT][0], title: 'claude agents' }]
}
expect(shown()).toBeUndefined()
state.terminalLayoutsByTabId = {
...state.terminalLayoutsByTabId,
[mountedTabId]: {
...state.terminalLayoutsByTabId[mountedTabId],
titlesByLeafId: { [MOUNTED_LEAF_ID]: 'Claude' }
}
}
expect(shown()).toBe('keep this turn')
state.runtimePaneTitlesByTabId = { [mountedTabId]: { 1: 'claude agents' } }
expect(shown()).toBeUndefined()
state.runtimePaneTitlesByTabId = { [mountedTabId]: { 1: 'Claude' } }
expect(shown()).toBe('keep this turn')
state.runtimePaneTitlesByTabId = {}
state.terminalLayoutsByTabId = {
...state.terminalLayoutsByTabId,
[mountedTabId]: { ...state.terminalLayoutsByTabId[mountedTabId], titlesByLeafId: {} }
}
expect(shown()).toBeUndefined()
surface.addPane(2, SPLIT_LEAF_ID)
expect(shown()).toBe('keep this turn')
} finally {
unregister()
}
})
@@ -20,8 +20,6 @@ export type RuntimeMobileSessionSyncKey = {
activeTabTypeByWorktree: AppState['activeTabTypeByWorktree']
activeTabId: AppState['activeTabId']
activeBrowserTabIdByWorktree: AppState['activeBrowserTabIdByWorktree']
agentStatusEpoch: number
agentStatusProjection: object
generatedTabTitlesEnabled: boolean
systemPrefersDark: boolean | null
terminalThemeProjection: string
@@ -90,16 +88,11 @@ export type EditorDraftHashCache = {
entries: Map<string, EditorDraftHashCacheEntry>
hashByFileId: Map<string, string>
}
export type MobileSessionAgentStatusByWorktree = ReadonlyMap<
string,
ReadonlyMap<string, NonNullable<ReturnType<AppState['agentStatusByPaneKey']['get']>>>
>
/** Slices shared by every worktree in one publication; derived from `AppState` exactly once. */
export type MobileSessionPublicationInputs = {
browserTabsByWorktree: AppState['browserTabsByWorktree']
openFileIndexes: OpenFileIndexes
editorDraftVersionByFileId: ReadonlyMap<string, string>
agentStatusByWorktreeId: MobileSessionAgentStatusByWorktree
generatedTitlesEnabled: boolean
terminalTheme: RuntimeMobileTerminalTheme | undefined
}
@@ -134,10 +127,6 @@ export type MobileSessionWorktreeInputs = {
string,
NonNullable<AppState['nativeChatLaunchDraftByTabId']>[string]
>
agentStatusByPaneKey: ReadonlyMap<
string,
NonNullable<ReturnType<AppState['agentStatusByPaneKey']['get']>>
>
editorDraftVersionByFileId: ReadonlyMap<string, string>
pagesByBrowserWorkspaceId: ReadonlyMap<
string,
@@ -1,4 +1,3 @@
import { serializeAgentStatusEntry } from '@/runtime/sync-runtime-graph/agent-status-projection'
import { structuralValuesEqualIgnoringUndefined as equal } from '../../../../../shared/collections/structural-value-equality'
import { isAiVaultTitleAgent } from '../../../../../shared/ai-vault/contracts/ai-vault-session-title'
import { AgentStatusProjection } from './agent-status-projection'
@@ -11,7 +10,6 @@ export type AgentStatusReplacement = readonly [string, AgentStatusEntry | null]
export class AcceptedAgentStatuses implements ReadonlyMap<string, AgentStatusEntry> {
readonly [Symbol.toStringTag] = 'AcceptedAgentStatuses'
titleRevision = 0
mobileToken: object = {}
private pending: Map<string, AgentStatusEntry | null> | null = null
private operations: AgentStatusReplacement[] = []
private moved = new Set<string>()
@@ -59,7 +57,6 @@ export class AcceptedAgentStatuses implements ReadonlyMap<string, AgentStatusEnt
? this
: new AcceptedAgentStatuses(this.rows, this.projection, this.sleepingCount)
draft.titleRevision = this.titleRevision
draft.mobileToken = this.mobileToken
draft.pending ??= new Map()
for (const [key, value] of replacements) {
const prior = draft.get(key)
@@ -87,7 +84,6 @@ export class AcceptedAgentStatuses implements ReadonlyMap<string, AgentStatusEnt
? this
: new AcceptedAgentStatuses(this.rows, this.projection, this.sleepingCount)
draft.titleRevision = this.titleRevision
draft.mobileToken = this.mobileToken
draft.pending ??= new Map()
draft.refreshes = keys
return draft
@@ -152,16 +148,9 @@ export class AcceptedAgentStatuses implements ReadonlyMap<string, AgentStatusEnt
const titleChanged = changes.some(
(change) => !equal(fact(change.previous), fact(change.current))
)
const mobileChanged = changes.some(
({ paneKey, previous, current }) =>
(previous ? serializeAgentStatusEntry(paneKey, previous) : null) !==
(current ? serializeAgentStatusEntry(paneKey, current) : null)
)
const titleRevision = this.titleRevision + Number(titleChanged)
const mobileToken = mobileChanged ? {} : this.mobileToken
return () => {
this.titleRevision = titleRevision
this.mobileToken = mobileToken
for (const [key, value] of this.operations) {
if (value === null) {
this.rows.delete(key)
@@ -183,7 +172,6 @@ export class AcceptedAgentStatuses implements ReadonlyMap<string, AgentStatusEnt
this.sleepingCount
)
captured.titleRevision = this.titleRevision
captured.mobileToken = this.mobileToken
return captured
}
@@ -1,4 +1,7 @@
import * as mobileStatusProjection from '@/runtime/sync-runtime-graph/agent-status-projection'
import type { RendererStatusPublication } from '../../../../../shared/agent-status/renderer-status-publication'
import type { TerminalPaneLayoutNode } from '../../../../../shared/workspace-layout/terminal-tab-types'
import { registerRuntimeTerminalTab } from '@/runtime/hosted-terminals/mounted-surfaces/mounted-terminal-tab-registry'
import type { PaneManager } from '@/lib/pane-manager/pane-manager'
import { acceptedAgentStatuses } from '@/store/slices/agent-status/accepted-agent-statuses'
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest'
import type { AgentStatusEntry } from '../../../../../shared/agent-status/contracts/agent-status-types'
@@ -40,15 +43,13 @@ describe('setAgentStatuses', () => {
const rows = projection.list('wt-1')
const observed = vi.fn()
const stop = before.agentStatusByPaneKey.subscribe(FIRST_PANE, observed)
const serializer = vi
.spyOn(mobileStatusProjection, 'serializeAgentStatusEntry')
.mockImplementationOnce(() => {
throw new Error('cannot serialize status')
})
const serializer = vi.spyOn(projection, 'prepare').mockImplementationOnce(() => {
throw new Error('cannot prepare projection')
})
try {
expect(() =>
store.getState().setAgentStatus(FIRST_PANE, { state: 'done', prompt: 'Finished' })
).toThrow('cannot serialize status')
).toThrow('cannot prepare projection')
expect(store.getState()).toBe(before)
expect(before.agentStatusByPaneKey.get(FIRST_PANE)?.state).toBe('working')
expect(projection.list('wt-1')).toBe(rows)
@@ -59,6 +60,199 @@ describe('setAgentStatuses', () => {
}
})
it('reseeds an unchanged accepted row when its saved binding changes', async () => {
vi.useFakeTimers()
const batches: RendererStatusPublication[] = []
vi.stubGlobal('window', {
api: {
runtime: {
syncAgentStatus: async (batch: RendererStatusPublication) => {
batches.push(batch)
return { accepted: true }
}
}
}
})
const { startRendererStatusPublication, rendererStatusGraphAccepted } =
await import('@/runtime/agent-status/renderer-status-publication')
const store = seedBatchStore()
const leafId = FIRST_PANE.slice('tab-1:'.length)
const layout = {
root: { type: 'leaf' as const, leafId },
activeLeafId: leafId,
expandedLeafId: null,
ptyIdsByLeafId: { [leafId]: 'A' }
}
store.setState({ terminalLayoutsByTabId: { 'tab-1': layout } })
store.getState().setAgentStatus(FIRST_PANE, { state: 'working', prompt: 'same turn' })
const row = store.getState().agentStatusByPaneKey.get(FIRST_PANE)
const stop = startRendererStatusPublication(store, () => undefined)
try {
rendererStatusGraphAccepted()
await vi.advanceTimersByTimeAsync(16)
expect(batches.at(-1)?.rows).toEqual([
expect.objectContaining({
rendererPtyId: 'A',
row: expect.objectContaining({ prompt: 'same turn' })
})
])
store.setState({
terminalLayoutsByTabId: {
'tab-1': {
...layout,
ptyIdsByLeafId: { [leafId]: 'B' }
}
}
})
await vi.advanceTimersByTimeAsync(16)
expect(batches.at(-1)).toMatchObject({
type: 'changes',
rows: [
{ rendererPtyId: 'A', row: null },
{ rendererPtyId: 'B', row: { prompt: 'same turn' } }
]
})
expect(store.getState().agentStatusByPaneKey.get(FIRST_PANE)).toBe(row)
} finally {
stop()
}
})
// The changed-key capture must stay independent of the saved split width.
it.each([100, 1000])(
'resolves live and saved bindings before traversing %i saved leaves',
async (width) => {
vi.useFakeTimers()
const batches: RendererStatusPublication[] = []
vi.stubGlobal('window', {
api: {
runtime: {
syncAgentStatus: async (batch: RendererStatusPublication) => {
batches.push(batch)
return { accepted: true }
}
}
}
})
const { startRendererStatusPublication, rendererStatusGraphAccepted } =
await import('@/runtime/agent-status/renderer-status-publication')
const store = seedBatchStore()
const leafId = FIRST_PANE.slice('tab-1:'.length)
let visits = 0
const tree = (count: number, offset = 0): TerminalPaneLayoutNode =>
count === 1
? {
type: 'leaf',
get leafId() {
if (offset !== 0) {
visits++
}
return offset === 0
? leafId
: `11111111-1111-4111-8111-${String(offset).padStart(12, '0')}`
}
}
: {
type: 'split',
direction: 'horizontal',
first: tree(Math.floor(count / 2), offset),
second: tree(count - Math.floor(count / 2), offset + Math.floor(count / 2))
}
const layout = {
root: tree(width),
activeLeafId: leafId,
expandedLeafId: null,
ptyIdsByLeafId: { [leafId]: 'saved' }
}
store.setState({ terminalLayoutsByTabId: { 'tab-1': layout } })
store.getState().setAgentStatus(FIRST_PANE, { state: 'working', prompt: 'initial' })
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: capture only asks this fixture manager for the addressed numeric ID.
const manager = {
getNumericIdForLeaf: (id: string) => (id === leafId ? 1 : null)
} as PaneManager
const unregister = registerRuntimeTerminalTab({
tabId: 'tab-1',
worktreeId: 'wt-1',
getManager: () => manager,
getContainer: () => null,
getPtyIdForPane: () => 'live',
getTabWideAgentHintLeafId: () => leafId
})
const stop = startRendererStatusPublication(store, () => undefined)
try {
rendererStatusGraphAccepted()
await vi.advanceTimersByTimeAsync(16)
visits = 0
store.getState().setAgentStatus(FIRST_PANE, { state: 'working', prompt: 'mounted' })
await vi.advanceTimersByTimeAsync(16)
expect(batches.at(-1)?.rows).toMatchObject([
{ rendererPtyId: 'live', row: { prompt: 'mounted' } }
])
expect(visits).toBe(0)
unregister()
await vi.advanceTimersByTimeAsync(16)
visits = 0
store.getState().setAgentStatus(FIRST_PANE, { state: 'working', prompt: 'unmounted' })
await vi.advanceTimersByTimeAsync(16)
expect(batches.at(-1)?.rows).toMatchObject([
{ rendererPtyId: 'saved', row: { prompt: 'unmounted' } }
])
expect(visits).toBe(0)
store.setState({
tabsByWorktree: {
'wt-1': [makeTab({ id: 'tab-1', worktreeId: 'wt-1', title: 'pi', ptyId: 'sole-tab' })]
},
terminalLayoutsByTabId: { 'tab-1': { ...layout, root: tree(1), ptyIdsByLeafId: {} } }
})
await vi.advanceTimersByTimeAsync(16)
expect(batches.at(-1)?.rows).toMatchObject([
{ rendererPtyId: 'saved', row: null },
{ rendererPtyId: 'sole-tab', row: { prompt: 'unmounted' } }
])
store.setState({
tabsByWorktree: {
'wt-1': [makeTab({ id: 'tab-1', worktreeId: 'wt-1', title: 'pi', ptyId: null })]
},
terminalLayoutsByTabId: { 'tab-1': { ...layout, ptyIdsByLeafId: {} } }
})
await vi.advanceTimersByTimeAsync(16)
visits = 0
store.getState().setAgentStatus(FIRST_PANE, { state: 'working', prompt: 'unbound' })
await vi.advanceTimersByTimeAsync(16)
expect(batches.at(-1)?.rows).toMatchObject([
{ rendererPtyId: null, row: { prompt: 'unbound' } }
])
expect(visits).toBe(0)
const deep = (count: number): TerminalPaneLayoutNode =>
count === 1
? tree(1)
: {
type: 'split',
direction: 'horizontal',
first: deep(count - 1),
second: tree(1, count)
}
store.setState({
tabsByWorktree: {
'wt-1': [makeTab({ id: 'tab-1', worktreeId: 'wt-1', title: 'pi', ptyId: 'sole-tab' })]
},
terminalLayoutsByTabId: { 'tab-1': { ...layout, root: deep(width), ptyIdsByLeafId: {} } }
})
await vi.advanceTimersByTimeAsync(16)
visits = 0
store.getState().setAgentStatus(FIRST_PANE, { state: 'working', prompt: 'deep' })
await vi.advanceTimersByTimeAsync(16)
expect(batches.at(-1)?.rows).toMatchObject([
{ rendererPtyId: null, row: { prompt: 'deep' } }
])
expect(visits).toBe(0)
} finally {
stop()
unregister()
}
}
)
it('exposes cap evictions to later updates in the same transaction', () => {
const store = seedBatchStore()
const firstPane = 'orphan-tab:orphan-0'
@@ -18,6 +18,11 @@ export function publishProjectionTopology(
data.changedKeys.add(change.paneKey)
data.notices.add(`status\0${change.paneKey}`)
}
for (const tabId of topology.bindingTabs) {
for (const key of data.acceptedByTab.get(tabId) ?? []) {
data.changedKeys.add(key)
}
}
data.inputs = state
represented.commitInto(data.represented)
for (const [id, tab] of nextTabs) {
@@ -31,6 +31,7 @@ export function stageProjectionTopology(
)
)
const changedTabs = new Set<string>()
const bindingTabs = new Set<string>()
const acceptedKeys = new Set(changes.map((change) => change.paneKey))
const changedKeys = new Set([...acceptedKeys, ...refreshKeys])
const nextTabs = new Map<string, TerminalTab | null>()
@@ -52,6 +53,7 @@ export function stageProjectionTopology(
nextTabs.set(tab.id, null)
nextTabOwners.set(tab.id, null)
changedTabs.add(tab.id)
bindingTabs.add(tab.id)
}
for (const tab of state.tabsByWorktree[owner] ?? []) {
if (diff?.kind === 'addressed' && !diff.tabIds.has(tab.id)) {
@@ -60,6 +62,7 @@ export function stageProjectionTopology(
nextTabs.set(tab.id, tab)
nextTabOwners.set(tab.id, owner)
changedTabs.add(tab.id)
bindingTabs.add(tab.id)
}
}
}
@@ -113,6 +116,9 @@ export function stageProjectionTopology(
? diff.keys
: new Set([...Object.keys(previous?.[field] ?? {}), ...Object.keys(state[field] ?? {})])) {
changedTabs.add(tab)
if (field !== 'runtimePaneTitlesByTabId' && state[field][tab] !== previous?.[field][tab]) {
bindingTabs.add(tab)
}
}
}
for (const field of [
@@ -205,6 +211,7 @@ export function stageProjectionTopology(
previous,
moved,
changedTabs,
bindingTabs,
acceptedKeys,
changedKeys,
nextTabs,
@@ -122,6 +122,11 @@ export class AgentStatusProjection {
this.data.notifying = false
}
}
mobileSource(key: string, tabId: string) {
const worktreeId = this.data.mobileOwners.get(key)
const tab = this.data.tabs.get(tabId)
return worktreeId && tab ? { worktreeId, tab } : undefined
}
tabKeys(tabId: string): Iterable<string> {
return this.data.acceptedByTab.get(tabId) ?? []
}
@@ -10,6 +10,7 @@ import { noopUnsubscribe } from './web-storage'
export function createWebRuntimeApi(): NonNullable<Partial<PreloadApi>['runtime']> {
return {
syncAgentStatus: async () => ({ accepted: false, reason: 'superseded' }),
syncWindowGraph: async (_graph: RuntimeSyncWindowGraph) => getRemoteRuntimeStatus(),
getStatus: () => getRemoteRuntimeStatus(),
call: ({ method, params }) => callRuntimeEnvelope(method, params),
@@ -0,0 +1,23 @@
import type { AgentStatusEntry } from './contracts/agent-status-types'
import { isClaudeManagementTitle } from './title/agent-title-core'
import type { TerminalLayoutSnapshot } from '../workspace-layout/terminal-tab-types'
export function isTerminalTabWideFallbackSafe(
layout: TerminalLayoutSnapshot | null | undefined
): boolean {
if (!layout?.root) {
return true
}
if (layout.root.type === 'split') {
return false
}
return !layout.activeLeafId || layout.activeLeafId === layout.root.leafId
}
/** The renderer supplies its exact title input; display titles have different fallback rules. */
export function shapeMobileTerminalStatus(
row: AgentStatusEntry | undefined,
statusSuppressionTitle: string
): AgentStatusEntry | undefined {
return isClaudeManagementTitle(statusSuppressionTitle) ? undefined : row
}
@@ -0,0 +1,23 @@
import type { AgentStatusEntry } from './contracts/agent-status-types'
export type RendererStatusOccupant = {
paneKey: string
leafId: string
rendererPtyId: string | null
}
export type RendererStatusRecord = RendererStatusOccupant & { row: AgentStatusEntry | null }
export type RendererStatusPublication = {
type: 'snapshot' | 'changes'
epoch: string
seq: number
rows: RendererStatusRecord[]
}
export type RendererStatusAck = {
accepted: boolean
snapshotRequired?: boolean
reason?: 'superseded' | 'not-ready'
}
export function rendererStatusOccupantKey(occupant: RendererStatusOccupant): string {
return JSON.stringify([occupant.paneKey, occupant.leafId, occupant.rendererPtyId])
}
@@ -27,6 +27,8 @@ export type RuntimeMobileSessionTerminalTab = {
/** Host-owned PTY incarnation used to fence remote identity observations. */
incarnationId?: string | null
terminalTheme?: RuntimeMobileTerminalTheme
/** Same-build renderer graph input; main never returns this in client frames. */
statusSuppressionTitle?: string
agentStatus?: AgentStatusEntry | null
/** Event-only lead-turn end time for paired clients; never persisted in AgentStatusEntry. */
turnCompletedAt?: number