diff --git a/config/scripts/test-runtime/sqlite-admission/vitest-sqlite-runtime-scan.mjs b/config/scripts/test-runtime/sqlite-admission/vitest-sqlite-runtime-scan.mjs index b52d995ed1c..290f657819b 100644 --- a/config/scripts/test-runtime/sqlite-admission/vitest-sqlite-runtime-scan.mjs +++ b/config/scripts/test-runtime/sqlite-admission/vitest-sqlite-runtime-scan.mjs @@ -21,6 +21,7 @@ const SQLITE_HARNESSES = new Set([ 'journal-host-database-test-support', 'terminal-topology-profile-fixture', 'acknowledged-terminal-tab-retirement-fixture', + 'last-status.test-fixtures', // Opens the index read-only after the indexer closes; Bun's macOS SQLite refuses a WAL file then. 'session-search-indexer-test-fixture', 'session-search-index-test-fixture', diff --git a/src/main/agent-hooks/server/testing/persistence/server-last-status-migration.test.ts b/src/main/agent-hooks/server/testing/persistence/server-last-status-migration.test.ts index d11d5b340ed..248abb7652e 100644 --- a/src/main/agent-hooks/server/testing/persistence/server-last-status-migration.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-last-status-migration.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { AgentHookServer, _internals } from '../../agent-hook-server' import { recentTs, PANE } from '../server.test-fixtures' -import { holdSavedStatusLock } from './last-status.test-fixtures' +import { holdSavedStatusLock, readSavedStatus } from './last-status.test-fixtures' vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) vi.mock('../../../../telemetry/cohort-classifier', () => ({ @@ -73,6 +73,61 @@ describe('saved agent status from an older build', () => { expect(existsSync(lastStatusPath())).toBe(false) }) + it('never reports disabled writes saved and resumes from authoritative rows with the next writer', async () => { + writeLegacyFile('protected original') + const release = holdSavedStatusLock(lastStatusPath()) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const server = new AgentHookServer() + await server.start({ env: 'production', userDataPath }) + release() + try { + for (let index = 0; index < 100; index++) { + const paneKey = `disabled-${index}:11111111-1111-4111-8111-111111111111` + server.recordLaunchResumeIdentity({ + paneKey, + agentType: 'codex', + providerSession: { key: 'session_id', id: `session-${index}` }, + launchedAt: 1 + }) + server.dropStatusEntry(paneKey, { preserveResumeIdentity: false }) + } + server.ingestTerminalStatus({ + paneKey: PANE, + payload: { + state: 'done', + prompt: 'uncommitted session', + agentType: 'codex' + } + }) + expect(server.flushStatusPersistSync()).toBe(false) + } finally { + server.stop() + vi.restoreAllMocks() + } + expect(existsSync(lastStatusPath())).toBe(true) + + const next = new AgentHookServer() + await next.start({ env: 'production', userDataPath }) + try { + expect(next.getStatusSnapshot().map((row) => row.prompt)).toEqual(['protected original']) + next.ingestTerminalStatus({ + paneKey: PANE, + payload: { + state: 'working', + prompt: 'recovered writer', + agentType: 'claude' + } + }) + expect(next.flushStatusPersistSync()).toBe(true) + expect(JSON.parse(readSavedStatus(lastStatusPath())).entries[PANE].payload.prompt).toBe( + 'recovered writer' + ) + } finally { + next.stop() + } + expect(await restoredPrompt()).toBe('recovered writer') + }) + it('keeps the saved rows when an old file is rejected', async () => { writeLegacyFile('saved in rows') expect(await restoredPrompt()).toBe('saved in rows') diff --git a/src/main/runtime/orca-runtime-saved-restore-launch.test.ts b/src/main/runtime/orca-runtime-saved-restore-launch.test.ts index fd03c943bd2..bed26383d17 100644 --- a/src/main/runtime/orca-runtime-saved-restore-launch.test.ts +++ b/src/main/runtime/orca-runtime-saved-restore-launch.test.ts @@ -50,7 +50,8 @@ function restoreOnHost(args: { getWorkspaceSessionForWorktree: () => ({ sleepingAgentSessionsByPaneKey: { [SOURCE_PANE]: record } }), - getAgentProviderSessionSnapshotFn: () => [hookRow] + getAgentProviderSessionRowsForPaneFn: (paneKey: string) => + paneKey === SOURCE_PANE ? [hookRow] : [] }) const createTerminal = vi.spyOn(runtime, 'createTerminal').mockResolvedValue({ handle: 'term_restore', diff --git a/src/main/runtime/rpc/methods/orchestration/worker/follow-up/closed-worker-terminal.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/closed-worker-terminal.test.ts index 7197c89c5d3..76238d18aa9 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/follow-up/closed-worker-terminal.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/closed-worker-terminal.test.ts @@ -2,6 +2,11 @@ import { describe, expect, it, vi } from 'vitest' import type { AgentStatusIpcPayload } from '../../../../../../../shared/agent-status/contracts/agent-status-ipc-payload' import { useHelperFollowUpCli } from '../testing/helper-follow-up-cli.test-support' import { chooseWorkerFollowUpPlacement } from './worker-follow-up-choice' +import { agentProviderSessionsEqual } from '../../../../../../../shared/agent-session/lifecycle/agent-session-resume' + +import { AgentHookServer } from '../../../../../../agent-hooks/server/agent-hook-server' +import { agentHookRuntimeDeps } from '../../../../../../agent-hooks/runtime/agent-hook-runtime-deps' +import { watchMovedWorkerResumeSessions } from './worker-resume-session-capture' const CONVERSATION = { key: 'session_id', id: 'fixture-conversation' } as const const REOPENED_PANE = 'tab_reopened:leaf' @@ -28,6 +33,15 @@ describe('opening a terminal worker Orca closed', () => { configurable: true, value: () => hookRows }) + Object.defineProperty(h.runtime, 'getAgentProviderSessionRowsForSessionFn', { + configurable: true, + value: (agent: string, session: AgentStatusIpcPayload['providerSession']) => + hookRows.filter( + (row) => + row.agentType === agent && + agentProviderSessionsEqual(agent, row.providerSession, session) + ) + }) vi.spyOn(h.runtime, 'getTerminalHandleForPaneKey').mockImplementation((paneKey) => paneKey === REOPENED_PANE && live.has('term_reopened') ? 'term_reopened' : null ) @@ -63,6 +77,73 @@ describe('opening a terminal worker Orca closed', () => { const open = (address: string) => h.call('orchestration.partyOpen', { address }) + it('keeps a held worker conversation current without capturing equal status reports', async () => { + const { helper, worker } = await pair() + const paneKey = panes.get('term_helper')! + const server = new AgentHookServer() + const deps = agentHookRuntimeDeps(server, { read: () => ({ kind: 'unobserved' }) }, () => ({})) + const read = vi.fn(() => { + const row = deps.getAgentProviderSessionRowsForPane(paneKey)[0] + return row?.providerSession + ? { + paneKey, + agent: 'codex' as const, + providerSession: row.providerSession, + processIncarnation: 'process:term_helper', + observedAt: 1, + connectionId: null + } + : null + }) + const getDb = vi.fn(() => h.db) + const stop = deps.subscribeAgentProviderSessionChanges( + watchMovedWorkerResumeSessions({ getExactWorkerProviderSession: read }, getDb) + ) + const report = (id: string, state: 'working' | 'done', prompt: string) => + server.ingestRemote( + { + paneKey, + worktreeId: 'repo::worktree', + providerSession: { key: 'session_id', id }, + payload: { state, prompt, agentType: 'codex' } + }, + null + ) + const saved = () => + JSON.parse(h.db.getWorkerTerminalResourceByOwner(helper.dispatchId)!.resume_session!) + const fleetReads = vi.spyOn(server, 'getStatusSnapshot') + try { + report('session-a', 'working', 'First task') + expect(saved()).toEqual({ + agent: 'codex', + providerSession: { key: 'session_id', id: 'session-a' }, + connectionId: null + }) + read.mockClear() + getDb.mockClear() + for (let index = 0; index < 100; index++) { + report('session-a', index % 2 === 0 ? 'done' : 'working', `Progress ${index}`) + } + expect(read).not.toHaveBeenCalled() + expect(getDb).not.toHaveBeenCalled() + expect(fleetReads).not.toHaveBeenCalled() + expect(saved().providerSession.id).toBe('session-a') + + report('session-b', 'working', 'New conversation') + expect(read).toHaveBeenCalledOnce() + expect(saved().providerSession.id).toBe('session-b') + server.dropStatusEntry(paneKey, { preserveResumeIdentity: false }) + report('session-b', 'working', 'Reconnected') + expect(read).toHaveBeenCalledTimes(2) + expect(saved().providerSession.id).toBe('session-b') + expect(h.db.getWorkerTerminalResourceByOwner(worker.dispatchId)?.resume_session).toBeNull() + expect(fleetReads).not.toHaveBeenCalled() + } finally { + stop() + server.stop() + } + }) + it('resumes its conversation in a new terminal, and a click after it reports reuses it', async () => { const { resource, resume, report } = await closedHelper() for (let click = 0; click < 2; click++) { diff --git a/src/main/runtime/terminal/input/agent-prompt-restored-permission.test.ts b/src/main/runtime/terminal/input/agent-prompt-restored-permission.test.ts index 69042ee1cc3..388cf6b7e70 100644 --- a/src/main/runtime/terminal/input/agent-prompt-restored-permission.test.ts +++ b/src/main/runtime/terminal/input/agent-prompt-restored-permission.test.ts @@ -59,6 +59,19 @@ async function createReattachedClaudePane( }> { let handle = '' const askedAt = Date.now() - 24 * 60_000 + const rows = () => [ + { + paneKey: 'restored-pane', + terminalHandle: handle, + state: 'waiting' as const, + prompt: 'clean up scratch audio', + agentType: 'claude', + connectionId: null, + receivedAt: askedAt, + stateStartedAt: askedAt, + restoredUnconfirmed: true + } + ] const pane = await createAgentPromptSubmissionRuntime( (runtime, data) => { // Echo the paste as Claude does, so the send outlives the frame that let it start. @@ -67,19 +80,8 @@ async function createReattachedClaudePane( 'claude', () => true, { - getAgentStatusSnapshot: () => [ - { - paneKey: 'restored-pane', - terminalHandle: handle, - state: 'waiting', - prompt: 'clean up scratch audio', - agentType: 'claude', - connectionId: null, - receivedAt: askedAt, - stateStartedAt: askedAt, - restoredUnconfirmed: true - } - ] + getAgentStatusSnapshot: rows, + getPublicAgentStatusSnapshotForPane: rows }, controller ) diff --git a/src/main/runtime/terminal/input/agent-prompt-submission-runtime-hook-and-generation.test.ts b/src/main/runtime/terminal/input/agent-prompt-submission-runtime-hook-and-generation.test.ts index 88c6dd61883..65ac2d8a914 100644 --- a/src/main/runtime/terminal/input/agent-prompt-submission-runtime-hook-and-generation.test.ts +++ b/src/main/runtime/terminal/input/agent-prompt-submission-runtime-hook-and-generation.test.ts @@ -71,21 +71,23 @@ describe('agent prompt submission runtime hook and generation cases', () => { }> { let handle = '' const writes: string[] = [] + const rows = () => [ + { + paneKey: 'prompt-pane', + terminalHandle: handle, + state: hook.state, + prompt: '', + agentType: launchAgent, + connectionId: null, + // receivedAt changes even on same-state tool pings. + receivedAt: Date.now(), + stateStartedAt: hook.stateStartedAt, + ...(hook.mainAgent ? { mainAgent: { ...hook.mainAgent } } : {}) + } + ] const runtime = new OrcaRuntimeService(makeStore() as never, undefined, { - getAgentStatusSnapshot: () => [ - { - paneKey: 'prompt-pane', - terminalHandle: handle, - state: hook.state, - prompt: '', - agentType: launchAgent, - connectionId: null, - // receivedAt changes even on same-state tool pings. - receivedAt: Date.now(), - stateStartedAt: hook.stateStartedAt, - ...(hook.mainAgent ? { mainAgent: { ...hook.mainAgent } } : {}) - } - ] + getAgentStatusSnapshot: rows, + getPublicAgentStatusSnapshotForPane: rows }) runtime.setPtyController({ spawn: vi.fn().mockResolvedValue({ id: 'pty-prompt' }), diff --git a/src/main/runtime/terminal/wait/orca-runtime-exact-worker-provider-session.test.ts b/src/main/runtime/terminal/wait/orca-runtime-exact-worker-provider-session.test.ts index f06b8879b21..1d5076c59d2 100644 --- a/src/main/runtime/terminal/wait/orca-runtime-exact-worker-provider-session.test.ts +++ b/src/main/runtime/terminal/wait/orca-runtime-exact-worker-provider-session.test.ts @@ -19,16 +19,19 @@ function selectThroughRuntime(statusConnectionId: string | null): unknown { [PTY_ID, { connectionId: null, launchToken: 'launch-1', wslDistro: 'Ubuntu' }] ]), wslDistroByPtyId: new Map([[PTY_ID, 'Ubuntu']]), - getAgentStatusSnapshotFn: () => [ - { - paneKey: PANE_KEY, - connectionId: statusConnectionId, - launchToken: 'launch-1', - agentType: 'codex', - receivedAt: 500, - providerSession: { key: 'session_id', id: 's1', transcriptPath: '/t.jsonl' } - } - ] + publicPaneStatusFn: (paneKey: string) => + paneKey === PANE_KEY + ? [ + { + paneKey: PANE_KEY, + connectionId: statusConnectionId, + launchToken: 'launch-1', + agentType: 'codex', + receivedAt: 500, + providerSession: { key: 'session_id', id: 's1', transcriptPath: '/t.jsonl' } + } + ] + : [] } return ( OrcaRuntimeWithGetTerminalInteractiveWait.prototype as unknown as ExactWorkerProviderSessionHost diff --git a/src/renderer/src/components/dashboard/agent-destination-navigation.integration.test.tsx b/src/renderer/src/components/dashboard/agent-destination-navigation.integration.test.tsx index 66f819ab82b..e2c0626c325 100644 --- a/src/renderer/src/components/dashboard/agent-destination-navigation.integration.test.tsx +++ b/src/renderer/src/components/dashboard/agent-destination-navigation.integration.test.tsx @@ -10,6 +10,7 @@ import { makeCreatedAgentWorktree, seedAlreadyActiveWorktree } from '@/lib/workspace/activation/worktree-activation-created-agent.test-fixture' +import { structuredAgentSessionPaneKey } from '../../../../shared/agent-session/view/structured-agent-session-projection' import { folderWorkspaceKey } from '../../../../shared/workspace-scope' import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import type { Tab } from '../../../../shared/tab-types' @@ -79,7 +80,9 @@ describe('Dashboard and sidebar destination contract', () => { const seeded = useAppStore.getState() const terminal = { ...seeded.tabsByWorktree[worktree.id][0], executionHostId: owner } const tabId = native ? 'native-B' : terminal.id - const paneKey = makePaneKey(tabId, LEAF) + const paneKey = native + ? structuredAgentSessionPaneKey(tabId, 'session-B') + : makePaneKey(tabId, LEAF) const group = seeded.groupsByWorktree[worktree.id][0] const nativeTab: Tab = { id: tabId, @@ -166,6 +169,23 @@ describe('Dashboard and sidebar destination contract', () => { ) }) + if (native) { + const unified = useAppStore.getState().unifiedTabsByWorktree + useAppStore.setState({ + unifiedTabsByWorktree: { + [worktree.id]: unified[worktree.id].filter((tab) => tab.id !== tabId) + } + }) + expect(useAppStore.getState().agentStatusByPaneKey.projection.list(worktree.id)).toEqual([]) + useAppStore.setState({ unifiedTabsByWorktree: unified }) + expect( + useAppStore + .getState() + .agentStatusByPaneKey.projection.list(worktree.id) + .map((row) => row.paneKey) + ).toEqual([paneKey]) + } + const snapshot = buildDashboardSnapshot( { ...useAppStore.getState(), chatNames: new Map() }, NOW diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.test.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.test.tsx index 8c6e1942539..daffa068d2f 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.test.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.test.tsx @@ -2,6 +2,7 @@ import { acceptedAgentStatuses, type AcceptedAgentStatuses } from '@/store/slices/agent-status/accepted-agent-statuses' +import { createTestStore } from '@/store/testing/app-store-test-fixture' import { renderToStaticMarkup } from 'react-dom/server' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { AgentStatusEntry } from '../../../../../../shared/agent-status/contracts/agent-status-types' @@ -188,6 +189,15 @@ describe('useWorktreeActivityStatus', () => { ) } + const store = createTestStore() + store.setState({ + tabsByWorktree: mockState.tabsByWorktree, + ptyIdsByTabId: mockState.ptyIdsByTabId, + runtimePaneTitlesByTabId: mockState.runtimePaneTitlesByTabId, + terminalLayoutsByTabId: mockState.terminalLayoutsByTabId, + agentStatusByPaneKey: mockState.agentStatusByPaneKey + }) + mockState = store.getState() expect(renderToStaticMarkup()).toBe('done') }) }) diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.ts b/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.ts index 24ef411737c..af9c10a0dac 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.ts +++ b/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.ts @@ -76,17 +76,7 @@ export function useWorktreeActivityStatus(worktreeId: string): WorktreeStatus { const terminalLayoutRootsByTabId = useAppStore( useShallow((s) => selectTerminalLayoutRootsForWorktree(s, worktreeId)) ) - const { - hasPermission, - hasLiveWorking, - hasLiveMonitoring, - hasFailed, - hasInterrupted, - hasUnconfirmed, - hasLiveDone, - agentStatusPaneIdsByTabId, - stalePaneIdsByTabId - } = useAppStore(useShallow((s) => selectWorktreeAgentActivitySummary(s, worktreeId))) + const summary = useAppStore(useShallow((s) => selectWorktreeAgentActivitySummary(s, worktreeId))) // Use common liveness and agent-row precedence so compact and detailed cards show the same status. return useMemo( @@ -97,16 +87,8 @@ export function useWorktreeActivityStatus(worktreeId: string): WorktreeStatus { hasStructuredChat, ptyIdsByTabId: ptyIdsForWorktree, runtimePaneTitlesByTabId: runtimePaneTitlesForWorktree, - agentStatusPaneIdsByTabId, - stalePaneIdsByTabId, terminalLayoutRootsByTabId, - hasPermission, - hasLiveWorking, - hasLiveMonitoring, - hasFailed, - hasInterrupted, - hasUnconfirmed, - hasLiveDone + ...summary }), [ tabs, @@ -114,16 +96,8 @@ export function useWorktreeActivityStatus(worktreeId: string): WorktreeStatus { hasStructuredChat, ptyIdsForWorktree, runtimePaneTitlesForWorktree, - agentStatusPaneIdsByTabId, - stalePaneIdsByTabId, terminalLayoutRootsByTabId, - hasPermission, - hasLiveWorking, - hasLiveMonitoring, - hasFailed, - hasInterrupted, - hasUnconfirmed, - hasLiveDone + summary ] ) } diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-agent-rows-subscriptions.test.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-agent-rows-subscriptions.test.tsx index e518e66cc1b..22cf87c2ae8 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-agent-rows-subscriptions.test.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-agent-rows-subscriptions.test.tsx @@ -6,11 +6,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { useAppStore } from '@/store' import { makeTab } from '@/store/terminals/terminal-tab.test-fixture' -import type { AppState } from '@/store/types' import type { DashboardAgentRow } from '@/components/dashboard/useDashboardData' import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id' import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../../../shared/agent-status/contracts/agent-status-freshness' import type { AgentStatusEntry } from '../../../../../../shared/agent-status/contracts/agent-status-types' +import { useWorktreeActivityStatus } from './use-worktree-activity-status' +import { useWorktreeActivityStatuses } from './use-worktree-activity-statuses' import { useWorktreeAgentRows } from './useWorktreeAgentRows' Reflect.set(globalThis, 'IS_REACT_ACT_ENVIRONMENT', true) @@ -45,9 +46,6 @@ function entry(key: string, worktreeId: string): AgentStatusEntry { stateHistory: [] } } -function patch(update: Partial) { - act(() => useAppStore.setState(update)) -} beforeEach(() => { vi.useFakeTimers() @@ -102,11 +100,11 @@ describe('mounted worktree agent row subscriptions', () => { expect(rows[0].state).toBe('blocked') }) - it('decays on an epoch-only freshness tick', () => { + it('decays when its live status expires', () => { act(() => root.render()) expect(rows[0].state).toBe('working') - vi.setSystemTime(Date.now() + AGENT_STATUS_STALE_AFTER_MS + 1) - patch({ agentStatusEpoch: useAppStore.getState().agentStatusEpoch + 1 }) + act(() => useAppStore.getState().scheduleAgentStatusFreshness()) + act(() => vi.advanceTimersByTime(AGENT_STATUS_STALE_AFTER_MS + 1)) expect(rows[0].state).toBe('idle') }) }) @@ -115,9 +113,15 @@ it.each([100, 1000])( 'keeps unrelated mounted rows stable after equal replay then membership changes (%i workspaces)', (count) => { const ids = Array.from({ length: count }, (_, i) => `fleet-${i}`) - const updates = ids.map((worktreeId) => ({ + const updates = ids.map((worktreeId, index) => ({ paneKey: makePaneKey(`tab-${worktreeId}`, LEAF), - payload: { state: 'working' as const, agentType: 'claude', prompt: worktreeId }, + payload: { + state: index % 2 ? ('done' as const) : ('working' as const), + agentType: 'claude', + prompt: worktreeId, + ...(index % 2 ? { paneSleep: { ptyId: `pty-${worktreeId}` } } : {}) + }, + metadata: { providerSession: { key: 'session_id' as const, id: `session-${worktreeId}` } }, timing: { updatedAt: 2_000_000, stateStartedAt: 2_000_000 }, routing: { tabId: `tab-${worktreeId}`, worktreeId } })) @@ -158,11 +162,18 @@ it.each([100, 1000])( act(() => useAppStore.getState().setAgentStatuses( updates.map((update) => ({ - ...update, + ...structuredClone(update), timing: { ...update.timing, isReplay: true } })) ) ) + for (const id of ids) { + expect(outputs.get(id)).toBe(before.get(id)) + expect(renders.get(id)).toBe(rendered.get(id)) + } + expect( + useAppStore.getState().agentStatusByPaneKey.get(updates[0].paneKey)?.acceptedStatusSeq + ).toBe(2) const target = ids[0] const addedPane = makePaneKey(`tab-${target}`, '22222222-2222-4222-8222-222222222222') act(() => @@ -185,3 +196,71 @@ it.each([100, 1000])( } } ) + +it('updates mounted card status when Done membership moves without a flag change', () => { + const sibling = makePaneKey('tab-sibling', LEAF) + const doneA = { ...entry(KEY_A, 'folder-a'), state: 'done' as const } + const doneB = { ...entry(sibling, 'folder-a'), state: 'done' as const } + const state = useAppStore.getState() + const remote = state.agentStatusByPaneKey.get(KEY_B)! + const paneLayout = { + root: { type: 'leaf' as const, leafId: LEAF }, + activeLeafId: LEAF, + expandedLeafId: null + } + useAppStore.setState({ + tabsByWorktree: { + ...state.tabsByWorktree, + 'folder-a': [ + state.tabsByWorktree['folder-a'][0], + makeTab({ id: 'tab-sibling', worktreeId: 'folder-a' }) + ] + }, + ptyIdsByTabId: { 'tab-a': ['pty-a'], 'tab-sibling': ['pty-sibling'] }, + runtimePaneTitlesByTabId: { 'tab-a': { 1: '⠋ Codex' }, 'tab-sibling': { 1: 'bash' } }, + terminalLayoutsByTabId: { 'tab-a': paneLayout, 'tab-sibling': paneLayout }, + agentStatusByPaneKey: acceptedAgentStatuses([ + [KEY_A, doneA], + [KEY_B, remote] + ]) + }) + const outputs = new Map() + const renders = new Map() + function ActivityProbe({ id }: { id: string }) { + const single = useWorktreeActivityStatus(id) + const plural = useWorktreeActivityStatuses([id]).get(id)! + outputs.set(id, [single, plural]) + renders.set(id, (renders.get(id) ?? 0) + 1) + return null + } + act(() => + root.render( + <> + + + + ) + ) + expect(outputs.get('folder-a')).toEqual(['done', 'done']) + const unrelatedRenders = renders.get('ssh-b') + act(() => + useAppStore.setState((current) => ({ + agentStatusByPaneKey: current.agentStatusByPaneKey.replace([ + [KEY_A, null], + [sibling, doneB] + ]) + })) + ) + expect(outputs.get('folder-a')).toEqual(['working', 'working']) + expect(renders.get('ssh-b')).toBe(unrelatedRenders) + act(() => + useAppStore.setState((current) => ({ + agentStatusByPaneKey: current.agentStatusByPaneKey.replace([ + [sibling, null], + [KEY_A, doneA] + ]) + })) + ) + expect(outputs.get('folder-a')).toEqual(['done', 'done']) + expect(renders.get('ssh-b')).toBe(unrelatedRenders) +}) diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-activity-summary.test.ts b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-activity-summary.test.ts index bcdd458d99a..0d60e430faa 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-activity-summary.test.ts +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-activity-summary.test.ts @@ -1,4 +1,5 @@ import { acceptedAgentStatuses } from '@/store/slices/agent-status/accepted-agent-statuses' +import { createTestStore } from '@/store/testing/app-store-test-fixture' import { afterEach, describe, expect, it, vi } from 'vitest' import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../../../shared/agent-status/contracts/agent-status-freshness' @@ -8,10 +9,7 @@ import { structuredAgentSessionPaneKey } from '../../../../../../shared/agent-se import type { Tab } from '../../../../../../shared/tab-types' import type { TerminalTab } from '../../../../../../shared/workspace-layout/terminal-tab-types' -import { - selectWorktreeAgentActivitySummary, - type AgentActivityInput -} from './worktree-agent-activity-summary' +import { selectWorktreeAgentActivitySummary } from './worktree-agent-activity-summary' const LEAF_ID = '11111111-1111-4111-8111-111111111111' @@ -82,7 +80,8 @@ describe('selectWorktreeAgentActivitySummary', () => { createdAt: 0 } const paneKey = structuredAgentSessionPaneKey(tab.id, tab.entityId) - const state: AgentActivityInput = { + const store = createTestStore() + store.setState({ tabsByWorktree: {}, unifiedTabsByWorktree: {}, agentStatusEpoch: 0, @@ -93,18 +92,22 @@ describe('selectWorktreeAgentActivitySummary', () => { ), migrationUnsupportedByPtyId: {}, runtimeAgentOrchestrationByPaneKey: {} - } + }) - expect(selectWorktreeAgentActivitySummary(state, worktreeId).hasLiveWorking).toBe(false) - const represented = { ...state, unifiedTabsByWorktree: { [worktreeId]: [tab] } } - expect(selectWorktreeAgentActivitySummary(represented, worktreeId).hasLiveWorking).toBe(true) - expect( - selectWorktreeAgentActivitySummary({ ...represented, unifiedTabsByWorktree: {} }, worktreeId) - .hasLiveWorking - ).toBe(false) + expect(selectWorktreeAgentActivitySummary(store.getState(), worktreeId).hasLiveWorking).toBe( + false + ) + store.setState({ unifiedTabsByWorktree: { [worktreeId]: [tab] } }) + expect(selectWorktreeAgentActivitySummary(store.getState(), worktreeId).hasLiveWorking).toBe( + true + ) + store.setState({ unifiedTabsByWorktree: {} }) + expect(selectWorktreeAgentActivitySummary(store.getState(), worktreeId).hasLiveWorking).toBe( + false + ) }) - it('reuses only summaries whose pane membership is still current', () => { + it('reports current pane membership and preserves an explicitly captured summary', () => { vi.spyOn(Date, 'now').mockReturnValue(2_000) const worktreeId = 'repo::/wt-1' const firstPaneKey = makePaneKey('tab-1', LEAF_ID) @@ -114,7 +117,8 @@ describe('selectWorktreeAgentActivitySummary', () => { migrationUnsupportedByPtyId: {}, runtimeAgentOrchestrationByPaneKey: {} } - const initial: AgentActivityInput = { + const store = createTestStore() + store.setState({ ...sharedInputs, tabsByWorktree: { [worktreeId]: [makeTab('tab-1', worktreeId), makeTab('tab-2', worktreeId)] @@ -126,18 +130,14 @@ describe('selectWorktreeAgentActivitySummary', () => { [secondPaneKey]: makeAgentStatusEntry({ paneKey: secondPaneKey, state: 'working' }) }) ) - } - const reordered: AgentActivityInput = { - ...initial, - agentStatusEpoch: 1, - agentStatusByPaneKey: acceptedAgentStatuses( - Object.entries({ - [secondPaneKey]: initial.agentStatusByPaneKey.get(secondPaneKey)!, - [firstPaneKey]: initial.agentStatusByPaneKey.get(firstPaneKey)! - }) - ) - } - const replacement: AgentActivityInput = { + }) + expect( + selectWorktreeAgentActivitySummary(store.getState(), worktreeId).agentStatusPaneIdsByTabId + ).toEqual({ + 'tab-1': new Set([LEAF_ID]), + 'tab-2': new Set([LEAF_ID]) + }) + store.setState({ ...sharedInputs, tabsByWorktree: { [worktreeId]: [makeTab('tab-3', worktreeId)] }, agentStatusEpoch: 2, @@ -149,24 +149,19 @@ describe('selectWorktreeAgentActivitySummary', () => { }) }) ) - } - const removed: AgentActivityInput = { - ...replacement, + }) + const afterReplacement = selectWorktreeAgentActivitySummary(store.getState(), worktreeId) + expect(afterReplacement.agentStatusPaneIdsByTabId).toEqual({ 'tab-3': new Set([LEAF_ID]) }) + const captured = store.getState().agentStatusByPaneKey.capture() + store.setState({ agentStatusEpoch: 3, agentStatusByPaneKey: acceptedAgentStatuses(Object.entries({})) - } + }) + const afterRemoval = selectWorktreeAgentActivitySummary(store.getState(), worktreeId) - const first = selectWorktreeAgentActivitySummary(initial, worktreeId) - const afterReorder = selectWorktreeAgentActivitySummary(reordered, worktreeId) - const afterReplacement = selectWorktreeAgentActivitySummary(replacement, worktreeId) - const afterRemoval = selectWorktreeAgentActivitySummary(removed, worktreeId) - - expect(afterReorder).toBe(first) - expect(afterReplacement).not.toBe(first) - expect(afterReplacement.agentStatusPaneIdsByTabId).toEqual({ + expect(captured.projection.summary(worktreeId).agentStatusPaneIdsByTabId).toEqual({ 'tab-3': new Set([LEAF_ID]) }) - expect(afterRemoval).not.toBe(afterReplacement) expect(afterRemoval).toMatchObject({ hasLiveWorking: false }) expect(afterRemoval.agentStatusPaneIdsByTabId).toEqual({}) }) @@ -176,15 +171,16 @@ describe('selectWorktreeAgentActivitySummary', () => { const paneKey = makePaneKey('tab-1', LEAF_ID) const entry = makeAgentStatusEntry({ paneKey, state: 'done', worktreeId: 'repo::/wt-1' }) vi.spyOn(Date, 'now').mockReturnValue(entry.updatedAt + AGENT_STATUS_STALE_AFTER_MS + 1) - const state: AgentActivityInput = { + const store = createTestStore() + store.setState({ tabsByWorktree: { 'repo::/wt-1': [makeTab('tab-1', 'repo::/wt-1')] }, agentStatusEpoch: 0, agentStatusByPaneKey: acceptedAgentStatuses(Object.entries({ [paneKey]: entry })), migrationUnsupportedByPtyId: {}, runtimeAgentOrchestrationByPaneKey: {} - } + }) - const summary = selectWorktreeAgentActivitySummary(state, 'repo::/wt-1') + const summary = selectWorktreeAgentActivitySummary(store.getState(), 'repo::/wt-1') expect(summary.stalePaneIdsByTabId['tab-1']).toEqual(new Set([LEAF_ID])) // Staleness still ends the row's authority: no fresh pane id, no liveness flag. diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-live-index-patch.ts b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-live-index-patch.ts index 178b17b31c6..73ba86e682b 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-live-index-patch.ts +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-live-index-patch.ts @@ -1,4 +1,4 @@ -import { shallow } from 'zustand/shallow' +import { structuralValuesEqualIgnoringUndefined } from '../../../../../../shared/structural-value-equality' import type { Tab } from '../../../../../../shared/tab-types' import { parseAgentStatusPaneIdentity, @@ -12,7 +12,7 @@ export function liveEntryWorktreeId( paneKey: string, entry: AgentStatusEntry, tabIdToWorktreeId: Pick, 'get'>, - representedTabs?: ReadonlyMap + representedTabs?: Pick, 'get'> ): string | undefined { const parsed = parseAgentStatusPaneIdentity(paneKey, representedTabs?.get(paneKey)) if (!parsed) { @@ -33,5 +33,5 @@ export function agentRowEntriesEqual(previous: AgentStatusEntry, next: AgentStat } const { acceptedStatusSeq: _previousSequence, ...previousRow } = previous const { acceptedStatusSeq: _nextSequence, ...nextRow } = next - return shallow(previousRow, nextRow) + return structuralValuesEqualIgnoringUndefined(previousRow, nextRow) } diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-remote-attribution.test.ts b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-remote-attribution.test.ts index be1ccb427ac..c0b5c4a90dc 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-remote-attribution.test.ts +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-remote-attribution.test.ts @@ -1,4 +1,5 @@ import { acceptedAgentStatuses } from '@/store/slices/agent-status/accepted-agent-statuses' +import { createTestStore } from '@/store/testing/app-store-test-fixture' import { beforeEach, describe, expect, it, vi } from 'vitest' import type { AgentStatusEntry } from '../../../../../../shared/agent-status/contracts/agent-status-types' import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id' @@ -68,23 +69,27 @@ describe('remote completed sidebar rows before tab hydration', () => { NOW ) const unknown = status(toWebTerminalSurfaceTabId('unknown-owner'), worktreeId) - const beforeTabs = makeState({ - agentStatusByPaneKey: acceptedAgentStatuses([ - ...(owner.agentStatusByPaneKey ?? acceptedAgentStatuses()), - ...(sibling.agentStatusByPaneKey ?? acceptedAgentStatuses()), - ...(otherWorkspace.agentStatusByPaneKey ?? acceptedAgentStatuses()), - [unknown.paneKey, unknown] as const - ]) - }) - const removed = { - ...beforeTabs, - ...applyWebSessionTabsSnapshot( + const store = createTestStore() + store.setState( + makeState({ + agentStatusByPaneKey: acceptedAgentStatuses([ + ...(owner.agentStatusByPaneKey ?? acceptedAgentStatuses()), + ...(sibling.agentStatusByPaneKey ?? acceptedAgentStatuses()), + ...(otherWorkspace.agentStatusByPaneKey ?? acceptedAgentStatuses()), + [unknown.paneKey, unknown] as const + ]) + }) + ) + const beforeTabs = store.getState() + store.setState( + applyWebSessionTabsSnapshot( beforeTabs, makeSnapshot([], { worktree: worktreeId, snapshotVersion: 2 }), ENV, NOW + 1 ) - } + ) + const removed = store.getState() expect(Array.from(removed.agentStatusByPaneKey.keys()).sort()).toEqual( [ makePaneKey(toWebTerminalSurfaceTabId('sibling'), LEAF_ID), diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agents.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agents.tsx index d68c9def46f..104f86b7f1f 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agents.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agents.tsx @@ -1,10 +1,5 @@ import type { AgentGroupSummary } from '@/store/slices/agent-status/agent-row-display-index' import { formatAgentTypeLabel } from '../../../../../../shared/agent-status/presentation/agent-type-label' -import { - formatAllAgentsInState, - formatStateCount, - formatSummaryStateLabel -} from './worktree-card-agent-summary' import React, { useCallback, useRef } from 'react' import { ChevronDown } from 'lucide-react' import { AgentStateDot } from '@/components/AgentStateDot' @@ -13,6 +8,9 @@ import { AgentTypeIcon } from '@/components/agent/icons/agent-type-icon' import { cn } from '@/lib/class-names' import { buildSummaryAgentGroups, + formatAllAgentsInState, + formatStateCount, + formatSummaryStateLabel, selectSummaryGroupIconAgents, summarizeAgentIdentities, summarizeAgents diff --git a/src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.test.ts b/src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.test.ts index b12c9b3d31d..83c9e838a64 100644 --- a/src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.test.ts +++ b/src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.test.ts @@ -1,106 +1,77 @@ import { acceptedAgentStatuses } from '@/store/slices/agent-status/accepted-agent-statuses' +import { createTestStore } from '@/store/testing/app-store-test-fixture' import { describe, expect, it } from 'vitest' - import type { AgentStatusEntry } from '../../../../shared/agent-status/contracts/agent-status-types' -import { mulberry32 } from '../../../../shared/agent-tui-ansi-fuzz-stream' import type { TerminalLayoutSnapshot } from '../../../../shared/workspace-layout/terminal-tab-types' +import { createTabBarAgentProjectionSelector } from './tab-agent-types-by-tab-id' -import { - createTabBarAgentProjectionSelector, - selectNativeChatTabWideFallbackUnsafeTabsById, - selectTabAgentTypesByTabId -} from './tab-agent-types-by-tab-id' - -function entry(partial: Partial): AgentStatusEntry { - return { state: 'working', updatedAt: 0, ...partial } as AgentStatusEntry -} - +const A = '11111111-1111-4111-8111-111111111111' +const B = '22222222-2222-4222-8222-222222222222' +const STALE = '33333333-3333-4333-8333-333333333333' function splitLayout(activeLeafId: string | null): TerminalLayoutSnapshot { return { root: { type: 'split', direction: 'horizontal', - first: { type: 'leaf', leafId: 'leaf-a' }, - second: { type: 'leaf', leafId: 'leaf-b' } + first: { type: 'leaf', leafId: A }, + second: { type: 'leaf', leafId: B } }, activeLeafId, expandedLeafId: null } } +function entry(paneKey: string, agentType: string): AgentStatusEntry { + return { + paneKey, + agentType, + state: 'working', + prompt: '', + updatedAt: 0, + stateStartedAt: 0, + stateHistory: [] + } +} -describe('selectTabAgentTypesByTabId', () => { - it('patches incrementally to the same result as a full projection', () => { - // Why: an LCG multiply past 2^53 loses low bits and collapses the picks onto a few cases. - const nextRandom = mulberry32(7) - const random = (limit: number): number => Math.floor(nextRandom() * limit) - const tabCount = 8 - const agents = ['claude', 'codex', 'grok', undefined] as const - const leaves = ['leaf-a', 'leaf-b', 'leaf-c'] as const - const layoutChoices: TerminalLayoutSnapshot[] = [ - splitLayout('leaf-a'), - splitLayout('leaf-b'), - splitLayout(null), - splitLayout('leaf-c'), - { - root: { type: 'leaf', leafId: 'leaf-b' }, - activeLeafId: 'leaf-b', - expandedLeafId: null - }, - { root: null, activeLeafId: 'leaf-a', expandedLeafId: null }, - { root: null, activeLeafId: null, expandedLeafId: null } - ] +describe('published tab agent projection', () => { + it('follows the active split pane without borrowing a removed sibling', () => { + const store = createTestStore() const select = createTabBarAgentProjectionSelector() - let statuses: Record = {} - let layouts: Record = {} - const seenTabIds = new Set() - const seenAgents = new Set<(typeof agents)[number]>() - const seenLayouts = new Set() - const appliedOperations = new Set() - for (let step = 0; step < 2_000; step++) { - const tabId = `tab-${random(tabCount)}` - const paneKey = `${tabId}:${leaves[random(leaves.length)]}` - const operation = random(7) - seenTabIds.add(tabId) - // A status ping for a missing pane falls through, like operation 6, to reselect unchanged inputs. - if (operation !== 1 || statuses[paneKey]) { - appliedOperations.add(operation) - } - if (operation === 0) { - const agentType = agents[random(agents.length)] - seenAgents.add(agentType) - statuses = { ...statuses, [paneKey]: entry({ agentType }) } - } else if (operation === 1 && statuses[paneKey]) { - statuses = { - ...statuses, - [paneKey]: { ...statuses[paneKey], state: 'done' } - } - } else if (operation === 2) { - const { [paneKey]: _removed, ...rest } = statuses - statuses = rest - } else if (operation === 3) { - // Same keys and entries in a new insertion order. - statuses = Object.fromEntries(Object.entries(statuses).toReversed()) - } else if (operation === 4) { - const layout = layoutChoices[random(layoutChoices.length)]! - seenLayouts.add(layout) - layouts = { ...layouts, [tabId]: layout } - } else if (operation === 5) { - const { [tabId]: _removed, ...rest } = layouts - layouts = rest - } - const result = select({ - agentStatusByPaneKey: acceptedAgentStatuses(Object.entries(statuses)), - terminalLayoutsByTabId: layouts - }) - expect(result.tabAgentTypesByTabId).toEqual(selectTabAgentTypesByTabId(statuses, layouts)) - expect(result.nativeChatTabWideFallbackUnsafeTabsById).toEqual( - selectNativeChatTabWideFallbackUnsafeTabsById(layouts) - ) - } - // Why: a degenerate generator silently narrows the differential check, so pin what it exercised. - expect(seenTabIds.size).toBe(tabCount) - expect(seenAgents).toEqual(new Set(agents)) - expect(seenLayouts).toEqual(new Set(layoutChoices)) - expect(appliedOperations).toEqual(new Set([0, 1, 2, 3, 4, 5, 6])) + store.setState({ + agentStatusByPaneKey: acceptedAgentStatuses([ + [`tab:${A}`, entry(`tab:${A}`, 'claude')], + [`tab:${B}`, entry(`tab:${B}`, 'codex')] + ]), + terminalLayoutsByTabId: { tab: splitLayout(A) } + }) + expect(select(store.getState()).tabAgentTypesByTabId).toEqual({ tab: 'claude' }) + expect(select(store.getState()).nativeChatTabWideFallbackUnsafeTabsById).toEqual({ tab: true }) + store.getState().setTabLayout('tab', splitLayout(B)) + expect(select(store.getState()).tabAgentTypesByTabId).toEqual({ tab: 'codex' }) + store.getState().setTabLayout('tab', splitLayout(STALE)) + expect(select(store.getState()).tabAgentTypesByTabId).toEqual({}) + store.getState().removeAgentStatus(`tab:${A}`) + store.getState().setTabLayout('tab', { + root: { type: 'leaf', leafId: B }, + activeLeafId: B, + expandedLeafId: null + }) + expect(select(store.getState()).tabAgentTypesByTabId).toEqual({ tab: 'codex' }) + expect(select(store.getState()).nativeChatTabWideFallbackUnsafeTabsById).toEqual({}) + store.getState().removeAgentStatus(`tab:${B}`) + store.getState().setTabLayout('tab', null) + expect(select(store.getState()).tabAgentTypesByTabId).toEqual({}) + expect(select(store.getState()).nativeChatTabWideFallbackUnsafeTabsById).toEqual({}) + }) + + it('publishes and retires unsafe split routing even without agent rows', () => { + const store = createTestStore() + const select = createTabBarAgentProjectionSelector() + store.getState().setTabLayout('empty', splitLayout(A)) + expect(select(store.getState()).tabAgentTypesByTabId).toEqual({}) + expect(select(store.getState()).nativeChatTabWideFallbackUnsafeTabsById).toEqual({ + empty: true + }) + store.getState().setTabLayout('empty', null) + expect(select(store.getState()).nativeChatTabWideFallbackUnsafeTabsById).toEqual({}) }) }) diff --git a/src/renderer/src/components/tab-bar/tab-session-history-switch.test.ts b/src/renderer/src/components/tab-bar/tab-session-history-switch.test.ts index 011eb47c0f2..24baf6f7ea4 100644 --- a/src/renderer/src/components/tab-bar/tab-session-history-switch.test.ts +++ b/src/renderer/src/components/tab-bar/tab-session-history-switch.test.ts @@ -128,7 +128,7 @@ describe('one pane of a terminal tab', () => { } }) const state = useAppStore.getState() - expect(state.agentStatusByPaneKey).toEqual({}) + expect(state.agentStatusByPaneKey.size).toBe(0) expect( resolveCliChatResumeSource(state, { tab: { id: 'term-1', worktreeId: WORKTREE_ID }, diff --git a/src/renderer/src/components/terminal-pane/links/handles/terminal-handle-links.test.ts b/src/renderer/src/components/terminal-pane/links/handles/terminal-handle-links.test.ts index 208b5173554..17b11e4d862 100644 --- a/src/renderer/src/components/terminal-pane/links/handles/terminal-handle-links.test.ts +++ b/src/renderer/src/components/terminal-pane/links/handles/terminal-handle-links.test.ts @@ -10,27 +10,31 @@ import { import { extractOrchestrationTaskLinks } from './terminal-orchestration-task-links' import type { TerminalLinkActionContext } from '../terminal-link-action-request' -const mocks = vi.hoisted(() => ({ - activateTabAndFocusPane: vi.fn(), - focusTerminalTabSurface: vi.fn(), - revealFloatingWorkspacePanel: vi.fn(), - storeState: { - tabsByWorktree: {}, - ptyIdsByTabId: {}, - terminalLayoutsByTabId: {}, - agentStatusByPaneKey: acceptedAgentStatuses(Object.entries({})), +const mocks = await vi.hoisted(async () => { + const { acceptedAgentStatuses } = + await import('@/store/slices/agent-status/accepted-agent-statuses') + return { + activateTabAndFocusPane: vi.fn(), + focusTerminalTabSurface: vi.fn(), + revealFloatingWorkspacePanel: vi.fn(), + storeState: { + tabsByWorktree: {}, + ptyIdsByTabId: {}, + terminalLayoutsByTabId: {}, + agentStatusByPaneKey: acceptedAgentStatuses(Object.entries({})), - runtimeAgentOrchestrationByPaneKey: {}, - setActiveWorktree: vi.fn(), - markWorktreeVisited: vi.fn(), - recordWorktreeVisit: vi.fn(), - isNavigatingHistory: false, - setActiveView: vi.fn(), - setActiveTabType: vi.fn(), - revealWorktreeInSidebar: vi.fn(), - setActiveTab: vi.fn() + runtimeAgentOrchestrationByPaneKey: {}, + setActiveWorktree: vi.fn(), + markWorktreeVisited: vi.fn(), + recordWorktreeVisit: vi.fn(), + isNavigatingHistory: false, + setActiveView: vi.fn(), + setActiveTabType: vi.fn(), + revealWorktreeInSidebar: vi.fn(), + setActiveTab: vi.fn() + } } -})) +}) vi.mock('@/store/index', () => ({ useAppStore: { diff --git a/src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-parked-leaf.test.ts b/src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-parked-leaf.test.ts index 6168683225c..c60abd6b40d 100644 --- a/src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-parked-leaf.test.ts +++ b/src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-parked-leaf.test.ts @@ -4,6 +4,7 @@ import type { RuntimeSyncWindowGraph } from '../../../../shared/runtime-session- import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' import type { AppState } from '../../store/types' import type { TerminalTab } from '../../../../shared/workspace-layout/terminal-tab-types' +import { acceptedAgentStatuses } from '@/store/slices/agent-status/accepted-agent-statuses' vi.mock( '@/components/terminal-pane/pty-transport/delivery/pty-dispatcher', @@ -27,6 +28,7 @@ const TAB_ID = 'parked-tab-1' function makeState(overrides: Partial = {}): AppState { return { + agentStatusByPaneKey: acceptedAgentStatuses(), tabsByWorktree: {}, terminalLayoutsByTabId: {} as AppState['terminalLayoutsByTabId'], runtimePaneTitlesByTabId: {} as AppState['runtimePaneTitlesByTabId'], diff --git a/src/renderer/src/store/slices/agent-status/agent-conversation-capacity.test.ts b/src/renderer/src/store/slices/agent-status/agent-conversation-capacity.test.ts index d260f5313dd..0994fb58a82 100644 --- a/src/renderer/src/store/slices/agent-status/agent-conversation-capacity.test.ts +++ b/src/renderer/src/store/slices/agent-status/agent-conversation-capacity.test.ts @@ -4,6 +4,7 @@ import { replaceRecordEntries } from '../../keyed-record-transitions' import type { AppState } from '../../types' import type { AgentPaneConversationIdentity } from './agent-pane-conversation' import type { AgentStatusUpdate } from './agent-status-contract' +import { createAgentConversationCapacityIndex } from './agent-conversation-capacity-index' import { makeTab } from '../../terminals/terminal-tab.test-fixture' function conversation(key: string): AgentPaneConversationIdentity { @@ -21,112 +22,130 @@ const layout = (root: AppState['terminalLayoutsByTabId'][string]['root']) => ({ expandedLeafId: null }) -it.each([100, 1000])( - 'addresses capacity work across %s workspaces with placed owners above 500', - (size) => { - const store = createTestStore() - const visits: string[] = [] - const roots: string[] = [] - const leaf = (id: string, leafId = 'leaf') => ({ - get type() { - visits.push(id) - return 'leaf' as const - }, - leafId - }) - const layouts = Object.fromEntries( - Array.from({ length: size * 10 }, (_, i) => [`tab-${i}`, layout(leaf(`tab-${i}`))]) - ) - for (const [id, snapshot] of Object.entries(layouts)) { - const root = snapshot.root - Object.defineProperty(snapshot, 'root', { - enumerable: true, - get: () => { - roots.push(id) - return root - } - }) - } - const entries = Object.fromEntries( - Array.from({ length: size * 6 }, (_, i) => [`tab-${i}:leaf`, conversation(`tab-${i}:leaf`)]) - ) - store.setState({ - terminalLayoutsByTabId: layouts, - agentConversationsByPaneKey: entries, - tabsByWorktree: { - 'wt-order': Object.keys(layouts).map((id) => makeTab({ id, worktreeId: 'wt-order' })) - } - }) - const update = (index: number, state: 'working' | 'done', at: number): AgentStatusUpdate => ({ - paneKey: `tab-${index}:leaf`, - payload: { state, prompt: 'task', agentType: 'codex' }, - timing: { updatedAt: at, stateStartedAt: at, turnStartedAt: 1000 }, - routing: { worktreeId: 'wt-order' } - }) - store - .getState() - .setAgentStatuses(Array.from({ length: 100 }, (_, i) => update(i, 'working', 1000))) - const unrelatedRoot = layouts[`tab-${size * 10 - 1}`].root - visits.length = 0 - roots.length = 0 - const original = store.getState().agentConversationsByPaneKey - store.getState().setAgentStatuses([update(0, 'working', 2000)]) - expect(store.getState().agentConversationsByPaneKey).toBe(original) - store.getState().setAgentStatuses([update(0, 'done', 3000)]) - expect(store.getState().agentConversationsByPaneKey['tab-0:leaf'].continuity?.state).toBe( - 'done' - ) - store - .getState() - .setAgentStatuses([update(1, 'done', 4000), update(2, 'done', 4000), update(3, 'done', 4000)]) - const unrelated = `tab-${size * 10 - 1}` - store.setState((state) => ({ - terminalLayoutsByTabId: replaceRecordEntries( - state.terminalLayoutsByTabId, - [ - [ - unrelated, - { ...layout(unrelatedRoot), activeLeafId: null, ptyIdsByLeafId: { leaf: 'pty' } } - ], - ['empty-tab', layout(null)] - ] - ) - })) - expect(visits).toEqual([]) - expect(roots).toEqual([]) - const freshRoot = leaf('fresh-tab') - const freshLayout = layout(freshRoot) - Object.defineProperty(freshLayout, 'root', { +function exerciseAddressedCapacity(size: number): number[] { + const store = createTestStore() + const visits: string[] = [] + const work: number[] = [] + const recordWork = () => work.push(visits.length, roots.length) + const roots: string[] = [] + const leaf = (id: string, leafId = 'leaf') => ({ + get type() { + visits.push(id) + return 'leaf' as const + }, + leafId + }) + const layouts = Object.fromEntries( + Array.from({ length: size * 10 }, (_, i) => [`tab-${i}`, layout(leaf(`tab-${i}`))]) + ) + for (const [id, snapshot] of Object.entries(layouts)) { + const root = snapshot.root + Object.defineProperty(snapshot, 'root', { enumerable: true, get: () => { - roots.push('fresh-tab') - return freshRoot + roots.push(id) + return root } }) - store.setState((state) => ({ - terminalLayoutsByTabId: replaceRecordEntries( - state.terminalLayoutsByTabId, - [['fresh-tab', freshLayout]] - ) - })) - expect(visits).toEqual([]) - store - .getState() - .setAgentStatuses([{ ...update(0, 'working', 5000), paneKey: 'fresh-tab:leaf' }]) - expect(visits).toEqual(['fresh-tab']) - expect(roots).toEqual(['fresh-tab']) - expect(store.getState().agentConversationsByPaneKey['fresh-tab:leaf']).toBeDefined() - visits.length = 0 - roots.length = 0 - store - .getState() - .closeTab('tab-0', { localPtyTeardownOwnedExternally: true, captureRecentlyClosed: false }) - expect(store.getState().agentConversationsByPaneKey['tab-0:leaf']).toBeUndefined() - expect(store.getState().agentConversationsByPaneKey['tab-1:leaf']).toBeDefined() - expect(visits.filter((id) => id !== 'tab-0')).toEqual([]) - expect(roots.filter((id) => id !== 'tab-0')).toEqual([]) } -) + const entries = Object.fromEntries( + Array.from({ length: size * 6 }, (_, i) => [`tab-${i}:leaf`, conversation(`tab-${i}:leaf`)]) + ) + store.setState({ + terminalLayoutsByTabId: layouts, + agentConversationsByPaneKey: entries, + tabsByWorktree: { + 'wt-order': Object.keys(layouts).map((id) => makeTab({ id, worktreeId: 'wt-order' })) + } + }) + const update = (index: number, state: 'working' | 'done', at: number): AgentStatusUpdate => ({ + paneKey: `tab-${index}:leaf`, + payload: { state, prompt: 'task', agentType: 'codex' }, + timing: { updatedAt: at, stateStartedAt: at, turnStartedAt: 1000 }, + routing: { worktreeId: 'wt-order' } + }) + store + .getState() + .setAgentStatuses(Array.from({ length: 100 }, (_, i) => update(i, 'working', 1000))) + const unrelatedRoot = layouts[`tab-${size * 10 - 1}`].root + visits.length = 0 + roots.length = 0 + const original = store.getState().agentConversationsByPaneKey + store.getState().setAgentStatuses([update(0, 'working', 2000)]) + expect(store.getState().agentConversationsByPaneKey).toBe(original) + store.getState().setAgentStatuses([update(0, 'done', 3000)]) + expect(store.getState().agentConversationsByPaneKey['tab-0:leaf'].continuity?.state).toBe('done') + store + .getState() + .setAgentStatuses([update(1, 'done', 4000), update(2, 'done', 4000), update(3, 'done', 4000)]) + const updatedTabs = new Set(['tab-0', 'tab-1', 'tab-2', 'tab-3']) + expect(visits.filter((id) => !updatedTabs.has(id))).toEqual([]) + expect(roots.filter((id) => !updatedTabs.has(id))).toEqual([]) + recordWork() + visits.length = 0 + roots.length = 0 + const unrelated = `tab-${size * 10 - 1}` + store.setState((state) => ({ + terminalLayoutsByTabId: replaceRecordEntries( + state.terminalLayoutsByTabId, + [ + [ + unrelated, + { ...layout(unrelatedRoot), activeLeafId: null, ptyIdsByLeafId: { leaf: 'pty' } } + ], + ['empty-tab', layout(null)] + ] + ) + })) + expect(visits.filter((id) => id !== unrelated)).toEqual([]) + expect(roots.filter((id) => id !== unrelated)).toEqual([]) + recordWork() + visits.length = 0 + roots.length = 0 + const freshRoot = leaf('fresh-tab') + const freshLayout = layout(freshRoot) + Object.defineProperty(freshLayout, 'root', { + enumerable: true, + get: () => { + roots.push('fresh-tab') + return freshRoot + } + }) + store.setState((state) => ({ + terminalLayoutsByTabId: replaceRecordEntries( + state.terminalLayoutsByTabId, + [['fresh-tab', freshLayout]] + ) + })) + expect(visits.filter((id) => id !== 'fresh-tab')).toEqual([]) + expect(roots.filter((id) => id !== 'fresh-tab')).toEqual([]) + recordWork() + visits.length = 0 + roots.length = 0 + store.getState().setAgentStatuses([{ ...update(0, 'working', 5000), paneKey: 'fresh-tab:leaf' }]) + expect(visits.filter((id) => id !== 'fresh-tab')).toEqual([]) + expect(roots.filter((id) => id !== 'fresh-tab')).toEqual([]) + expect(store.getState().agentConversationsByPaneKey['fresh-tab:leaf']).toBeDefined() + recordWork() + visits.length = 0 + roots.length = 0 + store + .getState() + .closeTab('tab-0', { localPtyTeardownOwnedExternally: true, captureRecentlyClosed: false }) + expect(store.getState().agentConversationsByPaneKey['tab-0:leaf']).toBeUndefined() + expect(store.getState().agentConversationsByPaneKey['tab-1:leaf']).toBeDefined() + expect(visits.filter((id) => id !== 'tab-0')).toEqual([]) + expect(roots.filter((id) => id !== 'tab-0')).toEqual([]) + recordWork() + return work +} + +it('keeps changed-target capacity and projection work constant at 100 and 1000 workspaces', () => { + const small = exerciseAddressedCapacity(100) + const large = exerciseAddressedCapacity(1000) + // The same fixed-depth target writes require no extra work when only unrelated layouts grow. + expect(large.map((count, index) => count - small[index])).toEqual([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) +}) it('enforces oldest-unplaced order on demotion, restoration and unknown replacement', () => { const store = createTestStore() @@ -175,12 +194,7 @@ it('enforces oldest-unplaced order on demotion, restoration and unknown replacem it('preserves exact legacy full-key placement and bounds rootless or missing leaves on hydrate', () => { const store = createTestStore() - const cold = { - get type(): 'leaf' { - throw new Error('unrelated tree visited') - }, - leafId: 'unused' - } + const cold = { type: 'leaf' as const, leafId: 'unused' } const legacy = 'host:tab:leaf' const rootless = 'rootless:leaf' const missing = 'rooted:missing' @@ -230,3 +244,40 @@ it('appends a new integer-shaped key for eviction, then follows record ordering expect(store.getState().agentConversationsByPaneKey['1']).toBeUndefined() expect(store.getState().agentConversationsByPaneKey['gone-1:leaf']).toBeDefined() }) + +it.each([100, 1000])( + 'skips capacity roots without association candidates (%s workspaces)', + (size) => { + const index = createAgentConversationCapacityIndex() + const entries = Object.fromEntries( + Array.from({ length: size * 6 }, (_, i) => [`tab-${i}:leaf`, conversation(`tab-${i}:leaf`)]) + ) + const layouts: AppState['terminalLayoutsByTabId'] = Object.fromEntries( + Array.from({ length: size * 10 }, (_, i) => [ + `tab-${i}`, + layout({ type: 'leaf', leafId: 'leaf' }) + ]) + ) + layouts.unrelated = layout({ + get type(): 'leaf' { + throw new Error('capacity visited a root without candidates') + }, + leafId: 'unused' + }) + const accepted = index.cap(entries, layouts) + expect(Object.keys(accepted)).toHaveLength(size * 6) + const untouched = { + get root(): null { + throw new Error('capacity visited an unchanged unrelated layout') + }, + activeLeafId: null, + expandedLeafId: null + } + const candidateFree = `tab-${size * 10 - 1}` + const next = replaceRecordEntries(layouts, [ + [candidateFree, untouched], + ['empty-tab', untouched] + ]) + expect(index.cap(accepted, next)).toBe(accepted) + } +) diff --git a/src/renderer/src/store/slices/agent-status/agent-status-cleanup-actions.ts b/src/renderer/src/store/slices/agent-status/agent-status-cleanup-actions.ts index d1c85754dc2..6d881205bd5 100644 --- a/src/renderer/src/store/slices/agent-status/agent-status-cleanup-actions.ts +++ b/src/renderer/src/store/slices/agent-status/agent-status-cleanup-actions.ts @@ -172,7 +172,6 @@ export function createAgentStatusCleanupActions( if (connectionId.length === 0 || !Number.isFinite(clearedAt)) { return } - let removed = false set((s, changedPaneKeys) => { const worktreeIdsOnConnection = collectWorktreeIdsForConnection(s, connectionId) let next: typeof s.agentStatusByPaneKey | null = null @@ -195,7 +194,6 @@ export function createAgentStatusCleanupActions( if (!next && alreadyBlocked) { return s } - removed = next !== null return { ...(next ? { @@ -209,9 +207,6 @@ export function createAgentStatusCleanupActions( : { ...s.transientClearedAgentStatusConnectionIds, [connectionId]: true } } }) - if (removed) { - freshness.scheduleDeferred() - } } } } diff --git a/src/renderer/src/store/slices/agent-status/agent-status-keyed-owner.test.tsx b/src/renderer/src/store/slices/agent-status/agent-status-keyed-owner.test.tsx index a0cf40ef023..7ad85dd9585 100644 --- a/src/renderer/src/store/slices/agent-status/agent-status-keyed-owner.test.tsx +++ b/src/renderer/src/store/slices/agent-status/agent-status-keyed-owner.test.tsx @@ -78,6 +78,61 @@ function fleet(active: number, sleeping: number) { } describe('accepted keyed owner', () => { + it('keeps an aged sleeping completion visible without renewing attention until a new turn', () => { + const store = fleet(1, 1) + const completedAt = NOW - 31 * 60_000 + store + .getState() + .setAgentStatus(keyFor(0), { state: 'done', prompt: 'Awake result' }, undefined, { + updatedAt: NOW, + stateStartedAt: completedAt + }) + store + .getState() + .setAgentStatus( + keyFor(1), + { state: 'done', prompt: 'Sleeping result', paneSleep: { ptyId: 'pty-1' } }, + undefined, + { updatedAt: NOW, stateStartedAt: completedAt } + ) + const projection = () => store.getState().agentStatusByPaneKey.projection + expect( + projection() + .list('worktree') + .map((row) => row.state) + ).toEqual(['done', 'done']) + expect(projection().attention('worktree', 0, NOW)).toEqual({ cls: 5, attentionTimestamp: 0 }) + + vi.setSystemTime(NOW + 1_000) + store + .getState() + .setAgentStatus( + keyFor(1), + { state: 'done', prompt: 'Sleeping result', paneSleep: { ptyId: 'pty-1' } }, + undefined, + { updatedAt: NOW + 1_000, stateStartedAt: completedAt } + ) + expect(projection().attention('worktree', 0, NOW + 1_000)).toEqual({ + cls: 5, + attentionTimestamp: 0 + }) + expect(store.getState().agentStatusByPaneKey.get(keyFor(1))?.stateStartedAt).toBe(completedAt) + expect(projection().row(keyFor(1))?.state).toBe('done') + + store + .getState() + .setAgentStatus(keyFor(1), { state: 'working', prompt: 'New turn' }, undefined, { + updatedAt: NOW + 1_000, + stateStartedAt: NOW + 1_000 + }) + expect(store.getState().agentStatusByPaneKey.get(keyFor(1))?.paneSleep).toBeUndefined() + expect(projection().row(keyFor(1))?.state).toBe('working') + expect(projection().attention('worktree', 0, NOW + 1_000)).toEqual({ + cls: 3, + attentionTimestamp: completedAt + }) + }) + it.each([750, 7500])( 'routes paired presentation updates past %i unrelated sleeping rows', (sleeping) => { diff --git a/src/renderer/src/store/slices/agent-status/agent-status-projection-capture.ts b/src/renderer/src/store/slices/agent-status/agent-status-projection-capture.ts index 24af1be34e4..83482234e06 100644 --- a/src/renderer/src/store/slices/agent-status/agent-status-projection-capture.ts +++ b/src/renderer/src/store/slices/agent-status/agent-status-projection-capture.ts @@ -15,7 +15,9 @@ export function captureProjectionState( captured.activeDashboardOwners = new Set(data.activeDashboardOwners) captured.dashboardTotals = data.dashboardTotals captured.inputs = data.inputs - captured.represented = data.represented + for (const [key, tab] of data.represented) { + captured.represented.set(key, tab) + } captured.nextRank = data.nextRank captured.nextRowRevision = data.nextRowRevision captured.freshEvidence = data.freshEvidence diff --git a/src/renderer/src/store/slices/agent-status/agent-status-projection-publish-rows.ts b/src/renderer/src/store/slices/agent-status/agent-status-projection-publish-rows.ts index eb03862e9a2..47872df1cca 100644 --- a/src/renderer/src/store/slices/agent-status/agent-status-projection-publish-rows.ts +++ b/src/renderer/src/store/slices/agent-status/agent-status-projection-publish-rows.ts @@ -9,6 +9,7 @@ import { EMPTY_KEYS } from './agent-status-projection-types' import type { AgentStatusProjectionState } from './agent-status-projection-state' import type { ProjectionTopology } from './agent-status-projection-topology' import type { ProjectionRows } from './agent-status-projection-rows' +import { agentRowEntriesEqual } from '@/components/sidebar/workspace-card/activity/worktree-agent-live-index-patch' export function publishProjectionRows( data: AgentStatusProjectionState, @@ -55,7 +56,11 @@ export function publishProjectionRows( arrange.add(next.worktreeId) } b.keys.add(row.paneKey) - if (!prior || !equal(prior, { ...row, lineage: prior.lineage })) { + if ( + !prior || + !agentRowEntriesEqual(prior.entry, row.entry) || + !equal(prior, { ...row, entry: prior.entry, lineage: prior.lineage }) + ) { data.rows.set(row.paneKey, prior?.lineage ? { ...row, lineage: prior.lineage } : row) b.revision = ++data.nextRowRevision data.notices.add(`row\0${row.paneKey}`) diff --git a/src/renderer/src/store/slices/agent-status/agent-status-projection-publish-topology.ts b/src/renderer/src/store/slices/agent-status/agent-status-projection-publish-topology.ts index 1193c7651d4..4607d43b121 100644 --- a/src/renderer/src/store/slices/agent-status/agent-status-projection-publish-topology.ts +++ b/src/renderer/src/store/slices/agent-status/agent-status-projection-publish-topology.ts @@ -19,7 +19,7 @@ export function publishProjectionTopology( data.notices.add(`status\0${change.paneKey}`) } data.inputs = state - data.represented = represented + represented.commitInto(data.represented) for (const [id, tab] of nextTabs) { if (tab) { data.tabs.set(id, tab) diff --git a/src/renderer/src/store/slices/agent-status/agent-status-projection-rows.ts b/src/renderer/src/store/slices/agent-status/agent-status-projection-rows.ts index 9f935c20bf9..2d64b82c1c6 100644 --- a/src/renderer/src/store/slices/agent-status/agent-status-projection-rows.ts +++ b/src/renderer/src/store/slices/agent-status/agent-status-projection-rows.ts @@ -1,6 +1,7 @@ import type { AppState } from '../../types' import { parseAgentStatusPaneIdentity, + resolveAgentStatusWorktreeId, mergeAgentStatusOrchestration } from '../../../../../shared/agent-status/identity/agent-status-worktree-attribution' import { liveEntryWorktreeId } from '@/components/sidebar/workspace-card/activity/worktree-agent-live-index-patch' @@ -55,12 +56,14 @@ export function stageProjectionRows( if (leaf) { keys.push(makePaneKey(legacy!.tabId, leaf)) } - const parent = mergeAgentStatusOrchestration( + const orchestration = mergeAgentStatusOrchestration( entry, state.runtimeAgentOrchestrationByPaneKey[key] - )?.parentPaneKey + ) + const parent = orchestration?.parentPaneKey const parsed = parent ? parsePaneKey(parent) : null - if (entry.state === 'done' && parsed && ownerOf(parsed.tabId) === ownerOf(identity.tabId)) { + const owner = resolveAgentStatusWorktreeId(entry, { get: ownerOf }, orchestration) + if (entry.state === 'done' && parsed && owner && ownerOf(parsed.tabId) === owner) { keys.push(parent!) } } @@ -113,7 +116,14 @@ export function stageProjectionRows( ? [fallback] : [] let contribution: Contribution | undefined - if (entry && worktreeId && identity) { + const summaryWorktreeId = entry + ? resolveAgentStatusWorktreeId( + entry, + { get: ownerOf }, + mergeAgentStatusOrchestration(entry, state.runtimeAgentOrchestrationByPaneKey[key]) + ) + : undefined + if (entry && summaryWorktreeId && identity) { const flags = emptySummary(), panes: string[] = [], stale: string[] = [], @@ -134,12 +144,12 @@ export function stageProjectionRows( ?.parentPaneKey ) : null - if (parent && ownerOf(parent.tabId) === worktreeId) { + if (parent && ownerOf(parent.tabId) === summaryWorktreeId) { panes.push(`${parent.tabId}\0${parent.paneId}`) } } contribution = { - worktreeId, + worktreeId: summaryWorktreeId, flags: FLAGS.filter((flag) => flags[flag]), panes, stale, diff --git a/src/renderer/src/store/slices/agent-status/agent-status-projection-state.ts b/src/renderer/src/store/slices/agent-status/agent-status-projection-state.ts index ed75d827d37..d9b69a3b274 100644 --- a/src/renderer/src/store/slices/agent-status/agent-status-projection-state.ts +++ b/src/renderer/src/store/slices/agent-status/agent-status-projection-state.ts @@ -36,7 +36,7 @@ export class AgentStatusProjectionState { inputs: AppState | null = null readonly tabs = new Map() readonly tabWorktrees = new Map() - represented: ReadonlyMap = new Map() + readonly represented = new Map() readonly orphanOwners = new Map() readonly orphansByOwner = new Map>() readonly handleByKey = new Map() diff --git a/src/renderer/src/store/slices/agent-status/agent-status-projection-topology.test.ts b/src/renderer/src/store/slices/agent-status/agent-status-projection-topology.test.ts new file mode 100644 index 00000000000..311e8d2b94d --- /dev/null +++ b/src/renderer/src/store/slices/agent-status/agent-status-projection-topology.test.ts @@ -0,0 +1,95 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { createTestStore } from '../../testing/app-store-test-fixture' +import { makeUnifiedTab } from '../tabs/tab-group.test-fixture' +import { withWorktreeTabEntry } from '@/runtime/web-session-tabs-sync/presentation-record-drafts' +import { structuredAgentSessionPaneKey } from '../../../../../shared/agent-session/view/structured-agent-session-projection' +import { acceptedAgentStatuses, AcceptedAgentStatuses } from './accepted-agent-statuses' + +afterEach(() => vi.restoreAllMocks()) + +it.each([100, 1000])('addresses tab changes beside %i unrelated recognized chats', (count) => { + const store = createTestStore() + const visits: string[] = [] + const chats = Array.from({ length: count }, (_, index) => { + const id = `native-${index}` + const tab = makeUnifiedTab({ + id, + worktreeId: `workspace-${index}`, + groupId: 'group', + contentType: 'agent-session', + entityId: `session-${index}`, + agentSessionAgent: 'claude' + }) + Object.defineProperty(tab, 'id', { + enumerable: true, + get: () => { + visits.push(id) + return id + } + }) + return tab + }) + const key = structuredAgentSessionPaneKey('native-0', 'session-0') + const now = Date.now() + const terminal = makeUnifiedTab({ + id: 'target', + worktreeId: 'target-workspace', + groupId: 'group' + }) + store.setState({ + unifiedTabsByWorktree: { + ...Object.fromEntries(chats.map((tab) => [tab.worktreeId, [tab]])), + 'target-workspace': [terminal] + }, + agentStatusByPaneKey: acceptedAgentStatuses([ + [ + key, + { + paneKey: key, + worktreeId: 'workspace-0', + state: 'working', + agentType: 'claude', + prompt: 'Native task', + updatedAt: now, + stateStartedAt: now, + stateHistory: [] + } + ] + ]) + }) + const reads = vi.spyOn(AcceptedAgentStatuses.prototype, 'get') + visits.length = 0 + store.setState((state) => ({ + unifiedTabsByWorktree: withWorktreeTabEntry( + state, + 'unifiedTabsByWorktree', + 'target-workspace', + [{ ...terminal, label: 'Updated shell' }], + (previous, next) => previous === next + ) + })) + expect(visits).toEqual([]) + expect(reads).not.toHaveBeenCalled() + expect(store.getState().unifiedTabsByWorktree['target-workspace'][0].label).toBe('Updated shell') + + const changed = { ...chats[0], label: 'Updated chat' } + visits.length = 0 + reads.mockClear() + store.setState((state) => ({ + unifiedTabsByWorktree: withWorktreeTabEntry( + state, + 'unifiedTabsByWorktree', + 'workspace-0', + [changed], + (previous, next) => previous === next + ) + })) + expect(visits.filter((id) => id !== 'native-0')).toEqual([]) + expect(new Set(reads.mock.calls.map(([paneKey]) => paneKey))).toEqual(new Set([key])) + expect( + store + .getState() + .agentStatusByPaneKey.projection.list('workspace-0') + .map((row) => row.entry.prompt) + ).toEqual(['Native task']) +}) diff --git a/src/renderer/src/store/slices/agent-status/agent-status-projection-topology.ts b/src/renderer/src/store/slices/agent-status/agent-status-projection-topology.ts index 0d60d244144..68e131463f4 100644 --- a/src/renderer/src/store/slices/agent-status/agent-status-projection-topology.ts +++ b/src/renderer/src/store/slices/agent-status/agent-status-projection-topology.ts @@ -3,9 +3,11 @@ import type { AgentStatusEntry } from '../../../../../shared/agent-status/contra import type { AgentStatusChange } from './agent-status-contract' import type { DashboardAgentRow } from '@/components/dashboard/useDashboardData' import type { TerminalTab } from '../../../../../shared/workspace-layout/terminal-tab-types' +import { structuredAgentSessionPaneKey } from '../../../../../shared/agent-session/view/structured-agent-session-projection' import { parseAgentStatusPaneIdentity } from '../../../../../shared/agent-status/identity/agent-status-worktree-attribution' import { buildTitleDerivedAgentRows } from '@/components/sidebar/workspace-card/activity/worktree-title-derived-agent-rows' -import { getStructuredAgentSessionTabsByPaneKey } from '@/components/native-chat/session/status/structured-agent-session-tabs' +import { isStructuredTab } from '../../../../../shared/agent-session/view/structured-agent-session-tab' +import { AgentStatusStoreDraftTable } from '../../../../../shared/agent-status/store/agent-status-store-table' import { readRecordChanges, readTabMapChanges } from '../../keyed-record-change-reads' import { migrationUnsupportedToAgentStatusEntry } from '../../../../../shared/migration-unsupported-agent-entry' import type { AgentStatusProjectionState } from './agent-status-projection-state' @@ -61,11 +63,8 @@ export function stageProjectionTopology( } } } - const represented = - state.unifiedTabsByWorktree !== previous?.unifiedTabsByWorktree - ? getStructuredAgentSessionTabsByPaneKey(state.unifiedTabsByWorktree ?? {}) - : data.represented - if (represented !== data.represented) { + const represented = new AgentStatusStoreDraftTable(data.represented) + if (state.unifiedTabsByWorktree !== previous?.unifiedTabsByWorktree) { const diff = previous ? readTabMapChanges(state.unifiedTabsByWorktree, previous.unifiedTabsByWorktree) : null @@ -83,6 +82,9 @@ export function stageProjectionTopology( (diff?.kind !== 'addressed' || diff.tabIds.has(tab.id)) ) { changedTabs.add(tab.id) + const key = structuredAgentSessionPaneKey(tab.id, tab.entityId) + changedKeys.add(key) + represented.delete(key) nextTabOwners.set(tab.id, null) } } @@ -92,20 +94,15 @@ export function stageProjectionTopology( (diff?.kind !== 'addressed' || diff.tabIds.has(tab.id)) ) { changedTabs.add(tab.id) + const key = structuredAgentSessionPaneKey(tab.id, tab.entityId) + changedKeys.add(key) + if (isStructuredTab(tab)) { + represented.set(key, tab) + } nextTabOwners.set(tab.id, owner) } } } - for (const [key, tab] of data.represented) { - if (changedTabs.has(tab.id)) { - changedKeys.add(key) - } - } - for (const [key, tab] of represented) { - if (changedTabs.has(tab.id)) { - changedKeys.add(key) - } - } } for (const field of SEAM_AGENT_PRESENTATION_FIELDS) { if (state[field] === previous?.[field]) { diff --git a/src/renderer/src/store/slices/agent-status/agent-status-ssh-connection-clear.test.ts b/src/renderer/src/store/slices/agent-status/agent-status-ssh-connection-clear.test.ts index 8e6125defbe..860677be65c 100644 --- a/src/renderer/src/store/slices/agent-status/agent-status-ssh-connection-clear.test.ts +++ b/src/renderer/src/store/slices/agent-status/agent-status-ssh-connection-clear.test.ts @@ -63,13 +63,11 @@ describe('agent status cleanup for a lost SSH connection', () => { }) const subscriber = vi.fn() const unsubscribe = store.subscribe(subscriber) - const queueMicrotaskSpy = vi.spyOn(globalThis, 'queueMicrotask').mockImplementation(() => {}) store.getState().clearTransientAgentStatuses('ssh-a', 30) unsubscribe() expect(subscriber).toHaveBeenCalledOnce() - expect(queueMicrotaskSpy).toHaveBeenCalledOnce() expect(store.getState().agentStatusByPaneKey.get(oldA)).toBeUndefined() expect(store.getState().agentStatusByPaneKey.get(secondA)).toBeUndefined() expect(store.getState().agentStatusByPaneKey.get(newerA)).toBeDefined() diff --git a/tests/e2e/helpers/terminal-pane-operations.ts b/tests/e2e/helpers/terminal-pane-operations.ts index 542ebed8a40..a593f67449f 100644 --- a/tests/e2e/helpers/terminal-pane-operations.ts +++ b/tests/e2e/helpers/terminal-pane-operations.ts @@ -91,6 +91,26 @@ export async function waitForActiveTerminalManager(page: Page, timeoutMs = 30_00 } ) .toBe(true) + .catch(async (error: unknown) => { + const tabId = await resolveActiveTabId(page).catch(() => null) + const diagnostic = await page + .evaluate(async (tabId) => { + const manager = tabId ? window.__paneManagers?.get(tabId) : undefined + const report = await window.api.crashReports.getLatestReport() + return { + tabId, + managerPresent: Boolean(manager), + paneCount: manager?.getPanes?.().length ?? 0, + rendererError: report?.details.errorMessage, + componentStack: report?.details.componentStack + } + }, tabId) + .catch(() => null) + throw new Error( + `Active terminal PaneManager did not finish mounting: ${JSON.stringify(diagnostic)}`, + { cause: error } + ) + }) } export async function splitActiveTerminalPane( diff --git a/tests/e2e/omp-risk-remote-review.unit.test.ts b/tests/e2e/omp-risk-remote-review.unit.test.ts index f3175c63090..7eb57de0e4a 100644 --- a/tests/e2e/omp-risk-remote-review.unit.test.ts +++ b/tests/e2e/omp-risk-remote-review.unit.test.ts @@ -1,4 +1,5 @@ import { acceptedAgentStatuses } from '@/store/slices/agent-status/accepted-agent-statuses' +import { createTestStore } from '@/store/testing/app-store-test-fixture' import { beforeEach, expect, it, vi } from 'vitest' import { makePaneKey } from '../../src/shared/workspace-layout/stable-pane-id' import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' @@ -73,24 +74,29 @@ it.each( otherHost, NOW ) - const state = makeState({ - ...(hydrated ? a : {}), - agentStatusByPaneKey: acceptedAgentStatuses([ - ...(a.agentStatusByPaneKey ?? []), - ...(b.agentStatusByPaneKey ?? []) - ]), - acknowledgedAgentsByPaneKey: { [ownPane]: 1, [sibling]: 2 }, - paneForegroundAgentByPaneKey: { - [ownPane]: { agent: 'omp', shellForeground: false }, - [sibling]: { agent: 'omp', shellForeground: false } - } - }) + const store = createTestStore() + store.setState( + makeState({ + ...(hydrated ? a : {}), + agentStatusByPaneKey: acceptedAgentStatuses([ + ...(a.agentStatusByPaneKey ?? []), + ...(b.agentStatusByPaneKey ?? []) + ]), + acknowledgedAgentsByPaneKey: { [ownPane]: 1, [sibling]: 2 }, + paneForegroundAgentByPaneKey: { + [ownPane]: { agent: 'omp', shellForeground: false }, + [sibling]: { agent: 'omp', shellForeground: false } + } + }) + ) + const state = store.getState() expect(state.agentStatusByPaneKey.get(sibling)).toBeDefined() const empty = makeSnapshot([], { worktree: 'folder:same', snapshotVersion: 2 }) const patch = batch ? applyWebSessionTabsSnapshots(state, [empty], 'host-a', NOW + 1) : applyWebSessionTabsSnapshot(state, empty, 'host-a', NOW + 1) - const after = { ...state, ...patch } + store.setState(patch) + const after = store.getState() expect(after.agentStatusByPaneKey.get(ownPane)).toBeUndefined() expect(after.agentStatusByPaneKey.get(sibling)).toEqual(state.agentStatusByPaneKey.get(sibling)) expect(after.acknowledgedAgentsByPaneKey?.[ownPane]).toBeUndefined() @@ -101,20 +107,20 @@ it.each( ) expect(after.recentlyClosedAgentStatusTabIds?.[tabId]).toBeUndefined() - const next = { - ...after, - ...applyWebSessionTabsSnapshot( + store.setState( + applyWebSessionTabsSnapshot( after, snapshot(otherWorktree, SECOND_LEAF_ID, 2), otherHost, NOW + 2 ) - } + ) + const next = store.getState() expect(next.agentStatusByPaneKey.get(sibling)).toBeDefined() - const reopened = { - ...next, - ...applyWebSessionTabsSnapshot(next, snapshot('folder:same', LEAF_ID, 3), 'host-a', NOW + 3) - } + store.setState( + applyWebSessionTabsSnapshot(next, snapshot('folder:same', LEAF_ID, 3), 'host-a', NOW + 3) + ) + const reopened = store.getState() expect(reopened.agentStatusByPaneKey.get(ownPane)).toBeDefined() expect(reopened.agentStatusByPaneKey.get(sibling)).toBeDefined() }