From 05f7f0ec2e688ce2a5ccf73ec6a1aff52bf3e68d Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Sun, 19 Jul 2026 04:47:06 -0700 Subject: [PATCH] Convert agents view from full-page navigation to companion overlay panel Agents is now a non-modal side panel (like the workspace board) that stays open alongside the main workspace, keeping the sidebar and navigation active. The experimental gate is removed and the feature is always available. - Add Agents button to sidebar toolbar (always visible, shows unread badge) - Implement AgentsDrawer as a Sheet-based companion panel - Add spatial canvas view with orchestration DAG layout and node visualization - Add status filter dropdown and group collapse/expand controls - Add orchestration lineage nesting (parent/child relationships in list rows) - Add view mode toggle (list/canvas) and responsive detail panel - Support both list and canvas rendering paths with shared lineage resolution - Update terminal portal system to keep agents panel active across all views - Remove experimentalActivity setting and related sidebar navigation entry - Map legacy persisted 'activity' activeView to 'terminal' (agents no longer a top-level view) - Coordinate workspace board and agents panel exclusivity (only one open at a time) --- src/renderer/src/App.tsx | 18 +- src/renderer/src/assets/main.css | 47 + src/renderer/src/components/Terminal.tsx | 6 +- .../activity/ActivityAgentsCanvas.tsx | 384 ++++++ .../activity/ActivityCanvasNodeCard.tsx | 184 +++ .../activity/ActivityPrototypePage.test.ts | 78 +- .../activity/ActivityPrototypePage.tsx | 1049 +++++++++++------ .../activity/ActivityTitlebarControls.tsx | 4 +- .../src/components/activity/AgentsDrawer.tsx | 194 +++ .../activity/activity-canvas-demo-threads.ts | 100 ++ .../activity/activity-canvas-layout.test.ts | 88 ++ .../activity/activity-canvas-layout.ts | 335 ++++++ .../activity/activity-canvas-types.ts | 81 ++ .../activity/activity-thread-lineage.test.ts | 84 ++ .../activity/activity-thread-lineage.ts | 200 ++++ .../activity/agents-panel-events.ts | 16 + .../src/components/activity/useAgentsPanel.ts | 106 ++ .../components/settings/ExperimentalPane.tsx | 48 - .../settings/experimental-search.ts | 52 - .../components/sidebar/SidebarNav.test.tsx | 29 - .../src/components/sidebar/SidebarNav.tsx | 42 +- .../sidebar/SidebarToolbar.test.tsx | 51 +- .../src/components/sidebar/SidebarToolbar.tsx | 36 +- .../src/components/sidebar/WorktreeList.tsx | 3 +- src/renderer/src/components/sidebar/index.tsx | 73 +- src/renderer/src/i18n/locales/en.json | 24 +- src/renderer/src/i18n/locales/es.json | 24 +- src/renderer/src/i18n/locales/ja.json | 24 +- src/renderer/src/i18n/locales/ko.json | 24 +- src/renderer/src/i18n/locales/zh.json | 24 +- src/renderer/src/store/slices/ui.test.ts | 16 +- src/renderer/src/store/slices/ui.ts | 51 +- .../e2e/activity-agent-pane-isolation.spec.ts | 8 +- 33 files changed, 2891 insertions(+), 612 deletions(-) create mode 100644 src/renderer/src/components/activity/ActivityAgentsCanvas.tsx create mode 100644 src/renderer/src/components/activity/ActivityCanvasNodeCard.tsx create mode 100644 src/renderer/src/components/activity/AgentsDrawer.tsx create mode 100644 src/renderer/src/components/activity/activity-canvas-demo-threads.ts create mode 100644 src/renderer/src/components/activity/activity-canvas-layout.test.ts create mode 100644 src/renderer/src/components/activity/activity-canvas-layout.ts create mode 100644 src/renderer/src/components/activity/activity-canvas-types.ts create mode 100644 src/renderer/src/components/activity/activity-thread-lineage.test.ts create mode 100644 src/renderer/src/components/activity/activity-thread-lineage.ts create mode 100644 src/renderer/src/components/activity/agents-panel-events.ts create mode 100644 src/renderer/src/components/activity/useAgentsPanel.ts diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 6a150add5..d7fd266e5 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -47,7 +47,6 @@ import { isRemoteWorkspaceSnapshotApplyInProgress, useIpcEvents } from './hooks/ import { useAutomationDispatchEvents } from './hooks/useAutomationDispatchEvents' import RetainedAgentsSyncGate from './components/dashboard/RetainedAgentsSyncGate' import { AgentHibernationGate } from './components/AgentHibernationGate' -import { ActivityTitlebarControls } from './components/activity/ActivityTitlebarControls' import Sidebar from './components/Sidebar' import { shutdownBufferCaptures } from './components/terminal-pane/shutdown-buffer-captures' import { dispatchWindowCloseRequest } from './components/window-close-request-coordinator' @@ -312,7 +311,6 @@ const WorktreeCreationPanel = lazy( ) const TaskPage = lazy(() => import('./components/TaskPage')) const AutomationsPage = lazy(() => import('./components/automations/AutomationsPage')) -const ActivityPrototypePage = lazy(() => import('./components/activity/ActivityPrototypePage')) const Settings = lazy(() => import('./components/settings/Settings')) const SkillsPage = lazy(() => import('./components/skills/SkillsPage')) const WorkspaceSpacePage = lazy(() => import('./components/workspace-space/WorkspaceSpacePage')) @@ -1532,13 +1530,10 @@ function App(): React.JSX.Element { const hasTabBar = tabCount >= 2 const showTitlebarExpandButton = workspaceChromeActive && !hasTabBar && effectiveActiveTabExpanded - // Why: Activity and Space are full-page navigation surfaces — same - // treatment as Settings — so the worktree sidebar is removed for those views. - const showSidebar = - activeView !== 'settings' && - activeView !== 'activity' && - activeView !== 'space' && - activeView !== 'skills' + // Why: Space is a full-page navigation surface — same treatment as Settings — + // so the worktree sidebar is removed for those views. Agents is a companion + // overlay and keeps the sidebar (like the workspace board). + const showSidebar = activeView !== 'settings' && activeView !== 'space' && activeView !== 'skills' // Why: Tasks/Landing keep the full titlebar only when the sidebar is // collapsed; with it open, mirror workspace view so titlebar-left sits flush // above nav. Creation layout suppresses the full-width titlebar. @@ -2173,9 +2168,7 @@ function App(): React.JSX.Element { const titlebarMainStrip = ( <> - {activeView === 'activity' ? ( - - ) : creationLayoutActive ? null : ( + {creationLayoutActive ? null : (
: null} {activeView === 'tasks' ? : null} {activeView === 'automations' ? : null} - {activeView === 'activity' ? : null} {activeView === 'space' ? : null} {activeView === 'mobile' ? : null} {activeView === 'terminal' && diff --git a/src/renderer/src/assets/main.css b/src/renderer/src/assets/main.css index 90549525a..52489208e 100644 --- a/src/renderer/src/assets/main.css +++ b/src/renderer/src/assets/main.css @@ -1689,6 +1689,53 @@ } } +/* Why: Agents is a companion overlay, not a drawer. The generic left-sheet + slide translates the full width (and from far left once offset to the + sidebar edge), which feels wrong for a quick panel toggle. */ +.agents-panel-sheet-content[data-state='open'] { + animation-name: agents-panel-sheet-in; + animation-duration: 80ms; + animation-timing-function: ease-out; +} + +.agents-panel-sheet-content[data-state='closed'] { + animation-name: agents-panel-sheet-out; + animation-duration: 60ms; + animation-timing-function: ease-in; +} + +.agents-panel-sheet-content { + box-shadow: inset 1px 0 0 color-mix(in srgb, var(--border) 80%, transparent); + backdrop-filter: none; +} + +@keyframes agents-panel-sheet-in { + from { + opacity: 0; + } + + to { + opacity: 1; + } +} + +@keyframes agents-panel-sheet-out { + from { + opacity: 1; + } + + to { + opacity: 0; + } +} + +@media (prefers-reduced-motion: reduce) { + .agents-panel-sheet-content[data-state='open'], + .agents-panel-sheet-content[data-state='closed'] { + animation: none; + } +} + /* Why: board-origin cards use pointer drag so Shift+scroll can keep firing; these replace the native drag cursor and ghost affordance. */ [data-workspace-board-pointer-draggable='true'] { diff --git a/src/renderer/src/components/Terminal.tsx b/src/renderer/src/components/Terminal.tsx index 14df288fd..88a6c144e 100644 --- a/src/renderer/src/components/Terminal.tsx +++ b/src/renderer/src/components/Terminal.tsx @@ -331,9 +331,9 @@ function Terminal(): React.JSX.Element | null { // activeTabId here used to flash the wrong terminal — selectThread updates // the store in multiple steps and intermediate renders briefly pointed the // portal at the new worktree's stale last-active tab. - const activityTerminalPortals: ActivityTerminalPortalTarget[] = useActivityTerminalPortals( - activeView === 'activity' - ) + // Why: Agents is a companion overlay, so portals are active whenever the + // panel publishes targets — not only when activeView was 'activity'. + const activityTerminalPortals: ActivityTerminalPortalTarget[] = useActivityTerminalPortals(true) const foregroundTerminalTabIds = useMemo(() => { const ids = new Set() if (activeView === 'terminal' && activeTabType === 'terminal' && activeTabId) { diff --git a/src/renderer/src/components/activity/ActivityAgentsCanvas.tsx b/src/renderer/src/components/activity/ActivityAgentsCanvas.tsx new file mode 100644 index 000000000..8559a280e --- /dev/null +++ b/src/renderer/src/components/activity/ActivityAgentsCanvas.tsx @@ -0,0 +1,384 @@ +import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { Expand, LocateFixed, Minus, Network, Plus } from 'lucide-react' + +import { Button } from '@/components/ui/button' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { cn } from '@/lib/utils' +import { translate } from '@/i18n/i18n' + +import { ACTIVITY_CANVAS_STATUS_SURFACE, ActivityCanvasNodeCard } from './ActivityCanvasNodeCard' +import { buildDemoCanvasThreads } from './activity-canvas-demo-threads' +import { + type ActivityCanvasAgentState, + type ActivityCanvasLayout, + type ActivityCanvasThreadInput, + layoutActivityCanvas +} from './activity-canvas-layout' + +export type { ActivityViewMode } from './ActivityCanvasNodeCard' +export { ActivityViewModeToggle } from './ActivityCanvasNodeCard' + +const MIN_ZOOM = 0.35 +const MAX_ZOOM = 1.75 +const ZOOM_STEP = 0.12 + +function clamp(n: number, min: number, max: number): number { + return Math.min(max, Math.max(min, n)) +} + +export function ActivityAgentsCanvas({ + threads, + selectedPaneKey, + onSelectPaneKey, + className +}: { + threads: ActivityCanvasThreadInput[] + selectedPaneKey: string | null + onSelectPaneKey: (paneKey: string | null) => void + className?: string +}): React.JSX.Element { + const viewportRef = useRef(null) + const [zoom, setZoom] = useState(0.9) + const [pan, setPan] = useState({ x: 24, y: 24 }) + // Demo nodes are not real panes; keep selection local so the sample graph + // still shows a selected ring without mutating Activity thread state. + const [demoSelectedPaneKey, setDemoSelectedPaneKey] = useState(null) + const dragRef = useRef<{ + pointerId: number + startX: number + startY: number + originX: number + originY: number + moved: boolean + } | null>(null) + + const usingDemo = threads.length === 0 + const layoutThreads = useMemo( + () => (usingDemo ? buildDemoCanvasThreads() : threads), + [threads, usingDemo] + ) + const layout: ActivityCanvasLayout = useMemo( + () => layoutActivityCanvas(layoutThreads), + [layoutThreads] + ) + const effectiveSelectedPaneKey = usingDemo ? demoSelectedPaneKey : selectedPaneKey + + const fitView = useCallback(() => { + const el = viewportRef.current + if (!el) { + return + } + const pad = 48 + const vw = el.clientWidth + const vh = el.clientHeight + if (vw <= 0 || vh <= 0) { + return + } + const scale = clamp( + Math.min((vw - pad * 2) / layout.width, (vh - pad * 2) / layout.height), + MIN_ZOOM, + 1 + ) + setZoom(scale) + setPan({ + x: (vw - layout.width * scale) / 2, + y: Math.max(16, (vh - layout.height * scale) / 2) + }) + }, [layout.height, layout.width]) + + useEffect(() => { + fitView() + }, [fitView, layout.nodes.length]) + + const onWheel = (event: React.WheelEvent): void => { + if (event.ctrlKey || event.metaKey) { + event.preventDefault() + const delta = event.deltaY > 0 ? -ZOOM_STEP : ZOOM_STEP + setZoom((z) => clamp(z + delta, MIN_ZOOM, MAX_ZOOM)) + return + } + setPan((p) => ({ x: p.x - event.deltaX, y: p.y - event.deltaY })) + } + + const onPointerDown = (event: React.PointerEvent): void => { + if (event.button !== 0) { + return + } + // Only start pan from the empty field, not from a node. + if ((event.target as HTMLElement).closest('[data-testid="activity-canvas-node"]')) { + return + } + dragRef.current = { + pointerId: event.pointerId, + startX: event.clientX, + startY: event.clientY, + originX: pan.x, + originY: pan.y, + moved: false + } + event.currentTarget.setPointerCapture(event.pointerId) + } + + const onPointerMove = (event: React.PointerEvent): void => { + const drag = dragRef.current + if (!drag || drag.pointerId !== event.pointerId) { + return + } + const dx = event.clientX - drag.startX + const dy = event.clientY - drag.startY + if (Math.abs(dx) + Math.abs(dy) > 3) { + drag.moved = true + } + setPan({ x: drag.originX + dx, y: drag.originY + dy }) + } + + const onPointerUp = (event: React.PointerEvent): void => { + const drag = dragRef.current + if (!drag || drag.pointerId !== event.pointerId) { + return + } + dragRef.current = null + if (!drag.moved) { + if (usingDemo) { + setDemoSelectedPaneKey(null) + } else { + onSelectPaneKey(null) + } + } + } + + const statusLegend = useMemo(() => { + const counts = new Map() + for (const node of layout.nodes) { + counts.set(node.thread.agentState, (counts.get(node.thread.agentState) ?? 0) + 1) + } + return (Object.keys(ACTIVITY_CANVAS_STATUS_SURFACE) as ActivityCanvasAgentState[]) + .filter((state) => (counts.get(state) ?? 0) > 0) + .map((state) => ({ + state, + count: counts.get(state) ?? 0, + ...ACTIVITY_CANVAS_STATUS_SURFACE[state] + })) + }, [layout.nodes]) + + return ( +
+
+
+ {layout.clusters.map((cluster) => ( +
+
+ {cluster.label} +
+
+ ))} + + + + + + + + {layout.edges.map((edge) => ( + + ))} + + + {layout.nodes.map((node) => ( + { + if (usingDemo) { + setDemoSelectedPaneKey(node.thread.paneKey) + return + } + onSelectPaneKey(node.thread.paneKey) + }} + /> + ))} +
+ +
+
+
+ + {usingDemo + ? translate( + 'auto.components.activity.ActivityAgentsCanvas.demoTitle', + 'Canvas preview (sample data)' + ) + : translate( + 'auto.components.activity.ActivityAgentsCanvas.liveTitle', + 'Agents canvas' + )} +
+
+ {usingDemo + ? translate( + 'auto.components.activity.ActivityAgentsCanvas.demoHint', + 'No live agents match filters — showing a sample orchestration graph. Start agents to replace this with real data.' + ) + : translate( + 'auto.components.activity.ActivityAgentsCanvas.liveHint', + '{{linked}} linked · {{isolated}} isolated · fill = status · stripe = agent', + { + linked: layout.linkedCount, + isolated: layout.isolatedCount + } + )} +
+ {statusLegend.length > 0 ? ( +
+ {statusLegend.map((item) => ( + + + + {item.label.toLowerCase()} ({item.count}) + + + ))} +
+ ) : null} +
+ +
+ + + + + Zoom out + + + {Math.round(zoom * 100)}% + + + + + + Zoom in + + + + + + Fit view + + {effectiveSelectedPaneKey ? ( + + + + + Clear selection + + ) : null} +
+
+ + {layout.nodes.length === 0 ? ( +
+ {translate( + 'auto.components.activity.ActivityAgentsCanvas.empty', + 'No agent activity to place on the canvas.' + )} +
+ ) : null} +
+
+ ) +} diff --git a/src/renderer/src/components/activity/ActivityCanvasNodeCard.tsx b/src/renderer/src/components/activity/ActivityCanvasNodeCard.tsx new file mode 100644 index 000000000..a51042c2c --- /dev/null +++ b/src/renderer/src/components/activity/ActivityCanvasNodeCard.tsx @@ -0,0 +1,184 @@ +import React from 'react' +import { List, Network } from 'lucide-react' + +import { AgentIcon } from '@/lib/agent-catalog' +import { agentTypeToIconAgent, formatAgentTypeLabel } from '@/lib/agent-status' +import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' +import { cn } from '@/lib/utils' +import { translate } from '@/i18n/i18n' + +import type { ActivityCanvasAgentState, ActivityCanvasNode } from './activity-canvas-types' + +export type ActivityViewMode = 'list' | 'canvas' + +export const ACTIVITY_CANVAS_STATUS_SURFACE: Record< + ActivityCanvasAgentState, + { surface: string; accent: string; label: string } +> = { + working: { + surface: + 'bg-amber-500/12 text-amber-950 border-amber-500/35 dark:bg-amber-400/12 dark:text-amber-50 dark:border-amber-400/30', + accent: 'rgb(245 158 11)', + label: 'WORKING' + }, + blocked: { + surface: + 'bg-red-500/12 text-red-950 border-red-500/35 dark:bg-red-400/12 dark:text-red-50 dark:border-red-400/30', + accent: 'rgb(239 68 68)', + label: 'BLOCKED' + }, + waiting: { + surface: + 'bg-orange-500/12 text-orange-950 border-orange-500/35 dark:bg-orange-400/12 dark:text-orange-50 dark:border-orange-400/30', + accent: 'rgb(249 115 22)', + label: 'WAITING' + }, + done: { + surface: + 'bg-emerald-500/12 text-emerald-950 border-emerald-500/35 dark:bg-emerald-400/12 dark:text-emerald-50 dark:border-emerald-400/30', + accent: 'rgb(16 185 129)', + label: 'DONE' + }, + interrupted: { + surface: + 'bg-neutral-500/12 text-neutral-900 border-neutral-500/30 dark:bg-neutral-400/10 dark:text-neutral-50 dark:border-neutral-400/25', + accent: 'rgb(115 115 115)', + label: 'INTERRUPTED' + } +} + +export function ActivityViewModeToggle({ + value, + onChange, + className +}: { + value: ActivityViewMode + onChange: (mode: ActivityViewMode) => void + className?: string +}): React.JSX.Element { + return ( + { + if (next === 'list' || next === 'canvas') { + onChange(next) + } + }} + variant="outline" + size="sm" + spacing={0} + className={cn('shrink-0', className)} + aria-label={translate( + 'auto.components.activity.ActivityAgentsCanvas.viewMode', + 'Agents view mode' + )} + > + + + List + + + + Canvas + + + ) +} + +export function ActivityCanvasNodeCard({ + node, + selected, + onSelect +}: { + node: ActivityCanvasNode + selected: boolean + onSelect: () => void +}): React.JSX.Element { + const theme = ACTIVITY_CANVAS_STATUS_SURFACE[node.thread.agentState] + const title = + node.thread.paneTitle.trim().length > 0 ? node.thread.paneTitle : node.thread.workspaceTitle + const subtitle = + title !== node.thread.workspaceTitle ? node.thread.workspaceTitle : node.thread.projectLabel + + return ( + + ) +} diff --git a/src/renderer/src/components/activity/ActivityPrototypePage.test.ts b/src/renderer/src/components/activity/ActivityPrototypePage.test.ts index b9e03ecc4..78bf300e9 100644 --- a/src/renderer/src/components/activity/ActivityPrototypePage.test.ts +++ b/src/renderer/src/components/activity/ActivityPrototypePage.test.ts @@ -11,8 +11,12 @@ import { formatAgentTypeLabel } from '@/lib/agent-status' import type { RetainedAgentEntry } from '@/store/slices/agent-status' import { ACTIVITY_SEARCH_QUERY_MAX_BYTES, + ACTIVITY_STATUS_GROUP_ORDER, activityThreadResponseRenderPreview, activityThreadMatchesSearchQuery, + activityThreadMatchesStatusFilter, + createDefaultActivityStatusFilter, + createDefaultCollapsedActivityGroups, handleActivityFilterFocusShortcut, isActivityFilterFocusShortcut, shouldIgnoreActivityFilterFocusShortcutTarget, @@ -21,7 +25,9 @@ import { buildAgentPaneThreads, getActivityThreadGroup, groupActivityThreadsByStatus, - isActivitySearchQueryTooLarge + isActivitySearchQueryTooLarge, + toggleActivityGroupCollapsed, + toggleActivityStatusFilter } from './ActivityPrototypePage' import { makePaneKey } from '../../../../shared/stable-pane-id' @@ -912,3 +918,73 @@ describe('activity filter focus shortcut', () => { ).toBe(false) }) }) + +describe('activity status filter and collapse helpers', () => { + it('defaults to every status enabled and collapses done/interrupted groups', () => { + expect([...createDefaultActivityStatusFilter()]).toEqual([...ACTIVITY_STATUS_GROUP_ORDER]) + expect([...createDefaultCollapsedActivityGroups()].sort()).toEqual(['done', 'interrupted']) + }) + + it('filters threads by enabled agent status groups', () => { + const workingEntry: AgentStatusEntry = { + state: 'working', + updatedAt: 2_000, + stateStartedAt: 2_000, + paneKey: PANE_KEY, + terminalTitle: 'Claude', + stateHistory: [], + agentType: 'claude', + prompt: 'ship it' + } + const doneEntry: AgentStatusEntry = { + state: 'done', + updatedAt: 1_000, + stateStartedAt: 1_000, + paneKey: PANE_KEY_2, + terminalTitle: 'Codex', + stateHistory: [], + agentType: 'codex', + prompt: 'done work' + } + const { events, liveAgentByPaneKey } = buildActivityEvents({ + agentStatusByPaneKey: { + [PANE_KEY]: workingEntry, + [PANE_KEY_2]: doneEntry + }, + retainedAgentsByPaneKey: {}, + tabsByWorktree: { 'wt-1': [makeTab(), { ...makeTab(), id: 'tab-2', ptyId: 'pty-2' }] }, + worktreeMap: new Map([['wt-1', makeWorktree()]]), + repoMap: new Map([['repo-1', makeRepo()]]), + acknowledgedAgentsByPaneKey: {}, + now: 3_000 + }) + const threads = buildAgentPaneThreads({ events, liveAgentByPaneKey }) + const workingOnly = new Set(['working'] as const) + + expect( + threads + .filter((thread) => activityThreadMatchesStatusFilter(thread, workingOnly)) + .map((t) => t.paneKey) + ).toEqual([PANE_KEY]) + expect( + threads.filter((thread) => + activityThreadMatchesStatusFilter(thread, createDefaultActivityStatusFilter()) + ) + ).toHaveLength(threads.length) + }) + + it('toggles status filter membership and collapsed group keys', () => { + const withoutDone = toggleActivityStatusFilter( + createDefaultActivityStatusFilter(), + 'done', + false + ) + expect(withoutDone.has('done')).toBe(false) + expect(toggleActivityStatusFilter(withoutDone, 'done', true).has('done')).toBe(true) + + const collapsed = createDefaultCollapsedActivityGroups() + const expandedDone = toggleActivityGroupCollapsed(collapsed, 'done') + expect(expandedDone.has('done')).toBe(false) + expect(toggleActivityGroupCollapsed(expandedDone, 'done').has('done')).toBe(true) + }) +}) diff --git a/src/renderer/src/components/activity/ActivityPrototypePage.tsx b/src/renderer/src/components/activity/ActivityPrototypePage.tsx index ccb57a05e..6d25aa8b0 100644 --- a/src/renderer/src/components/activity/ActivityPrototypePage.tsx +++ b/src/renderer/src/components/activity/ActivityPrototypePage.tsx @@ -6,12 +6,25 @@ import { useShallow } from 'zustand/react/shallow' import { Bell, BellDot, + ChevronRight, ExternalLink, + ListFilter, MessageSquareText, MoreVertical, Search, - TerminalSquare + TerminalSquare, + X } from 'lucide-react' +import { + ActivityAgentsCanvas, + ActivityViewModeToggle, + type ActivityViewMode +} from './ActivityAgentsCanvas' +import type { ActivityCanvasThreadInput } from './activity-canvas-layout' +import { + buildActivityThreadLineageItems, + type ActivityThreadLineageMeta +} from './activity-thread-lineage' import { AgentStateDot, agentStateLabel } from '@/components/AgentStateDot' import { AgentIcon } from '@/lib/agent-catalog' @@ -36,7 +49,6 @@ import { DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu' -import { Input } from '@/components/ui/input' import { Select, SelectContent, @@ -78,7 +90,7 @@ type ThreadReadFilter = 'all' | 'unread' type ActivityGroupBy = 'status' | 'project' | 'worktree' | 'agent' type ActivityEventState = Extract type ActivityLiveAgentState = Extract -type ActivityStatusGroupId = 'working' | 'blocked' | 'waiting' | 'done' | 'interrupted' +export type ActivityStatusGroupId = 'working' | 'blocked' | 'waiting' | 'done' | 'interrupted' type ActivityEvent = { id: string @@ -148,13 +160,16 @@ type ActivityTerminalPortalSlotId = 'primary' | 'secondary' const ACTIVITY_TERMINAL_LOADING_LABEL_DELAY_MS = 180 const ACTIVITY_THREAD_RESPONSE_RENDER_PREVIEW_MAX_LENGTH = 320 -const ACTIVITY_STATUS_GROUP_ORDER: ActivityStatusGroupId[] = [ +export const ACTIVITY_STATUS_GROUP_ORDER: readonly ActivityStatusGroupId[] = [ 'working', 'blocked', 'waiting', 'done', 'interrupted' -] +] as const + +// Why: Done/Interrupted usually dominate the feed and push live agents off-screen. +const DEFAULT_COLLAPSED_ACTIVITY_GROUP_KEYS: readonly string[] = ['done', 'interrupted'] const STANDALONE_ACTIVITY_WORKTREE_REPO_ID = '__activity_standalone__' const absoluteDateFormatter = new Intl.DateTimeFormat(undefined, { @@ -978,6 +993,55 @@ function threadAgentStateLabel(thread: AgentPaneThread): string { return agentStateLabel(state) } +function threadStatusEntry(thread: AgentPaneThread): AgentStatusEntry | null { + return thread.currentAgentEntry ?? thread.latestEvent?.entry ?? null +} + +function threadOrchestrationContext(thread: AgentPaneThread) { + return threadStatusEntry(thread)?.orchestration +} + +function toActivityLineageThread(thread: AgentPaneThread) { + const orchestration = threadOrchestrationContext(thread) + const entry = threadStatusEntry(thread) + return { + paneKey: thread.paneKey, + paneTitle: thread.paneTitle, + terminalHandle: entry?.terminalHandle ?? null, + parentPaneKey: orchestration?.parentPaneKey ?? null, + parentTerminalHandle: orchestration?.parentTerminalHandle ?? null, + coordinatorHandle: orchestration?.coordinatorHandle ?? null, + thread + } +} + +function toActivityCanvasThreadInput( + thread: AgentPaneThread, + parentPaneKey: string | null +): ActivityCanvasThreadInput { + const state = threadAgentState(thread) + const interrupted = + !thread.currentAgentState && state === 'done' && thread.latestEvent?.entry.interrupted === true + const agentState = interrupted + ? 'interrupted' + : state === 'working' || state === 'blocked' || state === 'waiting' || state === 'done' + ? state + : 'done' + return { + paneKey: thread.paneKey, + paneTitle: thread.paneTitle, + workspaceTitle: getActivityThreadWorkspaceTitle(thread.worktree), + projectLabel: thread.repo?.displayName ?? 'Unknown project', + agentType: thread.agentType, + agentState, + agentStateLabel: threadAgentStateLabel(thread), + responsePreview: thread.responsePreview, + latestTimestamp: thread.latestTimestamp, + unread: thread.unread, + parentPaneKey + } +} + export function getActivityThreadGroup( thread: AgentPaneThread, groupBy: ActivityGroupBy @@ -1067,6 +1131,57 @@ export function groupActivityThreadsByStatus(threads: AgentPaneThread[]): Activi }) } +export function activityStatusGroupLabel(id: ActivityStatusGroupId): string { + return threadStatusGroupLabel(id) +} + +export function activityStatusGroupState(id: ActivityStatusGroupId): AgentStatusState { + return threadStatusGroupState(id) +} + +export function createDefaultActivityStatusFilter(): Set { + return new Set(ACTIVITY_STATUS_GROUP_ORDER) +} + +export function createDefaultCollapsedActivityGroups(): Set { + return new Set(DEFAULT_COLLAPSED_ACTIVITY_GROUP_KEYS) +} + +export function activityThreadMatchesStatusFilter( + thread: AgentPaneThread, + enabledStatuses: ReadonlySet +): boolean { + // Why: empty selection means "no statuses" (show nothing), not "all". + return enabledStatuses.has(threadStatusGroupId(thread)) +} + +export function toggleActivityStatusFilter( + enabledStatuses: ReadonlySet, + status: ActivityStatusGroupId, + checked: boolean +): Set { + const next = new Set(enabledStatuses) + if (checked) { + next.add(status) + } else { + next.delete(status) + } + return next +} + +export function toggleActivityGroupCollapsed( + collapsedGroupKeys: ReadonlySet, + groupKey: string +): Set { + const next = new Set(collapsedGroupKeys) + if (next.has(groupKey)) { + next.delete(groupKey) + } else { + next.add(groupKey) + } + return next +} + function threadSearchText(thread: AgentPaneThread): string { const latest = thread.latestEvent const stateLabel = threadAgentStateLabel(thread) @@ -1188,12 +1303,34 @@ function ThreadAgentStateIndicator({ thread }: { thread: AgentPaneThread }): Rea ) } -function ActivityStatusGroupHeader({ group }: { group: ActivityThreadGroup }): React.JSX.Element { +function ActivityStatusGroupHeader({ + group, + collapsed, + onToggle +}: { + group: ActivityThreadGroup + collapsed: boolean + onToggle: () => void +}): React.JSX.Element { return ( -
+
+ ) } @@ -1225,6 +1362,7 @@ function isEventFromNestedInteractiveElement( function ThreadRow({ thread, + lineage, selected, onSelect, onJump, @@ -1233,6 +1371,7 @@ function ThreadRow({ compactMode }: { thread: AgentPaneThread + lineage: ActivityThreadLineageMeta selected: boolean onSelect: () => void onJump: () => void @@ -1245,7 +1384,24 @@ function ThreadRow({ }) const workspaceTitle = getActivityThreadWorkspaceTitle(thread.worktree) const taskTitle = thread.paneTitle - const agentLabel = formatAgentTypeLabel(thread.agentType) + const isLineageChild = lineage.depth > 0 + const relationshipLabel = + lineage.childCount > 0 + ? translate( + 'auto.components.activity.ActivityPrototypePage.dispatchedAgents', + 'dispatched {{count}} {{unit}}', + { + count: lineage.childCount, + unit: lineage.childCount === 1 ? 'agent' : 'agents' + } + ) + : lineage.parentTitle + ? translate( + 'auto.components.activity.ActivityPrototypePage.fromParentAgent', + 'from {{parent}}', + { parent: lineage.parentTitle } + ) + : null const showStatusPreview = !compactMode && renderedResponsePreview.length > 0 && @@ -1254,8 +1410,12 @@ function ThreadRow({ return (
0 ? lineage.childCount : undefined} onClick={onSelect} - role="button" + role={isLineageChild || lineage.childCount > 0 ? 'treeitem' : 'button'} + aria-level={isLineageChild || lineage.childCount > 0 ? lineage.depth + 1 : undefined} tabIndex={0} onKeyDown={(event) => { // Why: response markdown can contain links; keyboard activation on a @@ -1282,14 +1442,44 @@ function ThreadRow({ // ~3px of internal space above the cap-height that isn't present // below the secondary badge row. Symmetric py made the top read // heavier; the smaller top pad visually evens the row. - 'group relative flex w-full cursor-pointer flex-col gap-1 border-b border-border px-3 pt-2.5 pb-3 text-left transition-colors', + 'group relative flex w-full cursor-pointer flex-col gap-1 border-b border-border pt-2.5 pb-3 text-left transition-colors', + isLineageChild ? 'pr-3 pl-8' : 'px-3', selected ? 'bg-black/[0.08] shadow-[0_1px_2px_rgba(0,0,0,0.04)] dark:bg-white/[0.10] dark:shadow-[0_1px_2px_rgba(0,0,0,0.03)]' : 'hover:bg-accent/40' )} > {thread.unread ? ( - + + ) : null} + {/* Orchestration tree connector — child under parent (dashboard lineage pattern). */} + {isLineageChild ? ( + + + + + ) : null} + {lineage.childCount > 0 ? ( + ) : null}
@@ -1333,47 +1523,53 @@ function ThreadRow({ title={thread.responsePreview} /> ) : null} -
- {agentLabel} - {canJump ? ( - - - - - - - {translate( + {relationshipLabel ? ( +
+ {relationshipLabel} +
+ ) : null} +
+ + {canJump ? ( + + + +
-
- + onClick={(event) => { + event.stopPropagation() + onJump() + }} + onMouseDown={(event) => event.stopPropagation()} + > + + + + + {translate( + 'auto.components.activity.ActivityPrototypePage.4616ea39fd', + 'Jump to workspace' + )} + + + + ) : null} {thread.unread ? ( ('all') const [groupBy, setGroupBy] = useState('status') + const [enabledStatuses, setEnabledStatuses] = useState>( + createDefaultActivityStatusFilter + ) + const [collapsedGroupKeys, setCollapsedGroupKeys] = useState>( + createDefaultCollapsedActivityGroups + ) const [query, setQuery] = useState('') - const activityFilterInputRef = useRef(null) + const activitySearchInputRef = useRef(null) const [compactMode, setCompactMode] = useState(false) + // Why (prototype): List is the current production-shaped agents feed; Canvas + // is the orca-viz-inspired spatial alternative. Local state only until the + // next refinement pass decides whether view mode is a setting. + const [viewMode, setViewMode] = useState('list') const [selectedPaneKey, setSelectedPaneKey] = useState(null) const [displayedPaneKey, setDisplayedPaneKey] = useState(null) const [activePortalSlotId, setActivePortalSlotId] = @@ -1525,16 +1731,43 @@ export default function ActivityPrototypePage(): React.JSX.Element { ) { return false } + if ( + !activityThreadMatchesStatusFilter(thread, enabledStatuses) && + thread.paneKey !== effectiveSelectedPaneKey + ) { + return false + } if (normalizedQuery === null) { return false } return activityThreadMatchesSearchQuery({ thread, searchQuery: normalizedQuery }) }) - }, [allThreads, readFilter, query, effectiveSelectedPaneKey]) + }, [allThreads, enabledStatuses, readFilter, query, effectiveSelectedPaneKey]) const visibleThreadGroups = useMemo( () => buildActivityThreadGroups(visibleThreads, groupBy), [visibleThreads, groupBy] ) + const statusFilterActive = enabledStatuses.size < ACTIVITY_STATUS_GROUP_ORDER.length + // Why: one lineage pass over the filtered feed so list nesting and canvas + // edges share parent resolution (pane key + terminal handles). + const visibleLineageItems = useMemo( + () => buildActivityThreadLineageItems(visibleThreads.map(toActivityLineageThread)), + [visibleThreads] + ) + const lineageByPaneKey = useMemo( + () => + new Map( + visibleLineageItems.map((item) => [item.thread.thread.paneKey, item.lineage] as const) + ), + [visibleLineageItems] + ) + const canvasThreads = useMemo( + () => + visibleLineageItems.map(({ thread: wrapped, lineage }) => + toActivityCanvasThreadInput(wrapped.thread, lineage.parentPaneKey) + ), + [visibleLineageItems] + ) const selectedThread = effectiveSelectedPaneKey ? (allThreads.find((thread) => thread.paneKey === effectiveSelectedPaneKey) ?? null) @@ -1708,17 +1941,17 @@ export default function ActivityPrototypePage(): React.JSX.Element { }, []) useEffect(() => { - const focusActivityFilter = (event: KeyboardEvent): void => { + const focusActivitySearch = (event: KeyboardEvent): void => { handleActivityFilterFocusShortcut({ activeElement: document.activeElement, event, - input: activityFilterInputRef.current, + input: activitySearchInputRef.current, terminalPortalTargets: [activePortalTargetEl, inactivePortalTargetEl] }) } - window.addEventListener('keydown', focusActivityFilter, { capture: true }) - return () => window.removeEventListener('keydown', focusActivityFilter, { capture: true }) + window.addEventListener('keydown', focusActivitySearch, { capture: true }) + return () => window.removeEventListener('keydown', focusActivitySearch, { capture: true }) }, [activePortalTargetEl, inactivePortalTargetEl]) const markThreadRead = (thread: AgentPaneThread): void => { @@ -1808,305 +2041,431 @@ export default function ActivityPrototypePage(): React.JSX.Element { storeData.acknowledgeAgents(unreadKeys) } - // Why (page padding): drop top + horizontal padding so the page extends to - // the window's left and right edges (matching how sidebars abut the chrome - // elsewhere). The titlebar (ActivityTitlebarControls) already provides the - // breathing-room band above; the right pane's title row supplies its own - // top padding (pt-2) so the heading isn't pinned to the titlebar. - return ( -
-
- - -
- {selectedThread ? ( -
- {/* Why (no header action button): per-card hover actions on the - thread list (Mark unread, Open) are the primary controls now, - so the header keeps just the thread identity. */} -
-
-
- - - - - - -

- {selectedThread.paneTitle} -

-
-
- - - {selectedThread.worktree.displayName} - -
-
-
- {/* Why: Terminal stays mounted in the hidden workspace tree while - Activity is open. This target lets that existing TerminalPane - move here instead of creating a second PTY/xterm owner. */} - {(() => { - // Why: retained threads can outlive their tab; portal needs a live TerminalPane to render into. - if (!selectedHasLiveTab) { - return ( -
- - {storeData.worktreeMap.has(selectedThread.worktree.id) - ? translate( - 'auto.components.activity.ActivityPrototypePage.afdc2139a8', - 'Agent terminal closed. Open a new terminal in this workspace to continue.' - ) - : translate( - 'auto.components.activity.ActivityPrototypePage.22b22034bc', - 'Standalone terminal unavailable in Activity.' - )} -
- ) - } - return ( -
-
-
- {visibleThread && !stagedThread && !visiblePortalReady ? ( - - ) : null} -
- ) - })()} -
- ) : ( -
- {visibleThreads.length === 0 ? ( - <> - - {translate( - 'auto.components.activity.ActivityPrototypePage.e3db9892f6', - 'No activity yet.' - )} - - ) : ( - <> - - {translate( - 'auto.components.activity.ActivityPrototypePage.cf780197a1', - 'Select an agent to view its activity' - )} - - )} -
+ ) + })()} +
+ ) : ( +
+ {visibleThreads.length === 0 ? ( + <> + + {translate( + 'auto.components.activity.ActivityPrototypePage.e3db9892f6', + 'No activity yet.' )} -
-
+ + ) : ( + <> + + {translate( + 'auto.components.activity.ActivityPrototypePage.cf780197a1', + 'Select an agent to view its activity' + )} + + )} +
+ ) + + return ( +
+ {viewMode === 'canvas' ? ( +
+
{listToolbar}
+
+ { + if (!paneKey) { + setSelectedPaneKey(null) + return + } + const thread = allThreads.find((candidate) => candidate.paneKey === paneKey) + if (thread) { + selectThread(thread) + } + }} + /> + {selectedThread ? ( +
+ {detailPanel} +
+ ) : null} +
+
+ ) : ( +
+ + +
{detailPanel}
+
+ )}
) } diff --git a/src/renderer/src/components/activity/ActivityTitlebarControls.tsx b/src/renderer/src/components/activity/ActivityTitlebarControls.tsx index 93ca4c65c..10f583996 100644 --- a/src/renderer/src/components/activity/ActivityTitlebarControls.tsx +++ b/src/renderer/src/components/activity/ActivityTitlebarControls.tsx @@ -1,4 +1,4 @@ -import { ArrowLeft, Bell } from 'lucide-react' +import { ArrowLeft, Bot } from 'lucide-react' import { useAppStore } from '@/store' import { Badge } from '@/components/ui/badge' @@ -42,7 +42,7 @@ export function ActivityTitlebarControls(): React.JSX.Element { )} - + {translate('auto.components.activity.ActivityTitlebarControls.d6a8de3934', 'agents')} diff --git a/src/renderer/src/components/activity/AgentsDrawer.tsx b/src/renderer/src/components/activity/AgentsDrawer.tsx new file mode 100644 index 000000000..69dc9f4d4 --- /dev/null +++ b/src/renderer/src/components/activity/AgentsDrawer.tsx @@ -0,0 +1,194 @@ +import React, { useEffect, useRef } from 'react' +import { X } from 'lucide-react' +import { useAppStore } from '@/store' +import { Button } from '@/components/ui/button' +import { + Sheet, + SheetContent, + SheetDescription, + SheetHeader, + SheetTitle +} from '@/components/ui/sheet' +import { useActivityUnreadCount } from './useActivityUnreadCount' +import ActivityPrototypePage from './ActivityPrototypePage' +import { translate } from '@/i18n/i18n' + +type AgentsDrawerProps = { + leftSidebarStyle?: React.CSSProperties + open: boolean + statusBarVisible: boolean + onOpenChange: (open: boolean) => void +} + +const WORKSPACE_TOP_CHROME_HEIGHT = 36 +const STATUS_BAR_RESERVE_HEIGHT = 24 + +const AGENTS_PANEL_KEEP_OPEN_SELECTOR = [ + '[data-agents-panel-trigger]', + '[data-radix-popper-content-wrapper]', + '[data-slot="dropdown-menu-content"]', + '[data-slot="context-menu-content"]', + '[data-slot="popover-content"]', + '[data-slot="dialog-content"]', + '[data-slot="dialog-overlay"]', + '[data-sonner-toast]', + '[role="dialog"][data-state="open"]', + '[role="alertdialog"][data-state="open"]', + '[role="menu"][data-state="open"]' +].join(', ') + +function isAgentsPanelKeepOpenTarget(target: EventTarget | null): boolean { + const element = + target instanceof Element ? target : target instanceof Node ? target.parentElement : null + return Boolean(element?.closest(AGENTS_PANEL_KEEP_OPEN_SELECTOR)) +} + +export default function AgentsDrawer({ + leftSidebarStyle, + open, + statusBarVisible, + onOpenChange +}: AgentsDrawerProps): React.JSX.Element { + const sidebarOpen = useAppStore((s) => s.sidebarOpen) + const sidebarWidth = useAppStore((s) => s.sidebarWidth) + const unreadCount = useActivityUnreadCount(open, 'agent-events') + const contentRef = useRef(null) + + const drawerLeftCss = sidebarOpen + ? `var(--workspace-sidebar-live-width, ${sidebarWidth}px)` + : '0px' + const drawerBottom = `${statusBarVisible ? STATUS_BAR_RESERVE_HEIGHT : 0}px` + + useEffect(() => { + if (!open) { + return + } + + const handlePointerDown = (event: PointerEvent): void => { + const content = contentRef.current?.closest('[data-slot="sheet-content"]') + if (!content) { + return + } + if (event.target instanceof Node && content.contains(event.target)) { + return + } + if (isAgentsPanelKeepOpenTarget(event.target)) { + return + } + const rect = content.getBoundingClientRect() + if (event.clientX > rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom) { + onOpenChange(false) + } + } + + document.addEventListener('pointerdown', handlePointerDown, true) + return () => document.removeEventListener('pointerdown', handlePointerDown, true) + }, [onOpenChange, open]) + + return ( + + { + // Why: avoid auto-focusing the first control (and its tooltip) on open. + event.preventDefault() + }} + onPointerDownOutside={(event) => { + const originalEvent = event.detail.originalEvent + const target = originalEvent.target + if (isAgentsPanelKeepOpenTarget(target)) { + event.preventDefault() + return + } + const liveDrawerLeft = + contentRef.current + ?.closest('[data-slot="sheet-content"]') + ?.getBoundingClientRect().left ?? (sidebarOpen ? sidebarWidth : 0) + const pointerX = + 'clientX' in originalEvent && typeof originalEvent.clientX === 'number' + ? originalEvent.clientX + : null + if (pointerX !== null && pointerX < liveDrawerLeft) { + // Why: keep the workspace sidebar interactive while the panel stays open. + event.preventDefault() + } + }} + onInteractOutside={(event) => { + const originalEvent = event.detail.originalEvent + const target = originalEvent.target + if (isAgentsPanelKeepOpenTarget(target)) { + event.preventDefault() + return + } + const liveDrawerLeft = + contentRef.current + ?.closest('[data-slot="sheet-content"]') + ?.getBoundingClientRect().left ?? (sidebarOpen ? sidebarWidth : 0) + const pointerX = + 'clientX' in originalEvent && typeof originalEvent.clientX === 'number' + ? originalEvent.clientX + : null + if (pointerX !== null && pointerX < liveDrawerLeft) { + event.preventDefault() + } + }} + > + + + {translate('auto.components.activity.AgentsDrawer.title', 'Agents')} + {unreadCount > 0 ? ( + + {unreadCount} {translate('auto.components.activity.AgentsDrawer.unread', 'unread')} + + ) : null} + + + {translate( + 'auto.components.activity.AgentsDrawer.description', + 'Browse agent sessions by status and open their terminals.' + )} + + + +
+ +
+ +
+ {open ? : null} +
+
+
+ ) +} diff --git a/src/renderer/src/components/activity/activity-canvas-demo-threads.ts b/src/renderer/src/components/activity/activity-canvas-demo-threads.ts new file mode 100644 index 000000000..47075705e --- /dev/null +++ b/src/renderer/src/components/activity/activity-canvas-demo-threads.ts @@ -0,0 +1,100 @@ +import type { ActivityCanvasThreadInput } from './activity-canvas-types' + +/** Sample graph used when the live agent feed is empty so the canvas is reviewable. */ +export function buildDemoCanvasThreads(): ActivityCanvasThreadInput[] { + const now = Date.now() + return [ + { + paneKey: 'demo:orchestrator', + paneTitle: 'Coordinate agents view prototype', + workspaceTitle: 'prototype-new-agents-view', + projectLabel: 'orca', + agentType: 'claude', + agentState: 'working', + agentStateLabel: 'Working', + responsePreview: 'Dispatching canvas layout + list toggle…', + latestTimestamp: now - 30_000, + unread: false, + parentPaneKey: null, + monogram: 'OR' + }, + { + paneKey: 'demo:a1', + paneTitle: 'Scaffold list/canvas view toggle', + workspaceTitle: 'prototype-new-agents-view', + projectLabel: 'orca', + agentType: 'claude', + agentState: 'done', + agentStateLabel: 'Done', + responsePreview: 'ToggleGroup wired into the filter bar.', + latestTimestamp: now - 120_000, + unread: false, + parentPaneKey: 'demo:orchestrator' + }, + { + paneKey: 'demo:a2', + paneTitle: 'Build agents canvas layout', + workspaceTitle: 'prototype-new-agents-view', + projectLabel: 'orca', + agentType: 'codex', + agentState: 'working', + agentStateLabel: 'Working', + responsePreview: 'Placing forest + isolated grid…', + latestTimestamp: now - 20_000, + unread: true, + parentPaneKey: 'demo:orchestrator' + }, + { + paneKey: 'demo:a3', + paneTitle: 'Style nodes like orca-viz', + workspaceTitle: 'prototype-new-agents-view', + projectLabel: 'orca', + agentType: 'claude', + agentState: 'waiting', + agentStateLabel: 'Waiting for input', + responsePreview: 'Need review on stripe colours.', + latestTimestamp: now - 45_000, + unread: true, + parentPaneKey: 'demo:orchestrator' + }, + { + paneKey: 'demo:a4', + paneTitle: 'Wire selection → terminal detail', + workspaceTitle: 'prototype-new-agents-view', + projectLabel: 'orca', + agentType: 'gemini', + agentState: 'blocked', + agentStateLabel: 'Blocked', + responsePreview: 'Blocked on portal target mount.', + latestTimestamp: now - 90_000, + unread: false, + parentPaneKey: 'demo:a2' + }, + { + paneKey: 'demo:solo-1', + paneTitle: 'Explore login race fix', + workspaceTitle: 'mobile-auth', + projectLabel: 'app', + agentType: 'cursor', + agentState: 'done', + agentStateLabel: 'Done', + responsePreview: 'PR opened.', + latestTimestamp: now - 3_600_000, + unread: false, + parentPaneKey: null + }, + { + paneKey: 'demo:solo-2', + paneTitle: 'Docs pass for agents view', + workspaceTitle: 'prototype-new-agents-view', + projectLabel: 'orca', + agentType: 'claude', + agentState: 'interrupted', + agentStateLabel: 'Interrupted', + responsePreview: 'Stopped mid-draft.', + latestTimestamp: now - 7_200_000, + unread: false, + parentPaneKey: null + } + ] +} diff --git a/src/renderer/src/components/activity/activity-canvas-layout.test.ts b/src/renderer/src/components/activity/activity-canvas-layout.test.ts new file mode 100644 index 000000000..c28e07daa --- /dev/null +++ b/src/renderer/src/components/activity/activity-canvas-layout.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it } from 'vitest' + +import { + assignAgentLooks, + layoutActivityCanvas, + type ActivityCanvasThreadInput +} from './activity-canvas-layout' +import { buildDemoCanvasThreads } from './activity-canvas-demo-threads' + +function thread( + partial: Partial & Pick +): ActivityCanvasThreadInput { + return { + paneTitle: partial.paneTitle ?? partial.paneKey, + workspaceTitle: partial.workspaceTitle ?? 'ws', + projectLabel: partial.projectLabel ?? 'proj', + agentType: partial.agentType ?? 'claude', + agentState: partial.agentState ?? 'working', + agentStateLabel: partial.agentStateLabel ?? 'Working', + responsePreview: partial.responsePreview ?? '', + latestTimestamp: partial.latestTimestamp ?? 1, + unread: partial.unread ?? false, + parentPaneKey: partial.parentPaneKey ?? null, + ...partial + } +} + +describe('layoutActivityCanvas', () => { + it('packs agents with no edges into an isolated cluster', () => { + const layout = layoutActivityCanvas([ + thread({ paneKey: 'a', latestTimestamp: 3 }), + thread({ paneKey: 'b', latestTimestamp: 2 }), + thread({ paneKey: 'c', latestTimestamp: 1 }) + ]) + expect(layout.linkedCount).toBe(0) + expect(layout.isolatedCount).toBe(3) + expect(layout.edges).toHaveLength(0) + expect(layout.clusters).toHaveLength(1) + expect(layout.nodes.every((n) => n.isolated)).toBe(true) + }) + + it('places parent above children and draws parent→child edges', () => { + const layout = layoutActivityCanvas([ + thread({ paneKey: 'root', parentPaneKey: null }), + thread({ paneKey: 'child-1', parentPaneKey: 'root' }), + thread({ paneKey: 'child-2', parentPaneKey: 'root' }) + ]) + expect(layout.linkedCount).toBe(3) + expect(layout.isolatedCount).toBe(0) + expect(layout.edges).toHaveLength(2) + + const root = layout.nodes.find((n) => n.id === 'root')! + const child1 = layout.nodes.find((n) => n.id === 'child-1')! + const child2 = layout.nodes.find((n) => n.id === 'child-2')! + expect(root.y).toBeLessThan(child1.y) + expect(root.y).toBeLessThan(child2.y) + expect(root.isolated).toBe(false) + }) + + it('ignores parentPaneKey when the parent is not in the thread set', () => { + const layout = layoutActivityCanvas([ + thread({ paneKey: 'orphan', parentPaneKey: 'missing-parent' }) + ]) + expect(layout.isolatedCount).toBe(1) + expect(layout.edges).toHaveLength(0) + }) + + it('assigns stable monograms with roots before children', () => { + const looks = assignAgentLooks([ + thread({ paneKey: 'child', parentPaneKey: 'root' }), + thread({ paneKey: 'root', parentPaneKey: null }), + thread({ paneKey: 'solo', parentPaneKey: null }) + ]) + expect(looks.get('root')?.monogram).toMatch(/^A\d+$/) + expect(looks.get('solo')?.monogram).toMatch(/^A\d+$/) + expect(looks.get('child')?.monogram).toMatch(/^A\d+$/) + // Roots sort before children; root + solo come first alphabetically as roots. + expect(looks.get('root')!.index).toBeLessThan(looks.get('child')!.index) + }) + + it('lays out the demo sample without empty geometry', () => { + const layout = layoutActivityCanvas(buildDemoCanvasThreads()) + expect(layout.nodes.length).toBeGreaterThan(3) + expect(layout.edges.length).toBeGreaterThan(0) + expect(layout.width).toBeGreaterThan(200) + expect(layout.height).toBeGreaterThan(200) + }) +}) diff --git a/src/renderer/src/components/activity/activity-canvas-layout.ts b/src/renderer/src/components/activity/activity-canvas-layout.ts new file mode 100644 index 000000000..c5ad0b95c --- /dev/null +++ b/src/renderer/src/components/activity/activity-canvas-layout.ts @@ -0,0 +1,335 @@ +/** + * Pure layout for the Activity canvas prototype. + * + * Inspired by orca-viz's DAG canvas: status keeps the hue, agent identity is a + * monogram + left stripe, and parent→child edges come from orchestration + * `parentPaneKey` when present. Agents with no edges pack into an isolated grid + * (the common case outside an active orchestration run). + */ + +import { + ACTIVITY_CANVAS_NODE_HEIGHT, + ACTIVITY_CANVAS_NODE_WIDTH, + AGENT_STRIPE_COLOURS, + type ActivityCanvasAgentLook, + type ActivityCanvasCluster, + type ActivityCanvasEdge, + type ActivityCanvasLayout, + type ActivityCanvasNode, + type ActivityCanvasThreadInput +} from './activity-canvas-types' + +export type { + ActivityCanvasAgentLook, + ActivityCanvasAgentState, + ActivityCanvasCluster, + ActivityCanvasEdge, + ActivityCanvasLayout, + ActivityCanvasNode, + ActivityCanvasThreadInput +} from './activity-canvas-types' +export { + ACTIVITY_CANVAS_NODE_HEIGHT, + ACTIVITY_CANVAS_NODE_WIDTH, + AGENT_STRIPE_COLOURS +} from './activity-canvas-types' + +const NODE_GAP_X = 48 +const NODE_GAP_Y = 56 +const ISOLATED_GAP_X = 28 +const ISOLATED_GAP_Y = 28 +const ISOLATED_COLUMNS = 3 +const TREE_ROOT_GAP_X = 80 +const CANVAS_PAD = 48 + +export function agentLookAt(index: number): ActivityCanvasAgentLook { + const colour = AGENT_STRIPE_COLOURS[index % AGENT_STRIPE_COLOURS.length]! + return { + monogram: `A${index + 1}`, + colour, + index + } +} + +function hashPaneKey(paneKey: string): number { + let hash = 0 + for (let i = 0; i < paneKey.length; i++) { + hash = (hash * 31 + paneKey.charCodeAt(i)) | 0 + } + return Math.abs(hash) +} + +/** + * Assign monograms deterministically: coordinators first (no parent in set), + * then children in stable paneKey order so A1/A2 stay stable across re-layouts. + */ +export function assignAgentLooks( + threads: ActivityCanvasThreadInput[] +): Map { + const paneKeys = new Set(threads.map((t) => t.paneKey)) + const roots = threads + .filter((t) => !t.parentPaneKey || !paneKeys.has(t.parentPaneKey)) + .sort((a, b) => a.paneKey.localeCompare(b.paneKey)) + const children = threads + .filter((t) => t.parentPaneKey && paneKeys.has(t.parentPaneKey)) + .sort((a, b) => a.paneKey.localeCompare(b.paneKey)) + const ordered = [...roots, ...children] + const looks = new Map() + ordered.forEach((thread, index) => { + const base = agentLookAt(index) + looks.set(thread.paneKey, { + ...base, + monogram: thread.monogram ?? base.monogram + }) + }) + return looks +} + +type ForestNode = { + thread: ActivityCanvasThreadInput + children: ForestNode[] +} + +type ForestEdge = { sourceId: string; targetId: string } + +function buildForest(threads: ActivityCanvasThreadInput[]): { + roots: ForestNode[] + isolated: ActivityCanvasThreadInput[] + edges: ForestEdge[] +} { + const byKey = new Map(threads.map((t) => [t.paneKey, t])) + const childIds = new Set() + const edges: ForestEdge[] = [] + + for (const thread of threads) { + const parent = thread.parentPaneKey + if (parent && byKey.has(parent) && parent !== thread.paneKey) { + childIds.add(thread.paneKey) + edges.push({ sourceId: parent, targetId: thread.paneKey }) + } + } + + // Why: a node is "linked" if it participates in any edge; pure singletons + // pack into the isolated grid so a flat agent list does not look like a + // broken empty DAG (orca-viz SPEC §7.5). + const linkedIds = new Set() + for (const edge of edges) { + linkedIds.add(edge.sourceId) + linkedIds.add(edge.targetId) + } + + const childrenByParent = new Map() + for (const edge of edges) { + const list = childrenByParent.get(edge.sourceId) ?? [] + const child = byKey.get(edge.targetId) + if (child) { + list.push(child) + } + childrenByParent.set(edge.sourceId, list) + } + + function toForestNode(thread: ActivityCanvasThreadInput): ForestNode { + const kids = (childrenByParent.get(thread.paneKey) ?? []) + .slice() + .sort((a, b) => a.paneKey.localeCompare(b.paneKey)) + .map(toForestNode) + return { thread, children: kids } + } + + const roots: ForestNode[] = [] + const isolated: ActivityCanvasThreadInput[] = [] + + for (const thread of threads) { + if (!linkedIds.has(thread.paneKey)) { + isolated.push(thread) + continue + } + if (!childIds.has(thread.paneKey)) { + roots.push(toForestNode(thread)) + } + } + + roots.sort((a, b) => a.thread.paneKey.localeCompare(b.thread.paneKey)) + isolated.sort((a, b) => b.latestTimestamp - a.latestTimestamp) + + return { roots, isolated, edges } +} + +type Placed = { id: string; x: number; y: number; depth: number } + +/** Recursive tidy tree: children centered under parent, left-to-right siblings. */ +function placeTree( + node: ForestNode, + depth: number, + nextLeafX: { value: number }, + placed: Placed[] +): { x: number; width: number } { + if (node.children.length === 0) { + const x = nextLeafX.value + nextLeafX.value += ACTIVITY_CANVAS_NODE_WIDTH + NODE_GAP_X + placed.push({ + id: node.thread.paneKey, + x, + y: depth * (ACTIVITY_CANVAS_NODE_HEIGHT + NODE_GAP_Y), + depth + }) + return { x, width: ACTIVITY_CANVAS_NODE_WIDTH } + } + + const childBoxes = node.children.map((child) => placeTree(child, depth + 1, nextLeafX, placed)) + const first = childBoxes.at(0)! + const last = childBoxes.at(-1)! + const left = first.x + const right = last.x + last.width + const x = left + (right - left - ACTIVITY_CANVAS_NODE_WIDTH) / 2 + placed.push({ + id: node.thread.paneKey, + x, + y: depth * (ACTIVITY_CANVAS_NODE_HEIGHT + NODE_GAP_Y), + depth + }) + return { x: left, width: right - left } +} + +function edgePath( + source: { x: number; y: number; width: number; height: number }, + target: { x: number; y: number; width: number; height: number } +): string { + const x1 = source.x + source.width / 2 + const y1 = source.y + source.height + const x2 = target.x + target.width / 2 + const y2 = target.y + const midY = (y1 + y2) / 2 + return `M ${x1} ${y1} C ${x1} ${midY}, ${x2} ${midY}, ${x2} ${y2}` +} + +export function layoutActivityCanvas(threads: ActivityCanvasThreadInput[]): ActivityCanvasLayout { + if (threads.length === 0) { + return { + nodes: [], + edges: [], + clusters: [], + width: 640, + height: 400, + linkedCount: 0, + isolatedCount: 0 + } + } + + const looks = assignAgentLooks(threads) + const { roots, isolated, edges: rawEdges } = buildForest(threads) + const placed: Placed[] = [] + let cursorX = CANVAS_PAD + let treeBottom = CANVAS_PAD + + for (const root of roots) { + const treePlaced: Placed[] = [] + const nextLeafX = { value: 0 } + placeTree(root, 0, nextLeafX, treePlaced) + let minX = Infinity + for (const p of treePlaced) { + minX = Math.min(minX, p.x) + } + const offsetX = cursorX - (Number.isFinite(minX) ? minX : 0) + for (const p of treePlaced) { + placed.push({ + ...p, + x: p.x + offsetX, + y: p.y + CANVAS_PAD + }) + treeBottom = Math.max(treeBottom, p.y + CANVAS_PAD + ACTIVITY_CANVAS_NODE_HEIGHT) + } + const treeWidth = nextLeafX.value + cursorX += treeWidth + TREE_ROOT_GAP_X + } + + const linkedNodes: ActivityCanvasNode[] = placed.map((p) => { + const thread = threads.find((t) => t.paneKey === p.id)! + return { + id: p.id, + x: p.x, + y: p.y, + width: ACTIVITY_CANVAS_NODE_WIDTH, + height: ACTIVITY_CANVAS_NODE_HEIGHT, + isolated: false, + thread, + agent: looks.get(p.id) ?? agentLookAt(hashPaneKey(p.id) % AGENT_STRIPE_COLOURS.length) + } + }) + + // Isolated grid sits below the forest (or at origin when there is no forest). + const isolatedOriginY = linkedNodes.length > 0 ? treeBottom + NODE_GAP_Y + 24 : CANVAS_PAD + const isolatedOriginX = CANVAS_PAD + const isolatedNodes: ActivityCanvasNode[] = isolated.map((thread, index) => { + const col = index % ISOLATED_COLUMNS + const row = Math.floor(index / ISOLATED_COLUMNS) + return { + id: thread.paneKey, + x: isolatedOriginX + col * (ACTIVITY_CANVAS_NODE_WIDTH + ISOLATED_GAP_X), + y: isolatedOriginY + row * (ACTIVITY_CANVAS_NODE_HEIGHT + ISOLATED_GAP_Y), + width: ACTIVITY_CANVAS_NODE_WIDTH, + height: ACTIVITY_CANVAS_NODE_HEIGHT, + isolated: true, + thread, + agent: looks.get(thread.paneKey) ?? agentLookAt(index) + } + }) + + const nodes = [...linkedNodes, ...isolatedNodes] + const nodeById = new Map(nodes.map((n) => [n.id, n])) + + const edges: ActivityCanvasEdge[] = rawEdges + .map((edge) => { + const source = nodeById.get(edge.sourceId) + const target = nodeById.get(edge.targetId) + if (!source || !target) { + return null + } + return { + id: `${edge.sourceId}->${edge.targetId}`, + sourceId: edge.sourceId, + targetId: edge.targetId, + path: edgePath(source, target) + } + }) + .filter((e): e is ActivityCanvasEdge => e !== null) + + const clusters: ActivityCanvasCluster[] = [] + if (isolatedNodes.length > 0) { + const xs = isolatedNodes.map((n) => n.x) + const ys = isolatedNodes.map((n) => n.y) + const minX = Math.min(...xs) - 16 + const minY = Math.min(...ys) - 36 + const maxX = Math.max(...isolatedNodes.map((n) => n.x + n.width)) + 16 + const maxY = Math.max(...isolatedNodes.map((n) => n.y + n.height)) + 16 + clusters.push({ + id: 'isolated', + label: `Isolated agents (${isolatedNodes.length})`, + x: minX, + y: minY, + width: maxX - minX, + height: maxY - minY + }) + } + + let maxX = CANVAS_PAD + 400 + let maxY = CANVAS_PAD + 280 + for (const n of nodes) { + maxX = Math.max(maxX, n.x + n.width + CANVAS_PAD) + maxY = Math.max(maxY, n.y + n.height + CANVAS_PAD) + } + for (const c of clusters) { + maxX = Math.max(maxX, c.x + c.width + CANVAS_PAD) + maxY = Math.max(maxY, c.y + c.height + CANVAS_PAD) + } + + return { + nodes, + edges, + clusters, + width: maxX, + height: maxY, + linkedCount: linkedNodes.length, + isolatedCount: isolatedNodes.length + } +} diff --git a/src/renderer/src/components/activity/activity-canvas-types.ts b/src/renderer/src/components/activity/activity-canvas-types.ts new file mode 100644 index 000000000..8dee75627 --- /dev/null +++ b/src/renderer/src/components/activity/activity-canvas-types.ts @@ -0,0 +1,81 @@ +import type { AgentStatusState, AgentType } from '../../../../shared/agent-status-types' + +export const ACTIVITY_CANVAS_NODE_WIDTH = 240 +export const ACTIVITY_CANVAS_NODE_HEIGHT = 92 + +/** Stable palette for agent monograms — distinct from status fills. */ +export const AGENT_STRIPE_COLOURS = [ + '#38bdf8', // sky + '#a78bfa', // violet + '#f472b6', // pink + '#34d399', // emerald + '#fbbf24', // amber + '#fb7185', // rose + '#22d3ee', // cyan + '#c084fc' // purple +] as const + +export type ActivityCanvasAgentState = + | Extract + | 'interrupted' + +export type ActivityCanvasThreadInput = { + paneKey: string + paneTitle: string + workspaceTitle: string + projectLabel: string + agentType: AgentType + agentState: ActivityCanvasAgentState + agentStateLabel: string + responsePreview: string + latestTimestamp: number + unread: boolean + /** Orchestration parent pane, when this agent was dispatched by another. */ + parentPaneKey: string | null + /** Optional monogram override; otherwise assigned by stable index. */ + monogram?: string +} + +export type ActivityCanvasAgentLook = { + monogram: string + colour: string + index: number +} + +export type ActivityCanvasNode = { + id: string + x: number + y: number + width: number + height: number + isolated: boolean + thread: ActivityCanvasThreadInput + agent: ActivityCanvasAgentLook +} + +export type ActivityCanvasEdge = { + id: string + sourceId: string + targetId: string + /** Pixel geometry after layout. */ + path: string +} + +export type ActivityCanvasCluster = { + id: string + label: string + x: number + y: number + width: number + height: number +} + +export type ActivityCanvasLayout = { + nodes: ActivityCanvasNode[] + edges: ActivityCanvasEdge[] + clusters: ActivityCanvasCluster[] + width: number + height: number + linkedCount: number + isolatedCount: number +} diff --git a/src/renderer/src/components/activity/activity-thread-lineage.test.ts b/src/renderer/src/components/activity/activity-thread-lineage.test.ts new file mode 100644 index 000000000..1545fbd37 --- /dev/null +++ b/src/renderer/src/components/activity/activity-thread-lineage.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it } from 'vitest' + +import { + buildActivityThreadLineageItems, + resolveActivityThreadParentPaneKey, + type ActivityLineageThreadLike +} from './activity-thread-lineage' + +function thread( + partial: Partial & Pick +): ActivityLineageThreadLike { + return { + paneTitle: partial.paneTitle ?? partial.paneKey, + terminalHandle: partial.terminalHandle ?? null, + parentPaneKey: partial.parentPaneKey ?? null, + parentTerminalHandle: partial.parentTerminalHandle ?? null, + coordinatorHandle: partial.coordinatorHandle ?? null, + ...partial + } +} + +describe('buildActivityThreadLineageItems', () => { + it('nests children under parents and reports relationship metadata', () => { + const items = buildActivityThreadLineageItems([ + thread({ paneKey: 'child-b', paneTitle: 'Worker B', parentPaneKey: 'root' }), + thread({ paneKey: 'root', paneTitle: 'Coordinator' }), + thread({ paneKey: 'child-a', paneTitle: 'Worker A', parentPaneKey: 'root' }), + thread({ paneKey: 'solo', paneTitle: 'Solo' }) + ]) + + expect(items.map((item) => item.thread.paneKey)).toEqual(['root', 'child-b', 'child-a', 'solo']) + expect(items[0]?.lineage).toMatchObject({ + depth: 0, + childCount: 2, + parentTitle: null + }) + expect(items[1]?.lineage).toMatchObject({ + depth: 1, + parentPaneKey: 'root', + parentTitle: 'Coordinator', + isFirstSibling: true, + isLastSibling: false + }) + expect(items[2]?.lineage).toMatchObject({ + depth: 1, + parentTitle: 'Coordinator', + isFirstSibling: false, + isLastSibling: true + }) + expect(items[3]?.lineage.depth).toBe(0) + }) + + it('resolves parent via terminal handle when pane key is missing', () => { + const parent = thread({ + paneKey: 'parent', + paneTitle: 'Parent', + terminalHandle: 'term_parent' + }) + const child = thread({ + paneKey: 'child', + paneTitle: 'Child', + parentTerminalHandle: 'term_parent' + }) + const byPaneKey = new Map([ + [parent.paneKey, parent], + [child.paneKey, child] + ]) + const byHandle = new Map([['term_parent', 'parent']]) + expect(resolveActivityThreadParentPaneKey(child, byPaneKey, byHandle)).toBe('parent') + + const items = buildActivityThreadLineageItems([child, parent]) + expect(items.map((item) => item.thread.paneKey)).toEqual(['parent', 'child']) + expect(items[1]?.lineage.parentTitle).toBe('Parent') + }) + + it('keeps cycle participants visible as roots', () => { + const items = buildActivityThreadLineageItems([ + thread({ paneKey: 'a', parentPaneKey: 'b' }), + thread({ paneKey: 'b', parentPaneKey: 'a' }) + ]) + expect(items).toHaveLength(2) + expect(items.every((item) => item.lineage.depth === 0)).toBe(true) + }) +}) diff --git a/src/renderer/src/components/activity/activity-thread-lineage.ts b/src/renderer/src/components/activity/activity-thread-lineage.ts new file mode 100644 index 000000000..4fc67e516 --- /dev/null +++ b/src/renderer/src/components/activity/activity-thread-lineage.ts @@ -0,0 +1,200 @@ +/** + * Orchestration lineage for Activity list rows. + * + * Mirrors dashboard `agent-row-lineage-model`: resolve parent via + * `parentPaneKey` / terminal handles, nest children under parents, and keep + * cycle/unreachable rows visible as roots. + */ + +export type ActivityLineageThreadLike = { + paneKey: string + paneTitle: string + terminalHandle?: string | null + parentPaneKey?: string | null + parentTerminalHandle?: string | null + coordinatorHandle?: string | null +} + +export type ActivityThreadLineageMeta = { + depth: number + parentPaneKey: string | null + parentTitle: string | null + childCount: number + isFirstSibling: boolean + isLastSibling: boolean +} + +export type ActivityThreadLineageItem = { + thread: T + lineage: ActivityThreadLineageMeta +} + +function buildPaneKeyByTerminalHandle( + threads: readonly T[] +): Map { + const map = new Map() + for (const thread of threads) { + const handle = thread.terminalHandle?.trim() + if (handle && !map.has(handle)) { + map.set(handle, thread.paneKey) + } + } + return map +} + +export function resolveActivityThreadParentPaneKey( + thread: T, + byPaneKey: ReadonlyMap, + paneKeyByTerminalHandle: ReadonlyMap +): string | null { + const explicit = thread.parentPaneKey?.trim() + if (explicit && explicit !== thread.paneKey && byPaneKey.has(explicit)) { + return explicit + } + + for (const handle of [thread.parentTerminalHandle, thread.coordinatorHandle]) { + const trimmed = handle?.trim() + if (!trimmed) { + continue + } + const parentPaneKey = paneKeyByTerminalHandle.get(trimmed) + if (parentPaneKey && parentPaneKey !== thread.paneKey && byPaneKey.has(parentPaneKey)) { + return parentPaneKey + } + } + + return null +} + +/** + * Flatten threads into parent-then-children order with lineage metadata for + * indentation and relationship captions in the list. + */ +export function buildActivityThreadLineageItems( + threads: readonly T[] +): ActivityThreadLineageItem[] { + if (threads.length === 0) { + return [] + } + + const byPaneKey = new Map() + for (const thread of threads) { + if (!byPaneKey.has(thread.paneKey)) { + byPaneKey.set(thread.paneKey, thread) + } + } + const paneKeyByTerminalHandle = buildPaneKeyByTerminalHandle(threads) + const childrenByParent = new Map() + const childPaneKeys = new Set() + + for (const thread of threads) { + const parentPaneKey = resolveActivityThreadParentPaneKey( + thread, + byPaneKey, + paneKeyByTerminalHandle + ) + if (!parentPaneKey) { + continue + } + childPaneKeys.add(thread.paneKey) + const siblings = childrenByParent.get(parentPaneKey) + if (siblings) { + siblings.push(thread) + } else { + childrenByParent.set(parentPaneKey, [thread]) + } + } + + // Preserve caller order among roots / among siblings (group order, recency). + const orderIndex = new Map(threads.map((thread, index) => [thread.paneKey, index])) + const sortByCallerOrder = (a: T, b: T): number => + (orderIndex.get(a.paneKey) ?? 0) - (orderIndex.get(b.paneKey) ?? 0) + + for (const [parentPaneKey, siblings] of childrenByParent) { + childrenByParent.set(parentPaneKey, [...siblings].sort(sortByCallerOrder)) + } + + let rootThreads = threads.filter((thread) => !childPaneKeys.has(thread.paneKey)) + if (rootThreads.length === 0) { + // Why: closed cycles must not hide every participant. + return threads.map((thread) => ({ + thread, + lineage: { + depth: 0, + parentPaneKey: null, + parentTitle: null, + childCount: 0, + isFirstSibling: true, + isLastSibling: true + } + })) + } + + const reachable = new Set() + const visit = (thread: T, ancestors: ReadonlySet): void => { + if (reachable.has(thread.paneKey) || ancestors.has(thread.paneKey)) { + return + } + reachable.add(thread.paneKey) + const nextAncestors = new Set(ancestors) + nextAncestors.add(thread.paneKey) + for (const child of childrenByParent.get(thread.paneKey) ?? []) { + visit(child, nextAncestors) + } + } + for (const root of rootThreads) { + visit(root, new Set()) + } + + for (const thread of threads) { + if (reachable.has(thread.paneKey)) { + continue + } + // Unreachable (partial cycle): promote to root and detach edges. + if (!rootThreads.some((root) => root.paneKey === thread.paneKey)) { + rootThreads = [...rootThreads, thread] + } + childPaneKeys.delete(thread.paneKey) + childrenByParent.delete(thread.paneKey) + for (const [parentPaneKey, siblings] of childrenByParent) { + const next = siblings.filter((sibling) => sibling.paneKey !== thread.paneKey) + if (next.length === 0) { + childrenByParent.delete(parentPaneKey) + } else if (next.length !== siblings.length) { + childrenByParent.set(parentPaneKey, next) + } + } + } + + rootThreads = [...rootThreads].sort(sortByCallerOrder) + + const items: ActivityThreadLineageItem[] = [] + const walk = (thread: T, depth: number, siblingIndex: number, siblingCount: number): void => { + const children = childrenByParent.get(thread.paneKey) ?? [] + const parentPaneKey = + depth > 0 + ? resolveActivityThreadParentPaneKey(thread, byPaneKey, paneKeyByTerminalHandle) + : null + const parent = parentPaneKey ? byPaneKey.get(parentPaneKey) : undefined + items.push({ + thread, + lineage: { + depth, + parentPaneKey, + parentTitle: parent?.paneTitle ?? null, + childCount: children.length, + isFirstSibling: siblingIndex === 0, + isLastSibling: siblingIndex === siblingCount - 1 + } + }) + children.forEach((child, index) => { + walk(child, depth + 1, index, children.length) + }) + } + + rootThreads.forEach((root, index) => { + walk(root, 0, index, rootThreads.length) + }) + + return items +} diff --git a/src/renderer/src/components/activity/agents-panel-events.ts b/src/renderer/src/components/activity/agents-panel-events.ts new file mode 100644 index 000000000..9c219edba --- /dev/null +++ b/src/renderer/src/components/activity/agents-panel-events.ts @@ -0,0 +1,16 @@ +export const OPEN_AGENTS_PANEL_EVENT = 'orca:open-agents-panel' +export const CLOSE_AGENTS_PANEL_EVENT = 'orca:close-agents-panel' + +export function requestOpenAgentsPanel(): void { + if (typeof window === 'undefined') { + return + } + window.dispatchEvent(new Event(OPEN_AGENTS_PANEL_EVENT)) +} + +export function requestCloseAgentsPanel(): void { + if (typeof window === 'undefined') { + return + } + window.dispatchEvent(new Event(CLOSE_AGENTS_PANEL_EVENT)) +} diff --git a/src/renderer/src/components/activity/useAgentsPanel.ts b/src/renderer/src/components/activity/useAgentsPanel.ts new file mode 100644 index 000000000..d924ecd5c --- /dev/null +++ b/src/renderer/src/components/activity/useAgentsPanel.ts @@ -0,0 +1,106 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { CLOSE_AGENTS_PANEL_EVENT, OPEN_AGENTS_PANEL_EVENT } from './agents-panel-events' + +const AGENTS_PANEL_ESCAPE_BLOCKING_OVERLAY_SELECTOR = [ + '[data-slot="dropdown-menu-content"][data-state="open"]', + '[data-slot="context-menu-content"][data-state="open"]', + '[data-slot="popover-content"][data-state="open"]', + '[role="dialog"][data-state="open"]:not([data-agents-panel-sheet])', + '[role="alertdialog"][data-state="open"]', + '[role="menu"][data-state="open"]', + '[role="listbox"][data-state="open"]' +].join(', ') + +export type AgentsPanelState = { + agentsPanelOpen: boolean + openAgentsPanel: () => void + closeAgentsPanel: () => void + toggleAgentsPanel: () => void + handleAgentsPanelOpenChange: (open: boolean) => void +} + +export function useAgentsPanel(): AgentsPanelState { + const [agentsPanelOpen, setAgentsPanelOpen] = useState(false) + const agentsPanelOpenRef = useRef(agentsPanelOpen) + agentsPanelOpenRef.current = agentsPanelOpen + + const openAgentsPanel = useCallback(() => { + if (agentsPanelOpenRef.current) { + return + } + agentsPanelOpenRef.current = true + setAgentsPanelOpen(true) + }, []) + + const closeAgentsPanel = useCallback(() => { + if (!agentsPanelOpenRef.current) { + return + } + agentsPanelOpenRef.current = false + setAgentsPanelOpen(false) + }, []) + + const handleAgentsPanelOpenChange = useCallback( + (open: boolean) => { + if (open) { + openAgentsPanel() + return + } + closeAgentsPanel() + }, + [closeAgentsPanel, openAgentsPanel] + ) + + const toggleAgentsPanel = useCallback(() => { + if (agentsPanelOpenRef.current) { + closeAgentsPanel() + return + } + openAgentsPanel() + }, [closeAgentsPanel, openAgentsPanel]) + + useEffect(() => { + if (!agentsPanelOpen) { + return + } + + const handleKeyDown = (event: KeyboardEvent): void => { + if (event.key !== 'Escape') { + return + } + // Why: Escape should dismiss nested menus/dialogs before this companion panel. + if (document.querySelector(AGENTS_PANEL_ESCAPE_BLOCKING_OVERLAY_SELECTOR)) { + return + } + event.preventDefault() + closeAgentsPanel() + } + + // Why: non-modal companion panel — focus may be outside the sheet when Escape fires. + document.addEventListener('keydown', handleKeyDown, true) + return () => document.removeEventListener('keydown', handleKeyDown, true) + }, [agentsPanelOpen, closeAgentsPanel]) + + useEffect(() => { + const onOpen = (): void => { + openAgentsPanel() + } + const onClose = (): void => { + closeAgentsPanel() + } + window.addEventListener(OPEN_AGENTS_PANEL_EVENT, onOpen) + window.addEventListener(CLOSE_AGENTS_PANEL_EVENT, onClose) + return () => { + window.removeEventListener(OPEN_AGENTS_PANEL_EVENT, onOpen) + window.removeEventListener(CLOSE_AGENTS_PANEL_EVENT, onClose) + } + }, [closeAgentsPanel, openAgentsPanel]) + + return { + agentsPanelOpen, + openAgentsPanel, + closeAgentsPanel, + toggleAgentsPanel, + handleAgentsPanelOpenChange + } +} diff --git a/src/renderer/src/components/settings/ExperimentalPane.tsx b/src/renderer/src/components/settings/ExperimentalPane.tsx index 2aaa38d6b..fb321c854 100644 --- a/src/renderer/src/components/settings/ExperimentalPane.tsx +++ b/src/renderer/src/components/settings/ExperimentalPane.tsx @@ -34,9 +34,6 @@ export function ExperimentalPane({ }: ExperimentalPaneProps): React.JSX.Element { const searchQuery = useAppStore((s) => s.settingsSearchQuery) const showPet = matchesSettingsSearch(searchQuery, [getExperimentalSearchEntry().pet]) - const showAgentsView = matchesSettingsSearch(searchQuery, [ - getExperimentalSearchEntry().agentsView - ]) const showNativeChat = matchesSettingsSearch(searchQuery, [ getExperimentalSearchEntry().nativeChat ]) @@ -103,51 +100,6 @@ export function ExperimentalPane({ ) : null} - {showAgentsView ? ( - -
-
- -

- {translate( - 'auto.components.settings.ExperimentalPane.0277901cf7', - 'Adds an Agents entry to the left sidebar with a threaded worktree feed for completed agents, blocking questions, unread state, and worktree creation events. Experimental — the event model and UI may change.' - )} -

-
- -
-
- ) : 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..24db5171f 100644 --- a/src/renderer/src/components/settings/experimental-search.ts +++ b/src/renderer/src/components/settings/experimental-search.ts @@ -46,55 +46,6 @@ export const getExperimentalPaneSearchEntries = createLocalizedCatalog( ) ] }, - { - title: translate('auto.components.settings.experimental.search.ccc5548ac5', 'Agents View'), - description: translate( - 'auto.components.settings.experimental.search.4d63251595', - 'Threaded left-sidebar feed for agent completions and blocking states.' - ), - keywords: [ - ...translateSearchKeyword( - 'auto.components.settings.experimental.search.0d24759f14', - 'experimental' - ), - ...translateSearchKeyword( - 'auto.components.settings.experimental.search.fa72e71f05', - 'agents' - ), - ...translateSearchKeyword( - 'auto.components.settings.experimental.search.92a9357d1f', - 'agents view' - ), - ...translateSearchKeyword( - 'auto.components.settings.experimental.search.244a0ecd3d', - 'activity' - ), - ...translateSearchKeyword( - 'auto.components.settings.experimental.search.d01b3882ba', - 'notifications' - ), - ...translateSearchKeyword( - 'auto.components.settings.experimental.search.10b52f79c1', - 'worktrees' - ), - ...translateSearchKeyword( - 'auto.components.settings.experimental.search.ca5d1f3f46', - 'timeline' - ), - ...translateSearchKeyword( - 'auto.components.settings.experimental.search.7b79081695', - 'unread' - ), - ...translateSearchKeyword( - 'auto.components.settings.experimental.search.8facf10138', - 'bell' - ), - ...translateSearchKeyword( - 'auto.components.settings.experimental.search.fe5688b761', - 'sidebar' - ) - ] - }, getNativeChatExperimentalSearchEntry(), { title: translate( @@ -203,9 +154,6 @@ function findEntry(title: string): SettingsSearchEntry { export function getExperimentalSearchEntry() { return { pet: findEntry(translate('auto.components.settings.experimental.search.87d99e634b', 'Pet')), - agentsView: findEntry( - translate('auto.components.settings.experimental.search.ccc5548ac5', 'Agents View') - ), 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..b962e15d3 100644 --- a/src/renderer/src/components/sidebar/SidebarNav.test.tsx +++ b/src/renderer/src/components/sidebar/SidebarNav.test.tsx @@ -13,7 +13,6 @@ const mocks = vi.hoisted(() => ({ state: {} as Record, openTaskPage: vi.fn(), openAutomationsPage: vi.fn(), - openActivityPage: vi.fn(), openMobilePage: vi.fn(), openModal: vi.fn(), updateSettings: vi.fn(), @@ -35,10 +34,6 @@ vi.mock('@/store/selectors', () => ({ ) })) -vi.mock('@/components/activity/useActivityUnreadCount', () => ({ - useActivityUnreadCount: () => 0 -})) - vi.mock('@/hooks/useShortcutLabel', () => ({ useShortcutKeyComboDetails: () => [{ keys: ['⌘', 'J'], doubleTap: false }] })) @@ -77,7 +72,6 @@ vi.mock('@/components/ui/context-menu', () => ({ import { getSetupGuideSidebarEntryReady, - shouldShowAgentsButton, shouldShowAutomationsButton, shouldShowMobileButton, shouldShowSetupGuideEntry @@ -119,7 +113,6 @@ function setSidebarState({ activeView: 'worktrees', openTaskPage: mocks.openTaskPage, openAutomationsPage: mocks.openAutomationsPage, - openActivityPage: mocks.openActivityPage, openMobilePage: mocks.openMobilePage, openModal: mocks.openModal, updateSettings: mocks.updateSettings, @@ -205,28 +198,6 @@ describe('SidebarNav', () => { setSidebarState() }) - it('hides the Agents entry while settings are loading', () => { - expect(shouldShowAgentsButton(null)).toBe(false) - }) - - it('hides the Agents entry while the experimental Agents view is off', () => { - expect( - shouldShowAgentsButton({ - ...getDefaultSettings('/tmp'), - experimentalActivity: false - }) - ).toBe(false) - }) - - it('shows the Agents entry when the experimental Agents view is on', () => { - expect( - shouldShowAgentsButton({ - ...getDefaultSettings('/tmp'), - experimentalActivity: true - }) - ).toBe(true) - }) - 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..1f545d34e 100644 --- a/src/renderer/src/components/sidebar/SidebarNav.tsx +++ b/src/renderer/src/components/sidebar/SidebarNav.tsx @@ -1,10 +1,9 @@ import React from 'react' -import { Bell, CalendarClock, EyeOff, Search, Smartphone } from 'lucide-react' +import { CalendarClock, EyeOff, 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 { useActivityUnreadCount } from '@/components/activity/useActivityUnreadCount' import { useShortcutKeyComboDetails } from '@/hooks/useShortcutLabel' import { ShortcutKeyCombo } from '@/components/ShortcutKeyCombo' import { useMobileSidebarOnboardingBadge } from './mobile-sidebar-onboarding-badge' @@ -18,12 +17,6 @@ import { translate } from '@/i18n/i18n' export { getSetupGuideSidebarEntryReady, shouldShowSetupGuideEntry } from './SetupGuideSidebarEntry' -export function shouldShowAgentsButton( - settings: Pick | null | undefined -): boolean { - return settings?.experimentalActivity === true -} - export function shouldShowMobileButton( settings: Pick | null | undefined ): boolean { @@ -42,18 +35,14 @@ const SidebarNav = React.memo(function SidebarNav() { useTranslation() const worktreePaletteShortcutCombos = useShortcutKeyComboDetails('worktree.palette') const openAutomationsPage = useAppStore((s) => s.openAutomationsPage) - const openActivityPage = useAppStore((s) => s.openActivityPage) const openMobilePage = useAppStore((s) => s.openMobilePage) const openModal = useAppStore((s) => s.openModal) const updateSettings = useAppStore((s) => s.updateSettings) const activeView = useAppStore((s) => s.activeView) - const showAgentsButton = useAppStore((s) => shouldShowAgentsButton(s.settings)) const showAutomationsButton = useAppStore((s) => shouldShowAutomationsButton(s.settings)) const showMobileButton = useAppStore((s) => shouldShowMobileButton(s.settings)) const automationsActive = activeView === 'automations' - const activityActive = activeView === 'activity' const mobileActive = activeView === 'mobile' - const activityUnreadCount = useActivityUnreadCount(showAgentsButton, 'sidebar-badge') const mobileOnboardingBadge = useMobileSidebarOnboardingBadge(showMobileButton) const hideAutomationsButton = React.useCallback(() => { void updateSettings({ showAutomationsButton: false }) @@ -98,35 +87,6 @@ const SidebarNav = React.memo(function SidebarNav() { ) : null} - {showAgentsButton ? ( - - ) : null} {showMobileButton ? ( diff --git a/src/renderer/src/components/sidebar/SidebarToolbar.test.tsx b/src/renderer/src/components/sidebar/SidebarToolbar.test.tsx index f3dde9621..89e471902 100644 --- a/src/renderer/src/components/sidebar/SidebarToolbar.test.tsx +++ b/src/renderer/src/components/sidebar/SidebarToolbar.test.tsx @@ -18,6 +18,10 @@ vi.mock('@/store', () => ({ useAppStore: (selector: (state: Partial) => unknown) => selector(mocks.state) })) +vi.mock('@/components/activity/useActivityUnreadCount', () => ({ + useActivityUnreadCount: () => 0 +})) + vi.mock('@/components/ui/tooltip', () => ({ Tooltip: ({ children, open }: { children: ReactNode; open?: boolean }) => { mocks.activeTooltipOpen = open === true @@ -46,10 +50,15 @@ vi.mock('../orca-profiles/OrcaProfileSwitcher', () => ({ const roots: Root[] = [] -async function renderToolbar(onWorkspaceBoardToggle = vi.fn()): Promise<{ +async function renderToolbar( + onWorkspaceBoardToggle = vi.fn(), + onAgentsPanelToggle = vi.fn(), + agentsPanelOpen = false +): Promise<{ container: HTMLDivElement rerender: () => Promise onWorkspaceBoardToggle: ReturnType + onAgentsPanelToggle: ReturnType }> { const container = document.createElement('div') document.body.appendChild(container) @@ -62,13 +71,15 @@ async function renderToolbar(onWorkspaceBoardToggle = vi.fn()): Promise<{ ) }) } await render() - return { container, rerender: render, onWorkspaceBoardToggle } + return { container, rerender: render, onWorkspaceBoardToggle, onAgentsPanelToggle } } describe('SidebarToolbar moved workspace board hint', () => { @@ -138,4 +149,40 @@ describe('SidebarToolbar moved workspace board hint', () => { expect(html).toContain('data-placement="sidebar"') expect(html.indexOf('Profile')).toBeLessThan(html.indexOf('Settings')) }) + + it('renders an always-on Agents button next to the workspace board button', async () => { + const { container } = await renderToolbar() + const agentsButton = container.querySelector('button[aria-label="Agents"]') + const boardButton = container.querySelector( + 'button[aria-label="Workspace board"]' + ) + + expect(agentsButton).not.toBeNull() + expect(boardButton).not.toBeNull() + expect(container.innerHTML.indexOf('aria-label="Agents"')).toBeLessThan( + container.innerHTML.indexOf('aria-label="Workspace board"') + ) + }) + + it('toggles the agents companion panel from the toolbar button', async () => { + const onAgentsPanelToggle = vi.fn() + const { container } = await renderToolbar(vi.fn(), onAgentsPanelToggle, false) + const agentsButton = container.querySelector('button[aria-label="Agents"]') + + expect(agentsButton?.getAttribute('aria-pressed')).toBe('false') + expect(agentsButton?.hasAttribute('data-agents-panel-trigger')).toBe(true) + + await act(async () => { + agentsButton?.click() + }) + + expect(onAgentsPanelToggle).toHaveBeenCalledOnce() + }) + + it('marks the agents toolbar button pressed while the panel is open', async () => { + const { container } = await renderToolbar(vi.fn(), vi.fn(), true) + const agentsButton = container.querySelector('button[aria-label="Agents"]') + + expect(agentsButton?.getAttribute('aria-pressed')).toBe('true') + }) }) diff --git a/src/renderer/src/components/sidebar/SidebarToolbar.tsx b/src/renderer/src/components/sidebar/SidebarToolbar.tsx index ff2e030c7..3a4465f93 100644 --- a/src/renderer/src/components/sidebar/SidebarToolbar.tsx +++ b/src/renderer/src/components/sidebar/SidebarToolbar.tsx @@ -1,7 +1,8 @@ import React from 'react' -import { Kanban } from 'lucide-react' +import { Bot, Kanban } from 'lucide-react' import { Button } from '@/components/ui/button' import { Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip' +import { useActivityUnreadCount } from '@/components/activity/useActivityUnreadCount' import { ScrollToCurrentWorkspaceToolbarButton } from './ScrollToCurrentWorkspaceToolbarButton' import { SidebarSettingsHelpMenu } from './SidebarSettingsHelpMenu' import { OrcaProfileSwitcher } from '../orca-profiles/OrcaProfileSwitcher' @@ -16,12 +17,16 @@ type SidebarToolbarProps = { workspaceBoardOpen: boolean workspaceBoardDragPreviewOpen?: boolean onWorkspaceBoardToggle: () => void + agentsPanelOpen: boolean + onAgentsPanelToggle: () => void } const SidebarToolbar = React.memo(function SidebarToolbar({ workspaceBoardOpen, workspaceBoardDragPreviewOpen = false, - onWorkspaceBoardToggle + onWorkspaceBoardToggle, + agentsPanelOpen, + onAgentsPanelToggle }: SidebarToolbarProps) { const [workspaceBoardMovedHintOpen, setWorkspaceBoardMovedHintOpen] = React.useState(false) const movedHintEligibleRef = React.useRef(null) @@ -29,6 +34,7 @@ const SidebarToolbar = React.memo(function SidebarToolbar({ const hasUsedWorkspaceBoard = useAppStore((state) => hasFeatureInteraction(state.featureInteractions, 'workspace-board') ) + const activityUnreadCount = useActivityUnreadCount(true, 'sidebar-badge') React.useEffect(() => { if (!persistedUIReady) { @@ -72,6 +78,32 @@ const SidebarToolbar = React.memo(function SidebarToolbar({
+ + + + + + {agentsPanelOpen + ? translate('auto.components.sidebar.SidebarToolbar.closeAgents', 'Close agents') + : translate('auto.components.sidebar.SidebarToolbar.agents', 'Agents')} + +