Show worktree child agents inline (#4371)
* Show worktree-attributed child agents inline - Keep orchestration worker rows visible when hook status arrives before the renderer has a tab for the pane. - Show child agent lineage expanded by default with clearer parent/child styling. - Tighten worktree list indentation so grouped and nested rows align correctly. * Sync agent lineage from runtime graph - Return main-owned orchestration metadata during window graph sync so live, retained, and title-derived agent rows stay grouped under the right parent. - Match lineage by terminal handle when pane keys are unavailable after teardown, and ignore stale completed dispatches. - Adjust sidebar indentation and compact agent row chrome/readability. * Preserve agent lineage across status replay and worktree cleanup - Enrich agent status snapshots with runtime terminal and orchestration metadata - Share lineage tree building between dashboard and sidebar, including coordinator fallback - Avoid applying stale runtime dispatch metadata to current hook statuses - Use worktree attribution for PR refresh and live status removal before tabs mount
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -15,6 +15,7 @@ const handleHandlers = new Map<string, (event: unknown, ...args: unknown[]) => 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', () => {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -103,7 +103,7 @@ export function registerCoreHandlers(
|
||||
registerCodexUsageHandlers(codexUsage)
|
||||
registerOpenCodeUsageHandlers(openCodeUsage)
|
||||
registerCodexAccountHandlers(codexAccounts)
|
||||
registerAgentHookHandlers()
|
||||
registerAgentHookHandlers(runtime)
|
||||
registerAgentTrustHandlers()
|
||||
registerClaudeAccountHandlers(claudeAccounts)
|
||||
registerRateLimitHandlers(rateLimits)
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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<RuntimeMobileSessionTabsResult> {
|
||||
@@ -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<string, AgentStatusOrchestrationContext>
|
||||
| undefined {
|
||||
const db = this.getOrchestrationDbIfAvailable()
|
||||
const dispatch = db?.getActiveDispatchForTerminal(handle)
|
||||
if (!db) {
|
||||
return undefined
|
||||
}
|
||||
const contexts: Record<string, AgentStatusOrchestrationContext> = {}
|
||||
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<OrchestrationDb['getLatestDispatchForTerminal']> {
|
||||
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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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' })
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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<RuntimeStatus>
|
||||
syncWindowGraph: (graph: RuntimeSyncWindowGraph) => Promise<RuntimeSyncWindowGraphResult>
|
||||
getStatus: () => Promise<RuntimeStatus>
|
||||
call: (args: { method: string; params?: unknown }) => Promise<RuntimeRpcResponse<unknown>>
|
||||
getTerminalFitOverrides: () => Promise<
|
||||
|
||||
@@ -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<RuntimeStatus> =>
|
||||
syncWindowGraph: (graph: RuntimeSyncWindowGraph): Promise<RuntimeSyncWindowGraphResult> =>
|
||||
ipcRenderer.invoke('runtime:syncWindowGraph', graph),
|
||||
getStatus: (): Promise<RuntimeStatus> => ipcRenderer.invoke('runtime:getStatus'),
|
||||
call: (args: { method: string; params?: unknown }): Promise<RuntimeRpcResponse<unknown>> =>
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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'
|
||||
}`}
|
||||
|
||||
@@ -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(
|
||||
<TooltipProvider>
|
||||
<DashboardAgentRow
|
||||
agent={makeAgent()}
|
||||
onDismiss={vi.fn()}
|
||||
onActivate={vi.fn()}
|
||||
now={NOW}
|
||||
hideIdentityIcon
|
||||
hideExpand
|
||||
childAgentCount={2}
|
||||
childAgentsExpanded={false}
|
||||
onToggleChildAgents={vi.fn()}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
)
|
||||
|
||||
expect(classTokens(markup)).toContain('worktree-agent-lineage-parent-row')
|
||||
expect(markup).toContain('aria-label="Show 2 child agents"')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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}
|
||||
>
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,129 @@
|
||||
import type { DashboardAgentRow } from './useDashboardData'
|
||||
|
||||
export type AgentRowLineageTree<T extends DashboardAgentRow> = {
|
||||
rootRows: T[]
|
||||
childrenByParentPaneKey: Map<string, T[]>
|
||||
childPaneKeys: Set<string>
|
||||
}
|
||||
|
||||
function buildPaneKeyByTerminalHandle<T extends DashboardAgentRow>(
|
||||
rows: readonly T[]
|
||||
): Map<string, string> {
|
||||
const paneKeyByTerminalHandle = new Map<string, string>()
|
||||
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<T extends DashboardAgentRow>(
|
||||
row: T,
|
||||
rowsByPaneKey: ReadonlyMap<string, T>,
|
||||
paneKeyByTerminalHandle: ReadonlyMap<string, string>
|
||||
): 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<T extends DashboardAgentRow>(
|
||||
rows: readonly T[]
|
||||
): AgentRowLineageTree<T> {
|
||||
const rowsByPaneKey = new Map<string, T>()
|
||||
for (const row of rows) {
|
||||
if (!rowsByPaneKey.has(row.paneKey)) {
|
||||
rowsByPaneKey.set(row.paneKey, row)
|
||||
}
|
||||
}
|
||||
const paneKeyByTerminalHandle = buildPaneKeyByTerminalHandle(rows)
|
||||
const childrenByParentPaneKey = new Map<string, T[]>()
|
||||
const childPaneKeys = new Set<string>()
|
||||
|
||||
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<string>()
|
||||
const markReachable = (row: T, ancestorPaneKeys: ReadonlySet<string> = 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
|
||||
}
|
||||
}
|
||||
@@ -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<string, DashboardAgentRow[]>()
|
||||
const childPaneKeys = new Set<string>()
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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 = (
|
||||
<div
|
||||
className={cn(
|
||||
'group relative flex items-start gap-1.5 px-1.5 pt-1.5 pb-2 cursor-pointer transition-[background-color,border-color,opacity,box-shadow] duration-200 outline-none select-none',
|
||||
'group relative flex items-start gap-0.5 pl-0 pr-1.5 pt-1.5 pb-2 cursor-pointer transition-[background-color,border-color,opacity,box-shadow] duration-200 outline-none select-none',
|
||||
flushSurface ? 'ml-1 w-[calc(100%-0.25rem)]' : 'ml-1',
|
||||
isMultiSelected ? 'rounded-sm' : 'rounded-lg',
|
||||
isActiveSurface
|
||||
@@ -725,7 +726,12 @@ const WorktreeCard = React.memo(function WorktreeCard({
|
||||
) : null}
|
||||
|
||||
{/* Content area */}
|
||||
<div className="flex-1 min-w-0 overflow-hidden flex flex-col gap-1.5">
|
||||
<div
|
||||
className={cn(
|
||||
'flex min-w-0 flex-1 flex-col gap-1.5',
|
||||
lineageChildren ? 'overflow-visible' : 'overflow-hidden'
|
||||
)}
|
||||
>
|
||||
{/* Header row: Title */}
|
||||
<div className="flex items-center justify-between min-w-0 gap-2">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1.5">
|
||||
@@ -977,7 +983,11 @@ const WorktreeCard = React.memo(function WorktreeCard({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{lineageChildren && <div className="-ml-3 mt-1.5 space-y-1">{lineageChildren}</div>}
|
||||
{lineageChildren && (
|
||||
<div className="-ml-[1.125rem] mt-1.5 w-[calc(100%+1.125rem)] space-y-1">
|
||||
{lineageChildren}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -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(<WorktreeCardAgents worktreeId="wt-1" />)
|
||||
|
||||
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(<WorktreeCardAgents worktreeId="wt-1" />)
|
||||
|
||||
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(<WorktreeCardAgents worktreeId="wt-1" />)
|
||||
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(
|
||||
<CompactAgentSummaryButton
|
||||
agents={agents}
|
||||
subjectLabel="5 agents"
|
||||
expanded
|
||||
onToggle={vi.fn()}
|
||||
/>
|
||||
)
|
||||
|
||||
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(
|
||||
<CompactAgentExpansion expanded contentClassName="pl-1">
|
||||
<div>Agent row</div>
|
||||
</CompactAgentExpansion>
|
||||
)
|
||||
|
||||
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')
|
||||
})
|
||||
|
||||
@@ -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<string, DashboardAgentRowData[]>
|
||||
}
|
||||
|
||||
function buildAgentLineageModel(agents: DashboardAgentRowData[]): AgentLineageModel {
|
||||
const agentPaneKeys = new Set(agents.map((agent) => agent.paneKey))
|
||||
const childrenByParentPaneKey = new Map<string, DashboardAgentRowData[]>()
|
||||
const childPaneKeys = new Set<string>()
|
||||
|
||||
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<string>()
|
||||
const markReachable = (
|
||||
agent: DashboardAgentRowData,
|
||||
ancestorPaneKeys: ReadonlySet<string> = 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<ReadonlySet<string>>(
|
||||
const [collapsedLineageParents, setCollapsedLineageParents] = useState<ReadonlySet<string>>(
|
||||
() => 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 ? (
|
||||
<div className="worktree-agent-lineage-children">
|
||||
{childAgents.map((childAgent) =>
|
||||
renderAgentBranch(childAgent, descendantAncestorPaneKeys)
|
||||
)
|
||||
: null}
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</React.Fragment>
|
||||
)
|
||||
}
|
||||
@@ -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 ? (
|
||||
<CompactAgentExpansion expanded={expanded}>
|
||||
{childAgents.map((childAgent) =>
|
||||
renderCompactAgentBranch(childAgent, descendantAncestorPaneKeys)
|
||||
)}
|
||||
<div className="worktree-agent-lineage-children flex flex-col gap-0.5">
|
||||
{childAgents.map((childAgent) =>
|
||||
renderCompactAgentBranch(childAgent, descendantAncestorPaneKeys)
|
||||
)}
|
||||
</div>
|
||||
</CompactAgentExpansion>
|
||||
) : null}
|
||||
</React.Fragment>
|
||||
@@ -437,24 +396,32 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({
|
||||
role={hasLineage ? 'tree' : 'group'}
|
||||
aria-label="Agents"
|
||||
>
|
||||
{shouldUseSummaryRow && (
|
||||
<CompactAgentSummaryButton
|
||||
agents={summaryAgents}
|
||||
subjectLabel={subjectLabel}
|
||||
expanded={compactRootListExpanded}
|
||||
onToggle={() => {
|
||||
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.
|
||||
<div
|
||||
className={cn(
|
||||
'compact-agent-summary-panel',
|
||||
compactRootListExpanded && 'compact-agent-summary-panel-expanded'
|
||||
)}
|
||||
>
|
||||
<CompactAgentSummaryButton
|
||||
agents={summaryAgents}
|
||||
subjectLabel={subjectLabel}
|
||||
expanded={compactRootListExpanded}
|
||||
onToggle={() => {
|
||||
dispatchSuppressScrollAdjustment()
|
||||
setCompactRootListExpanded((expanded) => !expanded)
|
||||
}}
|
||||
/>
|
||||
<CompactAgentExpansion expanded={compactRootListExpanded}>
|
||||
{rootAgents.map((rootAgent) => renderCompactAgentBranch(rootAgent))}
|
||||
</CompactAgentExpansion>
|
||||
</div>
|
||||
) : (
|
||||
rootAgents.map((rootAgent) => renderCompactAgentBranch(rootAgent))
|
||||
) : shouldUseSummaryRow ? (
|
||||
<CompactAgentExpansion expanded={compactRootListExpanded}>
|
||||
{rootAgents.map((rootAgent) => renderCompactAgentBranch(rootAgent))}
|
||||
</CompactAgentExpansion>
|
||||
) : null}
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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('<div style="padding-left:18px"><div id="worktree-list-option-child"')
|
||||
})
|
||||
|
||||
it('opens the reconnect dialog for an active disconnected lineage child during render', async () => {
|
||||
setLineageFixtureState()
|
||||
const repo = (mockStore.state.repos as Repo[])[0]!
|
||||
@@ -415,4 +441,16 @@ describe('WorktreeList lineage child card renderer', () => {
|
||||
'<section data-worktree-card-id="parent" data-content-indent="18" data-flush-surface="true">'
|
||||
)
|
||||
})
|
||||
|
||||
it('adds project group depth to workspace card content indentation', async () => {
|
||||
setLineageFixtureState('repo', { projectGrouped: true })
|
||||
const markup = await renderWorktreeListMarkup()
|
||||
|
||||
const parentRow = markup.match(/<div[^>]*id="worktree-list-option-parent"[^>]*>/)?.[0] ?? ''
|
||||
|
||||
expect(parentRow).not.toContain('padding-left')
|
||||
expect(markup).toContain(
|
||||
'<section data-worktree-card-id="parent" data-content-indent="36" data-flush-surface="true">'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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 (
|
||||
<div
|
||||
key={child.worktree.id}
|
||||
style={{ paddingLeft: `${Math.max(0, child.depth - 1) * LINEAGE_INDENT}px` }}
|
||||
// Why: lineage child workspaces need their whole card surface
|
||||
// nested, not only the text/status content inside the card.
|
||||
style={childCardIndent > 0 ? { paddingLeft: `${childCardIndent}px` } : undefined}
|
||||
>
|
||||
<WorktreeContextMenu
|
||||
worktree={child.worktree}
|
||||
@@ -2984,7 +2994,7 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
data-worktree-card-surface="true"
|
||||
data-worktree-card-active={isActive ? 'true' : undefined}
|
||||
className={cn(
|
||||
'relative flex cursor-pointer items-start gap-1.5 rounded-md border border-transparent px-2 py-1.5 transition-colors',
|
||||
'relative flex w-full cursor-pointer items-start gap-1.5 rounded-lg border border-transparent py-1.5 pr-2 transition-colors',
|
||||
highlightedRevealWorktreeId === child.worktree.id && [
|
||||
'scroll-to-current-workspace-reveal-highlight',
|
||||
revealHighlightTone === 'ai' &&
|
||||
@@ -3000,88 +3010,97 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
|
||||
onClick={handleClick}
|
||||
onDoubleClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<span className="mt-[2px] flex w-4 shrink-0 justify-center pt-[2px]">
|
||||
<WorktreeActivityStatusIndicator worktreeId={child.worktree.id} />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-[12px] leading-tight text-foreground">
|
||||
{child.worktree.displayName}
|
||||
</div>
|
||||
<div className="mt-1 flex min-w-0 items-center gap-1.5">
|
||||
{child.repo && groupBy !== 'repo' ? (
|
||||
<span className="flex h-[16px] shrink-0 items-center gap-1.5 rounded-[4px] border border-border bg-accent px-1.5 text-[10px] font-semibold leading-none text-foreground dark:bg-accent/50 dark:border-border/60">
|
||||
<RepoBadgeMark color={child.repo.badgeColor} />
|
||||
<span className="max-w-[6rem] truncate lowercase">
|
||||
{child.repo.displayName}
|
||||
</span>
|
||||
</span>
|
||||
) : null}
|
||||
<span className="truncate text-[10.5px] leading-none text-muted-foreground">
|
||||
{branchDisplayName(child.worktree.branch)}
|
||||
</span>
|
||||
</div>
|
||||
{child.worktree.linkedIssue || child.worktree.comment ? (
|
||||
<div className="mt-1.5 truncate text-[10.5px] leading-tight text-muted-foreground">
|
||||
{child.worktree.linkedIssue ? (
|
||||
<span className="font-medium text-foreground/80">
|
||||
#{child.worktree.linkedIssue}
|
||||
<div
|
||||
className="flex min-w-0 flex-1 items-start gap-1.5 pl-2"
|
||||
style={
|
||||
childContentIndent > 0
|
||||
? { paddingLeft: `calc(0.5rem + ${childContentIndent}px)` }
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<span className="mt-[2px] flex w-4 shrink-0 justify-center pt-[2px]">
|
||||
<WorktreeActivityStatusIndicator worktreeId={child.worktree.id} />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-[12px] leading-tight text-foreground">
|
||||
{child.worktree.displayName}
|
||||
</div>
|
||||
<div className="mt-1 flex min-w-0 items-center gap-1.5">
|
||||
{child.repo && groupBy !== 'repo' ? (
|
||||
<span className="flex h-[16px] shrink-0 items-center gap-1.5 rounded-[4px] border border-border bg-accent px-1.5 text-[10px] font-semibold leading-none text-foreground dark:bg-accent/50 dark:border-border/60">
|
||||
<RepoBadgeMark color={child.repo.badgeColor} />
|
||||
<span className="max-w-[6rem] truncate lowercase">
|
||||
{child.repo.displayName}
|
||||
</span>
|
||||
</span>
|
||||
) : null}
|
||||
{child.worktree.linkedIssue && child.worktree.comment ? ' ' : null}
|
||||
{child.worktree.comment}
|
||||
<span className="truncate text-[10.5px] leading-none text-muted-foreground">
|
||||
{branchDisplayName(child.worktree.branch)}
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
{showInlineAgentCards ? (
|
||||
// Why: nested lineage children use this lightweight
|
||||
// renderer instead of WorktreeCard, so their inline
|
||||
// agent rows must be mounted here explicitly.
|
||||
<WorktreeCardAgents
|
||||
worktreeId={child.worktree.id}
|
||||
className="mt-1 divide-y-0"
|
||||
/>
|
||||
) : null}
|
||||
{child.lineageChildCount > 0 && lineageToggleGroupKey ? (
|
||||
<div className="mt-1.5 flex min-w-0 justify-start">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
className="h-[18px] max-w-[8rem] gap-1 rounded-md border border-sidebar-border bg-sidebar px-1.5 text-[10px] font-medium leading-none text-muted-foreground shadow-none hover:bg-sidebar-accent hover:text-foreground focus-visible:ring-1 focus-visible:ring-sidebar-ring"
|
||||
aria-label={`${child.lineageCollapsed ? 'Show' : 'Hide'} ${
|
||||
child.lineageChildCount
|
||||
} child ${
|
||||
child.lineageChildCount === 1 ? 'workspace' : 'workspaces'
|
||||
}`}
|
||||
aria-expanded={!child.lineageCollapsed}
|
||||
onClick={(event) => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
toggleGroupWithScrollAnchor(lineageToggleGroupKey)
|
||||
}}
|
||||
>
|
||||
<Workflow className="size-2.5" />
|
||||
<span className="truncate">
|
||||
{child.lineageChildCount}{' '}
|
||||
{child.lineageChildCount === 1 ? 'child' : 'children'}
|
||||
</span>
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
'size-2.5 transition-transform',
|
||||
child.lineageCollapsed && '-rotate-90'
|
||||
)}
|
||||
/>
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right" sideOffset={8}>
|
||||
{child.lineageCollapsed
|
||||
? 'Show child workspaces'
|
||||
: 'Hide child workspaces'}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : null}
|
||||
{child.worktree.linkedIssue || child.worktree.comment ? (
|
||||
<div className="mt-1.5 truncate text-[10.5px] leading-tight text-muted-foreground">
|
||||
{child.worktree.linkedIssue ? (
|
||||
<span className="font-medium text-foreground/80">
|
||||
#{child.worktree.linkedIssue}
|
||||
</span>
|
||||
) : null}
|
||||
{child.worktree.linkedIssue && child.worktree.comment ? ' ' : null}
|
||||
{child.worktree.comment}
|
||||
</div>
|
||||
) : null}
|
||||
{showInlineAgentCards ? (
|
||||
// Why: nested lineage children use this lightweight
|
||||
// renderer instead of WorktreeCard, so their inline
|
||||
// agent rows must be mounted here explicitly.
|
||||
<WorktreeCardAgents
|
||||
worktreeId={child.worktree.id}
|
||||
className="mt-1 divide-y-0"
|
||||
/>
|
||||
) : null}
|
||||
{child.lineageChildCount > 0 && lineageToggleGroupKey ? (
|
||||
<div className="mt-1.5 flex min-w-0 justify-start">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
className="h-[18px] max-w-[8rem] gap-1 rounded-md border border-sidebar-border bg-sidebar px-1.5 text-[10px] font-medium leading-none text-muted-foreground shadow-none hover:bg-sidebar-accent hover:text-foreground focus-visible:ring-1 focus-visible:ring-sidebar-ring"
|
||||
aria-label={`${child.lineageCollapsed ? 'Show' : 'Hide'} ${
|
||||
child.lineageChildCount
|
||||
} child ${
|
||||
child.lineageChildCount === 1 ? 'workspace' : 'workspaces'
|
||||
}`}
|
||||
aria-expanded={!child.lineageCollapsed}
|
||||
onClick={(event) => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
toggleGroupWithScrollAnchor(lineageToggleGroupKey)
|
||||
}}
|
||||
>
|
||||
<Workflow className="size-2.5" />
|
||||
<span className="truncate">
|
||||
{child.lineageChildCount}{' '}
|
||||
{child.lineageChildCount === 1 ? 'child' : 'children'}
|
||||
</span>
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
'size-2.5 transition-transform',
|
||||
child.lineageCollapsed && '-rotate-90'
|
||||
)}
|
||||
/>
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right" sideOffset={8}>
|
||||
{child.lineageCollapsed
|
||||
? 'Show child workspaces'
|
||||
: 'Hide child workspaces'}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</WorktreeContextMenu>
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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
|
||||
])
|
||||
}
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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<string, AgentStatusOrchestrationContext> = {}
|
||||
|
||||
type WorktreeAgentRowsState = Pick<
|
||||
AppState,
|
||||
@@ -90,7 +92,7 @@ function getLiveEntriesByWorktree(state: WorktreeAgentRowsState): Map<string, Ag
|
||||
if (!parsed) {
|
||||
continue
|
||||
}
|
||||
const worktreeId = tabIdToWorktreeId.get(parsed.tabId)
|
||||
const worktreeId = tabIdToWorktreeId.get(parsed.tabId) ?? entry.worktreeId
|
||||
if (!worktreeId) {
|
||||
continue
|
||||
}
|
||||
@@ -203,6 +205,41 @@ export function selectRetainedAgentEntriesForWorktree(
|
||||
return getRetainedEntriesByWorktree(state).get(worktreeId) ?? EMPTY_RETAINED
|
||||
}
|
||||
|
||||
export function selectRuntimeAgentOrchestrationForWorktree(
|
||||
state: Pick<
|
||||
AppState,
|
||||
| 'agentStatusByPaneKey'
|
||||
| 'retainedAgentsByPaneKey'
|
||||
| 'runtimeAgentOrchestrationByPaneKey'
|
||||
| 'tabsByWorktree'
|
||||
>,
|
||||
worktreeId: string
|
||||
): Record<string, AgentStatusOrchestrationContext> {
|
||||
const tabs = state.tabsByWorktree[worktreeId] ?? []
|
||||
const tabIds = new Set(tabs.map((tab) => tab.id))
|
||||
const out: Record<string, AgentStatusOrchestrationContext> = {}
|
||||
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<AppState, 'tabsByWorktree' | 'terminalLayoutsByTabId'>,
|
||||
worktreeId: string
|
||||
|
||||
@@ -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<string, AgentStatusOrchestrationContext> | 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<string, Record<number, string>>
|
||||
ptyIdsByTabId?: Record<string, string[]>
|
||||
terminalLayoutsByTabId?: Record<string, TerminalLayoutSnapshot | undefined>
|
||||
runtimeAgentOrchestrationByPaneKey?: Record<string, AgentStatusOrchestrationContext>
|
||||
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
|
||||
})
|
||||
|
||||
@@ -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<AgentDotState, DashboardAgentRowData[]>()
|
||||
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<AgentDotState, number>()
|
||||
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<string, { agents: DashboardAgentRowData[]; firstIndex: number }>()
|
||||
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
|
||||
}
|
||||
@@ -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<AgentDotState, number>()
|
||||
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<string, { agents: DashboardAgentRowData[]; firstIndex: number }>()
|
||||
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({
|
||||
>
|
||||
<div className="min-h-0 overflow-hidden">
|
||||
{shouldRenderChildren && (
|
||||
<div className="compact-agent-expansion-content flex flex-col gap-0.5 pt-0.5">
|
||||
<div
|
||||
className={cn(
|
||||
'compact-agent-expansion-content flex flex-col gap-0.5 pt-0.5',
|
||||
contentClassName
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)}
|
||||
@@ -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}
|
||||
>
|
||||
<span className="flex shrink-0 items-center gap-0.5" aria-hidden>
|
||||
{iconAgents.map((agent) => (
|
||||
<span
|
||||
key={agent.paneKey}
|
||||
className="inline-flex size-4 items-center justify-center rounded-full border border-sidebar bg-sidebar"
|
||||
title={formatAgentTypeLabel(agent.agentType)}
|
||||
>
|
||||
<AgentIcon agent={agentTypeToIconAgent(agent.agentType)} size={12} />
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate">{summary}</span>
|
||||
{hiddenIconAgentCount > 0 && (
|
||||
<span className="shrink-0 text-[10px] tabular-nums text-muted-foreground/70">
|
||||
+{hiddenIconAgentCount}
|
||||
{expanded ? (
|
||||
<span className="min-w-0 flex-1 truncate px-1 font-medium text-muted-foreground">
|
||||
{subjectLabel}
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<span className="flex min-w-0 flex-1 items-center gap-1 overflow-hidden" aria-hidden>
|
||||
{visibleGroups.map((group) => {
|
||||
const iconAgents = selectSummaryGroupIconAgents(group.agents, 3)
|
||||
const hiddenIconCount = Math.max(0, group.agents.length - iconAgents.length)
|
||||
return (
|
||||
<span
|
||||
key={group.state}
|
||||
className="inline-flex min-w-0 shrink-0 items-center gap-0.5 rounded-sm bg-sidebar/70 px-1 py-0.5"
|
||||
>
|
||||
<AgentStateDot state={group.state} size="sm" />
|
||||
<span className="inline-flex shrink-0 items-center gap-0.5">
|
||||
{iconAgents.map((agent) => (
|
||||
<span
|
||||
key={agent.paneKey}
|
||||
className="inline-flex size-3.5 items-center justify-center rounded-full border border-sidebar-border/70 bg-sidebar"
|
||||
>
|
||||
<AgentIcon agent={agentTypeToIconAgent(agent.agentType)} size={10} />
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
{hiddenIconCount > 0 && (
|
||||
<span className="shrink-0 text-[10px] tabular-nums text-muted-foreground/70">
|
||||
+{hiddenIconCount}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
</span>
|
||||
{hiddenGroupAgentCount > 0 && (
|
||||
<span className="shrink-0 text-[10px] tabular-nums text-muted-foreground/70">
|
||||
+{hiddenGroupAgentCount}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<ChevronRight
|
||||
className={cn('size-3 shrink-0 transition-transform duration-150', expanded && 'rotate-90')}
|
||||
@@ -311,6 +264,7 @@ export const CompactAgentRow = React.memo(function CompactAgentRow({
|
||||
const primary = getCompactAgentPrimary(agent)
|
||||
const assistantMessage = agent.entry.lastAssistantMessage?.trim() ?? ''
|
||||
const hasAssistantImage = MARKDOWN_IMAGE_PATTERN.test(assistantMessage)
|
||||
const isLineageChild = agent.lineage?.depth === 1
|
||||
const secondary = hasAssistantImage
|
||||
? formatAgentTypeLabel(agent.agentType)
|
||||
: getCompactAgentSecondary(agent)
|
||||
@@ -337,7 +291,7 @@ export const CompactAgentRow = React.memo(function CompactAgentRow({
|
||||
{hasChildDisclosure ? (
|
||||
<button
|
||||
type="button"
|
||||
className="flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground/70 hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-sidebar-ring"
|
||||
className="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 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-sidebar-ring"
|
||||
aria-label={`${childAgentsExpanded ? 'Hide' : 'Show'} ${childAgentCount} child ${
|
||||
childAgentCount === 1 ? 'agent' : 'agents'
|
||||
}`}
|
||||
@@ -363,16 +317,34 @@ export const CompactAgentRow = React.memo(function CompactAgentRow({
|
||||
</span>
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate">
|
||||
<span className="text-foreground/85">{primary}</span>
|
||||
{secondary && <span className="text-muted-foreground/75"> - {secondary}</span>}
|
||||
{/* Why: the selected-row fill is strong enough to wash out the dimmed
|
||||
prompt/secondary text, so lift both toward full foreground when focused. */}
|
||||
<span className={isFocusedPane ? 'text-foreground' : 'text-foreground/85'}>{primary}</span>
|
||||
{secondary && (
|
||||
<span className={isFocusedPane ? 'text-foreground/70' : 'text-muted-foreground/75'}>
|
||||
{' '}
|
||||
- {secondary}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{hasChildDisclosure && !childAgentsExpanded && (
|
||||
<span className="shrink-0 text-[10px] tabular-nums text-muted-foreground/70">
|
||||
<span
|
||||
className={cn(
|
||||
'shrink-0 text-[10px] tabular-nums',
|
||||
isFocusedPane ? 'text-foreground/70' : 'text-muted-foreground/70'
|
||||
)}
|
||||
>
|
||||
+{childAgentCount}
|
||||
</span>
|
||||
)}
|
||||
{shortTime && (
|
||||
<span className="shrink-0 text-[10px] tabular-nums text-muted-foreground/60">
|
||||
<span
|
||||
className={cn(
|
||||
'shrink-0 text-[10px] tabular-nums',
|
||||
// Why: the muted timestamp drops out against the selected-row fill.
|
||||
isFocusedPane ? 'text-foreground/70' : 'text-muted-foreground/60'
|
||||
)}
|
||||
>
|
||||
{shortTime}
|
||||
</span>
|
||||
)}
|
||||
@@ -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'
|
||||
)}
|
||||
|
||||
@@ -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 })
|
||||
})
|
||||
|
||||
|
||||
@@ -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<string, number>()
|
||||
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<string, Repo>,
|
||||
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<string>
|
||||
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
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,6 +51,7 @@ const makeWorktreeRow = (id: string): Extract<Row, { type: 'item' }> => ({
|
||||
worktree: makeWorktree(id),
|
||||
repo,
|
||||
depth: 0,
|
||||
groupDepth: 0,
|
||||
lineageTrail: [],
|
||||
isLastLineageChild: false,
|
||||
lineageChildCount: 0
|
||||
|
||||
@@ -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))
|
||||
})
|
||||
})
|
||||
@@ -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
|
||||
}
|
||||
@@ -51,6 +51,7 @@ const makeWorktreeRow = (id: string): Extract<Row, { type: 'item' }> => ({
|
||||
worktree: makeWorktree(id),
|
||||
repo,
|
||||
depth: 0,
|
||||
groupDepth: 0,
|
||||
lineageTrail: [],
|
||||
isLastLineageChild: false,
|
||||
lineageChildCount: 0
|
||||
|
||||
@@ -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')],
|
||||
|
||||
@@ -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<string, Record<number, string>>
|
||||
ptyIdsByTabId?: Record<string, string[]>
|
||||
terminalLayoutsByTabId?: Record<string, TerminalLayoutSnapshot | undefined>
|
||||
runtimeAgentOrchestrationByPaneKey?: Record<string, AgentStatusOrchestrationContext>
|
||||
seenPaneKeys: Set<string>
|
||||
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<string, AgentStatusOrchestrationContext>
|
||||
}): 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,
|
||||
|
||||
@@ -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<typeof useAppStore.getState>,
|
||||
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
|
||||
|
||||
@@ -570,7 +570,10 @@ async function syncRuntimeGraph(): Promise<void> {
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -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<AppState>)
|
||||
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<AppState>)
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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<string, AgentStatusEntry>
|
||||
/** Main-synced dispatch metadata for live terminal panes that may only have
|
||||
* title-derived status in the renderer. */
|
||||
runtimeAgentOrchestrationByPaneKey: Record<string, AgentStatusOrchestrationContext>
|
||||
/** PTYs that still report legacy numeric pane keys but have registry-backed
|
||||
* UUID pane proof. Stored separately from normal hook-reported status. */
|
||||
migrationUnsupportedByPtyId: Record<string, MigrationUnsupportedPtyEntry>
|
||||
@@ -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<string, AgentStatusOrchestrationContext>
|
||||
) => 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<string, AgentStatusOrchestrationContext>,
|
||||
b: Record<string, AgentStatusOrchestrationContext>
|
||||
): 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<AppState, [], [], AgentStatusSlice> = (
|
||||
set,
|
||||
get
|
||||
@@ -195,12 +239,72 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
|
||||
|
||||
return {
|
||||
agentStatusByPaneKey: {},
|
||||
runtimeAgentOrchestrationByPaneKey: {},
|
||||
migrationUnsupportedByPtyId: {},
|
||||
agentStatusEpoch: 0,
|
||||
retainedAgentsByPaneKey: {},
|
||||
retentionSuppressedPaneKeys: {},
|
||||
|
||||
setAgentStatus: (paneKey, payload, terminalTitle, timing) => {
|
||||
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: StateCreator<AppState, [], [], AgentStatusS
|
||||
// carries the authoritative current snapshot — including clears on a
|
||||
// fresh turn. Writing through directly (no existing fallback) is what
|
||||
// lets a `UserPromptSubmit` reset clear stale tool lines in the UI.
|
||||
const runtimeOrchestration = s.runtimeAgentOrchestrationByPaneKey[paneKey]
|
||||
const runtimeMergedOrchestration = runtimeOrchestration
|
||||
? mergeCurrentOrchestrationContext(existing?.orchestration, runtimeOrchestration)
|
||||
: undefined
|
||||
const payloadMergedOrchestration = payload.orchestration
|
||||
? mergeCurrentOrchestrationContext(
|
||||
runtimeMergedOrchestration ?? existing?.orchestration,
|
||||
payload.orchestration
|
||||
)
|
||||
: undefined
|
||||
const completedFallbackOrchestration =
|
||||
payload.state === 'done' ? existing?.orchestration : undefined
|
||||
const orchestration =
|
||||
payloadMergedOrchestration ?? runtimeMergedOrchestration ?? completedFallbackOrchestration
|
||||
const entry: AgentStatusEntry = {
|
||||
state: payload.state,
|
||||
prompt: payload.prompt,
|
||||
@@ -288,15 +406,22 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
|
||||
stateStartedAt,
|
||||
agentType: identity.agentType,
|
||||
paneKey,
|
||||
terminalHandle: routing?.terminalHandle ?? existing?.terminalHandle,
|
||||
worktreeId:
|
||||
routing?.worktreeId ??
|
||||
existing?.worktreeId ??
|
||||
findAgentPaneWorktreeId(s, paneKey) ??
|
||||
undefined,
|
||||
tabId: routing?.tabId ?? existing?.tabId ?? getTabIdFromPaneKey(paneKey) ?? undefined,
|
||||
terminalTitle: effectiveTitle,
|
||||
stateHistory: history,
|
||||
toolName: payload.toolName,
|
||||
toolInput: payload.toolInput,
|
||||
lastAssistantMessage: payload.lastAssistantMessage,
|
||||
// Why: orchestration dispatch metadata may disappear after the
|
||||
// worker completes and the active dispatch closes. Preserve the last
|
||||
// known parent-child link so done/retained rows stay grouped.
|
||||
orchestration: payload.orchestration ?? existing?.orchestration,
|
||||
// Why: reused panes may start non-orchestrated work after runtime
|
||||
// metadata expires. Only final done rows keep the previous lineage
|
||||
// fallback so completed children stay grouped.
|
||||
orchestration,
|
||||
// Why: interrupted lives on `done` only. parseAgentStatusPayload
|
||||
// already clamps it to `undefined` for non-done states, so writing
|
||||
// the field through directly preserves truth for done and resets
|
||||
@@ -308,7 +433,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
|
||||
existing !== undefined &&
|
||||
!isAgentCompletionState(existing.state)
|
||||
) {
|
||||
completionRefreshWorktreeId = findAgentPaneWorktreeId(s, paneKey)
|
||||
completionRefreshWorktreeId = entry.worktreeId ?? findAgentPaneWorktreeId(s, paneKey)
|
||||
}
|
||||
// Why: broad freshness-aware subscribers only need a global tick when
|
||||
// an entry appears, changes state, crosses stale->fresh, or receives
|
||||
@@ -721,9 +846,13 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
|
||||
let hadLive = false
|
||||
set((s) => {
|
||||
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<AppState, [], [], AgentStatusS
|
||||
(entry.paneKey ? paneKeyMatchesAnyTabPrefix(entry.paneKey, tabPrefixes) : false)
|
||||
)
|
||||
// See removeAgentStatus for rationale on ack cleanup. Current tabs are
|
||||
// swept by prefix; orphan retained rows are swept by their retained key.
|
||||
// swept by prefix; attributed live rows and orphan retained rows are
|
||||
// swept by their retained/lifecycle key.
|
||||
let nextAck = s.acknowledgedAgentsByPaneKey
|
||||
const ackKeys = Object.keys(nextAck).filter(
|
||||
(k) => 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<AppState, [], [], AgentStatusS
|
||||
}
|
||||
const next = { ...s.retainedAgentsByPaneKey }
|
||||
for (const retained of entries) {
|
||||
const runtimeOrchestration = s.runtimeAgentOrchestrationByPaneKey[retained.entry.paneKey]
|
||||
const mergedOrchestration = runtimeOrchestration
|
||||
? mergeCurrentOrchestrationContext(retained.entry.orchestration, runtimeOrchestration)
|
||||
: retained.entry.orchestration
|
||||
const entry =
|
||||
mergedOrchestration !== retained.entry.orchestration
|
||||
? { ...retained.entry, orchestration: mergedOrchestration }
|
||||
: retained.entry
|
||||
// Why: INVARIANT — the map key equals retained.entry.paneKey. This
|
||||
// lets callers look up a retained row by the same paneKey they use
|
||||
// for agentStatusByPaneKey and keeps dismissal (dismissRetainedAgent)
|
||||
@@ -837,7 +976,8 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
|
||||
// relies on this invariant too: it checks
|
||||
// `retainedAgentsByPaneKey[paneKey]` to decide whether a vanished
|
||||
// agent is already retained.
|
||||
next[retained.entry.paneKey] = retained
|
||||
next[retained.entry.paneKey] =
|
||||
entry === retained.entry ? retained : { ...retained, entry }
|
||||
}
|
||||
return { retainedAgentsByPaneKey: next }
|
||||
})
|
||||
|
||||
@@ -82,6 +82,16 @@ export type AgentStatusEntry = {
|
||||
agentType?: AgentType
|
||||
/** Composite key: `${tabId}:${leafId}` where leafId is a stable UUID layout leaf. */
|
||||
paneKey: string
|
||||
/** Runtime terminal handle for matching retained parent rows when the parent
|
||||
* pane key cannot be re-derived after terminal teardown. */
|
||||
terminalHandle?: string
|
||||
/** Worktree attribution stamped by main when a hook can be resolved there.
|
||||
* Why: orchestration workers can report status before their terminal tab is
|
||||
* present in a renderer; retaining this lets worktree-level UI still show
|
||||
* the live child agent instead of dropping it as unattributed. */
|
||||
worktreeId?: string
|
||||
/** Tab attribution from the hook IPC payload, when available. */
|
||||
tabId?: string
|
||||
terminalTitle?: string
|
||||
/** Rolling log of previous states. Each entry records a state the agent was in
|
||||
* before transitioning to the current one. Capped at AGENT_STATE_HISTORY_MAX. */
|
||||
@@ -149,6 +159,7 @@ export type ParsedAgentStatusPayload = Omit<AgentStatusPayload, 'prompt'> & { 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.
|
||||
|
||||
@@ -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<string, AgentStatusOrchestrationContext>
|
||||
}
|
||||
|
||||
export type RuntimeMobileSessionTerminalTab = {
|
||||
type: 'terminal'
|
||||
id: string
|
||||
|
||||
Reference in New Issue
Block a user