diff --git a/src/main/index.ts b/src/main/index.ts index 96668696f..616097bb9 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -612,9 +612,11 @@ function openMainWindow(): BrowserWindow { } maybeAutoRenameBranchOnFirstWorkFromHook({ paneKey, tabId, worktreeId, payload, isReplay }) const orchestration = runtime?.getAgentStatusOrchestrationContextForPaneKey(paneKey) + const terminalHandle = runtime?.getAgentStatusTerminalHandleForPaneKey(paneKey) mainWindow?.webContents.send('agentStatus:set', { ...payload, paneKey, + ...(terminalHandle ? { terminalHandle } : {}), tabId, worktreeId, connectionId, diff --git a/src/main/ipc/agent-hooks.test.ts b/src/main/ipc/agent-hooks.test.ts index 711cf3982..9cee0fee9 100644 --- a/src/main/ipc/agent-hooks.test.ts +++ b/src/main/ipc/agent-hooks.test.ts @@ -15,6 +15,7 @@ const handleHandlers = new Map u const removeHandler = vi.fn() const removeAllListeners = vi.fn() const PANE_KEY = makePaneKey('tab-1', '11111111-1111-4111-8111-111111111111') +const CHILD_PANE_KEY = makePaneKey('tab-2', '22222222-2222-4222-8222-222222222222') vi.mock('electron', () => ({ ipcMain: { @@ -114,6 +115,68 @@ describe('agentStatus:getSnapshot IPC', () => { expect(handler).toBeDefined() expect(handler!({})).toEqual(snapshot) }) + + it('enriches the hook cache snapshot with runtime lineage metadata', async () => { + const snapshot = [ + { + paneKey: PANE_KEY, + state: 'done', + prompt: 'parent', + agentType: 'codex', + connectionId: null, + receivedAt: 1_700_000_000_000, + stateStartedAt: 1_699_999_999_000 + }, + { + paneKey: CHILD_PANE_KEY, + state: 'done', + prompt: 'child', + agentType: 'codex', + connectionId: null, + receivedAt: 1_700_000_001_000, + stateStartedAt: 1_700_000_000_500 + } + ] + getStatusSnapshot.mockReturnValue(snapshot) + const runtime = { + getAgentStatusTerminalHandleForPaneKey: vi.fn((paneKey: string) => + paneKey === PANE_KEY ? 'term-parent' : paneKey === CHILD_PANE_KEY ? 'term-child' : undefined + ), + getAgentStatusOrchestrationContextForPaneKey: vi.fn((paneKey: string) => + paneKey === CHILD_PANE_KEY + ? { + taskId: 'task-child', + dispatchId: 'dispatch-child', + parentTerminalHandle: 'term-parent', + parentPaneKey: PANE_KEY, + coordinatorHandle: 'term-parent' + } + : undefined + ) + } + const { registerAgentHookHandlers } = await import('./agent-hooks') + registerAgentHookHandlers(runtime) + + const handler = handleHandlers.get('agentStatus:getSnapshot') + expect(handler).toBeDefined() + expect(handler!({})).toEqual([ + { + ...snapshot[0], + terminalHandle: 'term-parent' + }, + { + ...snapshot[1], + terminalHandle: 'term-child', + orchestration: { + taskId: 'task-child', + dispatchId: 'dispatch-child', + parentTerminalHandle: 'term-parent', + parentPaneKey: PANE_KEY, + coordinatorHandle: 'term-parent' + } + } + ]) + }) }) describe('agentHooks:antigravityStatus IPC', () => { diff --git a/src/main/ipc/agent-hooks.ts b/src/main/ipc/agent-hooks.ts index 7637fd0d2..8c0805485 100644 --- a/src/main/ipc/agent-hooks.ts +++ b/src/main/ipc/agent-hooks.ts @@ -5,6 +5,7 @@ import type { MigrationUnsupportedPtyEntry } from '../../shared/agent-status-types' import type { AgentInterruptInferenceRequest } from '../../shared/agent-interrupt-intent' +import type { OrcaRuntimeService } from '../runtime/orca-runtime' import { agentHookServer, isValidPaneKey } from '../agent-hooks/server' import { ampHookService } from '../amp/hook-service' import { @@ -23,11 +24,32 @@ import { copilotHookService } from '../copilot/hook-service' import { hermesHookService } from '../hermes/hook-service' import { openClaudeHookService } from '../openclaude/hook-service' +type AgentStatusRuntimeEnrichment = Pick< + OrcaRuntimeService, + 'getAgentStatusTerminalHandleForPaneKey' | 'getAgentStatusOrchestrationContextForPaneKey' +> + +function enrichAgentStatusIpcPayload( + data: AgentStatusIpcPayload, + runtime: AgentStatusRuntimeEnrichment | undefined +): AgentStatusIpcPayload { + if (!runtime) { + return data + } + const terminalHandle = runtime.getAgentStatusTerminalHandleForPaneKey(data.paneKey) + const orchestration = runtime.getAgentStatusOrchestrationContextForPaneKey(data.paneKey) + return { + ...data, + ...(terminalHandle ? { terminalHandle } : {}), + ...(orchestration ? { orchestration } : {}) + } +} + // Why: install/remove are intentionally not exposed to the renderer. Orca // auto-installs managed hooks at app startup (see src/main/index.ts), so a // renderer-triggered remove would be silently reverted on the next launch // and mislead the user. -export function registerAgentHookHandlers(): void { +export function registerAgentHookHandlers(runtime?: AgentStatusRuntimeEnrichment): void { // Why: matches the defensive pattern in src/main/ipc/pty.ts so re-registration // never throws "Attempted to register a second handler..." if this function is // ever invoked more than once (e.g. the macOS app re-activation path that @@ -71,8 +93,11 @@ export function registerAgentHookHandlers(): void { }) ipcMain.handle('agentStatus:getSnapshot', (): AgentStatusIpcPayload[] => { // Why: the renderer pulls this after workspace hydration, so startup cannot - // lose replayed statuses while its local store is still empty. - return agentHookServer.getStatusSnapshot() + // lose replayed statuses while its local store is still empty. Match the + // live push enrichment in main/index.ts so parent/child rows survive replay. + return agentHookServer + .getStatusSnapshot() + .map((entry) => enrichAgentStatusIpcPayload(entry, runtime)) }) ipcMain.handle('agentStatus:inferInterrupt', (_event, request: unknown): boolean => { if (typeof request !== 'object' || request === null) { diff --git a/src/main/ipc/register-core-handlers.test.ts b/src/main/ipc/register-core-handlers.test.ts index 0a0fb44cc..ee7a90f07 100644 --- a/src/main/ipc/register-core-handlers.test.ts +++ b/src/main/ipc/register-core-handlers.test.ts @@ -357,7 +357,7 @@ describe('registerCoreHandlers', () => { expect(registerOpenCodeUsageHandlersMock).toHaveBeenCalledWith(openCodeUsage) expect(registerAppHandlersMock).toHaveBeenCalledWith(store, { onBeforeRelaunch }) expect(registerCodexAccountHandlersMock).toHaveBeenCalledWith(codexAccounts) - expect(registerAgentHookHandlersMock).toHaveBeenCalled() + expect(registerAgentHookHandlersMock).toHaveBeenCalledWith(runtime) expect(registerPetHandlersMock).toHaveBeenCalled() expect(registerClaudeAccountHandlersMock).toHaveBeenCalledWith(claudeAccounts) expect(registerRateLimitHandlersMock).toHaveBeenCalledWith(rateLimits) diff --git a/src/main/ipc/register-core-handlers.ts b/src/main/ipc/register-core-handlers.ts index 53e676f61..3aeaa9b43 100644 --- a/src/main/ipc/register-core-handlers.ts +++ b/src/main/ipc/register-core-handlers.ts @@ -103,7 +103,7 @@ export function registerCoreHandlers( registerCodexUsageHandlers(codexUsage) registerOpenCodeUsageHandlers(openCodeUsage) registerCodexAccountHandlers(codexAccounts) - registerAgentHookHandlers() + registerAgentHookHandlers(runtime) registerAgentTrustHandlers() registerClaudeAccountHandlers(claudeAccounts) registerRateLimitHandlers(rateLimits) diff --git a/src/main/ipc/runtime.ts b/src/main/ipc/runtime.ts index a13f8419a..e2805fd28 100644 --- a/src/main/ipc/runtime.ts +++ b/src/main/ipc/runtime.ts @@ -3,6 +3,7 @@ import type { OrcaRuntimeService } from '../runtime/orca-runtime' import type { RuntimeBrowserDriverState, RuntimeStatus, + RuntimeSyncWindowGraphResult, RuntimeSyncWindowGraph, RuntimeTerminalDriverState } from '../../shared/runtime-types' @@ -16,7 +17,7 @@ export function registerRuntimeHandlers(runtime: OrcaRuntimeService): void { ipcMain.handle( 'runtime:syncWindowGraph', - (event, graph: RuntimeSyncWindowGraph): RuntimeStatus => { + (event, graph: RuntimeSyncWindowGraph): RuntimeSyncWindowGraphResult => { const window = BrowserWindow.fromWebContents(event.sender) if (!window) { throw new Error('Runtime graph sync must originate from a BrowserWindow') diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index e3cdc190e..a166328c6 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -6,6 +6,7 @@ import { tmpdir } from 'os' import { join } from 'path' import { ipcMain } from 'electron' import type { WorktreeLineage, WorktreeMeta } from '../../shared/types' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../shared/agent-status-types' import { addWorktree, assertWorktreeCleanForRemoval, @@ -39,6 +40,7 @@ import { import { registerSshGitProvider, unregisterSshGitProvider } from '../providers/ssh-git-dispatch' import { DEFAULT_REPO_BADGE_COLOR } from '../../shared/constants' import { advertisedUrlWatcher } from '../ports/advertised-url-watcher' +import { makePaneKey } from '../../shared/stable-pane-id' const electronMocks = vi.hoisted(() => { type Listener = (...args: unknown[]) => void @@ -7706,6 +7708,268 @@ describe('OrcaRuntimeService', () => { ) }) + it('returns active orchestration context for renderer-synced terminal leaves', () => { + const runtime = new OrcaRuntimeService(store) + const workerLeafId = '11111111-1111-4111-8111-111111111111' + const coordinatorLeafId = '22222222-2222-4222-8222-222222222222' + const workerPaneKey = makePaneKey('tab-worker', workerLeafId) + const coordinatorPaneKey = makePaneKey('tab-coordinator', coordinatorLeafId) + const workerHandle = runtime.preAllocateHandleForPty('pty-worker') + const coordinatorHandle = runtime.preAllocateHandleForPty('pty-coordinator') + runtime.setOrchestrationDb({ + getActiveDispatchForTerminal: vi.fn((handle: string) => + handle === workerHandle + ? { + id: 'ctx-1', + task_id: 'task-1', + assignee_handle: workerHandle, + status: 'dispatched' + } + : undefined + ), + getLatestDispatchForTerminal: vi.fn((handle: string) => + handle === workerHandle + ? { + id: 'ctx-done', + task_id: 'task-done', + assignee_handle: workerHandle, + status: 'completed', + completed_at: new Date(Date.now()).toISOString() + } + : undefined + ), + getTask: vi.fn(() => ({ + id: 'task-1', + created_by_terminal_handle: coordinatorHandle + })), + getActiveCoordinatorRun: vi.fn(() => ({ + id: 'run-1', + coordinator_handle: coordinatorHandle + })) + } as never) + runtime.attachWindow(1) + + const result = runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'tab-worker', + worktreeId: TEST_WORKTREE_ID, + title: 'Claude Code', + activeLeafId: workerLeafId, + layout: null + }, + { + tabId: 'tab-coordinator', + worktreeId: TEST_WORKTREE_ID, + title: 'Codex', + activeLeafId: coordinatorLeafId, + layout: null + } + ], + leaves: [ + { + tabId: 'tab-worker', + worktreeId: TEST_WORKTREE_ID, + leafId: workerLeafId, + paneRuntimeId: 1, + ptyId: 'pty-worker', + paneTitle: null + }, + { + tabId: 'tab-coordinator', + worktreeId: TEST_WORKTREE_ID, + leafId: coordinatorLeafId, + paneRuntimeId: 2, + ptyId: 'pty-coordinator', + paneTitle: null + } + ] + }) + + expect(result.agentOrchestrationByPaneKey?.[workerPaneKey]).toMatchObject({ + taskId: 'task-1', + dispatchId: 'ctx-1', + parentPaneKey: coordinatorPaneKey, + parentTerminalHandle: coordinatorHandle, + coordinatorHandle, + orchestrationRunId: 'run-1' + }) + }) + + it('returns completed orchestration context for renderer-synced terminal leaves', () => { + const runtime = new OrcaRuntimeService(store) + const workerLeafId = '33333333-3333-4333-8333-333333333333' + const coordinatorLeafId = '44444444-4444-4444-8444-444444444444' + const workerPaneKey = makePaneKey('tab-worker', workerLeafId) + const coordinatorPaneKey = makePaneKey('tab-coordinator', coordinatorLeafId) + const workerHandle = runtime.preAllocateHandleForPty('pty-worker') + const coordinatorHandle = runtime.preAllocateHandleForPty('pty-coordinator') + runtime.setOrchestrationDb({ + getActiveDispatchForTerminal: vi.fn(() => undefined), + getLatestDispatchForTerminal: vi.fn((handle: string) => + handle === workerHandle + ? { + id: 'ctx-done', + task_id: 'task-done', + assignee_handle: workerHandle, + status: 'completed', + completed_at: new Date(Date.now()).toISOString() + } + : undefined + ), + getTask: vi.fn(() => ({ + id: 'task-done', + created_by_terminal_handle: coordinatorHandle + })) + } as never) + runtime.attachWindow(1) + + const result = runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'tab-worker', + worktreeId: TEST_WORKTREE_ID, + title: 'Claude Code', + activeLeafId: workerLeafId, + layout: null + }, + { + tabId: 'tab-coordinator', + worktreeId: TEST_WORKTREE_ID, + title: 'Codex', + activeLeafId: coordinatorLeafId, + layout: null + } + ], + leaves: [ + { + tabId: 'tab-worker', + worktreeId: TEST_WORKTREE_ID, + leafId: workerLeafId, + paneRuntimeId: 1, + ptyId: 'pty-worker', + paneTitle: null + }, + { + tabId: 'tab-coordinator', + worktreeId: TEST_WORKTREE_ID, + leafId: coordinatorLeafId, + paneRuntimeId: 2, + ptyId: 'pty-coordinator', + paneTitle: null + } + ] + }) + + expect(result.agentOrchestrationByPaneKey?.[workerPaneKey]).toMatchObject({ + taskId: 'task-done', + dispatchId: 'ctx-done', + parentPaneKey: coordinatorPaneKey, + parentTerminalHandle: coordinatorHandle + }) + }) + + it('does not attach an unrelated active coordinator run to a completed dispatch', () => { + const runtime = new OrcaRuntimeService(store) + const workerLeafId = '55555555-5555-4555-8555-555555555555' + const workerPaneKey = makePaneKey('tab-worker', workerLeafId) + const workerHandle = runtime.preAllocateHandleForPty('pty-worker') + runtime.setOrchestrationDb({ + getActiveDispatchForTerminal: vi.fn(() => undefined), + getLatestDispatchForTerminal: vi.fn((handle: string) => + handle === workerHandle + ? { + id: 'ctx-done', + task_id: 'task-done', + assignee_handle: workerHandle, + status: 'completed', + completed_at: new Date(Date.now()).toISOString() + } + : undefined + ), + getTask: vi.fn(() => ({ + id: 'task-done' + })), + getActiveCoordinatorRun: vi.fn(() => ({ + id: 'run-unrelated', + coordinator_handle: 'term_unrelated' + })) + } as never) + runtime.attachWindow(1) + + const result = runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'tab-worker', + worktreeId: TEST_WORKTREE_ID, + title: 'Claude Code', + activeLeafId: workerLeafId, + layout: null + } + ], + leaves: [ + { + tabId: 'tab-worker', + worktreeId: TEST_WORKTREE_ID, + leafId: workerLeafId, + paneRuntimeId: 1, + ptyId: 'pty-worker', + paneTitle: null + } + ] + }) + + expect(result.agentOrchestrationByPaneKey?.[workerPaneKey]).toEqual({ + taskId: 'task-done', + dispatchId: 'ctx-done' + }) + }) + + it('does not return stale completed orchestration context for renderer-synced terminal leaves', () => { + const runtime = new OrcaRuntimeService(store) + const workerLeafId = '77777777-7777-4777-8777-777777777777' + const workerHandle = runtime.preAllocateHandleForPty('pty-worker') + runtime.setOrchestrationDb({ + getActiveDispatchForTerminal: vi.fn(() => undefined), + getLatestDispatchForTerminal: vi.fn((handle: string) => + handle === workerHandle + ? { + id: 'ctx-stale', + task_id: 'task-stale', + assignee_handle: workerHandle, + status: 'completed', + completed_at: new Date(Date.now() - AGENT_STATUS_STALE_AFTER_MS - 1).toISOString() + } + : undefined + ) + } as never) + runtime.attachWindow(1) + + const result = runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'tab-worker', + worktreeId: TEST_WORKTREE_ID, + title: 'Claude Code', + activeLeafId: workerLeafId, + layout: null + } + ], + leaves: [ + { + tabId: 'tab-worker', + worktreeId: TEST_WORKTREE_ID, + leafId: workerLeafId, + paneRuntimeId: 1, + ptyId: 'pty-worker', + paneTitle: null + } + ] + }) + + expect(result.agentOrchestrationByPaneKey).toBeUndefined() + }) + it('falls back to cwd lineage when the caller terminal handle is stale', async () => { const parentPath = '/tmp/worktree-parent' const childPath = '/tmp/workspaces/cwd-child' diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index b5ecb3e2b..30e9cfa99 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -7,7 +7,10 @@ import { isShellProcess } from '../../shared/agent-detection' import type { AgentStatus } from '../../shared/agent-detection' -import type { AgentStatusOrchestrationContext } from '../../shared/agent-status-types' +import { + AGENT_STATUS_STALE_AFTER_MS, + type AgentStatusOrchestrationContext +} from '../../shared/agent-status-types' import { gitExecFileAsync, wslAwareSpawn } from '../git/runner' import { cleanupClaimedCloneTarget, @@ -121,6 +124,7 @@ import type { RuntimeTerminalListResult, RuntimeTerminalState, RuntimeStatus, + RuntimeSyncWindowGraphResult, RuntimeTerminalWait, RuntimeTerminalWaitBlockedReason, RuntimeTerminalWaitCondition, @@ -1793,7 +1797,7 @@ export class OrcaRuntimeService { } } - syncWindowGraph(windowId: number, graph: RuntimeSyncWindowGraph): RuntimeStatus { + syncWindowGraph(windowId: number, graph: RuntimeSyncWindowGraph): RuntimeSyncWindowGraphResult { if (this.authoritativeWindowId === null) { this.authoritativeWindowId = windowId } @@ -1896,7 +1900,11 @@ export class OrcaRuntimeService { cb() } - return this.getStatus() + const agentOrchestrationByPaneKey = this.buildAgentOrchestrationByPaneKey() + return { + ...this.getStatus(), + ...(agentOrchestrationByPaneKey ? { agentOrchestrationByPaneKey } : {}) + } } async listMobileSessionTabs(worktreeSelector: string): Promise { @@ -11501,13 +11509,59 @@ export class OrcaRuntimeService { if (!handle) { return undefined } + return this.getAgentStatusOrchestrationContextForHandle(handle) + } + + getAgentStatusTerminalHandleForPaneKey(paneKey: string): string | undefined { + return this.getTerminalHandleForPaneKey(paneKey) ?? undefined + } + + private buildAgentOrchestrationByPaneKey(): + | Record + | undefined { const db = this.getOrchestrationDbIfAvailable() - const dispatch = db?.getActiveDispatchForTerminal(handle) + if (!db) { + return undefined + } + const contexts: Record = {} + for (const leaf of this.leaves.values()) { + if (!leaf.ptyId) { + continue + } + const handle = this.issueHandle(leaf) + const context = this.getAgentStatusOrchestrationContextForHandle(handle, db) + if (context) { + contexts[this.makeRuntimePaneKey(leaf)] = context + } + } + for (const pty of this.ptysById.values()) { + if (!pty.paneKey || contexts[pty.paneKey]) { + continue + } + const handle = this.issuePtyHandle(pty) + const context = this.getAgentStatusOrchestrationContextForHandle(handle, db) + if (context) { + contexts[pty.paneKey] = context + } + } + return Object.keys(contexts).length > 0 ? contexts : undefined + } + + private getAgentStatusOrchestrationContextForHandle( + handle: string, + db = this.getOrchestrationDbIfAvailable() + ): AgentStatusOrchestrationContext | undefined { + // Why: active dispatches are authoritative for reused terminals. Completed + // context is only useful while the corresponding done/recent row can still + // be visible; after that it would stale-group unrelated future work. + const dispatch = + db?.getActiveDispatchForTerminal?.(handle) ?? + this.getRecentCompletedDispatchForTerminal(handle, db) if (!dispatch) { return undefined } - const task = db?.getTask(dispatch.task_id) - const activeRun = db?.getActiveCoordinatorRun() + const task = db?.getTask?.(dispatch.task_id) + const activeRun = dispatch.status === 'completed' ? undefined : db?.getActiveCoordinatorRun?.() const parentTerminalHandle = task?.created_by_terminal_handle ?? (activeRun?.coordinator_handle && activeRun.coordinator_handle !== handle @@ -11527,6 +11581,25 @@ export class OrcaRuntimeService { } } + private getRecentCompletedDispatchForTerminal( + handle: string, + db = this.getOrchestrationDbIfAvailable() + ): ReturnType { + const dispatch = db?.getLatestDispatchForTerminal?.(handle) + if (dispatch?.status !== 'completed' || !dispatch.completed_at) { + return undefined + } + const completedAtMs = Date.parse( + dispatch.completed_at.includes('T') + ? dispatch.completed_at + : `${dispatch.completed_at.replace(' ', 'T')}Z` + ) + if (!Number.isFinite(completedAtMs)) { + return undefined + } + return Date.now() - completedAtMs <= AGENT_STATUS_STALE_AFTER_MS ? dispatch : undefined + } + private getTerminalHandleForPaneKey(paneKey: string): string | null { const parsed = parsePaneKey(paneKey) if (parsed) { @@ -11552,6 +11625,9 @@ export class OrcaRuntimeService { if (!record || record.runtimeId !== this.runtimeId) { return null } + if (!isTerminalLeafId(record.leafId)) { + return null + } return makePaneKey(record.tabId, record.leafId) } diff --git a/src/main/runtime/orchestration/db.test.ts b/src/main/runtime/orchestration/db.test.ts index 83f09cd13..ae4393b23 100644 --- a/src/main/runtime/orchestration/db.test.ts +++ b/src/main/runtime/orchestration/db.test.ts @@ -364,6 +364,21 @@ describe('OrchestrationDb', () => { expect(d.getActiveDispatchForTerminal('term_b')).toBeUndefined() }) + it('getLatestDispatchForTerminal returns the most recent completed dispatch', () => { + const d = createDb() + const firstTask = d.createTask({ spec: 'first' }) + const first = d.createDispatchContext(firstTask.id, 'term_a') + d.completeDispatch(first.id) + const secondTask = d.createTask({ spec: 'second' }) + const second = d.createDispatchContext(secondTask.id, 'term_a') + d.completeDispatch(second.id) + + const latest = d.getLatestDispatchForTerminal('term_a') + expect(latest?.id).toBe(second.id) + expect(latest?.status).toBe('completed') + expect(d.getActiveDispatchForTerminal('term_a')).toBeUndefined() + }) + it('circuit breaker trips after 3 failures', () => { const d = createDb() const task = d.createTask({ spec: 'flaky' }) diff --git a/src/main/runtime/orchestration/db.ts b/src/main/runtime/orchestration/db.ts index ad48d48a1..9af2e686b 100644 --- a/src/main/runtime/orchestration/db.ts +++ b/src/main/runtime/orchestration/db.ts @@ -610,6 +610,14 @@ export class OrchestrationDb { .get(handle) as DispatchContextRow | undefined } + getLatestDispatchForTerminal(handle: string): DispatchContextRow | undefined { + return this.db + .prepare( + 'SELECT * FROM dispatch_contexts WHERE assignee_handle = ? ORDER BY rowid DESC LIMIT 1' + ) + .get(handle) as DispatchContextRow | undefined + } + completeDispatch(ctxId: string): void { this.db .prepare( diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index f6ea2586f..2fb4fff26 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -196,6 +196,7 @@ import type { RuntimeBrowserDriverState, RuntimeMobileSessionTabMove, RuntimeStatus, + RuntimeSyncWindowGraphResult, RuntimeSyncWindowGraph, RuntimeTerminalDriverState } from '../shared/runtime-types' @@ -2095,7 +2096,7 @@ export type PreloadApi = { confirmWindowClose: () => void } runtime: { - syncWindowGraph: (graph: RuntimeSyncWindowGraph) => Promise + syncWindowGraph: (graph: RuntimeSyncWindowGraph) => Promise getStatus: () => Promise call: (args: { method: string; params?: unknown }) => Promise> getTerminalFitOverrides: () => Promise< diff --git a/src/preload/index.ts b/src/preload/index.ts index ae8be9135..1f2c76308 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -48,6 +48,7 @@ import type { RuntimeBrowserDriverState, RuntimeMobileSessionTabMove, RuntimeStatus, + RuntimeSyncWindowGraphResult, RuntimeSyncWindowGraph, RuntimeTerminalDriverState } from '../shared/runtime-types' @@ -2950,7 +2951,7 @@ const api = { }, runtime: { - syncWindowGraph: (graph: RuntimeSyncWindowGraph): Promise => + syncWindowGraph: (graph: RuntimeSyncWindowGraph): Promise => ipcRenderer.invoke('runtime:syncWindowGraph', graph), getStatus: (): Promise => ipcRenderer.invoke('runtime:getStatus'), call: (args: { method: string; params?: unknown }): Promise> => diff --git a/src/renderer/src/assets/main.css b/src/renderer/src/assets/main.css index 7caa44fa3..f15491656 100644 --- a/src/renderer/src/assets/main.css +++ b/src/renderer/src/assets/main.css @@ -846,7 +846,10 @@ } .worktree-agent-row-hover[data-focused-agent-pane='true'] { - background: color-mix(in srgb, var(--sidebar-foreground) 6%, transparent); + /* Why: a borderless fill. --sidebar-accent ≈ --sidebar in light mode, so the + selection wash mixes sidebar-foreground into the accent to stay legible + without going so dark that muted text (timestamp) drops out. */ + background: color-mix(in srgb, var(--sidebar-foreground) 12%, var(--sidebar-accent)); } .dark .worktree-agent-row-hover:hover { @@ -854,7 +857,7 @@ } .dark .worktree-agent-row-hover[data-focused-agent-pane='true'] { - background: color-mix(in srgb, var(--accent) 30%, transparent); + background: color-mix(in srgb, var(--accent) 70%, transparent); } /* Why: sidebar-accent sits too close to sidebar for this persistent prompt; @@ -877,6 +880,72 @@ background: color-mix(in srgb, var(--sidebar-foreground) 8%, var(--sidebar)); } +.worktree-agent-lineage-parent-row { + /* Why: inline orchestration trees have two chevron levels; the manager row + needs a structural cue that is quieter than the workspace card chrome. */ + background: color-mix(in srgb, var(--sidebar-foreground) 3%, var(--sidebar)); + box-shadow: + inset 2px 0 0 color-mix(in srgb, var(--sidebar-foreground) 38%, transparent), + inset 0 0 0 1px color-mix(in srgb, var(--sidebar-foreground) 10%, transparent); +} + +.worktree-agent-lineage-parent-row.worktree-agent-row-hover:hover { + background: color-mix(in srgb, var(--sidebar-foreground) 6%, var(--sidebar)); +} + +.dark .worktree-agent-lineage-parent-row { + background: color-mix(in srgb, var(--accent) 22%, var(--sidebar)); + box-shadow: + inset 2px 0 0 color-mix(in srgb, var(--accent) 58%, transparent), + inset 0 0 0 1px color-mix(in srgb, var(--accent) 22%, transparent); +} + +.dark .worktree-agent-lineage-parent-row.worktree-agent-row-hover:hover { + background: color-mix(in srgb, var(--accent) 30%, var(--sidebar)); +} + +.worktree-agent-lineage-child-row { + position: relative; + background: color-mix(in srgb, var(--sidebar) 74%, var(--background)); + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--sidebar-foreground) 7%, transparent); +} + +.worktree-agent-lineage-child-row.worktree-agent-row-hover:hover { + background: color-mix(in srgb, var(--sidebar-foreground) 4%, var(--sidebar)); +} + +.worktree-agent-lineage-child-row::before { + content: ''; + position: absolute; + left: 0.15rem; + top: 50%; + width: 0.35rem; + border-top: 1px solid color-mix(in srgb, var(--sidebar-foreground) 20%, transparent); +} + +.dark .worktree-agent-lineage-child-row { + background: color-mix(in srgb, var(--accent) 10%, var(--sidebar)); + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--accent) 16%, transparent); +} + +.dark .worktree-agent-lineage-child-row.worktree-agent-row-hover:hover { + background: color-mix(in srgb, var(--accent) 18%, var(--sidebar)); +} + +.dark .worktree-agent-lineage-child-row::before { + border-top-color: color-mix(in srgb, var(--accent) 42%, transparent); +} + +.worktree-agent-lineage-children { + margin-left: 0.75rem; + padding-left: 0.25rem; + border-left: 1px solid color-mix(in srgb, var(--sidebar-foreground) 22%, transparent); +} + +.dark .worktree-agent-lineage-children { + border-left-color: color-mix(in srgb, var(--accent) 28%, transparent); +} + .worktree-agent-send-target-button { /* Why: the row remains an ordinary agent row during send-target mode; the action itself carries the AI target outline so the clickable affordance @@ -898,11 +967,12 @@ box-shadow: 0 0 0 2px color-mix(in srgb, var(--ring) 50%, transparent); } -/* Why: the virtualized card row is height-measured; animating height would - make TanStack reposition sibling cards on every frame. */ +/* Why: the virtualized card row is height-measured; animate the grid track + instead of explicit height so the reveal stays CSS-owned and interruptible. */ .compact-agent-expansion-grid { display: grid; grid-template-rows: 0fr; + transition: grid-template-rows 180ms cubic-bezier(0.16, 1, 0.3, 1); } .compact-agent-expansion-grid-expanded { @@ -922,13 +992,40 @@ } .compact-agent-expansion-grid-expanded .compact-agent-expansion-content { - animation: compact-agent-expansion-reveal 150ms ease-out both; + animation: compact-agent-expansion-reveal 180ms cubic-bezier(0.16, 1, 0.3, 1) both; +} + +/* Why: the expanded summary becomes one enclosed panel. Keep the box model + stable across states (padding always reserved, border drawn as a non-layout + box-shadow) and fade only the chrome, so toggling doesn't snap the header and + rows while the content height animates. */ +.compact-agent-summary-panel { + padding: 2px; + border-radius: var(--radius-sm, 0.25rem); + background: transparent; + box-shadow: inset 0 0 0 1px transparent; + transition: + background 180ms cubic-bezier(0.16, 1, 0.3, 1), + box-shadow 180ms cubic-bezier(0.16, 1, 0.3, 1); +} + +.compact-agent-summary-panel-expanded { + background: color-mix(in srgb, var(--sidebar-accent) 20%, transparent); + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--sidebar-border) 70%, transparent); } @media (prefers-reduced-motion: reduce) { + .compact-agent-expansion-grid { + transition-duration: 0ms; + } + .compact-agent-expansion-grid-expanded .compact-agent-expansion-content { animation-duration: 0ms; } + + .compact-agent-summary-panel { + transition-duration: 0ms; + } } .scroll-to-current-workspace-reveal-highlight { diff --git a/src/renderer/src/components/dashboard/DashboardAgentChildDisclosure.tsx b/src/renderer/src/components/dashboard/DashboardAgentChildDisclosure.tsx index 5cf8d0527..e5c86b176 100644 --- a/src/renderer/src/components/dashboard/DashboardAgentChildDisclosure.tsx +++ b/src/renderer/src/components/dashboard/DashboardAgentChildDisclosure.tsx @@ -50,7 +50,7 @@ export function DashboardAgentChildDisclosure({ onClick={handleToggleChildren} onMouseDown={stopMouseDown} onKeyDown={stopKeyDown} - className="-ml-0.5 inline-flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-sidebar-accent hover:text-foreground" + className="-ml-0.5 inline-flex size-4 shrink-0 items-center justify-center rounded-sm border border-sidebar-border/80 bg-sidebar text-foreground/80 shadow-xs hover:bg-sidebar-accent hover:text-foreground" aria-label={`${childAgentsExpanded ? 'Hide' : 'Show'} ${childAgentCount} child ${ childAgentCount === 1 ? 'agent' : 'agents' }`} diff --git a/src/renderer/src/components/dashboard/DashboardAgentRow.test.tsx b/src/renderer/src/components/dashboard/DashboardAgentRow.test.tsx index 7c5b5c87c..95058d85d 100644 --- a/src/renderer/src/components/dashboard/DashboardAgentRow.test.tsx +++ b/src/renderer/src/components/dashboard/DashboardAgentRow.test.tsx @@ -349,4 +349,25 @@ describe('DashboardAgentRow', () => { expect(classTokens(markup)).toContain('left-[13px]') expect(markup).toContain('aria-level="1"') }) + + it('marks child-disclosure rows as lineage manager rows', () => { + const markup = renderToStaticMarkup( + + + + ) + + expect(classTokens(markup)).toContain('worktree-agent-lineage-parent-row') + expect(markup).toContain('aria-label="Show 2 child agents"') + }) }) diff --git a/src/renderer/src/components/dashboard/DashboardAgentRow.tsx b/src/renderer/src/components/dashboard/DashboardAgentRow.tsx index 928c1afc7..13dc1a20a 100644 --- a/src/renderer/src/components/dashboard/DashboardAgentRow.tsx +++ b/src/renderer/src/components/dashboard/DashboardAgentRow.tsx @@ -296,6 +296,8 @@ const DashboardAgentRow = React.memo(function DashboardAgentRow({ // their hover wash must stay softer than the parent card highlight. // The focused-pane state reuses the same class via data attribute. 'cursor-pointer rounded-sm worktree-agent-row-hover', + hasChildDisclosure && 'worktree-agent-lineage-parent-row', + isLineageChild && 'worktree-agent-lineage-child-row', sendTargetStatus === 'sending' && 'cursor-progress opacity-75', sendTargetStatus === 'disabled' && 'cursor-default opacity-60' )} @@ -392,7 +394,9 @@ const DashboardAgentRow = React.memo(function DashboardAgentRow({ 'block min-w-0 flex-1 overflow-hidden text-[11px] leading-snug', 'transition-[height] duration-200 ease-out [interpolate-size:allow-keywords]', expanded ? 'h-auto whitespace-pre-wrap break-words' : 'h-[1lh] truncate', - isUnvisited ? 'font-semibold text-foreground' : 'font-normal text-muted-foreground' + isUnvisited ? 'font-semibold text-foreground' : 'font-normal text-muted-foreground', + // Why: the selected-row fill washes out muted text — keep it readable. + isFocusedPane && !isUnvisited && 'text-foreground/90' )} title={displayLabel} > diff --git a/src/renderer/src/components/dashboard/agent-row-lineage-model.test.ts b/src/renderer/src/components/dashboard/agent-row-lineage-model.test.ts new file mode 100644 index 000000000..028670a91 --- /dev/null +++ b/src/renderer/src/components/dashboard/agent-row-lineage-model.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it } from 'vitest' +import type { AgentStatusEntry } from '../../../../shared/agent-status-types' +import type { TerminalTab } from '../../../../shared/types' +import type { DashboardAgentRow } from './useDashboardData' +import { buildAgentRowLineageTree } from './agent-row-lineage-model' + +function makeTab(id: string): TerminalTab { + return { + id, + worktreeId: 'wt-1', + ptyId: null, + title: 'Agent', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 0 + } +} + +function makeRow( + paneKey: string, + options: { + terminalHandle?: string + parentPaneKey?: string + parentTerminalHandle?: string + coordinatorHandle?: string + } = {} +): DashboardAgentRow { + const orchestration = + options.parentPaneKey || options.parentTerminalHandle || options.coordinatorHandle + ? { + taskId: `${paneKey}-task`, + dispatchId: `${paneKey}-dispatch`, + ...(options.parentPaneKey ? { parentPaneKey: options.parentPaneKey } : {}), + ...(options.parentTerminalHandle + ? { parentTerminalHandle: options.parentTerminalHandle } + : {}), + ...(options.coordinatorHandle ? { coordinatorHandle: options.coordinatorHandle } : {}) + } + : undefined + const entry: AgentStatusEntry = { + paneKey, + state: 'done', + prompt: paneKey, + updatedAt: 1000, + stateStartedAt: 1000, + stateHistory: [], + agentType: 'codex', + ...(options.terminalHandle ? { terminalHandle: options.terminalHandle } : {}), + ...(orchestration ? { orchestration } : {}) + } + + return { + paneKey, + entry, + tab: makeTab(paneKey.split(':')[0] ?? paneKey), + agentType: 'codex', + state: 'done', + startedAt: 1000 + } +} + +describe('buildAgentRowLineageTree', () => { + it('groups children by explicit parent pane key', () => { + const parent = makeRow('parent:1') + const child = makeRow('child:1', { parentPaneKey: 'parent:1' }) + + const tree = buildAgentRowLineageTree([parent, child]) + + expect(tree.rootRows.map((row) => row.paneKey)).toEqual(['parent:1']) + expect(tree.childrenByParentPaneKey.get('parent:1')?.map((row) => row.paneKey)).toEqual([ + 'child:1' + ]) + }) + + it('falls back to the parent terminal handle when the parent pane key is absent', () => { + const parent = makeRow('parent:1', { terminalHandle: 'term-parent' }) + const child = makeRow('child:1', { parentTerminalHandle: 'term-parent' }) + + const tree = buildAgentRowLineageTree([parent, child]) + + expect(tree.rootRows.map((row) => row.paneKey)).toEqual(['parent:1']) + expect(tree.childrenByParentPaneKey.get('parent:1')?.map((row) => row.paneKey)).toEqual([ + 'child:1' + ]) + }) + + it('uses the coordinator handle as the last visible parent fallback', () => { + const parent = makeRow('parent:1', { terminalHandle: 'term-coordinator' }) + const child = makeRow('child:1', { coordinatorHandle: 'term-coordinator' }) + + const tree = buildAgentRowLineageTree([parent, child]) + + expect(tree.rootRows.map((row) => row.paneKey)).toEqual(['parent:1']) + expect(tree.childrenByParentPaneKey.get('parent:1')?.map((row) => row.paneKey)).toEqual([ + 'child:1' + ]) + }) + + it('keeps cyclic lineage rows visible as flat roots', () => { + const root = makeRow('root:1') + const firstCycleRow = makeRow('cycle-a:1', { parentPaneKey: 'cycle-b:1' }) + const secondCycleRow = makeRow('cycle-b:1', { parentPaneKey: 'cycle-a:1' }) + + const tree = buildAgentRowLineageTree([root, firstCycleRow, secondCycleRow]) + + expect(tree.rootRows.map((row) => row.paneKey)).toEqual(['root:1', 'cycle-a:1', 'cycle-b:1']) + expect(tree.childrenByParentPaneKey.size).toBe(0) + expect(tree.childPaneKeys.size).toBe(0) + }) +}) diff --git a/src/renderer/src/components/dashboard/agent-row-lineage-model.ts b/src/renderer/src/components/dashboard/agent-row-lineage-model.ts new file mode 100644 index 000000000..cb1cf3363 --- /dev/null +++ b/src/renderer/src/components/dashboard/agent-row-lineage-model.ts @@ -0,0 +1,129 @@ +import type { DashboardAgentRow } from './useDashboardData' + +export type AgentRowLineageTree = { + rootRows: T[] + childrenByParentPaneKey: Map + childPaneKeys: Set +} + +function buildPaneKeyByTerminalHandle( + rows: readonly T[] +): Map { + const paneKeyByTerminalHandle = new Map() + for (const row of rows) { + if (row.entry.terminalHandle && !paneKeyByTerminalHandle.has(row.entry.terminalHandle)) { + paneKeyByTerminalHandle.set(row.entry.terminalHandle, row.paneKey) + } + } + return paneKeyByTerminalHandle +} + +export function resolveAgentRowParentPaneKey( + row: T, + rowsByPaneKey: ReadonlyMap, + paneKeyByTerminalHandle: ReadonlyMap +): string | undefined { + const explicitParentPaneKey = row.entry.orchestration?.parentPaneKey + if ( + explicitParentPaneKey && + explicitParentPaneKey !== row.paneKey && + rowsByPaneKey.has(explicitParentPaneKey) + ) { + return explicitParentPaneKey + } + + const parentTerminalHandles = [ + row.entry.orchestration?.parentTerminalHandle, + row.entry.orchestration?.coordinatorHandle + ] + for (const parentTerminalHandle of parentTerminalHandles) { + const parentPaneKey = parentTerminalHandle + ? paneKeyByTerminalHandle.get(parentTerminalHandle) + : undefined + if (parentPaneKey && parentPaneKey !== row.paneKey && rowsByPaneKey.has(parentPaneKey)) { + return parentPaneKey + } + } + + return undefined +} + +export function buildAgentRowLineageTree( + rows: readonly T[] +): AgentRowLineageTree { + const rowsByPaneKey = new Map() + for (const row of rows) { + if (!rowsByPaneKey.has(row.paneKey)) { + rowsByPaneKey.set(row.paneKey, row) + } + } + const paneKeyByTerminalHandle = buildPaneKeyByTerminalHandle(rows) + const childrenByParentPaneKey = new Map() + const childPaneKeys = new Set() + + for (const row of rows) { + const parentPaneKey = resolveAgentRowParentPaneKey(row, rowsByPaneKey, paneKeyByTerminalHandle) + if (!parentPaneKey) { + continue + } + childPaneKeys.add(row.paneKey) + const siblings = childrenByParentPaneKey.get(parentPaneKey) + if (siblings) { + siblings.push(row) + } else { + childrenByParentPaneKey.set(parentPaneKey, [row]) + } + } + + const rootRows = rows.filter((row) => !childPaneKeys.has(row.paneKey)) + if (rootRows.length === 0 && rows.length > 0) { + // Why: malformed orchestration metadata can form a closed cycle. Keep every + // row visible as a flat root instead of hiding all participants. + return { rootRows: [...rows], childrenByParentPaneKey: new Map(), childPaneKeys: new Set() } + } + + const reachablePaneKeys = new Set() + const markReachable = (row: T, ancestorPaneKeys: ReadonlySet = new Set()): void => { + if (reachablePaneKeys.has(row.paneKey) || ancestorPaneKeys.has(row.paneKey)) { + return + } + reachablePaneKeys.add(row.paneKey) + const descendantAncestorPaneKeys = new Set(ancestorPaneKeys) + descendantAncestorPaneKeys.add(row.paneKey) + for (const childRow of childrenByParentPaneKey.get(row.paneKey) ?? []) { + markReachable(childRow, descendantAncestorPaneKeys) + } + } + for (const rootRow of rootRows) { + markReachable(rootRow) + } + + const unreachableRows = rows.filter((row) => !reachablePaneKeys.has(row.paneKey)) + if (unreachableRows.length === 0) { + return { rootRows, childrenByParentPaneKey, childPaneKeys } + } + + const normalizedChildrenByParentPaneKey = new Map(childrenByParentPaneKey) + const normalizedChildPaneKeys = new Set(childPaneKeys) + for (const row of unreachableRows) { + if (!rootRows.some((rootRow) => rootRow.paneKey === row.paneKey)) { + rootRows.push(row) + } + normalizedChildPaneKeys.delete(row.paneKey) + normalizedChildrenByParentPaneKey.delete(row.paneKey) + for (const [parentPaneKey, siblings] of normalizedChildrenByParentPaneKey) { + const visibleSiblings = siblings.filter((sibling) => sibling.paneKey !== row.paneKey) + if (visibleSiblings.length === 0) { + normalizedChildrenByParentPaneKey.delete(parentPaneKey) + } else if (visibleSiblings.length !== siblings.length) { + normalizedChildrenByParentPaneKey.set(parentPaneKey, visibleSiblings) + } + } + } + + return { + rootRows, + childrenByParentPaneKey: normalizedChildrenByParentPaneKey, + childPaneKeys: normalizedChildPaneKeys + } +} diff --git a/src/renderer/src/components/dashboard/agent-row-lineage.ts b/src/renderer/src/components/dashboard/agent-row-lineage.ts index 51aa8cf56..38efc312a 100644 --- a/src/renderer/src/components/dashboard/agent-row-lineage.ts +++ b/src/renderer/src/components/dashboard/agent-row-lineage.ts @@ -1,4 +1,5 @@ import type { DashboardAgentRow } from './useDashboardData' +import { buildAgentRowLineageTree } from './agent-row-lineage-model' export type AgentRowLineagePresentation = { depth: 0 | 1 @@ -23,23 +24,7 @@ export function applyAgentRowLineage(rows: DashboardAgentRow[]): DashboardAgentR return rows.map((row) => ({ ...row, lineage: ROOT_LINEAGE })) } - const rowsByPaneKey = new Map(rows.map((row) => [row.paneKey, row])) - const childrenByParentPaneKey = new Map() - const childPaneKeys = new Set() - - for (const row of rows) { - const parentPaneKey = row.entry.orchestration?.parentPaneKey - if (!parentPaneKey || !rowsByPaneKey.has(parentPaneKey)) { - continue - } - childPaneKeys.add(row.paneKey) - const siblings = childrenByParentPaneKey.get(parentPaneKey) - if (siblings) { - siblings.push(row) - } else { - childrenByParentPaneKey.set(parentPaneKey, [row]) - } - } + const { rootRows, childrenByParentPaneKey, childPaneKeys } = buildAgentRowLineageTree(rows) if (childPaneKeys.size === 0) { return rows.map((row) => ({ ...row, lineage: ROOT_LINEAGE })) @@ -74,10 +59,7 @@ export function applyAgentRowLineage(rows: DashboardAgentRow[]): DashboardAgentR }) } - for (const row of rows) { - if (childPaneKeys.has(row.paneKey)) { - continue - } + for (const row of rootRows) { emitSubtree(row, ROOT_LINEAGE) } diff --git a/src/renderer/src/components/sidebar/WorktreeCard.tsx b/src/renderer/src/components/sidebar/WorktreeCard.tsx index 56ad15f3c..2d40c6c3b 100644 --- a/src/renderer/src/components/sidebar/WorktreeCard.tsx +++ b/src/renderer/src/components/sidebar/WorktreeCard.tsx @@ -607,7 +607,8 @@ const WorktreeCard = React.memo(function WorktreeCard({ // aligned with the pre-inset layout and the repo header hierarchy. const cardStyle = flushSurface ? { - paddingLeft: contentIndent > 0 ? `calc(${contentIndent}px - 0.125rem)` : '0.125rem' + paddingLeft: + contentIndent > 0 ? `max(0.125rem, calc(${contentIndent}px - 0.625rem))` : '0.125rem' } : contentIndent > 0 ? { paddingLeft: `calc(0.125rem + ${contentIndent}px)` } @@ -674,7 +675,7 @@ const WorktreeCard = React.memo(function WorktreeCard({ const cardBody = (
+
{/* Header row: Title */}
@@ -977,7 +983,11 @@ const WorktreeCard = React.memo(function WorktreeCard({
)} - {lineageChildren &&
{lineageChildren}
} + {lineageChildren && ( +
+ {lineageChildren} +
+ )}
) diff --git a/src/renderer/src/components/sidebar/WorktreeCardAgents.test.tsx b/src/renderer/src/components/sidebar/WorktreeCardAgents.test.tsx index bcdbec029..bd9d8fe35 100644 --- a/src/renderer/src/components/sidebar/WorktreeCardAgents.test.tsx +++ b/src/renderer/src/components/sidebar/WorktreeCardAgents.test.tsx @@ -3,6 +3,7 @@ import { renderToStaticMarkup } from 'react-dom/server' import type { ReactNode } from 'react' import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { DashboardAgentRow as DashboardAgentRowData } from '@/components/dashboard/useDashboardData' type MockAgentOptions = { paneKey?: string @@ -13,7 +14,12 @@ type MockAgentOptions = { prompt?: string lastAssistantMessage?: string stateStartedAt?: number - orchestration?: { parentPaneKey: string } + terminalHandle?: string + orchestration?: { + parentPaneKey?: string + parentTerminalHandle?: string + coordinatorHandle?: string + } lineage?: { depth: number isFirstSibling: boolean @@ -31,6 +37,7 @@ function mockAgent({ prompt, lastAssistantMessage, stateStartedAt = 1000, + terminalHandle, orchestration, lineage }: MockAgentOptions = {}): unknown { @@ -46,6 +53,7 @@ function mockAgent({ state, stateStartedAt, stateHistory: prompt === undefined ? undefined : [], + terminalHandle, orchestration }, lineage @@ -182,7 +190,7 @@ describe('WorktreeCardAgents', () => { expect(markup).toContain('data-pane-key="tab-1:2"') }) - it('collapses orchestration child agent rows behind a parent disclosure by default', async () => { + it('shows orchestration child agent rows under their parent by default', async () => { mockAgentActivityDisplayMode = 'full' mockAgents = [ mockAgent({ @@ -213,9 +221,57 @@ describe('WorktreeCardAgents', () => { expect(markup).toContain('role="tree"') expect(markup).toContain('data-pane-key="tab-parent:1"') - expect(markup).not.toContain('data-pane-key="tab-child:1"') - expect(markup).toContain('aria-label="Show 1 child agent"') - expect(markup).toContain('aria-expanded="false"') + expect(markup).toContain('data-pane-key="tab-child:1"') + expect(markup).toContain('aria-label="Hide 1 child agent"') + expect(markup).toContain('aria-expanded="true"') + }) + + it('shows orchestration children under a retained parent matched by terminal handle', async () => { + mockAgentActivityDisplayMode = 'full' + mockAgents = [ + mockAgent({ + paneKey: 'tab-parent:1', + terminalHandle: 'term-parent' + }), + mockAgent({ + paneKey: 'tab-child:1', + state: 'done', + stateStartedAt: 1500, + orchestration: { parentTerminalHandle: 'term-parent' } + }) + ] + const { default: WorktreeCardAgents } = await import('./WorktreeCardAgents') + + const markup = renderToStaticMarkup() + + expect(markup).toContain('role="tree"') + expect(markup).toContain('data-pane-key="tab-parent:1"') + expect(markup).toContain('data-pane-key="tab-child:1"') + expect(markup).toContain('aria-label="Hide 1 child agent"') + }) + + it('shows orchestration children under a visible coordinator when parent handle is absent', async () => { + mockAgentActivityDisplayMode = 'full' + mockAgents = [ + mockAgent({ + paneKey: 'tab-parent:1', + terminalHandle: 'term-coordinator' + }), + mockAgent({ + paneKey: 'tab-child:1', + state: 'done', + stateStartedAt: 1500, + orchestration: { coordinatorHandle: 'term-coordinator' } + }) + ] + const { default: WorktreeCardAgents } = await import('./WorktreeCardAgents') + + const markup = renderToStaticMarkup() + + expect(markup).toContain('role="tree"') + expect(markup).toContain('data-pane-key="tab-parent:1"') + expect(markup).toContain('data-pane-key="tab-child:1"') + expect(markup).toContain('aria-label="Hide 1 child agent"') }) it('keeps partially cyclic orchestration rows visible as flat roots', async () => { @@ -283,6 +339,9 @@ describe('WorktreeCardAgents', () => { expect(markup).toContain('All 2 agents done') expect(markup).toContain('Expand All 2 agents done') + expect(markup).not.toContain('title="Codex done"') + expect(markup).not.toContain('title="Claude done"') + expect(markup).not.toContain('>2 done<') expect(markup).not.toContain('First agent') expect(markup).not.toContain('Second agent') expect(markup).not.toContain('data-testid="agent-row"') @@ -365,6 +424,9 @@ describe('WorktreeCardAgents', () => { expect(markup).not.toContain('-space-x-1') expect(markup).toContain('3 agents: 1 waiting, 1 working, 1 done') expect(markup).toContain('Expand 3 agents: 1 waiting, 1 working, 1 done') + expect(markup).not.toContain('title="Codex waiting"') + expect(markup).not.toContain('title="Claude working"') + expect(markup).not.toContain('title="Gemini done"') expect(markup).not.toContain('data-testid="agent-row"') }) @@ -413,10 +475,51 @@ describe('WorktreeCardAgents', () => { const markup = renderToStaticMarkup() const iconTitles = [...markup.matchAll(/title="([^"]+)"/g)].map((match) => match[1]) - expect(iconTitles).toEqual(['Codex', 'Gemini', 'Claude']) + expect(iconTitles).toEqual([]) + expect(markup).not.toContain('>5 working<') expect(markup).toContain('>+2<') }) + it('uses a neutral compact summary label while expanded', async () => { + const { CompactAgentSummaryButton } = await import('./worktree-card-compact-agents') + const agents = [ + ['tab-1:1', 'codex', 'One'], + ['tab-1:2', 'codex', 'Two'], + ['tab-1:3', 'codex', 'Three'], + ['tab-1:4', 'gemini', 'Four'], + ['tab-1:5', 'claude', 'Five'] + ].map(([paneKey, agentType, prompt]) => + mockAgent({ paneKey, agentType, startedAt: 1000, prompt }) + ) as DashboardAgentRowData[] + + const markup = renderToStaticMarkup( + + ) + + expect(markup).toContain('aria-expanded="true"') + expect(markup).toContain('Collapse 5 agents') + expect(markup).toContain('>5 agents<') + expect(markup).not.toContain('>+2<') + expect(markup).not.toContain('Expand All 5 agents working') + }) + + it('can slightly indent expanded compact summary content', async () => { + const { CompactAgentExpansion } = await import('./worktree-card-compact-agents') + + const markup = renderToStaticMarkup( + +
Agent row
+
+ ) + + expect(markup).toContain('compact-agent-expansion-content flex flex-col gap-0.5 pt-0.5 pl-1') + }) + it('summarizes compact lineage by parent rows before revealing children', async () => { mockAgentActivityDisplayMode = 'compact' mockAgents = [ @@ -466,6 +569,9 @@ describe('WorktreeCardAgents', () => { expect(markup).toContain('role="tree"') expect(markup).toContain('3 parents: 1 waiting, 1 working, 1 done') + expect(markup).not.toContain('title="Gemini waiting"') + expect(markup).not.toContain('title="Codex working"') + expect(markup).not.toContain('title="Codex done"') expect(markup).not.toContain('Parent A') expect(markup).not.toContain('Child A') }) diff --git a/src/renderer/src/components/sidebar/WorktreeCardAgents.tsx b/src/renderer/src/components/sidebar/WorktreeCardAgents.tsx index 87883bf06..fcce9b871 100644 --- a/src/renderer/src/components/sidebar/WorktreeCardAgents.tsx +++ b/src/renderer/src/components/sidebar/WorktreeCardAgents.tsx @@ -1,3 +1,6 @@ +/* eslint-disable max-lines -- Why: this component keeps compact/full inline + agent rendering and lineage disclosure behavior together; splitting during + this bug fix would risk divergent parent-child row behavior. */ import React, { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react' import { useAppStore } from '@/store' import { activateAndRevealWorktree } from '@/lib/worktree-activation' @@ -16,6 +19,7 @@ import { CompactAgentRow, CompactAgentSummaryButton } from './worktree-card-compact-agents' +import { buildAgentRowLineageTree } from '@/components/dashboard/agent-row-lineage-model' import { DEFAULT_AGENT_ACTIVITY_DISPLAY_MODE } from '../../../../shared/constants' import { revealElementInScrollContainer } from './worktree-sidebar-reveal' @@ -71,70 +75,6 @@ type BodyProps = { className?: string } -type AgentLineageModel = { - rootAgents: DashboardAgentRowData[] - childrenByParentPaneKey: Map -} - -function buildAgentLineageModel(agents: DashboardAgentRowData[]): AgentLineageModel { - const agentPaneKeys = new Set(agents.map((agent) => agent.paneKey)) - const childrenByParentPaneKey = new Map() - const childPaneKeys = new Set() - - for (const agent of agents) { - const parentPaneKey = agent.entry.orchestration?.parentPaneKey - if (!parentPaneKey || !agentPaneKeys.has(parentPaneKey)) { - continue - } - childPaneKeys.add(agent.paneKey) - const siblings = childrenByParentPaneKey.get(parentPaneKey) - if (siblings) { - siblings.push(agent) - } else { - childrenByParentPaneKey.set(parentPaneKey, [agent]) - } - } - - const rootAgents = agents.filter((agent) => !childPaneKeys.has(agent.paneKey)) - if (rootAgents.length === 0 && agents.length > 0) { - // Why: malformed orchestration metadata can theoretically form a cycle. - // Keep every row visible instead of recursing forever or hiding the list. - return { rootAgents: agents, childrenByParentPaneKey: new Map() } - } - - const reachablePaneKeys = new Set() - const markReachable = ( - agent: DashboardAgentRowData, - ancestorPaneKeys: ReadonlySet = new Set() - ): void => { - if (reachablePaneKeys.has(agent.paneKey) || ancestorPaneKeys.has(agent.paneKey)) { - return - } - reachablePaneKeys.add(agent.paneKey) - const descendantAncestorPaneKeys = new Set(ancestorPaneKeys) - descendantAncestorPaneKeys.add(agent.paneKey) - for (const childAgent of childrenByParentPaneKey.get(agent.paneKey) ?? []) { - markReachable(childAgent, descendantAncestorPaneKeys) - } - } - for (const rootAgent of rootAgents) { - markReachable(rootAgent) - } - - for (const agent of agents) { - if (reachablePaneKeys.has(agent.paneKey)) { - continue - } - // Why: a partial cycle alongside a valid root has no true root, so it - // would otherwise disappear. Render malformed participants as flat rows - // and drop their child edges, matching the dashboard lineage fallback. - rootAgents.push(agent) - childrenByParentPaneKey.delete(agent.paneKey) - } - - return { rootAgents, childrenByParentPaneKey } -} - const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({ worktreeId, agents, @@ -255,6 +195,13 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({ scrollToBottomIfOutputSinceLastView: true }) } else { + const liveEntry = useAppStore.getState().agentStatusByPaneKey[paneKey] + if (liveEntry?.worktreeId === worktreeId) { + // Why: orchestration worker status can be worktree-attributed before + // the renderer knows its tab. Keep the visible live row instead of + // dismissing it as stale just because it cannot be focused yet. + return + } dismissStaleAgentRowByKey(paneKey) } }, @@ -265,12 +212,12 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({ // never mount this component (see WorktreeCardAgents), so idle worktrees // don't pay any timer cost. const now = useNow(30_000) - const { rootAgents, childrenByParentPaneKey } = useMemo( - () => buildAgentLineageModel(agents), + const { rootRows: rootAgents, childrenByParentPaneKey } = useMemo( + () => buildAgentRowLineageTree(agents), [agents] ) const hasLineage = childrenByParentPaneKey.size > 0 - const [expandedLineageParents, setExpandedLineageParents] = useState>( + const [collapsedLineageParents, setCollapsedLineageParents] = useState>( () => new Set() ) const [compactRootListExpanded, setCompactRootListExpanded] = useState(false) @@ -278,14 +225,20 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({ useLayoutEffect(() => { if (compactRootListExpanded && agentActivityDisplayMode === 'compact') { dispatchSuppressScrollAdjustment() - // Why: keep any needed reveal scroll in the expansion commit; a delayed - // store reveal paints the tall card once, then scrolls it on the next turn. - revealCompactAgentCard(compactAgentListRootRef.current) + // Why: defer the reveal scroll out of the expand commit. Running it inline + // forces a synchronous sidebar layout that blocks the animation's opening + // frames (a visible jump); next-frame keeps the open smooth and the + // ScrollBehavior 'auto' still lands before the height transition finishes. + const handle = requestAnimationFrame(() => { + revealCompactAgentCard(compactAgentListRootRef.current) + }) + return () => cancelAnimationFrame(handle) } + return undefined }, [agentActivityDisplayMode, compactRootListExpanded]) const toggleLineageParent = useCallback((paneKey: string) => { dispatchSuppressScrollAdjustment() - setExpandedLineageParents((current) => { + setCollapsedLineageParents((current) => { const next = new Set(current) if (next.has(paneKey)) { next.delete(paneKey) @@ -320,7 +273,9 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({ } const childAgents = childrenByParentPaneKey.get(agent.paneKey) ?? [] const hasChildAgents = childAgents.length > 0 - const expanded = expandedLineageParents.has(agent.paneKey) + // Why: spawned child agents are actionable work, so they should be visible + // as soon as the parent appears; the disclosure remains available to fold noise. + const expanded = !collapsedLineageParents.has(agent.paneKey) const sendTarget = isAgentSendTargetModeActive ? (sendTargetsByPaneKey.get(agent.paneKey) ?? { status: 'disabled' as const, @@ -371,11 +326,13 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({ // chevron-shifted column and read as floating fragments. hideLineageConnectors /> - {hasChildAgents && expanded - ? childAgents.map((childAgent) => + {hasChildAgents && expanded ? ( +
+ {childAgents.map((childAgent) => renderAgentBranch(childAgent, descendantAncestorPaneKeys) - ) - : null} + )} +
+ ) : null} ) } @@ -389,7 +346,7 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({ } const childAgents = childrenByParentPaneKey.get(agent.paneKey) ?? [] const hasChildAgents = childAgents.length > 0 - const expanded = expandedLineageParents.has(agent.paneKey) + const expanded = !collapsedLineageParents.has(agent.paneKey) const descendantAncestorPaneKeys = new Set(ancestorPaneKeys) descendantAncestorPaneKeys.add(agent.paneKey) return ( @@ -408,9 +365,11 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({ /> {hasChildAgents ? ( - {childAgents.map((childAgent) => - renderCompactAgentBranch(childAgent, descendantAncestorPaneKeys) - )} +
+ {childAgents.map((childAgent) => + renderCompactAgentBranch(childAgent, descendantAncestorPaneKeys) + )} +
) : null} @@ -437,24 +396,32 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({ role={hasLineage ? 'tree' : 'group'} aria-label="Agents" > - {shouldUseSummaryRow && ( - { - dispatchSuppressScrollAdjustment() - setCompactRootListExpanded((expanded) => !expanded) - }} - /> - )} - {!shouldUseSummaryRow ? ( + {shouldUseSummaryRow ? ( + // Why: when expanded, the header and its agent rows read as a single + // enclosed panel rather than a standalone pill with rows floating + // below it — the border/fill wraps the whole group. +
+ { + dispatchSuppressScrollAdjustment() + setCompactRootListExpanded((expanded) => !expanded) + }} + /> + + {rootAgents.map((rootAgent) => renderCompactAgentBranch(rootAgent))} + +
+ ) : ( rootAgents.map((rootAgent) => renderCompactAgentBranch(rootAgent)) - ) : shouldUseSummaryRow ? ( - - {rootAgents.map((rootAgent) => renderCompactAgentBranch(rootAgent))} - - ) : null} + )}
) } diff --git a/src/renderer/src/components/sidebar/WorktreeList.lineage-child-card.test.ts b/src/renderer/src/components/sidebar/WorktreeList.lineage-child-card.test.ts index b7b4f79be..ecf3ffc70 100644 --- a/src/renderer/src/components/sidebar/WorktreeList.lineage-child-card.test.ts +++ b/src/renderer/src/components/sidebar/WorktreeList.lineage-child-card.test.ts @@ -191,8 +191,26 @@ function makeLineage(worktree: Worktree, parent: Worktree): WorktreeLineage { } } -function setLineageFixtureState(groupBy: 'none' | 'repo' = 'none'): void { - const repo = makeRepo() +function setLineageFixtureState( + groupBy: 'none' | 'repo' = 'none', + options: { projectGrouped?: boolean } = {} +): void { + const projectGroup: ProjectGroup = { + id: 'project-group-1', + name: 'Personal', + parentPath: '/tmp/lineage-order', + parentGroupId: null, + createdFrom: 'manual', + tabOrder: 0, + isCollapsed: false, + color: null, + createdAt: 1, + updatedAt: 1 + } + const repo = { + ...makeRepo(), + projectGroupId: options.projectGrouped ? projectGroup.id : null + } const parent = makeWorktree({ id: 'parent', instanceId: 'parent-instance', @@ -233,6 +251,7 @@ function setLineageFixtureState(groupBy: 'none' | 'repo' = 'none'): void { pendingRevealWorktree: null, prCache: {}, prVisibleRefreshGeneration: 0, + projectGroups: options.projectGrouped ? [projectGroup] : [], ptyIdsByTabId: {}, reorderRepos: vi.fn(), reportVisibleGitHubPRRefreshCandidates: vi.fn(), @@ -378,6 +397,13 @@ describe('WorktreeList lineage child card renderer', () => { expect(agentRowIndex).toBeLessThan(childToggleIndex) }) + it('nests the first-level child workspace card surface under its parent', async () => { + setLineageFixtureState() + const markup = await renderWorktreeListMarkup() + + expect(markup).toContain('
{ setLineageFixtureState() const repo = (mockStore.state.repos as Repo[])[0]! @@ -415,4 +441,16 @@ describe('WorktreeList lineage child card renderer', () => { '
' ) }) + + it('adds project group depth to workspace card content indentation', async () => { + setLineageFixtureState('repo', { projectGrouped: true }) + const markup = await renderWorktreeListMarkup() + + const parentRow = markup.match(/]*id="worktree-list-option-parent"[^>]*>/)?.[0] ?? '' + + expect(parentRow).not.toContain('padding-left') + expect(markup).toContain( + '
' + ) + }) }) diff --git a/src/renderer/src/components/sidebar/WorktreeList.tsx b/src/renderer/src/components/sidebar/WorktreeList.tsx index 1a9499fd0..e15ef90f3 100644 --- a/src/renderer/src/components/sidebar/WorktreeList.tsx +++ b/src/renderer/src/components/sidebar/WorktreeList.tsx @@ -188,6 +188,12 @@ import { type WorktreeSectionActivityState, type WorktreeSectionActivitySummary } from './worktree-section-activity' +import { + WORKTREE_SECTION_HEADER_PADDING_LEFT, + SIDEBAR_TREE_INDENT, + getProjectGroupHeaderPaddingLeft, + getWorktreeCardContentIndent +} from './worktree-list-indentation' export { getScrollTopToRevealBounds, @@ -333,12 +339,7 @@ function getWorktreeVisibilityMenuLabel(repo: Repo): string { return visibility === 'show' ? 'Hide non-Orca worktrees' : 'Show hidden worktrees' } -const LINEAGE_INDENT = 18 -// Why: top-level worktrees are children of their project header; indent the -// group one step so the status dots nest under the folder icon for hierarchy. -const WORKTREE_GROUP_INDENT = 18 -const PROJECT_GROUP_HEADER_BASE_PADDING = 4 -const PROJECT_GROUP_HEADER_INDENT = 10 +const LINEAGE_INDENT = SIDEBAR_TREE_INDENT const SIDEBAR_POINTER_DRAG_THRESHOLD_PX = 4 type VirtualizedWorktreeViewportProps = { @@ -2499,6 +2500,12 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp }) : null const projectGroupDepth = row.projectGroupDepth ?? 0 + // Why: non-project section headers like "All" are labels for the + // flat list, so they should not reserve project hierarchy indent. + const headerPaddingLeft = + isRepoHeader || isProjectGroupHeader + ? getProjectGroupHeaderPaddingLeft(projectGroupDepth) + : WORKTREE_SECTION_HEADER_PADDING_LEFT const isCollapsed = collapsedGroups.has(row.key) const sectionActivity = sectionActivityByGroupKey.get(row.key) ?? EMPTY_WORKTREE_SECTION_ACTIVITY @@ -2548,11 +2555,7 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp 'rounded-md bg-sidebar-accent ring-1 ring-sidebar-ring/40', row.repo && 'overflow-hidden' )} - style={{ - paddingLeft: - PROJECT_GROUP_HEADER_BASE_PADDING + - Math.min(projectGroupDepth, 6) * PROJECT_GROUP_HEADER_INDENT - }} + style={{ paddingLeft: headerPaddingLeft }} onDragOver={ isPinnedHeader ? handleWorkspacePinDragOver @@ -2862,10 +2865,13 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp // Why: child cards render inside the parent card body, so their // first nested level starts flush with that inset. const paddingDepth = nested ? Math.max(0, itemRow.depth - 1) : itemRow.depth - // Why: grouped rows still indent their contents under the header, - // but the card surface spans the full sidebar hit/background row. - const basePadding = !nested && groupBy !== 'none' ? WORKTREE_GROUP_INDENT : 0 - const paddingLeft = basePadding + paddingDepth * LINEAGE_INDENT + // Why: grouped rows inherit their project/group header depth, + // while the card surface still spans the full hit/background row. + const paddingLeft = getWorktreeCardContentIndent({ + isGrouped: !nested && groupBy !== 'none', + groupDepth: itemRow.groupDepth, + lineageDepth: paddingDepth + }) const worktreeDragGroupKey = groupKeyByWorktreeId.get(itemRow.worktree.id) const worktreeDragGroupIndex = groupIndexByWorktreeId.get(itemRow.worktree.id) const revealHighlightTone = @@ -2966,10 +2972,14 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp } } const lineageToggleGroupKey = child.lineageGroupKey + const childCardIndent = Math.max(0, child.depth) * LINEAGE_INDENT + const childContentIndent = Math.max(0, child.depth - 1) * LINEAGE_INDENT return (
0 ? { paddingLeft: `${childCardIndent}px` } : undefined} > event.stopPropagation()} > - - - -
-
- {child.worktree.displayName} -
-
- {child.repo && groupBy !== 'repo' ? ( - - - - {child.repo.displayName} - - - ) : null} - - {branchDisplayName(child.worktree.branch)} - -
- {child.worktree.linkedIssue || child.worktree.comment ? ( -
- {child.worktree.linkedIssue ? ( - - #{child.worktree.linkedIssue} +
0 + ? { paddingLeft: `calc(0.5rem + ${childContentIndent}px)` } + : undefined + } + > + + + +
+
+ {child.worktree.displayName} +
+
+ {child.repo && groupBy !== 'repo' ? ( + + + + {child.repo.displayName} + ) : null} - {child.worktree.linkedIssue && child.worktree.comment ? ' ' : null} - {child.worktree.comment} + + {branchDisplayName(child.worktree.branch)} +
- ) : null} - {showInlineAgentCards ? ( - // Why: nested lineage children use this lightweight - // renderer instead of WorktreeCard, so their inline - // agent rows must be mounted here explicitly. - - ) : null} - {child.lineageChildCount > 0 && lineageToggleGroupKey ? ( -
- - - - - - {child.lineageCollapsed - ? 'Show child workspaces' - : 'Hide child workspaces'} - - -
- ) : null} + {child.worktree.linkedIssue || child.worktree.comment ? ( +
+ {child.worktree.linkedIssue ? ( + + #{child.worktree.linkedIssue} + + ) : null} + {child.worktree.linkedIssue && child.worktree.comment ? ' ' : null} + {child.worktree.comment} +
+ ) : null} + {showInlineAgentCards ? ( + // Why: nested lineage children use this lightweight + // renderer instead of WorktreeCard, so their inline + // agent rows must be mounted here explicitly. + + ) : null} + {child.lineageChildCount > 0 && lineageToggleGroupKey ? ( +
+ + + + + + {child.lineageCollapsed + ? 'Show child workspaces' + : 'Hide child workspaces'} + + +
+ ) : null} +
diff --git a/src/renderer/src/components/sidebar/focused-agent-row-highlight.test.ts b/src/renderer/src/components/sidebar/focused-agent-row-highlight.test.ts index 1f5c87eb6..c3cd30089 100644 --- a/src/renderer/src/components/sidebar/focused-agent-row-highlight.test.ts +++ b/src/renderer/src/components/sidebar/focused-agent-row-highlight.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' import type { AgentStatusEntry, MigrationUnsupportedPtyEntry @@ -10,13 +10,6 @@ import { type FocusedAgentRowHighlightState } from './focused-agent-row-highlight' -vi.mock('@/lib/agent-status', () => ({ - isExplicitAgentStatusFresh: vi.fn( - (entry: AgentStatusEntry, now: number, staleAfterMs: number) => - now - entry.updatedAt <= staleAfterMs - ) -})) - const WORKTREE_ID = 'repo-1::/worktree' const OTHER_WORKTREE_ID = 'repo-1::/other' const TAB_ID = 'tab-1' @@ -89,14 +82,26 @@ function makeState( } describe('getFocusedAgentPaneKeyForWorktree', () => { - it('returns the focused pane key when that pane has a fresh live agent status', () => { + it('returns the focused pane key when that pane has a live agent status', () => { const state = makeState({ agentStatusByPaneKey: { [PANE_KEY]: makeAgentStatusEntry(PANE_KEY) } }) - expect(getFocusedAgentPaneKeyForWorktree(state, WORKTREE_ID, 2_000)).toBe(PANE_KEY) + expect(getFocusedAgentPaneKeyForWorktree(state, WORKTREE_ID)).toBe(PANE_KEY) + }) + + it('highlights a focused row whose status has decayed past freshness', () => { + // Why: the inline card keeps decayed agents visible; clicking one must still + // color the row even though its status is no longer fresh. + const state = makeState({ + agentStatusByPaneKey: { + [PANE_KEY]: makeAgentStatusEntry(PANE_KEY, 1) + } + }) + + expect(getFocusedAgentPaneKeyForWorktree(state, WORKTREE_ID)).toBe(PANE_KEY) }) it('does not return another split pane in the same terminal tab', () => { @@ -106,7 +111,7 @@ describe('getFocusedAgentPaneKeyForWorktree', () => { } }) - expect(getFocusedAgentPaneKeyForWorktree(state, WORKTREE_ID, 2_000)).toBeNull() + expect(getFocusedAgentPaneKeyForWorktree(state, WORKTREE_ID)).toBeNull() }) it('does not highlight while another surface type is active', () => { @@ -117,7 +122,7 @@ describe('getFocusedAgentPaneKeyForWorktree', () => { } }) - expect(getFocusedAgentPaneKeyForWorktree(state, WORKTREE_ID, 2_000)).toBeNull() + expect(getFocusedAgentPaneKeyForWorktree(state, WORKTREE_ID)).toBeNull() }) it('returns retained agent row pane keys for the focused pane', () => { @@ -134,7 +139,7 @@ describe('getFocusedAgentPaneKeyForWorktree', () => { } }) - expect(getFocusedAgentPaneKeyForWorktree(state, WORKTREE_ID, 2_000)).toBe(PANE_KEY) + expect(getFocusedAgentPaneKeyForWorktree(state, WORKTREE_ID)).toBe(PANE_KEY) }) it('returns migration-unsupported agent row pane keys for the focused pane', () => { @@ -144,6 +149,6 @@ describe('getFocusedAgentPaneKeyForWorktree', () => { } }) - expect(getFocusedAgentPaneKeyForWorktree(state, WORKTREE_ID, 2_000)).toBe(PANE_KEY) + expect(getFocusedAgentPaneKeyForWorktree(state, WORKTREE_ID)).toBe(PANE_KEY) }) }) diff --git a/src/renderer/src/components/sidebar/focused-agent-row-highlight.ts b/src/renderer/src/components/sidebar/focused-agent-row-highlight.ts index 8ddc911ca..5f6b2daba 100644 --- a/src/renderer/src/components/sidebar/focused-agent-row-highlight.ts +++ b/src/renderer/src/components/sidebar/focused-agent-row-highlight.ts @@ -1,10 +1,5 @@ import { useAppStore } from '@/store' import type { AppState } from '@/store/types' -import { isExplicitAgentStatusFresh } from '@/lib/agent-status' -import { - AGENT_STATUS_STALE_AFTER_MS, - type AgentStatusEntry -} from '../../../../shared/agent-status-types' import { isTerminalLeafId, makePaneKey } from '../../../../shared/stable-pane-id' export type FocusedAgentRowHighlightState = Pick< @@ -21,8 +16,7 @@ export type FocusedAgentRowHighlightState = Pick< export function getFocusedAgentPaneKeyForWorktree( state: FocusedAgentRowHighlightState, - worktreeId: string, - now = Date.now() + worktreeId: string ): string | null { if (state.activeWorktreeId !== worktreeId || state.activeTabType !== 'terminal') { return null @@ -46,8 +40,11 @@ export function getFocusedAgentPaneKeyForWorktree( } const activePaneKey = makePaneKey(activeTabId, activeLeafId) - const liveEntry = state.agentStatusByPaneKey[activePaneKey] - if (liveEntry && isFreshLiveAgent(liveEntry, now)) { + // Why: the inline card lists every agent attributed to this worktree, even + // after its status decays to idle. Highlight whichever displayed row matches + // the focused pane — gating on freshness left clicked-into stale rows with no + // selection coloring. + if (state.agentStatusByPaneKey[activePaneKey]) { return activePaneKey } @@ -64,7 +61,3 @@ export function getFocusedAgentPaneKeyForWorktree( export function useFocusedAgentPaneKey(worktreeId: string): string | null { return useAppStore((state) => getFocusedAgentPaneKeyForWorktree(state, worktreeId)) } - -function isFreshLiveAgent(entry: AgentStatusEntry, now: number): boolean { - return isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS) -} diff --git a/src/renderer/src/components/sidebar/useWorktreeAgentRows.test.ts b/src/renderer/src/components/sidebar/useWorktreeAgentRows.test.ts index 52d3555bb..5dff9ef77 100644 --- a/src/renderer/src/components/sidebar/useWorktreeAgentRows.test.ts +++ b/src/renderer/src/components/sidebar/useWorktreeAgentRows.test.ts @@ -1,3 +1,5 @@ +/* eslint-disable max-lines -- Why: this suite covers one row-building seam + shared by retention, stale decay, and orchestration lineage regressions. */ import { describe, expect, it } from 'vitest' import { AGENT_STATUS_STALE_AFTER_MS, @@ -110,6 +112,166 @@ describe('buildWorktreeAgentRows', () => { expect(working?.state).toBe('idle') expect(done?.state).toBe('done') }) + + it('renders live worktree-attributed entries even when their tab is absent', () => { + const rows = buildWorktreeAgentRows({ + tabs: [], + entries: [ + makeEntry(PANE_KEY_1, 1000, { + state: 'working', + worktreeId: 'wt-1', + tabId: 'tab-1', + prompt: 'child agent' + }) + ], + retained: [], + now: 2000 + }) + + expect(rows.map((row) => row.paneKey)).toEqual([PANE_KEY_1]) + expect(rows[0]).toMatchObject({ + state: 'working', + tab: { + id: 'tab-1', + worktreeId: 'wt-1' + } + }) + }) + + it('uses runtime orchestration metadata for hook-reported live rows', () => { + const parent = makeEntry(PANE_KEY_1, 1000, { + prompt: 'parent', + state: 'working' + }) + const child = makeEntry(PANE_KEY_2, 1200, { + prompt: 'child', + state: 'working' + }) + const rows = applyAgentRowLineage( + buildWorktreeAgentRows({ + tabs: [makeTab('tab-1'), makeTab('tab-2')], + entries: [parent, child], + retained: [], + runtimeAgentOrchestrationByPaneKey: { + [PANE_KEY_2]: { + taskId: 'task-1', + dispatchId: 'ctx-1', + parentPaneKey: PANE_KEY_1 + } + }, + now: 2000 + }) + ) + + expect(rows.map((row) => row.paneKey)).toEqual([PANE_KEY_1, PANE_KEY_2]) + expect(rows[0].lineage).toMatchObject({ depth: 0, childCount: 1 }) + expect(rows[1].lineage).toMatchObject({ depth: 1, childCount: 0 }) + expect(rows[1].entry.orchestration).toMatchObject({ parentPaneKey: PANE_KEY_1 }) + }) + + it('does not override current hook dispatch identity with mismatched runtime metadata', () => { + const currentParent = makeEntry(PANE_KEY_1, 1000, { + prompt: 'current parent', + state: 'done' + }) + const staleParent = makeEntry(PANE_KEY_3, 1100, { + prompt: 'stale parent', + state: 'working' + }) + const child = makeEntry(PANE_KEY_2, 1200, { + prompt: 'child', + state: 'working', + orchestration: { + taskId: 'task-2', + dispatchId: 'ctx-2', + parentPaneKey: PANE_KEY_1, + parentTerminalHandle: 'term-current' + } + }) + const rows = applyAgentRowLineage( + buildWorktreeAgentRows({ + tabs: [makeTab('tab-1'), makeTab('tab-2'), makeTab('tab-3')], + entries: [currentParent, staleParent, child], + retained: [], + runtimeAgentOrchestrationByPaneKey: { + [PANE_KEY_2]: { + taskId: 'task-1', + dispatchId: 'ctx-1', + parentPaneKey: PANE_KEY_3, + parentTerminalHandle: 'term-stale' + } + }, + now: 2000 + }) + ) + + expect(rows.map((row) => row.paneKey)).toEqual([PANE_KEY_1, PANE_KEY_2, PANE_KEY_3]) + expect(rows[0].lineage).toMatchObject({ depth: 0, childCount: 1 }) + expect(rows[1].lineage).toMatchObject({ depth: 1, childCount: 0 }) + expect(rows[1].entry.orchestration).toEqual({ + taskId: 'task-2', + dispatchId: 'ctx-2', + parentPaneKey: PANE_KEY_1, + parentTerminalHandle: 'term-current' + }) + }) + + it('uses runtime orchestration metadata for retained child rows', () => { + const parent = makeEntry(PANE_KEY_1, 1000, { + prompt: 'parent', + state: 'done' + }) + const retainedChild = makeRetained(PANE_KEY_2, 'wt-1', 1200) + const rows = applyAgentRowLineage( + buildWorktreeAgentRows({ + tabs: [makeTab('tab-1')], + entries: [parent], + retained: [retainedChild], + runtimeAgentOrchestrationByPaneKey: { + [PANE_KEY_2]: { + taskId: 'task-1', + dispatchId: 'ctx-1', + parentPaneKey: PANE_KEY_1 + } + }, + now: 2000 + }) + ) + + expect(rows.map((row) => row.paneKey)).toEqual([PANE_KEY_1, PANE_KEY_2]) + expect(rows[0].lineage).toMatchObject({ depth: 0, childCount: 1 }) + expect(rows[1].lineage).toMatchObject({ depth: 1, childCount: 0 }) + expect(rows[1].entry.orchestration).toMatchObject({ parentPaneKey: PANE_KEY_1 }) + }) + + it('groups child rows by parent terminal handle when parent pane key is missing', () => { + const parent = makeEntry(PANE_KEY_1, 1000, { + prompt: 'parent', + state: 'done', + terminalHandle: 'term-parent' + }) + const child = makeEntry(PANE_KEY_2, 1200, { + prompt: 'child', + state: 'done', + orchestration: { + taskId: 'task-1', + dispatchId: 'ctx-1', + parentTerminalHandle: 'term-parent' + } + }) + const rows = applyAgentRowLineage( + buildWorktreeAgentRows({ + tabs: [makeTab('tab-1'), makeTab('tab-2')], + entries: [parent, child], + retained: [], + now: 2000 + }) + ) + + expect(rows.map((row) => row.paneKey)).toEqual([PANE_KEY_1, PANE_KEY_2]) + expect(rows[0].lineage).toMatchObject({ depth: 0, childCount: 1 }) + expect(rows[1].lineage).toMatchObject({ depth: 1, childCount: 0 }) + }) }) describe('applyAgentRowLineage', () => { diff --git a/src/renderer/src/components/sidebar/useWorktreeAgentRows.ts b/src/renderer/src/components/sidebar/useWorktreeAgentRows.ts index c88e7122c..be3ab7fd4 100644 --- a/src/renderer/src/components/sidebar/useWorktreeAgentRows.ts +++ b/src/renderer/src/components/sidebar/useWorktreeAgentRows.ts @@ -12,6 +12,7 @@ import { buildWorktreeAgentRows } from './worktree-agent-rows' import { selectLiveAgentStatusEntriesForWorktree, selectMigrationUnsupportedEntriesForWorktree, + selectRuntimeAgentOrchestrationForWorktree, selectRetainedAgentEntriesForWorktree, selectTerminalLayoutsForWorktree } from './worktree-agent-row-selectors' @@ -20,6 +21,7 @@ export { buildWorktreeAgentRows } from './worktree-agent-rows' export { selectLiveAgentStatusEntriesForWorktree, selectMigrationUnsupportedEntriesForWorktree, + selectRuntimeAgentOrchestrationForWorktree, selectRetainedAgentEntriesForWorktree } from './worktree-agent-row-selectors' @@ -59,6 +61,9 @@ export function useWorktreeAgentRows(worktreeId: string): DashboardAgentRow[] { const terminalLayoutsByTabId = useAppStore( useShallow((s) => selectTerminalLayoutsForWorktree(s, worktreeId)) ) + const runtimeAgentOrchestrationByPaneKey = useAppStore( + useShallow((s) => selectRuntimeAgentOrchestrationForWorktree(s, worktreeId)) + ) // Why: agentStatusEpoch is included in the dependency array (but not in the // computation itself) so the memo recomputes when freshness boundaries // expire, even if no new PTY data arrives — same rationale as @@ -88,6 +93,7 @@ export function useWorktreeAgentRows(worktreeId: string): DashboardAgentRow[] { runtimePaneTitlesByTabId, ptyIdsByTabId, terminalLayoutsByTabId, + runtimeAgentOrchestrationByPaneKey, now }) ) @@ -100,6 +106,7 @@ export function useWorktreeAgentRows(worktreeId: string): DashboardAgentRow[] { runtimePaneTitlesByTabId, ptyIdsByTabId, terminalLayoutsByTabId, + runtimeAgentOrchestrationByPaneKey, agentStatusEpoch ]) } diff --git a/src/renderer/src/components/sidebar/worktree-agent-row-selectors.test.ts b/src/renderer/src/components/sidebar/worktree-agent-row-selectors.test.ts index 40be718f2..c3d33e7f0 100644 --- a/src/renderer/src/components/sidebar/worktree-agent-row-selectors.test.ts +++ b/src/renderer/src/components/sidebar/worktree-agent-row-selectors.test.ts @@ -9,6 +9,7 @@ import { makePaneKey } from '../../../../shared/stable-pane-id' import { selectLiveAgentStatusEntriesForWorktree, selectMigrationUnsupportedEntriesForWorktree, + selectRuntimeAgentOrchestrationForWorktree, selectRetainedAgentEntriesForWorktree } from './worktree-agent-row-selectors' @@ -129,6 +130,102 @@ describe('selectLiveAgentStatusEntriesForWorktree', () => { expect(secondWt2).not.toBe(firstWt2) expect(secondWt2[0]?.prompt).toBe('updated prompt preview') }) + + it('uses worktree attribution when the status tab is not in the renderer tab list', () => { + const childEntry = makeEntry(PANE_KEY_1, 1000, { + state: 'working', + worktreeId: 'wt-1', + tabId: 'tab-1' + }) + const state = { + tabsByWorktree: { + 'wt-1': [] + }, + agentStatusByPaneKey: { + [PANE_KEY_1]: childEntry + }, + migrationUnsupportedByPtyId: {}, + retainedAgentsByPaneKey: {} + } + + expect(selectLiveAgentStatusEntriesForWorktree(state, 'wt-1')).toEqual([childEntry]) + }) +}) + +describe('selectRuntimeAgentOrchestrationForWorktree', () => { + it('includes child orchestration metadata when only the parent tab is in the worktree', () => { + const childPaneKey = makePaneKey('tab-child', '44444444-4444-4444-8444-444444444444') + const state = { + tabsByWorktree: { + 'wt-1': [makeTab('tab-1')] + }, + agentStatusByPaneKey: {}, + retainedAgentsByPaneKey: {}, + runtimeAgentOrchestrationByPaneKey: { + [childPaneKey]: { + taskId: 'task-1', + dispatchId: 'ctx-1', + parentPaneKey: PANE_KEY_1 + } + } + } + + expect(selectRuntimeAgentOrchestrationForWorktree(state, 'wt-1')).toEqual({ + [childPaneKey]: state.runtimeAgentOrchestrationByPaneKey[childPaneKey] + }) + }) + + it('includes child orchestration metadata for a worktree-attributed live row without tab membership', () => { + const childPaneKey = makePaneKey('tab-child', '44444444-4444-4444-8444-444444444444') + const childEntry = makeEntry(childPaneKey, 1000, { + worktreeId: 'wt-1' + }) + const state = { + tabsByWorktree: { + 'wt-1': [] + }, + agentStatusByPaneKey: { + [childPaneKey]: childEntry + }, + retainedAgentsByPaneKey: {}, + runtimeAgentOrchestrationByPaneKey: { + [childPaneKey]: { + taskId: 'task-1', + dispatchId: 'ctx-1', + parentPaneKey: PANE_KEY_1 + } + } + } + + expect(selectRuntimeAgentOrchestrationForWorktree(state, 'wt-1')).toEqual({ + [childPaneKey]: state.runtimeAgentOrchestrationByPaneKey[childPaneKey] + }) + }) + + it('includes child orchestration metadata for a retained worktree row without tab membership', () => { + const childPaneKey = makePaneKey('tab-child', '44444444-4444-4444-8444-444444444444') + const retainedChild = makeRetained(childPaneKey, 'wt-1', 1000) + const state = { + tabsByWorktree: { + 'wt-1': [] + }, + agentStatusByPaneKey: {}, + retainedAgentsByPaneKey: { + [childPaneKey]: retainedChild + }, + runtimeAgentOrchestrationByPaneKey: { + [childPaneKey]: { + taskId: 'task-1', + dispatchId: 'ctx-1', + parentPaneKey: PANE_KEY_1 + } + } + } + + expect(selectRuntimeAgentOrchestrationForWorktree(state, 'wt-1')).toEqual({ + [childPaneKey]: state.runtimeAgentOrchestrationByPaneKey[childPaneKey] + }) + }) }) describe('selectRetainedAgentEntriesForWorktree', () => { diff --git a/src/renderer/src/components/sidebar/worktree-agent-row-selectors.ts b/src/renderer/src/components/sidebar/worktree-agent-row-selectors.ts index 8159e187e..546618af1 100644 --- a/src/renderer/src/components/sidebar/worktree-agent-row-selectors.ts +++ b/src/renderer/src/components/sidebar/worktree-agent-row-selectors.ts @@ -2,6 +2,7 @@ import type { RetainedAgentEntry } from '@/store/slices/agent-status' import type { AppState } from '@/store/types' import type { AgentStatusEntry, + AgentStatusOrchestrationContext, MigrationUnsupportedPtyEntry } from '../../../../shared/agent-status-types' import { parsePaneKey } from '../../../../shared/stable-pane-id' @@ -10,6 +11,7 @@ import type { TerminalLayoutSnapshot } from '../../../../shared/types' const EMPTY_LIVE_ENTRIES: AgentStatusEntry[] = [] const EMPTY_MIGRATION_UNSUPPORTED_ENTRIES: MigrationUnsupportedPtyEntry[] = [] const EMPTY_RETAINED: RetainedAgentEntry[] = [] +const EMPTY_RUNTIME_AGENT_ORCHESTRATION: Record = {} type WorktreeAgentRowsState = Pick< AppState, @@ -90,7 +92,7 @@ function getLiveEntriesByWorktree(state: WorktreeAgentRowsState): Map, + worktreeId: string +): Record { + const tabs = state.tabsByWorktree[worktreeId] ?? [] + const tabIds = new Set(tabs.map((tab) => tab.id)) + const out: Record = {} + for (const [paneKey, orchestration] of Object.entries(state.runtimeAgentOrchestrationByPaneKey)) { + const parsed = parsePaneKey(paneKey) + const parsedParent = orchestration.parentPaneKey + ? parsePaneKey(orchestration.parentPaneKey) + : null + const liveEntry = state.agentStatusByPaneKey[paneKey] + const retainedEntry = state.retainedAgentsByPaneKey[paneKey] + // Why: child agent terminals can be attributed to a worktree before their + // tab reaches this renderer, or after the row has been retained as done. + // The parent link must still reach that worktree card. + if ( + (parsed && tabIds.has(parsed.tabId)) || + (parsedParent && tabIds.has(parsedParent.tabId)) || + liveEntry?.worktreeId === worktreeId || + retainedEntry?.worktreeId === worktreeId + ) { + out[paneKey] = orchestration + } + } + return Object.keys(out).length > 0 ? out : EMPTY_RUNTIME_AGENT_ORCHESTRATION +} + export function selectTerminalLayoutsForWorktree( state: Pick, worktreeId: string diff --git a/src/renderer/src/components/sidebar/worktree-agent-rows.ts b/src/renderer/src/components/sidebar/worktree-agent-rows.ts index cc686c676..15102a4ca 100644 --- a/src/renderer/src/components/sidebar/worktree-agent-rows.ts +++ b/src/renderer/src/components/sidebar/worktree-agent-rows.ts @@ -3,12 +3,73 @@ import { isExplicitAgentStatusFresh } from '@/lib/agent-status' import type { RetainedAgentEntry } from '@/store/slices/agent-status' import { AGENT_STATUS_STALE_AFTER_MS, - type AgentStatusEntry + type AgentStatusEntry, + type AgentStatusOrchestrationContext } from '../../../../shared/agent-status-types' import { parsePaneKey } from '../../../../shared/stable-pane-id' import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/types' import { buildTitleDerivedAgentRows } from './worktree-title-derived-agent-rows' +function tabFromAttributedStatusEntry(entry: AgentStatusEntry): TerminalTab | null { + const parsed = parsePaneKey(entry.paneKey) + if (!parsed || !entry.worktreeId) { + return null + } + return { + id: parsed.tabId, + ptyId: null, + worktreeId: entry.worktreeId, + title: entry.terminalTitle ?? 'Agent', + customTitle: null, + color: null, + sortOrder: Number.MAX_SAFE_INTEGER, + createdAt: entry.stateStartedAt + } +} + +function orchestrationContextsEqual( + a: AgentStatusOrchestrationContext, + b: AgentStatusOrchestrationContext +): boolean { + return ( + a.taskId === b.taskId && + a.dispatchId === b.dispatchId && + a.parentTerminalHandle === b.parentTerminalHandle && + a.parentPaneKey === b.parentPaneKey && + a.coordinatorHandle === b.coordinatorHandle && + a.orchestrationRunId === b.orchestrationRunId + ) +} + +function entryWithRuntimeOrchestration( + entry: AgentStatusEntry, + runtimeAgentOrchestrationByPaneKey: Record | undefined +): AgentStatusEntry { + const runtimeOrchestration = runtimeAgentOrchestrationByPaneKey?.[entry.paneKey] + const sameDispatch = + entry.orchestration && + runtimeOrchestration && + entry.orchestration.taskId === runtimeOrchestration.taskId && + entry.orchestration.dispatchId === runtimeOrchestration.dispatchId + if (entry.orchestration && runtimeOrchestration && !sameDispatch) { + return entry + } + const orchestration = + sameDispatch && entry.orchestration && runtimeOrchestration + ? { ...entry.orchestration, ...runtimeOrchestration } + : (runtimeOrchestration ?? entry.orchestration) + if (!orchestration || orchestration === entry.orchestration) { + return entry + } + if (entry.orchestration && orchestrationContextsEqual(entry.orchestration, orchestration)) { + return entry + } + // Why: runtime graph metadata can arrive after a hook status ping. Keep old + // fields only for the same dispatch; a reused terminal must not inherit a + // previous worker's stale parent. + return { ...entry, orchestration } +} + export function buildWorktreeAgentRows(args: { tabs: TerminalTab[] entries: AgentStatusEntry[] @@ -16,6 +77,7 @@ export function buildWorktreeAgentRows(args: { runtimePaneTitlesByTabId?: Record> ptyIdsByTabId?: Record terminalLayoutsByTabId?: Record + runtimeAgentOrchestrationByPaneKey?: Record now: number }): DashboardAgentRow[] { const rows: DashboardAgentRow[] = [] @@ -38,33 +100,67 @@ export function buildWorktreeAgentRows(args: { for (const tab of args.tabs) { const explicitEntries = entriesByTabId.get(tab.id) ?? [] for (const entry of explicitEntries) { - const isFresh = isExplicitAgentStatusFresh(entry, args.now, AGENT_STATUS_STALE_AFTER_MS) + const rowEntry = entryWithRuntimeOrchestration(entry, args.runtimeAgentOrchestrationByPaneKey) + const isFresh = isExplicitAgentStatusFresh(rowEntry, args.now, AGENT_STATUS_STALE_AFTER_MS) const shouldDecay = !isFresh && - (entry.state === 'working' || entry.state === 'blocked' || entry.state === 'waiting') + (rowEntry.state === 'working' || + rowEntry.state === 'blocked' || + rowEntry.state === 'waiting') rows.push({ - paneKey: entry.paneKey, - entry, + paneKey: rowEntry.paneKey, + entry: rowEntry, tab, - agentType: entry.agentType ?? 'unknown', - state: shouldDecay ? 'idle' : entry.state, - startedAt: entry.stateHistory[0]?.startedAt ?? entry.stateStartedAt + agentType: rowEntry.agentType ?? 'unknown', + state: shouldDecay ? 'idle' : rowEntry.state, + startedAt: rowEntry.stateHistory[0]?.startedAt ?? rowEntry.stateStartedAt }) - seenPaneKeys.add(entry.paneKey) + seenPaneKeys.add(rowEntry.paneKey) } } rows.push(...buildTitleDerivedAgentRows({ ...args, seenPaneKeys })) + // Why: orchestration workers can be attributed to a worktree by main before + // their tab is present in this renderer. Keep those live rows visible in the + // worktree card instead of waiting for tab membership that may never arrive. + for (const entry of args.entries) { + if (seenPaneKeys.has(entry.paneKey)) { + continue + } + const rowEntry = entryWithRuntimeOrchestration(entry, args.runtimeAgentOrchestrationByPaneKey) + const tab = tabFromAttributedStatusEntry(rowEntry) + if (!tab) { + continue + } + const isFresh = isExplicitAgentStatusFresh(rowEntry, args.now, AGENT_STATUS_STALE_AFTER_MS) + const shouldDecay = + !isFresh && + (rowEntry.state === 'working' || rowEntry.state === 'blocked' || rowEntry.state === 'waiting') + rows.push({ + paneKey: rowEntry.paneKey, + entry: rowEntry, + tab, + agentType: rowEntry.agentType ?? 'unknown', + state: shouldDecay ? 'idle' : rowEntry.state, + startedAt: rowEntry.stateHistory[0]?.startedAt ?? rowEntry.stateStartedAt + }) + seenPaneKeys.add(rowEntry.paneKey) + } + for (const ra of args.retained) { if (seenPaneKeys.has(ra.entry.paneKey)) { continue } + const rowEntry = entryWithRuntimeOrchestration( + ra.entry, + args.runtimeAgentOrchestrationByPaneKey + ) rows.push({ - paneKey: ra.entry.paneKey, - entry: ra.entry, + paneKey: rowEntry.paneKey, + entry: rowEntry, tab: ra.tab, - agentType: ra.agentType, + agentType: rowEntry.agentType ?? ra.agentType, state: 'done', startedAt: ra.startedAt }) diff --git a/src/renderer/src/components/sidebar/worktree-card-agent-summary.ts b/src/renderer/src/components/sidebar/worktree-card-agent-summary.ts new file mode 100644 index 000000000..e5a678ad8 --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-card-agent-summary.ts @@ -0,0 +1,130 @@ +import type { AgentDotState } from '@/components/AgentStateDot' +import type { DashboardAgentRow as DashboardAgentRowData } from '@/components/dashboard/useDashboardData' +import { formatAgentTypeLabel } from '@/lib/agent-status' +import type { AgentStatusState } from '../../../../shared/agent-status-types' + +export type SummaryAgentGroup = { + state: AgentDotState + agents: DashboardAgentRowData[] +} + +const SUMMARY_STATE_ORDER: AgentDotState[] = [ + 'waiting', + 'blocked', + 'interrupted', + 'working', + 'done', + 'idle' +] + +function asDotState(state: AgentStatusState | 'idle'): AgentDotState { + switch (state) { + case 'working': + case 'blocked': + case 'waiting': + case 'done': + case 'idle': + return state + } + return 'idle' +} + +export function getAgentDotState(agent: DashboardAgentRowData): AgentDotState { + return agent.entry.interrupted === true ? 'interrupted' : asDotState(agent.state) +} + +export function formatSummaryStateLabel(state: AgentDotState): string { + switch (state) { + case 'waiting': + return 'waiting' + case 'blocked': + return 'blocked' + case 'interrupted': + return 'interrupted' + case 'working': + return 'working' + case 'done': + return 'done' + case 'idle': + return 'idle' + case 'permission': + return 'needs attention' + } +} + +export function buildSummaryAgentGroups(agents: DashboardAgentRowData[]): SummaryAgentGroup[] { + const groups = new Map() + for (const agent of agents) { + const dotState = getAgentDotState(agent) + const group = groups.get(dotState) + if (group) { + group.push(agent) + } else { + groups.set(dotState, [agent]) + } + } + return SUMMARY_STATE_ORDER.flatMap((state) => { + const groupAgents = groups.get(state) + return groupAgents ? [{ state, agents: groupAgents }] : [] + }) +} + +export function summarizeAgents(agents: DashboardAgentRowData[], subjectLabel: string): string { + const counts = new Map() + for (const agent of agents) { + const dotState = getAgentDotState(agent) + counts.set(dotState, (counts.get(dotState) ?? 0) + 1) + } + const parts = SUMMARY_STATE_ORDER.flatMap((state) => { + const count = counts.get(state) ?? 0 + if (count === 0) { + return [] + } + const label = formatSummaryStateLabel(state) + return `${count} ${label}` + }) + if (parts.length === 1) { + const onlyStatusLabel = parts[0].replace(/^\d+\s+/, '') + return agents.length === 1 + ? `${subjectLabel} ${onlyStatusLabel}` + : `All ${subjectLabel} ${onlyStatusLabel}` + } + return `${subjectLabel}: ${parts.join(', ')}` +} + +export function summarizeAgentIdentities(agents: DashboardAgentRowData[]): string { + return agents + .map((agent) => { + const agentLabel = formatAgentTypeLabel(agent.agentType) + const stateLabel = formatSummaryStateLabel(getAgentDotState(agent)) + return `${agentLabel} ${stateLabel}` + }) + .join('; ') +} + +export function selectSummaryGroupIconAgents( + agents: DashboardAgentRowData[], + maxCount: number +): DashboardAgentRowData[] { + const groups = new Map() + agents.forEach((agent, index) => { + const key = agent.agentType ?? 'unknown' + const group = groups.get(key) + if (group) { + group.agents.push(agent) + } else { + groups.set(key, { agents: [agent], firstIndex: index }) + } + }) + const sortedGroups = [...groups.values()].sort( + (a, b) => b.agents.length - a.agents.length || a.firstIndex - b.firstIndex + ) + const selected: DashboardAgentRowData[] = [] + for (const group of sortedGroups) { + if (selected.length >= maxCount) { + break + } + selected.push(group.agents[0]) + } + return selected +} diff --git a/src/renderer/src/components/sidebar/worktree-card-compact-agents.tsx b/src/renderer/src/components/sidebar/worktree-card-compact-agents.tsx index 2eb5009cf..8a8217136 100644 --- a/src/renderer/src/components/sidebar/worktree-card-compact-agents.tsx +++ b/src/renderer/src/components/sidebar/worktree-card-compact-agents.tsx @@ -1,31 +1,21 @@ import React, { useCallback, useRef } from 'react' import { ChevronRight } from 'lucide-react' -import { AgentStateDot, agentStateLabel, type AgentDotState } from '@/components/AgentStateDot' +import { AgentStateDot, agentStateLabel } from '@/components/AgentStateDot' import type { DashboardAgentRow as DashboardAgentRowData } from '@/components/dashboard/useDashboardData' import { AgentIcon } from '@/lib/agent-catalog' import { agentTypeToIconAgent, formatAgentTypeLabel } from '@/lib/agent-status' import { cn } from '@/lib/utils' -import type { AgentStatusState } from '../../../../shared/agent-status-types' import CommentMarkdown from './CommentMarkdown' +import { + buildSummaryAgentGroups, + getAgentDotState, + selectSummaryGroupIconAgents, + summarizeAgentIdentities, + summarizeAgents +} from './worktree-card-agent-summary' const MARKDOWN_IMAGE_PATTERN = /!\[[^\]\n]*\]\([^)]+\)/ -function asDotState(state: AgentStatusState | 'idle'): AgentDotState { - switch (state) { - case 'working': - case 'blocked': - case 'waiting': - case 'done': - case 'idle': - return state - } - return 'idle' -} - -function getAgentDotState(agent: DashboardAgentRowData): AgentDotState { - return agent.entry.interrupted === true ? 'interrupted' : asDotState(agent.state) -} - function formatShortTimeAgo(ts: number, now: number): string { const delta = now - ts if (delta < 60_000) { @@ -86,15 +76,6 @@ function getCompactAgentTime(agent: DashboardAgentRowData, now: number): string return startedAt > 0 ? formatShortTimeAgo(startedAt, now) : null } -const SUMMARY_STATE_ORDER: AgentDotState[] = [ - 'waiting', - 'blocked', - 'interrupted', - 'working', - 'done', - 'idle' -] - function stopActivationKeyPropagation(e: React.KeyboardEvent): void { // Why: the surrounding worktree list handles Enter/Space as row activation. // Focused nested buttons need those keys to stay local. @@ -103,77 +84,6 @@ function stopActivationKeyPropagation(e: React.KeyboardEvent): void { } } -function summarizeAgents(agents: DashboardAgentRowData[], subjectLabel: string): string { - const counts = new Map() - for (const agent of agents) { - const dotState = getAgentDotState(agent) - counts.set(dotState, (counts.get(dotState) ?? 0) + 1) - } - const parts = SUMMARY_STATE_ORDER.flatMap((state) => { - const count = counts.get(state) ?? 0 - if (count === 0) { - return [] - } - const label = - state === 'waiting' - ? 'waiting' - : state === 'blocked' - ? 'blocked' - : state === 'interrupted' - ? 'interrupted' - : state === 'working' - ? 'working' - : state === 'done' - ? 'done' - : 'idle' - return `${count} ${label}` - }) - if (parts.length === 1) { - const onlyStatusLabel = parts[0].replace(/^\d+\s+/, '') - return agents.length === 1 - ? `${subjectLabel} ${onlyStatusLabel}` - : `All ${subjectLabel} ${onlyStatusLabel}` - } - return `${subjectLabel}: ${parts.join(', ')}` -} - -function selectSummaryIconAgents( - agents: DashboardAgentRowData[], - maxCount: number -): DashboardAgentRowData[] { - const groups = new Map() - agents.forEach((agent, index) => { - const key = agent.agentType ?? 'unknown' - const group = groups.get(key) - if (group) { - group.agents.push(agent) - } else { - groups.set(key, { agents: [agent], firstIndex: index }) - } - }) - const sortedGroups = [...groups.values()].sort( - (a, b) => b.agents.length - a.agents.length || a.firstIndex - b.firstIndex - ) - const selected: DashboardAgentRowData[] = [] - for (const group of sortedGroups) { - if (selected.length >= maxCount) { - break - } - selected.push(group.agents[0]) - } - // Why: once every visible agent kind is represented, duplicate slots should - // reflect the largest groups instead of arbitrary list order. - for (const group of sortedGroups) { - for (const agent of group.agents.slice(1)) { - if (selected.length >= maxCount) { - return selected - } - selected.push(agent) - } - } - return selected -} - type CompactAgentSummaryButtonProps = { agents: DashboardAgentRowData[] subjectLabel: string @@ -183,11 +93,13 @@ type CompactAgentSummaryButtonProps = { type CompactAgentExpansionProps = { expanded: boolean + contentClassName?: string children: React.ReactNode } export function CompactAgentExpansion({ expanded, + contentClassName, children }: CompactAgentExpansionProps): React.JSX.Element { const hasRenderedChildrenRef = useRef(expanded) @@ -209,7 +121,12 @@ export function CompactAgentExpansion({ >
{shouldRenderChildren && ( -
+
{children}
)} @@ -225,8 +142,12 @@ export function CompactAgentSummaryButton({ onToggle }: CompactAgentSummaryButtonProps): React.JSX.Element { const summary = summarizeAgents(agents, subjectLabel) - const iconAgents = selectSummaryIconAgents(agents, 3) - const hiddenIconAgentCount = Math.max(0, agents.length - iconAgents.length) + const groups = buildSummaryAgentGroups(agents) + const visibleGroups = groups.slice(0, 3) + const hiddenGroupAgentCount = groups + .slice(visibleGroups.length) + .reduce((count, group) => count + group.agents.length, 0) + const agentIdentitySummary = summarizeAgentIdentities(agents) const stopPointerPropagation = useCallback((e: React.SyntheticEvent) => { e.stopPropagation() }, []) @@ -243,11 +164,18 @@ export function CompactAgentSummaryButton({ type="button" draggable={false} className={cn( - 'group/agent-summary flex h-6 w-full min-w-0 items-center gap-1.5 rounded-sm border border-sidebar-border/70', - 'bg-sidebar-accent/35 px-1.5 text-left text-[11px] leading-none text-muted-foreground', - 'hover:bg-sidebar-accent focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-sidebar-ring' + 'group/agent-summary flex h-6 w-full min-w-0 items-center gap-1 rounded-sm', + 'px-1 text-left text-[11px] leading-none text-muted-foreground', + 'focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-sidebar-ring', + // Why: collapsed it's a standalone pill; expanded it's the header of the + // enclosing panel, so it drops its own border/fill to avoid double chrome. + expanded + ? 'hover:bg-sidebar-accent/60' + : 'border border-sidebar-border/70 bg-sidebar-accent/35 hover:bg-sidebar-accent' )} - aria-label={`${expanded ? 'Collapse' : 'Expand'} ${summary}`} + aria-label={ + expanded ? `Collapse ${subjectLabel}` : `Expand ${summary}. ${agentIdentitySummary}` + } aria-expanded={expanded} onClick={handleToggle} onKeyDown={stopActivationKeyPropagation} @@ -255,22 +183,47 @@ export function CompactAgentSummaryButton({ onPointerDown={stopPointerPropagation} onDragStart={stopPointerPropagation} > - - {iconAgents.map((agent) => ( - - - - ))} - - {summary} - {hiddenIconAgentCount > 0 && ( - - +{hiddenIconAgentCount} + {expanded ? ( + + {subjectLabel} + ) : ( + <> + + {visibleGroups.map((group) => { + const iconAgents = selectSummaryGroupIconAgents(group.agents, 3) + const hiddenIconCount = Math.max(0, group.agents.length - iconAgents.length) + return ( + + + + {iconAgents.map((agent) => ( + + + + ))} + + {hiddenIconCount > 0 && ( + + +{hiddenIconCount} + + )} + + ) + })} + + {hiddenGroupAgentCount > 0 && ( + + +{hiddenGroupAgentCount} + + )} + )} )} - {primary} - {secondary && - {secondary}} + {/* Why: the selected-row fill is strong enough to wash out the dimmed + prompt/secondary text, so lift both toward full foreground when focused. */} + {primary} + {secondary && ( + + {' '} + - {secondary} + + )} {hasChildDisclosure && !childAgentsExpanded && ( - + +{childAgentCount} )} {shortTime && ( - + {shortTime} )} @@ -385,6 +357,8 @@ export const CompactAgentRow = React.memo(function CompactAgentRow({ className={cn( 'group/compact-agent-row min-w-0 cursor-pointer rounded-sm px-1 text-[11px] leading-none', 'text-muted-foreground worktree-agent-row-hover', + hasChildDisclosure && 'worktree-agent-lineage-parent-row', + isLineageChild && 'worktree-agent-lineage-child-row', hasAssistantImage ? 'flex flex-col py-0.5' : 'flex h-6 items-center gap-1', isFocusedPane && 'bg-sidebar-accent' )} diff --git a/src/renderer/src/components/sidebar/worktree-list-groups.test.ts b/src/renderer/src/components/sidebar/worktree-list-groups.test.ts index 6dd20d007..5e648882d 100644 --- a/src/renderer/src/components/sidebar/worktree-list-groups.test.ts +++ b/src/renderer/src/components/sidebar/worktree-list-groups.test.ts @@ -986,6 +986,10 @@ describe('project groups', () => { expect(rows.filter((row) => row.type === 'header').map((row) => row.projectGroupDepth)).toEqual( [0, 1, 2] ) + expect(rows.find((row) => row.type === 'item')).toMatchObject({ + type: 'item', + groupDepth: 2 + }) expect(rows[0]).toMatchObject({ count: 1 }) }) diff --git a/src/renderer/src/components/sidebar/worktree-list-groups.ts b/src/renderer/src/components/sidebar/worktree-list-groups.ts index 0eeca8a67..7d6678a8e 100644 --- a/src/renderer/src/components/sidebar/worktree-list-groups.ts +++ b/src/renderer/src/components/sidebar/worktree-list-groups.ts @@ -58,6 +58,7 @@ export type WorktreeRow = { worktree: Worktree repo: Repo | undefined depth: number + groupDepth: number lineageTrail: boolean[] isLastLineageChild: boolean lineageChildCount: number @@ -246,7 +247,7 @@ function emitPinnedGroup( const lastPinnedIndexByRepoId = new Map() pinned.forEach((worktree, index) => lastPinnedIndexByRepoId.set(worktree.repoId, index)) for (const [index, worktree] of pinned.entries()) { - result.push(buildWorktreeRow(worktree, repoMap, 0, [], false, 0, false)) + result.push(buildWorktreeRow(worktree, repoMap, 0, 0, [], false, 0, false)) const candidate = importedWorktreesByRepo.get(worktree.repoId) if ( candidate && @@ -277,6 +278,7 @@ function buildWorktreeRow( worktree: Worktree, repoMap: Map, depth: number, + groupDepth: number, lineageTrail: boolean[], isLastLineageChild: boolean, lineageChildCount: number, @@ -287,6 +289,7 @@ function buildWorktreeRow( worktree, repo: repoMap.get(worktree.repoId), depth, + groupDepth, lineageTrail, isLastLineageChild, lineageChildCount, @@ -304,12 +307,13 @@ function appendWorktreeRows( options: { nestLineage: boolean collapsedGroups: Set + groupDepth: number } ): void { - const { nestLineage, collapsedGroups } = options + const { nestLineage, collapsedGroups, groupDepth } = options if (!nestLineage) { for (const worktree of worktrees) { - result.push(buildWorktreeRow(worktree, repoMap, 0, [], false, 0, false)) + result.push(buildWorktreeRow(worktree, repoMap, 0, groupDepth, [], false, 0, false)) } return } @@ -347,6 +351,7 @@ function appendWorktreeRows( worktree, repoMap, depth, + groupDepth, lineageTrail, isLastChild, children.length, @@ -445,7 +450,8 @@ export function buildRows( if (!collapsedGroups.has(ALL_GROUP_KEY)) { appendWorktreeRows(result, unpinned, repoMap, lineageById, worktreeMap, { nestLineage, - collapsedGroups + collapsedGroups, + groupDepth: 0 }) } } @@ -606,7 +612,8 @@ export function buildRows( const items = groupBy === 'repo' ? orderMainWorktreeFirst(group.items) : group.items appendWorktreeRows(result, items, repoMap, lineageById, worktreeMap, { nestLineage, - collapsedGroups + collapsedGroups, + groupDepth: projectGroupDepth }) } } diff --git a/src/renderer/src/components/sidebar/worktree-list-imported-rows.test.ts b/src/renderer/src/components/sidebar/worktree-list-imported-rows.test.ts index 96e5dae93..9960ea363 100644 --- a/src/renderer/src/components/sidebar/worktree-list-imported-rows.test.ts +++ b/src/renderer/src/components/sidebar/worktree-list-imported-rows.test.ts @@ -51,6 +51,7 @@ const makeWorktreeRow = (id: string): Extract => ({ worktree: makeWorktree(id), repo, depth: 0, + groupDepth: 0, lineageTrail: [], isLastLineageChild: false, lineageChildCount: 0 diff --git a/src/renderer/src/components/sidebar/worktree-list-indentation.test.ts b/src/renderer/src/components/sidebar/worktree-list-indentation.test.ts new file mode 100644 index 000000000..2f235de07 --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list-indentation.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest' +import { + WORKTREE_SECTION_HEADER_PADDING_LEFT, + getProjectGroupHeaderPaddingLeft, + getWorktreeCardContentIndent +} from './worktree-list-indentation' + +describe('worktree list indentation', () => { + it('keeps ungrouped workspaces flush with the list', () => { + expect(getWorktreeCardContentIndent({ isGrouped: false, groupDepth: 4, lineageDepth: 0 })).toBe( + 0 + ) + }) + + it('indents workspace content one step deeper than its containing project header', () => { + expect(getWorktreeCardContentIndent({ isGrouped: true, groupDepth: 0, lineageDepth: 0 })).toBe( + 18 + ) + expect(getWorktreeCardContentIndent({ isGrouped: true, groupDepth: 1, lineageDepth: 0 })).toBe( + 36 + ) + }) + + it('adds lineage depth after project/group depth', () => { + expect(getWorktreeCardContentIndent({ isGrouped: true, groupDepth: 1, lineageDepth: 2 })).toBe( + 72 + ) + }) + + it('caps header indentation separately from workspace content indentation', () => { + expect(getProjectGroupHeaderPaddingLeft(100)).toBe(70) + }) + + it('keeps flat section headers closer to the sidebar edge than project headers', () => { + expect(WORKTREE_SECTION_HEADER_PADDING_LEFT).toBeLessThan(getProjectGroupHeaderPaddingLeft(0)) + }) +}) diff --git a/src/renderer/src/components/sidebar/worktree-list-indentation.ts b/src/renderer/src/components/sidebar/worktree-list-indentation.ts new file mode 100644 index 000000000..87d60c81f --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list-indentation.ts @@ -0,0 +1,25 @@ +export const SIDEBAR_TREE_INDENT = 18 +export const WORKTREE_SECTION_HEADER_PADDING_LEFT = 6 +export const PROJECT_GROUP_HEADER_BASE_PADDING = 10 +export const PROJECT_GROUP_HEADER_INDENT = 10 +export const MAX_PROJECT_GROUP_HEADER_DEPTH = 6 + +function clampDepth(depth: number): number { + return Math.max(0, Math.floor(Number.isFinite(depth) ? depth : 0)) +} + +export function getProjectGroupHeaderPaddingLeft(depth: number): number { + return ( + PROJECT_GROUP_HEADER_BASE_PADDING + + Math.min(clampDepth(depth), MAX_PROJECT_GROUP_HEADER_DEPTH) * PROJECT_GROUP_HEADER_INDENT + ) +} + +export function getWorktreeCardContentIndent(args: { + isGrouped: boolean + groupDepth: number + lineageDepth: number +}): number { + const groupSteps = args.isGrouped ? clampDepth(args.groupDepth) + 1 : 0 + return (groupSteps + clampDepth(args.lineageDepth)) * SIDEBAR_TREE_INDENT +} diff --git a/src/renderer/src/components/sidebar/worktree-list-sticky-headers.test.ts b/src/renderer/src/components/sidebar/worktree-list-sticky-headers.test.ts index 0ccd595f2..d4a8827a0 100644 --- a/src/renderer/src/components/sidebar/worktree-list-sticky-headers.test.ts +++ b/src/renderer/src/components/sidebar/worktree-list-sticky-headers.test.ts @@ -51,6 +51,7 @@ const makeWorktreeRow = (id: string): Extract => ({ worktree: makeWorktree(id), repo, depth: 0, + groupDepth: 0, lineageTrail: [], isLastLineageChild: false, lineageChildCount: 0 diff --git a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts index 0f2e75c94..a260471a1 100644 --- a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts +++ b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { applyAgentRowLineage } from '@/components/dashboard/agent-row-lineage' import type { TerminalLayoutSnapshot, TerminalTab, TuiAgent } from '../../../../shared/types' import { makePaneKey } from '../../../../shared/stable-pane-id' import { buildWorktreeAgentRows } from './worktree-agent-rows' @@ -33,6 +34,14 @@ function makeSplitLayout(): TerminalLayoutSnapshot { } } +function makeSingleLayout(leafId: string): TerminalLayoutSnapshot { + return { + root: { type: 'leaf', leafId }, + activeLeafId: leafId, + expandedLeafId: null + } +} + describe('buildTitleDerivedAgentRows', () => { it('adds title-derived rows for live agent panes that have no hook status yet', () => { const rows = buildWorktreeAgentRows({ @@ -76,6 +85,43 @@ describe('buildTitleDerivedAgentRows', () => { expect(rows).toHaveLength(0) }) + it('uses runtime orchestration metadata for title-derived worker rows', () => { + const parentPaneKey = makePaneKey('tab-parent', LEAF_ID_1) + const childPaneKey = makePaneKey('tab-child', LEAF_ID_2) + const rows = applyAgentRowLineage( + buildWorktreeAgentRows({ + tabs: [makeTab('tab-parent'), makeTab('tab-child')], + entries: [], + retained: [], + runtimePaneTitlesByTabId: { + 'tab-parent': { 1: '⠋ Codex' }, + 'tab-child': { 1: '⠋ Claude Code' } + }, + ptyIdsByTabId: { + 'tab-parent': ['pty-parent'], + 'tab-child': ['pty-child'] + }, + terminalLayoutsByTabId: { + 'tab-parent': makeSingleLayout(LEAF_ID_1), + 'tab-child': makeSingleLayout(LEAF_ID_2) + }, + runtimeAgentOrchestrationByPaneKey: { + [childPaneKey]: { + taskId: 'task-1', + dispatchId: 'ctx-1', + parentPaneKey + } + }, + now: 2000 + }) + ) + + expect(rows.map((row) => row.paneKey)).toEqual([parentPaneKey, childPaneKey]) + expect(rows[0].lineage).toMatchObject({ depth: 0, childCount: 1 }) + expect(rows[1].lineage).toMatchObject({ depth: 1, childCount: 0 }) + expect(rows[1].entry.orchestration).toMatchObject({ parentPaneKey }) + }) + it('does not infer Claude Code from a spinner-only non-agent title', () => { const rows = buildWorktreeAgentRows({ tabs: [makeTab('tab-1')], diff --git a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts index 6cd2cdeb6..624ef6736 100644 --- a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts +++ b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts @@ -3,6 +3,7 @@ import { detectAgentStatusFromTitle, getAgentLabel } from '@/lib/agent-status' import { tabHasLivePty } from '@/lib/tab-has-live-pty' import { type AgentStatusEntry, + type AgentStatusOrchestrationContext, type AgentStatusState, type AgentType } from '../../../../shared/agent-status-types' @@ -40,6 +41,7 @@ export function buildTitleDerivedAgentRows(args: { runtimePaneTitlesByTabId?: Record> ptyIdsByTabId?: Record terminalLayoutsByTabId?: Record + runtimeAgentOrchestrationByPaneKey?: Record seenPaneKeys: Set now: number }): DashboardAgentRow[] { @@ -70,7 +72,13 @@ export function buildTitleDerivedAgentRows(args: { if (!leafId) { continue } - const row = buildTitleDerivedAgentRow({ tab, leafId, title, now: args.now }) + const row = buildTitleDerivedAgentRow({ + tab, + leafId, + title, + now: args.now, + runtimeAgentOrchestrationByPaneKey: args.runtimeAgentOrchestrationByPaneKey + }) if (!row || args.seenPaneKeys.has(row.paneKey)) { continue } @@ -84,7 +92,13 @@ export function buildTitleDerivedAgentRows(args: { if (!leafId) { continue } - const row = buildTitleDerivedAgentRow({ tab, leafId, title: tab.title, now: args.now }) + const row = buildTitleDerivedAgentRow({ + tab, + leafId, + title: tab.title, + now: args.now, + runtimeAgentOrchestrationByPaneKey: args.runtimeAgentOrchestrationByPaneKey + }) if (!row || args.seenPaneKeys.has(row.paneKey)) { continue } @@ -100,6 +114,7 @@ function buildTitleDerivedAgentRow(args: { leafId: string title: string now: number + runtimeAgentOrchestrationByPaneKey?: Record }): DashboardAgentRow | null { const status = detectAgentStatusFromTitle(args.title) const label = getAgentLabel(args.title) @@ -110,6 +125,7 @@ function buildTitleDerivedAgentRow(args: { return null } const paneKey = makePaneKey(args.tab.id, args.leafId) + const orchestration = args.runtimeAgentOrchestrationByPaneKey?.[paneKey] const agentType = resolveTitleDerivedAgentType(args.title, label) if (!agentType) { return null @@ -127,7 +143,8 @@ function buildTitleDerivedAgentRow(args: { stateHistory: [], agentType, terminalTitle: args.title, - lastAssistantMessage: secondary + lastAssistantMessage: secondary, + ...(orchestration ? { orchestration } : {}) } return { paneKey, diff --git a/src/renderer/src/hooks/useIpcEvents.ts b/src/renderer/src/hooks/useIpcEvents.ts index 5f7d97adf..f2f9c80ee 100644 --- a/src/renderer/src/hooks/useIpcEvents.ts +++ b/src/renderer/src/hooks/useIpcEvents.ts @@ -2204,7 +2204,7 @@ export function useIpcEvents(): void { if (!payload) { return 'dropped' } - const { + let { exists, title, identityTitle, @@ -2212,6 +2212,19 @@ export function useIpcEvents(): void { repoConnectionResolved, owningWorktreeId } = resolvePaneKey(store, data.paneKey) + if (!exists && data.worktreeId) { + // Why: orchestration worker hooks can carry main-side worktree + // attribution before this renderer has a terminal tab for the pane. + // Accept those only when the worktree is known, then keep the normal + // repo connection check below for SSH/local ownership. + const fallbackOwnership = resolveWorktreeConnection(store, data.worktreeId) + if (fallbackOwnership.worktreeExists) { + owningWorktreeId = data.worktreeId + repoConnectionId = fallbackOwnership.repoConnectionId + repoConnectionResolved = fallbackOwnership.repoConnectionResolved + exists = true + } + } if (!exists) { // Why: empty paneKeys are dropped in main before IPC fanout. Reaching // this branch means a non-empty paneKey escaped without a matching @@ -2293,12 +2306,22 @@ export function useIpcEvents(): void { return 'dropped' } const terminalTitle = resolveAgentStatusTerminalTitle(statusPayload, title) - store.setAgentStatus(data.paneKey, statusPayload, terminalTitle, { - updatedAt: data.receivedAt, - stateStartedAt: data.stateStartedAt - }) - applyResolvedAgentTerminalTitleToTab(store, data.paneKey, title, terminalTitle) const statusWorktreeId = data.worktreeId ?? owningWorktreeId + store.setAgentStatus( + data.paneKey, + statusPayload, + terminalTitle, + { + updatedAt: data.receivedAt, + stateStartedAt: data.stateStartedAt + }, + { + tabId: data.tabId, + worktreeId: statusWorktreeId, + terminalHandle: data.terminalHandle + } + ) + applyResolvedAgentTerminalTitleToTab(store, data.paneKey, title, terminalTitle) if (options?.replay !== true && statusWorktreeId) { // Why: local Codex/Claude hooks arrive through this main-process IPC // path, not the PTY OSC fallback, so task-complete notifications must @@ -2683,6 +2706,26 @@ function resolvePaneKey( } } +function resolveWorktreeConnection( + store: ReturnType, + worktreeId: string +): { + worktreeExists: boolean + repoConnectionId: string | null + repoConnectionResolved: boolean +} { + const worktree = getWorktreeMapFromState(store).get(worktreeId) + if (!worktree) { + return { worktreeExists: false, repoConnectionId: null, repoConnectionResolved: false } + } + const repo = getRepoMapFromState(store).get(worktree.repoId) + return { + worktreeExists: true, + repoConnectionId: repo?.connectionId ?? null, + repoConnectionResolved: repo !== undefined + } +} + function resolveHookPayloadAgentType( payload: ParsedAgentStatusPayload, terminalTitle: string | undefined diff --git a/src/renderer/src/runtime/sync-runtime-graph.ts b/src/renderer/src/runtime/sync-runtime-graph.ts index 67501143b..62542dec6 100644 --- a/src/renderer/src/runtime/sync-runtime-graph.ts +++ b/src/renderer/src/runtime/sync-runtime-graph.ts @@ -570,7 +570,10 @@ async function syncRuntimeGraph(): Promise { } try { - await window.api.runtime.syncWindowGraph(graph) + const result = await window.api.runtime.syncWindowGraph(graph) + getStoreState()?.setRuntimeAgentOrchestrationByPaneKey?.( + result?.agentOrchestrationByPaneKey ?? {} + ) } catch (error) { console.error('[runtime] Failed to sync renderer graph:', error) } diff --git a/src/renderer/src/store/slices/agent-status.test.ts b/src/renderer/src/store/slices/agent-status.test.ts index e50526fb2..426c99462 100644 --- a/src/renderer/src/store/slices/agent-status.test.ts +++ b/src/renderer/src/store/slices/agent-status.test.ts @@ -4,7 +4,6 @@ import { AGENT_STATUS_STALE_AFTER_MS, type AgentStatusEntry } from '../../../../shared/agent-status-types' -import type { TerminalTab } from '../../../../shared/types' import type { AppState } from '../types' import type { RetainedAgentEntry } from './agent-status' import { createTestStore, makeTab, makeWorktree } from './store-test-helpers' @@ -107,6 +106,286 @@ describe('agent status freshness expiry', () => { }) }) +describe('agent status routing attribution', () => { + afterEach(() => { + vi.useRealTimers() + }) + + it('stores worktree and tab attribution from accepted hook events', () => { + vi.useFakeTimers() + const store = createTestStore() + + store + .getState() + .setAgentStatus( + 'tab-child:11111111-1111-4111-8111-111111111111', + { state: 'working', prompt: 'child agent', agentType: 'codex' }, + undefined, + undefined, + { tabId: 'tab-child', worktreeId: 'wt-1', terminalHandle: 'term-child' } + ) + + expect( + store.getState().agentStatusByPaneKey['tab-child:11111111-1111-4111-8111-111111111111'] + ).toMatchObject({ + tabId: 'tab-child', + worktreeId: 'wt-1', + terminalHandle: 'term-child' + }) + }) +}) + +describe('agent status runtime orchestration metadata', () => { + afterEach(() => { + vi.useRealTimers() + }) + + it('fills runtime orchestration metadata into existing live entries', () => { + vi.useFakeTimers() + const store = createTestStore() + const childPaneKey = 'tab-child:11111111-1111-4111-8111-111111111111' + const parentPaneKey = 'tab-parent:22222222-2222-4222-8222-222222222222' + + store.getState().setAgentStatus(childPaneKey, { + state: 'working', + prompt: 'child agent', + agentType: 'codex' + }) + const epochBeforeRuntime = store.getState().agentStatusEpoch + store.getState().setRuntimeAgentOrchestrationByPaneKey({ + [childPaneKey]: { + taskId: 'task-1', + dispatchId: 'ctx-1', + parentPaneKey + } + }) + + expect(store.getState().agentStatusByPaneKey[childPaneKey].orchestration).toMatchObject({ + taskId: 'task-1', + dispatchId: 'ctx-1', + parentPaneKey + }) + expect(store.getState().agentStatusEpoch).toBe(epochBeforeRuntime + 1) + }) + + it('replaces stale live orchestration metadata when runtime dispatch identity changes', () => { + vi.useFakeTimers() + const store = createTestStore() + const childPaneKey = 'tab-child:11111111-1111-4111-8111-111111111111' + const staleParentPaneKey = 'tab-parent:22222222-2222-4222-8222-222222222222' + const currentParentPaneKey = 'tab-parent:33333333-3333-4333-8333-333333333333' + + store.getState().setAgentStatus(childPaneKey, { + state: 'working', + prompt: 'child agent', + agentType: 'codex', + orchestration: { + taskId: 'task-1', + dispatchId: 'ctx-1', + parentPaneKey: staleParentPaneKey, + parentTerminalHandle: 'term-stale' + } + }) + store.getState().setRuntimeAgentOrchestrationByPaneKey({ + [childPaneKey]: { + taskId: 'task-2', + dispatchId: 'ctx-2', + parentPaneKey: currentParentPaneKey, + parentTerminalHandle: 'term-current' + } + }) + + expect(store.getState().agentStatusByPaneKey[childPaneKey].orchestration).toEqual({ + taskId: 'task-2', + dispatchId: 'ctx-2', + parentPaneKey: currentParentPaneKey, + parentTerminalHandle: 'term-current' + }) + }) + + it('uses existing orchestration fields only as fallback for the same runtime dispatch', () => { + vi.useFakeTimers() + const store = createTestStore() + const childPaneKey = 'tab-child:11111111-1111-4111-8111-111111111111' + const parentPaneKey = 'tab-parent:22222222-2222-4222-8222-222222222222' + + store.getState().setAgentStatus(childPaneKey, { + state: 'working', + prompt: 'child agent', + agentType: 'codex', + orchestration: { + taskId: 'task-1', + dispatchId: 'ctx-1', + parentPaneKey, + coordinatorHandle: 'term-stale-coordinator' + } + }) + store.getState().setRuntimeAgentOrchestrationByPaneKey({ + [childPaneKey]: { + taskId: 'task-1', + dispatchId: 'ctx-1', + coordinatorHandle: 'term-current-coordinator' + } + }) + + expect(store.getState().agentStatusByPaneKey[childPaneKey].orchestration).toEqual({ + taskId: 'task-1', + dispatchId: 'ctx-1', + parentPaneKey, + coordinatorHandle: 'term-current-coordinator' + }) + }) + + it('keeps current payload orchestration ahead of a stale runtime map entry', () => { + vi.useFakeTimers() + const store = createTestStore() + const childPaneKey = 'tab-child:11111111-1111-4111-8111-111111111111' + + store.getState().setRuntimeAgentOrchestrationByPaneKey({ + [childPaneKey]: { + taskId: 'task-1', + dispatchId: 'ctx-1', + parentTerminalHandle: 'term-stale' + } + }) + store.getState().setAgentStatus(childPaneKey, { + state: 'working', + prompt: 'child agent', + agentType: 'codex', + orchestration: { + taskId: 'task-2', + dispatchId: 'ctx-2', + parentTerminalHandle: 'term-current' + } + }) + + expect(store.getState().agentStatusByPaneKey[childPaneKey].orchestration).toEqual({ + taskId: 'task-2', + dispatchId: 'ctx-2', + parentTerminalHandle: 'term-current' + }) + }) + + it('fills already-synced runtime orchestration metadata into new live entries', () => { + vi.useFakeTimers() + const store = createTestStore() + const childPaneKey = 'tab-child:11111111-1111-4111-8111-111111111111' + const parentPaneKey = 'tab-parent:22222222-2222-4222-8222-222222222222' + + store.getState().setRuntimeAgentOrchestrationByPaneKey({ + [childPaneKey]: { + taskId: 'task-1', + dispatchId: 'ctx-1', + parentPaneKey + } + }) + store.getState().setAgentStatus(childPaneKey, { + state: 'working', + prompt: 'child agent', + agentType: 'codex' + }) + + expect(store.getState().agentStatusByPaneKey[childPaneKey].orchestration).toMatchObject({ + taskId: 'task-1', + dispatchId: 'ctx-1', + parentPaneKey + }) + }) + + it('clears stale live orchestration when a reused pane starts non-orchestrated work', () => { + vi.useFakeTimers() + const store = createTestStore() + const childPaneKey = 'tab-child:11111111-1111-4111-8111-111111111111' + + store.getState().setAgentStatus(childPaneKey, { + state: 'done', + prompt: 'finished child', + agentType: 'codex', + orchestration: { + taskId: 'task-1', + dispatchId: 'ctx-1', + parentTerminalHandle: 'term-parent' + } + }) + store.getState().setRuntimeAgentOrchestrationByPaneKey({}) + store.getState().setAgentStatus(childPaneKey, { + state: 'working', + prompt: 'manual follow-up', + agentType: 'codex' + }) + + expect(store.getState().agentStatusByPaneKey[childPaneKey].orchestration).toBeUndefined() + }) + + it('preserves stale live orchestration for final done rows', () => { + vi.useFakeTimers() + const store = createTestStore() + const childPaneKey = 'tab-child:11111111-1111-4111-8111-111111111111' + + store.getState().setAgentStatus(childPaneKey, { + state: 'working', + prompt: 'child agent', + agentType: 'codex', + orchestration: { + taskId: 'task-1', + dispatchId: 'ctx-1', + parentTerminalHandle: 'term-parent' + } + }) + store.getState().setRuntimeAgentOrchestrationByPaneKey({}) + store.getState().setAgentStatus(childPaneKey, { + state: 'done', + prompt: 'child finished', + agentType: 'codex' + }) + + expect(store.getState().agentStatusByPaneKey[childPaneKey].orchestration).toEqual({ + taskId: 'task-1', + dispatchId: 'ctx-1', + parentTerminalHandle: 'term-parent' + }) + }) + + it('fills runtime orchestration metadata into retained entries', () => { + const store = createTestStore() + const childPaneKey = 'tab-child:11111111-1111-4111-8111-111111111111' + const parentPaneKey = 'tab-parent:22222222-2222-4222-8222-222222222222' + const now = Date.now() + const entry: AgentStatusEntry = { + state: 'done', + prompt: 'child agent', + updatedAt: now, + stateStartedAt: now, + paneKey: childPaneKey, + stateHistory: [] + } + const retained: RetainedAgentEntry = { + entry, + worktreeId: 'wt-1', + tab: makeTab({ id: 'tab-child', worktreeId: 'wt-1', title: 'codex' }), + agentType: 'codex', + startedAt: now + } + + store.getState().retainAgents([retained]) + store.getState().setRuntimeAgentOrchestrationByPaneKey({ + [childPaneKey]: { + taskId: 'task-1', + dispatchId: 'ctx-1', + parentPaneKey + } + }) + + expect( + store.getState().retainedAgentsByPaneKey[childPaneKey].entry.orchestration + ).toMatchObject({ + taskId: 'task-1', + dispatchId: 'ctx-1', + parentPaneKey + }) + }) +}) + describe('agent status tool + assistant fields', () => { // Why: setAgentStatus schedules a real 30-minute freshness setTimeout via // queueMicrotask. Without fake timers those handles leak into the test @@ -416,6 +695,47 @@ describe('agent status PR refresh handoff', () => { }) }) + it('uses hook worktree attribution for PR refresh when the agent tab is not mounted', async () => { + vi.useFakeTimers() + const enqueuePRRefresh = stubGitHubPRRefreshApi() + const store = createTestStore() + seedAgentPRRefreshFixture(store, ['pr']) + store.setState({ tabsByWorktree: { 'wt-1': [] } } as Partial) + const paneKey = 'tab-worker:11111111-1111-4111-8111-111111111111' + + store + .getState() + .setAgentStatus( + paneKey, + { state: 'working', prompt: 'create a PR', agentType: 'codex' }, + undefined, + undefined, + { tabId: 'tab-worker', worktreeId: 'wt-1', terminalHandle: 'term-worker' } + ) + store + .getState() + .setAgentStatus( + paneKey, + { state: 'done', prompt: 'create a PR', agentType: 'codex' }, + undefined, + undefined, + { tabId: 'tab-worker', worktreeId: 'wt-1', terminalHandle: 'term-worker' } + ) + + await flushMicrotasks() + + expect(enqueuePRRefresh).toHaveBeenCalledWith({ + candidate: expect.objectContaining({ + repoPath: '/repo', + branch: 'feature/pr-from-agent', + worktreeId: 'wt-1', + linkedPRNumber: null + }), + reason: 'active', + priority: 80 + }) + }) + it('does not spend a PR refresh when no PR surface is visible', async () => { vi.useFakeTimers() const enqueuePRRefresh = stubGitHubPRRefreshApi() @@ -601,14 +921,14 @@ describe('agent status retention + prefix sweep', () => { const retainedA: RetainedAgentEntry = { entry: entryA, worktreeId: 'wt-a', - tab: { id: 'tab-a', title: 'claude' } as unknown as TerminalTab, + tab: makeTab({ id: 'tab-a', worktreeId: 'wt-a', title: 'claude' }), agentType: 'claude', startedAt: now } const retainedB: RetainedAgentEntry = { entry: entryB, worktreeId: 'wt-b', - tab: { id: 'tab-b', title: 'claude' } as unknown as TerminalTab, + tab: makeTab({ id: 'tab-b', worktreeId: 'wt-b', title: 'claude' }), agentType: 'claude', startedAt: now } @@ -651,14 +971,14 @@ describe('agent status retention + prefix sweep', () => { const retainedA: RetainedAgentEntry = { entry: entryA, worktreeId: 'wt-a', - tab: { id: 'tab-a', title: 'claude' } as unknown as TerminalTab, + tab: makeTab({ id: 'tab-a', worktreeId: 'wt-a', title: 'claude' }), agentType: 'claude', startedAt: now } const retainedB: RetainedAgentEntry = { entry: entryB, worktreeId: 'wt-a', - tab: { id: 'tab-a', title: 'claude' } as unknown as TerminalTab, + tab: makeTab({ id: 'tab-a', worktreeId: 'wt-a', title: 'claude' }), agentType: 'claude', startedAt: now } @@ -678,6 +998,35 @@ describe('agent status retention + prefix sweep', () => { expect(suppressed['tab-a:1']).toBeUndefined() }) + it('dropAgentStatusByWorktree removes live entries attributed before their tab exists', () => { + vi.useFakeTimers() + const store = createTestStore() + const paneKey = 'tab-worker:11111111-1111-4111-8111-111111111111' + + store + .getState() + .setAgentStatus( + paneKey, + { state: 'working', prompt: 'worker', agentType: 'codex' }, + undefined, + undefined, + { + tabId: 'tab-worker', + worktreeId: 'wt-a', + terminalHandle: 'term-worker' + } + ) + store.setState({ + acknowledgedAgentsByPaneKey: { [paneKey]: Date.now() } + } as Partial) + + store.getState().dropAgentStatusByWorktree('wt-a') + + expect(store.getState().agentStatusByPaneKey[paneKey]).toBeUndefined() + expect(store.getState().acknowledgedAgentsByPaneKey[paneKey]).toBeUndefined() + expect(store.getState().retentionSuppressedPaneKeys[paneKey]).toBe(true) + }) + it('pruneRetainedAgents keeps only entries whose worktreeId is in the valid set', () => { const store = createTestStore() const now = Date.now() @@ -700,14 +1049,14 @@ describe('agent status retention + prefix sweep', () => { const retainedA: RetainedAgentEntry = { entry: entryA, worktreeId: 'wt-a', - tab: { id: 'tab-a', title: 'claude' } as unknown as TerminalTab, + tab: makeTab({ id: 'tab-a', worktreeId: 'wt-a', title: 'claude' }), agentType: 'claude', startedAt: now } const retainedB: RetainedAgentEntry = { entry: entryB, worktreeId: 'wt-b', - tab: { id: 'tab-b', title: 'claude' } as unknown as TerminalTab, + tab: makeTab({ id: 'tab-b', worktreeId: 'wt-b', title: 'claude' }), agentType: 'claude', startedAt: now } diff --git a/src/renderer/src/store/slices/agent-status.ts b/src/renderer/src/store/slices/agent-status.ts index f61df8367..ad4cecd91 100644 --- a/src/renderer/src/store/slices/agent-status.ts +++ b/src/renderer/src/store/slices/agent-status.ts @@ -39,6 +39,9 @@ export type AgentStatusSlice = { /** Explicit agent status entries keyed by `${tabId}:${leafId}` composite. * Real-time only — lives in renderer memory, not persisted to disk. */ agentStatusByPaneKey: Record + /** Main-synced dispatch metadata for live terminal panes that may only have + * title-derived status in the renderer. */ + runtimeAgentOrchestrationByPaneKey: Record /** PTYs that still report legacy numeric pane keys but have registry-backed * UUID pane proof. Stored separately from normal hook-reported status. */ migrationUnsupportedByPtyId: Record @@ -61,7 +64,12 @@ export type AgentStatusSlice = { paneKey: string, payload: ParsedAgentStatusPayload & { orchestration?: AgentStatusOrchestrationContext }, terminalTitle?: string, - timing?: { updatedAt?: number; stateStartedAt?: number } + timing?: { updatedAt?: number; stateStartedAt?: number }, + routing?: { tabId?: string; worktreeId?: string; terminalHandle?: string } + ) => void + + setRuntimeAgentOrchestrationByPaneKey: ( + entries: Record ) => void setMigrationUnsupportedPty: (entry: MigrationUnsupportedPtyEntry) => void @@ -88,15 +96,9 @@ export type AgentStatusSlice = { * Used on worktree sleep/remove — the whole worktree surface is folding, so * retained rows must drop even if their original tab is no longer present. * - * Note on orphan-live asymmetry: liveKeys are matched against tab prefixes - * derived from `tabsByWorktree[worktreeId]`. Live entries belonging to the - * same worktree but whose tab has already been pruned from `tabsByWorktree` - * (an orphan-live race) are not swept here. The retained side has a - * fallback (`retained.worktreeId === worktreeId`); the live side does not, - * because live entries do not carry a worktreeId. In practice the gap is - * bounded — `removeAgentStatus` is called on PTY exit — and dropping an - * orphan-live entry on shutdown is best-effort, so accepting the asymmetry - * is the simpler tradeoff. */ + * Live entries are swept by tab prefix and by main-stamped worktree + * attribution so worker rows that arrive before their tab exists do not + * survive sleep/remove. */ dropAgentStatusByWorktree: (worktreeId: string) => void /** Retain agent snapshots (called by the top-level retention sync effect). @@ -169,6 +171,48 @@ function pruneMigrationUnsupportedEntries( return { next: changed ? next : entries, changed } } +function orchestrationContextsEqual( + a: AgentStatusOrchestrationContext, + b: AgentStatusOrchestrationContext +): boolean { + return ( + a.taskId === b.taskId && + a.dispatchId === b.dispatchId && + a.parentTerminalHandle === b.parentTerminalHandle && + a.parentPaneKey === b.parentPaneKey && + a.coordinatorHandle === b.coordinatorHandle && + a.orchestrationRunId === b.orchestrationRunId + ) +} + +function orchestrationMapsEqual( + a: Record, + b: Record +): boolean { + const aKeys = Object.keys(a) + const bKeys = Object.keys(b) + if (aKeys.length !== bKeys.length) { + return false + } + return aKeys.every((key) => b[key] !== undefined && orchestrationContextsEqual(a[key]!, b[key]!)) +} + +function mergeCurrentOrchestrationContext( + existing: AgentStatusOrchestrationContext | undefined, + current: AgentStatusOrchestrationContext +): AgentStatusOrchestrationContext { + if (!existing) { + return current + } + const sameDispatch = + existing.taskId === current.taskId && existing.dispatchId === current.dispatchId + if (!sameDispatch) { + return current + } + const merged = { ...existing, ...current } + return orchestrationContextsEqual(existing, merged) ? existing : merged +} + export const createAgentStatusSlice: StateCreator = ( set, get @@ -195,12 +239,72 @@ export const createAgentStatusSlice: StateCreator { + setRuntimeAgentOrchestrationByPaneKey: (entries) => { + set((s) => { + const runtimeMapChanged = !orchestrationMapsEqual( + s.runtimeAgentOrchestrationByPaneKey, + entries + ) + let nextLive = s.agentStatusByPaneKey + let liveChanged = false + let nextRetained = s.retainedAgentsByPaneKey + let retainedChanged = false + + for (const [paneKey, runtimeOrchestration] of Object.entries(entries)) { + const liveEntry = nextLive[paneKey] + if (liveEntry) { + const merged = mergeCurrentOrchestrationContext( + liveEntry.orchestration, + runtimeOrchestration + ) + if (merged !== liveEntry.orchestration) { + if (!liveChanged) { + nextLive = { ...nextLive } + liveChanged = true + } + nextLive[paneKey] = { ...liveEntry, orchestration: merged } + } + } + + const retainedEntry = nextRetained[paneKey] + if (retainedEntry) { + const merged = mergeCurrentOrchestrationContext( + retainedEntry.entry.orchestration, + runtimeOrchestration + ) + if (merged !== retainedEntry.entry.orchestration) { + if (!retainedChanged) { + nextRetained = { ...nextRetained } + retainedChanged = true + } + nextRetained[paneKey] = { + ...retainedEntry, + entry: { ...retainedEntry.entry, orchestration: merged } + } + } + } + } + + if (!runtimeMapChanged && !liveChanged && !retainedChanged) { + return s + } + + return { + ...(runtimeMapChanged ? { runtimeAgentOrchestrationByPaneKey: entries } : {}), + ...(liveChanged ? { agentStatusByPaneKey: nextLive } : {}), + ...(retainedChanged ? { retainedAgentsByPaneKey: nextRetained } : {}), + ...(liveChanged ? { agentStatusEpoch: s.agentStatusEpoch + 1 } : {}) + } + }) + }, + + setAgentStatus: (paneKey, payload, terminalTitle, timing, routing) => { const updatedAt = timing?.updatedAt ?? Date.now() let completionRefreshWorktreeId: string | null = null let suppressedInheritedTerminalStatus = false @@ -281,6 +385,20 @@ export const createAgentStatusSlice: StateCreatorfresh, or receives @@ -721,9 +846,13 @@ export const createAgentStatusSlice: StateCreator { const tabPrefixes = (s.tabsByWorktree[worktreeId] ?? []).map((tab) => `${tab.id}:`) - const liveKeys = Object.keys(s.agentStatusByPaneKey).filter((k) => - paneKeyMatchesAnyTabPrefix(k, tabPrefixes) - ) + const liveKeys = Object.entries(s.agentStatusByPaneKey) + .filter( + ([paneKey, entry]) => + entry.worktreeId === worktreeId || paneKeyMatchesAnyTabPrefix(paneKey, tabPrefixes) + ) + .map(([paneKey]) => paneKey) + const liveKeySet = new Set(liveKeys) const retainedKeys = Object.entries(s.retainedAgentsByPaneKey) .filter( ([paneKey, retained]) => @@ -738,10 +867,12 @@ export const createAgentStatusSlice: StateCreator paneKeyMatchesAnyTabPrefix(k, tabPrefixes) || retainedKeySet.has(k) + (k) => + paneKeyMatchesAnyTabPrefix(k, tabPrefixes) || liveKeySet.has(k) || retainedKeySet.has(k) ) if (ackKeys.length > 0) { nextAck = { ...nextAck } @@ -830,6 +961,14 @@ export const createAgentStatusSlice: StateCreator & { pr */ export type AgentStatusIpcPayload = ParsedAgentStatusPayload & { paneKey: string + terminalHandle?: string tabId?: string worktreeId?: string /** Identifies the SSH connection the event arrived on, or null for local. diff --git a/src/shared/runtime-types.ts b/src/shared/runtime-types.ts index e1a9c2ff9..d64bc7df0 100644 --- a/src/shared/runtime-types.ts +++ b/src/shared/runtime-types.ts @@ -1,5 +1,5 @@ /* eslint-disable max-lines -- Why: shared type definitions for all runtime RPC methods live in one file for discoverability and import simplicity. */ -import type { AgentStatusEntry } from './agent-status-types' +import type { AgentStatusEntry, AgentStatusOrchestrationContext } from './agent-status-types' import type { BaseRefSearchResult, BrowserCookieImportResult, @@ -101,6 +101,12 @@ export type RuntimeSyncWindowGraph = { mobileSessionTabs?: RuntimeMobileSessionTabsSnapshot[] } +export type RuntimeSyncWindowGraphResult = RuntimeStatus & { + /** Main owns terminal handles/dispatches, so renderer graph sync returns the + * parent metadata needed by title-derived agent rows without name guessing. */ + agentOrchestrationByPaneKey?: Record +} + export type RuntimeMobileSessionTerminalTab = { type: 'terminal' id: string