From 7d46eb08dd10bb9772b5ace608f7d0a19ad48e2a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 12 May 2026 20:50:18 -0700 Subject: [PATCH] Activity page agent terminal view (#1723) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(activity): align unread dot with row icon Anchor the unread mini-dot to the icon's own bounding box (relative inline-flex with -top-1 -left-1) instead of the 24x24 cell. The previous absolute positioning was relative to the cell, so the dot landed visibly off-center against the centered AgentStateDot/Plus glyph. Adds a ring-2 ring-background halo for contrast against the row's tinted unread background. Applies to both AgentEventRow and WorktreeEventRow. Co-authored-by: Orca * fix(activity): drop top padding so content sits flush with titlebar Outer wrapper used py-3, plus the right-pane
had pt-2 and the thread-list header had py-2 — the stacked top whitespace produced a visible gap above the first row against the titlebar. The ActivityTitlebarControls bar already provides the breathing-room band. Drop the wrapper's top padding (py-3 → pb-3), drop the right-pane section's pt-2, and tighten the thread-list header to pt-1.5 pb-2 so the WORKTREES label aligns with the right-pane worktree title row. Co-authored-by: Orca * fix(activity): make event row the click target for navigate + ack The inline "Jump to agent" button only rendered when agentAlive was true, so retained-done rows had no jump affordance, and in compact mode it was hover-only. Users naturally click anywhere on the row expecting it to navigate. Move the navigate-and-ack logic onto the row's onClick (with role, tabIndex, and Enter/Space keyboard support) and drop the inline buttons. Per the design doc (option 1), drop the agentAlive gate entirely: activateAndRevealWorktree is safe unconditionally and activateTabAndFocusPane silently no-ops on a missing tab id, so a stale-tab click is a soft no-op. Mirror the same pattern on WorktreeEventRow so clicking a "Worktree created" row navigates to that worktree. Co-authored-by: Orca * fix(activity): bell glyph for unread + larger row state icon The unread mini-dot stacked on the AgentStateDot competed with the dot itself for the eye and read like a status badge on the agent state. Replace it with a small BellDot glyph at the icon's top-right corner so the unread cue rhymes with the bell button on ThreadRow — one unread vocabulary across both surfaces. While here, bump the row state icon to a new 'lg' AgentStateDot size (18px) so the green check sits center-of-mass in its 32px column instead of floating small and high. Bump the WorktreeEventRow Plus glyph to match. Co-authored-by: Orca * fix(activity): drop left padding so thread list reaches the window edge The page wrapper used px-4, which left a 16px gap to the left of the thread list — visually inconsistent with how sidebars abut the window chrome elsewhere. Switch to pr-4 (keep right padding for the right pane). Inner thread-list and right-pane padding remain unchanged. Co-authored-by: Orca * fix(activity): use left-edge bar for unread instead of an icon overlay Mini-dot and bell-glyph attempts both crowded the AgentStateDot/Plus icon column. Switch to the same left-edge primary bar that ThreadRow already uses for unread — a row-level cue keeps the icon column clean and unifies the unread vocabulary across both panes. Co-authored-by: Orca * fix(activity): page extends to both edges, restore right-pane top padding, rename to "workspace" - Drop horizontal padding on the page wrapper (pr-4 → none) so the thread list reaches the left edge and the right pane reaches the right edge — matches how sidebars abut the chrome elsewhere. - Restore a small top padding (pt-2) on the right-pane title row so the workspace heading isn't pinned to the titlebar. Earlier Fix 2 over-corrected by removing it entirely. - Rename user-facing "Worktree(s)" → "Workspace(s)" (column label, event title "Worktree created", description copy, "Jump to worktree" button, empty state). Internal identifiers stay as worktree* since that's the data-model name. Co-authored-by: Orca * fix(activity): remove redundant "Jump to workspace" header button Clicking any event row already calls markThreadRead + activateAndRevealWorktree (plus a tab focus, so it's a strict superset of what the header button did). The button's only unique behavior was "go to the workspace without picking a tab" — thin justification when the latest event is one row down. cursor-pointer + hover already signal that rows are clickable. Co-authored-by: Orca * fix(activity): wrap agent summary instead of truncating The summary line used 'truncate' with a max-width, hiding the rest of the agent's message behind an ellipsis. The Activity page is meant to let users scan what each agent said without leaving the surface, so truncation defeats its purpose. Switch to break-words + whitespace-pre-wrap so the full message renders and multi-line output keeps its line breaks. Co-authored-by: Orca * fix(activity): clamp agent summary to 3 lines Showing the full message made tall rows for chatty agents. Cap at 3 lines (line-clamp-3) — long enough to convey what happened, short enough that rows stay scannable. Users open the workspace if they want the full transcript. Co-authored-by: Orca * feat(activity): switch left list from workspaces to agent panes Restructure the activity feed so each thread is one *agent pane* (a terminal tab + pane id) rather than one workspace. Internal model goes from WorktreeThread → AgentPaneThread keyed on paneKey. Renderer changes: - Left list: each row shows the pane title (with agent icon + repo badge), then the workspace name as secondary context. Section label changes "Workspaces" → "Agents". - Right pane: header shows the pane title, agent icon, repo badge, and the workspace name beneath. Drops the Today/Yesterday/Earlier day grouping per design — the relative timestamp on each row is enough orientation, and a flat chronological list scans more cleanly. - Drops the workspace-created event kind entirely (and the WorktreeEventRow + ActivityRow union dispatcher), since the surface is now strictly agent activity. Side effects: - Mark-read no longer needs the locallyReadEventIds layer or the worktree-unread store calls (markWorktreeUnread/clearWorktreeUnread). Acknowledge by paneKey is the only persistence path. - Removes Plus and groupForTimestamp (unused after the refactor). Co-authored-by: Orca * feat(activity): label panes like the per-workspace agents dropdown Pane labels now follow the same hierarchy DashboardAgentRow uses inside the WorktreeCardAgents dropdown: customTitle (user rename) > non-default OSC title > last prompt > defaultTitle / "Terminal" The prompt fallback is the important one — agents that haven't been renamed and don't set an OSC title now render with what the user asked the agent to do (e.g. "Fix the unread dot alignment") instead of the generic "Terminal 1" placeholder. Matches the visual + naming pattern on each workspace card so the activity page reads as a flat-feed extension of that surface. Co-authored-by: Orca * fix(activity): smaller titles, allow 2-line prompt clamp Long prompts were getting truncated at one line, hiding most of the ask. Switch the thread row title from truncate to line-clamp-2, with break-words so long words wrap, and tighten size to text-[13px] + leading-snug so two clamped lines don't dominate the row vertically. Anchor the agent icon to the first line via items-start + pt-[3px]. Right-pane heading drops text-base → text-sm to match. Co-authored-by: Orca * fix(activity): right-pane title gets the same 2-line clamp + smaller size Mirror the ThreadRow change on the right-pane heading: line-clamp-2 + break-words + leading-snug so a long prompt title shows two lines instead of a single-line ellipsis. The repo badge moves down to the secondary line (next to the workspace name) so it doesn't shift with the title height. Co-authored-by: Orca * fix(activity): match WorktreeCard's selected/hover/unread cues Three stacked tints (selected + unread row tint + hover) made an unread hovered row look identical to a selected row, and hover even fought selected. Mirror WorktreeCard: - selected → solid black/white tint + faint shadow, hover suppressed (the active class wins so the row stays visually fixed) - non-selected → only then does hover apply (bg-accent/40) - unread → weight + left-edge primary bar carry the cue; row tint removed (matches WorktreeCard's "weight alone carries the unread signal") Co-authored-by: Orca * feat(activity): portal selected agent terminal Co-authored-by: Orca * fix(activity): keep completed entries after terminal input Co-authored-by: Orca * fix(activity): tighten portal target, unread count, and selection edges - activity-terminal-portal: replace document.body MutationObserver with a module-level pub/sub registry; the page publishes the target via a ref callback, Terminal subscribes. Removes body-wide DOM observation. - Terminal: memoize activityTerminalPortal so WorktreeSplitSurface's React.memo bail-out is preserved across unrelated Terminal re-renders. - ActivityPrototypePage: cap events per-pane (5) so a chatty pane can't push quiet panes off the left list; render an empty-state when a retained thread's tab is gone; skip workspace mutation in activateThreadTerminal when the tab is no longer live; keep the selected thread visible in unread-only mode after auto-mark-read. - ActivityTitlebarControls: walk stateHistory in the unread accumulator (mirrors the new feed semantics); drop worktree-created counting since the new feed has no surface to dismiss them. - AgentStateDot: remove the dead 'lg' size variant. - App: hide worktree sidebar on the Activity view and include it in the back/forward shortcut + button cluster. Co-authored-by: Orca * fix(activity): double-buffer portal slots to remove cold-mount flash Switching threads on the Activity page used to expose xterm's empty canvas for ~133ms while a newly-mounted TerminalPane attached. Replace the single portal target with a double-buffered set of slots: keep the previously displayed terminal visible while the next selected terminal mounts in an invisible same-size slot, then flip slots once the staged slot contains the selected terminal DOM with xterm's screen and PTY binding (with one extra frame only after observing an empty mount). Skips publishing a portal target when the selected retained thread no longer has a live tab so the previous tab's target doesn't linger. Co-authored-by: Orca * fix(activity): remove single-option Display style settings dropdown The activity page's gear menu only held a "Compact list" toggle. Drop the dropdown along with the leftSidebarCompact state, the ActivityDensity type, and the unused dropdown-menu / Settings imports. The thread list keeps the compact layout (the previous default). Co-authored-by: Orca * fix(activity): vertically center Jump to workspace button The header row uses items-start so a 2-line prompt clamps without the badge jumping. self-center on the button overrides that just for the action so it sits in the middle of the title block instead of pinned to the top edge. Co-authored-by: Orca * fix(activity): prefer prompt over OSC live title for thread label paneTitleForEvent put the non-default tab.title ahead of the prompt, so agent CLIs that set "Claude Code" / "Codex" via OSC pinned every row and the right-pane heading to the agent name. The dashboard row this function claims to mirror uses the prompt directly. Re-order to: customTitle (explicit rename) → prompt → non-default liveTitle → defaultTitle, so sending "hi" actually shows "hi" in the title. Co-authored-by: Orca * fix(activity): drop extra row height when prompt is one line The thread row's right column stacked time over the count badge with a gap, which forced the row to ~48px even when the left column's prompt was a single line. Collapse the right column into one horizontal cluster (count + time/bell) so single-line rows stay tight, while two-line prompts still drive the row taller as before. Co-authored-by: Orca * fix(activity): add top/bottom padding to thread rows Bump py-1.5 → py-2.5 so single-line rows breathe and don't sit flush against the row dividers. Co-authored-by: Orca * fix(activity): even out optical row padding (top read heavier than bottom) Symmetric py-2.5 looked top-heavy because the title's leading-snug adds internal whitespace above the cap-height that the secondary row doesn't have below it. Trim the top to pt-2 / pb-2.5 so the row reads balanced. Co-authored-by: Orca --------- Co-authored-by: Orca --- src/renderer/src/App.tsx | 9 +- src/renderer/src/components/Terminal.tsx | 75 +- .../activity/ActivityPrototypePage.test.ts | 96 ++ .../activity/ActivityPrototypePage.tsx | 1153 ++++++++++------- .../activity/ActivityTitlebarControls.tsx | 74 +- .../activity/activity-terminal-portal.ts | 60 + .../components/tab-group/TabGroupPanel.tsx | 80 +- .../tab-group/TabGroupSplitLayout.tsx | 13 +- 8 files changed, 990 insertions(+), 570 deletions(-) create mode 100644 src/renderer/src/components/activity/ActivityPrototypePage.test.ts create mode 100644 src/renderer/src/components/activity/activity-terminal-portal.ts diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 092309492..f8b7ce125 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -612,7 +612,10 @@ function App(): React.JSX.Element { activeWorktreeId !== null && !hasTabBar && effectiveActiveTabExpanded - const showSidebar = activeView !== 'settings' + // Why: Activity is a full-page navigation surface — same treatment as + // Settings — so the worktree sidebar is removed for that view, letting the + // thread list + agent terminal span edge-to-edge. + const showSidebar = activeView !== 'settings' && activeView !== 'activity' // Why: only the terminal workspace replaces the full-width titlebar with // split-column chrome. Full-page navigation views keep the draggable app // titlebar so their page-level controls can live in that window strip. @@ -881,7 +884,9 @@ function App(): React.JSX.Element { {/* Why: Back/Forward traverse mixed worktree + Tasks history, so the cluster is shown wherever the history shortcut is live (terminal or - tasks). Hidden in Settings to keep that view modal-ish. */} + tasks). Hidden in Settings to keep that view modal-ish, and in + Activity since that page owns its own back-out via the Close button + in ActivityTitlebarControls. */} {(activeView === 'terminal' || activeView === 'tasks') && (
diff --git a/src/renderer/src/components/Terminal.tsx b/src/renderer/src/components/Terminal.tsx index db6fcc4fe..f00a42a32 100644 --- a/src/renderer/src/components/Terminal.tsx +++ b/src/renderer/src/components/Terminal.tsx @@ -54,6 +54,11 @@ import { } from './terminal/split-group-mount' import { appendUniqueOpenFileIds } from './terminal/unsaved-close-queue' import CodexRestartChip from './CodexRestartChip' +import { + findActivityTerminalPortal, + useActivityTerminalPortals, + type ActivityTerminalPortalTarget +} from './activity/activity-terminal-portal' const EditorPanel = lazy(() => import('./editor/EditorPanel')) @@ -102,6 +107,15 @@ function Terminal(): React.JSX.Element | null { const setTabBarOrder = useAppStore((s) => s.setTabBarOrder) const tabBarOrderByWorktree = useAppStore((s) => s.tabBarOrderByWorktree) const tabBarOrder = activeWorktreeId ? tabBarOrderByWorktree[activeWorktreeId] : undefined + // Why (anchored to selected thread, not active tab): the activity page + // publishes the full {target, worktreeId, tabId} descriptor sourced from + // its selectedThread. Deriving worktreeId/tabId from activeWorktreeId/ + // 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' + ) const tabs = useMemo( () => (activeWorktreeId ? (tabsByWorktree[activeWorktreeId] ?? []) : []), @@ -1247,6 +1261,7 @@ function Terminal(): React.JSX.Element | null { layout={layout} focusedGroupId={activeGroupIdByWorktree[worktree.id]} isVisible={isVisible} + activityTerminalPortals={activityTerminalPortals} /> ) })} @@ -1299,27 +1314,40 @@ function Terminal(): React.JSX.Element | null { aria-hidden={!isVisible} > - {(tabsByWorktree[worktree.id] ?? []).map((tab) => ( - handlePtyExit(tab.id, ptyId)} - onCloseTab={() => handleCloseTab(tab.id)} - /> - ))} + {(tabsByWorktree[worktree.id] ?? []).map((tab) => { + const activityTerminalPortal = findActivityTerminalPortal( + activityTerminalPortals, + worktree.id, + tab.id + ) + const isActivityPortalTab = activityTerminalPortal !== null + const isActiveTerminalTab = + isVisible && tab.id === activeTabId && activeTabType === 'terminal' + const terminalPane = ( + handlePtyExit(tab.id, ptyId)} + onCloseTab={() => handleCloseTab(tab.id)} + /> + ) + if (activityTerminalPortal) { + return createPortal( + terminalPane, + activityTerminalPortal.target, + `activity-terminal-${tab.id}` + ) + } + return terminalPane + })}
) })} @@ -1478,12 +1506,14 @@ const WorktreeSplitSurface = React.memo(function WorktreeSplitSurface({ worktreeId, layout, focusedGroupId, - isVisible + isVisible, + activityTerminalPortals }: { worktreeId: string layout: TabGroupLayoutNode focusedGroupId?: string isVisible: boolean + activityTerminalPortals: ActivityTerminalPortalTarget[] }): React.JSX.Element { return (
diff --git a/src/renderer/src/components/activity/ActivityPrototypePage.test.ts b/src/renderer/src/components/activity/ActivityPrototypePage.test.ts new file mode 100644 index 000000000..a04a56fab --- /dev/null +++ b/src/renderer/src/components/activity/ActivityPrototypePage.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, it } from 'vitest' +import type { AgentStatusEntry } from '../../../../shared/agent-status-types' +import type { Repo, TerminalTab, Worktree } from '../../../../shared/types' +import { buildActivityEvents } from './ActivityPrototypePage' + +function makeRepo(): Repo { + return { + id: 'repo-1', + path: '/repo', + displayName: 'Repo', + badgeColor: '#000', + addedAt: 1 + } +} + +function makeWorktree(): Worktree { + return { + id: 'wt-1', + repoId: 'repo-1', + path: '/repo/wt-1', + head: 'abc123', + branch: 'feature', + isBare: false, + isMainWorktree: false, + displayName: 'feature', + comment: '', + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 1 + } +} + +function makeTab(): TerminalTab { + return { + id: 'tab-1', + ptyId: 'pty-1', + worktreeId: 'wt-1', + title: 'Claude', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } +} + +function makeWorkingEntryWithPriorDone(): AgentStatusEntry { + return { + state: 'working', + prompt: 'Second prompt', + updatedAt: 2_000, + stateStartedAt: 2_000, + paneKey: 'tab-1:1', + terminalTitle: 'Claude', + stateHistory: [ + { + state: 'done', + prompt: 'First prompt', + startedAt: 1_000 + } + ], + agentType: 'claude' + } +} + +describe('buildActivityEvents', () => { + it('keeps a prior done event after the same pane starts working again', () => { + const repo = makeRepo() + const worktree = makeWorktree() + const tab = makeTab() + + const events = buildActivityEvents({ + agentStatusByPaneKey: { + 'tab-1:1': makeWorkingEntryWithPriorDone() + }, + retainedAgentsByPaneKey: {}, + tabsByWorktree: { + [worktree.id]: [tab] + }, + worktreeMap: new Map([[worktree.id, worktree]]), + repoMap: new Map([[repo.id, repo]]), + acknowledgedAgentsByPaneKey: {} + }) + + expect(events).toHaveLength(1) + expect(events[0]).toMatchObject({ + state: 'done', + timestamp: 1_000 + }) + expect(events[0].entry.prompt).toBe('First prompt') + }) +}) diff --git a/src/renderer/src/components/activity/ActivityPrototypePage.tsx b/src/renderer/src/components/activity/ActivityPrototypePage.tsx index 404bf3534..1dcdc8c00 100644 --- a/src/renderer/src/components/activity/ActivityPrototypePage.tsx +++ b/src/renderer/src/components/activity/ActivityPrototypePage.tsx @@ -1,18 +1,9 @@ /* eslint-disable max-lines -- Why: this prototype keeps the real-data adapter and current visual skeleton together until the next refinement pass decides which pieces become production modules. */ -import React, { useEffect, useMemo, useState } from 'react' +import React, { useCallback, useEffect, useLayoutEffect, useMemo, useState } from 'react' import { useShallow } from 'zustand/react/shallow' -import { - Bell, - BellDot, - BellOff, - GitBranch, - MessageSquareText, - Plus, - Search, - Settings -} from 'lucide-react' +import { Bell, BellDot, BellOff, MessageSquareText, Search, TerminalSquare } from 'lucide-react' import { AgentIcon } from '@/lib/agent-catalog' import { agentTypeToIconAgent, formatAgentTypeLabel } from '@/lib/agent-status' @@ -22,35 +13,30 @@ import { useAppStore } from '@/store' import type { RetainedAgentEntry } from '@/store/slices/agent-status' import { getRepoMapFromState, getWorktreeMapFromState } from '@/store/selectors' import { useSidebarResize } from '@/hooks/useSidebarResize' -import { AgentStateDot, agentStateLabel, type AgentDotState } from '@/components/AgentStateDot' import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' -import { - DropdownMenu, - DropdownMenuCheckboxItem, - DropdownMenuContent, - DropdownMenuLabel, - DropdownMenuSeparator, - DropdownMenuTrigger -} from '@/components/ui/dropdown-menu' import { Input } from '@/components/ui/input' import { Toggle } from '@/components/ui/toggle' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { cn } from '@/lib/utils' +import { + setActivityTerminalPortals, + type ActivityTerminalPortalTarget +} from './activity-terminal-portal' import type { Repo, TerminalTab, Worktree } from '../../../../shared/types' import type { + AgentStateHistoryEntry, AgentStatusEntry, AgentStatusState, AgentType } from '../../../../shared/agent-status-types' type ThreadReadFilter = 'all' | 'unread' -type ActivityDensity = 'compact' | 'comfortable' +type ActivityEventState = Extract -type AgentActivityEvent = { +type ActivityEvent = { id: string - kind: 'agent' - state: Extract + state: ActivityEventState timestamp: number worktree: Worktree repo: Repo | null @@ -61,25 +47,35 @@ type AgentActivityEvent = { unread: boolean } -type WorktreeActivityEvent = { - id: string - kind: 'worktree-created' - timestamp: number - worktree: Worktree - repo: Repo | null - unread: boolean -} - -type ActivityEvent = AgentActivityEvent | WorktreeActivityEvent - -type WorktreeThread = { +// Why (per-pane thread): the activity feed is keyed on the agent pane (a +// terminal tab + pane id) rather than on the workspace, so the left list +// shows one entry per agent. paneKey is the stable identity (`${tabId}:${paneId}`). +type AgentPaneThread = { + paneKey: string + paneTitle: string worktree: Worktree repo: Repo | null + agentType: AgentType latestEvent: ActivityEvent events: ActivityEvent[] unread: boolean } +type ActivityTerminalPortalReadiness = { + target: HTMLElement | null + tabId: string | null + ready: boolean +} + +type ActivityTerminalPortalDomStatus = { + hasSelectedRoot: boolean + ready: boolean +} + +type ActivityTerminalPortalSlotId = 'primary' | 'secondary' + +const ACTIVITY_TERMINAL_LOADING_LABEL_DELAY_MS = 180 + const absoluteDateFormatter = new Intl.DateTimeFormat(undefined, { year: 'numeric', month: 'short', @@ -108,13 +104,6 @@ function formatRelativeTime(timestamp: number): string { return relativeTimeFormatter.format(diffDays, 'day') } -function asDotState(state: AgentStatusState): AgentDotState { - if (state === 'blocked' || state === 'waiting' || state === 'done') { - return state - } - return 'idle' -} - function paneIdFromPaneKey(paneKey: string): number | null { const colon = paneKey.indexOf(':') const tail = colon > 0 ? paneKey.slice(colon + 1) : '' @@ -122,14 +111,145 @@ function paneIdFromPaneKey(paneKey: string): number | null { return Number.isFinite(parsed) && parsed > 0 ? parsed : null } -function agentTitle(event: AgentActivityEvent): string { +function getSelectedActivityTerminalPortalStatus( + target: HTMLElement, + tabId: string +): ActivityTerminalPortalDomStatus { + let selectedRoot: HTMLElement | null = null + for (const candidate of target.querySelectorAll('[data-terminal-tab-id]')) { + if (candidate.dataset.terminalTabId === tabId) { + selectedRoot = candidate + break + } + } + if (!selectedRoot) { + return { hasSelectedRoot: false, ready: false } + } + const hasPtyBinding = + selectedRoot.hasAttribute('data-pty-id') || + selectedRoot.querySelector('[data-pty-id]') !== null + const hasXtermScreen = selectedRoot.querySelector('.xterm-screen') !== null + return { hasSelectedRoot: true, ready: hasPtyBinding && hasXtermScreen } +} + +function useActivityTerminalPortalReadiness( + target: HTMLElement | null, + tabId: string | null +): boolean { + const [readiness, setReadiness] = useState({ + target: null, + tabId: null, + ready: false + }) + + useLayoutEffect(() => { + if (!target || !tabId) { + setReadiness((prev) => + prev.target === null && prev.tabId === null && !prev.ready + ? prev + : { target: null, tabId: null, ready: false } + ) + return + } + + let disposed = false + let readyFrame: number | null = null + let sawUnreadySelectedRoot = false + + const updateReadiness = (ready: boolean): void => { + setReadiness((prev) => + prev.target === target && prev.tabId === tabId && prev.ready === ready + ? prev + : { target, tabId, ready } + ) + } + + const cancelReadyFrame = (): void => { + if (readyFrame !== null) { + cancelAnimationFrame(readyFrame) + readyFrame = null + } + } + + const checkReadiness = (): void => { + const status = getSelectedActivityTerminalPortalStatus(target, tabId) + if (status.ready) { + if (!sawUnreadySelectedRoot) { + cancelReadyFrame() + updateReadiness(true) + return + } + if (readyFrame !== null) { + return + } + // Why: the PTY id can appear before xterm has painted replayed output. + // Waiting one frame keeps Activity's cover in place for the blank canvas + // frame without moving terminal lifecycle work into global layout effects. + readyFrame = requestAnimationFrame(() => { + readyFrame = null + if (!disposed && getSelectedActivityTerminalPortalStatus(target, tabId).ready) { + updateReadiness(true) + } + }) + return + } + if (status.hasSelectedRoot) { + sawUnreadySelectedRoot = true + } + cancelReadyFrame() + updateReadiness(false) + } + + updateReadiness(false) + checkReadiness() + + const observer = new MutationObserver(checkReadiness) + observer.observe(target, { + childList: true, + subtree: true, + attributes: true, + attributeFilter: ['data-terminal-tab-id', 'data-pty-id'] + }) + + return () => { + disposed = true + cancelReadyFrame() + observer.disconnect() + } + }, [target, tabId]) + + return readiness.target === target && readiness.tabId === tabId && readiness.ready +} + +function otherActivityTerminalSlot( + slotId: ActivityTerminalPortalSlotId +): ActivityTerminalPortalSlotId { + return slotId === 'primary' ? 'secondary' : 'primary' +} + +function useActivityTerminalLoadingLabel(loading: boolean): boolean { + const [visible, setVisible] = useState(false) + + useEffect(() => { + if (!loading) { + setVisible(false) + return + } + const timer = setTimeout(() => setVisible(true), ACTIVITY_TERMINAL_LOADING_LABEL_DELAY_MS) + return () => clearTimeout(timer) + }, [loading]) + + return visible +} + +function agentTitle(event: ActivityEvent): string { if (event.state === 'done') { return event.entry.interrupted ? 'Agent interrupted' : 'Agent finished' } return event.state === 'waiting' ? 'Agent waiting for input' : 'Agent needs input' } -function agentSummary(event: AgentActivityEvent): string { +function agentSummary(event: ActivityEvent): string { const prompt = event.entry.prompt.trim() if (event.state === 'done') { const message = event.entry.lastAssistantMessage?.trim() @@ -138,7 +258,7 @@ function agentSummary(event: AgentActivityEvent): string { return prompt || event.entry.lastAssistantMessage?.trim() || 'The agent paused for user input.' } -function agentMeta(event: AgentActivityEvent): string { +function agentMeta(event: ActivityEvent): string { const agent = formatAgentTypeLabel(event.agentType) if (event.state === 'done') { return event.entry.interrupted ? `${agent} interrupted` : `${agent} completed` @@ -146,31 +266,134 @@ function agentMeta(event: AgentActivityEvent): string { return event.state === 'waiting' ? `${agent} waiting` : `${agent} blocked` } -function eventTitle(event: ActivityEvent): string { - return event.kind === 'agent' ? agentTitle(event) : 'Worktree created' -} - -function eventSummary(event: ActivityEvent): string { - return event.kind === 'agent' ? agentSummary(event) : event.worktree.displayName -} - -function eventMeta(event: ActivityEvent): string { - if (event.kind === 'agent') { - return agentMeta(event) +// Why (label hierarchy): mirror DashboardAgentRow — the agent's last prompt +// IS what the agent is working on and is the primary signal users want at a +// glance. A user-renamed customTitle still wins (explicit rename intent), but +// the OSC-set live title ("Claude Code", "Codex", …) must NOT shadow the +// prompt: agent CLIs set that title eagerly, so preferring it would pin every +// row to the agent name and hide the actual turn. Fall back to a non-default +// liveTitle only when there is no prompt at all. +function paneTitleForEvent(event: ActivityEvent): string { + const tab = event.tab + const customTitle = tab.customTitle?.trim() + if (customTitle) { + return customTitle } - return event.worktree.branch + const prompt = event.entry.prompt.trim() + if (prompt) { + return prompt + } + const liveTitle = tab.title?.trim() + const defaultTitle = tab.defaultTitle?.trim() + if (liveTitle && liveTitle !== defaultTitle) { + return liveTitle + } + return defaultTitle || liveTitle || 'Terminal' } -function buildActivityEvents(args: { +function isActivityEventState(state: AgentStatusState): state is ActivityEventState { + return state === 'done' || state === 'blocked' || state === 'waiting' +} + +// Why: per-pane cap guarantees each agent appears in the left list even when one pane has a long history. +const EVENTS_PER_PANE_CAP = 5 + +function historyEntrySnapshot( + entry: AgentStatusEntry, + history: AgentStateHistoryEntry +): AgentStatusEntry { + return { + ...entry, + state: history.state, + prompt: history.prompt, + updatedAt: history.startedAt, + stateStartedAt: history.startedAt, + stateHistory: [], + toolName: undefined, + toolInput: undefined, + lastAssistantMessage: undefined, + interrupted: history.interrupted + } +} + +function appendActivityEvent(args: { + events: ActivityEvent[] + seenEventIds: Set + state: ActivityEventState + timestamp: number + worktree: Worktree + repo: Repo | null + entry: AgentStatusEntry + tab: TerminalTab + agentType: AgentType + agentAlive: boolean + acknowledgedAt: number +}): void { + const id = `agent:${args.entry.paneKey}:${args.state}:${args.timestamp}` + if (args.seenEventIds.has(id)) { + return + } + args.seenEventIds.add(id) + args.events.push({ + id, + state: args.state, + timestamp: args.timestamp, + worktree: args.worktree, + repo: args.repo, + entry: args.entry, + tab: args.tab, + agentType: args.agentType, + agentAlive: args.agentAlive, + unread: args.acknowledgedAt < args.timestamp + }) +} + +function appendActivityEventsForEntry(args: { + events: ActivityEvent[] + seenEventIds: Set + entry: AgentStatusEntry + worktree: Worktree + repo: Repo | null + tab: TerminalTab + agentType: AgentType + agentAlive: boolean + acknowledgedAt: number +}): void { + // Why: Activity is an append-only history surface. When a user continues in + // the same terminal pane, the live entry moves done→working; stateHistory is + // the only place the previous done/blocking event still exists. + for (const history of args.entry.stateHistory) { + if (!isActivityEventState(history.state)) { + continue + } + appendActivityEvent({ + ...args, + state: history.state, + timestamp: history.startedAt, + entry: historyEntrySnapshot(args.entry, history) + }) + } + + if (!isActivityEventState(args.entry.state)) { + return + } + appendActivityEvent({ + ...args, + state: args.entry.state, + timestamp: args.entry.stateStartedAt + }) +} + +export function buildActivityEvents(args: { agentStatusByPaneKey: Record retainedAgentsByPaneKey: Record tabsByWorktree: Record worktreeMap: Map repoMap: Map acknowledgedAgentsByPaneKey: Record - locallyReadEventIds: Set }): ActivityEvent[] { const events: ActivityEvent[] = [] + const seenEventIds = new Set() const tabContext = new Map() for (const worktree of args.worktreeMap.values()) { @@ -178,23 +401,9 @@ function buildActivityEvents(args: { for (const tab of tabs) { tabContext.set(tab.id, { worktree, tab }) } - if (worktree.createdAt) { - const id = `worktree-created:${worktree.id}` - events.push({ - id, - kind: 'worktree-created', - timestamp: worktree.createdAt, - worktree, - repo: args.repoMap.get(worktree.repoId) ?? null, - unread: worktree.isUnread && !args.locallyReadEventIds.has(id) - }) - } } for (const [paneKey, entry] of Object.entries(args.agentStatusByPaneKey)) { - if (entry.state !== 'done' && entry.state !== 'blocked' && entry.state !== 'waiting') { - continue - } const separatorIndex = paneKey.indexOf(':') if (separatorIndex <= 0) { continue @@ -205,53 +414,68 @@ function buildActivityEvents(args: { continue } const ackAt = args.acknowledgedAgentsByPaneKey[paneKey] ?? 0 - events.push({ - id: `agent-live:${paneKey}:${entry.stateStartedAt}`, - kind: 'agent', - state: entry.state, - timestamp: entry.stateStartedAt, + appendActivityEventsForEntry({ + events, + seenEventIds, worktree: context.worktree, repo: args.repoMap.get(context.worktree.repoId) ?? null, entry, tab: context.tab, agentType: entry.agentType ?? 'unknown', agentAlive: true, - unread: ackAt < entry.stateStartedAt + acknowledgedAt: ackAt }) } for (const [paneKey, retained] of Object.entries(args.retainedAgentsByPaneKey)) { const worktree = args.worktreeMap.get(retained.worktreeId) - if (!worktree || retained.entry.state !== 'done') { + if (!worktree) { continue } const ackAt = args.acknowledgedAgentsByPaneKey[paneKey] ?? 0 - events.push({ - id: `agent-retained:${paneKey}:${retained.entry.stateStartedAt}`, - kind: 'agent', - state: 'done', - timestamp: retained.entry.stateStartedAt, + appendActivityEventsForEntry({ + events, + seenEventIds, worktree, repo: args.repoMap.get(worktree.repoId) ?? null, entry: retained.entry, tab: retained.tab, agentType: retained.agentType, agentAlive: false, - unread: ackAt < retained.entry.stateStartedAt + acknowledgedAt: ackAt }) } - return events.sort((a, b) => b.timestamp - a.timestamp).slice(0, 80) + const sorted = events.sort((a, b) => b.timestamp - a.timestamp) + const perPaneCount = new Map() + const capped: ActivityEvent[] = [] + for (const event of sorted) { + const paneKey = event.entry.paneKey + const count = perPaneCount.get(paneKey) ?? 0 + if (count >= EVENTS_PER_PANE_CAP) { + continue + } + perPaneCount.set(paneKey, count + 1) + capped.push(event) + if (capped.length >= 80) { + break + } + } + return capped } -function buildWorktreeThreads(events: ActivityEvent[]): WorktreeThread[] { - const byWorktreeId = new Map() +function buildAgentPaneThreads(events: ActivityEvent[]): AgentPaneThread[] { + const byPaneKey = new Map() for (const event of events) { - const existing = byWorktreeId.get(event.worktree.id) + const paneKey = event.entry.paneKey + const existing = byPaneKey.get(paneKey) if (!existing) { - byWorktreeId.set(event.worktree.id, { + byPaneKey.set(paneKey, { + paneKey, + paneTitle: paneTitleForEvent(event), worktree: event.worktree, repo: event.repo, + agentType: event.agentType, latestEvent: event, events: [event], unread: event.unread @@ -262,13 +486,15 @@ function buildWorktreeThreads(events: ActivityEvent[]): WorktreeThread[] { existing.unread = existing.unread || event.unread if (event.timestamp > existing.latestEvent.timestamp) { existing.latestEvent = event + existing.paneTitle = paneTitleForEvent(event) + existing.agentType = event.agentType } } - return Array.from(byWorktreeId.values()) + return Array.from(byPaneKey.values()) .map((thread) => ({ ...thread, - events: [...thread.events].sort((a, b) => a.timestamp - b.timestamp) + events: [...thread.events].sort((a, b) => b.timestamp - a.timestamp) })) .sort((a, b) => b.latestEvent.timestamp - a.latestEvent.timestamp) } @@ -308,207 +534,18 @@ function EventRepoBadge({ repo }: { repo: Repo | null }): React.JSX.Element | nu ) } -function AgentEventRow({ - event, - density, - onMarkRead -}: { - event: AgentActivityEvent - density: ActivityDensity - onMarkRead: (event: ActivityEvent) => void -}): React.JSX.Element { - const compact = density === 'compact' - const dotState = asDotState(event.state) - - const jumpToAgent = (clickEvent: React.MouseEvent): void => { - clickEvent.stopPropagation() - onMarkRead(event) - activateAndRevealWorktree(event.worktree.id) - activateTabAndFocusPane(event.tab.id, paneIdFromPaneKey(event.entry.paneKey)) - } - - return ( -
onMarkRead(event)} - > -
-
- {event.unread ? ( - - ) : null} - - - - - - - - {event.entry.interrupted ? 'Interrupted' : agentStateLabel(dotState)} - - -
-
- -
-
- - {agentTitle(event)} - - - - - - - - - {formatAgentTypeLabel(event.agentType)} - - -
-
- {agentSummary(event)} -
-
- - - {event.worktree.displayName} - - {agentMeta(event)} -
- {!compact && event.agentAlive ? ( -
- -
- ) : null} -
- -
- - {compact && event.agentAlive ? ( - - ) : null} -
-
- ) -} - -function WorktreeEventRow({ - event, - density, - onMarkRead -}: { - event: WorktreeActivityEvent - density: ActivityDensity - onMarkRead: (event: ActivityEvent) => void -}): React.JSX.Element { - const compact = density === 'compact' - - return ( -
onMarkRead(event)} - > -
-
- {event.unread ? ( - - ) : null} - -
-
-
-
- - Worktree created - -
-
- {event.worktree.displayName} -
-
- - - {event.worktree.branch} - - {event.worktree.path} -
-
-
- -
-
- ) -} - -function ActivityRow({ - event, - density, - onMarkRead -}: { - event: ActivityEvent - density: ActivityDensity - onMarkRead: (event: ActivityEvent) => void -}): React.JSX.Element { - return event.kind === 'agent' ? ( - - ) : ( - - ) -} - -function groupForTimestamp(timestamp: number): 'Today' | 'Yesterday' | 'Earlier' { - const date = new Date(timestamp) - const today = new Date() - const startToday = new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime() - const startYesterday = startToday - 24 * 60 * 60 * 1000 - if (date.getTime() >= startToday) { - return 'Today' - } - if (date.getTime() >= startYesterday) { - return 'Yesterday' - } - return 'Earlier' -} - function ThreadRow({ thread, - density, selected, onSelect, onToggleRead }: { - thread: WorktreeThread - density: ActivityDensity + thread: AgentPaneThread selected: boolean onSelect: () => void onToggleRead: () => void }): React.JSX.Element { const latest = thread.latestEvent - const compact = density === 'compact' const toggleLabel = thread.unread ? 'Mark thread read' : 'Mark thread unread' return (
{thread.unread ? ( ) : null} - + + + + + {/* Why (line-clamp-2 + smaller size): prompts can be long; clamping + to two lines lets users read more of the prompt while keeping + rows scannable. text-[13px] tightens the leading slightly so two + clamped lines don't dominate the row vertically. */} - {thread.worktree.displayName} + {thread.paneTitle} - {eventTitle(latest)} + + {thread.worktree.displayName} + - {!compact ? ( - - {eventSummary(latest)} + + {/* Why (single-line right cluster): keeping time and count on the same + row stops the right column from forcing a ~48px height when the + left column's prompt is only one line. The row now collapses to + fit a 1-line title and grows naturally for 2-line prompts. */} + + {thread.unread ? ( + + New ) : null} - - - - - - - - - - - - - {toggleLabel} - - + + {thread.events.length} + + + + - - {thread.unread ? ( - - New - - ) : null} - - {thread.events.length} - + + + + + + {toggleLabel} + @@ -599,11 +652,13 @@ function ThreadRow({ export default function ActivityPrototypePage(): React.JSX.Element { const [readFilter, setReadFilter] = useState('all') - const [leftSidebarCompact, setLeftSidebarCompact] = useState(true) - const leftSidebarDensity: ActivityDensity = leftSidebarCompact ? 'compact' : 'comfortable' const [query, setQuery] = useState('') - const [locallyReadEventIds, setLocallyReadEventIds] = useState>(() => new Set()) - const [selectedWorktreeId, setSelectedWorktreeId] = useState(null) + const [selectedPaneKey, setSelectedPaneKey] = useState(null) + const [displayedPaneKey, setDisplayedPaneKey] = useState(null) + const [activePortalSlotId, setActivePortalSlotId] = + useState('primary') + const [primaryPortalTargetEl, setPrimaryPortalTargetEl] = useState(null) + const [secondaryPortalTargetEl, setSecondaryPortalTargetEl] = useState(null) const [threadListWidth, setThreadListWidth] = useState(340) const { containerRef: threadListRef, @@ -627,27 +682,21 @@ export default function ActivityPrototypePage(): React.JSX.Element { repoMap: getRepoMapFromState(s), acknowledgedAgentsByPaneKey: s.acknowledgedAgentsByPaneKey, acknowledgeAgents: s.acknowledgeAgents, - unacknowledgeAgents: s.unacknowledgeAgents, - markWorktreeUnread: s.markWorktreeUnread, - clearWorktreeUnread: s.clearWorktreeUnread + unacknowledgeAgents: s.unacknowledgeAgents })) ) - const allEvents = useMemo( - () => - buildActivityEvents({ - ...storeData, - locallyReadEventIds - }), - [storeData, locallyReadEventIds] - ) + const allEvents = useMemo(() => buildActivityEvents(storeData), [storeData]) - const allThreads = useMemo(() => buildWorktreeThreads(allEvents), [allEvents]) + const allThreads = useMemo(() => buildAgentPaneThreads(allEvents), [allEvents]) const visibleThreads = useMemo(() => { const trimmedQuery = query.trim().toLowerCase() return allThreads.filter((thread) => { - if (readFilter === 'unread' && !thread.unread) { + // Why: keep the just-selected thread visible even after auto-mark-read + // flips it to read, otherwise clicking a row in unread-only mode makes it + // vanish from the left list while staying selected on the right. + if (readFilter === 'unread' && !thread.unread && thread.paneKey !== selectedPaneKey) { return false } if (!trimmedQuery) { @@ -655,84 +704,199 @@ export default function ActivityPrototypePage(): React.JSX.Element { } const latest = thread.latestEvent const text = - `${thread.worktree.displayName} ${thread.repo?.displayName ?? ''} ${eventTitle(latest)} ${eventSummary(latest)} ${eventMeta(latest)}`.toLowerCase() + `${thread.paneTitle} ${thread.worktree.displayName} ${thread.repo?.displayName ?? ''} ${agentTitle(latest)} ${agentSummary(latest)} ${agentMeta(latest)}`.toLowerCase() return text.includes(trimmedQuery) }) - }, [allThreads, readFilter, query]) + }, [allThreads, readFilter, query, selectedPaneKey]) useEffect(() => { - if (visibleThreads.length === 0) { - setSelectedWorktreeId(null) + if (selectedPaneKey && !allThreads.some((thread) => thread.paneKey === selectedPaneKey)) { + setSelectedPaneKey(null) + } + }, [allThreads, selectedPaneKey]) + + const selectedThread = selectedPaneKey + ? (allThreads.find((thread) => thread.paneKey === selectedPaneKey) ?? null) + : null + const selectedTabId = selectedThread?.latestEvent.tab.id ?? null + const selectedHasLiveTab = + selectedThread && selectedTabId + ? (storeData.tabsByWorktree[selectedThread.worktree.id] ?? []).some( + (tab) => tab.id === selectedTabId + ) + : false + const displayedThread = displayedPaneKey + ? (allThreads.find((thread) => thread.paneKey === displayedPaneKey) ?? null) + : null + const displayedTabId = displayedThread?.latestEvent.tab.id ?? null + const displayedHasLiveTab = + displayedThread && displayedTabId + ? (storeData.tabsByWorktree[displayedThread.worktree.id] ?? []).some( + (tab) => tab.id === displayedTabId + ) + : false + const displayedIsSelectedTerminal = + selectedThread && + displayedThread && + displayedThread.worktree.id === selectedThread.worktree.id && + displayedThread.latestEvent.tab.id === selectedThread.latestEvent.tab.id + const visibleThread = + selectedThread && selectedHasLiveTab + ? displayedThread && displayedHasLiveTab && displayedThread.paneKey !== selectedThread.paneKey + ? displayedIsSelectedTerminal + ? selectedThread + : displayedThread + : selectedThread + : null + const stagedThread = + selectedThread && + selectedHasLiveTab && + visibleThread && + visibleThread.paneKey !== selectedThread.paneKey && + !displayedIsSelectedTerminal + ? selectedThread + : null + const inactivePortalSlotId = otherActivityTerminalSlot(activePortalSlotId) + const portalTargetBySlot = { + primary: primaryPortalTargetEl, + secondary: secondaryPortalTargetEl + } satisfies Record + const activePortalTargetEl = portalTargetBySlot[activePortalSlotId] + const inactivePortalTargetEl = portalTargetBySlot[inactivePortalSlotId] + const visibleTabId = visibleThread?.latestEvent.tab.id ?? null + const stagedTabId = stagedThread?.latestEvent.tab.id ?? null + const visiblePortalReady = useActivityTerminalPortalReadiness(activePortalTargetEl, visibleTabId) + const stagedPortalReady = useActivityTerminalPortalReadiness(inactivePortalTargetEl, stagedTabId) + const showTerminalLoadingLabel = useActivityTerminalLoadingLabel( + Boolean(visibleThread && !stagedThread && !visiblePortalReady) + ) + + const setPrimaryPortalTarget = useCallback((target: HTMLElement | null): void => { + setPrimaryPortalTargetEl(target) + }, []) + + const setSecondaryPortalTarget = useCallback((target: HTMLElement | null): void => { + setSecondaryPortalTargetEl(target) + }, []) + + // Why (no flash on selection): publish the portal descriptor with the + // selected thread's worktreeId+tabId directly, instead of letting Terminal + // derive it from activeWorktreeId/activeTabId. selectThread updates the + // store in multiple steps (setActiveRepo → setActiveWorktree → + // setActiveTabType → setActiveTab) and React commits in between can + // briefly reflect the new worktree's stale "last active tab" — that's the + // wrong-terminal flash. Anchoring the portal to the selected thread + // sidesteps the race entirely. + // Why useMemo: keep a stable descriptor identity across unrelated re-renders + // so subscribers (Terminal → WorktreeSplitSurface) keep their React.memo + // bail-outs. The inactive descriptor is a same-size staging slot: the old + // terminal stays visible while the next terminal mounts underneath it. + const portalDescriptors = useMemo(() => { + const descriptors: ActivityTerminalPortalTarget[] = [] + if (visibleThread && activePortalTargetEl) { + descriptors.push({ + slotId: activePortalSlotId, + target: activePortalTargetEl, + worktreeId: visibleThread.worktree.id, + tabId: visibleThread.latestEvent.tab.id, + active: true + }) + } + if (stagedThread && inactivePortalTargetEl) { + descriptors.push({ + slotId: inactivePortalSlotId, + target: inactivePortalTargetEl, + worktreeId: stagedThread.worktree.id, + tabId: stagedThread.latestEvent.tab.id, + active: false + }) + } + return descriptors + }, [ + activePortalSlotId, + activePortalTargetEl, + inactivePortalSlotId, + inactivePortalTargetEl, + stagedThread, + visibleThread + ]) + + useLayoutEffect(() => { + if (!selectedThread || !selectedHasLiveTab) { + setDisplayedPaneKey(null) return } - if ( - !selectedWorktreeId || - !visibleThreads.some((thread) => thread.worktree.id === selectedWorktreeId) - ) { - setSelectedWorktreeId(visibleThreads[0].worktree.id) + if (stagedThread && stagedPortalReady) { + setActivePortalSlotId(inactivePortalSlotId) + setDisplayedPaneKey(stagedThread.paneKey) + return } - }, [selectedWorktreeId, visibleThreads]) + if (!stagedThread && visibleThread?.paneKey === selectedThread.paneKey && visiblePortalReady) { + setDisplayedPaneKey(selectedThread.paneKey) + } + }, [ + inactivePortalSlotId, + selectedHasLiveTab, + selectedThread, + stagedPortalReady, + stagedThread, + visiblePortalReady, + visibleThread + ]) - const selectedThread = - visibleThreads.find((thread) => thread.worktree.id === selectedWorktreeId) ?? - visibleThreads[0] ?? - null + // Why useLayoutEffect (not useEffect): publish must happen before paint so + // Terminal's portal subscriber rerenders in the same commit. With useEffect + // the publish runs after paint, so the user briefly sees Terminal's stale + // portal target on screen — the "wrong terminal flash" symptom. + // Why no cleanup-to-null on every change: clearing on dependency change + // forces the portal through a null state on every thread switch (cleanup → + // effect within one commit) which can flash the workspace pane behind the + // activity slot. We only null on unmount, via a separate effect below. + useLayoutEffect(() => { + setActivityTerminalPortals(portalDescriptors) + }, [portalDescriptors]) - const selectedGroupedEvents = useMemo(() => { - const groups: Record<'Today' | 'Yesterday' | 'Earlier', ActivityEvent[]> = { - Today: [], - Yesterday: [], - Earlier: [] + useLayoutEffect(() => { + return () => { + setActivityTerminalPortals([]) } - if (!selectedThread) { - return groups - } - for (const event of selectedThread.events) { - groups[groupForTimestamp(event.timestamp)].push(event) - } - return groups - }, [selectedThread]) + }, []) - const selectThread = (thread: WorktreeThread): void => { - setSelectedWorktreeId(thread.worktree.id) + const markThreadRead = (thread: AgentPaneThread): void => { + storeData.acknowledgeAgents([thread.paneKey]) + } + + const markThreadUnread = (thread: AgentPaneThread): void => { + storeData.unacknowledgeAgents([thread.paneKey]) + } + + const activateThreadTerminal = (thread: AgentPaneThread): void => { + const state = useAppStore.getState() + // Why: retained-agent threads can outlive their tab. With no live tab, the + // right pane shows the empty-state placeholder; reorienting the workspace + // and dispatching focus to a dead tab id would just confuse the user. + const liveTabs = state.tabsByWorktree[thread.worktree.id] ?? [] + const hasLiveTab = liveTabs.some((t) => t.id === thread.latestEvent.tab.id) + if (!hasLiveTab) { + return + } + if (state.activeRepoId !== thread.worktree.repoId) { + state.setActiveRepo(thread.worktree.repoId) + } + if (state.activeWorktreeId !== thread.worktree.id) { + state.setActiveWorktree(thread.worktree.id) + } + state.setActiveTabType('terminal') + activateTabAndFocusPane(thread.latestEvent.tab.id, paneIdFromPaneKey(thread.paneKey)) + } + + const selectThread = (thread: AgentPaneThread): void => { + setSelectedPaneKey(thread.paneKey) markThreadRead(thread) + activateThreadTerminal(thread) } - const markThreadRead = (thread: WorktreeThread): void => { - const agentPaneKeys = thread.events.flatMap((event) => - event.kind === 'agent' ? [event.entry.paneKey] : [] - ) - storeData.acknowledgeAgents(agentPaneKeys) - if (thread.events.some((event) => event.kind === 'worktree-created')) { - storeData.clearWorktreeUnread(thread.worktree.id) - } - setLocallyReadEventIds((current) => { - const next = new Set(current) - for (const event of thread.events) { - next.add(event.id) - } - return next - }) - } - - const markThreadUnread = (thread: WorktreeThread): void => { - const agentPaneKeys = thread.events.flatMap((event) => - event.kind === 'agent' ? [event.entry.paneKey] : [] - ) - storeData.unacknowledgeAgents(agentPaneKeys) - if (thread.events.some((event) => event.kind === 'worktree-created')) { - storeData.markWorktreeUnread(thread.worktree.id) - } - setLocallyReadEventIds((current) => { - const next = new Set(current) - for (const event of thread.events) { - next.delete(event.id) - } - return next - }) - } - - const toggleThreadRead = (thread: WorktreeThread): void => { + const toggleThreadRead = (thread: AgentPaneThread): void => { if (thread.unread) { markThreadRead(thread) return @@ -740,51 +904,24 @@ export default function ActivityPrototypePage(): React.JSX.Element { markThreadUnread(thread) } - const markRead = (event: ActivityEvent): void => { - if (event.kind === 'agent') { - storeData.acknowledgeAgents([event.entry.paneKey]) - return - } - setLocallyReadEventIds((current) => new Set(current).add(event.id)) - storeData.clearWorktreeUnread(event.worktree.id) - } - + // 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 ? (
-
+
-
-

- {selectedThread.worktree.displayName} +
+ + + + {/* Why: clamp to 2 lines (matches ThreadRow) so longer + prompts don't get cut to one ellipsis. Badge moves to + the secondary line so it stays at a fixed position + regardless of title height. */} +

+ {selectedThread.paneTitle}

-
-
- Complete worktree history, from creation through latest agent updates +
+ + + {selectedThread.worktree.displayName} +

-
- {(['Today', 'Yesterday', 'Earlier'] as const).map((group) => - selectedGroupedEvents[group].length > 0 ? ( -
-
- {group} + {/* 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 ( +
+ + Agent terminal closed. Open a new terminal in this workspace to continue. +
+ ) + } + return ( +
+
+
+ {visibleThread && !stagedThread && !visiblePortalReady ? ( + - {[...selectedGroupedEvents[group]].reverse().map((event) => ( - - ))} -
- ) : null - )} -
+ ) : null} +
+ ) + })()}
) : (
- - No activity yet. + {visibleThreads.length === 0 ? ( + <> + + No activity yet. + + ) : ( + <> + + Select an agent to open its terminal. + + )}
)}
diff --git a/src/renderer/src/components/activity/ActivityTitlebarControls.tsx b/src/renderer/src/components/activity/ActivityTitlebarControls.tsx index 10f4010c6..47e25fb39 100644 --- a/src/renderer/src/components/activity/ActivityTitlebarControls.tsx +++ b/src/renderer/src/components/activity/ActivityTitlebarControls.tsx @@ -1,34 +1,34 @@ -import { Bell } from 'lucide-react' +import { ArrowLeft, Bell } from 'lucide-react' import { useAppStore } from '@/store' import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import type { AgentStatusEntry, AgentStatusState } from '../../../../shared/agent-status-types' function useActivityUnreadCount(): number { return useAppStore((s) => { let count = 0 - for (const worktrees of Object.values(s.worktreesByRepo)) { - for (const worktree of worktrees) { - if (worktree.createdAt && worktree.isUnread) { + const isUnreadState = (state: AgentStatusState): boolean => + state === 'done' || state === 'blocked' || state === 'waiting' + // Why: Activity feed surfaces every historical done/blocked/waiting event from + // stateHistory plus the live state, so the badge must mirror the same walk — + // counting only on entry.state under-counts panes that started a new turn. + const accumulate = (entry: AgentStatusEntry, ackAt: number): void => { + for (const history of entry.stateHistory) { + if (isUnreadState(history.state) && ackAt < history.startedAt) { count += 1 } } + if (isUnreadState(entry.state) && ackAt < entry.stateStartedAt) { + count += 1 + } } for (const [paneKey, entry] of Object.entries(s.agentStatusByPaneKey)) { - if (entry.state !== 'done' && entry.state !== 'blocked' && entry.state !== 'waiting') { - continue - } - if ((s.acknowledgedAgentsByPaneKey[paneKey] ?? 0) < entry.stateStartedAt) { - count += 1 - } + accumulate(entry, s.acknowledgedAgentsByPaneKey[paneKey] ?? 0) } for (const [paneKey, retained] of Object.entries(s.retainedAgentsByPaneKey)) { - if (retained.entry.state !== 'done') { - continue - } - if ((s.acknowledgedAgentsByPaneKey[paneKey] ?? 0) < retained.entry.stateStartedAt) { - count += 1 - } + accumulate(retained.entry, s.acknowledgedAgentsByPaneKey[paneKey] ?? 0) } return count }) @@ -37,31 +37,43 @@ function useActivityUnreadCount(): number { export function ActivityTitlebarControls(): React.JSX.Element { const unreadCount = useActivityUnreadCount() const acknowledgeAgents = useAppStore((s) => s.acknowledgeAgents) - const clearWorktreeUnread = useAppStore((s) => s.clearWorktreeUnread) + const closeActivityPage = useAppStore((s) => s.closeActivityPage) const markAllRead = (): void => { const state = useAppStore.getState() + // Why: ack every pane (live + retained) — Date.now() exceeds all historical + // startedAt values, clearing the per-history-event unread flags too. acknowledgeAgents([ - ...Object.values(state.agentStatusByPaneKey) - .filter( - (entry) => - entry.state === 'done' || entry.state === 'blocked' || entry.state === 'waiting' - ) - .map((entry) => entry.paneKey), + ...Object.values(state.agentStatusByPaneKey).map((entry) => entry.paneKey), ...Object.values(state.retainedAgentsByPaneKey).map((retained) => retained.entry.paneKey) ]) - for (const worktrees of Object.values(state.worktreesByRepo)) { - for (const worktree of worktrees) { - if (worktree.createdAt && worktree.isUnread) { - clearWorktreeUnread(worktree.id) - } - } - } } return (
-
+
+ {/* Why: Activity hides the worktree sidebar (full-page surface), so the + sidebar's nav row isn't available as the back path. This Back button + is the dedicated exit, mirroring Settings' onBack pattern. */} + + + + + + Close activity + + Activity diff --git a/src/renderer/src/components/activity/activity-terminal-portal.ts b/src/renderer/src/components/activity/activity-terminal-portal.ts new file mode 100644 index 000000000..3c83470d6 --- /dev/null +++ b/src/renderer/src/components/activity/activity-terminal-portal.ts @@ -0,0 +1,60 @@ +import { useLayoutEffect, useState } from 'react' + +export type ActivityTerminalPortalTarget = { + slotId: string + target: HTMLElement + worktreeId: string + tabId: string + active: boolean +} + +let currentTargets: ActivityTerminalPortalTarget[] = [] +const subscribers = new Set<(targets: ActivityTerminalPortalTarget[]) => void>() + +// Why: the portal target is published with its {worktreeId, tabId} already +// attached so consumers don't have to derive routing from the global +// activeTabId/activeWorktreeId. The activity page knows which agent pane it +// wants to display; deriving from global active state introduced a race where +// repo/worktree updates landed before the matching setActiveTab, briefly +// portaling a different terminal into the activity slot ("flash" of the wrong +// terminal for a few ms). +export function setActivityTerminalPortals(targets: ActivityTerminalPortalTarget[]): void { + if (currentTargets === targets) { + return + } + currentTargets = targets + for (const subscriber of subscribers) { + subscriber(targets) + } +} + +export function useActivityTerminalPortals(enabled: boolean): ActivityTerminalPortalTarget[] { + const [targets, setTargets] = useState( + enabled ? currentTargets : [] + ) + + useLayoutEffect(() => { + if (!enabled) { + setTargets([]) + return + } + setTargets(currentTargets) + const subscriber = (next: ActivityTerminalPortalTarget[]): void => setTargets(next) + subscribers.add(subscriber) + return () => { + subscribers.delete(subscriber) + } + }, [enabled]) + + return targets +} + +export function findActivityTerminalPortal( + targets: ActivityTerminalPortalTarget[], + worktreeId: string, + tabId: string +): ActivityTerminalPortalTarget | null { + return ( + targets.find((target) => target.worktreeId === worktreeId && target.tabId === tabId) ?? null + ) +} diff --git a/src/renderer/src/components/tab-group/TabGroupPanel.tsx b/src/renderer/src/components/tab-group/TabGroupPanel.tsx index b0be2bbbc..c1a921515 100644 --- a/src/renderer/src/components/tab-group/TabGroupPanel.tsx +++ b/src/renderer/src/components/tab-group/TabGroupPanel.tsx @@ -1,4 +1,5 @@ import { lazy, Suspense, useEffect, useMemo, useState } from 'react' +import { createPortal } from 'react-dom' import { useDroppable } from '@dnd-kit/core' import { Columns2, Ellipsis, Rows2, X } from 'lucide-react' import { useAppStore } from '../../store' @@ -20,6 +21,10 @@ import { type HoveredTabInsertion, type TabDropZone } from './useTabDragSplit' +import { + findActivityTerminalPortal, + type ActivityTerminalPortalTarget +} from '../activity/activity-terminal-portal' const EditorPanel = lazy(() => import('../editor/EditorPanel')) @@ -35,7 +40,8 @@ export default function TabGroupPanel({ reserveCollapsedSidebarHeaderSpace, isTabDragActive = false, activeDropZone = null, - hoveredTabInsertion = null + hoveredTabInsertion = null, + activityTerminalPortals = [] }: { groupId: string worktreeId: string @@ -49,6 +55,7 @@ export default function TabGroupPanel({ isTabDragActive?: boolean activeDropZone?: TabDropZone | null hoveredTabInsertion?: HoveredTabInsertion | null + activityTerminalPortals?: ActivityTerminalPortalTarget[] }): React.JSX.Element { const rightSidebarOpen = useAppStore((state) => state.rightSidebarOpen) const sidebarOpen = useAppStore((state) => state.sidebarOpen) @@ -351,36 +358,47 @@ export default function TabGroupPanel({ {activeDropZone ? : null} {model.groupTabs .filter((item) => item.contentType === 'terminal') - .map((item) => ( -
@@ -192,12 +198,14 @@ export default function TabGroupSplitLayout({ layout, worktreeId, focusedGroupId, - isWorktreeActive + isWorktreeActive, + activityTerminalPortals = [] }: { layout: TabGroupLayoutNode worktreeId: string focusedGroupId?: string isWorktreeActive: boolean + activityTerminalPortals?: ActivityTerminalPortalTarget[] }): React.JSX.Element { const dragSplit = useTabDragSplit({ worktreeId, enabled: isWorktreeActive }) const hasSplits = layout.type === 'split' @@ -254,6 +262,7 @@ export default function TabGroupSplitLayout({ activeDropGroupId={dragSplit.hoveredDropTarget?.groupId ?? null} activeDropZone={dragSplit.hoveredDropTarget?.zone ?? null} hoveredTabInsertion={dragSplit.hoveredTabInsertion} + activityTerminalPortals={activityTerminalPortals} />