diff --git a/agent-dashboard-mocks/RESEARCH.md b/agent-dashboard-mocks/RESEARCH.md new file mode 100644 index 000000000..da546889c --- /dev/null +++ b/agent-dashboard-mocks/RESEARCH.md @@ -0,0 +1,33 @@ +# How people like to see all their agents at once — research + how it shaped the mocks + +Grounded in shipping tools (Warp Agent Panel, herdr, Claude Code Agent View, Claude Squad, uzi, Conductor/Crystal, Vibe Kanban, k9s/Lens, Datadog Host Map, Buildkite, pm2/btop) and notification/triage UX literature. This drives `index.html`. + +## The core finding +**"Waiting for input" is the whole reason this view exists.** Everything else is ambient. Every serious tool makes the needs-a-human state the loudest thing on screen and lets you resolve it without a full context switch (Warp "jump to pane", Claude Agent View "reply without attaching"). Practical parallelism tops out around **4–8 agents** (occasionally ~30), so the default should optimize glanceability for a handful, with a density fallback for many. + +## Design principles applied to the mocks +1. **Waiting-for-input is loudest.** Amber + gentle pulse, top-of-sort priority, an always-visible aggregate ("2 need you"), a one-line *reason label*, and inline **Answer**/**Open** actions. → the **Needs you** inbox is the purest form; every other view surfaces it too. +2. **State is the primary channel, encoded redundantly.** Color + icon + text label (never color alone — accessibility). Colors map to Orca's `main.css` tokens (success green, destructive red) with a mock-local amber/blue for waiting/working. +3. **Motion = "needs you or is changing," never decoration.** Only *working* (subtle) and *waiting* (pulse) animate; done/idle/error are static. Respects `prefers-reduced-motion`. +4. **Density adapts to count.** Cards (≤8) → table (8–20) → tiles/grid (20+). The switcher lets you feel each. +5. **Group by project with roll-up, but let urgency flatten it.** Gallery/tree group by repo; the inbox is the flat, urgency-sorted triage view. +6. **Per-agent info priority:** state → reason (when blocked) → what it's working on → last activity → elapsed → provider badge → branch. Shown progressively (1–4 always, 5–7 on hover/detail). +7. **Live preview on hover, dots at rest.** Don't mount 30 live xterms (perf) — rest = status; **hover → terminal tail popover** with a jump-in affordance. This is the shared popover in every variant. +8. **Notify on transitions, tiered.** waiting/error = interruptive (toast + unread badge, and Orca's mobile push); done = ambient; working/idle = silent. + +## The seven variants ↔ research concepts +| Variant | Maps to | Best for | +|---|---|---| +| **Repo › worktree › agent** (nested, default) | herdr state roll-up; k9s XRay tree; your own idea | Mirrors Orca's real hierarchy; roll-up dot on each repo/worktree tells you if anything inside needs you; agents sorted by urgency | +| **Needs you** (inbox) | Inbox-zero triage; Warp attention state | Any count — the "just tell me what needs me" view | +| **Card gallery** (default) | Conductor/Lens cards + progressive disclosure | Typical 5–12 — best glanceability/info balance | +| **Kanban board** | Vibe Kanban (columns = state) | 8–15; managing rather than co-coding | +| **Mission control** (table) | uzi `ls -w`, k9s | 15–30; terminal-native power users | +| **Terminal wall** (mosaic) | tmux wall, Claude Squad panes | 2–6; comparison runs / ambient monitor | +| **Tree + focus** (master-detail) | k9s XRay tree, Conductor, herdr roll-up | Supervise + dive-in; strong general default | +| **Radial map** | Datadog Host Map / your original concentric dashboard | Stretch/overview concept; homage to the movable-UI branch | + +**Recommendation from the research:** ship **Card gallery** as default + **Tree + focus** as the working surface, with **Needs you** as a one-key filter and **Mission control** as the "I have 25 agents" density toggle. Wall/radial are focus/overview modes. + +## Sources +Warp [managing-agents](https://docs.warp.dev/agents/using-agents/managing-agents) · herdr [github](https://github.com/ogulcancelik/herdr), [docs](https://herdr.dev/docs/agents/) · Claude Code [agent-teams](https://code.claude.com/docs/en/agent-teams), [Agent View cockpit](https://www.contextstudios.ai/blog/claude-code-agent-view-multi-agent-cockpit) · Claude Squad [github](https://github.com/smtg-ai/claude-squad) · uzi [github](https://github.com/devflowinc/uzi) · Conductor [docs](https://www.conductor.build/docs/guides/parallel-agents/run-multiple-claude-code-sessions) · Vibe Kanban [github](https://github.com/BloopAI/vibe-kanban) · k9s [site](https://k9scli.io/), [palark](https://palark.com/blog/k9s-the-powerful-terminal-ui-for-kubernetes/) · Datadog [host map](https://docs.datadoghq.com/dashboards/widgets/hostmap/), [widget colors](https://docs.datadoghq.com/dashboards/guide/widget_colors/) · Buildkite [dashboard](https://buildkite.com/docs/pipelines/dashboard-walkthrough) · pm2/btop [monitoring](https://pm2.keymetrics.io/docs/usage/monitoring/) · Triage UX [Smart Interface Design Patterns](https://smart-interface-design-patterns.com/articles/notifications/), [Missive inbox zero](https://missiveapp.com/blog/inbox-zero) diff --git a/agent-dashboard-mocks/index.html b/agent-dashboard-mocks/index.html new file mode 100644 index 000000000..b0d95b6d2 --- /dev/null +++ b/agent-dashboard-mocks/index.html @@ -0,0 +1,788 @@ + + + + + +Orca · Agent Dashboard — UI explorations + + + +
+
OrcaAgents
+
+
+ +
+ +
+
+ Eight ways to see every agent across all your worktrees at once. Hover any agent to peek its live terminal + in a popover (move into the popover to interact). Layout switcher is top-right; ◐ toggles light/dark. +
+ +
+ + + + + + + diff --git a/electron.vite.config.ts b/electron.vite.config.ts index 7733aa0e5..956349c70 100644 --- a/electron.vite.config.ts +++ b/electron.vite.config.ts @@ -239,6 +239,19 @@ export default defineConfig({ plugins: [react(), tailwindcss()], worker: { format: 'es' + }, + build: { + // Why: the pop-out dashboard is a second top-level window with its own + // React root. It gets its own HTML entry so it can boot independently of + // the main window while reusing the same preload/window.api. `index` must + // stay listed — overriding input otherwise drops electron-vite's default + // renderer entry. + rollupOptions: { + input: { + index: resolve('src/renderer/index.html'), + popout: resolve('src/renderer/popout.html') + } + } } } }) diff --git a/src/main/ipc/crash-reporting.ts b/src/main/ipc/crash-reporting.ts index 89b88537e..7ced0354e 100644 --- a/src/main/ipc/crash-reporting.ts +++ b/src/main/ipc/crash-reporting.ts @@ -53,7 +53,8 @@ const REACT_ERROR_BOUNDARY_SURFACES = new Set { + it('accepts a complete dashboard snapshot', () => { + expect(isDashboardSnapshot(SNAPSHOT)).toBe(true) + }) + + it('rejects malformed or unbounded snapshot fields', () => { + expect(isDashboardSnapshot({ ...SNAPSHOT, generatedAt: Number.NaN })).toBe(false) + expect( + isDashboardSnapshot({ + ...SNAPSHOT, + cards: [{ ...SNAPSHOT.cards[0], bucket: 'unexpected' }] + }) + ).toBe(false) + expect( + isDashboardSnapshot({ + ...SNAPSHOT, + cards: [{ ...SNAPSHOT.cards[0], lastAgentMessage: 'x'.repeat(8_001) }] + }) + ).toBe(false) + }) + + it('requires complete bounded reveal routing', () => { + expect( + isDashboardRevealAgentArgs({ + repoId: 'repo-1', + worktreeId: 'worktree-1', + tabId: 'tab-1', + leafId: null + }) + ).toBe(true) + expect( + isDashboardRevealAgentArgs({ repoId: 'repo-1', worktreeId: 'worktree-1', tabId: '' }) + ).toBe(false) + }) +}) diff --git a/src/main/ipc/dashboard-payload-validation.ts b/src/main/ipc/dashboard-payload-validation.ts new file mode 100644 index 000000000..a729db97f --- /dev/null +++ b/src/main/ipc/dashboard-payload-validation.ts @@ -0,0 +1,84 @@ +import type { DashboardRevealAgentArgs, DashboardSnapshot } from '../../shared/dashboard-snapshot' +import { + AGENT_STATUS_ASSISTANT_MESSAGE_MAX_LENGTH, + AGENT_STATUS_INTERACTIVE_PROMPT_MAX_LENGTH, + AGENT_STATUS_MAX_FIELD_LENGTH, + AGENT_TYPE_MAX_LENGTH +} from '../../shared/agent-status-types' + +const MAX_DASHBOARD_CARDS = 1_000 +const MAX_ID_LENGTH = 4_096 +const MAX_LABEL_LENGTH = 1_024 +const DASHBOARD_BUCKETS = new Set(['attention', 'working', 'idle']) +const DASHBOARD_DOT_STATES = new Set(['working', 'blocked', 'waiting', 'done', 'idle']) + +function isBoundedString(value: unknown, maxLength: number, allowEmpty = false): value is string { + return typeof value === 'string' && value.length <= maxLength && (allowEmpty || value.length > 0) +} + +function isOptionalBoundedString(value: unknown, maxLength: number): boolean { + return value === undefined || isBoundedString(value, maxLength, true) +} + +function isFiniteNumber(value: unknown): value is number { + return typeof value === 'number' && Number.isFinite(value) +} + +export function isDashboardRevealAgentArgs(value: unknown): value is DashboardRevealAgentArgs { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return false + } + const args = value as Record + return ( + isBoundedString(args.repoId, MAX_ID_LENGTH) && + isBoundedString(args.worktreeId, MAX_ID_LENGTH) && + isBoundedString(args.tabId, MAX_ID_LENGTH) && + (args.leafId === null || isBoundedString(args.leafId, MAX_ID_LENGTH)) + ) +} + +export function isDashboardPaneKey(value: unknown): value is string { + return isBoundedString(value, MAX_ID_LENGTH) +} + +export function isDashboardSnapshot(value: unknown): value is DashboardSnapshot { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return false + } + const snapshot = value as Record + return ( + isFiniteNumber(snapshot.generatedAt) && + Array.isArray(snapshot.cards) && + snapshot.cards.length <= MAX_DASHBOARD_CARDS && + snapshot.cards.every(isDashboardCard) + ) +} + +function isDashboardCard(value: unknown): boolean { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return false + } + const card = value as Record + return ( + isBoundedString(card.paneKey, MAX_ID_LENGTH) && + (card.ptyId === null || isBoundedString(card.ptyId, MAX_ID_LENGTH)) && + isBoundedString(card.agentType, AGENT_TYPE_MAX_LENGTH) && + typeof card.bucket === 'string' && + DASHBOARD_BUCKETS.has(card.bucket) && + typeof card.dotState === 'string' && + DASHBOARD_DOT_STATES.has(card.dotState) && + isBoundedString(card.task, AGENT_STATUS_MAX_FIELD_LENGTH, true) && + isOptionalBoundedString(card.lastUserMessage, AGENT_STATUS_MAX_FIELD_LENGTH) && + isOptionalBoundedString(card.lastAgentMessage, AGENT_STATUS_ASSISTANT_MESSAGE_MAX_LENGTH) && + isBoundedString(card.repoId, MAX_ID_LENGTH) && + isBoundedString(card.worktreeId, MAX_ID_LENGTH) && + isBoundedString(card.tabId, MAX_ID_LENGTH) && + (card.leafId === null || isBoundedString(card.leafId, MAX_ID_LENGTH)) && + isBoundedString(card.repoName, MAX_LABEL_LENGTH, true) && + isBoundedString(card.worktreeName, MAX_LABEL_LENGTH, true) && + isFiniteNumber(card.startedAt) && + isFiniteNumber(card.stateChangedAt) && + typeof card.unseen === 'boolean' && + isOptionalBoundedString(card.askSummary, AGENT_STATUS_INTERACTIVE_PROMPT_MAX_LENGTH) + ) +} diff --git a/src/main/ipc/dashboard-popout.test.ts b/src/main/ipc/dashboard-popout.test.ts new file mode 100644 index 000000000..c14b8b3c1 --- /dev/null +++ b/src/main/ipc/dashboard-popout.test.ts @@ -0,0 +1,183 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { + handlers, + ipcMainMock, + appMock, + createPopoutMock, + closePopoutMock, + getPopoutMock, + isPopoutRendererMock, + isTrustedUIRendererMock, + getTrustedWindowMock, + sendToTrustedMock, + safelyRevealMock +} = vi.hoisted(() => { + const map = new Map unknown>() + return { + handlers: map, + ipcMainMock: { + removeHandler: vi.fn(), + handle: (channel: string, fn: (...args: unknown[]) => unknown) => map.set(channel, fn) + }, + appMock: { focus: vi.fn() }, + createPopoutMock: vi.fn(), + closePopoutMock: vi.fn(), + getPopoutMock: vi.fn((): unknown => null), + isPopoutRendererMock: vi.fn((_sender: unknown) => false), + isTrustedUIRendererMock: vi.fn((_sender: unknown) => false), + getTrustedWindowMock: vi.fn((): unknown => null), + sendToTrustedMock: vi.fn(), + safelyRevealMock: vi.fn() + } +}) + +vi.mock('electron', () => ({ app: appMock, ipcMain: ipcMainMock })) +vi.mock('../window/dashboard-popout-window', () => ({ + createOrFocusDashboardPopout: createPopoutMock, + closeDashboardPopout: closePopoutMock, + getDashboardPopoutWindow: getPopoutMock, + isDashboardPopoutRenderer: isPopoutRendererMock, + onDashboardPopoutOpenChanged: vi.fn() +})) +vi.mock('../window/focus-existing-window', () => ({ safelyRevealWindow: safelyRevealMock })) +vi.mock('./ui', () => ({ + getTrustedUIRendererWindow: getTrustedWindowMock, + isTrustedUIRenderer: isTrustedUIRendererMock, + sendToTrustedUIRenderer: sendToTrustedMock +})) + +import { registerDashboardPopoutHandlers } from './dashboard-popout' + +const mainSender = { id: 1, send: vi.fn() } +const popoutSender = { id: 2, send: vi.fn() } +const untrustedSender = { id: 3, send: vi.fn() } +const SNAPSHOT = { generatedAt: 1, cards: [] } + +function makeWindow(sender: typeof mainSender) { + return { + isDestroyed: () => false, + webContents: sender + } +} + +function makeStore(enabled = true) { + let settingsListener: + | ((updates: Record, settings: Record) => void) + | null = null + return { + getSettings: vi.fn(() => ({ experimentalAgentDashboardPopout: enabled })), + onSettingsChanged: vi.fn((listener) => { + settingsListener = listener + return vi.fn() + }), + fireSettingsChanged: (nextEnabled: boolean) => + settingsListener?.( + { experimentalAgentDashboardPopout: nextEnabled }, + { experimentalAgentDashboardPopout: nextEnabled } + ) + } +} + +describe('registerDashboardPopoutHandlers', () => { + let store: ReturnType + + beforeEach(() => { + handlers.clear() + store = makeStore() + isTrustedUIRendererMock.mockImplementation((sender) => sender === mainSender) + isPopoutRendererMock.mockImplementation((sender) => sender === popoutSender) + registerDashboardPopoutHandlers(store as never) + }) + + afterEach(() => { + vi.clearAllMocks() + getPopoutMock.mockReturnValue(null) + getTrustedWindowMock.mockReturnValue(null) + }) + + it('opens only for the trusted main renderer while the feature is enabled', () => { + handlers.get('dashboardPopout:open')!({ sender: untrustedSender } as never) + expect(createPopoutMock).not.toHaveBeenCalled() + + store.getSettings.mockReturnValue({ experimentalAgentDashboardPopout: false }) + handlers.get('dashboardPopout:open')!({ sender: mainSender } as never) + expect(createPopoutMock).not.toHaveBeenCalled() + + store.getSettings.mockReturnValue({ experimentalAgentDashboardPopout: true }) + handlers.get('dashboardPopout:open')!({ sender: mainSender } as never) + expect(createPopoutMock).toHaveBeenCalledWith(store) + }) + + it('auto-closes the popout when the feature is disabled', () => { + store.fireSettingsChanged(false) + expect(closePopoutMock).toHaveBeenCalledOnce() + }) + + it('caches and forwards only valid trusted snapshots', () => { + const popout = makeWindow(popoutSender) + getPopoutMock.mockReturnValue(popout) + + handlers.get('dashboard:publishSnapshot')!({ sender: untrustedSender } as never, SNAPSHOT) + handlers.get('dashboard:publishSnapshot')!({ sender: mainSender } as never, { + generatedAt: Number.NaN, + cards: [] + }) + expect(popoutSender.send).not.toHaveBeenCalled() + + handlers.get('dashboard:publishSnapshot')!({ sender: mainSender } as never, SNAPSHOT) + expect(popoutSender.send).toHaveBeenCalledWith('dashboard:snapshot', SNAPSHOT) + }) + + it('replays the cached snapshot only to the popout and nudges only the trusted main renderer', () => { + const popout = makeWindow(popoutSender) + getPopoutMock.mockReturnValue(popout) + handlers.get('dashboard:publishSnapshot')!({ sender: mainSender } as never, SNAPSHOT) + + handlers.get('dashboard:requestSnapshot')!({ sender: untrustedSender } as never) + expect(untrustedSender.send).not.toHaveBeenCalled() + + handlers.get('dashboard:requestSnapshot')!({ sender: popoutSender } as never) + expect(popoutSender.send).toHaveBeenCalledWith('dashboard:snapshot', SNAPSHOT) + expect(sendToTrustedMock).toHaveBeenCalledWith('dashboard:snapshotRequested', null) + }) + + it('reports open state only to the trusted main renderer', () => { + getPopoutMock.mockReturnValue(makeWindow(popoutSender)) + expect(handlers.get('dashboard:getPopoutOpen')!({ sender: untrustedSender } as never)).toBe( + false + ) + expect(handlers.get('dashboard:getPopoutOpen')!({ sender: mainSender } as never)).toBe(true) + }) + + it('relays valid seen acknowledgements from only the popout', () => { + handlers.get('dashboardPopout:ackAgent')!({ sender: untrustedSender } as never, { + paneKey: 'tab1:leaf1' + }) + handlers.get('dashboardPopout:ackAgent')!({ sender: popoutSender } as never, { paneKey: '' }) + expect(sendToTrustedMock).not.toHaveBeenCalled() + + handlers.get('dashboardPopout:ackAgent')!({ sender: popoutSender } as never, { + paneKey: 'tab1:leaf1' + }) + expect(sendToTrustedMock).toHaveBeenCalledWith('ui:ackDashboardAgent', 'tab1:leaf1') + }) + + it('reveals an agent in only the trusted main window', () => { + const main = makeWindow(mainSender) + getTrustedWindowMock.mockReturnValue(main) + const args = { repoId: 'r1', worktreeId: 'w1', tabId: 't1', leafId: 'l1' } + + handlers.get('dashboardPopout:revealAgent')!({ sender: untrustedSender } as never, args) + handlers.get('dashboardPopout:revealAgent')!({ sender: popoutSender } as never, { + ...args, + tabId: '' + }) + expect(safelyRevealMock).not.toHaveBeenCalled() + + handlers.get('dashboardPopout:revealAgent')!({ sender: popoutSender } as never, args) + expect(safelyRevealMock).toHaveBeenCalledWith(main) + expect(mainSender.send).toHaveBeenCalledWith('ui:revealDashboardAgent', args) + expect(appMock.focus).toHaveBeenCalledOnce() + }) +}) diff --git a/src/main/ipc/dashboard-popout.ts b/src/main/ipc/dashboard-popout.ts new file mode 100644 index 000000000..95e602ad1 --- /dev/null +++ b/src/main/ipc/dashboard-popout.ts @@ -0,0 +1,125 @@ +import { app, ipcMain } from 'electron' +import type { Store } from '../persistence' +import type { DashboardSnapshot } from '../../shared/dashboard-snapshot' +import { + createOrFocusDashboardPopout, + closeDashboardPopout, + getDashboardPopoutWindow, + isDashboardPopoutRenderer, + onDashboardPopoutOpenChanged +} from '../window/dashboard-popout-window' +import { safelyRevealWindow } from '../window/focus-existing-window' +import { getTrustedUIRendererWindow, isTrustedUIRenderer, sendToTrustedUIRenderer } from './ui' +import { + isDashboardPaneKey, + isDashboardRevealAgentArgs, + isDashboardSnapshot +} from './dashboard-payload-validation' + +// The most recent snapshot the main renderer published, replayed to the popout +// the instant it mounts so the board paints without waiting for the next tick. +// Cleared on close so a reopened popout never flashes a previous session. +let lastSnapshot: DashboardSnapshot | null = null + +function isDashboardEnabled(store: Store): boolean { + return store.getSettings().experimentalAgentDashboardPopout === true +} + +export function registerDashboardPopoutHandlers(store: Store): void { + ipcMain.removeHandler('dashboardPopout:open') + ipcMain.removeHandler('dashboard:publishSnapshot') + ipcMain.removeHandler('dashboard:requestSnapshot') + ipcMain.removeHandler('dashboard:getPopoutOpen') + ipcMain.removeHandler('dashboardPopout:revealAgent') + ipcMain.removeHandler('dashboardPopout:ackAgent') + + onDashboardPopoutOpenChanged((open) => { + if (!open) { + lastSnapshot = null + } + }) + store.onSettingsChanged((updates, settings) => { + if ( + 'experimentalAgentDashboardPopout' in updates && + settings.experimentalAgentDashboardPopout !== true + ) { + lastSnapshot = null + closeDashboardPopout() + } + }) + + ipcMain.handle('dashboardPopout:open', (event): void => { + if (!isTrustedUIRenderer(event.sender) || !isDashboardEnabled(store)) { + return + } + createOrFocusDashboardPopout(store) + }) + + // Relay: the main renderer publishes derived snapshots; forward to the popout. + ipcMain.handle('dashboard:publishSnapshot', (event, snapshot: unknown): void => { + if ( + !isTrustedUIRenderer(event.sender) || + !isDashboardEnabled(store) || + !isDashboardSnapshot(snapshot) + ) { + return + } + lastSnapshot = snapshot + getDashboardPopoutWindow()?.webContents.send('dashboard:snapshot', snapshot) + }) + + // The popout asks for a snapshot on mount: replay the cache immediately, then + // nudge the main renderer to publish a fresh one. + ipcMain.handle('dashboard:requestSnapshot', (event): void => { + if (!isDashboardPopoutRenderer(event.sender) || !isDashboardEnabled(store)) { + return + } + if (lastSnapshot) { + event.sender.send('dashboard:snapshot', lastSnapshot) + } + sendToTrustedUIRenderer('dashboard:snapshotRequested', null) + }) + + ipcMain.handle('dashboard:getPopoutOpen', (event): boolean => + isTrustedUIRenderer(event.sender) && isDashboardEnabled(store) + ? getDashboardPopoutWindow() !== null + : false + ) + + // Seen-sync: opening a card's terminal dialog acknowledges the agent in the + // main renderer's store — the same ack that mutes its sidebar row. + ipcMain.handle('dashboardPopout:ackAgent', (event, args: unknown): void => { + if ( + !isDashboardPopoutRenderer(event.sender) || + !isDashboardEnabled(store) || + !args || + typeof args !== 'object' || + !isDashboardPaneKey((args as { paneKey?: unknown }).paneKey) + ) { + return + } + sendToTrustedUIRenderer('ui:ackDashboardAgent', (args as { paneKey: string }).paneKey) + }) + + // Click-to-focus: raise the main window and route it to the agent's pane. + ipcMain.handle('dashboardPopout:revealAgent', (event, args: unknown): void => { + if ( + !isDashboardPopoutRenderer(event.sender) || + !isDashboardEnabled(store) || + !isDashboardRevealAgentArgs(args) + ) { + return + } + const mainWindow = getTrustedUIRendererWindow() + if (!mainWindow) { + return + } + safelyRevealWindow(mainWindow) + mainWindow.webContents.send('ui:revealDashboardAgent', args) + try { + app.focus({ steal: true }) + } catch { + // Best-effort; the per-window focus above may still bring it forward. + } + }) +} diff --git a/src/main/ipc/pty.ts b/src/main/ipc/pty.ts index 0d0b79b6b..573506367 100644 --- a/src/main/ipc/pty.ts +++ b/src/main/ipc/pty.ts @@ -1605,7 +1605,7 @@ export function registerPtyHandlers( const backgroundedDeliverySyncByPty = new Map() function syncPtyBackgroundedDelivery(id: string, caller: string): void { const background = - rendererPtyIsKnownHidden(id) && !(runtime?.hasRemoteTerminalViewSubscriber(id) ?? false) + rendererPtyIsKnownHidden(id) && !(runtime?.hasRawTerminalViewSubscriber?.(id) ?? false) if ((backgroundedDeliverySyncByPty.get(id) ?? false) === background) { return } diff --git a/src/main/ipc/register-core-handlers.test.ts b/src/main/ipc/register-core-handlers.test.ts index bcfedc363..787053b49 100644 --- a/src/main/ipc/register-core-handlers.test.ts +++ b/src/main/ipc/register-core-handlers.test.ts @@ -54,6 +54,8 @@ const { registerHostedReviewHandlersMock, registerExportHandlersMock, registerOnboardingHandlersMock, + registerDashboardPopoutHandlersMock, + registerTerminalPreviewHandlersMock, registerSpeechHandlersMock, registerSkillsHandlersMock, registerWorkspaceSpaceHandlersMock, @@ -116,6 +118,8 @@ const { registerHostedReviewHandlersMock: vi.fn(), registerExportHandlersMock: vi.fn(), registerOnboardingHandlersMock: vi.fn(), + registerDashboardPopoutHandlersMock: vi.fn(), + registerTerminalPreviewHandlersMock: vi.fn(), registerSpeechHandlersMock: vi.fn(), registerSkillsHandlersMock: vi.fn(), registerWorkspaceSpaceHandlersMock: vi.fn(), @@ -144,6 +148,14 @@ vi.mock('./onboarding', () => ({ registerOnboardingHandlers: registerOnboardingHandlersMock })) +vi.mock('./dashboard-popout', () => ({ + registerDashboardPopoutHandlers: registerDashboardPopoutHandlersMock +})) + +vi.mock('./terminal-preview', () => ({ + registerTerminalPreviewHandlers: registerTerminalPreviewHandlersMock +})) + vi.mock('./speech', () => ({ registerSpeechHandlers: registerSpeechHandlersMock })) @@ -417,6 +429,8 @@ describe('registerCoreHandlers', () => { registerGitLabHandlersMock.mockReset() registerHostedReviewHandlersMock.mockReset() registerExportHandlersMock.mockReset() + registerDashboardPopoutHandlersMock.mockReset() + registerTerminalPreviewHandlersMock.mockReset() registerSpeechHandlersMock.mockReset() registerSkillsHandlersMock.mockReset() registerWorkspaceSpaceHandlersMock.mockReset() @@ -493,6 +507,8 @@ describe('registerCoreHandlers', () => { expect(registerNotificationHandlersMock).toHaveBeenCalledWith(store, runtime) expect(registerDeveloperPermissionHandlersMock).toHaveBeenCalled() expect(registerComputerUsePermissionHandlersMock).toHaveBeenCalled() + expect(registerDashboardPopoutHandlersMock).toHaveBeenCalledWith(store) + expect(registerTerminalPreviewHandlersMock).toHaveBeenCalledWith(runtime) expect(registerSettingsHandlersMock).toHaveBeenCalledWith(store, agentAwakeService) expect(registerSkillsHandlersMock).toHaveBeenCalledWith(store) expect(registerWorkspaceSpaceHandlersMock).toHaveBeenCalledWith(store) diff --git a/src/main/ipc/register-core-handlers.ts b/src/main/ipc/register-core-handlers.ts index 9b951a626..ec25e2779 100644 --- a/src/main/ipc/register-core-handlers.ts +++ b/src/main/ipc/register-core-handlers.ts @@ -30,6 +30,8 @@ import { registerNativeChatHandlers } from './native-chat' import { registerNotificationHandlers } from './notifications' import { registerNotebookHandlers } from './notebook' import { registerOnboardingHandlers } from './onboarding' +import { registerDashboardPopoutHandlers } from './dashboard-popout' +import { registerTerminalPreviewHandlers } from './terminal-preview' import { registerDeveloperPermissionHandlers } from './developer-permissions' import { registerComputerUsePermissionHandlers } from './computer-use-permissions' import { setTrustedBrowserRendererWebContentsId, setAgentBrowserBridgeRef } from './browser' @@ -155,6 +157,8 @@ export function registerCoreHandlers( registerNotificationHandlers(store, runtime) registerNotebookHandlers(store) registerOnboardingHandlers(store) + registerDashboardPopoutHandlers(store) + registerTerminalPreviewHandlers(runtime) registerDeveloperPermissionHandlers() // Why: diagnostics handlers are wired alongside telemetry but the two // lanes never share a code path — `ipc/diagnostics.ts` imports only from diff --git a/src/main/ipc/terminal-preview-output-stream.ts b/src/main/ipc/terminal-preview-output-stream.ts new file mode 100644 index 000000000..1eb9699ec --- /dev/null +++ b/src/main/ipc/terminal-preview-output-stream.ts @@ -0,0 +1,238 @@ +import type { WebContents } from 'electron' +import { iterateTerminalInputChunks } from '../../shared/terminal-input' +import type { TerminalPreviewDataPayload } from '../../shared/terminal-preview' + +const OUTPUT_BATCH_MS = 5 +export const TERMINAL_PREVIEW_OUTPUT_BATCH_MAX_BYTES = 64 * 1024 +const OUTPUT_IN_FLIGHT_MAX_BYTES = 512 * 1024 +const OUTPUT_PENDING_MAX_BYTES = 256 * 1024 +const INITIAL_PENDING_MAX_BYTES = 256 * 1024 + +export type TerminalPreviewOutputMeta = { + seq?: number + rawLength?: number + transformed?: boolean +} + +type PendingOutput = { data: string; bytes: number; meta?: TerminalPreviewOutputMeta } + +function outputAfterSnapshotSeq(output: PendingOutput, snapshotSeq?: number): string | null { + if ( + typeof snapshotSeq !== 'number' || + typeof output.meta?.seq !== 'number' || + typeof output.meta.rawLength !== 'number' + ) { + return output.data + } + if (output.meta.seq <= snapshotSeq) { + return null + } + const startSeq = output.meta.seq - output.meta.rawLength + if (startSeq >= snapshotSeq || output.meta.transformed === true) { + return output.data + } + return output.data.slice(snapshotSeq - startSeq) +} + +/** Owns one preview's bounded snapshot/live output queue and acknowledgements. */ +export class TerminalPreviewOutputStream { + private bufferingSnapshot = true + private initialPending: PendingOutput[] = [] + private initialPendingBytes = 0 + private initialPendingOverflowed = false + private batchChunks: string[] = [] + private batchBytes = 0 + private batchTimer: ReturnType | null = null + private inFlightBytes = 0 + private pendingBatches: { data: string; bytes: number }[] = [] + private pendingBatchBytes = 0 + private resyncPending = false + private awaitingReconnect = false + private unsubscribeData: () => void = () => {} + private isDisposed = false + + constructor( + readonly contents: WebContents, + readonly ptyId: string, + private readonly releaseRawView: () => void, + private readonly onDispose: (stream: TerminalPreviewOutputStream) => void + ) {} + + get disposed(): boolean { + return this.isDisposed + } + + setDataSubscription(unsubscribe: () => void): void { + this.unsubscribeData = unsubscribe + } + + dispose(): void { + if (this.isDisposed) { + return + } + this.isDisposed = true + if (this.batchTimer) { + clearTimeout(this.batchTimer) + this.batchTimer = null + } + this.unsubscribeData() + this.releaseRawView() + this.onDispose(this) + } + + append(data: string, meta?: TerminalPreviewOutputMeta): void { + if (this.bufferingSnapshot) { + this.appendInitial(data, meta) + } else { + this.appendLive(data) + } + } + + consumeInitialOverflow(): boolean { + if (!this.initialPendingOverflowed) { + return false + } + this.initialPending = [] + this.initialPendingBytes = 0 + this.initialPendingOverflowed = false + return true + } + + completeSnapshot(snapshotSeq?: number): string[] { + const replay = this.initialPending.flatMap((output) => { + const uncovered = outputAfterSnapshotSeq(output, snapshotSeq) + return uncovered ? [uncovered] : [] + }) + this.initialPending = [] + this.initialPendingBytes = 0 + this.bufferingSnapshot = false + return replay + } + + pauseForReconnect(): void { + if (this.batchTimer) { + clearTimeout(this.batchTimer) + this.batchTimer = null + } + this.batchChunks = [] + this.batchBytes = 0 + this.pendingBatches = [] + this.pendingBatchBytes = 0 + this.awaitingReconnect = true + } + + acknowledge(bytes: number): void { + this.inFlightBytes = Math.max( + 0, + this.inFlightBytes - Math.min(this.inFlightBytes, Math.floor(bytes)) + ) + this.maybeDrain() + } + + private send(payload: TerminalPreviewDataPayload): boolean { + if (this.isDisposed || this.contents.isDestroyed()) { + this.dispose() + return false + } + try { + this.contents.send('terminalPreview:data', payload) + return true + } catch { + this.dispose() + return false + } + } + + private maybeDrain(): void { + if (this.isDisposed || this.awaitingReconnect) { + return + } + if (this.resyncPending) { + if (this.inFlightBytes === 0) { + this.resyncPending = false + this.awaitingReconnect = true + this.send({ type: 'resync', ptyId: this.ptyId }) + } + return + } + while (this.pendingBatches.length > 0) { + const next = this.pendingBatches[0]! + if (this.inFlightBytes > 0 && this.inFlightBytes + next.bytes > OUTPUT_IN_FLIGHT_MAX_BYTES) { + break + } + this.pendingBatches.shift() + this.pendingBatchBytes -= next.bytes + if (this.send({ type: 'data', ptyId: this.ptyId, data: next.data, bytes: next.bytes })) { + this.inFlightBytes += next.bytes + } + } + } + + private queueBatch(data: string, bytes: number): void { + if (this.isDisposed || this.awaitingReconnect || this.resyncPending) { + return + } + if ( + this.pendingBatches.length === 0 && + (this.inFlightBytes === 0 || this.inFlightBytes + bytes <= OUTPUT_IN_FLIGHT_MAX_BYTES) + ) { + if (this.send({ type: 'data', ptyId: this.ptyId, data, bytes })) { + this.inFlightBytes += bytes + } + return + } + this.pendingBatches.push({ data, bytes }) + this.pendingBatchBytes += bytes + if (this.pendingBatchBytes > OUTPUT_PENDING_MAX_BYTES) { + // Why: a stuck renderer heals from a fresh authoritative snapshot instead of retaining output without bound. + this.pendingBatches = [] + this.pendingBatchBytes = 0 + this.resyncPending = true + } + } + + private flushBatch(): void { + if (this.batchTimer) { + clearTimeout(this.batchTimer) + this.batchTimer = null + } + if (this.batchChunks.length === 0) { + return + } + const data = this.batchChunks.length === 1 ? this.batchChunks[0]! : this.batchChunks.join('') + const bytes = this.batchBytes + this.batchChunks = [] + this.batchBytes = 0 + this.queueBatch(data, bytes) + } + + private appendLive(data: string): void { + for (const chunk of iterateTerminalInputChunks(data, TERMINAL_PREVIEW_OUTPUT_BATCH_MAX_BYTES)) { + const bytes = Buffer.byteLength(chunk, 'utf8') + if ( + this.batchBytes > 0 && + this.batchBytes + bytes > TERMINAL_PREVIEW_OUTPUT_BATCH_MAX_BYTES + ) { + this.flushBatch() + } + this.batchChunks.push(chunk) + this.batchBytes += bytes + if (this.batchBytes >= TERMINAL_PREVIEW_OUTPUT_BATCH_MAX_BYTES) { + this.flushBatch() + } else if (!this.batchTimer) { + this.batchTimer = setTimeout(() => this.flushBatch(), OUTPUT_BATCH_MS) + this.batchTimer.unref?.() + } + } + } + + private appendInitial(data: string, meta?: TerminalPreviewOutputMeta): void { + const bytes = Buffer.byteLength(data, 'utf8') + this.initialPending.push({ data, bytes, meta }) + this.initialPendingBytes += bytes + while (this.initialPendingBytes > INITIAL_PENDING_MAX_BYTES && this.initialPending.length > 0) { + this.initialPendingBytes -= this.initialPending.shift()!.bytes + this.initialPendingOverflowed = true + } + } +} diff --git a/src/main/ipc/terminal-preview.test.ts b/src/main/ipc/terminal-preview.test.ts new file mode 100644 index 000000000..cb5cf50d6 --- /dev/null +++ b/src/main/ipc/terminal-preview.test.ts @@ -0,0 +1,293 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { handlers, ipcMainMock, isDashboardPopoutRendererMock } = vi.hoisted(() => { + const map = new Map unknown>() + return { + handlers: map, + ipcMainMock: { + removeHandler: vi.fn(), + handle: (channel: string, fn: (...args: unknown[]) => unknown) => map.set(channel, fn) + }, + isDashboardPopoutRendererMock: vi.fn(() => true) + } +}) + +vi.mock('electron', () => ({ ipcMain: ipcMainMock })) +vi.mock('../window/dashboard-popout-window', () => ({ + isDashboardPopoutRenderer: isDashboardPopoutRendererMock +})) + +import { registerTerminalPreviewHandlers } from './terminal-preview' + +type OutputMeta = { seq?: number; rawLength?: number; transformed?: boolean } +type Listener = (data: string, meta?: OutputMeta) => void + +function makeRuntime() { + const listeners: Listener[] = [] + const unsubscribe = vi.fn() + const releaseRawView = vi.fn() + return { + listeners, + unsubscribe, + releaseRawView, + serializeTerminalBuffer: vi.fn( + async (): Promise<{ data: string; cols: number; rows: number; seq: number } | null> => ({ + data: 'screen', + cols: 80, + rows: 20, + seq: 5 + }) + ), + subscribeToTerminalData: vi.fn((_ptyId: string, listener: Listener) => { + listeners.push(listener) + return unsubscribe + }), + registerRawTerminalViewSubscriber: vi.fn(() => releaseRawView), + writeTerminalPreviewInput: vi.fn(async () => true) + } +} + +function makeSender(id = 1) { + const destroyedListeners: (() => void)[] = [] + return { + id, + isDestroyed: () => false, + send: vi.fn(), + once: (event: string, cb: () => void) => { + if (event === 'destroyed') { + destroyedListeners.push(cb) + } + }, + fireDestroyed: () => destroyedListeners.forEach((cb) => cb()) + } +} + +function eventFor(sender: ReturnType) { + return { sender } as never +} + +describe('registerTerminalPreviewHandlers', () => { + beforeEach(() => { + handlers.clear() + isDashboardPopoutRendererMock.mockReturnValue(true) + }) + afterEach(() => { + vi.clearAllMocks() + vi.useRealTimers() + }) + + it('subscribes before snapshot acquisition and replays only bytes after its sequence', async () => { + const runtime = makeRuntime() + let resolveSnapshot!: (snapshot: { + data: string + cols: number + rows: number + seq: number + }) => void + runtime.serializeTerminalBuffer.mockImplementationOnce( + () => + new Promise((resolve) => { + resolveSnapshot = resolve + }) + ) + registerTerminalPreviewHandlers(runtime as never) + const sender = makeSender() + + const resultPromise = handlers.get('terminalPreview:connect')!(eventFor(sender), { + ptyId: 'p1', + opts: { scrollbackRows: 24 } + }) as Promise + + expect(runtime.subscribeToTerminalData).toHaveBeenCalledBefore(runtime.serializeTerminalBuffer) + runtime.listeners[0]!('abc', { seq: 7, rawLength: 3 }) + resolveSnapshot({ data: 'screen', cols: 80, rows: 20, seq: 6 }) + + await expect(resultPromise).resolves.toEqual({ + snapshot: { data: 'screen', cols: 80, rows: 20, seq: 6 }, + replay: ['c'] + }) + expect(runtime.registerRawTerminalViewSubscriber).toHaveBeenCalledWith('p1') + }) + + it('coalesces live chunks before crossing IPC and releases them with acknowledgements', async () => { + vi.useFakeTimers() + const runtime = makeRuntime() + registerTerminalPreviewHandlers(runtime as never) + const sender = makeSender() + await handlers.get('terminalPreview:connect')!(eventFor(sender), { ptyId: 'p1' }) + + runtime.listeners[0]!('a') + runtime.listeners[0]!('b') + expect(sender.send).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(5) + expect(sender.send).toHaveBeenCalledTimes(1) + expect(sender.send).toHaveBeenCalledWith('terminalPreview:data', { + type: 'data', + ptyId: 'p1', + data: 'ab', + bytes: 2 + }) + + handlers.get('terminalPreview:ack')!(eventFor(sender), { ptyId: 'p1', bytes: 2 }) + expect(sender.send).toHaveBeenCalledTimes(1) + }) + + it('bounds an unresponsive renderer and requests a snapshot resync after prior writes drain', async () => { + const runtime = makeRuntime() + registerTerminalPreviewHandlers(runtime as never) + const sender = makeSender() + await handlers.get('terminalPreview:connect')!(eventFor(sender), { ptyId: 'p1' }) + + const chunk = 'x'.repeat(64 * 1024) + for (let index = 0; index < 13; index++) { + runtime.listeners[0]!(chunk) + } + const dataSends = sender.send.mock.calls.filter(([, payload]) => payload.type === 'data') + expect(dataSends).toHaveLength(8) + + for (let index = 0; index < 8; index++) { + handlers.get('terminalPreview:ack')!(eventFor(sender), { + ptyId: 'p1', + bytes: 64 * 1024 + }) + } + expect(sender.send).toHaveBeenLastCalledWith('terminalPreview:data', { + type: 'resync', + ptyId: 'p1' + }) + }) + + it('never overshoots the in-flight byte budget with partial batches', async () => { + vi.useFakeTimers() + const runtime = makeRuntime() + registerTerminalPreviewHandlers(runtime as never) + const sender = makeSender() + await handlers.get('terminalPreview:connect')!(eventFor(sender), { ptyId: 'p1' }) + + const fullChunk = 'x'.repeat(64 * 1024) + for (let index = 0; index < 7; index++) { + runtime.listeners[0]!(fullChunk) + } + runtime.listeners[0]!('a'.repeat(40 * 1024)) + await vi.advanceTimersByTimeAsync(5) + runtime.listeners[0]!('b'.repeat(40 * 1024)) + await vi.advanceTimersByTimeAsync(5) + expect(sender.send).toHaveBeenCalledTimes(8) + + handlers.get('terminalPreview:ack')!(eventFor(sender), { + ptyId: 'p1', + bytes: 64 * 1024 + }) + expect(sender.send).toHaveBeenCalledTimes(9) + }) + + it('fails safe to another resync when output overflows both snapshot captures', async () => { + const runtime = makeRuntime() + const snapshotResolvers: ((snapshot: { + data: string + cols: number + rows: number + seq: number + }) => void)[] = [] + runtime.serializeTerminalBuffer.mockImplementation( + () => + new Promise((resolve) => { + snapshotResolvers.push(resolve) + }) + ) + registerTerminalPreviewHandlers(runtime as never) + const sender = makeSender() + + const resultPromise = handlers.get('terminalPreview:connect')!(eventFor(sender), { + ptyId: 'p1' + }) as Promise + const chunk = 'x'.repeat(64 * 1024) + for (let index = 0; index < 5; index++) { + runtime.listeners[0]!(chunk) + } + snapshotResolvers[0]!({ data: 'first', cols: 80, rows: 20, seq: 1 }) + await vi.waitFor(() => expect(snapshotResolvers).toHaveLength(2)) + for (let index = 0; index < 5; index++) { + runtime.listeners[0]!(chunk) + } + snapshotResolvers[1]!({ data: 'second', cols: 80, rows: 20, seq: 2 }) + + await expect(resultPromise).resolves.toEqual({ + snapshot: { data: 'second', cols: 80, rows: 20, seq: 2 }, + replay: [], + resyncRequired: true + }) + runtime.listeners[0]!('held until reconnect') + expect(sender.send).not.toHaveBeenCalled() + }) + + it('releases output and raw-view presence on unsubscribe and sender destruction', async () => { + const runtime = makeRuntime() + registerTerminalPreviewHandlers(runtime as never) + const sender = makeSender() + await handlers.get('terminalPreview:connect')!(eventFor(sender), { ptyId: 'p1' }) + handlers.get('terminalPreview:unsubscribe')!(eventFor(sender), { ptyId: 'p1' }) + expect(runtime.unsubscribe).toHaveBeenCalledTimes(1) + expect(runtime.releaseRawView).toHaveBeenCalledTimes(1) + + await handlers.get('terminalPreview:connect')!(eventFor(sender), { ptyId: 'p2' }) + sender.fireDestroyed() + expect(runtime.unsubscribe).toHaveBeenCalledTimes(2) + expect(runtime.releaseRawView).toHaveBeenCalledTimes(2) + }) + + it('releases output and raw-view presence when no snapshot exists', async () => { + const runtime = makeRuntime() + runtime.serializeTerminalBuffer.mockResolvedValueOnce(null) + registerTerminalPreviewHandlers(runtime as never) + const sender = makeSender() + + await expect( + handlers.get('terminalPreview:connect')!(eventFor(sender), { ptyId: 'missing' }) + ).resolves.toEqual({ snapshot: null, replay: [] }) + expect(runtime.unsubscribe).toHaveBeenCalledTimes(1) + expect(runtime.releaseRawView).toHaveBeenCalledTimes(1) + }) + + it('rejects non-dashboard senders on every preview channel', async () => { + const runtime = makeRuntime() + registerTerminalPreviewHandlers(runtime as never) + const sender = makeSender() + isDashboardPopoutRendererMock.mockReturnValue(false) + + await expect( + handlers.get('terminalPreview:connect')!(eventFor(sender), { ptyId: 'p1' }) + ).resolves.toEqual({ snapshot: null, replay: [] }) + await expect( + handlers.get('terminalPreview:input')!(eventFor(sender), { ptyId: 'p1', data: 'x' }) + ).resolves.toBe(false) + handlers.get('terminalPreview:ack')!(eventFor(sender), { ptyId: 'p1', bytes: 1 }) + handlers.get('terminalPreview:unsubscribe')!(eventFor(sender), { ptyId: 'p1' }) + + expect(runtime.serializeTerminalBuffer).not.toHaveBeenCalled() + expect(runtime.subscribeToTerminalData).not.toHaveBeenCalled() + expect(runtime.writeTerminalPreviewInput).not.toHaveBeenCalled() + }) + + it('validates input before routing it to the runtime', async () => { + const runtime = makeRuntime() + registerTerminalPreviewHandlers(runtime as never) + const sender = makeSender() + + await expect( + handlers.get('terminalPreview:input')!(eventFor(sender), { ptyId: 'p1', data: 'ls\r' }) + ).resolves.toBe(true) + expect(runtime.writeTerminalPreviewInput).toHaveBeenCalledWith('p1', 'ls\r') + + await expect( + handlers.get('terminalPreview:input')!(eventFor(sender), { ptyId: '', data: 'x' }) + ).resolves.toBe(false) + await expect( + handlers.get('terminalPreview:input')!(eventFor(sender), { + ptyId: 'x'.repeat(4097), + data: 'x' + }) + ).resolves.toBe(false) + expect(runtime.writeTerminalPreviewInput).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/main/ipc/terminal-preview.ts b/src/main/ipc/terminal-preview.ts new file mode 100644 index 000000000..3df3c4726 --- /dev/null +++ b/src/main/ipc/terminal-preview.ts @@ -0,0 +1,155 @@ +import { ipcMain, type WebContents } from 'electron' +import type { + TerminalPreviewConnectResult, + TerminalPreviewSnapshot +} from '../../shared/terminal-preview' +import type { OrcaRuntimeService } from '../runtime/orca-runtime' +import { isDashboardPopoutRenderer } from '../window/dashboard-popout-window' +import { + TERMINAL_PREVIEW_OUTPUT_BATCH_MAX_BYTES, + TerminalPreviewOutputStream +} from './terminal-preview-output-stream' + +const PREVIEW_ID_MAX_LENGTH = 4096 + +function isValidPtyId(value: unknown): value is string { + return typeof value === 'string' && value.length > 0 && value.length <= PREVIEW_ID_MAX_LENGTH +} + +/** Pop-out terminal transport with an atomic snapshot/live boundary. */ +export function registerTerminalPreviewHandlers(runtime: OrcaRuntimeService): void { + ipcMain.removeHandler('terminalPreview:connect') + ipcMain.removeHandler('terminalPreview:unsubscribe') + ipcMain.removeHandler('terminalPreview:input') + ipcMain.removeHandler('terminalPreview:ack') + + const subscriptionsByContents = new Map>() + + const removeSubscription = (subscription: TerminalPreviewOutputStream): void => { + const perPty = subscriptionsByContents.get(subscription.contents.id) + if (perPty?.get(subscription.ptyId) === subscription) { + perPty.delete(subscription.ptyId) + } + } + + const disposeContents = (contentsId: number): void => { + const perPty = subscriptionsByContents.get(contentsId) + if (!perPty) { + return + } + for (const subscription of perPty.values()) { + subscription.dispose() + } + subscriptionsByContents.delete(contentsId) + } + + const subscriptionsFor = (contents: WebContents): Map => { + let perPty = subscriptionsByContents.get(contents.id) + if (!perPty) { + perPty = new Map() + subscriptionsByContents.set(contents.id, perPty) + contents.once('destroyed', () => disposeContents(contents.id)) + } + return perPty + } + + ipcMain.handle( + 'terminalPreview:connect', + async ( + event, + args: { ptyId?: unknown; opts?: { scrollbackRows?: unknown } } + ): Promise => { + if (!isDashboardPopoutRenderer(event.sender) || !isValidPtyId(args?.ptyId)) { + return { snapshot: null, replay: [] } + } + const ptyId = args.ptyId + const perPty = subscriptionsFor(event.sender) + perPty.get(ptyId)?.dispose() + + const subscription = new TerminalPreviewOutputStream( + event.sender, + ptyId, + runtime.registerRawTerminalViewSubscriber(ptyId), + removeSubscription + ) + subscription.setDataSubscription( + runtime.subscribeToTerminalData(ptyId, (data, meta) => subscription.append(data, meta)) + ) + perPty.set(ptyId, subscription) + + const requestedRows = args.opts?.scrollbackRows + const scrollbackRows = + typeof requestedRows === 'number' && Number.isFinite(requestedRows) + ? Math.max(0, Math.min(1000, Math.floor(requestedRows))) + : undefined + let snapshot: TerminalPreviewSnapshot | null + let resyncRequired = false + try { + snapshot = await runtime.serializeTerminalBuffer(ptyId, { scrollbackRows }) + if (subscription.consumeInitialOverflow() && !subscription.disposed) { + snapshot = await runtime.serializeTerminalBuffer(ptyId, { scrollbackRows }) + if (subscription.consumeInitialOverflow()) { + // Why: never replay a tail with a silently missing middle; the renderer keeps its old frame while reconnecting. + resyncRequired = true + } + } + } catch { + subscription.dispose() + return { snapshot: null, replay: [] } + } + if (subscription.disposed) { + return { snapshot: null, replay: [] } + } + if (!snapshot) { + // Why: a failed lookup has no future live boundary; release raw presence even if the renderer never invokes unsubscribe. + subscription.dispose() + return { snapshot: null, replay: [] } + } + + const replay = subscription.completeSnapshot(snapshot.seq) + if (resyncRequired) { + // Why: no live writes may outlive this stream and acknowledge bytes against its replacement. + subscription.pauseForReconnect() + } + return { snapshot, replay, ...(resyncRequired ? { resyncRequired: true } : {}) } + } + ) + + ipcMain.handle( + 'terminalPreview:input', + (event, args: { ptyId?: unknown; data?: unknown }): Promise => { + if ( + !isDashboardPopoutRenderer(event.sender) || + !isValidPtyId(args?.ptyId) || + typeof args.data !== 'string' + ) { + return Promise.resolve(false) + } + return runtime.writeTerminalPreviewInput(args.ptyId, args.data) + } + ) + + ipcMain.handle( + 'terminalPreview:ack', + (event, args: { ptyId?: unknown; bytes?: unknown }): void => { + if ( + !isDashboardPopoutRenderer(event.sender) || + !isValidPtyId(args?.ptyId) || + typeof args.bytes !== 'number' || + !Number.isFinite(args.bytes) || + args.bytes <= 0 || + args.bytes > TERMINAL_PREVIEW_OUTPUT_BATCH_MAX_BYTES + ) { + return + } + subscriptionsByContents.get(event.sender.id)?.get(args.ptyId)?.acknowledge(args.bytes) + } + ) + + ipcMain.handle('terminalPreview:unsubscribe', (event, args: { ptyId?: unknown }): void => { + if (!isDashboardPopoutRenderer(event.sender) || !isValidPtyId(args?.ptyId)) { + return + } + subscriptionsByContents.get(event.sender.id)?.get(args.ptyId)?.dispose() + }) +} diff --git a/src/main/ipc/ui.test.ts b/src/main/ipc/ui.test.ts index 806d0fa5a..398efa806 100644 --- a/src/main/ipc/ui.test.ts +++ b/src/main/ipc/ui.test.ts @@ -36,6 +36,7 @@ vi.mock('electron', () => ({ import { clearTrustedUIRendererWebContentsId, + getTrustedUIRendererWindow, registerUIHandlers, sendToTrustedUIRenderer, setTrustedUIRendererWebContentsId @@ -112,6 +113,20 @@ describe('UI IPC', () => { expect(guestSends.reduce((total, send) => total + send.mock.calls.length, 0)).toBe(0) }) + it('resolves only the BrowserWindow that owns the trusted renderer', () => { + const renderer = { id: 17, isDestroyed: () => false } + const mainWindow = { id: 'main' } + fromIdMock.mockReturnValue(renderer) + fromWebContentsMock.mockReturnValue(mainWindow) + setTrustedUIRendererWebContentsId(17) + + expect(getTrustedUIRendererWindow()).toBe(mainWindow) + expect(fromWebContentsMock).toHaveBeenCalledWith(renderer) + + fromIdMock.mockReturnValue({ id: 17, isDestroyed: () => true }) + expect(getTrustedUIRendererWindow()).toBeNull() + }) + it('skips missing, destroyed, and originating renderers', () => { const rendererSend = vi.fn() setTrustedUIRendererWebContentsId(17) diff --git a/src/main/ipc/ui.ts b/src/main/ipc/ui.ts index de6f26136..83744b040 100644 --- a/src/main/ipc/ui.ts +++ b/src/main/ipc/ui.ts @@ -20,17 +20,28 @@ export function sendToTrustedUIRenderer( payload: unknown, excludedWebContentsId?: number ): void { + const renderer = getTrustedUIRendererWebContents(excludedWebContentsId) + renderer?.send(channel, payload) +} + +export function getTrustedUIRendererWebContents( + excludedWebContentsId?: number +): WebContents | null { + // Why: exact targeting avoids waking retained browser/utility windows that cannot consume app UI events. const rendererId = trustedUIRendererWebContentsId if (rendererId == null || rendererId === excludedWebContentsId) { - return + return null } const renderer = webContents.fromId(rendererId) if (!renderer || renderer.isDestroyed()) { - return + return null } - // Why: app events belong to the registered UI renderer; enumerating every - // WebContents wakes retained browser guests that cannot consume the channel. - renderer.send(channel, payload) + return renderer +} + +export function getTrustedUIRendererWindow(): BrowserWindow | null { + const renderer = getTrustedUIRendererWebContents() + return renderer ? BrowserWindow.fromWebContents(renderer) : null } export function registerUIHandlers(store: Store): void { diff --git a/src/main/runtime/mobile-presence-lock.test.ts b/src/main/runtime/mobile-presence-lock.test.ts index 87568e3e9..517c038bd 100644 --- a/src/main/runtime/mobile-presence-lock.test.ts +++ b/src/main/runtime/mobile-presence-lock.test.ts @@ -71,12 +71,16 @@ function createRuntime(mobileAutoRestoreFitMs: number | null = 5_000) { ['pty-1', { cols: 150, rows: 40 }] ]) const resizes: { ptyId: string; cols: number; rows: number }[] = [] + const writes: string[] = [] const driverEvents: { ptyId: string; driver: { kind: string; clientId?: string } }[] = [] const fitOverrideEvents: { ptyId: string; mode: string; cols: number; rows: number }[] = [] let resizeSucceeds = true runtime.setPtyController({ - write: () => true, + write: (_ptyId, data) => { + writes.push(data) + return true + }, kill: () => true, getForegroundProcess: async () => null, resize: (ptyId, cols, rows) => { @@ -111,6 +115,7 @@ function createRuntime(mobileAutoRestoreFitMs: number | null = 5_000) { runtime, ptySizes, resizes, + writes, driverEvents, fitOverrideEvents, setResizeSucceeds: (next: boolean) => { @@ -128,6 +133,22 @@ describe('mobile presence lock — driver state machine', () => { expect(runtime.getDriver('pty-1')).toEqual({ kind: 'idle' }) }) + it('stops a preview paste when mobile claims the floor between chunks', async () => { + const { runtime, writes } = createRuntime() + let driverChecks = 0 + vi.spyOn(runtime, 'getDriver').mockImplementation(() => { + driverChecks++ + return driverChecks >= 3 ? { kind: 'mobile', clientId: 'phone-A' } : { kind: 'idle' } + }) + + const result = runtime.writeTerminalPreviewInput('pty-1', 'x'.repeat(32 * 1024)) + await vi.advanceTimersByTimeAsync(0) + + await expect(result).resolves.toBe(false) + expect(writes).toHaveLength(1) + expect(Buffer.byteLength(writes[0]!, 'utf8')).toBe(16 * 1024) + }) + it('handleMobileSubscribe in auto mode transitions idle → mobile{clientId}', async () => { const { runtime, driverEvents } = createRuntime() await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 }) diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 6d6e66a89..492d7abbb 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -2488,6 +2488,9 @@ export class OrcaRuntimeService { // streams can attach concurrently; mobileSubscribers is consulted too so // grace-window mobile records keep suppressing. private remoteTerminalViewSubscriberCounts = new Map() + // Preview windows consume the raw stream but deliberately leave terminal + // query replies to main's headless emulator. + private rawTerminalViewSubscriberCounts = new Map() // Why: per-PTY driver state. The "driver" is whoever currently owns the // input/resize floor. While `kind === 'mobile'` the desktop renderer drops @@ -7263,6 +7266,37 @@ export class OrcaRuntimeService { } } + /** Mark a raw-output viewer without transferring terminal query authority. */ + registerRawTerminalViewSubscriber(ptyId: string): () => void { + this.rawTerminalViewSubscriberCounts.set( + ptyId, + (this.rawTerminalViewSubscriberCounts.get(ptyId) ?? 0) + 1 + ) + this.notifyRemoteTerminalViewPresenceChanged(ptyId) + let released = false + return () => { + if (released) { + return + } + released = true + const next = (this.rawTerminalViewSubscriberCounts.get(ptyId) ?? 1) - 1 + if (next <= 0) { + this.rawTerminalViewSubscriberCounts.delete(ptyId) + } else { + this.rawTerminalViewSubscriberCounts.set(ptyId, next) + } + this.notifyRemoteTerminalViewPresenceChanged(ptyId) + } + } + + /** Raw stream presence prevents provider thinning without changing reply ownership. */ + hasRawTerminalViewSubscriber(ptyId: string): boolean { + return ( + (this.rawTerminalViewSubscriberCounts.get(ptyId) ?? 0) > 0 || + this.hasRemoteTerminalViewSubscriber(ptyId) + ) + } + hasRemoteTerminalViewSubscriber(ptyId: string): boolean { if ((this.remoteTerminalViewSubscriberCounts.get(ptyId) ?? 0) > 0) { return true @@ -7344,6 +7378,28 @@ export class OrcaRuntimeService { return this.serializeTerminalBufferFromAvailableState(ptyId, opts) } + /** Raw keystroke pass-through for the pop-out dashboard's terminal preview. + * Honors the mobile-presence lock like the main window's pty:write path. */ + async writeTerminalPreviewInput(ptyId: string, data: string): Promise { + if (data.length === 0 || this.getDriver(ptyId).kind === 'mobile') { + return false + } + try { + await assertTerminalInputWithinLimitWithYield(data) + await this.writeTerminalInputChunks(ptyId, data, { + // Why: a phone can claim the floor while a paste yields between chunks. + beforeWrite: () => { + if (this.getDriver(ptyId).kind === 'mobile') { + throw new Error('terminal_mobile_driver_active') + } + } + }) + return true + } catch { + return false + } + } + hasHeadlessTerminalState(ptyId: string): boolean { return this.headlessTerminals.has(ptyId) } @@ -9284,6 +9340,7 @@ export class OrcaRuntimeService { // Clean up new mobile state for this PTY this.mobileSubscribers.delete(ptyId) this.remoteTerminalViewSubscriberCounts.delete(ptyId) + this.rawTerminalViewSubscriberCounts.delete(ptyId) this.mobileDisplayModes.delete(ptyId) this.resizeListeners.delete(ptyId) this.lastRendererSizes.delete(ptyId) diff --git a/src/main/runtime/terminal-query-responder.test.ts b/src/main/runtime/terminal-query-responder.test.ts index 896fa59b0..cdcd10dfb 100644 --- a/src/main/runtime/terminal-query-responder.test.ts +++ b/src/main/runtime/terminal-query-responder.test.ts @@ -247,6 +247,21 @@ describe('reply ownership matrix', () => { expect(runtime.hasRemoteTerminalViewSubscriber('pty-m')).toBe(false) }) + it('keeps raw preview presence separate from terminal query authority', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-preview') + const release = runtime.registerRawTerminalViewSubscriber('pty-preview') + + expect(runtime.hasRawTerminalViewSubscriber('pty-preview')).toBe(true) + expect(runtime.hasRemoteTerminalViewSubscriber('pty-preview')).toBe(false) + runtime.onPtyData('pty-preview', DA1, Date.now()) + await settle(runtime, 'pty-preview') + expect(replies.map((reply) => reply.data)).toEqual(['\x1b[?1;2c']) + + release() + expect(runtime.hasRawTerminalViewSubscriber('pty-preview')).toBe(false) + }) + it('treats mobile subscriber records as remote view subscribers', async () => { const { runtime } = createResponderRuntime() await runtime.handleMobileSubscribe('pty-mob', 'client-1', { cols: 40, rows: 20 }) diff --git a/src/main/window/createMainWindow.ts b/src/main/window/createMainWindow.ts index 3be600cb5..e35cd24d7 100644 --- a/src/main/window/createMainWindow.ts +++ b/src/main/window/createMainWindow.ts @@ -7,8 +7,7 @@ import { nativeTheme, Notification, powerMonitor, - screen, - shell + screen } from 'electron' import { join } from 'node:path' import { is } from '@electron-toolkit/utils' @@ -17,10 +16,7 @@ import { getAppIconPath } from '../app-icon' import { browserManager } from '../browser/browser-manager' import { browserSessionRegistry } from '../browser/browser-session-registry' import { translateMain } from '../i18n/main-i18n' -import { - normalizeBrowserNavigationUrl, - normalizeExternalBrowserUrl -} from '../../shared/browser-url' +import { normalizeBrowserNavigationUrl } from '../../shared/browser-url' import { ORCA_BROWSER_GUEST_WEB_PREFERENCES } from '../../shared/browser-guest-web-preferences' import { isCrashReportReason } from '../../shared/crash-reporting' import { @@ -49,6 +45,9 @@ import { getMainE2EConfig } from '../e2e-config' import { buildEditableContextMenuTemplate } from './editable-context-menu' import { clearTrustedUIRendererWebContentsId, setTrustedUIRendererWebContentsId } from '../ipc/ui' import { resolveWindowCloseAction } from './window-close-decision' +import { rectHasVisibleAreaOnAnyDisplay } from './window-bounds-validation' +import { closeDashboardPopout } from './dashboard-popout-window' +import { installPrivilegedWindowNavigationPolicy } from './privileged-window-navigation' // Why: show/restore/resume can overlap before the size nudge resets; never capture the temporary width as the next baseline. const activeRepaintJiggles = new WeakSet() @@ -173,34 +172,12 @@ export function createMainWindow( opts?: CreateMainWindowOptions ): BrowserWindow { const rawSavedBounds = store?.getUI().windowBounds - // Why: discard persisted bounds that are shrink-to-min (corrupt, see freezeBoundsOnQuit) or off-screen, falling back to defaultBounds. - // Require ~half MIN_WIDTH/HEIGHT of workArea overlap so a 1px sliver or dock-hidden rect isn't treated as visible. - const rectHasVisibleAreaOnAnyDisplay = (b: { - x: number - y: number - width: number - height: number - }): boolean => { - try { - return screen.getAllDisplays().some((d) => { - const wa = d.workArea - const overlapX = Math.max(0, Math.min(b.x + b.width, wa.x + wa.width) - Math.max(b.x, wa.x)) - const overlapY = Math.max( - 0, - Math.min(b.y + b.height, wa.y + wa.height) - Math.max(b.y, wa.y) - ) - return overlapX >= MIN_WIDTH / 2 && overlapY >= MIN_HEIGHT / 2 - }) - } catch (err) { - console.warn('[window] screen.getAllDisplays() threw; treating bounds as off-screen', err) - return false - } - } + // Why: reject min-size or substantially off-screen bounds so the titlebar stays reachable after display changes. const savedBounds = rawSavedBounds && rawSavedBounds.width > MIN_WIDTH && rawSavedBounds.height > MIN_HEIGHT && - rectHasVisibleAreaOnAnyDisplay(rawSavedBounds) + rectHasVisibleAreaOnAnyDisplay(rawSavedBounds, MIN_WIDTH / 2, MIN_HEIGHT / 2) ? rawSavedBounds : undefined if (rawSavedBounds && !savedBounds) { @@ -417,13 +394,7 @@ export function createMainWindow( mainWindow.webContents.send('window:fullscreen-changed', false) }) - mainWindow.webContents.setWindowOpenHandler((details) => { - const externalUrl = normalizeExternalBrowserUrl(details.url) - if (externalUrl) { - shell.openExternal(externalUrl) - } - return { action: 'deny' } - }) + installPrivilegedWindowNavigationPolicy(mainWindow.webContents) mainWindow.webContents.on('will-attach-webview', (event, webPreferences, params) => { const src = typeof params.src === 'string' ? params.src : '' @@ -458,29 +429,6 @@ export function createMainWindow( browserManager.attachGuestPolicies(guest) }) - // Why: block in-window navigations so remote pages can't inherit the privileged preload bridge (dev server allowed for HMR). - mainWindow.webContents.on('will-navigate', (event, url) => { - const externalUrl = normalizeExternalBrowserUrl(url) - - if (externalUrl) { - const target = new URL(externalUrl) - if (is.dev && process.env.ELECTRON_RENDERER_URL) { - try { - const allowed = new URL(process.env.ELECTRON_RENDERER_URL) - if (target.origin === allowed.origin) { - return // allow dev server navigations (HMR, etc.) - } - } catch { - // fall through to prevent - } - } - - shell.openExternal(externalUrl) - } - - event.preventDefault() - }) - // Why: mirror markdown-editor focus so before-input-event skips Cmd/Ctrl+B while TipTap owns focus (docs/markdown-cmd-b-bold-design.md). let markdownEditorFocused = false let terminalInputFocused = false @@ -1033,6 +981,10 @@ export function createMainWindow( ipcMain.on(confirmCloseChannel, onConfirmClose) mainWindow.on('closed', () => { + // Why: the dashboard pop-out is a companion of the main window — close it + // alongside so it never orphans as a lone window after the app window is + // gone (e.g. on macOS where the app stays alive after the window closes). + closeDashboardPopout() clearInitialRevealFallbackTimer() // Why: default-deny the Cmd+B carve-out after the window is gone so a stale-true flag can't leak into later state. markdownEditorFocused = false diff --git a/src/main/window/dashboard-popout-window.test.ts b/src/main/window/dashboard-popout-window.test.ts new file mode 100644 index 000000000..79396e1c7 --- /dev/null +++ b/src/main/window/dashboard-popout-window.test.ts @@ -0,0 +1,270 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +type Display = { workArea: { x: number; y: number; width: number; height: number } } + +const { + instances, + BrowserWindowMock, + nativeThemeMock, + appOnMock, + appRemoveListenerMock, + getAllDisplaysMock, + installNavigationPolicyMock, + sendToTrustedUIRendererMock, + isMock +} = vi.hoisted(() => { + const created: FakeWindow[] = [] + + class FakeWindow { + options: Electron.BrowserWindowConstructorOptions + private handlers: Record void)[]> = {} + private onceHandlers: Record void)[]> = {} + destroyed = false + minimized = false + fullscreen = false + webContents = { id: created.length + 1, send: vi.fn(), isDestroyed: () => this.destroyed } + bounds = { x: 100, y: 100, width: 960, height: 720 } + focus = vi.fn() + show = vi.fn() + restore = vi.fn(() => { + this.minimized = false + }) + loadURL = vi.fn() + loadFile = vi.fn() + close = vi.fn(() => { + this.destroyed = true + this.emit('close') + this.emit('closed') + }) + + constructor(options: Electron.BrowserWindowConstructorOptions) { + this.options = options + created.push(this) + } + + on(event: string, cb: (...args: unknown[]) => void): this { + ;(this.handlers[event] ||= []).push(cb) + return this + } + + once(event: string, cb: (...args: unknown[]) => void): this { + ;(this.onceHandlers[event] ||= []).push(cb) + return this + } + + emit(event: string, ...args: unknown[]): void { + for (const cb of this.handlers[event] ?? []) { + cb(...args) + } + for (const cb of this.onceHandlers[event] ?? []) { + cb(...args) + } + } + + isDestroyed(): boolean { + return this.destroyed + } + isMinimized(): boolean { + return this.minimized + } + isFullScreen(): boolean { + return this.fullscreen + } + getBounds(): { x: number; y: number; width: number; height: number } { + return this.bounds + } + } + + return { + instances: created, + BrowserWindowMock: FakeWindow, + nativeThemeMock: { shouldUseDarkColors: true }, + appOnMock: vi.fn(), + appRemoveListenerMock: vi.fn(), + getAllDisplaysMock: vi.fn((): Display[] => [ + { workArea: { x: 0, y: 0, width: 1920, height: 1080 } } + ]), + installNavigationPolicyMock: vi.fn(), + sendToTrustedUIRendererMock: vi.fn(), + isMock: { dev: false } as { dev: boolean } + } +}) + +// Static helpers live on the constructor; broadcastPopoutOpenChanged uses +// BrowserWindow.getAllWindows(). Return the instances created in this test. +;(BrowserWindowMock as unknown as { getAllWindows: () => unknown[] }).getAllWindows = () => + instances + +vi.mock('electron', () => ({ + app: { on: appOnMock, removeListener: appRemoveListenerMock }, + BrowserWindow: BrowserWindowMock, + nativeTheme: nativeThemeMock, + screen: { getAllDisplays: getAllDisplaysMock } +})) + +vi.mock('@electron-toolkit/utils', () => ({ is: isMock })) +vi.mock('../ipc/ui', () => ({ sendToTrustedUIRenderer: sendToTrustedUIRendererMock })) +vi.mock('./privileged-window-navigation', () => ({ + installPrivilegedWindowNavigationPolicy: installNavigationPolicyMock +})) + +import { + createOrFocusDashboardPopout, + closeDashboardPopout, + isDashboardPopoutRenderer +} from './dashboard-popout-window' + +type FakeWindow = InstanceType + +function makeStore(ui: Record = {}): { + getUI: () => Record + updateUI: ReturnType +} { + return { getUI: () => ui, updateUI: vi.fn() } +} + +const RENDERER_URL = 'http://localhost:5173' + +describe('createOrFocusDashboardPopout', () => { + beforeEach(() => { + instances.length = 0 + isMock.dev = false + vi.stubEnv('ELECTRON_RENDERER_URL', '') + getAllDisplaysMock.mockReturnValue([{ workArea: { x: 0, y: 0, width: 1920, height: 1080 } }]) + }) + + afterEach(() => { + // Reset the module-level singleton between tests. + closeDashboardPopout() + vi.unstubAllEnvs() + vi.clearAllMocks() + }) + + it('creates a native-frame window with the shared preload and no webview surface', () => { + createOrFocusDashboardPopout(makeStore() as never) + + expect(instances).toHaveLength(1) + const opts = instances[0].options + expect(opts.title).toBe('Orca Agent Dashboard') + expect(opts.minWidth).toBe(480) + expect(opts.minHeight).toBe(360) + // Native frame: neither a custom titleBarStyle nor frame:false is set. + expect(opts.titleBarStyle).toBeUndefined() + expect(opts.frame).toBeUndefined() + expect(opts.backgroundColor).toBe('#0a0a0a') // dark theme mock + expect(opts.webPreferences?.sandbox).toBe(true) + expect(opts.webPreferences?.webviewTag).toBe(false) + expect(opts.webPreferences?.preload).toMatch(/preload[\\/]index\.js$/) + expect(installNavigationPolicyMock).toHaveBeenCalledWith(instances[0].webContents) + expect(sendToTrustedUIRendererMock).toHaveBeenCalledWith('dashboard:popoutOpenChanged', true) + }) + + it('shows the window on ready-to-show', () => { + createOrFocusDashboardPopout(makeStore() as never) + const win = instances[0] + expect(win.show).not.toHaveBeenCalled() + win.emit('ready-to-show') + expect(win.show).toHaveBeenCalledTimes(1) + }) + + it('loads the prod file entry with the requested view', () => { + createOrFocusDashboardPopout(makeStore() as never, 'kanban') + const win = instances[0] + expect(win.loadURL).not.toHaveBeenCalled() + expect(win.loadFile).toHaveBeenCalledTimes(1) + const [file, options] = win.loadFile.mock.calls[0] + expect(String(file)).toMatch(/renderer[\\/]popout\.html$/) + expect(options).toEqual({ search: 'view=kanban' }) + }) + + it('loads the dev server URL with the requested view when in dev', () => { + isMock.dev = true + vi.stubEnv('ELECTRON_RENDERER_URL', RENDERER_URL) + createOrFocusDashboardPopout(makeStore() as never, 'kanban') + const win = instances[0] + expect(win.loadFile).not.toHaveBeenCalled() + expect(win.loadURL).toHaveBeenCalledWith(`${RENDERER_URL}/popout.html?view=kanban`) + }) + + it('focuses the existing window instead of creating a second one', () => { + const store = makeStore() + const first = createOrFocusDashboardPopout(store as never) + const second = createOrFocusDashboardPopout(store as never) + expect(instances).toHaveLength(1) + expect(second).toBe(first) + expect(instances[0].focus).toHaveBeenCalledTimes(1) + }) + + it('trusts only the live popout webContents', () => { + const win = createOrFocusDashboardPopout(makeStore() as never) as unknown as FakeWindow + expect(isDashboardPopoutRenderer(win.webContents as never)).toBe(true) + expect(isDashboardPopoutRenderer({ id: win.webContents.id } as never)).toBe(false) + win.destroyed = true + expect(isDashboardPopoutRenderer(win.webContents as never)).toBe(false) + }) + + it('restores a minimized window when re-requested', () => { + const store = makeStore() + const win = createOrFocusDashboardPopout(store as never) as unknown as FakeWindow + win.minimized = true + createOrFocusDashboardPopout(store as never) + expect(win.restore).toHaveBeenCalledTimes(1) + expect(win.focus).toHaveBeenCalledTimes(1) + }) + + it('restores valid persisted bounds', () => { + const store = makeStore({ + dashboardPopoutBounds: { x: 200, y: 150, width: 1000, height: 800 } + }) + createOrFocusDashboardPopout(store as never) + const opts = instances[0].options + expect(opts.x).toBe(200) + expect(opts.y).toBe(150) + expect(opts.width).toBe(1000) + expect(opts.height).toBe(800) + }) + + it('discards off-screen persisted bounds and falls back to defaults', () => { + // Display does not overlap the saved rect at all. + getAllDisplaysMock.mockReturnValue([{ workArea: { x: 0, y: 0, width: 800, height: 600 } }]) + const store = makeStore({ + dashboardPopoutBounds: { x: 5000, y: 5000, width: 1000, height: 800 } + }) + createOrFocusDashboardPopout(store as never) + const opts = instances[0].options + expect(opts.x).toBeUndefined() + expect(opts.y).toBeUndefined() + expect(opts.width).toBe(960) + expect(opts.height).toBe(720) + }) + + it('persists bounds on resize after the debounce, guarding near-minimum sizes', () => { + vi.useFakeTimers() + try { + const store = makeStore() + const win = createOrFocusDashboardPopout(store as never) as unknown as FakeWindow + + win.bounds = { x: 10, y: 10, width: 1200, height: 900 } + win.emit('resize') + vi.advanceTimersByTime(500) + expect(store.updateUI).toHaveBeenCalledWith({ + dashboardPopoutBounds: { x: 10, y: 10, width: 1200, height: 900 } + }) + + store.updateUI.mockClear() + win.bounds = { x: 10, y: 10, width: 100, height: 100 } // below minimum + win.emit('resize') + vi.advanceTimersByTime(500) + expect(store.updateUI).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + + it('closeDashboardPopout closes an open window', () => { + createOrFocusDashboardPopout(makeStore() as never) + const win = instances[0] + closeDashboardPopout() + expect(win.close).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/main/window/dashboard-popout-window.ts b/src/main/window/dashboard-popout-window.ts new file mode 100644 index 000000000..bcfd59857 --- /dev/null +++ b/src/main/window/dashboard-popout-window.ts @@ -0,0 +1,189 @@ +import { app, BrowserWindow, nativeTheme, type WebContents } from 'electron' +import { join } from 'node:path' +import { is } from '@electron-toolkit/utils' +import type { Store } from '../persistence' +import { rectHasVisibleAreaOnAnyDisplay } from './window-bounds-validation' +import { sendToTrustedUIRenderer } from '../ipc/ui' +import { installPrivilegedWindowNavigationPolicy } from './privileged-window-navigation' + +const MIN_WIDTH = 480 +const MIN_HEIGHT = 360 +const DEFAULT_WIDTH = 960 +const DEFAULT_HEIGHT = 720 +const DEFAULT_VIEW = 'kanban' + +// Why: singleton — the dashboard is a companion surface, so a second "Pop Out" +// request focuses the existing window rather than spawning duplicates. +let dashboardPopoutWindow: BrowserWindow | null = null + +/** The live pop-out window, or null when closed. Used by the dashboard relay to + * forward snapshots to the popout's webContents. */ +export function getDashboardPopoutWindow(): BrowserWindow | null { + return dashboardPopoutWindow && + !dashboardPopoutWindow.isDestroyed() && + !dashboardPopoutWindow.webContents.isDestroyed() + ? dashboardPopoutWindow + : null +} + +export function isDashboardPopoutRenderer(sender: WebContents): boolean { + return getDashboardPopoutWindow()?.webContents === sender +} + +// In-process listeners (the dashboard relay clears its cached snapshot on close). +const popoutOpenListeners = new Set<(open: boolean) => void>() + +/** Subscribe to pop-out open/close transitions in the main process. */ +export function onDashboardPopoutOpenChanged(listener: (open: boolean) => void): () => void { + popoutOpenListeners.add(listener) + return () => popoutOpenListeners.delete(listener) +} + +// Why: the main renderer's snapshot publisher only runs while the pop-out is +// open. Tell that exact window when the state flips, then notify listeners. +function broadcastPopoutOpenChanged(open: boolean): void { + sendToTrustedUIRenderer('dashboard:popoutOpenChanged', open) + for (const listener of popoutOpenListeners) { + listener(open) + } +} + +function loadDashboardPopout(window: BrowserWindow, view: string): void { + const search = `view=${encodeURIComponent(view)}` + // Why: mirror loadMainWindow's dev/prod branch — the dev server serves the + // second HTML entry, prod loads the emitted file. + if (is.dev && process.env.ELECTRON_RENDERER_URL) { + void window.loadURL(`${process.env.ELECTRON_RENDERER_URL}/popout.html?${search}`) + } else { + void window.loadFile(join(__dirname, '../renderer/popout.html'), { search }) + } +} + +function resolveRestoredBounds(store: Store | null): { + x: number + y: number + width: number + height: number +} | null { + const raw = store?.getUI().dashboardPopoutBounds ?? null + if ( + raw && + raw.width >= MIN_WIDTH && + raw.height >= MIN_HEIGHT && + rectHasVisibleAreaOnAnyDisplay(raw, MIN_WIDTH / 2, MIN_HEIGHT / 2) + ) { + return raw + } + if (raw) { + console.warn('[dashboard-popout] Discarding off-screen/near-min popout bounds:', raw) + } + return null +} + +/** + * Open the pop-out dashboard window, or focus it if already open. The window is + * a standalone top-level BrowserWindow with a native frame that reuses the same + * preload/window.api as the main window but renders its own React root + * (popout.html?view=…). + */ +export function createOrFocusDashboardPopout( + store: Store | null, + view: string = DEFAULT_VIEW +): BrowserWindow { + if (dashboardPopoutWindow && !dashboardPopoutWindow.isDestroyed()) { + if (dashboardPopoutWindow.isMinimized()) { + dashboardPopoutWindow.restore() + } + dashboardPopoutWindow.focus() + return dashboardPopoutWindow + } + + const savedBounds = resolveRestoredBounds(store) + + const window = new BrowserWindow({ + width: savedBounds?.width ?? DEFAULT_WIDTH, + height: savedBounds?.height ?? DEFAULT_HEIGHT, + ...(savedBounds ? { x: savedBounds.x, y: savedBounds.y } : {}), + minWidth: MIN_WIDTH, + minHeight: MIN_HEIGHT, + title: 'Orca Agent Dashboard', + show: false, + autoHideMenuBar: true, + backgroundColor: nativeTheme.shouldUseDarkColors ? '#0a0a0a' : '#ffffff', + // Why: the pop-out uses a standard native frame so it is movable, closable, + // and minimizable on every platform without reimplementing the main + // window's custom titlebar/drag-region/window-control chrome. The main + // window is frameless because it draws its own titlebar; the dashboard has + // no such chrome yet, so a native frame is the correct default here. + webPreferences: { + preload: join(__dirname, '../preload/index.js'), + sandbox: true, + // Why: the dashboard is plain DOM — no guests — so keep the + // guest-embedding surface off for this window. + webviewTag: false + } + }) + installPrivilegedWindowNavigationPolicy(window.webContents) + dashboardPopoutWindow = window + broadcastPopoutOpenChanged(true) + + window.once('ready-to-show', () => { + if (!window.isDestroyed()) { + window.show() + } + }) + + // Bounds persistence — mirrors the main window's debounced/frozen approach so + // teardown-time resize/move events can't clobber the remembered size with + // near-minimum bounds. + let boundsTimer: ReturnType | null = null + let windowClosing = false + const saveBounds = (): void => { + if (boundsTimer) { + clearTimeout(boundsTimer) + } + boundsTimer = setTimeout(() => { + boundsTimer = null + if (windowClosing || window.isDestroyed() || window.isMinimized() || window.isFullScreen()) { + return + } + const bounds = window.getBounds() + if (bounds.width < MIN_WIDTH || bounds.height < MIN_HEIGHT) { + return + } + store?.updateUI({ dashboardPopoutBounds: bounds }) + }, 500) + } + window.on('resize', saveBounds) + window.on('move', saveBounds) + + const freezeBounds = (): void => { + windowClosing = true + if (boundsTimer) { + clearTimeout(boundsTimer) + boundsTimer = null + } + } + window.on('close', freezeBounds) + app.on('before-quit', freezeBounds) + + window.on('closed', () => { + app.removeListener('before-quit', freezeBounds) + if (dashboardPopoutWindow === window) { + dashboardPopoutWindow = null + } + broadcastPopoutOpenChanged(false) + }) + + loadDashboardPopout(window, view) + return window +} + +/** Close the pop-out dashboard if it is open. Called when the main window + * closes so the dashboard never orphans without its owning app window. */ +export function closeDashboardPopout(): void { + if (dashboardPopoutWindow && !dashboardPopoutWindow.isDestroyed()) { + dashboardPopoutWindow.close() + } + dashboardPopoutWindow = null +} diff --git a/src/main/window/focus-existing-window.ts b/src/main/window/focus-existing-window.ts index 1ff9d8647..7c73b58b1 100644 --- a/src/main/window/focus-existing-window.ts +++ b/src/main/window/focus-existing-window.ts @@ -25,7 +25,7 @@ function safelyFocusApp(app: Pick): void { } } -function safelyRevealWindow(window: BrowserWindow): void { +export function safelyRevealWindow(window: BrowserWindow): void { if (window.isDestroyed()) { return } diff --git a/src/main/window/privileged-window-navigation.ts b/src/main/window/privileged-window-navigation.ts new file mode 100644 index 000000000..a5afbbe0a --- /dev/null +++ b/src/main/window/privileged-window-navigation.ts @@ -0,0 +1,33 @@ +import { shell, type WebContents } from 'electron' +import { is } from '@electron-toolkit/utils' +import { normalizeExternalBrowserUrl } from '../../shared/browser-url' + +/** Keep remote documents from inheriting an Orca window's privileged preload. */ +export function installPrivilegedWindowNavigationPolicy(contents: WebContents): void { + contents.setWindowOpenHandler(({ url }) => { + const externalUrl = normalizeExternalBrowserUrl(url) + if (externalUrl) { + void shell.openExternal(externalUrl) + } + return { action: 'deny' } + }) + + contents.on('will-navigate', (event, url) => { + const externalUrl = normalizeExternalBrowserUrl(url) + if (externalUrl) { + if (is.dev && process.env.ELECTRON_RENDERER_URL) { + try { + const target = new URL(externalUrl) + const allowed = new URL(process.env.ELECTRON_RENDERER_URL) + if (target.origin === allowed.origin) { + return + } + } catch { + // Fall through and block malformed navigation targets. + } + } + void shell.openExternal(externalUrl) + } + event.preventDefault() + }) +} diff --git a/src/main/window/window-bounds-validation.ts b/src/main/window/window-bounds-validation.ts new file mode 100644 index 000000000..f358ef391 --- /dev/null +++ b/src/main/window/window-bounds-validation.ts @@ -0,0 +1,35 @@ +import { screen } from 'electron' + +export type WindowRect = { x: number; y: number; width: number; height: number } + +/** + * True when `rect` overlaps some currently-attached display's workArea by at + * least the given visible width/height. Used to reject persisted bounds that + * would restore a window off-screen — e.g. saved while an external monitor was + * connected. workArea excludes the menu bar / dock, so a rect hidden entirely + * under the dock is also correctly rejected. Requiring a *meaningful* overlap + * (not just >0) avoids a one-pixel sliver leaving the titlebar unreachable. + */ +export function rectHasVisibleAreaOnAnyDisplay( + rect: WindowRect, + minVisibleWidth: number, + minVisibleHeight: number +): boolean { + try { + return screen.getAllDisplays().some((display) => { + const wa = display.workArea + const overlapX = Math.max( + 0, + Math.min(rect.x + rect.width, wa.x + wa.width) - Math.max(rect.x, wa.x) + ) + const overlapY = Math.max( + 0, + Math.min(rect.y + rect.height, wa.y + wa.height) - Math.max(rect.y, wa.y) + ) + return overlapX >= minVisibleWidth && overlapY >= minVisibleHeight + }) + } catch (err) { + console.warn('[window] screen.getAllDisplays() threw; treating bounds as off-screen', err) + return false + } +} diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index ee882503b..f10ba519b 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -9,6 +9,11 @@ import type { HostedReviewProvider } from '../shared/hosted-review' import type { NativeFileDropPayload } from '../shared/native-file-drop' +import type { DashboardSnapshot, DashboardRevealAgentArgs } from '../shared/dashboard-snapshot' +import type { + TerminalPreviewConnectResult, + TerminalPreviewDataPayload +} from '../shared/terminal-preview' import type { TerminalTabCloseRequest, TerminalTabCloseResponse @@ -2212,6 +2217,29 @@ export type PreloadApi = { } ) => Promise } + dashboard: { + openPopout: () => Promise + publishSnapshot: (snapshot: DashboardSnapshot) => Promise + getPopoutOpen: () => Promise + onPopoutOpenChanged: (callback: (open: boolean) => void) => () => void + onSnapshotRequested: (callback: () => void) => () => void + onRevealAgent: (callback: (args: DashboardRevealAgentArgs) => void) => () => void + onAckAgent: (callback: (paneKey: string) => void) => () => void + requestSnapshot: () => Promise + onSnapshot: (callback: (snapshot: DashboardSnapshot) => void) => () => void + revealAgent: (args: DashboardRevealAgentArgs) => Promise + ackAgent: (paneKey: string) => Promise + } + terminalPreview: { + connect: ( + ptyId: string, + opts?: { scrollbackRows?: number } + ) => Promise + input: (ptyId: string, data: string) => Promise + ack: (ptyId: string, bytes: number) => Promise + unsubscribe: (ptyId: string) => Promise + onData: (callback: (payload: TerminalPreviewDataPayload) => void) => () => void + } developerPermissions: { getStatus: () => Promise request: (args: { id: DeveloperPermissionId }) => Promise diff --git a/src/preload/index.ts b/src/preload/index.ts index af9439a66..0021f55df 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -4,6 +4,11 @@ import { electronAPI } from '@electron-toolkit/preload' import { preloadE2EConfig } from './e2e-config' import { glApi } from './gitlab' import type { AppIdentity } from '../shared/app-identity' +import type { DashboardSnapshot, DashboardRevealAgentArgs } from '../shared/dashboard-snapshot' +import type { + TerminalPreviewConnectResult, + TerminalPreviewDataPayload +} from '../shared/terminal-preview' import type { CliInstallStatus } from '../shared/cli-install-types' import type { AgentHookInstallStatus } from '../shared/agent-hook-types' import type { TerminalPaneSplitSource } from '../shared/feature-education-telemetry' @@ -2069,6 +2074,73 @@ const api = { ): Promise => ipcRenderer.invoke('onboarding:update', updates) }, + dashboard: { + // Open the pop-out dashboard window, or focus it if already open. + openPopout: (): Promise => ipcRenderer.invoke('dashboardPopout:open'), + + // ── Producer side (main window) ────────────────────────────────────── + publishSnapshot: (snapshot: DashboardSnapshot): Promise => + ipcRenderer.invoke('dashboard:publishSnapshot', snapshot), + getPopoutOpen: (): Promise => ipcRenderer.invoke('dashboard:getPopoutOpen'), + onPopoutOpenChanged: (callback: (open: boolean) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, open: boolean): void => callback(open) + ipcRenderer.on('dashboard:popoutOpenChanged', listener) + return () => ipcRenderer.removeListener('dashboard:popoutOpenChanged', listener) + }, + onSnapshotRequested: (callback: () => void): (() => void) => { + const listener = (): void => callback() + ipcRenderer.on('dashboard:snapshotRequested', listener) + return () => ipcRenderer.removeListener('dashboard:snapshotRequested', listener) + }, + onRevealAgent: (callback: (args: DashboardRevealAgentArgs) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, args: DashboardRevealAgentArgs): void => + callback(args) + ipcRenderer.on('ui:revealDashboardAgent', listener) + return () => ipcRenderer.removeListener('ui:revealDashboardAgent', listener) + }, + onAckAgent: (callback: (paneKey: string) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, paneKey: string): void => + callback(paneKey) + ipcRenderer.on('ui:ackDashboardAgent', listener) + return () => ipcRenderer.removeListener('ui:ackDashboardAgent', listener) + }, + + // ── Consumer side (pop-out window) ─────────────────────────────────── + requestSnapshot: (): Promise => ipcRenderer.invoke('dashboard:requestSnapshot'), + onSnapshot: (callback: (snapshot: DashboardSnapshot) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, snapshot: DashboardSnapshot): void => + callback(snapshot) + ipcRenderer.on('dashboard:snapshot', listener) + return () => ipcRenderer.removeListener('dashboard:snapshot', listener) + }, + revealAgent: (args: DashboardRevealAgentArgs): Promise => + ipcRenderer.invoke('dashboardPopout:revealAgent', args), + ackAgent: (paneKey: string): Promise => + ipcRenderer.invoke('dashboardPopout:ackAgent', { paneKey }) + }, + + terminalPreview: { + connect: ( + ptyId: string, + opts?: { scrollbackRows?: number } + ): Promise => + ipcRenderer.invoke('terminalPreview:connect', { ptyId, opts }), + input: (ptyId: string, data: string): Promise => + ipcRenderer.invoke('terminalPreview:input', { ptyId, data }), + ack: (ptyId: string, bytes: number): Promise => + ipcRenderer.invoke('terminalPreview:ack', { ptyId, bytes }), + unsubscribe: (ptyId: string): Promise => + ipcRenderer.invoke('terminalPreview:unsubscribe', { ptyId }), + onData: (callback: (payload: TerminalPreviewDataPayload) => void): (() => void) => { + const listener = ( + _event: Electron.IpcRendererEvent, + payload: TerminalPreviewDataPayload + ): void => callback(payload) + ipcRenderer.on('terminalPreview:data', listener) + return () => ipcRenderer.removeListener('terminalPreview:data', listener) + } + }, + developerPermissions: { getStatus: (): Promise => ipcRenderer.invoke('developerPermissions:getStatus'), request: (args: { id: string }): Promise => diff --git a/src/renderer/popout.html b/src/renderer/popout.html new file mode 100644 index 000000000..944bcd23b --- /dev/null +++ b/src/renderer/popout.html @@ -0,0 +1,13 @@ + + + + + Orca Agent Dashboard + + + + +
+ + + diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index faf1b7bb9..b228a4715 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -91,6 +91,7 @@ import RecentTabSwitcher from './components/tab-bar/RecentTabSwitcher' import { useGitStatusPolling } from './components/right-sidebar/useGitStatusPolling' import { useEditorExternalWatch } from './hooks/useEditorExternalWatch' import { useAutoAckViewedAgent } from './hooks/useAutoAckViewedAgent' +import { useDashboardPopoutBridge } from './components/dashboard/useDashboardPopoutBridge' import { useUnreadDockBadge } from './hooks/useUnreadDockBadge' import { resolvePrimarySelectionMiddleClickPaste, @@ -715,6 +716,7 @@ function App(): React.JSX.Element { useEditorExternalWatch() useGlobalFileDrop() useAutoAckViewedAgent() + useDashboardPopoutBridge(settings?.experimentalAgentDashboardPopout === true) useEffect(() => { return onOnboardingReopened(setOnboarding) diff --git a/src/renderer/src/components/dashboard-popout/AgentKanbanBoard.test.tsx b/src/renderer/src/components/dashboard-popout/AgentKanbanBoard.test.tsx new file mode 100644 index 000000000..da866c17a --- /dev/null +++ b/src/renderer/src/components/dashboard-popout/AgentKanbanBoard.test.tsx @@ -0,0 +1,172 @@ +// @vitest-environment happy-dom + +import '@testing-library/jest-dom/vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { cleanup, fireEvent, render, screen, within } from '@testing-library/react' +import type { DashboardCard, DashboardSnapshot } from '../../../../shared/dashboard-snapshot' +import { AgentKanbanBoard } from './AgentKanbanBoard' + +// Stub the card and dialog so the board test stays free of xterm / Radix +// machinery while still exercising the board-owned dialog wiring. +vi.mock('./AgentKanbanCard', () => ({ + AgentKanbanCard: ({ + card, + onOpenTerminal + }: { + card: DashboardCard + onOpenTerminal: (card: DashboardCard) => void + }) => ( +
onOpenTerminal(card)} + > + {card.worktreeName} +
+ ) +})) +vi.mock('./AgentTerminalDialog', () => ({ + AgentTerminalDialog: ({ + card, + onOpenChange + }: { + card: DashboardCard | null + onOpenChange: (open: boolean) => void + }) => ( +
+
+ ) +})) + +function card(overrides: Partial): DashboardCard { + return { + paneKey: Math.random().toString(36), + ptyId: 'p1', + agentType: 'claude', + bucket: 'working', + dotState: 'working', + task: 't', + repoId: 'r1', + worktreeId: 'w1', + tabId: 'tab1', + leafId: 'l1', + repoName: 'Repo', + worktreeName: 'wt', + startedAt: 0, + stateChangedAt: 0, + unseen: false, + ...overrides + } +} + +function renderBoard(cards: DashboardCard[]): void { + const snapshot: DashboardSnapshot = { generatedAt: 1, cards } + render() +} + +const ackAgent = vi.fn(async () => {}) + +describe('AgentKanbanBoard', () => { + beforeEach(() => { + // The board relays seen-acks through the dashboard preload API. + ;(window as unknown as { api: unknown }).api = { dashboard: { ackAgent } } + }) + afterEach(() => { + cleanup() + vi.clearAllMocks() + }) + + it('renders the three fixed columns in order', () => { + renderBoard([]) + const headers = screen.getAllByText(/Needs You|Working|Idle/) + expect(headers.map((h) => h.textContent)).toEqual(['Needs You', 'Working', 'Idle']) + }) + + it('places cards in their bucket column and counts them', () => { + renderBoard([ + card({ bucket: 'attention', worktreeName: 'a1' }), + card({ bucket: 'attention', worktreeName: 'a2' }), + card({ bucket: 'idle', worktreeName: 'i1' }) + ]) + const cards = screen.getAllByTestId('card') + expect(cards).toHaveLength(3) + expect(cards.filter((c) => c.dataset.bucket === 'attention')).toHaveLength(2) + expect(within(document.body).getByText('i1').dataset.bucket).toBe('idle') + expect(screen.getByText('3 total')).toBeTruthy() + }) + + it('shows "None" for empty columns', () => { + renderBoard([card({ bucket: 'working' })]) + // attention and idle are empty → two "None" placeholders. + expect(screen.getAllByText('None')).toHaveLength(2) + }) + + it('orders cards in a column by most recent bucket entry first', () => { + renderBoard([ + card({ bucket: 'working', worktreeName: 'old-move', stateChangedAt: 1000 }), + card({ bucket: 'working', worktreeName: 'new-move', stateChangedAt: 3000 }), + card({ bucket: 'working', worktreeName: 'mid-move', stateChangedAt: 2000 }) + ]) + const names = screen.getAllByTestId('card').map((c) => c.textContent) + expect(names).toEqual(['new-move', 'mid-move', 'old-move']) + }) + + it('keeps the terminal dialog open across bucket moves and card removal', () => { + const agent = card({ paneKey: 'pk-1', bucket: 'idle', worktreeName: 'wt1' }) + const { rerender } = render() + expect(screen.getByTestId('terminal-dialog').dataset.open).toBe('false') + + fireEvent.click(screen.getByTestId('card')) + expect(screen.getByTestId('terminal-dialog').dataset.open).toBe('true') + + // Sending a message flips the agent idle → working; the dialog must + // follow the card to its new bucket instead of closing. + const moved = { ...agent, bucket: 'working' as const, dotState: 'working' as const } + rerender() + expect(screen.getByTestId('terminal-dialog').dataset.open).toBe('true') + expect(screen.getByTestId('terminal-dialog').dataset.bucket).toBe('working') + + // Even a vanished card (pane closed) keeps the dialog up — the user + // dismisses it explicitly, but stale live routing is cleared. + rerender() + expect(screen.getByTestId('terminal-dialog').dataset.open).toBe('true') + expect(screen.getByTestId('terminal-dialog').dataset.ptyId).toBeUndefined() + }) + + it('relays a seen-ack when a dialog opens and when the open agent changes state', () => { + const agent = card({ paneKey: 'pk-ack', bucket: 'idle', unseen: true }) + const { rerender } = render() + // unseen comes straight from the snapshot (the shared ack map). + expect(screen.getByTestId('card').dataset.unseen).toBe('true') + + fireEvent.click(screen.getByTestId('card')) + expect(ackAgent).toHaveBeenCalledWith('pk-ack') + ackAgent.mockClear() + + // The ack round-trips through the main window; the next snapshot mutes it. + rerender( + + ) + expect(screen.getByTestId('card').dataset.unseen).toBe('false') + expect(ackAgent).not.toHaveBeenCalled() + + // A state change while the dialog is open re-acks (watching counts as + // seeing), so the card never flips bold under an open dialog. + rerender( + + ) + expect(ackAgent).toHaveBeenCalledWith('pk-ack') + }) +}) diff --git a/src/renderer/src/components/dashboard-popout/AgentKanbanBoard.tsx b/src/renderer/src/components/dashboard-popout/AgentKanbanBoard.tsx new file mode 100644 index 000000000..b386b5d0c --- /dev/null +++ b/src/renderer/src/components/dashboard-popout/AgentKanbanBoard.tsx @@ -0,0 +1,172 @@ +import { useCallback, useEffect, useMemo, useState } from 'react' +import { + DASHBOARD_BUCKET_ORDER, + type DashboardBucket, + type DashboardCard, + type DashboardSnapshot +} from '../../../../shared/dashboard-snapshot' +import { cn } from '@/lib/utils' +import { AgentKanbanCard } from './AgentKanbanCard' +import { AgentTerminalDialog } from './AgentTerminalDialog' +import './agent-board-transitions.css' +import { translate } from '@/i18n/i18n' + +function bucketLabel(bucket: DashboardBucket): string { + switch (bucket) { + case 'attention': + return translate('dashboardPopout.bucket.attention', 'Needs You') + case 'working': + return translate('dashboardPopout.bucket.working', 'Working') + case 'idle': + return translate('dashboardPopout.bucket.idle', 'Idle') + } +} + +function groupByBucket(cards: DashboardCard[]): Record { + const grouped: Record = { + attention: [], + working: [], + idle: [] + } + for (const card of cards) { + grouped[card.bucket].push(card) + } + // Most-recently-moved first: a card entering a column lands at the top, + // matching the view-transition motion the user just watched. + for (const bucket of DASHBOARD_BUCKET_ORDER) { + grouped[bucket].sort((a, b) => b.stateChangedAt - a.stateChangedAt) + } + return grouped +} + +function KanbanColumn({ + bucket, + cards, + now, + onOpenTerminal +}: { + bucket: DashboardBucket + cards: DashboardCard[] + now: number + onOpenTerminal: (card: DashboardCard) => void +}): React.JSX.Element { + const highlight = bucket === 'attention' && cards.length > 0 + return ( +
+
+ + {bucketLabel(bucket)} + + + {cards.length} + +
+
+ {cards.length === 0 ? ( +

+ {translate('dashboardPopout.bucket.empty', 'None')} +

+ ) : ( + cards.map((card) => ( + + )) + )} +
+
+ ) +} + +/** The pop-out agent board: status columns fed by the relayed snapshot. */ +export function AgentKanbanBoard({ snapshot }: { snapshot: DashboardSnapshot }): React.JSX.Element { + const grouped = useMemo(() => groupByBucket(snapshot.cards), [snapshot.cards]) + const [now, setNow] = useState(() => Date.now()) + + useEffect(() => { + const timer = setInterval(() => setNow(Date.now()), 30_000) + return () => clearInterval(timer) + }, []) + + // The open terminal dialog survives bucket moves: only the paneKey is + // remembered, and the card data is re-resolved from each fresh snapshot. + // The opened card is kept as a fallback so the dialog also survives the + // card vanishing entirely (pane closed) — the user dismisses it explicitly. + // Its live routing is cleared because daemon PTY ids can be reused. + const [openedCard, setOpenedCard] = useState(null) + const dialogCard = useMemo(() => { + if (!openedCard) { + return null + } + return ( + snapshot.cards.find((c) => c.paneKey === openedCard.paneKey) ?? { + ...openedCard, + ptyId: null, + leafId: null + } + ) + }, [snapshot.cards, openedCard]) + const handleDialogOpenChange = useCallback((open: boolean) => { + if (!open) { + setOpenedCard(null) + } + }, []) + + // Seen-state is the app-wide ack map (same signal as the sidebar's bold/mute + // rows): opening a dialog acks the agent in the main renderer via the relay, + // and the next snapshot comes back with unseen=false. + // ?. shields dialog-opening from dev-HMR preload skew (renderer updates + // hot, the preload only on app restart) — acks just no-op until restart. + const handleOpenTerminal = useCallback((card: DashboardCard) => { + void window.api.dashboard.ackAgent?.(card.paneKey) + setOpenedCard(card) + }, []) + // Watching the open dialog counts as seeing state changes as they happen — + // without this, an agent finishing while you watch would re-flag its card. + useEffect(() => { + if (dialogCard?.unseen) { + void window.api.dashboard.ackAgent?.(dialogCard.paneKey) + } + }, [dialogCard?.unseen, dialogCard?.paneKey]) + + return ( +
+
+

+ {translate('dashboardPopout.title', 'Agents')} +

+ + {translate('dashboardPopout.total', '{{count}} total', { + count: snapshot.cards.length + })} + +
+
+ {/* Why: columns share the window width up to a readable cap; mx-auto + centers the capped board so leftover space splits evenly instead of + pooling on the right. In overflow the auto margins collapse to 0, + keeping the left edge reachable while scrolling. */} +
+ {DASHBOARD_BUCKET_ORDER.map((bucket) => ( + + ))} +
+
+ +
+ ) +} diff --git a/src/renderer/src/components/dashboard-popout/AgentKanbanCard.test.tsx b/src/renderer/src/components/dashboard-popout/AgentKanbanCard.test.tsx new file mode 100644 index 000000000..9e2712e2e --- /dev/null +++ b/src/renderer/src/components/dashboard-popout/AgentKanbanCard.test.tsx @@ -0,0 +1,93 @@ +// @vitest-environment happy-dom + +import '@testing-library/jest-dom/vitest' +import { act, cleanup, render, screen } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { DashboardCard } from '../../../../shared/dashboard-snapshot' +import { i18n } from '@/i18n/i18n' +import { AgentKanbanCard } from './AgentKanbanCard' + +const agentIconRender = vi.fn() + +vi.mock('@/lib/agent-catalog', () => ({ + AgentIcon: () => { + agentIconRender() + return + } +})) + +vi.mock('@/components/AgentStateDot', () => ({ + AgentStateDot: () => +})) + +function card(overrides: Partial = {}): DashboardCard { + return { + paneKey: 'tab:leaf', + ptyId: 'pty-1', + agentType: 'claude', + bucket: 'working', + dotState: 'working', + task: 'Review the change', + repoId: 'repo-1', + worktreeId: 'worktree-1', + tabId: 'tab', + leafId: 'leaf', + repoName: 'Orca', + worktreeName: 'dashboard-review', + startedAt: 1_000, + stateChangedAt: 1_000, + unseen: false, + ...overrides + } +} + +describe('AgentKanbanCard', () => { + beforeEach(async () => { + await i18n.changeLanguage('en') + }) + + afterEach(() => { + cleanup() + vi.clearAllMocks() + }) + + it('does not render an invented age when the start time is unknown', () => { + render( + + ) + + expect(screen.queryByText(/\d+d/)).not.toBeInTheDocument() + }) + + it('skips structured-clone rerenders until visible card data or its age changes', () => { + const onOpenTerminal = vi.fn() + const initial = card({ startedAt: 1_000 }) + const { rerender } = render( + + ) + expect(agentIconRender).toHaveBeenCalledTimes(1) + expect(screen.getByText('1m')).toBeInTheDocument() + + rerender() + expect(agentIconRender).toHaveBeenCalledTimes(1) + + rerender( + + ) + expect(agentIconRender).toHaveBeenCalledTimes(2) + expect(screen.getByText('2m')).toBeInTheDocument() + }) + + it('updates the relative age when the UI language changes', async () => { + render( + + ) + expect(screen.getByText('2m')).toBeInTheDocument() + + await act(async () => { + await i18n.changeLanguage('ja') + }) + + expect(screen.getByText('2分')).toBeInTheDocument() + }) +}) diff --git a/src/renderer/src/components/dashboard-popout/AgentKanbanCard.tsx b/src/renderer/src/components/dashboard-popout/AgentKanbanCard.tsx new file mode 100644 index 000000000..ef4d6ddec --- /dev/null +++ b/src/renderer/src/components/dashboard-popout/AgentKanbanCard.tsx @@ -0,0 +1,143 @@ +import { memo } from 'react' +import { useTranslation } from 'react-i18next' +import { AgentIcon } from '@/lib/agent-catalog' +import { agentTypeToIconAgent, formatAgentTypeLabel } from '@/lib/agent-status' +import { AgentStateDot } from '@/components/AgentStateDot' +import { cn } from '@/lib/utils' +import type { DashboardCard } from '../../../../shared/dashboard-snapshot' +import { translate } from '@/i18n/i18n' + +/** Compact "started N ago" (the card is glanceable — coarse units are fine). */ +function formatStartedAgo(startedAt: number, now: number): string { + const seconds = Math.max(0, Math.floor((now - startedAt) / 1000)) + if (seconds < 60) { + return translate('dashboardPopout.card.time.justNow', 'just now') + } + const minutes = Math.floor(seconds / 60) + if (minutes < 60) { + return translate('dashboardPopout.card.time.minutes', '{{count}}m', { count: minutes }) + } + const hours = Math.floor(minutes / 60) + if (hours < 24) { + return translate('dashboardPopout.card.time.hours', '{{count}}h', { count: hours }) + } + return translate('dashboardPopout.card.time.days', '{{count}}d', { + count: Math.floor(hours / 24) + }) +} + +function sameCard(a: DashboardCard, b: DashboardCard): boolean { + return ( + a.paneKey === b.paneKey && + a.ptyId === b.ptyId && + a.agentType === b.agentType && + a.bucket === b.bucket && + a.dotState === b.dotState && + a.task === b.task && + a.lastUserMessage === b.lastUserMessage && + a.lastAgentMessage === b.lastAgentMessage && + a.repoId === b.repoId && + a.worktreeId === b.worktreeId && + a.tabId === b.tabId && + a.leafId === b.leafId && + a.repoName === b.repoName && + a.worktreeName === b.worktreeName && + a.startedAt === b.startedAt && + a.stateChangedAt === b.stateChangedAt && + a.unseen === b.unseen && + a.askSummary === b.askSummary + ) +} + +type AgentKanbanCardProps = { + card: DashboardCard + now: number + /** Opens the board-level terminal dialog. The dialog is NOT owned by the + * card: bucket moves remount the card, and an embedded dialog would close + * the chat mid-conversation. */ + onOpenTerminal: (card: DashboardCard) => void +} + +/** One agent on the kanban board. Clicking opens the board's live terminal dialog. */ +export const AgentKanbanCard = memo( + function AgentKanbanCard({ card, now, onOpenTerminal }: AgentKanbanCardProps): React.JSX.Element { + useTranslation() + + return ( + + ) + }, + (previous, next) => + previous.onOpenTerminal === next.onOpenTerminal && + sameCard(previous.card, next.card) && + (previous.card.startedAt <= 0 || + formatStartedAgo(previous.card.startedAt, previous.now) === + formatStartedAgo(next.card.startedAt, next.now)) +) diff --git a/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.tsx b/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.tsx new file mode 100644 index 000000000..76177fe95 --- /dev/null +++ b/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.tsx @@ -0,0 +1,100 @@ +import { useCallback } from 'react' +import { AgentIcon } from '@/lib/agent-catalog' +import { agentTypeToIconAgent, formatAgentTypeLabel } from '@/lib/agent-status' +import { agentStateLabel } from '@/components/AgentStateDot' +import { Dialog, DialogClose, DialogContent, DialogTitle } from '@/components/ui/dialog' +import { Button } from '@/components/ui/button' +import type { DashboardCard } from '../../../../shared/dashboard-snapshot' +import { AgentTerminalPreview } from './AgentTerminalPreview' +import { translate } from '@/i18n/i18n' + +type AgentTerminalDialogProps = { + /** The agent shown in the dialog; null renders the dialog closed. */ + card: DashboardCard | null + onOpenChange: (open: boolean) => void +} + +/** + * The near-fullscreen live-terminal dialog for one agent. Hosted by the BOARD, + * not the card: sending a message flips the agent's bucket, which remounts its + * card in another column — a card-owned dialog would close mid-conversation. + * Only an explicit close (button, click-outside, Esc outside the terminal) + * dismisses it. + */ +export function AgentTerminalDialog({ + card, + onOpenChange +}: AgentTerminalDialogProps): React.JSX.Element { + const reveal = useCallback(() => { + if (!card) { + return + } + void window.api.dashboard.revealAgent({ + repoId: card.repoId, + worktreeId: card.worktreeId, + tabId: card.tabId, + leafId: card.leafId + }) + }, [card]) + + return ( + + {card ? ( + { + if (e.target instanceof HTMLElement && e.target.closest('.xterm')) { + e.preventDefault() + } + }} + // Why: the preview focuses its terminal once the snapshot paints; + // Radix's default focus target would tug focus away first. + onOpenAutoFocus={(e) => { + if (card.ptyId) { + e.preventDefault() + } + }} + > +
+ + + {card.worktreeName} + + + {formatAgentTypeLabel(card.agentType)} · {agentStateLabel(card.dotState)} + +
+ {card.ptyId ? ( + + ) : ( +
+ {translate( + 'dashboardPopout.terminal.closed', + "No live terminal — this agent's pane has closed." + )} +
+ )} +
+ + + + + + +
+
+ ) : null} +
+ ) +} diff --git a/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx b/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx new file mode 100644 index 000000000..4102e0fe5 --- /dev/null +++ b/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx @@ -0,0 +1,220 @@ +// @vitest-environment happy-dom + +import '@testing-library/jest-dom/vitest' +import { act, cleanup, render, waitFor } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const terminalHarness = vi.hoisted(() => ({ + instances: [] as { + write: ReturnType + writeCallbacks: (() => void)[] + onDataListener: ((data: string) => void) | null + dispose: ReturnType + resize: ReturnType + reset: ReturnType + }[], + userInputListener: null as (() => void) | null, + userInputDispose: vi.fn() +})) + +vi.mock('@xterm/xterm', () => ({ + Terminal: class { + rows = 24 + buffer = { active: { cursorY: 0 } } + writeCallbacks: (() => void)[] = [] + onDataListener: ((data: string) => void) | null = null + write = vi.fn((_data: string, callback?: () => void) => { + if (callback) { + this.writeCallbacks.push(callback) + } + }) + open = vi.fn() + focus = vi.fn() + dispose = vi.fn() + resize = vi.fn() + reset = vi.fn() + onData = vi.fn((listener: (data: string) => void) => { + this.onDataListener = listener + return { dispose: vi.fn() } + }) + + constructor() { + terminalHarness.instances.push(this) + } + } +})) +vi.mock('@/lib/pane-manager/pane-terminal-options', () => ({ + buildDefaultTerminalOptions: () => ({}) +})) +vi.mock('@/components/terminal-pane/terminal-user-input-signal', () => ({ + subscribeToTerminalUserInput: (_terminal: unknown, listener: () => void) => { + terminalHarness.userInputListener = listener + return { dispose: terminalHarness.userInputDispose } + } +})) +vi.mock('@/components/terminal-pane/use-system-prefers-dark', () => ({ + useSystemPrefersDark: () => false +})) +vi.mock('@/store', () => ({ + useAppStore: (selector: (state: { settings: null }) => unknown) => selector({ settings: null }) +})) + +import { AgentTerminalPreview } from './AgentTerminalPreview' + +describe('AgentTerminalPreview', () => { + const input = vi.fn(async () => true) + const ack = vi.fn(async () => {}) + const unsubscribe = vi.fn(async () => {}) + const connect = vi.fn() + let emitData: ((payload: unknown) => void) | null + + beforeEach(() => { + terminalHarness.instances.length = 0 + terminalHarness.userInputListener = null + emitData = null + connect.mockResolvedValue({ + snapshot: { data: '', cols: 80, rows: 24, seq: 1 }, + replay: [] + }) + Object.assign(window, { + api: { + terminalPreview: { + connect, + input, + ack, + unsubscribe, + onData: (listener: (payload: unknown) => void) => { + emitData = listener + return vi.fn() + } + } + } + }) + }) + + afterEach(() => { + cleanup() + vi.clearAllMocks() + }) + + it('routes signaled user input while a live write parses and drops parser replies', async () => { + render() + await waitFor(() => expect(terminalHarness.instances).toHaveLength(1)) + const terminal = terminalHarness.instances[0]! + await waitFor(() => expect(terminal.onDataListener).not.toBeNull()) + + act(() => { + emitData?.({ type: 'data', ptyId: 'pty-1', data: '\x1b[6n', bytes: 4 }) + }) + expect(terminal.write).toHaveBeenCalledWith('\x1b[6n', expect.any(Function)) + + act(() => { + terminalHarness.userInputListener?.() + terminal.onDataListener?.('k') + terminal.onDataListener?.('\x1b[1;1R') + }) + expect(input).toHaveBeenCalledTimes(1) + expect(input).toHaveBeenCalledWith('pty-1', 'k') + + act(() => terminal.writeCallbacks.shift()?.()) + expect(ack).toHaveBeenCalledWith('pty-1', 4) + }) + + it('keeps the existing terminal visible while a resync snapshot is captured', async () => { + let resolveRefresh!: (value: { + snapshot: { data: string; cols: number; rows: number; seq: number } + replay: string[] + }) => void + connect + .mockResolvedValueOnce({ + snapshot: { data: 'first', cols: 80, rows: 24, seq: 1 }, + replay: [] + }) + .mockImplementationOnce( + () => + new Promise((resolve) => { + resolveRefresh = resolve + }) + ) + const view = render() + await waitFor(() => expect(terminalHarness.instances).toHaveLength(1)) + const terminal = terminalHarness.instances[0]! + + act(() => emitData?.({ type: 'resync', ptyId: 'pty-1' })) + await waitFor(() => expect(connect).toHaveBeenCalledTimes(2)) + expect(terminalHarness.instances).toHaveLength(1) + expect(terminal.dispose).not.toHaveBeenCalled() + expect(terminal.reset).not.toHaveBeenCalled() + expect(view.queryByText(/No live terminal/)).not.toBeInTheDocument() + + await act(async () => { + resolveRefresh({ + snapshot: { data: 'second', cols: 100, rows: 30, seq: 2 }, + replay: [] + }) + }) + await waitFor(() => expect(terminal.reset).toHaveBeenCalledTimes(1)) + expect(terminal.resize).toHaveBeenCalledWith(100, 30) + expect(terminalHarness.instances).toHaveLength(1) + expect(terminal.dispose).not.toHaveBeenCalled() + expect(view.queryByText(/No live terminal/)).not.toBeInTheDocument() + }) + + it('disposes a stale terminal when resync confirms the pty is gone', async () => { + connect + .mockResolvedValueOnce({ + snapshot: { data: 'first', cols: 80, rows: 24, seq: 1 }, + replay: [] + }) + .mockResolvedValueOnce({ snapshot: null, replay: [] }) + const view = render() + await waitFor(() => expect(terminalHarness.instances).toHaveLength(1)) + const terminal = terminalHarness.instances[0]! + + act(() => emitData?.({ type: 'resync', ptyId: 'pty-1' })) + + await waitFor(() => expect(view.getByText(/No live terminal/)).toBeInTheDocument()) + expect(terminal.dispose).toHaveBeenCalledTimes(1) + expect(terminalHarness.userInputDispose).toHaveBeenCalledTimes(1) + expect(unsubscribe).toHaveBeenCalledWith('pty-1') + }) + + it('connects a replacement pty after the previous pty was gone', async () => { + connect.mockResolvedValueOnce({ snapshot: null, replay: [] }).mockResolvedValueOnce({ + snapshot: { data: 'replacement', cols: 80, rows: 24, seq: 1 }, + replay: [] + }) + const view = render() + await waitFor(() => expect(view.getByText(/No live terminal/)).toBeInTheDocument()) + + view.rerender() + + await waitFor(() => expect(terminalHarness.instances).toHaveLength(1)) + expect(connect).toHaveBeenLastCalledWith('pty-live', { scrollbackRows: 24 }) + expect(view.queryByText(/No live terminal/)).not.toBeInTheDocument() + }) + + it('delays repeated capture after an overflow and cancels the retry on unmount', async () => { + vi.useFakeTimers() + connect.mockResolvedValue({ + snapshot: { data: 'screen', cols: 80, rows: 24, seq: 1 }, + replay: [], + resyncRequired: true + }) + const view = render() + await vi.waitFor(() => expect(terminalHarness.instances).toHaveLength(1)) + const terminal = terminalHarness.instances[0]! + expect(connect).toHaveBeenCalledTimes(1) + + act(() => terminal.writeCallbacks.splice(0).forEach((callback) => callback())) + await vi.advanceTimersByTimeAsync(149) + expect(connect).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(1) + expect(connect).toHaveBeenCalledTimes(2) + + act(() => terminal.writeCallbacks.splice(0).forEach((callback) => callback())) + view.unmount() + await vi.advanceTimersByTimeAsync(150) + expect(connect).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.tsx b/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.tsx new file mode 100644 index 000000000..129bcb35c --- /dev/null +++ b/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.tsx @@ -0,0 +1,288 @@ +import { useEffect, useMemo, useRef, useState } from 'react' +import { Terminal } from '@xterm/xterm' +import '@xterm/xterm/css/xterm.css' +import { buildDefaultTerminalOptions } from '@/lib/pane-manager/pane-terminal-options' +import { subscribeToTerminalUserInput } from '@/components/terminal-pane/terminal-user-input-signal' +import { composeActiveTerminalTheme } from '@/components/terminal-pane/terminal-appearance' +import { useSystemPrefersDark } from '@/components/terminal-pane/use-system-prefers-dark' +import { translate } from '@/i18n/i18n' +import { getBuiltinTheme, resolveEffectiveTerminalAppearance } from '@/lib/terminal-theme' +import { cn } from '@/lib/utils' +import { useAppStore } from '@/store' +import type { TerminalPreviewDataPayload } from '../../../../shared/terminal-preview' + +const PREVIEW_SCROLLBACK_ROWS = 24 +const FALLBACK_COLS = 80 +const FALLBACK_ROWS = 24 +const RESYNC_RETRY_DELAY_MS = 150 + +function clamp(value: number, min: number, max: number): number { + return Math.min(max, Math.max(min, value)) +} + +/** + * Live peek at an agent's terminal, streaming from the main process's per-PTY + * headless emulator. The terminal is created at the pane's REAL cols/rows — + * the serialized ANSI was produced at those dimensions, and replaying it into + * a narrower terminal rewraps every full-width line into garbage. The box + * stays fixed; the oversized terminal is scaled down to fit the width and + * bottom-anchored so the tail (prompt, status line) stays visible. Keystrokes + * pass through to the PTY; DOM renderer so it never grabs a WebGL context. + */ +export function AgentTerminalPreview({ ptyId }: { ptyId: string }): React.JSX.Element { + const containerRef = useRef(null) + const settings = useAppStore((state) => state.settings) + const systemPrefersDark = useSystemPrefersDark() + const terminalTheme = useMemo(() => { + if (!settings) { + return null + } + const appearance = resolveEffectiveTerminalAppearance(settings, systemPrefersDark) + return composeActiveTerminalTheme( + appearance.theme ?? getBuiltinTheme(appearance.themeName), + settings + ) + }, [settings, systemPrefersDark]) + // A null snapshot means no serializer knows this pty (it died or was never + // spawned this session) — say so instead of painting a silent blank terminal. + const [ptyGone, setPtyGone] = useState(false) + + useEffect(() => { + setPtyGone(false) + const container = containerRef.current + if (!container) { + return + } + let disposed = false + let terminal: Terminal | null = null + let offData: (() => void) | null = null + let userInputDisposable: { dispose: () => void } | null = null + let refreshInFlight = false + let refreshAgain = false + let retryTimer: ReturnType | null = null + const pendingLivePayloads: Extract[] = [] + + const fitToBox = (): void => { + const screen = container.querySelector('.xterm-screen') + const box = container.parentElement + if (!screen || !box || !terminal) { + return + } + const scale = Math.min(1, box.clientWidth / Math.max(1, screen.offsetWidth)) + container.style.transform = scale < 1 ? `scale(${scale})` : '' + // Anchor whichever end keeps the CURSOR row in view when the terminal is + // taller than the box: a fresh shell prompts at the TOP of its screen + // (blind bottom-anchoring clipped it away), while a busy TUI keeps its + // action at the bottom. + const cellHeight = screen.offsetHeight / Math.max(1, terminal.rows) + const cursorBottom = (terminal.buffer.active.cursorY + 1) * cellHeight * scale + const anchorTop = cursorBottom <= box.clientHeight + box.style.alignItems = anchorTop ? 'flex-start' : 'flex-end' + container.style.transformOrigin = anchorTop ? 'top left' : 'bottom left' + } + // Re-fit after every parsed write (cursor may move ends); rAF coalesces. + let fitScheduled = false + const scheduleFit = (): void => { + if (fitScheduled) { + return + } + fitScheduled = true + requestAnimationFrame(() => { + fitScheduled = false + fitToBox() + }) + } + + let replayDepth = 0 + const writeReplayed = (chunk: string, onDone?: () => void): void => { + replayDepth++ + terminal?.write(chunk, () => { + replayDepth-- + scheduleFit() + onDone?.() + }) + } + + const writeLive = (payload: Extract): void => { + if (!terminal) { + pendingLivePayloads.push(payload) + return + } + writeReplayed(payload.data, () => { + if (!disposed) { + void window.api.terminalPreview.ack(ptyId, payload.bytes) + } + }) + } + + const installInputRouting = (): void => { + if (!terminal) { + return + } + let pendingUserInputSignals = 0 + userInputDisposable = subscribeToTerminalUserInput(terminal, () => { + pendingUserInputSignals = Math.min(32, pendingUserInputSignals + 1) + }) + terminal.onData((data) => { + const signaledUserInput = pendingUserInputSignals > 0 + if (signaledUserInput) { + pendingUserInputSignals-- + } + // Why: core's signal distinguishes real input from parser replies, so typing survives live replay without forwarding synthetic CPR/DA bytes. + if (userInputDisposable ? !signaledUserInput : replayDepth > 0) { + return + } + void window.api.terminalPreview.input(ptyId, data) + }) + } + + const replayConnection = ( + connection: Awaited>, + replaceExisting: boolean, + requestRefresh: () => void + ): void => { + const snap = connection.snapshot! + if (!terminal) { + terminal = new Terminal({ + ...buildDefaultTerminalOptions(), + cols: clamp(snap.cols ?? FALLBACK_COLS, 2, 500), + rows: clamp(snap.rows ?? FALLBACK_ROWS, 2, 200), + theme: terminalTheme ?? undefined, + scrollback: 1000 + }) + try { + terminal.open(container) + } catch { + terminal.dispose() + terminal = null + return + } + installInputRouting() + } else if (replaceExisting) { + // Why: keep the old frame visible during capture, then atomically replace it once the authoritative snapshot arrives. + terminal.resize( + clamp(snap.cols ?? FALLBACK_COLS, 2, 500), + clamp(snap.rows ?? FALLBACK_ROWS, 2, 200) + ) + terminal.reset() + } + if (snap.scrollbackAnsi) { + writeReplayed(snap.scrollbackAnsi) + } + if (snap.data) { + writeReplayed(snap.data) + } + if (snap.pendingEscapeTailAnsi) { + writeReplayed(snap.pendingEscapeTailAnsi) + } + for (const data of connection.replay) { + writeReplayed(data) + } + for (const payload of pendingLivePayloads.splice(0)) { + writeLive(payload) + } + if (connection.resyncRequired) { + refreshAgain = false + // Why: sustained output can overflow every capture; delay retries so recovery cannot spin two serializations per event-loop turn. + writeReplayed('', () => { + if (disposed || retryTimer) { + return + } + retryTimer = setTimeout(() => { + retryTimer = null + requestRefresh() + }, RESYNC_RETRY_DELAY_MS) + }) + } else if (refreshAgain) { + refreshAgain = false + // Queue behind every replay write so replacement never clears a half-parsed frame. + writeReplayed('', requestRefresh) + } + scheduleFit() + terminal.focus() + } + + const setup = async (replaceExisting = false): Promise => { + if (refreshInFlight) { + refreshAgain = true + return + } + refreshInFlight = true + const connection = await window.api.terminalPreview.connect(ptyId, { + scrollbackRows: PREVIEW_SCROLLBACK_ROWS + }) + if (disposed) { + return + } + const snap = connection.snapshot + if (!snap) { + refreshInFlight = false + setPtyGone(true) + offData?.() + offData = null + userInputDisposable?.dispose() + userInputDisposable = null + terminal?.dispose() + terminal = null + void window.api.terminalPreview.unsubscribe(ptyId) + return + } + refreshInFlight = false + if (!connection.resyncRequired && retryTimer) { + clearTimeout(retryTimer) + retryTimer = null + } + replayConnection(connection, replaceExisting, () => void setup(true)) + } + + offData = window.api.terminalPreview.onData((payload) => { + if (payload.ptyId !== ptyId) { + return + } + if (payload.type === 'resync') { + void setup(true) + return + } + writeLive(payload) + }) + + void setup() + + return () => { + disposed = true + if (retryTimer) { + clearTimeout(retryTimer) + } + offData?.() + userInputDisposable?.dispose() + void window.api.terminalPreview.unsubscribe(ptyId) + terminal?.dispose() + } + }, [ptyId, terminalTheme]) + + return ( + // Why: a size FIXED by the viewport (not shrink-to-fit) + overflow-hidden + // keeps the dialog stable no matter how wide/tall the pane's serialized + // buffer is. The terminal keeps the pane's true dimensions and is scaled/ + // clipped to fit; fitToBox anchors whichever end keeps the cursor in view. +
+ {ptyGone ? ( +
+ {translate( + 'dashboardPopout.terminal.closed', + "No live terminal — this agent's pane has closed." + )} +
+ ) : null} +
+
+
+
+ ) +} diff --git a/src/renderer/src/components/dashboard-popout/DashboardPopoutRoot.tsx b/src/renderer/src/components/dashboard-popout/DashboardPopoutRoot.tsx new file mode 100644 index 000000000..a857b298b --- /dev/null +++ b/src/renderer/src/components/dashboard-popout/DashboardPopoutRoot.tsx @@ -0,0 +1,17 @@ +import { AgentKanbanBoard } from './AgentKanbanBoard' +import { useDashboardSnapshot } from './useDashboardSnapshot' + +type DashboardPopoutRootProps = { + /** The layout requested via popout.html?view=. Only "kanban" exists + * today; unknown views fall back to it. */ + view: string | null +} + +/** + * Root of the pop-out dashboard window. Subscribes to the live snapshot relayed + * from the main window and renders the requested layout. + */ +export function DashboardPopoutRoot(_props: DashboardPopoutRootProps): React.JSX.Element { + const snapshot = useDashboardSnapshot() + return +} diff --git a/src/renderer/src/components/dashboard-popout/agent-board-transitions.css b/src/renderer/src/components/dashboard-popout/agent-board-transitions.css new file mode 100644 index 000000000..96c407e11 --- /dev/null +++ b/src/renderer/src/components/dashboard-popout/agent-board-transitions.css @@ -0,0 +1,54 @@ +/* + * View-transition tuning for the agent board. Each card carries a unique + * `view-transition-name` (agentcard-…), so when a card changes column the + * browser morphs it from its old position to the new one. Only loaded in the + * pop-out (imported by AgentKanbanBoard), so these document-global pseudo rules + * never affect the main window. + */ + +/* Card move/resize easing (applies to every transition group). */ +::view-transition-group(*) { + animation-duration: 260ms; + animation-timing-function: cubic-bezier(0.2, 0, 0, 1); +} + +/* The columns/background don't move, so skip the root cross-fade — it would + * otherwise briefly double-image the lane heights as a card leaves/joins. */ +::view-transition-old(root), +::view-transition-new(root) { + animation-duration: 0s; +} + +/* + * Enter/exit. A card that MOVES columns has both an old and a new image, so it + * is not `:only-child` and just morphs position (above). A genuinely new or + * removed card has only one image (`:only-child`) — fade + scale it. + */ +@keyframes agent-card-enter { + from { + opacity: 0; + transform: scale(0.96); + } +} +@keyframes agent-card-exit { + to { + opacity: 0; + transform: scale(0.96); + } +} +::view-transition-new(*):only-child { + animation: 240ms cubic-bezier(0.2, 0, 0, 1) both agent-card-enter; +} +::view-transition-old(*):only-child { + animation: 180ms cubic-bezier(0.4, 0, 1, 1) both agent-card-exit; +} + +/* Respect reduced-motion — the JS also skips startViewTransition, but guard the + * pseudo animations too. */ +@media (prefers-reduced-motion: reduce) { + ::view-transition-group(*), + ::view-transition-old(*), + ::view-transition-new(*) { + animation: none !important; + } +} diff --git a/src/renderer/src/components/dashboard-popout/useDashboardSnapshot.ts b/src/renderer/src/components/dashboard-popout/useDashboardSnapshot.ts new file mode 100644 index 000000000..0a35499ea --- /dev/null +++ b/src/renderer/src/components/dashboard-popout/useDashboardSnapshot.ts @@ -0,0 +1,55 @@ +import { useEffect, useRef, useState } from 'react' +import { flushSync } from 'react-dom' +import { + EMPTY_DASHBOARD_SNAPSHOT, + type DashboardSnapshot +} from '../../../../shared/dashboard-snapshot' + +/** Which column each card sits in — the only thing a view transition should + * animate on. Content-only updates (such as new messages) must not. */ +function columnSignature(snapshot: DashboardSnapshot): string { + return snapshot.cards + .map((card) => `${card.paneKey}:${card.bucket}`) + .sort() + .join(',') +} + +function prefersReducedMotion(): boolean { + return window.matchMedia?.('(prefers-reduced-motion: reduce)').matches === true +} + +/** + * Pop-out side of the dashboard bridge: subscribe to snapshots relayed from the + * main window and request an initial one on mount. When a card changes column + * (or one appears/disappears), the update is wrapped in a View Transition so + * the browser morphs each card from its old position to its new one. + */ +export function useDashboardSnapshot(): DashboardSnapshot { + const [snapshot, setSnapshot] = useState(EMPTY_DASHBOARD_SNAPSHOT) + const columnSignatureRef = useRef('') + + useEffect(() => { + const apply = (next: DashboardSnapshot): void => { + const nextSignature = columnSignature(next) + const layoutChanged = nextSignature !== columnSignatureRef.current + columnSignatureRef.current = nextSignature + + const startViewTransition = document.startViewTransition?.bind(document) + if (!layoutChanged || prefersReducedMotion() || !startViewTransition) { + setSnapshot(next) + return + } + // flushSync so the DOM reflects `next` synchronously inside the transition + // callback — the browser captures the "after" state from it. + startViewTransition(() => { + flushSync(() => setSnapshot(next)) + }) + } + + const unsubscribe = window.api.dashboard.onSnapshot(apply) + void window.api.dashboard.requestSnapshot() + return unsubscribe + }, []) + + return snapshot +} diff --git a/src/renderer/src/components/dashboard/build-dashboard-snapshot.test.ts b/src/renderer/src/components/dashboard/build-dashboard-snapshot.test.ts new file mode 100644 index 000000000..8afb5bee8 --- /dev/null +++ b/src/renderer/src/components/dashboard/build-dashboard-snapshot.test.ts @@ -0,0 +1,186 @@ +import { describe, expect, it } from 'vitest' +import { buildDashboardSnapshot, type DashboardSnapshotState } from './build-dashboard-snapshot' +import { + AGENT_STATUS_STALE_AFTER_MS, + type AgentStatusEntry +} from '../../../../shared/agent-status-types' +import { makePaneKey } from '../../../../shared/stable-pane-id' + +const NOW = 1_000_000_000 +const TAB_ID = 'tab1' +const LEAF_ID = '11111111-1111-4111-8111-111111111111' +const GONE_LEAF_ID = '22222222-2222-4222-8222-222222222222' +const PANE_KEY = makePaneKey(TAB_ID, LEAF_ID) + +function entry(overrides: Partial): AgentStatusEntry { + return { + paneKey: PANE_KEY, + state: 'working', + prompt: 'do the thing', + updatedAt: NOW, + stateStartedAt: NOW - 5000, + stateHistory: [], + agentType: 'claude', + tabId: TAB_ID, + worktreeId: 'w1', + ...overrides + } +} + +function tab(): unknown { + return { + id: TAB_ID, + ptyId: 'pty1', + worktreeId: 'w1', + title: 'agent', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: NOW + } +} + +function baseState(overrides: Partial): DashboardSnapshotState { + return { + repos: [{ id: 'r1', path: '/r1', displayName: 'Repo One', badgeColor: '#000' }], + worktreesByRepo: { r1: [{ id: 'w1', displayName: 'wt-one', isArchived: false }] }, + tabsByWorktree: { w1: [tab()] }, + agentStatusByPaneKey: {}, + retainedAgentsByPaneKey: {}, + migrationUnsupportedByPtyId: {}, + runtimeAgentOrchestrationByPaneKey: {}, + terminalLayoutsByTabId: { + [TAB_ID]: { + root: { type: 'leaf', leafId: LEAF_ID }, + activeLeafId: LEAF_ID, + ptyIdsByLeafId: { [LEAF_ID]: 'pty1' } + } + }, + ptyIdsByTabId: { [TAB_ID]: ['pty1'] }, + runtimePaneTitlesByTabId: {}, + acknowledgedAgentsByPaneKey: {}, + ...overrides + } as unknown as DashboardSnapshotState +} + +describe('buildDashboardSnapshot', () => { + it('maps a live working agent to the working bucket with a resolved ptyId', () => { + const snapshot = buildDashboardSnapshot( + baseState({ + agentStatusByPaneKey: { + [PANE_KEY]: entry({ state: 'working', lastAssistantMessage: 'Working on it now' }) + } + }), + NOW + ) + expect(snapshot.cards).toHaveLength(1) + const card = snapshot.cards[0] + expect(card.bucket).toBe('working') + expect(card.dotState).toBe('working') + expect(card.ptyId).toBe('pty1') + expect(card.worktreeName).toBe('wt-one') + expect(card.repoName).toBe('Repo One') + expect(card.leafId).toBe(LEAF_ID) + expect(card.lastUserMessage).toBe('do the thing') + expect(card.lastAgentMessage).toBe('Working on it now') + // Column ordering key: when the agent entered its current state. + expect(card.stateChangedAt).toBe(NOW - 5000) + // No ack yet → unseen, mirroring the sidebar's unvisited signal. + expect(card.unseen).toBe(true) + }) + + it('nulls ptyId when the layout entry points at a dead pty', () => { + const snapshot = buildDashboardSnapshot( + baseState({ + agentStatusByPaneKey: { [PANE_KEY]: entry({}) }, + // Layout still remembers pty1 (it survives restarts), but the live + // set says that pty is gone — e.g. a parked tab after an app restart. + ptyIdsByTabId: { [TAB_ID]: [] } + }), + NOW + ) + expect(snapshot.cards[0].ptyId).toBeNull() + }) + + it('mutes unseen once the agent is acknowledged after its state change', () => { + const snapshot = buildDashboardSnapshot( + baseState({ + agentStatusByPaneKey: { [PANE_KEY]: entry({}) }, + acknowledgedAgentsByPaneKey: { [PANE_KEY]: NOW - 1000 } + }), + NOW + ) + // ack (NOW-1000) is after stateStartedAt (NOW-5000) → seen. + expect(snapshot.cards[0].unseen).toBe(false) + }) + + it('does not mark title-derived rows unseen from synthetic timestamps', () => { + const snapshot = buildDashboardSnapshot( + baseState({ + agentStatusByPaneKey: {}, + runtimePaneTitlesByTabId: { + [TAB_ID]: { 1: '⠋ Claude Code' } + } + }), + NOW + ) + + expect(snapshot.cards).toHaveLength(1) + expect(snapshot.cards[0].startedAt).toBe(0) + expect(snapshot.cards[0].unseen).toBe(false) + }) + + it.each(['blocked', 'waiting'] as const)( + 'routes %s agents to the attention bucket with an ask summary', + (state) => { + const snapshot = buildDashboardSnapshot( + baseState({ + agentStatusByPaneKey: { + [PANE_KEY]: entry({ state, interactivePrompt: 'Approve deploy?' }) + } + }), + NOW + ) + expect(snapshot.cards[0].bucket).toBe('attention') + expect(snapshot.cards[0].dotState).toBe(state) + expect(snapshot.cards[0].askSummary).toBe('Approve deploy?') + } + ) + + it('decays a stale working agent to the idle bucket', () => { + const snapshot = buildDashboardSnapshot( + baseState({ + agentStatusByPaneKey: { + [PANE_KEY]: entry({ + state: 'working', + updatedAt: NOW - AGENT_STATUS_STALE_AFTER_MS - 1000 + }) + } + }), + NOW + ) + expect(snapshot.cards[0].bucket).toBe('idle') + expect(snapshot.cards[0].dotState).toBe('idle') + }) + + it('folds retained done agents into the idle bucket, keeping a done dot', () => { + const donePaneKey = makePaneKey(TAB_ID, GONE_LEAF_ID) + const snapshot = buildDashboardSnapshot( + baseState({ + retainedAgentsByPaneKey: { + [donePaneKey]: { + entry: entry({ paneKey: donePaneKey, state: 'done' }), + worktreeId: 'w1', + tab: tab() as never, + agentType: 'claude', + startedAt: NOW - 60_000 + } as never + } + }), + NOW + ) + const done = snapshot.cards.find((c) => c.dotState === 'done') + expect(done).toBeDefined() + expect(done?.bucket).toBe('idle') + }) +}) diff --git a/src/renderer/src/components/dashboard/build-dashboard-snapshot.ts b/src/renderer/src/components/dashboard/build-dashboard-snapshot.ts new file mode 100644 index 000000000..6a44e73c8 --- /dev/null +++ b/src/renderer/src/components/dashboard/build-dashboard-snapshot.ts @@ -0,0 +1,172 @@ +import type { AppState } from '@/store/types' +import type { + DashboardBucket, + DashboardCard, + DashboardCardDotState, + DashboardSnapshot +} from '../../../../shared/dashboard-snapshot' +import { parsePaneKey } from '../../../../shared/stable-pane-id' +import { migrationUnsupportedToAgentStatusEntry } from '@/lib/migration-unsupported-agent-entry' +import { applyAgentRowLineage } from './agent-row-lineage' +import type { DashboardAgentRow } from './useDashboardData' +import { buildWorktreeAgentRows } from '../sidebar/worktree-agent-rows' +import { + selectLiveAgentStatusEntriesForWorktree, + selectMigrationUnsupportedEntriesForWorktree, + selectRetainedAgentEntriesForWorktree, + selectRuntimeAgentOrchestrationForWorktree, + selectTerminalLayoutsForWorktree +} from '../sidebar/worktree-agent-row-selectors' +import { + selectLivePtyIdsForWorktree, + selectRuntimePaneTitlesForWorktree +} from '../sidebar/worktree-card-status-inputs' + +/** The store slices the snapshot builder reads. Kept as a Pick so unit tests + * can pass a partial store without constructing the whole AppState. */ +export type DashboardSnapshotState = Pick< + AppState, + | 'repos' + | 'worktreesByRepo' + | 'tabsByWorktree' + | 'agentStatusByPaneKey' + | 'retainedAgentsByPaneKey' + | 'migrationUnsupportedByPtyId' + | 'runtimeAgentOrchestrationByPaneKey' + | 'terminalLayoutsByTabId' + | 'ptyIdsByTabId' + | 'runtimePaneTitlesByTabId' + | 'acknowledgedAgentsByPaneKey' +> + +function bucketForState(state: DashboardAgentRow['state']): DashboardBucket { + switch (state) { + case 'working': + return 'working' + // 'done' folds into Idle — it's only reported when a completion hook fires, + // so it's not a reliable standalone column. The card keeps a done dot. + case 'done': + case 'idle': + return 'idle' + // blocked | waiting — the agent needs the user. + case 'blocked': + case 'waiting': + return 'attention' + } +} + +function rowTask(row: DashboardAgentRow): string { + return (row.entry.orchestration?.taskTitle ?? '').trim() || (row.entry.prompt ?? '').trim() +} + +function nonEmpty(value: string | undefined): string | undefined { + const trimmed = (value ?? '').trim() + return trimmed.length > 0 ? trimmed : undefined +} + +/** + * Derive the serializable dashboard snapshot from the live renderer store. + * Reuses the exact per-worktree row machinery the sidebar uses + * (buildWorktreeAgentRows + the indexed selectors), then flattens every + * worktree's rows into presentational cards. Subagent/child rows are excluded + * from the board (out of scope for v1). + */ +export function buildDashboardSnapshot( + state: DashboardSnapshotState, + now: number +): DashboardSnapshot { + const cards: DashboardCard[] = [] + + for (const repo of state.repos ?? []) { + for (const worktree of state.worktreesByRepo?.[repo.id] ?? []) { + if (worktree.isArchived) { + continue + } + const worktreeId = worktree.id + const liveEntries = selectLiveAgentStatusEntriesForWorktree(state, worktreeId) + const migrationUnsupported = selectMigrationUnsupportedEntriesForWorktree(state, worktreeId) + const entries = + migrationUnsupported.length > 0 + ? [ + ...liveEntries, + ...migrationUnsupported.flatMap((unsupported) => { + const entry = migrationUnsupportedToAgentStatusEntry(unsupported) + return entry ? [entry] : [] + }) + ] + : liveEntries + const terminalLayoutsByTabId = selectTerminalLayoutsForWorktree(state, worktreeId) + + const rows = applyAgentRowLineage( + buildWorktreeAgentRows({ + tabs: state.tabsByWorktree[worktreeId] ?? [], + entries, + retained: selectRetainedAgentEntriesForWorktree(state, worktreeId), + runtimePaneTitlesByTabId: selectRuntimePaneTitlesForWorktree(state, worktreeId), + ptyIdsByTabId: selectLivePtyIdsForWorktree(state, worktreeId), + terminalLayoutsByTabId, + runtimeAgentOrchestrationByPaneKey: selectRuntimeAgentOrchestrationForWorktree( + state, + worktreeId + ), + now + }) + ) + + for (const row of rows) { + // Child rows have no pane of their own; the board lists top-level agents. + if (row.rowSource === 'subagent') { + continue + } + // Title-derived rows (a live pane read only from its terminal title, no + // agent-hook status) carry synthetic prompt/lastAssistantMessage — the + // agent LABEL and a status word like "Idle". They're marked by + // startedAt === 0, and must NOT be shown as real conversation. + const isTitleDerived = row.startedAt === 0 + const routingPaneKey = row.activationPaneKey ?? row.paneKey + const parsed = parsePaneKey(routingPaneKey) + const tabId = parsed?.tabId ?? row.tab.id + const leafId = parsed?.leafId ?? null + const layoutPtyId = + (leafId ? terminalLayoutsByTabId[tabId]?.ptyIdsByLeafId?.[leafId] : undefined) ?? null + // Layout entries survive app restarts, but their PTYs may not (parked + // tabs keep the pre-restart id). Only advertise a pty the terminal + // preview can actually serialize — ptyIdsByTabId is the liveness truth. + const ptyId = + layoutPtyId && (state.ptyIdsByTabId?.[tabId] ?? []).includes(layoutPtyId) + ? layoutPtyId + : null + const dotState = row.state as DashboardCardDotState + const bucket = bucketForState(row.state) + + cards.push({ + paneKey: row.paneKey, + ptyId, + agentType: row.agentType, + bucket, + dotState, + task: isTitleDerived ? '' : rowTask(row), + repoId: repo.id, + worktreeId, + tabId, + leafId, + repoName: repo.displayName, + worktreeName: worktree.displayName, + lastUserMessage: isTitleDerived ? undefined : nonEmpty(row.entry.prompt), + lastAgentMessage: isTitleDerived ? undefined : nonEmpty(row.entry.lastAssistantMessage), + startedAt: row.startedAt, + stateChangedAt: row.entry.stateStartedAt || row.startedAt, + // Same derivation as WorktreeCardAgents' unvisitedByPaneKey, so the + // board and the sidebar bold/mute the same agents at the same time. + unseen: + !isTitleDerived && + (state.acknowledgedAgentsByPaneKey?.[row.paneKey] ?? 0) < row.entry.stateStartedAt, + askSummary: + bucket === 'attention' ? (row.entry.interactivePrompt ?? undefined) : undefined + }) + } + } + } + + return { generatedAt: now, cards } +} diff --git a/src/renderer/src/components/dashboard/useAgentBucketCounts.ts b/src/renderer/src/components/dashboard/useAgentBucketCounts.ts new file mode 100644 index 000000000..d302e7786 --- /dev/null +++ b/src/renderer/src/components/dashboard/useAgentBucketCounts.ts @@ -0,0 +1,87 @@ +import { useMemo } from 'react' +import { useAppStore } from '@/store' +import { useShallow } from 'zustand/react/shallow' +import type { DashboardBucket } from '../../../../shared/dashboard-snapshot' +import { buildDashboardSnapshot } from './build-dashboard-snapshot' + +export type AgentBucketCounts = Record + +const EMPTY_COUNTS: AgentBucketCounts = { attention: 0, working: 0, idle: 0 } + +/** + * Per-state agent counts for the sidebar dashboard entry, derived from the same + * builder that feeds the pop-out board so the numbers always agree. Recomputes + * only when an input slice changes (mirrors useDashboardData's cost profile). + */ +export function useAgentBucketCounts(): AgentBucketCounts { + const { + repos, + worktreesByRepo, + tabsByWorktree, + agentStatusByPaneKey, + retainedAgentsByPaneKey, + migrationUnsupportedByPtyId, + runtimeAgentOrchestrationByPaneKey, + terminalLayoutsByTabId, + ptyIdsByTabId, + runtimePaneTitlesByTabId, + agentStatusEpoch + } = useAppStore( + useShallow((s) => ({ + repos: s.repos, + worktreesByRepo: s.worktreesByRepo, + tabsByWorktree: s.tabsByWorktree, + agentStatusByPaneKey: s.agentStatusByPaneKey, + retainedAgentsByPaneKey: s.retainedAgentsByPaneKey, + migrationUnsupportedByPtyId: s.migrationUnsupportedByPtyId, + runtimeAgentOrchestrationByPaneKey: s.runtimeAgentOrchestrationByPaneKey, + terminalLayoutsByTabId: s.terminalLayoutsByTabId, + ptyIdsByTabId: s.ptyIdsByTabId, + runtimePaneTitlesByTabId: s.runtimePaneTitlesByTabId, + agentStatusEpoch: s.agentStatusEpoch + })) + ) + + return useMemo(() => { + const snapshot = buildDashboardSnapshot( + { + repos, + worktreesByRepo, + tabsByWorktree, + agentStatusByPaneKey, + retainedAgentsByPaneKey, + migrationUnsupportedByPtyId, + runtimeAgentOrchestrationByPaneKey, + terminalLayoutsByTabId, + ptyIdsByTabId, + runtimePaneTitlesByTabId, + // Counts do not render acknowledgement state, so avoid subscribing the sidebar to it. + acknowledgedAgentsByPaneKey: {} + }, + Date.now() + ) + if (snapshot.cards.length === 0) { + return EMPTY_COUNTS + } + const counts: AgentBucketCounts = { attention: 0, working: 0, idle: 0 } + for (const card of snapshot.cards) { + counts[card.bucket] += 1 + } + return counts + // Why: Date.now() is read inside the memo (not a dep) so idle-decay tracks + // agentStatusEpoch ticks, matching useDashboardData. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [ + repos, + worktreesByRepo, + tabsByWorktree, + agentStatusByPaneKey, + retainedAgentsByPaneKey, + migrationUnsupportedByPtyId, + runtimeAgentOrchestrationByPaneKey, + terminalLayoutsByTabId, + ptyIdsByTabId, + runtimePaneTitlesByTabId, + agentStatusEpoch + ]) +} diff --git a/src/renderer/src/components/dashboard/useDashboardPopoutBridge.test.tsx b/src/renderer/src/components/dashboard/useDashboardPopoutBridge.test.tsx new file mode 100644 index 000000000..6b388f95f --- /dev/null +++ b/src/renderer/src/components/dashboard/useDashboardPopoutBridge.test.tsx @@ -0,0 +1,151 @@ +// @vitest-environment happy-dom + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const mocks = vi.hoisted(() => ({ + acknowledgeAgents: vi.fn(), + setActiveWorktree: vi.fn(), + subscribeStore: vi.fn(() => vi.fn()), + onRevealAgent: vi.fn(), + onAckAgent: vi.fn(), + onPopoutOpenChanged: vi.fn(), + onSnapshotRequested: vi.fn(), + getPopoutOpen: vi.fn(async () => false), + publishSnapshot: vi.fn(async () => undefined), + offRevealAgent: vi.fn(), + offAckAgent: vi.fn(), + offPopoutOpenChanged: vi.fn(), + offSnapshotRequested: vi.fn() +})) + +vi.mock('@/store', () => ({ + useAppStore: { + getState: () => ({ + acknowledgeAgents: mocks.acknowledgeAgents, + setActiveWorktree: mocks.setActiveWorktree + }), + subscribe: mocks.subscribeStore + } +})) + +vi.mock('@/lib/activate-tab-and-focus-pane', () => ({ + activateTabAndFocusPane: vi.fn() +})) + +import { + dashboardSnapshotInputsChanged, + useDashboardPopoutBridge +} from './useDashboardPopoutBridge' +import type { DashboardSnapshotState } from './build-dashboard-snapshot' +import type { AppState } from '@/store/types' + +type DashboardSnapshotWatchState = DashboardSnapshotState & Pick + +function makeSnapshotWatchState(): DashboardSnapshotWatchState { + return { + repos: [], + worktreesByRepo: {}, + tabsByWorktree: {}, + agentStatusByPaneKey: {}, + retainedAgentsByPaneKey: {}, + migrationUnsupportedByPtyId: {}, + runtimeAgentOrchestrationByPaneKey: {}, + terminalLayoutsByTabId: {}, + ptyIdsByTabId: {}, + runtimePaneTitlesByTabId: {}, + acknowledgedAgentsByPaneKey: {}, + agentStatusEpoch: 0 + } +} + +function Harness({ enabled }: { enabled: boolean }): null { + useDashboardPopoutBridge(enabled) + return null +} + +describe('useDashboardPopoutBridge', () => { + let root: Root + let container: HTMLDivElement + + beforeEach(() => { + vi.clearAllMocks() + mocks.onRevealAgent.mockReturnValue(mocks.offRevealAgent) + mocks.onAckAgent.mockReturnValue(mocks.offAckAgent) + mocks.onPopoutOpenChanged.mockReturnValue(mocks.offPopoutOpenChanged) + mocks.onSnapshotRequested.mockReturnValue(mocks.offSnapshotRequested) + ;(window as unknown as { api: unknown }).api = { + dashboard: { + onRevealAgent: mocks.onRevealAgent, + onAckAgent: mocks.onAckAgent, + onPopoutOpenChanged: mocks.onPopoutOpenChanged, + onSnapshotRequested: mocks.onSnapshotRequested, + getPopoutOpen: mocks.getPopoutOpen, + publishSnapshot: mocks.publishSnapshot + } + } + container = document.createElement('div') + root = createRoot(container) + }) + + afterEach(async () => { + await act(async () => root.unmount()) + }) + + it('does not register dashboard or store subscriptions while disabled', async () => { + await act(async () => root.render()) + + expect(mocks.onRevealAgent).not.toHaveBeenCalled() + expect(mocks.onAckAgent).not.toHaveBeenCalled() + expect(mocks.onPopoutOpenChanged).not.toHaveBeenCalled() + expect(mocks.onSnapshotRequested).not.toHaveBeenCalled() + expect(mocks.getPopoutOpen).not.toHaveBeenCalled() + expect(mocks.subscribeStore).not.toHaveBeenCalled() + }) + + it('ignores unrelated store writes while retaining every snapshot input', () => { + const previousState = makeSnapshotWatchState() + expect(dashboardSnapshotInputsChanged({ ...previousState }, previousState)).toBe(false) + + const referenceInputs = [ + 'repos', + 'worktreesByRepo', + 'tabsByWorktree', + 'agentStatusByPaneKey', + 'retainedAgentsByPaneKey', + 'migrationUnsupportedByPtyId', + 'runtimeAgentOrchestrationByPaneKey', + 'terminalLayoutsByTabId', + 'ptyIdsByTabId', + 'runtimePaneTitlesByTabId', + 'acknowledgedAgentsByPaneKey' + ] as const + for (const key of referenceInputs) { + expect( + dashboardSnapshotInputsChanged({ ...previousState, [key]: {} }, previousState), + key + ).toBe(true) + } + expect( + dashboardSnapshotInputsChanged({ ...previousState, agentStatusEpoch: 1 }, previousState) + ).toBe(true) + }) + + it('releases every dashboard listener when the experiment is disabled', async () => { + await act(async () => root.render()) + + expect(mocks.onRevealAgent).toHaveBeenCalledTimes(1) + expect(mocks.onAckAgent).toHaveBeenCalledTimes(1) + expect(mocks.onPopoutOpenChanged).toHaveBeenCalledTimes(1) + expect(mocks.onSnapshotRequested).toHaveBeenCalledTimes(1) + expect(mocks.getPopoutOpen).toHaveBeenCalledTimes(1) + + await act(async () => root.render()) + + expect(mocks.offRevealAgent).toHaveBeenCalledTimes(1) + expect(mocks.offAckAgent).toHaveBeenCalledTimes(1) + expect(mocks.offPopoutOpenChanged).toHaveBeenCalledTimes(1) + expect(mocks.offSnapshotRequested).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts b/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts new file mode 100644 index 000000000..3a8e8c2c0 --- /dev/null +++ b/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts @@ -0,0 +1,157 @@ +import { useEffect } from 'react' +import { useAppStore, type AppState } from '@/store' +import { activateTabAndFocusPane } from '@/lib/activate-tab-and-focus-pane' +import { buildDashboardSnapshot, type DashboardSnapshotState } from './build-dashboard-snapshot' + +// Why: cap snapshot rebuilds during bursts of agent-status pings. The board is a +// glanceable surface, so ~4 updates/sec is plenty and keeps the cross-worktree +// rebuild off the hot path. +const PUBLISH_THROTTLE_MS = 250 + +type DashboardSnapshotWatchState = DashboardSnapshotState & Pick + +export function dashboardSnapshotInputsChanged( + state: DashboardSnapshotWatchState, + previousState: DashboardSnapshotWatchState +): boolean { + return ( + state.repos !== previousState.repos || + state.worktreesByRepo !== previousState.worktreesByRepo || + state.tabsByWorktree !== previousState.tabsByWorktree || + state.agentStatusByPaneKey !== previousState.agentStatusByPaneKey || + state.retainedAgentsByPaneKey !== previousState.retainedAgentsByPaneKey || + state.migrationUnsupportedByPtyId !== previousState.migrationUnsupportedByPtyId || + state.runtimeAgentOrchestrationByPaneKey !== previousState.runtimeAgentOrchestrationByPaneKey || + state.terminalLayoutsByTabId !== previousState.terminalLayoutsByTabId || + state.ptyIdsByTabId !== previousState.ptyIdsByTabId || + state.runtimePaneTitlesByTabId !== previousState.runtimePaneTitlesByTabId || + state.acknowledgedAgentsByPaneKey !== previousState.acknowledgedAgentsByPaneKey || + // Why: freshness can change a bucket without replacing any backing map. + state.agentStatusEpoch !== previousState.agentStatusEpoch + ) +} + +/** + * Runs in the MAIN window (mount once in App). Two responsibilities: + * 1. While the pop-out dashboard is open, derive the snapshot from the live + * store and publish it to the main process (which relays it to the popout). + * Does nothing while the popout is closed, so it's free in the common case. + * 2. Handle click-to-focus reveal requests forwarded from the popout: activate + * the agent's worktree and focus its pane in this (main) window. + */ +export function useDashboardPopoutBridge(enabled: boolean): void { + useEffect(() => { + if (!enabled) { + return + } + return window.api.dashboard.onRevealAgent((args) => { + useAppStore.getState().setActiveWorktree(args.worktreeId) + activateTabAndFocusPane(args.tabId, args.leafId, { flashFocusedPane: true }) + }) + }, [enabled]) + + // Opening a card's terminal dialog in the popout acks the agent here — the + // same ack the sidebar's bold/mute treatment reads, keeping both in lockstep. + // ?. shields App mount from dev-HMR preload skew (preload updates only on + // app restart). + useEffect(() => { + if (!enabled) { + return + } + return window.api.dashboard.onAckAgent?.((paneKey) => { + useAppStore.getState().acknowledgeAgents([paneKey]) + }) + }, [enabled]) + + useEffect(() => { + if (!enabled) { + return + } + let open = false + let disposed = false + let unsubscribeStore: (() => void) | null = null + let trailingTimer: ReturnType | null = null + let lastPublishAt = 0 + + const publishNow = (): void => { + lastPublishAt = Date.now() + const snapshot = buildDashboardSnapshot(useAppStore.getState(), lastPublishAt) + void window.api.dashboard.publishSnapshot(snapshot) + } + + // Leading + trailing throttle so the first change paints immediately and + // bursts collapse into one trailing publish. + const publishThrottled = (): void => { + if (!open || disposed) { + return + } + const elapsed = Date.now() - lastPublishAt + if (elapsed >= PUBLISH_THROTTLE_MS) { + if (trailingTimer) { + clearTimeout(trailingTimer) + trailingTimer = null + } + publishNow() + return + } + if (!trailingTimer) { + trailingTimer = setTimeout(() => { + trailingTimer = null + if (open && !disposed) { + publishNow() + } + }, PUBLISH_THROTTLE_MS - elapsed) + } + } + + const setOpen = (next: boolean): void => { + if (next === open || disposed) { + return + } + open = next + if (open) { + if (!unsubscribeStore) { + unsubscribeStore = useAppStore.subscribe((state, previousState) => { + // Why: unrelated high-frequency store writes must not rebuild a cross-worktree snapshot. + if (dashboardSnapshotInputsChanged(state, previousState)) { + publishThrottled() + } + }) + } + publishNow() + } else { + unsubscribeStore?.() + unsubscribeStore = null + if (trailingTimer) { + clearTimeout(trailingTimer) + trailingTimer = null + } + } + } + + const offOpenChanged = window.api.dashboard.onPopoutOpenChanged((next) => setOpen(next)) + // Popout mount asks for a fresh snapshot (its cached one may be stale). + const offRequested = window.api.dashboard.onSnapshotRequested(() => { + if (open) { + publishNow() + } + }) + // Recover the open state when the main window (re)mounts while a pop-out is + // already open — e.g. after a renderer reload. + void window.api.dashboard.getPopoutOpen().then((isOpen) => { + if (!disposed && isOpen) { + setOpen(true) + } + }) + + return () => { + disposed = true + offOpenChanged?.() + offRequested?.() + unsubscribeStore?.() + if (trailingTimer) { + clearTimeout(trailingTimer) + } + } + }, [enabled]) +} diff --git a/src/renderer/src/components/settings/ExperimentalPane.test.tsx b/src/renderer/src/components/settings/ExperimentalPane.test.tsx index 768e8a9fb..8d86cc607 100644 --- a/src/renderer/src/components/settings/ExperimentalPane.test.tsx +++ b/src/renderer/src/components/settings/ExperimentalPane.test.tsx @@ -134,6 +134,38 @@ describe('ExperimentalPane', () => { ) }) + it('renders the agent dashboard as an off-by-default searchable experiment', () => { + const settings = getDefaultSettings('/tmp') + const markup = renderToStaticMarkup( + + ) + + expect(settings.experimentalAgentDashboardPopout).toBe(false) + expect(markup).toContain('Agent Dashboard') + expect(markup).toContain('monitor attention, working, and idle agents') + expect(getExperimentalPaneSearchEntries().map((entry) => entry.title)).toContain( + 'Agent Dashboard' + ) + }) + + it('enables the agent dashboard through its experimental switch', async () => { + const updateSettings = vi.fn() + const { root, container } = await renderExperimentalPane({ updateSettings }) + const switchButton = container.querySelector( + '#experimental-agent-dashboard button[role="switch"]' + ) + if (!switchButton) { + throw new Error('Agent Dashboard switch was not rendered') + } + + await act(async () => { + switchButton.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) + + expect(updateSettings).toHaveBeenCalledWith({ experimentalAgentDashboardPopout: true }) + root.unmount() + }) + it('renders per-workspace environments as an off-by-default experimental subsection', () => { const settings = getDefaultSettings('/tmp') const markup = renderToStaticMarkup( diff --git a/src/renderer/src/components/settings/ExperimentalPane.tsx b/src/renderer/src/components/settings/ExperimentalPane.tsx index 2aaa38d6b..1cf60d414 100644 --- a/src/renderer/src/components/settings/ExperimentalPane.tsx +++ b/src/renderer/src/components/settings/ExperimentalPane.tsx @@ -37,6 +37,9 @@ export function ExperimentalPane({ const showAgentsView = matchesSettingsSearch(searchQuery, [ getExperimentalSearchEntry().agentsView ]) + const showAgentDashboard = matchesSettingsSearch(searchQuery, [ + getExperimentalSearchEntry().agentDashboard + ]) const showNativeChat = matchesSettingsSearch(searchQuery, [ getExperimentalSearchEntry().nativeChat ]) @@ -148,6 +151,52 @@ export function ExperimentalPane({ ) : null} + {showAgentDashboard ? ( + +
+
+ +

+ {translate( + 'auto.components.settings.ExperimentalPane.agentDashboard.copy', + 'Adds an Agent Dashboard entry to the left sidebar. Open it to monitor attention, working, and idle agents in a separate window and jump into their live terminals.' + )} +

+
+ + updateSettings({ + experimentalAgentDashboardPopout: + settings.experimentalAgentDashboardPopout !== true + }) + } + /> +
+
+ ) : null} + {showNativeChat ? ( ) : null} diff --git a/src/renderer/src/components/settings/experimental-search.ts b/src/renderer/src/components/settings/experimental-search.ts index 71ff93ed5..b79fd0a41 100644 --- a/src/renderer/src/components/settings/experimental-search.ts +++ b/src/renderer/src/components/settings/experimental-search.ts @@ -95,6 +95,42 @@ export const getExperimentalPaneSearchEntries = createLocalizedCatalog( ) ] }, + { + title: translate( + 'auto.components.settings.experimental.search.agentDashboard.title', + 'Agent Dashboard' + ), + description: translate( + 'auto.components.settings.experimental.search.agentDashboard.description', + 'Pop-out Kanban board for monitoring agents across worktrees.' + ), + keywords: [ + ...translateSearchKeyword( + 'auto.components.settings.experimental.search.0d24759f14', + 'experimental' + ), + ...translateSearchKeyword( + 'auto.components.settings.experimental.search.agentDashboard.agent', + 'agent' + ), + ...translateSearchKeyword( + 'auto.components.settings.experimental.search.agentDashboard.dashboard', + 'dashboard' + ), + ...translateSearchKeyword( + 'auto.components.settings.experimental.search.agentDashboard.kanban', + 'kanban' + ), + ...translateSearchKeyword( + 'auto.components.settings.experimental.search.agentDashboard.popout', + 'pop-out' + ), + ...translateSearchKeyword( + 'auto.components.settings.experimental.search.agentDashboard.worktrees', + 'worktrees' + ) + ] + }, getNativeChatExperimentalSearchEntry(), { title: translate( @@ -206,6 +242,12 @@ export function getExperimentalSearchEntry() { agentsView: findEntry( translate('auto.components.settings.experimental.search.ccc5548ac5', 'Agents View') ), + agentDashboard: findEntry( + translate( + 'auto.components.settings.experimental.search.agentDashboard.title', + 'Agent Dashboard' + ) + ), nativeChat: findEntry( translate('auto.components.settings.experimental.search.nativeChat.title', 'Native chat') ), diff --git a/src/renderer/src/components/sidebar/SidebarNav.test.tsx b/src/renderer/src/components/sidebar/SidebarNav.test.tsx index 0411aa615..a436942bd 100644 --- a/src/renderer/src/components/sidebar/SidebarNav.test.tsx +++ b/src/renderer/src/components/sidebar/SidebarNav.test.tsx @@ -77,6 +77,7 @@ vi.mock('@/components/ui/context-menu', () => ({ import { getSetupGuideSidebarEntryReady, + shouldShowAgentDashboardButton, shouldShowAgentsButton, shouldShowAutomationsButton, shouldShowMobileButton, @@ -227,6 +228,30 @@ describe('SidebarNav', () => { ).toBe(true) }) + it('shows the Agent Dashboard entry only when its experiment is enabled', () => { + expect(shouldShowAgentDashboardButton(null)).toBe(false) + expect(shouldShowAgentDashboardButton({ experimentalAgentDashboardPopout: false })).toBe(false) + expect(shouldShowAgentDashboardButton({ experimentalAgentDashboardPopout: true })).toBe(true) + }) + + it('keeps the Agent Dashboard row unmounted by default', async () => { + const container = await renderSidebarNav() + + expect(queryButtonByText(container, 'Agent Dashboard')).toBeNull() + }) + + it('mounts the Agent Dashboard row after opt-in', async () => { + setSidebarState({ + settings: { + ...getDefaultSettings('/tmp'), + experimentalAgentDashboardPopout: true + } + }) + const container = await renderSidebarNav() + + expect(queryButtonByText(container, 'Agent Dashboard')).not.toBeNull() + }) + it('shows the Mobile entry by default for older settings', () => { expect(shouldShowMobileButton(null)).toBe(true) expect(shouldShowMobileButton({})).toBe(true) diff --git a/src/renderer/src/components/sidebar/SidebarNav.tsx b/src/renderer/src/components/sidebar/SidebarNav.tsx index bf92490d3..0572150a5 100644 --- a/src/renderer/src/components/sidebar/SidebarNav.tsx +++ b/src/renderer/src/components/sidebar/SidebarNav.tsx @@ -1,9 +1,11 @@ import React from 'react' -import { Bell, CalendarClock, EyeOff, Search, Smartphone } from 'lucide-react' +import { Bell, CalendarClock, EyeOff, LayoutDashboard, Search, Smartphone } from 'lucide-react' import { useTranslation } from 'react-i18next' import { useAppStore } from '@/store' import { cn } from '@/lib/utils' import type { GlobalSettings } from '../../../../shared/types' +import { DASHBOARD_BUCKET_ORDER, type DashboardBucket } from '../../../../shared/dashboard-snapshot' +import { useAgentBucketCounts } from '@/components/dashboard/useAgentBucketCounts' import { useActivityUnreadCount } from '@/components/activity/useActivityUnreadCount' import { useShortcutKeyComboDetails } from '@/hooks/useShortcutLabel' import { ShortcutKeyCombo } from '@/components/ShortcutKeyCombo' @@ -24,6 +26,12 @@ export function shouldShowAgentsButton( return settings?.experimentalActivity === true } +export function shouldShowAgentDashboardButton( + settings: Pick | null | undefined +): boolean { + return settings?.experimentalAgentDashboardPopout === true +} + export function shouldShowMobileButton( settings: Pick | null | undefined ): boolean { @@ -36,6 +44,76 @@ export function shouldShowAutomationsButton( return settings?.showAutomationsButton !== false } +// Per-state dot colors mirror AgentStateDot so the sidebar counts read the same +// as the board (amber = needs you, yellow = working, neutral = idle, emerald = done). +const DASHBOARD_BUCKET_DOT_CLASS: Record = { + attention: 'bg-amber-500', + working: 'bg-yellow-500', + idle: 'bg-neutral-500/50' +} + +function dashboardBucketLabel(bucket: DashboardBucket): string { + switch (bucket) { + case 'attention': + return translate('dashboardPopout.bucket.attention', 'Needs You') + case 'working': + return translate('dashboardPopout.bucket.working', 'Working') + case 'idle': + return translate('dashboardPopout.bucket.idle', 'Idle') + } +} + +function DashboardBucketCounts({ + counts +}: { + counts: Record +}): React.JSX.Element | null { + const active = DASHBOARD_BUCKET_ORDER.filter((bucket) => counts[bucket] > 0) + if (active.length === 0) { + return null + } + return ( + + {active.map((bucket) => ( + + + {counts[bucket]} + + ))} + + ) +} + +// Why: keep the dashboard's broad aggregate subscriptions out of SidebarNav so +// agent-status churn only updates this opt-in row, not the full navigation. +function AgentDashboardSidebarEntry(): React.JSX.Element { + const dashboardBucketCounts = useAgentBucketCounts() + + return ( + + ) +} + const SidebarNav = React.memo(function SidebarNav() { // Why: this memo boundary needs its own language subscription, while // translate() preserves Orca's pseudo-localization behavior. @@ -48,6 +126,7 @@ const SidebarNav = React.memo(function SidebarNav() { const updateSettings = useAppStore((s) => s.updateSettings) const activeView = useAppStore((s) => s.activeView) const showAgentsButton = useAppStore((s) => shouldShowAgentsButton(s.settings)) + const showAgentDashboardButton = useAppStore((s) => shouldShowAgentDashboardButton(s.settings)) const showAutomationsButton = useAppStore((s) => shouldShowAutomationsButton(s.settings)) const showMobileButton = useAppStore((s) => shouldShowMobileButton(s.settings)) const automationsActive = activeView === 'automations' @@ -98,6 +177,7 @@ const SidebarNav = React.memo(function SidebarNav() { ) : null} + {showAgentDashboardButton ? : null} {showAgentsButton ? (