diff --git a/src/main/runtime/client/events/runtime-notifier-contract.ts b/src/main/runtime/client/events/runtime-notifier-contract.ts index 910e00ed84a..a39b6216384 100644 --- a/src/main/runtime/client/events/runtime-notifier-contract.ts +++ b/src/main/runtime/client/events/runtime-notifier-contract.ts @@ -34,6 +34,10 @@ import type { RuntimeTerminalDriverState } from '../../../../shared/runtime-session-contracts' import type { RuntimeTerminalPresentation } from '../../../../shared/runtime-terminal-contracts' +import type { + AgentListPublication, + AgentPaneActivityChange +} from '../../../../shared/agent-status/presentation/agent-list-status' type DriverState = RuntimeTerminalDriverState @@ -174,6 +178,8 @@ export type RuntimeNotifier = { workspaceSleepChanged?(notice: WorkspaceSleepNotice): void // Only the host renderer owns slept-agent wake records; phones request navigation-free wake through this optional bridge. resumeSleepingAgents?(worktreeId: string): void + /** The window applies a client's Agents-list change with its own actions and answers with the verdicts it leaves. */ + applyAgentPaneActivity?(change: AgentPaneActivityChange): Promise terminalFitOverrideChanged( ptyId: string, mode: 'mobile-fit' | 'remote-desktop-fit' | 'desktop-fit', diff --git a/src/main/runtime/client/runtime-client-state.ts b/src/main/runtime/client/runtime-client-state.ts index 323c1b20c2d..d2e6570e368 100644 --- a/src/main/runtime/client/runtime-client-state.ts +++ b/src/main/runtime/client/runtime-client-state.ts @@ -17,6 +17,11 @@ import { killAllProcessesForWorktree } from '../workspaces/removal/worktree-tear import type { MemorySnapshot, StatsSummary } from '../../../shared/process-stats-types' import { collectMemorySnapshot } from '../../memory/collector' import type { PersistedUIState } from '../../../shared/persisted-ui-state-types' +import { isDeepStrictEqual } from 'node:util' +import type { + AgentListPublication, + AgentPaneActivityChange +} from '../../../shared/agent-status/presentation/agent-list-status' import type { FeatureInteractionId } from '../../../shared/feature-interaction-catalog' import type { RuntimeClientSettingsUpdate } from './settings/runtime-client-settings-shape' import type { AgentLaunchSettingsMutation } from '../../../shared/agent-launch/choices/agent-launch-settings' @@ -190,6 +195,29 @@ export abstract class OrcaRuntimeWithPtyForegroundProcessReads extends OrcaRunti return this.store.getUI() } + /** The live desktop window's Agents-list verdicts; null with no window, so worktree.ps claims none. */ + private agentListPublication: AgentListPublication | null = null + + readAgentListPublication(): AgentListPublication | null { + return this.agentListPublication + } + + setAgentListPublication(next: AgentListPublication | null): void { + const changed = !isDeepStrictEqual(this.agentListPublication?.verdicts, next?.verdicts) + this.agentListPublication = next + if (changed) { + this.emitClientEvent({ type: 'agentListChanged' }) + } + } + + /** Applies through the window's own Activity actions and keeps the verdicts it answers with, so the next worktree.ps already shows them. */ + async applyAgentPaneActivity(change: AgentPaneActivityChange): Promise { + if (!this.notifier?.applyAgentPaneActivity) { + throw new Error('agent_activity_needs_desktop_window') + } + this.setAgentListPublication(await this.notifier.applyAgentPaneActivity(change)) + } + recordFeatureInteraction(id: FeatureInteractionId): PersistedUIState { if (!this.store?.recordFeatureInteraction) { throw new Error('runtime_unavailable') diff --git a/src/main/runtime/rpc/methods/rpc-method-registry.ts b/src/main/runtime/rpc/methods/rpc-method-registry.ts index bc707050b33..79858ee663a 100644 --- a/src/main/runtime/rpc/methods/rpc-method-registry.ts +++ b/src/main/runtime/rpc/methods/rpc-method-registry.ts @@ -7,6 +7,7 @@ import { AI_VAULT_METHODS } from './history/ai-vault' import { AUTOMATION_METHODS } from './automations/automations' import { REPO_METHODS } from './projects/repo' import { WORKTREE_METHODS } from './workspaces/worktree' +import { AGENT_ACTIVITY_METHODS } from './workspaces/agent-activity-methods' import { REFERENCE_METHODS } from './reference/reference' import { TERMINAL_METHODS } from './terminal/terminal' import { TERMINAL_ORPHAN_METHODS } from './terminal/terminal-orphan' @@ -92,6 +93,7 @@ export const ALL_RPC_METHODS = [ ...AUTOMATION_METHODS, ...REPO_METHODS, ...WORKTREE_METHODS, + ...AGENT_ACTIVITY_METHODS, ...REFERENCE_METHODS, ...AGENT_SESSION_METHODS, ...STRUCTURED_AGENT_SESSION_METHODS, diff --git a/src/main/runtime/rpc/methods/workspaces/agent-activity-methods.ts b/src/main/runtime/rpc/methods/workspaces/agent-activity-methods.ts new file mode 100644 index 00000000000..24cfcf523b6 --- /dev/null +++ b/src/main/runtime/rpc/methods/workspaces/agent-activity-methods.ts @@ -0,0 +1,30 @@ +import { defineMethod } from '../../core' +import { + AgentActivityClearParams, + AgentActivitySetReadParams +} from '../../../../../shared/rpc-contract/agent-activity-params' + +// Desktop Agents-list read and clear for paired clients; the next worktree.ps already reflects them. +export const AGENT_ACTIVITY_METHODS = [ + defineMethod({ + name: 'agentActivity.setRead', + permission: 'workspace', + params: AgentActivitySetReadParams, + handler: async (params, { runtime }) => { + await runtime.applyAgentPaneActivity({ + kind: params.read ? 'read' : 'unread', + paneKeys: params.paneKeys + }) + return { applied: true } + } + }), + defineMethod({ + name: 'agentActivity.clear', + permission: 'workspace', + params: AgentActivityClearParams, + handler: async (params, { runtime }) => { + await runtime.applyAgentPaneActivity({ kind: 'clear', paneKeys: params.paneKeys }) + return { applied: true } + } + }) +] diff --git a/src/main/runtime/rpc/server/runtime-rpc-mobile-method-routing.ts b/src/main/runtime/rpc/server/runtime-rpc-mobile-method-routing.ts index dfe15ee9d1a..937d3cf7482 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-mobile-method-routing.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-mobile-method-routing.ts @@ -11,6 +11,9 @@ export const EXECUTION_HOST_METHODS = [ 'ui.mutateJiraSavedFilters', 'agent.launch', 'agent.launchReplay', + // Read state lives with the host whose worktree.ps reports it. + 'agentActivity.clear', + 'agentActivity.setRead', 'agentTeams.prepareLaunch', 'agentTeams.tmuxCompat', 'automation.list', diff --git a/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows-activity.test.ts b/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows-activity.test.ts new file mode 100644 index 00000000000..d19b986cee9 --- /dev/null +++ b/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows-activity.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it } from 'vitest' +import type { AgentListPublication } from '../../../../shared/agent-status/presentation/agent-list-status' +import type { RuntimeWorktreePsSummary } from '../../../../shared/runtime-worktree-contracts' +import { attachRuntimeWorktreeAgentRows } from './runtime-worktree-agent-rows' +import type { RuntimeWorktreeAgentSource } from './runtime-worktree-agent-source' + +const WORKTREE_ID = 'repo::/work/tree' +const PUBLISHED_AT = 1_800_000_000_000 + +function source(paneKey: string, updatedAt: number): RuntimeWorktreeAgentSource { + return { + paneKey, + worktreeId: WORKTREE_ID, + connectionId: null, + state: 'done', + agentType: 'claude', + prompt: 'fix it', + lastAssistantMessage: null, + toolName: null, + toolInput: null, + interrupted: false, + stateStartedAt: updatedAt, + updatedAt + } +} + +function listAgents(agentList: AgentListPublication | null) { + const summary: RuntimeWorktreePsSummary = { + worktreeId: WORKTREE_ID, + repoId: 'repo', + repo: 'repo', + path: '/work/tree', + branch: 'main', + isArchived: false, + isMainWorktree: false, + hasHostSidebarActivity: false, + parentWorktreeId: null, + childWorktreeIds: [], + displayName: 'tree', + workspaceStatus: '', + sortOrder: 0, + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + linkedGitLabMR: null, + linkedGitLabIssue: null, + comment: '', + isPinned: false, + isActive: false, + unread: false, + liveTerminalCount: 0, + hasAttachedPty: false, + lastOutputAt: null, + preview: '', + status: 'inactive', + agents: [] + } + const summaries = new Map([[WORKTREE_ID, summary]]) + attachRuntimeWorktreeAgentRows({ + summaries, + rowSources: new Map( + [ + source('tab-1:listed', PUBLISHED_AT - 3), + source('tab-1:session-start', PUBLISHED_AT - 2), + source('tab-1:unknown-old', PUBLISHED_AT - 1), + source('tab-1:unknown-new', PUBLISHED_AT + 1) + ].map((row) => [row.paneKey, row]) + ), + terminalTitleEvidenceByRow: new Map(), + orchestrationByPaneKey: null, + getSummary: (id) => summaries.get(id) ?? null, + agentList + }) + return Object.fromEntries((summary.agents ?? []).map((row) => [row.paneKey, row.activity])) +} + +describe('worktree.ps agent rows and the desktop Agents list', () => { + it('carries each pane’s verdict and holds back only turns newer than the verdicts', () => { + const listed = { + listed: true, + status: 'done', + unread: true, + clearable: true, + sortAt: PUBLISHED_AT - 3, + title: 'Fix the build', + childOf: 'tab-0:coordinator', + foldedChild: true + } as const + expect( + listAgents({ + publishedAt: PUBLISHED_AT, + verdicts: { 'tab-1:listed': listed, 'tab-1:session-start': { listed: false } } + }) + ).toEqual({ + 'tab-1:listed': listed, + 'tab-1:session-start': { listed: false }, + 'tab-1:unknown-old': { listed: false }, + 'tab-1:unknown-new': undefined + }) + }) + + it('claims no verdict when no desktop window has published one', () => { + expect(listAgents(null)).toEqual({ + 'tab-1:listed': undefined, + 'tab-1:session-start': undefined, + 'tab-1:unknown-old': undefined, + 'tab-1:unknown-new': undefined + }) + }) +}) diff --git a/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows.ts b/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows.ts index a306fd80fad..f3ec79e8fcb 100644 --- a/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows.ts +++ b/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows.ts @@ -7,6 +7,10 @@ import type { RuntimeWorktreeAgentRow, RuntimeWorktreePsSummary } from '../../../../shared/runtime-worktree-contracts' +import type { + AgentListPublication, + AgentListVerdict +} from '../../../../shared/agent-status/presentation/agent-list-status' import { mergeWorktreeSummaryStatus } from './runtime-worktree-status-projection' import { resolveRuntimeWorktreeSidebarStatus, @@ -25,6 +29,19 @@ type OrchestrationDisplay = { parentPaneKey?: string | null } +const UNLISTED: AgentListVerdict = { listed: false } + +/** A pane the window gave no verdict is not in its list, unless it changed after the window last looked. */ +function agentListVerdict( + agentList: AgentListPublication, + source: RuntimeWorktreeAgentSource +): AgentListVerdict | undefined { + return ( + agentList.verdicts[source.paneKey] ?? + (source.updatedAt > agentList.publishedAt ? undefined : UNLISTED) + ) +} + export function attachRuntimeWorktreeAgentRows(args: { summaries: Map rowSources: ReadonlyMap @@ -35,6 +52,8 @@ export function attachRuntimeWorktreeAgentRows(args: { orchestrationByPaneKey: Record | null | undefined getSummary: RuntimeWorktreePsSummaryLookup conversationName?: (source: RuntimeWorktreeAgentSource) => string | null + /** The desktop window's Agents-list verdicts; null when no window has published them. */ + agentList?: AgentListPublication | null }): void { const { rowSources } = args const now = Date.now() @@ -80,6 +99,10 @@ export function attachRuntimeWorktreeAgentRows(args: { if (source.children !== undefined || source.subagents !== undefined) { row.subagentObservation = isAgentStatusFresh(row, now) ? 'live' : 'unverifiable' } + const activity = args.agentList && agentListVerdict(args.agentList, source) + if (activity) { + row.activity = activity + } const rows = rowsBySummary.get(summary) if (rows) { rows.push(row) diff --git a/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts b/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts index 8610941e3fe..6334fb8480e 100644 --- a/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts +++ b/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts @@ -135,7 +135,8 @@ export abstract class OrcaRuntimeWithGetWorktreePs extends RuntimeChatWorkerEven rowSources, orchestrationByPaneKey: this.agentOrchestrationProjection.buildByPaneKey(), getSummary, - conversationName: this.orchestrationSenderNames.agentRowNamer() + conversationName: this.orchestrationSenderNames.agentRowNamer(), + agentList: this.readAgentListPublication() }) const sorted = [...summaries.values()].sort(compareWorktreePs) diff --git a/src/main/window/agent-pane-activity-relay.ts b/src/main/window/agent-pane-activity-relay.ts new file mode 100644 index 00000000000..a8c33e8231d --- /dev/null +++ b/src/main/window/agent-pane-activity-relay.ts @@ -0,0 +1,29 @@ +import type { BrowserWindow } from 'electron' + +import type { + AgentListPublication, + AgentPaneActivityChange, + AgentPaneActivityReply +} from '../../shared/agent-status/presentation/agent-list-status' +import { requestRendererReply } from './renderer-reply-request' + +// Under the client's call timeout, so the client hears a refusal rather than losing the reply. +const AGENT_PANE_ACTIVITY_TIMEOUT_MS = 10_000 + +/** Asks the window to apply a client's Agents-list change and answer with the verdicts it leaves. */ +export async function requestAgentPaneActivityFromRenderer( + mainWindow: BrowserWindow, + change: AgentPaneActivityChange +): Promise { + const reply = await requestRendererReply(mainWindow, { + requestChannel: 'ui:applyAgentPaneActivity', + replyChannel: 'ui:agentPaneActivityReply', + payload: change, + timeoutMs: AGENT_PANE_ACTIVITY_TIMEOUT_MS, + timeoutError: 'agent_activity_timeout' + }) + if ('error' in reply) { + throw new Error(reply.error) + } + return reply.publication +} diff --git a/src/main/window/main-window-service-stubs.test-fixture.ts b/src/main/window/main-window-service-stubs.test-fixture.ts index 0063c111933..b308406db67 100644 --- a/src/main/window/main-window-service-stubs.test-fixture.ts +++ b/src/main/window/main-window-service-stubs.test-fixture.ts @@ -30,6 +30,8 @@ type RuntimeStub = { markRendererReloadCancelled: MockFn markGraphReloadFailed: MockFn markGraphUnavailable: MockFn + readAgentListPublication: MockFn + setAgentListPublication: MockFn } export function createMainWindowServiceStub( @@ -67,7 +69,9 @@ export function createRuntime(): RuntimeStub { markRendererReloading: vi.fn(), markRendererReloadCancelled: vi.fn(), markGraphReloadFailed: vi.fn(), - markGraphUnavailable: vi.fn() + markGraphUnavailable: vi.fn(), + readAgentListPublication: vi.fn(() => null), + setAgentListPublication: vi.fn() } } diff --git a/src/main/window/renderer-reply-request.ts b/src/main/window/renderer-reply-request.ts new file mode 100644 index 00000000000..80582d8b885 --- /dev/null +++ b/src/main/window/renderer-reply-request.ts @@ -0,0 +1,65 @@ +import { randomUUID } from 'node:crypto' + +import { ipcMain, type BrowserWindow } from 'electron' + +import { addFanoutListener } from '../runtime/events/event-listener-fanout' +import { abortWhenRendererGone } from '../ipc/renderer-lifetime-abort' + +/** Sends one request to the window and resolves with the reply its own renderer sends; rejects when it goes away or times out. */ +export function requestRendererReply( + mainWindow: BrowserWindow, + options: { + requestChannel: string + replyChannel: string + payload: object + timeoutMs: number + timeoutError: string + } +): Promise { + if (mainWindow.isDestroyed() || mainWindow.webContents.isDestroyed()) { + return Promise.reject(new Error('renderer_unavailable')) + } + const webContents = mainWindow.webContents + const requestId = randomUUID() + return new Promise((resolve, reject) => { + let settled = false + const releaseListeners: (() => void)[] = [] + const finish = (error: Error | null, reply?: TReply): void => { + if (settled) { + return + } + settled = true + clearTimeout(timeout) + for (const release of releaseListeners) { + release() + } + if (reply) { + resolve(reply) + } else { + reject(error) + } + } + const onRendererUnavailable = (): void => finish(new Error('renderer_unavailable')) + const timeout = setTimeout(() => finish(new Error(options.timeoutError)), options.timeoutMs) + const onReply = (event: Electron.IpcMainEvent, reply: TReply): void => { + // Visible request IDs confer no authority; only the targeted window can answer. + if (event.sender !== webContents || reply?.requestId !== requestId) { + return + } + finish(null, reply) + } + const lifetime = abortWhenRendererGone(webContents) + lifetime.signal.addEventListener('abort', onRendererUnavailable, { once: true }) + releaseListeners.push( + lifetime.dispose, + () => lifetime.signal.removeEventListener('abort', onRendererUnavailable), + addFanoutListener(mainWindow, 'closed', onRendererUnavailable), + addFanoutListener(ipcMain, options.replyChannel, onReply) + ) + try { + webContents.send(options.requestChannel, { ...options.payload, requestId }) + } catch { + finish(new Error('renderer_unavailable')) + } + }) +} diff --git a/src/main/window/runtime-window-lifecycle.ts b/src/main/window/runtime-window-lifecycle.ts index 003ba029679..9af8fcb8048 100644 --- a/src/main/window/runtime-window-lifecycle.ts +++ b/src/main/window/runtime-window-lifecycle.ts @@ -8,6 +8,7 @@ import type { RuntimeMobileSessionTabMove } from '../../shared/runtime-types' import type { TerminalTabCreateReply } from '../../shared/workspace-layout/terminal-reveal-identity' import { runWorktreeChangeInvalidators } from '../ipc/worktrees/listing/worktree-change-invalidators' import { requestAgentLaunchTabPublishFromRenderer } from './agent-launch-tab-publish-relay' +import { requestAgentPaneActivityFromRenderer } from './agent-pane-activity-relay' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import { registerRendererDocumentNavigation } from './renderer-document-navigation' import { createRuntimeRendererNotificationSender } from './runtime-renderer-notification-sender' @@ -16,6 +17,8 @@ import { requestTerminalPaneMoveFromRenderer } from './terminal-pane-move-reques import { revealTerminalPaneInWindow } from './terminal-pane-reveal-relay' import { requestTerminalTabCloseFromRenderer } from './terminal-tab-close-request-relay' import { ORCA_SIDEBAR_INPUTS_IS_MAIN } from '../../shared/sidebar-inputs-switch' +import type { AgentListPublication } from '../../shared/agent-status/presentation/agent-list-status' +import { addFanoutListener } from '../runtime/events/event-listener-fanout' let runtimeNotifierTokenCounter = 0 let activeRuntimeNotifierToken: number | null = null @@ -219,6 +222,7 @@ export function registerRuntimeWindowLifecycle( requestTerminalTabCloseFromRenderer(mainWindow, tabId, options), workspaceSleepChanged: (notice) => send('ui:workspaceSleep', notice), resumeSleepingAgents: (worktreeId) => send('ui:resumeSleepingAgents', { worktreeId }), + applyAgentPaneActivity: (change) => requestAgentPaneActivityFromRenderer(mainWindow, change), terminalFitOverrideChanged: (ptyId, mode, cols, rows) => send('runtime:terminalFitOverrideChanged', { ptyId, mode, cols, rows }), terminalDriverChanged: (ptyId, driver) => @@ -244,13 +248,29 @@ export function registerRuntimeWindowLifecycle( { consumesTerminalSideEffects: false } ) : null + // Only this window's live document speaks for the Agents list; a gone one leaves no verdicts behind. + const releaseAgentListVerdicts = addFanoutListener( + ipcMain, + 'agentStatus:listVerdicts', + (event: Electron.IpcMainEvent, publication: AgentListPublication | null) => { + if (event.sender === mainWebContents && event.senderFrame === mainWebContents.mainFrame) { + runtime.setAgentListPublication(publication) + } + } + ) registerRendererDocumentNavigation(mainWebContents, () => { rendererNotifications.onMainFrameReloadStarted() + const agentListBeforeReload = runtime.readAgentListPublication() + runtime.setAgentListPublication(null) const fence = runtime.markRendererReloading(mainWindow.id) return () => { if (fence && runtime.markRendererReloadCancelled(mainWindow.id, fence)) { rendererNotifications.onMainFrameReloadCancelled() } + // The surviving document only re-sends on change. + if (runtime.readAgentListPublication() === null) { + runtime.setAgentListPublication(agentListBeforeReload) + } } }) mainWebContents.on('did-finish-load', () => { @@ -258,9 +278,12 @@ export function registerRuntimeWindowLifecycle( }) mainWebContents.on('render-process-gone', () => { rendererNotifications.onRendererProcessGone() + runtime.setAgentListPublication(null) }) mainWindow.on('closed', () => { detachSidebarInputsNotices?.() + releaseAgentListVerdicts() + runtime.setAgentListPublication(null) rendererNotifications.close() runtime.markGraphUnavailable(mainWindow.id) if (activeRuntimeNotifierToken === notifierToken) { diff --git a/src/main/window/terminal-pane-reveal-relay.ts b/src/main/window/terminal-pane-reveal-relay.ts index 2238704d08f..837cc459556 100644 --- a/src/main/window/terminal-pane-reveal-relay.ts +++ b/src/main/window/terminal-pane-reveal-relay.ts @@ -1,14 +1,11 @@ -import { randomUUID } from 'node:crypto' - -import { app, ipcMain, type BrowserWindow } from 'electron' +import { app, type BrowserWindow } from 'electron' import type { TerminalPaneRevealReply, TerminalPaneRevealTarget } from '../../shared/workspace-layout/terminal-pane-reveal' -import { addFanoutListener } from '../runtime/events/event-listener-fanout' -import { abortWhenRendererGone } from '../ipc/renderer-lifetime-abort' import { focusExistingMainWindow } from './focus-existing-window' +import { requestRendererReply } from './renderer-reply-request' const TERMINAL_PANE_REVEAL_TIMEOUT_MS = 10_000 @@ -17,7 +14,14 @@ export async function revealTerminalPaneInWindow( mainWindow: BrowserWindow, target: TerminalPaneRevealTarget ): Promise { - const revealed = await requestTerminalPaneRevealFromRenderer(mainWindow, target) + const reply = await requestRendererReply(mainWindow, { + requestChannel: 'ui:revealTerminalPane', + replyChannel: 'ui:terminalPaneRevealReply', + payload: target, + timeoutMs: TERMINAL_PANE_REVEAL_TIMEOUT_MS, + timeoutError: 'terminal_reveal_timeout' + }) + const revealed = reply.revealed === true if (revealed) { focusExistingMainWindow({ app, @@ -29,58 +33,3 @@ export async function revealTerminalPaneInWindow( } return revealed } - -function requestTerminalPaneRevealFromRenderer( - mainWindow: BrowserWindow, - target: TerminalPaneRevealTarget -): Promise { - if (mainWindow.isDestroyed() || mainWindow.webContents.isDestroyed()) { - return Promise.reject(new Error('renderer_unavailable')) - } - const webContents = mainWindow.webContents - const requestId = randomUUID() - return new Promise((resolve, reject) => { - let settled = false - const releaseListeners: (() => void)[] = [] - const finish = (error: Error | null, revealed = false): void => { - if (settled) { - return - } - settled = true - clearTimeout(timeout) - for (const release of releaseListeners) { - release() - } - if (error) { - reject(error) - } else { - resolve(revealed) - } - } - const onRendererUnavailable = (): void => finish(new Error('renderer_unavailable')) - const timeout = setTimeout( - () => finish(new Error('terminal_reveal_timeout')), - TERMINAL_PANE_REVEAL_TIMEOUT_MS - ) - const onReply = (event: Electron.IpcMainEvent, reply: TerminalPaneRevealReply): void => { - // Visible request IDs confer no authority; only the targeted window can answer. - if (event.sender !== webContents || reply.requestId !== requestId) { - return - } - finish(null, reply.revealed === true) - } - const lifetime = abortWhenRendererGone(webContents) - lifetime.signal.addEventListener('abort', onRendererUnavailable, { once: true }) - releaseListeners.push( - lifetime.dispose, - () => lifetime.signal.removeEventListener('abort', onRendererUnavailable), - addFanoutListener(mainWindow, 'closed', onRendererUnavailable), - addFanoutListener(ipcMain, 'ui:terminalPaneRevealReply', onReply) - ) - try { - webContents.send('ui:revealTerminalPane', { ...target, requestId }) - } catch { - finish(new Error('renderer_unavailable')) - } - }) -} diff --git a/src/preload/api/agent-status-api.ts b/src/preload/api/agent-status-api.ts index d34fa917782..5df1f88ef65 100644 --- a/src/preload/api/agent-status-api.ts +++ b/src/preload/api/agent-status-api.ts @@ -7,6 +7,7 @@ import type { import type { AgentInterruptInferenceRequest } from '../../shared/agent-status/lifecycle/agent-interrupt-intent' import type { AgentQuestionAnsweredInferenceRequest } from '../../shared/agent-status/lifecycle/agent-question-answered-intent' import type { ComputerAwakeStatus } from '../../shared/computer-awake-mode' +import type { AgentListPublication } from '../../shared/agent-status/presentation/agent-list-status' export type AgentStatusApi = { /** Listen for agent status updates forwarded from native hook receivers. */ @@ -45,6 +46,8 @@ export type AgentStatusApi = { /** Lift one pane's retirement fence when a live PTY re-attaches to it. Closed tabs stay retired. */ restorePaneAuthority: (paneKey: string) => void transferPaneAuthority: (args: { fromPaneKey: string; toPaneKey: string; ptyId?: string }) => void + /** The Agents list's verdicts, for worktree.ps to show paired clients. Fire-and-forget. */ + publishListVerdicts?: (publication: AgentListPublication | null) => void } export type AgentAwakeApi = { diff --git a/src/preload/api/agent-status-bridge.ts b/src/preload/api/agent-status-bridge.ts index dbf6ebb6f86..1a57c712b49 100644 --- a/src/preload/api/agent-status-bridge.ts +++ b/src/preload/api/agent-status-bridge.ts @@ -7,6 +7,7 @@ import type { } from '../../shared/agent-status/contracts/agent-status-ipc-payload' import type { AgentInterruptInferenceRequest } from '../../shared/agent-status/lifecycle/agent-interrupt-intent' import type { AgentQuestionAnsweredInferenceRequest } from '../../shared/agent-status/lifecycle/agent-question-answered-intent' +import type { AgentListPublication } from '../../shared/agent-status/presentation/agent-list-status' import type { PreloadApi } from '../api-types' export const agentStatusApi = { @@ -72,6 +73,9 @@ export const agentStatusApi = { dropPersistedBatch: (identities: readonly AgentStatusCacheIdentity[]): void => { ipcRenderer.send('agentStatus:dropPersistedBatch', identities) }, + publishListVerdicts: (publication: AgentListPublication | null): void => { + ipcRenderer.send('agentStatus:listVerdicts', publication) + }, reconcileEndedProcess: (paneKey: string): void => { ipcRenderer.send('agentStatus:reconcileEndedProcess', paneKey) }, diff --git a/src/preload/api/ui-bridge-clipboard-and-window-controls.ts b/src/preload/api/ui-bridge-clipboard-and-window-controls.ts index b7638093379..ed9e8eb9b0a 100644 --- a/src/preload/api/ui-bridge-clipboard-and-window-controls.ts +++ b/src/preload/api/ui-bridge-clipboard-and-window-controls.ts @@ -11,6 +11,10 @@ import type { RuntimeNavigationTarget } from '../../shared/runtime-navigation' import type { TerminalSurfaceCloseTarget } from '../../shared/workspace-layout/terminal-surface-close-target' import type { ClipboardImageThumbnail } from '../../shared/clipboard-image' import type { ReadClipboardTextOptions } from '../../shared/clipboard-text' +import type { + AgentPaneActivityReply, + AgentPaneActivityRequest +} from '../../shared/agent-status/presentation/agent-list-status' import type { PreloadApi } from '../api-types' export const uiClipboardAndWindowControlsApi = { @@ -85,6 +89,15 @@ export const uiClipboardAndWindowControlsApi = { ipcRenderer.on('ui:resumeSleepingAgents', listener) return () => ipcRenderer.removeListener('ui:resumeSleepingAgents', listener) }, + onApplyAgentPaneActivity: (callback: (data: AgentPaneActivityRequest) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, data: AgentPaneActivityRequest) => + callback(data) + ipcRenderer.on('ui:applyAgentPaneActivity', listener) + return () => ipcRenderer.removeListener('ui:applyAgentPaneActivity', listener) + }, + replyAgentPaneActivity: (reply: AgentPaneActivityReply): void => { + ipcRenderer.send('ui:agentPaneActivityReply', reply) + }, onTerminalZoom: (callback: (direction: 'in' | 'out' | 'reset') => void): (() => void) => { const listener = (_event: Electron.IpcRendererEvent, direction: 'in' | 'out' | 'reset') => callback(direction) diff --git a/src/preload/api/ui-command-event-api.ts b/src/preload/api/ui-command-event-api.ts index cfb796cc184..f9895cec986 100644 --- a/src/preload/api/ui-command-event-api.ts +++ b/src/preload/api/ui-command-event-api.ts @@ -26,6 +26,10 @@ import type { TerminalPaneRevealReply, TerminalPaneRevealRequest } from '../../shared/workspace-layout/terminal-pane-reveal' +import type { + AgentPaneActivityReply, + AgentPaneActivityRequest +} from '../../shared/agent-status/presentation/agent-list-status' import type { RuntimeNavigationTarget } from '../../shared/runtime-navigation' import type { ProjectMovePauseRequest, @@ -225,6 +229,8 @@ export type UiCommandEventApi = { onLaunchRecipe: (callback: (data: PaneLaunchRecipe) => void) => () => void onRevealTerminalPane: (callback: (data: TerminalPaneRevealRequest) => void) => () => void replyTerminalPaneReveal: (reply: TerminalPaneRevealReply) => void + onApplyAgentPaneActivity: (callback: (data: AgentPaneActivityRequest) => void) => () => void + replyAgentPaneActivity: (reply: AgentPaneActivityReply) => void onSplitTerminal: ( callback: (data: { tabId: string diff --git a/src/renderer/src/app-shell/AppBackgroundServices.tsx b/src/renderer/src/app-shell/AppBackgroundServices.tsx index d1c9ce9c824..0fa98b6070d 100644 --- a/src/renderer/src/app-shell/AppBackgroundServices.tsx +++ b/src/renderer/src/app-shell/AppBackgroundServices.tsx @@ -12,8 +12,12 @@ import { ActiveWorkspaceSyncGate } from './ActiveWorkspaceSyncGate' import { StructuredAgentSessionAttentionBridge } from '../components/native-chat/session/attention/StructuredAgentSessionAttentionBridge' import { StructuredAgentSessionStatusBridge } from '../components/native-chat/session/status/StructuredAgentSessionStatusBridge' import { NativeChatVisualGuestThemePublisher } from '../components/native-chat/media/visuals/NativeChatVisualGuestThemePublisher' +import { usePairedMobileDevices } from '../components/mobile/paired-mobile-devices' const DashboardPopoutBridge = lazy(() => import('../components/dashboard/DashboardPopoutBridge')) +const AgentListVerdictPublisher = lazy( + () => import('../components/activity/agent-list-verdict-publisher') +) /** Isolate high-churn subscriptions from App rendering; services outlive their consuming surfaces. */ export function AppBackgroundServices(): React.JSX.Element { @@ -21,6 +25,9 @@ export function AppBackgroundServices(): React.JSX.Element { const dashboardPopoutEnabled = useAppStore( (s) => s.settings?.experimentalAgentDashboardPopout === true ) + const canPublishAgentList = Boolean(window.api.agentStatus?.publishListVerdicts) + // The list builds on every agent update, so only a desktop with a paired phone pays for it. + const { hasPairedDevice } = usePairedMobileDevices({ enabled: canPublishAgentList }) return ( <> @@ -40,6 +47,12 @@ export function AppBackgroundServices(): React.JSX.Element { ) : null} + {/* Paired phones list agents with the desktop Agents list's verdicts; web clients have no host to tell. */} + {canPublishAgentList && hasPairedDevice ? ( + + + + ) : null} {/* Background chats have no mounted pane but still need completion attention. */} diff --git a/src/renderer/src/components/AgentStateDot.tsx b/src/renderer/src/components/AgentStateDot.tsx index 1cbc1ca512b..f9449bdfb64 100644 --- a/src/renderer/src/components/AgentStateDot.tsx +++ b/src/renderer/src/components/AgentStateDot.tsx @@ -14,25 +14,11 @@ import { StateIndicatorTooltip, type StateIndicatorTooltipSide } from '@/components/StateIndicatorTooltip' +import type { AgentListStatus } from '../../../shared/agent-status/presentation/agent-list-status' // Share state glyphs across agent surfaces. Keep the agent identity icon separate; completion uses a check while sidebar StatusIndicator uses an emerald dot/tooltip. -export type AgentDotState = - | 'working' - | 'monitoring' - | 'blocked' - | 'waiting' - | 'interrupted' - // Transcript-derived failure is an outcome, distinct from live blocked attention. - | 'failed' - | 'done' - | 'idle' - // A live PTY with stale reporting proves only missing evidence, not idle/work/completion. - | 'unverifiable' - // The turn ended without a proven outcome; use the missing-evidence glyph, never completion. - | 'unconfirmed' - // Sidebar combines blocked/waiting as permission; retain its vocabulary with the shared question glyph/token. - | 'permission' +export type AgentDotState = AgentListStatus /** Return the accessible label shared by every visual agent-state marker. */ export function agentStateLabel(state: AgentDotState): string { diff --git a/src/renderer/src/components/activity/activity-paired-client-change.ts b/src/renderer/src/components/activity/activity-paired-client-change.ts new file mode 100644 index 00000000000..401dcc2d718 --- /dev/null +++ b/src/renderer/src/components/activity/activity-paired-client-change.ts @@ -0,0 +1,37 @@ +import { useAppStore } from '@/store' +import type { + AgentListPublication, + AgentPaneActivityChange +} from '../../../../shared/agent-status/presentation/agent-list-status' +import { clearActivityThread } from './activity-clear-completed' +import { publishAgentListNow, readPublishedAgentPaneThreads } from './agent-list-verdict-publisher' + +/** Applies a paired client's change with the same actions as the Agents list row, then answers with the list it leaves. */ +export function applyPairedClientActivityChange( + change: AgentPaneActivityChange +): Promise { + const state = useAppStore.getState() + const threads = readPublishedAgentPaneThreads() + // Unhydrated maps are empty, and main would persist them over the saved ones. + if (!state.persistedUIReady || !threads) { + throw new Error('agent_activity_not_ready') + } + if (change.kind === 'read') { + state.acknowledgeAgents(change.paneKeys, undefined, 'explicit') + } else if (change.kind === 'unread') { + state.unacknowledgeAgents(change.paneKeys) + } else { + const paneKeys = new Set(change.paneKeys) + let cleared = 0 + for (const thread of threads) { + if (paneKeys.has(thread.paneKey) && clearActivityThread(thread)) { + cleared += 1 + } + } + // Answering success would let the phone drop its guess and show the row again with no word why. + if (cleared === 0) { + throw new Error('agent_activity_not_clearable') + } + } + return publishAgentListNow() +} diff --git a/src/renderer/src/components/activity/activity-thread-child-agent.ts b/src/renderer/src/components/activity/activity-thread-child-agent.ts index 3b6c75339f9..2f2297f3d04 100644 --- a/src/renderer/src/components/activity/activity-thread-child-agent.ts +++ b/src/renderer/src/components/activity/activity-thread-child-agent.ts @@ -46,6 +46,14 @@ function firstReportedTerminalHandle(thread: ChildAgentClassifiableThread): stri export function collectHiddenChildAgentPaneKeys( threads: readonly ChildAgentClassifiableThread[] ): Set { + return classifyChildAgents(threads).hidden +} + +/** Each child's parent and the children a hidden-children view folds away. */ +export function classifyChildAgents(threads: readonly ChildAgentClassifiableThread[]): { + parentPaneKeyByChild: Map + hidden: Set +} { const baseRows: AgentLineageSourceRow[] = threads.map((thread) => ({ paneKey: thread.paneKey, entry: { terminalHandle: firstReportedTerminalHandle(thread) } @@ -83,11 +91,18 @@ export function collectHiddenChildAgentPaneKeys( const livePaneKeys = new Set( threads.filter((thread) => thread.currentAgentState).map((thread) => thread.paneKey) ) + const tree = buildAgentRowLineageTree(rows) + const parentPaneKeyByChild = new Map() + for (const [parentPaneKey, children] of tree.childrenByParentPaneKey) { + for (const child of children) { + parentPaneKeyByChild.set(child.paneKey, parentPaneKey) + } + } const hidden = new Set() - for (const paneKey of buildAgentRowLineageTree(rows).childPaneKeys) { + for (const paneKey of tree.childPaneKeys) { if (!livePaneKeys.has(paneKey)) { hidden.add(paneKey) } } - return hidden + return { parentPaneKeyByChild, hidden } } diff --git a/src/renderer/src/components/activity/activity-thread-grouping.ts b/src/renderer/src/components/activity/activity-thread-grouping.ts index 997a0404437..1fcea62126c 100644 --- a/src/renderer/src/components/activity/activity-thread-grouping.ts +++ b/src/renderer/src/components/activity/activity-thread-grouping.ts @@ -10,30 +10,14 @@ import { agentMeta, agentSummary, agentTitle, - threadAgentStateLabel, - type ActivityThreadStatusId + threadAgentStateLabel } from './activity-thread-presentation' +import { AGENT_LIST_STATUS_RANK } from '../../../../shared/agent-status/presentation/agent-list-status' import type { ActivityGroupBy } from '../../../../shared/agents-view-thread-filters' import type { ActivityThreadGroup, AgentPaneThread } from './activity-thread-types' -// Use exhaustive, unique attention ranks so new states fail typecheck and recency cannot reorder headers. -const ACTIVITY_STATUS_GROUP_RANK: Record = { - waiting: 0, - blocked: 1, - permission: 2, - failed: 3, - unconfirmed: 4, - working: 5, - monitoring: 6, - // A user's Stop is not news, so it follows live work, but it is not a finish either. - interrupted: 7, - unverifiable: 8, - done: 9, - idle: 10 -} - function activityStatusRank(thread: AgentPaneThread): number { - return ACTIVITY_STATUS_GROUP_RANK[activityThreadStatusId(thread)] + return AGENT_LIST_STATUS_RANK[activityThreadStatusId(thread)] } export function getActivityThreadGroup( diff --git a/src/renderer/src/components/activity/agent-list-verdict-publisher.ts b/src/renderer/src/components/activity/agent-list-verdict-publisher.ts new file mode 100644 index 00000000000..862eb825ddf --- /dev/null +++ b/src/renderer/src/components/activity/agent-list-verdict-publisher.ts @@ -0,0 +1,134 @@ +import { useEffect, useMemo, useState } from 'react' +import { useAppStore } from '@/store' +import type { + AgentListPublication, + AgentListVerdict +} from '../../../../shared/agent-status/presentation/agent-list-status' +import { isClearableActivityThread } from './activity-clear-completed' +import { classifyChildAgents } from './activity-thread-child-agent' +import { activityThreadStatusId } from './activity-thread-presentation' +import type { AgentPaneThread } from './activity-thread-types' +import { useAllAgentPaneThreads } from './use-agent-pane-threads' + +const PUBLISH_INTERVAL_MS = 250 + +/** The Agents list's verdict for every pane the window knows; a pane with no thread is unlisted. */ +function buildAgentListVerdicts( + threads: readonly AgentPaneThread[], + knownPaneKeys: readonly string[] +): Record { + const { parentPaneKeyByChild, hidden } = classifyChildAgents(threads) + const verdicts: Record = {} + for (const paneKey of knownPaneKeys) { + verdicts[paneKey] = { listed: false } + } + for (const thread of threads) { + const childOf = parentPaneKeyByChild.get(thread.paneKey) + verdicts[thread.paneKey] = { + listed: true, + status: activityThreadStatusId(thread), + unread: thread.unread, + clearable: isClearableActivityThread(thread), + sortAt: thread.latestTimestamp, + title: thread.paneTitle, + ...(childOf ? { childOf } : {}), + ...(hidden.has(thread.paneKey) ? { foldedChild: true as const } : {}) + } + } + return verdicts +} + +// One publisher per window; a paired client's change reads its threads and waits for its next publish. +let published: { threads: readonly AgentPaneThread[]; publication: AgentListPublication } | null = + null +let requestRender: (() => void) | null = null +let waiters: ((publication: AgentListPublication) => void)[] = [] +let lastSentVerdicts: string | null = null +let lastSentAt = 0 +let timer: ReturnType | null = null + +function send(publication: AgentListPublication): void { + if (timer !== null) { + clearTimeout(timer) + timer = null + } + lastSentAt = Date.now() + const verdicts = JSON.stringify(publication.verdicts) + if (verdicts !== lastSentVerdicts) { + lastSentVerdicts = verdicts + window.api.agentStatus.publishListVerdicts?.(publication) + } +} + +/** The threads behind the last published verdicts; null until the publisher has run. */ +export function readPublishedAgentPaneThreads(): readonly AgentPaneThread[] | null { + return published?.threads ?? null +} + +/** Resolves with the verdicts once the publisher has rendered the store as it is now. */ +export function publishAgentListNow(): Promise { + const render = requestRender + if (!render) { + return Promise.reject(new Error('agent_activity_not_ready')) + } + return new Promise((resolve) => { + waiters.push(resolve) + render() + }) +} + +/** Sends the desktop Agents list's verdicts to main, so worktree.ps shows paired clients the same list. */ +export default function AgentListVerdictPublisher(): null { + const ready = useAppStore((s) => s.persistedUIReady) + // The unscoped list: view filters and the child-agent toggle only narrow what one surface shows. + const { storeData, allThreads } = useAllAgentPaneThreads() + const [renderRequest, setRenderRequest] = useState(0) + useEffect(() => { + requestRender = () => setRenderRequest((count) => count + 1) + return () => { + requestRender = null + published = null + lastSentVerdicts = null + // Unmounted with no phone paired: stale verdicts would hide new agents from a later pairing. + window.api.agentStatus.publishListVerdicts?.(null) + if (timer !== null) { + clearTimeout(timer) + timer = null + } + } + }, []) + const verdicts = useMemo( + () => buildAgentListVerdicts(allThreads, Object.keys(storeData.agentStatusByPaneKey)), + [allThreads, storeData.agentStatusByPaneKey] + ) + useEffect(() => { + // Unhydrated read stamps would mark every agent unread. + if (!ready) { + return + } + const publication = { publishedAt: Date.now(), verdicts } + published = { threads: allThreads, publication } + const pending = waiters + waiters = [] + if (pending.length > 0) { + send(publication) + for (const resolve of pending) { + resolve(publication) + } + return + } + // Each run reschedules from the last send, so a busy store cannot starve the publish. + const scheduled = setTimeout( + () => published && send(published.publication), + Math.max(0, lastSentAt + PUBLISH_INTERVAL_MS - Date.now()) + ) + timer = scheduled + return () => { + clearTimeout(scheduled) + if (timer === scheduled) { + timer = null + } + } + }, [ready, allThreads, verdicts, renderRequest]) + return null +} diff --git a/src/renderer/src/components/activity/use-agent-pane-thread-store-data.ts b/src/renderer/src/components/activity/use-agent-pane-thread-store-data.ts index 4e647f4f26f..cc2aac04cb3 100644 --- a/src/renderer/src/components/activity/use-agent-pane-thread-store-data.ts +++ b/src/renderer/src/components/activity/use-agent-pane-thread-store-data.ts @@ -16,7 +16,7 @@ import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' -export type AgentPaneThreadsStoreData = Pick< +export type AllAgentPaneThreadsStoreData = Pick< AppState, | 'agentStatusByPaneKey' | 'runtimeAgentOrchestrationByPaneKey' @@ -39,11 +39,20 @@ export type AgentPaneThreadsStoreData = Pick< worktreeMap: ReturnType repoMap: ReturnType generatedTitlesEnabled: boolean +} + +export type AgentPaneThreadsStoreData = AllAgentPaneThreadsStoreData & { /** Focused-host fallback for hostless worktrees, shared by the scope filter and the row actions. */ defaultHostId: ExecutionHostId } -export function useAgentPaneThreadStoreData(): AgentPaneThreadsStoreData { +/** Focused-host fallback for the scope filter and row actions; the unscoped list never reads it. */ +export function useAgentPaneThreadsDefaultHostId(): ExecutionHostId { + return useAppStore((s) => getSettingsFocusedExecutionHostId(s.settings)) +} + +/** Store inputs for every Activity thread, before any view scope. */ +export function useAllAgentPaneThreadStoreData(): AllAgentPaneThreadsStoreData { // Keep original native tabs for owner-qualified names; preserve terminal projections across focus writes. const tabProjectionRef = useRef<{ raw: AppState['unifiedTabsByWorktree'] | null @@ -77,8 +86,7 @@ export function useAgentPaneThreadStoreData(): AgentPaneThreadsStoreData { activityClearedAtByPaneKey: s.activityClearedAtByPaneKey, acknowledgeAgents: s.acknowledgeAgents, unacknowledgeAgents: s.unacknowledgeAgents, - generatedTitlesEnabled: s.settings?.tabAutoGenerateTitle === true, - defaultHostId: getSettingsFocusedExecutionHostId(s.settings) + generatedTitlesEnabled: s.settings?.tabAutoGenerateTitle === true })) ) } diff --git a/src/renderer/src/components/activity/use-agent-pane-threads.ts b/src/renderer/src/components/activity/use-agent-pane-threads.ts index 32836ff12b8..e32bb3c9ec2 100644 --- a/src/renderer/src/components/activity/use-agent-pane-threads.ts +++ b/src/renderer/src/components/activity/use-agent-pane-threads.ts @@ -4,8 +4,10 @@ import { useStructuredChatTabNames } from '@/runtime/native-chat/naming/structur import { buildActivityEvents, createActivityEventBuildCache } from './activity-event-builder' import { freshActivityLiveAgentState } from './activity-event-state' import { - useAgentPaneThreadStoreData, - type AgentPaneThreadsStoreData + useAgentPaneThreadsDefaultHostId, + useAllAgentPaneThreadStoreData, + type AgentPaneThreadsStoreData, + type AllAgentPaneThreadsStoreData } from './use-agent-pane-thread-store-data' import { buildAgentPaneThreads, createAgentPaneThreadReuseCache } from './activity-thread-builder' import { collectHiddenChildAgentPaneKeys } from './activity-thread-child-agent' @@ -34,56 +36,12 @@ const EMPTY_ACTIVITY_BUILD: ReturnType = { paneEntryByPaneKey: {} } -/** Shared Activity/sidebar pipeline: store data to events, threads, filters and groups. */ -export function useAgentPaneThreads(args: { - query: string - readFilter: ThreadReadFilter - groupBy: ActivityGroupBy - selectedPaneKey: string | null - showChildAgents?: boolean - /** Prepare only live badge rows, omitting list groups and bulk-action sets. */ - badgeOnly?: boolean -}): { - storeData: AgentPaneThreadsStoreData +/** Every Activity thread before any view filter: store data to events and threads. */ +export function useAllAgentPaneThreads({ badgeOnly = false }: { badgeOnly?: boolean } = {}): { + storeData: AllAgentPaneThreadsStoreData allThreads: AgentPaneThread[] - selectedPaneKeyIsLive: boolean - effectiveSelectedPaneKey: string | null - /** Every active view filter applies here; destructive Clear completed must not touch hidden rows. */ - visibleThreads: AgentPaneThread[] - /** Badge-coherent threads after child classification; ignore transient search/scope/read filters so Mark all read can clear the badge. */ - markAllReadThreads: AgentPaneThread[] - visibleThreadGroups: ActivityThreadGroup[] } { - const { - query, - readFilter, - groupBy, - selectedPaneKey, - showChildAgents = false, - badgeOnly = false - } = args - const agentsVisibleHostIds = useAppStore((s) => s.agentsVisibleHostIds) - const agentsFilterRepoIds = useAppStore((s) => s.agentsFilterRepoIds) - const hideWorkspacesFromOtherDevices = useAppStore((s) => s.agentsHideWorkspacesFromOtherDevices) - const hideAutomationGeneratedWorkspaces = useAppStore( - (s) => s.agentsHideAutomationGeneratedWorkspaces - ) - const hideCliCreatedWorkspaces = useAppStore((s) => s.agentsHideCliCreatedWorkspaces) - // Why gated selectors: runtime status churns, and only the other-device filter reads it. - const runtimeEnvironments = useAppStore((s) => - s.agentsHideWorkspacesFromOtherDevices ? s.runtimeEnvironments : null - ) - const runtimeStatusByEnvironmentId = useAppStore((s) => - s.agentsHideWorkspacesFromOtherDevices ? s.runtimeStatusByEnvironmentId : null - ) - const pairedDeviceIdsByEnvironment = useMemo( - () => - runtimeEnvironments && runtimeStatusByEnvironmentId - ? getPairedDeviceIdsByEnvironment(runtimeEnvironments, runtimeStatusByEnvironmentId) - : EMPTY_PAIRED_DEVICE_IDS_BY_ENVIRONMENT, - [runtimeEnvironments, runtimeStatusByEnvironmentId] - ) - const storeData = useAgentPaneThreadStoreData() + const storeData = useAllAgentPaneThreadStoreData() // Why: agentStatusEpoch is a dep (not used in the body) so the memo recomputes when freshness boundaries expire even without new PTY data. const agentStatusEpoch = useAppStore((s) => s.agentStatusEpoch) const chatNames = useStructuredChatTabNames() @@ -153,6 +111,65 @@ export function useAgentPaneThreads(args: { [allEvents, liveAgentByPaneKey, paneEntryByPaneKey, storeData.generatedTitlesEnabled, badgeOnly] ) + return { storeData, allThreads } +} + +/** Shared Activity/sidebar pipeline: store data to events, threads, filters and groups. */ +export function useAgentPaneThreads(args: { + query: string + readFilter: ThreadReadFilter + groupBy: ActivityGroupBy + selectedPaneKey: string | null + showChildAgents?: boolean + /** Prepare only live badge rows, omitting list groups and bulk-action sets. */ + badgeOnly?: boolean +}): { + storeData: AgentPaneThreadsStoreData + allThreads: AgentPaneThread[] + selectedPaneKeyIsLive: boolean + effectiveSelectedPaneKey: string | null + /** Every active view filter applies here; destructive Clear completed must not touch hidden rows. */ + visibleThreads: AgentPaneThread[] + /** Badge-coherent threads after child classification; ignore transient search/scope/read filters so Mark all read can clear the badge. */ + markAllReadThreads: AgentPaneThread[] + visibleThreadGroups: ActivityThreadGroup[] +} { + const { + query, + readFilter, + groupBy, + selectedPaneKey, + showChildAgents = false, + badgeOnly = false + } = args + const agentsVisibleHostIds = useAppStore((s) => s.agentsVisibleHostIds) + const agentsFilterRepoIds = useAppStore((s) => s.agentsFilterRepoIds) + const hideWorkspacesFromOtherDevices = useAppStore((s) => s.agentsHideWorkspacesFromOtherDevices) + const hideAutomationGeneratedWorkspaces = useAppStore( + (s) => s.agentsHideAutomationGeneratedWorkspaces + ) + const hideCliCreatedWorkspaces = useAppStore((s) => s.agentsHideCliCreatedWorkspaces) + // Why gated selectors: runtime status churns, and only the other-device filter reads it. + const runtimeEnvironments = useAppStore((s) => + s.agentsHideWorkspacesFromOtherDevices ? s.runtimeEnvironments : null + ) + const runtimeStatusByEnvironmentId = useAppStore((s) => + s.agentsHideWorkspacesFromOtherDevices ? s.runtimeStatusByEnvironmentId : null + ) + const pairedDeviceIdsByEnvironment = useMemo( + () => + runtimeEnvironments && runtimeStatusByEnvironmentId + ? getPairedDeviceIdsByEnvironment(runtimeEnvironments, runtimeStatusByEnvironmentId) + : EMPTY_PAIRED_DEVICE_IDS_BY_ENVIRONMENT, + [runtimeEnvironments, runtimeStatusByEnvironmentId] + ) + const { storeData: unscopedStoreData, allThreads } = useAllAgentPaneThreads({ badgeOnly }) + const defaultHostId = useAgentPaneThreadsDefaultHostId() + const storeData = useMemo( + () => ({ ...unscopedStoreData, defaultHostId }), + [unscopedStoreData, defaultHostId] + ) + const selectedPaneKeyIsLive = selectedPaneKey === null || allThreads.some((thread) => thread.paneKey === selectedPaneKey) const effectiveSelectedPaneKey = selectedPaneKeyIsLive ? selectedPaneKey : null @@ -201,7 +218,8 @@ export function useAgentPaneThreads(args: { const normalizedQuery = isActivitySearchQueryTooLarge(deferredQuery) ? null : deferredQuery.trim().toLowerCase() - let matchesSearchQuery: ReturnType | undefined + const matchesSearchQuery = + normalizedQuery === null ? null : createActivityThreadSearchMatcher(normalizedQuery) return scopeVisibleThreads.filter((thread) => { // Why: keep the just-selected thread visible after auto-mark-read flips it to read, else unread-only mode makes the clicked row vanish from the list. if ( @@ -219,11 +237,7 @@ export function useAgentPaneThreads(args: { ) { return false } - if (normalizedQuery === null) { - return false - } - matchesSearchQuery ??= createActivityThreadSearchMatcher(normalizedQuery) - return matchesSearchQuery(thread) + return matchesSearchQuery !== null && matchesSearchQuery(thread) }) }, [ scopeVisibleThreads, diff --git a/src/renderer/src/hooks/ipc-events-agent-status-window-test-fixtures.ts b/src/renderer/src/hooks/ipc-events-agent-status-window-test-fixtures.ts index 90b86ec2f4f..6acae390313 100644 --- a/src/renderer/src/hooks/ipc-events-agent-status-window-test-fixtures.ts +++ b/src/renderer/src/hooks/ipc-events-agent-status-window-test-fixtures.ts @@ -50,6 +50,7 @@ export function buildWindowApi(args: { onRequestTerminalCreate: () => () => {}, onPublishAgentLaunchTab: () => () => {}, onRevealTerminalPane: () => () => {}, + onApplyAgentPaneActivity: () => () => {}, onAgentLaunchPaneVerdict: () => () => {}, onLaunchRecipe: () => () => {}, onRequestTerminalTabMount: () => () => {}, diff --git a/src/renderer/src/hooks/ipc-events-close-routing-test-harness.ts b/src/renderer/src/hooks/ipc-events-close-routing-test-harness.ts index 1b6a6b05fe0..8ee024aecf7 100644 --- a/src/renderer/src/hooks/ipc-events-close-routing-test-harness.ts +++ b/src/renderer/src/hooks/ipc-events-close-routing-test-harness.ts @@ -181,6 +181,7 @@ export async function useIpcEventsForCloseRouting({ onRequestTerminalCreate: () => () => {}, onPublishAgentLaunchTab: () => () => {}, onRevealTerminalPane: () => () => {}, + onApplyAgentPaneActivity: () => () => {}, onAgentLaunchPaneVerdict: () => () => {}, onLaunchRecipe: () => () => {}, onRequestTerminalTabMount: () => () => {}, diff --git a/src/renderer/src/hooks/ipc-events/agent-pane-activity-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/agent-pane-activity-ipc-bridge.ts new file mode 100644 index 00000000000..4c5a44bcbbd --- /dev/null +++ b/src/renderer/src/hooks/ipc-events/agent-pane-activity-ipc-bridge.ts @@ -0,0 +1,19 @@ +import type { AgentPaneActivityReply } from '../../../../shared/agent-status/presentation/agent-list-status' + +export function registerAgentPaneActivityIpcBridge(unsubs: (() => void)[]): void { + unsubs.push( + window.api.ui.onApplyAgentPaneActivity(({ requestId, ...change }) => { + // Lazy: Activity's clear module binds window listeners on load. Main holds the caller's RPC open until this reply, so a throw must still answer. + void import('@/components/activity/activity-paired-client-change') + .then(({ applyPairedClientActivityChange }) => applyPairedClientActivityChange(change)) + .then( + (publication): AgentPaneActivityReply => ({ requestId, publication }), + (error: unknown): AgentPaneActivityReply => ({ + requestId, + error: error instanceof Error ? error.message : 'agent_activity_failed' + }) + ) + .then((reply) => window.api.ui.replyAgentPaneActivity(reply)) + }) + ) +} diff --git a/src/renderer/src/hooks/ipc-events/app-lifetime-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/app-lifetime-ipc-bridge.ts index aeccf75f220..80e83e8e5ad 100644 --- a/src/renderer/src/hooks/ipc-events/app-lifetime-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/app-lifetime-ipc-bridge.ts @@ -36,6 +36,7 @@ import { registerPtySourceDisownedIpcBridge } from './pty-source-disowned-ipc-br import { registerTerminalRequestIpcBridge } from './terminal-request-ipc-bridge' import { registerAgentLaunchTabIpcBridge } from './agent-launch-tab-ipc-bridge' import { registerTerminalPaneRevealIpcBridge } from './terminal-pane-reveal-ipc-bridge' +import { registerAgentPaneActivityIpcBridge } from './agent-pane-activity-ipc-bridge' import { registerTerminalUiRoutingIpcBridge } from './terminal-ui-routing-ipc-bridge' import { registerUpdaterStatusIpcBridge } from './updater-status-ipc-bridge' import { createWorktreeEventRuntime } from './worktree-event-runtime' @@ -128,6 +129,7 @@ export function installAppLifetimeIpcEvents(): () => void { registerPtySourceDisownedIpcBridge(unsubs) registerTerminalUiRoutingIpcBridge(unsubs) registerTerminalPaneRevealIpcBridge(unsubs) + registerAgentPaneActivityIpcBridge(unsubs) registerSessionTabIpcBridge(unsubs) registerMobileAndTerminalCloseIpcBridge(unsubs, backgroundWakeDispatcher.request) registerUpdaterStatusIpcBridge(unsubs) diff --git a/src/renderer/src/hooks/useIpcEvents-cli-worktree-activation.test.ts b/src/renderer/src/hooks/useIpcEvents-cli-worktree-activation.test.ts index 593243d963d..99f82153e85 100644 --- a/src/renderer/src/hooks/useIpcEvents-cli-worktree-activation.test.ts +++ b/src/renderer/src/hooks/useIpcEvents-cli-worktree-activation.test.ts @@ -140,6 +140,7 @@ describe('useIpcEvents CLI-created worktree activation', () => { onRequestTerminalCreate: () => () => {}, onPublishAgentLaunchTab: () => () => {}, onRevealTerminalPane: () => () => {}, + onApplyAgentPaneActivity: () => () => {}, onAgentLaunchPaneVerdict: () => () => {}, onLaunchRecipe: () => () => {}, onRequestTerminalTabMount: () => () => {}, @@ -404,6 +405,7 @@ describe('useIpcEvents CLI-created worktree activation', () => { onRequestTerminalCreate: () => () => {}, onPublishAgentLaunchTab: () => () => {}, onRevealTerminalPane: () => () => {}, + onApplyAgentPaneActivity: () => () => {}, onAgentLaunchPaneVerdict: () => () => {}, onLaunchRecipe: () => () => {}, onRequestTerminalTabMount: () => () => {}, diff --git a/src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts b/src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts index ab86cea6d68..946f333b56c 100644 --- a/src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts +++ b/src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts @@ -143,6 +143,7 @@ describe('useIpcEvents browser tab close routing', () => { onRequestTerminalCreate: () => () => {}, onPublishAgentLaunchTab: () => () => {}, onRevealTerminalPane: () => () => {}, + onApplyAgentPaneActivity: () => () => {}, onAgentLaunchPaneVerdict: () => () => {}, onLaunchRecipe: () => () => {}, onRequestTerminalTabMount: () => () => {}, @@ -374,6 +375,7 @@ describe('useIpcEvents browser tab close routing', () => { onRequestTerminalCreate: () => () => {}, onPublishAgentLaunchTab: () => () => {}, onRevealTerminalPane: () => () => {}, + onApplyAgentPaneActivity: () => () => {}, onAgentLaunchPaneVerdict: () => () => {}, onLaunchRecipe: () => () => {}, onRequestTerminalTabMount: () => () => {}, @@ -600,6 +602,7 @@ describe('useIpcEvents browser tab close routing', () => { onRequestTerminalCreate: () => () => {}, onPublishAgentLaunchTab: () => () => {}, onRevealTerminalPane: () => () => {}, + onApplyAgentPaneActivity: () => () => {}, onAgentLaunchPaneVerdict: () => () => {}, onLaunchRecipe: () => () => {}, onRequestTerminalTabMount: () => () => {}, diff --git a/src/renderer/src/hooks/useIpcEvents-ssh-disconnect-cleanup.test.ts b/src/renderer/src/hooks/useIpcEvents-ssh-disconnect-cleanup.test.ts index 35c7e61e8cd..920d515265c 100644 --- a/src/renderer/src/hooks/useIpcEvents-ssh-disconnect-cleanup.test.ts +++ b/src/renderer/src/hooks/useIpcEvents-ssh-disconnect-cleanup.test.ts @@ -155,6 +155,7 @@ describe('useIpcEvents updater integration', () => { onRequestTerminalCreate: () => () => {}, onPublishAgentLaunchTab: () => () => {}, onRevealTerminalPane: () => () => {}, + onApplyAgentPaneActivity: () => () => {}, onAgentLaunchPaneVerdict: () => () => {}, onLaunchRecipe: () => () => {}, onRequestTerminalTabMount: () => () => {}, diff --git a/src/renderer/src/web/preload-api/web-ui-api.ts b/src/renderer/src/web/preload-api/web-ui-api.ts index 1a8628ee724..5f6b1e2ec31 100644 --- a/src/renderer/src/web/preload-api/web-ui-api.ts +++ b/src/renderer/src/web/preload-api/web-ui-api.ts @@ -250,6 +250,8 @@ export function createWebUiApi(): NonNullable['ui']> { replyAgentLaunchTabPublish: () => {}, onRevealTerminalPane: () => noopUnsubscribe, replyTerminalPaneReveal: () => {}, + onApplyAgentPaneActivity: () => noopUnsubscribe, + replyAgentPaneActivity: () => {}, onSplitTerminal: () => noopUnsubscribe, onRenameTerminal: () => noopUnsubscribe, onSetPaneTitle: () => noopUnsubscribe, diff --git a/src/shared/agent-status/presentation/agent-list-status.ts b/src/shared/agent-status/presentation/agent-list-status.ts new file mode 100644 index 00000000000..dc0d5d8169f --- /dev/null +++ b/src/shared/agent-status/presentation/agent-list-status.ts @@ -0,0 +1,68 @@ +/** A row's status in the desktop Agents list; the renderer's AgentDotState is this union. */ +export type AgentListStatus = + | 'working' + | 'monitoring' + | 'blocked' + | 'waiting' + | 'interrupted' + // Transcript-derived failure is an outcome, distinct from live blocked attention. + | 'failed' + | 'done' + | 'idle' + // A live PTY with stale reporting proves only missing evidence, not idle/work/completion. + | 'unverifiable' + // The turn ended without a proven outcome; use the missing-evidence glyph, never completion. + | 'unconfirmed' + // Sidebar combines blocked/waiting as permission; retain its vocabulary with the shared question glyph/token. + | 'permission' + +// Use exhaustive, unique attention ranks so new states fail typecheck and recency cannot reorder headers. +export const AGENT_LIST_STATUS_RANK: Record = { + waiting: 0, + blocked: 1, + permission: 2, + failed: 3, + unconfirmed: 4, + working: 5, + monitoring: 6, + // A user's Stop is not news, so it follows live work, but it is not a finish either. + interrupted: 7, + unverifiable: 8, + done: 9, + idle: 10 +} + +/** How the desktop Agents list shows one agent pane; unlisted panes are not in the list at all. */ +export type AgentListVerdict = + | { listed: false } + | { + listed: true + status: AgentListStatus + unread: boolean + clearable: boolean + /** The row's recency, newest first within a status. */ + sortAt: number + title: string + /** The coordinator this worker nests under. */ + childOf?: string + /** A finished worker the list hides while child agents are hidden. */ + foldedChild?: true + } + +/** The desktop window's verdicts by pane key, as of `publishedAt`. */ +export type AgentListPublication = { + publishedAt: number + verdicts: Record +} + +/** A paired client's Agents-list change; the desktop window applies it with its own Activity actions. */ +export type AgentPaneActivityChange = { + kind: 'read' | 'unread' | 'clear' + paneKeys: string[] +} + +export type AgentPaneActivityRequest = AgentPaneActivityChange & { requestId: string } + +export type AgentPaneActivityReply = + | { requestId: string; publication: AgentListPublication } + | { requestId: string; error: string } diff --git a/src/shared/host-operation-ownership.ts b/src/shared/host-operation-ownership.ts index 0b6067e2ff8..a73a6b77a91 100644 --- a/src/shared/host-operation-ownership.ts +++ b/src/shared/host-operation-ownership.ts @@ -13,6 +13,7 @@ export type HostOperationOwnership = 'host' | 'credential' | 'client' | 'stream' export const HOST_OPERATION_OWNERSHIP = { accounts: 'host', agent: 'host', + agentActivity: 'host', agentHooks: 'host', agentSession: 'host', agentSessionAttachment: 'host', diff --git a/src/shared/rpc-contract/agent-activity-params.ts b/src/shared/rpc-contract/agent-activity-params.ts new file mode 100644 index 00000000000..b84f73940e5 --- /dev/null +++ b/src/shared/rpc-contract/agent-activity-params.ts @@ -0,0 +1,11 @@ +import { z } from 'zod' + +// Bounded like a worktree.ps page of agent rows; pane keys are `${tabId}:${leafUuid}`. +const AgentActivityPaneKeys = z.array(z.string().min(1).max(512)).min(1).max(500) + +export const AgentActivitySetReadParams = z.object({ + paneKeys: AgentActivityPaneKeys, + read: z.boolean() +}) + +export const AgentActivityClearParams = z.object({ paneKeys: AgentActivityPaneKeys }) diff --git a/src/shared/rpc-contract/rpc-params-catalog.generated.ts b/src/shared/rpc-contract/rpc-params-catalog.generated.ts index d2d44a18829..761f3ca6eb2 100644 --- a/src/shared/rpc-contract/rpc-params-catalog.generated.ts +++ b/src/shared/rpc-contract/rpc-params-catalog.generated.ts @@ -68,6 +68,7 @@ import { SelectCodexAccountForTargetParams, SelectDataAccountParams } from './accounts-params' +import { AgentActivityClearParams, AgentActivitySetReadParams } from './agent-activity-params' import { PrepareCodexForWslPaneParams } from './agent-hooks-params' import { AgentLaunch, AgentLaunchReplay } from './agent-launch-params' import { AgentLaunchSettingsMutation } from './agent-launch-settings-params' @@ -808,6 +809,8 @@ export const RPC_PARAMS_BY_METHOD = { 'accounts.zcodePlanSaveApiKey': UsageCredentialApiKeyParams, 'agent.launch': AgentLaunch, 'agent.launchReplay': AgentLaunchReplay, + 'agentActivity.clear': AgentActivityClearParams, + 'agentActivity.setRead': AgentActivitySetReadParams, 'agentHooks.prepareCodexForWslPane': PrepareCodexForWslPaneParams, 'agentSession.accountUsage': OptionsParams, 'agentSession.acknowledgeAttention': AcknowledgeAttentionParams, diff --git a/src/shared/runtime-client-events.ts b/src/shared/runtime-client-events.ts index 0c03f46106d..47e0f41508e 100644 --- a/src/shared/runtime-client-events.ts +++ b/src/shared/runtime-client-events.ts @@ -27,6 +27,8 @@ export type RuntimeClientEvent = | { type: 'gitStatusChanged'; repoId: string; worktreeIds?: string[] } /** Top-level settings whose values changed; a phone re-reads only the settings it shows. */ | { type: 'settingsChanged'; keys: string[] } + /** The desktop Agents list's verdicts changed; worktree.ps carries them. */ + | { type: 'agentListChanged' } | { type: 'worktreesChanged' repoId: string diff --git a/src/shared/runtime-worktree-contracts.ts b/src/shared/runtime-worktree-contracts.ts index 51a7d488806..ca10376ceb8 100644 --- a/src/shared/runtime-worktree-contracts.ts +++ b/src/shared/runtime-worktree-contracts.ts @@ -6,6 +6,7 @@ import type { } from './agent-status/contracts/agent-status-types' import type { AgentMainAgentStatus } from './agent-status/lifecycle/main-agent-status' import type { ProgramStatusFacet } from './program-status/facet' +import type { AgentListVerdict } from './agent-status/presentation/agent-list-status' import type { CheckStatus, ProviderCheckSummary } from './github/pull-request-types' import type { AgentChildWorkView } from './agent-status/child-work/agent-status-child-work-view' import type { AgentSubagentSnapshot } from './agent-status/contracts/agent-status-subagent-snapshot' @@ -63,6 +64,8 @@ export type RuntimeWorktreeAgentRow = { hasLivePty?: true /** The program's own OSC 7501 report; never decides `state`. Optional: old hosts never send it. */ programStatus?: ProgramStatusFacet + /** How the desktop Agents list shows this agent. Omitted with no desktop window, by old hosts, and for a turn newer than the window's last verdicts. */ + activity?: AgentListVerdict } export type RuntimeWorktreePsSummary = {