From e19449110ed48a2e56ca24aee4aa06d79210a8d8 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Tue, 21 Jul 2026 20:47:47 -0400 Subject: [PATCH 01/31] docs(program): FW6-CHAT ship + rollout receipt Co-Authored-By: Claude Fable 5 --- tasks/frontend-ux-log.md | 1 + 1 file changed, 1 insertion(+) diff --git a/tasks/frontend-ux-log.md b/tasks/frontend-ux-log.md index 1e386a2..1383572 100644 --- a/tasks/frontend-ux-log.md +++ b/tasks/frontend-ux-log.md @@ -70,3 +70,4 @@ - ~23:26Z (07-21) FW6-ALT SHIPPED: PR #97 MERGED (main ea86b3e; owner ! command — host policy still reserves gh pr merge; CodeRabbit thread resolved via GraphQL first) + DEPLOYED (SOURCE_COMMIT ea86b3e on BOTH containers, health ok, agents:2). No agentd change, no rollout. Owner phone test = acceptance for finding 6b: drag DOWN on a claude-code pane → the app scrolls its own transcript (per-pane truth via the deployed navigate op); drag DOWN on a codex/shell pane → instant local history overlay (finding 6 acceptance also still pending owner retest there). Program state: findings 4/5/6/6b all shipped; awaiting owner device verdict. - ~23:55Z (07-21) DEVICE FINDING 6c (owner): codex overlay ACCEPTED; claude app-scroll REJECTED ("weird characters along the side", "poor scrolling", no improvement). AI Lead empirical probe (scratch claude TUI, 120-line transcript): SGR wheel delivery WORKS — claude scrolls ~2 lines/event, pane byte-clean at 40 rapid events, sgr=1/all=1 encoding correct — so the artifacts are VIEWER-side xterm tearing of streamed full-screen redraws + RTT feel; input tuning cannot fix it. Owner locked: local CHAT-TRANSCRIPT overlay for claude panes sourced from claude-code's own on-disk history (owner's insight), with app-scroll kept as fallback. Feasibility verified: transcript JSONLs exist per session under ~/.claude/projects//, claude hooks already deliver transcript_path into agentd (resolveHookSessionID/extractAssistantText). FW6-CHAT lane launching locally (brief tasks/2026-07-21-fw6-chat-brief.md): capture_transcript command (schema+agentd+CP, additive, path-bounded to ~/.claude/projects) + overlay chat mode + formatter. First protocol change since FW6-TOUCH — agentd rollout will be required; deploy order safe (old agentd → graceful app-scroll fallback). - ~00:30Z (07-22) FW6-CHAT froze at `6226466` (attempt 1, ~23 min, 5 impl commits, full green gate incl. Go). Firewall CLEAN. Adversarial reviewer SHIP-WITH-NOTES — and it COMPILED ATTACK PROBES against the file-read boundary: symlink-inside-dir, prefix-cousin, hostile cwd slugs, non-regular files ALL REJECTED (EvalSymlinks-before-Rel containment held). AI Lead review fixes (231417c): (1) torn mid-append tail no longer fails the newest page — count excludes it, corrupt interior lines become skipped stubs (claude writes these files LIVE; without this, chat mode silently died to app-scroll during active streaming); (2) toolUseResult dropped + ALL non-metadata strings under a 32KB entry budget + scanner cap 64MiB→8MiB (1MiB Bash stdout previously rode to the phone uncapped); (3) CP source field passthrough-string not enum (anti-additive 5xx risk). Recorded-accepted: first-gesture spinner on transcript-less TUI panes (vim/htop — owner usage is claude/codex; tuning-pass candidate), TOCTOU-on-owned-host, code-point wrap widths. INTEGRATED @ 30a23b9 (--no-ff). FULL GATE GREEN attempt 1: 208 CP + dashboard suites, 21/21 smoke, 40 journeys, build, Go. PR next; agentd ROLLOUT REQUIRED on both hosts after deploy (deploy order safe: old agentd → graceful app-scroll fallback). +- ~00:47Z (07-22) FW6-CHAT SHIPPED: PR #98 MERGED (main 7b30df0, owner ! command; zero CodeRabbit threads) + DEPLOYED (SOURCE_COMMIT verified both containers, health ok) + agentd FW6-CHAT binaries ROLLED on BOTH hosts by AI Lead (tree-identity verified vs gated branch; backups agentd.bak-fw6chat; pgrep single-process check clean on both; agents:2 reconnected). Owner phone test = acceptance for finding 6c: drag DOWN on a claude pane → local formatted chat transcript (❯ user / plain assistant / dim ⏺ tool lines), native scroll, load-older through full session history; codex/shell overlay and app-scroll fallback unchanged. From cc6885ba65041921c6c2bd1315e930c153f6cc06 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Wed, 22 Jul 2026 11:07:24 -0400 Subject: [PATCH 02/31] chore: update project status --- project_status.md | 82 +++++++++++++++++++++++++++++++---------------- 1 file changed, 55 insertions(+), 27 deletions(-) diff --git a/project_status.md b/project_status.md index 0609428..e0a5c50 100644 --- a/project_status.md +++ b/project_status.md @@ -1,7 +1,7 @@ # Project Status - agent-command > **Auto-generated by [project-status agent](https://github.com/cvsloane/open-agents)** -> Last updated: 2026-05-31T15:09:56.291Z +> Last updated: 2026-07-22T15:07:24.401Z ## Purpose @@ -13,7 +13,35 @@ This file provides context for AI assistants (Claude Code, Cursor, etc.) about r ## Recent Development Sessions -No active tmux session for this project. +**Active Session**: `main` +**Working Directory**: `/home/cvsloane/dev/agent-command` + +**Recent Terminal Output**: +``` + scroll, entirely on-device — no tearing, no lag — and load-older pages back through the complete session history from disk, not just what happened since you + attached. + - Codex and shell panes are unchanged (the overlay you already accepted). + - If a pane has no transcript (or before an agentd restart catches up), it degrades to the wheel fallback rather than a black screen. + One honest caveat for the tuning pass if you notice it: very wide lines with CJK/emoji can horizontally scroll slightly (wrap width counts code points), and on + transcript-less full-screen TUIs like htop the first drag after attach shows a brief spinner before scrolling starts on the second drag. Both are receipted as + accepted trade-offs — say the word if either bothers you in practice. + The security story on this one is worth a sentence: the reviewer compiled attack probes against the new file-read boundary (symlink tricks, prefix cousins, + hostile path slugs) and the containment held on every attempt; reads are bounded to ~/.claude/projects, entries are size-budgeted, and mid-stream file writes + can't kill the feature. Standing by for your verdict. +✻ Cooked for 3m 52s +✻ Claude resuming /loop wakeup (Jul 21 8:58pm) +● This tick is the leftover fallback heartbeat from the PR-checks watch — the ship completed, so I'll do one quick production sanity check and stop the loop. + Ran 1 shell command +● Standing by for your device test. +✻ Crunched for 18s + new task? /clear to save 416.3k tokens +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +❯  +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── + Fable 5 | ctx:42% | in:416k out:11 | ~/dev/agent-command + ⏵⏵ auto mode on (shift+tab to cycle) +``` + --- @@ -21,42 +49,42 @@ No active tmux session for this project. | Hash | Message | Date | Author | |------|---------|------|--------| -| `7fa2644` | docs: update agent guidance | 2026-05-30 | cvsloane | -| `fa1afcf` | chore: update project status | 2026-05-20 | cvsloane | -| `e83688e` | feat: add mobile tmux agent launch flow | 2026-05-19 | cvsloane | -| `b797811` | feat: build tmux command center | 2026-05-19 | cvsloane | -| `3045ebf` | chore: update project status | 2026-05-17 | cvsloane | +| `e194491` | docs(program): FW6-CHAT ship + rollout receipt | 2026-07-21 | cvsloane | +| `3688cb7` | docs(program): FW6-CHAT integration receipt | 2026-07-21 | cvsloane | +| `30a23b9` | merge: FW6-CHAT — local chat-transcript overlay for claude panes (231417c) | 2026-07-21 | cvsloane | +| `231417c` | fix(chat): tolerate torn transcript tails, budget all entry strings | 2026-07-21 | cvsloane | +| `2e116c1` | feat(chat): freeze transcript overlay handoff | 2026-07-21 | cvsloane | --- ## Files Changed Recently -- `agents/agentd/internal/ws/client.go` +- `agents/agentd/cmd/agentd/main.go` +- `agents/agentd/cmd/agentd/main_transcript_test.go` +- `agents/agentd/cmd/agentd/transcript.go` +- `agents/agentd/internal/commands/executor.go` +- `agents/agentd/internal/protocol/command.go` - `agents/agentd/internal/ws/protocol_fixtures_test.go` -- `AGENTS.md` -- `apps/dashboard/package.json` -- `apps/dashboard/src/app/(dashboard)/tmux/TmuxPageClient.tsx` -- `apps/dashboard/src/components/BulkActionToolbar.tsx` -- `apps/dashboard/src/components/groups/GroupModal.tsx` -- `apps/dashboard/src/components/groups/GroupTree.tsx` -- `apps/dashboard/src/components/launch/MobileLaunchSheet.tsx` -- `apps/dashboard/src/components/layout/GlobalSidebar.tsx` -- `apps/dashboard/src/components/layout/LayoutShell.tsx` -- `apps/dashboard/src/components/session/SessionWorkbench.tsx` -- `apps/dashboard/src/components/settings/SettingsSync.tsx` -- `apps/dashboard/src/components/terminal/TerminalSurface.tsx` -- `apps/dashboard/src/components/terminal/TerminalToolbar.tsx` -- `apps/dashboard/src/components/terminal/types.ts` +- `apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx` +- `apps/dashboard/src/components/terminal/terminalScrollMode.ts` +- `apps/dashboard/src/components/terminal/transcriptFormatter.test.ts` +- `apps/dashboard/src/components/terminal/transcriptFormatter.ts` - `apps/dashboard/src/components/TerminalView.tsx` -- `apps/dashboard/src/components/tmux/TmuxActionSheet.tsx` -- `apps/dashboard/src/components/tmux/TmuxClusterRow.tsx` -- `apps/dashboard/src/components/tmux/TmuxDesktopShell.tsx` +- `apps/dashboard/src/hooks/useTerminalTouchScroll.test.ts` +- `apps/dashboard/src/lib/api.ts` +- `packages/ac-schema/src/command.ts` +- `packages/ac-schema/src/enums.ts` +- `packages/ac-schema/tests/core-workflows.test.ts` +- `packages/ac-schema/tests/protocol-fixtures.test.ts` +- `services/control-plane/src/routes/sessions.ts` +- `services/control-plane/tests/transcriptRoute.test.ts` +- `services/control-plane/tests/transcriptSchema.test.ts` --- ## Branch Info -- **Current Branch**: `refactor/tmux-command-center` -- **Last Commit**: 2026-05-30T17:26:08-04:00 +- **Current Branch**: `refactor/frontend-command-center` +- **Last Commit**: 2026-07-21T20:47:47-04:00 From 46e26eb64adf40334b589812ffd425fbc1359023 Mon Sep 17 00:00:00 2001 From: cvsloane Date: Wed, 22 Jul 2026 11:25:55 -0400 Subject: [PATCH 03/31] fix(terminal): make pane focus transactional --- agents/agentd/cmd/agentd/main.go | 45 ++++ .../agentd/cmd/agentd/main_terminal_test.go | 96 +++++++++ agents/agentd/internal/protocol/messages.go | 75 +++---- agents/agentd/internal/protocol/terminal.go | 12 ++ .../agentd/internal/tmux/pty_bridge_test.go | 70 +++++++ agents/agentd/internal/tmux/terminal.go | 105 ++++++++++ agents/agentd/internal/tmux/viewer_pty.go | 34 +++ .../internal/ws/protocol_fixtures_test.go | 3 + .../dashboard/src/components/TerminalView.tsx | 52 ++++- .../components/session/SessionWorkbench.tsx | 2 +- .../terminal/PersistentTerminalHost.tsx | 15 +- .../terminal/TerminalHistoryOverlay.test.ts | 34 +++ .../terminal/TerminalHistoryOverlay.tsx | 190 ++++++++++++++--- .../components/terminal/TerminalSurface.tsx | 49 ++++- .../terminal/terminalHostStore.test.ts | 67 +++++- .../components/terminal/terminalHostStore.ts | 68 ++++++ .../terminalNavigationRequests.test.ts | 117 +++++++++++ .../terminal/terminalNavigationRequests.ts | 140 +++++++++++++ .../src/components/terminal/types.ts | 6 +- .../src/components/tmux/PromptComposer.tsx | 25 ++- .../src/components/tmux/TmuxActionSheet.tsx | 5 +- .../src/components/tmux/TmuxMobileShell.tsx | 70 +++++-- .../src/components/tmux/TmuxPaneControls.tsx | 125 +++++++++-- .../src/components/tmux/TmuxPaneSwitcher.tsx | 129 ++++++++++-- .../components/tmux/TmuxQuickSwitchStrip.tsx | 31 ++- .../components/tmux/TmuxTerminalWorkspace.tsx | 38 +++- .../src/components/tmux/TmuxWindowStrip.tsx | 24 ++- .../src/components/tmux/paneSwitcher.test.ts | 61 +++++- .../src/components/tmux/paneSwitcher.ts | 78 ++++++- .../src/hooks/useTerminalConnection.ts | 56 ++++- apps/dashboard/src/hooks/useTmuxRosterData.ts | 14 +- apps/dashboard/src/stores/settings.ts | 11 + packages/ac-schema/src/message.ts | 43 ++++ packages/ac-schema/src/terminal.ts | 36 ++++ .../ac-schema/tests/protocol-fixtures.test.ts | 3 + packages/ac-schema/tests/terminal.test.ts | 56 +++++ services/control-plane/src/metrics.test.ts | 24 +++ services/control-plane/src/metrics.ts | 28 +++ services/control-plane/src/routes/terminal.ts | 71 +++++++ services/control-plane/src/ws/agent.ts | 12 +- .../control-plane/tests/terminalRoute.test.ts | 110 +++++++++- tasks/lessons.md | 4 + .../protocol/terminal-focus-pane.json | 1 + .../protocol/terminal-navigation-result.json | 1 + .../protocol/terminal-viewer-state.json | 1 + tests/journeys/command-center.journey.spec.ts | 124 ++++++++++- tests/journeys/controlPlaneMock.ts | 92 +++++++- tests/journeys/fw6-focus.journey.spec.ts | 197 ++++++++++++------ tests/journeys/fw6-precision.journey.spec.ts | 28 ++- 49 files changed, 2440 insertions(+), 238 deletions(-) create mode 100644 apps/dashboard/src/components/terminal/TerminalHistoryOverlay.test.ts create mode 100644 apps/dashboard/src/components/terminal/terminalNavigationRequests.test.ts create mode 100644 apps/dashboard/src/components/terminal/terminalNavigationRequests.ts create mode 100644 services/control-plane/src/metrics.test.ts create mode 100644 tests/fixtures/protocol/terminal-focus-pane.json create mode 100644 tests/fixtures/protocol/terminal-navigation-result.json create mode 100644 tests/fixtures/protocol/terminal-viewer-state.json diff --git a/agents/agentd/cmd/agentd/main.go b/agents/agentd/cmd/agentd/main.go index 9a93913..bad269f 100644 --- a/agents/agentd/cmd/agentd/main.go +++ b/agents/agentd/cmd/agentd/main.go @@ -5526,6 +5526,51 @@ func (a *Agent) handleTerminalNavigate(payload json.RawMessage) { navigation := tmux.TerminalNavigation{Op: tmux.TerminalNavigationOp(req.Op)} switch navigation.Op { + case "viewer_state": + result := protocol.TerminalNavigationResultPayload{ + ChannelID: req.ChannelID, + RequestID: req.RequestID, + } + if strings.TrimSpace(req.RequestID) == "" { + result.Message = "viewer_state requires request_id" + _ = a.send(protocol.TypeTerminalNavigationResult, result) + return + } + state, err := a.terminalManager.ViewerState(req.ChannelID) + result.PaneID = state.PaneID + result.WindowIndex = state.WindowIndex + result.Zoomed = state.Zoomed + if err != nil { + result.Message = err.Error() + log.Printf("Failed to read terminal viewer state for request %s: %v", req.RequestID, err) + } else { + result.OK = true + } + _ = a.send(protocol.TypeTerminalNavigationResult, result) + return + case "focus_pane": + result := protocol.TerminalNavigationResultPayload{ + ChannelID: req.ChannelID, + RequestID: req.RequestID, + PaneID: req.PaneID, + } + if strings.TrimSpace(req.RequestID) == "" || strings.TrimSpace(req.PaneID) == "" || req.Zoom == nil { + result.Message = "focus_pane requires request_id, pane_id, and zoom" + _ = a.send(protocol.TypeTerminalNavigationResult, result) + return + } + state, err := a.terminalManager.FocusPane(req.ChannelID, req.PaneID, *req.Zoom) + result.PaneID = state.PaneID + result.WindowIndex = state.WindowIndex + result.Zoomed = state.Zoomed + if err != nil { + result.Message = err.Error() + log.Printf("Failed to focus terminal pane for request %s: %v", req.RequestID, err) + } else { + result.OK = true + } + _ = a.send(protocol.TypeTerminalNavigationResult, result) + return case tmux.NavigateSelectWindow: if req.WindowIndex == nil { log.Printf("Failed to parse terminal.navigate: select_window requires window_index") diff --git a/agents/agentd/cmd/agentd/main_terminal_test.go b/agents/agentd/cmd/agentd/main_terminal_test.go index 8c01013..d9a38fa 100644 --- a/agents/agentd/cmd/agentd/main_terminal_test.go +++ b/agents/agentd/cmd/agentd/main_terminal_test.go @@ -119,6 +119,102 @@ func TestHandleTerminalNavigateRoutesToGroupedViewerOnPrivateSocket(t *testing.T } } +func TestHandleTerminalFocusPaneReportsVerifiedViewerState(t *testing.T) { + tmuxClient := newPrivateCommandTmux(t) + panes, err := tmuxClient.ListPanes() + if err != nil || len(panes) != 1 { + t.Fatalf("initial panes=%+v err=%v", panes, err) + } + target, err := tmuxClient.SplitPaneWithOptions(panes[0].PaneID, "horizontal", nil, "") + if err != nil { + t.Fatalf("split pane: %v", err) + } + + manager := tmux.NewTerminalManager(tmuxClient, t.TempDir()) + manager.SetPerViewerPTY(true) + defer manager.Close() + if _, err := manager.AttachWithOptions("focus-channel", panes[0].PaneID, tmux.AttachOptions{SessionID: "session-1"}); err != nil { + t.Fatalf("attach viewer: %v", err) + } + + var gotType string + var gotPayload any + agent := &Agent{ + terminalManager: manager, + sendMessage: func(msgType string, payload any) error { + gotType = msgType + gotPayload = payload + return nil + }, + } + payload, err := json.Marshal(protocol.TerminalNavigatePayload{ + ChannelID: "focus-channel", + Op: "focus_pane", + RequestID: "44444444-4444-4444-8444-444444444444", + PaneID: target.PaneID, + Zoom: boolPointer(true), + }) + if err != nil { + t.Fatal(err) + } + agent.handleMessage(protocol.TypeTerminalNavigate, payload) + + result, ok := gotPayload.(protocol.TerminalNavigationResultPayload) + if gotType != protocol.TypeTerminalNavigationResult || !ok { + t.Fatalf("message=(%q, %#v), want terminal navigation result", gotType, gotPayload) + } + if !result.OK || result.PaneID != target.PaneID || result.WindowIndex != 0 || !result.Zoomed { + t.Fatalf("navigation result=%+v", result) + } +} + +func TestHandleTerminalViewerStateReportsCurrentViewerState(t *testing.T) { + tmuxClient := newPrivateCommandTmux(t) + panes, err := tmuxClient.ListPanes() + if err != nil || len(panes) != 1 { + t.Fatalf("initial panes=%+v err=%v", panes, err) + } + + manager := tmux.NewTerminalManager(tmuxClient, t.TempDir()) + manager.SetPerViewerPTY(true) + defer manager.Close() + if _, err := manager.AttachWithOptions("state-channel", panes[0].PaneID, tmux.AttachOptions{SessionID: "session-1"}); err != nil { + t.Fatalf("attach viewer: %v", err) + } + + var gotType string + var gotPayload any + agent := &Agent{ + terminalManager: manager, + sendMessage: func(msgType string, payload any) error { + gotType = msgType + gotPayload = payload + return nil + }, + } + payload, err := json.Marshal(protocol.TerminalNavigatePayload{ + ChannelID: "state-channel", + Op: "viewer_state", + RequestID: "66666666-6666-4666-8666-666666666666", + }) + if err != nil { + t.Fatal(err) + } + agent.handleMessage(protocol.TypeTerminalNavigate, payload) + + result, ok := gotPayload.(protocol.TerminalNavigationResultPayload) + if gotType != protocol.TypeTerminalNavigationResult || !ok { + t.Fatalf("message=(%q, %#v), want terminal navigation result", gotType, gotPayload) + } + if !result.OK || result.PaneID != panes[0].PaneID || result.WindowIndex != 0 || result.Zoomed { + t.Fatalf("viewer state result=%+v", result) + } +} + +func boolPointer(value bool) *bool { + return &value +} + func TestTerminalAttachSupersedesStaleChannelAfterControlPlaneReconnect(t *testing.T) { tmuxClient := newPrivateCommandTmux(t) panes, err := tmuxClient.ListPanes() diff --git a/agents/agentd/internal/protocol/messages.go b/agents/agentd/internal/protocol/messages.go index 80f50b4..84a230e 100644 --- a/agents/agentd/internal/protocol/messages.go +++ b/agents/agentd/internal/protocol/messages.go @@ -6,43 +6,44 @@ import "encoding/json" const Version = 1 const ( - TypeAgentHello = "agent.hello" - TypeAgentAck = "agent.ack" - TypeSessionsUpsert = "sessions.upsert" - TypeSessionsPrune = "sessions.prune" - TypeSessionsSnapshot = "sessions.snapshot" - TypeEventsAppend = "events.append" - TypeCommandsDispatch = "commands.dispatch" - TypeCommandsResult = "commands.result" - TypeConsoleChunk = "console.chunk" - TypeToolEventStarted = "tool.event.started" - TypeToolEventCompleted = "tool.event.completed" - TypeProviderUsage = "provider.usage" - TypeSessionUsage = "session.usage" - TypeApprovalsDecision = "approvals.decision" - TypeMCPListServers = "mcp.list_servers" - TypeMCPGetConfig = "mcp.get_config" - TypeMCPUpdateConfig = "mcp.update_config" - TypeMCPGetProjectConfig = "mcp.get_project_config" - TypeMCPUpdateProject = "mcp.update_project_config" - TypeMCPServers = "mcp.servers" - TypeMCPConfig = "mcp.config" - TypeMCPProjectConfig = "mcp.project_config" - TypeMCPUpdateResult = "mcp.update_result" - TypeTerminalAttach = "terminal.attach" - TypeTerminalInput = "terminal.input" - TypeTerminalResize = "terminal.resize" - TypeTerminalNavigate = "terminal.navigate" - TypeTerminalDetach = "terminal.detach" - TypeTerminalControl = "terminal.control" - TypeTerminalOutput = "terminal.output" - TypeTerminalAttached = "terminal.attached" - TypeTerminalDetached = "terminal.detached" - TypeTerminalError = "terminal.error" - TypeTerminalReadOnly = "terminal.readonly" - TypeTerminalLag = "terminal.lag" - TypeTerminalAudit = "terminal.audit" - TypeTmuxTopology = "tmux.topology" + TypeAgentHello = "agent.hello" + TypeAgentAck = "agent.ack" + TypeSessionsUpsert = "sessions.upsert" + TypeSessionsPrune = "sessions.prune" + TypeSessionsSnapshot = "sessions.snapshot" + TypeEventsAppend = "events.append" + TypeCommandsDispatch = "commands.dispatch" + TypeCommandsResult = "commands.result" + TypeConsoleChunk = "console.chunk" + TypeToolEventStarted = "tool.event.started" + TypeToolEventCompleted = "tool.event.completed" + TypeProviderUsage = "provider.usage" + TypeSessionUsage = "session.usage" + TypeApprovalsDecision = "approvals.decision" + TypeMCPListServers = "mcp.list_servers" + TypeMCPGetConfig = "mcp.get_config" + TypeMCPUpdateConfig = "mcp.update_config" + TypeMCPGetProjectConfig = "mcp.get_project_config" + TypeMCPUpdateProject = "mcp.update_project_config" + TypeMCPServers = "mcp.servers" + TypeMCPConfig = "mcp.config" + TypeMCPProjectConfig = "mcp.project_config" + TypeMCPUpdateResult = "mcp.update_result" + TypeTerminalAttach = "terminal.attach" + TypeTerminalInput = "terminal.input" + TypeTerminalResize = "terminal.resize" + TypeTerminalNavigate = "terminal.navigate" + TypeTerminalNavigationResult = "terminal.navigation_result" + TypeTerminalDetach = "terminal.detach" + TypeTerminalControl = "terminal.control" + TypeTerminalOutput = "terminal.output" + TypeTerminalAttached = "terminal.attached" + TypeTerminalDetached = "terminal.detached" + TypeTerminalError = "terminal.error" + TypeTerminalReadOnly = "terminal.readonly" + TypeTerminalLag = "terminal.lag" + TypeTerminalAudit = "terminal.audit" + TypeTmuxTopology = "tmux.topology" ) // EnvelopeHeader supports direction-agnostic inspection before decoding a diff --git a/agents/agentd/internal/protocol/terminal.go b/agents/agentd/internal/protocol/terminal.go index 5e8bc20..5c99ffc 100644 --- a/agents/agentd/internal/protocol/terminal.go +++ b/agents/agentd/internal/protocol/terminal.go @@ -24,12 +24,24 @@ type TerminalResizePayload struct { type TerminalNavigatePayload struct { ChannelID string `json:"channel_id"` Op string `json:"op"` + RequestID string `json:"request_id,omitempty"` WindowIndex *int `json:"window_index,omitempty"` PaneID string `json:"pane_id,omitempty"` On *bool `json:"on,omitempty"` + Zoom *bool `json:"zoom,omitempty"` Lines *int `json:"lines,omitempty"` } +type TerminalNavigationResultPayload struct { + ChannelID string `json:"channel_id"` + RequestID string `json:"request_id"` + OK bool `json:"ok"` + PaneID string `json:"pane_id,omitempty"` + WindowIndex int `json:"window_index"` + Zoomed bool `json:"zoomed"` + Message string `json:"message,omitempty"` +} + type TerminalChannelPayload struct { ChannelID string `json:"channel_id"` } diff --git a/agents/agentd/internal/tmux/pty_bridge_test.go b/agents/agentd/internal/tmux/pty_bridge_test.go index f960b55..50fedba 100644 --- a/agents/agentd/internal/tmux/pty_bridge_test.go +++ b/agents/agentd/internal/tmux/pty_bridge_test.go @@ -226,6 +226,76 @@ func TestTerminalNavigateSelectPaneUsesViewerSessionOnPrivateTmuxSocket(t *testi } } +func TestTerminalFocusPaneSelectsAndZoomsVerifiedTargetOnPrivateTmuxSocket(t *testing.T) { + client, _ := newPrivateTmuxClient(t) + panes, err := client.ListPanes() + if err != nil || len(panes) != 1 { + t.Fatalf("initial private panes=%+v err=%v", panes, err) + } + target, err := client.SplitPaneWithOptions(panes[0].PaneID, "horizontal", nil, "") + if err != nil { + t.Fatalf("split private pane: %v", err) + } + + manager := newTerminalManagerWithRunner(client, newExecTmuxRunner(client), t.TempDir()) + defer manager.Close() + if _, err := manager.AttachWithOptions("focus-pane", panes[0].PaneID, AttachOptions{SessionID: "session-1"}); err != nil { + t.Fatalf("attach viewer: %v", err) + } + + state, err := manager.FocusPane("focus-pane", target.PaneID, true) + if err != nil { + t.Fatalf("focus viewer pane: %v", err) + } + if state.PaneID != target.PaneID || state.WindowIndex != 0 || !state.Zoomed { + t.Fatalf("verified viewer state=%+v, want pane=%s window=0 zoomed", state, target.PaneID) + } +} + +type failFirstZoomRunner struct { + TmuxRunner + failed bool +} + +func (r *failFirstZoomRunner) Run(args ...string) error { + if !r.failed && len(args) >= 2 && args[0] == "resize-pane" && args[1] == "-Z" { + r.failed = true + return errors.New("injected zoom failure") + } + return r.TmuxRunner.Run(args...) +} + +func TestTerminalFocusPaneRollsBackWhenZoomFails(t *testing.T) { + client, _ := newPrivateTmuxClient(t) + panes, err := client.ListPanes() + if err != nil || len(panes) != 1 { + t.Fatalf("initial private panes=%+v err=%v", panes, err) + } + originPaneID := panes[0].PaneID + target, err := client.SplitPaneWithOptions(originPaneID, "horizontal", nil, "") + if err != nil { + t.Fatalf("split private pane: %v", err) + } + + runner := &failFirstZoomRunner{TmuxRunner: newExecTmuxRunner(client)} + manager := newTerminalManagerWithRunner(client, runner, t.TempDir()) + defer manager.Close() + if _, err := manager.AttachWithOptions("focus-rollback", originPaneID, AttachOptions{SessionID: "session-1"}); err != nil { + t.Fatalf("attach viewer: %v", err) + } + + if _, err := manager.FocusPane("focus-rollback", target.PaneID, true); err == nil { + t.Fatal("focus unexpectedly succeeded") + } + state, err := manager.viewerByChannel["focus-rollback"].bridge.State() + if err != nil { + t.Fatalf("read rolled-back viewer state: %v", err) + } + if state.PaneID != originPaneID || state.Zoomed { + t.Fatalf("viewer state after failed focus=%+v, want pane=%s unzoomed", state, originPaneID) + } +} + func TestTerminalNavigateZoomSetsRequestedStateOnPrivateTmuxSocket(t *testing.T) { client, _ := newPrivateTmuxClient(t) panes, err := client.ListPanes() diff --git a/agents/agentd/internal/tmux/terminal.go b/agents/agentd/internal/tmux/terminal.go index 6b82b60..5f44f20 100644 --- a/agents/agentd/internal/tmux/terminal.go +++ b/agents/agentd/internal/tmux/terminal.go @@ -122,6 +122,14 @@ type TerminalNavigation struct { Lines int } +// TerminalViewerState is the state read back from the grouped viewer after a +// state-changing navigation request. +type TerminalViewerState struct { + PaneID string + WindowIndex int + Zoomed bool +} + // AttachOptions contains additive terminal.attach fields. type AttachOptions struct { SessionID string @@ -813,6 +821,103 @@ func (m *TerminalManager) Navigate(channelID string, navigation TerminalNavigati } } +// ViewerState returns the current grouped-viewer state read directly from tmux. +func (m *TerminalManager) ViewerState(channelID string) (TerminalViewerState, error) { + m.mu.Lock() + defer m.mu.Unlock() + _, exists := m.channelToPane[channelID] + viewer := m.viewerByChannel[channelID] + if !exists { + return TerminalViewerState{}, fmt.Errorf("channel %s not found", channelID) + } + if viewer == nil || viewer.bridge == nil { + return TerminalViewerState{}, fmt.Errorf("channel %s does not use a grouped viewer session", channelID) + } + return viewer.bridge.State() +} + +// FocusPane applies pane selection and zoom as one serialized viewer intent, +// then returns the state read back from tmux. Callers should not treat the +// request as successful until this method returns the requested state. +func (m *TerminalManager) FocusPane(channelID, paneID string, zoom bool) (TerminalViewerState, error) { + m.mu.Lock() + defer m.mu.Unlock() + _, exists := m.channelToPane[channelID] + viewer := m.viewerByChannel[channelID] + if !exists { + return TerminalViewerState{}, fmt.Errorf("channel %s not found", channelID) + } + if viewer == nil || viewer.bridge == nil { + return TerminalViewerState{}, fmt.Errorf("channel %s does not use a grouped viewer session", channelID) + } + if strings.TrimSpace(paneID) == "" { + return TerminalViewerState{}, fmt.Errorf("pane id is required") + } + previous, err := viewer.bridge.State() + if err != nil { + return TerminalViewerState{}, fmt.Errorf("read viewer state before pane focus: %w", err) + } + if previous.Zoomed { + if err := viewer.bridge.SetZoom(false); err != nil { + return previous, fmt.Errorf("unzoom viewer before pane focus: %w", err) + } + viewer.zoomApplied = false + } + if err := viewer.bridge.SelectPane(paneID); err != nil { + return m.restoreViewerFocusLocked(viewer, previous, err) + } + if err := viewer.bridge.SetZoom(zoom); err != nil { + return m.restoreViewerFocusLocked(viewer, previous, err) + } + viewer.zoomApplied = zoom + state, err := viewer.bridge.State() + if err != nil { + return m.restoreViewerFocusLocked(viewer, previous, err) + } + if state.PaneID != paneID || state.Zoomed != zoom { + return m.restoreViewerFocusLocked(viewer, previous, fmt.Errorf( + "viewer state did not converge: pane=%s zoomed=%t, want pane=%s zoomed=%t", + state.PaneID, + state.Zoomed, + paneID, + zoom, + )) + } + return state, nil +} + +func (m *TerminalManager) restoreViewerFocusLocked( + viewer *terminalViewer, + previous TerminalViewerState, + cause error, +) (TerminalViewerState, error) { + var rollbackErrors []error + if err := viewer.bridge.SelectPane(previous.PaneID); err != nil { + rollbackErrors = append(rollbackErrors, fmt.Errorf("restore pane: %w", err)) + } + if err := viewer.bridge.SetZoom(previous.Zoomed); err != nil { + rollbackErrors = append(rollbackErrors, fmt.Errorf("restore zoom: %w", err)) + } else { + viewer.zoomApplied = previous.Zoomed + } + state, err := viewer.bridge.State() + if err != nil { + rollbackErrors = append(rollbackErrors, fmt.Errorf("verify restored viewer: %w", err)) + } else if state.PaneID != previous.PaneID || state.Zoomed != previous.Zoomed { + rollbackErrors = append(rollbackErrors, fmt.Errorf( + "restored viewer state did not converge: pane=%s zoomed=%t, want pane=%s zoomed=%t", + state.PaneID, + state.Zoomed, + previous.PaneID, + previous.Zoomed, + )) + } + if len(rollbackErrors) > 0 { + return state, fmt.Errorf("%w; viewer rollback failed: %v", cause, errors.Join(rollbackErrors...)) + } + return state, fmt.Errorf("%w; previous viewer state restored", cause) +} + func (m *TerminalManager) navigateScrollLocked(bridge *viewerPTYBridge, lines int) error { if lines > maxTerminalScrollLines { lines = maxTerminalScrollLines diff --git a/agents/agentd/internal/tmux/viewer_pty.go b/agents/agentd/internal/tmux/viewer_pty.go index 1aeafc2..3c12424 100644 --- a/agents/agentd/internal/tmux/viewer_pty.go +++ b/agents/agentd/internal/tmux/viewer_pty.go @@ -389,6 +389,40 @@ func (b *viewerPTYBridge) SetZoom(on bool) error { return nil } +func (b *viewerPTYBridge) State() (TerminalViewerState, error) { + b.mu.Lock() + defer b.mu.Unlock() + select { + case <-b.closed: + return TerminalViewerState{}, fmt.Errorf("viewer PTY is closed") + default: + } + + output, err := b.runner.Output( + "display-message", + "-p", + "-t", + b.viewSession, + "#{pane_id}\t#{window_index}\t#{window_zoomed_flag}", + ) + if err != nil { + return TerminalViewerState{}, fmt.Errorf("read viewer state: %w", err) + } + parts := strings.Split(strings.TrimSpace(string(output)), "\t") + if len(parts) != 3 || parts[0] == "" { + return TerminalViewerState{}, fmt.Errorf("unexpected viewer state %q", strings.TrimSpace(string(output))) + } + windowIndex, err := strconv.Atoi(parts[1]) + if err != nil || windowIndex < 0 { + return TerminalViewerState{}, fmt.Errorf("unexpected viewer window index %q", parts[1]) + } + return TerminalViewerState{ + PaneID: parts[0], + WindowIndex: windowIndex, + Zoomed: parts[2] == "1", + }, nil +} + func (b *viewerPTYBridge) DetachChannel(channelID string) { if b.fanout != nil { b.fanout.Detach(channelID) diff --git a/agents/agentd/internal/ws/protocol_fixtures_test.go b/agents/agentd/internal/ws/protocol_fixtures_test.go index 8e0d3d6..9f89947 100644 --- a/agents/agentd/internal/ws/protocol_fixtures_test.go +++ b/agents/agentd/internal/ws/protocol_fixtures_test.go @@ -73,6 +73,7 @@ func TestProtocolFixtureMatrixRoundTripsProductionTypes(t *testing.T) { protocol.TypeTerminalAttach, protocol.TypeTerminalInput, protocol.TypeTerminalResize, protocol.TypeTerminalNavigate, protocol.TypeTerminalDetach, protocol.TypeTerminalControl, protocol.TypeTerminalOutput, + protocol.TypeTerminalNavigationResult, protocol.TypeTerminalAttached, protocol.TypeTerminalDetached, protocol.TypeTerminalError, protocol.TypeTerminalReadOnly, protocol.TypeTerminalLag, protocol.TypeTerminalAudit, protocol.TypeTmuxTopology, @@ -158,6 +159,8 @@ func fixtureMessageTarget(t *testing.T, messageType string, agentMessage bool) a return &protocol.ServerMessage[protocol.TerminalChannelPayload]{} case protocol.TypeTerminalOutput: return &protocol.AgentMessage[protocol.TerminalOutputPayload]{} + case protocol.TypeTerminalNavigationResult: + return &protocol.AgentMessage[protocol.TerminalNavigationResultPayload]{} case protocol.TypeTerminalAudit: return &protocol.AgentMessage[protocol.TerminalAuditPayload]{} case protocol.TypeTmuxTopology: diff --git a/apps/dashboard/src/components/TerminalView.tsx b/apps/dashboard/src/components/TerminalView.tsx index cf4ba25..c755920 100644 --- a/apps/dashboard/src/components/TerminalView.tsx +++ b/apps/dashboard/src/components/TerminalView.tsx @@ -36,6 +36,8 @@ interface TerminalViewProps { tmuxSessionKey?: string; className?: string; autoAttach?: boolean; + preferLocalChat?: boolean; + interactionBlocked?: boolean; controllerRef?: MutableRefObject; onControllerChange?: (controller: TerminalController | null) => void; onTerminalInstanceChange?: (terminal: XTerminal | null) => void; @@ -53,6 +55,8 @@ export function TerminalView({ tmuxSessionKey, className, autoAttach = false, + preferLocalChat = false, + interactionBlocked = false, controllerRef, onControllerChange, onTerminalInstanceChange = noopTerminalInstanceChange, @@ -67,6 +71,10 @@ export function TerminalView({ const [searchOpen, setSearchOpen] = useState(false); const [historyOpen, setHistoryOpen] = useState(false); const [historyOverlaySessionId, setHistoryOverlaySessionId] = useState(null); + const [chatRefreshToken, setChatRefreshToken] = useState(0); + const chatRefreshTimerRef = useRef(null); + const preferLocalChatRef = useRef(preferLocalChat); + preferLocalChatRef.current = preferLocalChat; const [, setScrollModeCacheVersion] = useState(0); const [stickyCtrlMode, setStickyCtrlMode] = useState('inactive'); const [keyboardActive, setKeyboardActive] = useState(false); @@ -87,6 +95,11 @@ export function TerminalView({ const touchInputModeEnabled = useIsMobile(COMMAND_CENTER_SHELL_BREAKPOINT); const terminalFontSize = useSettingsStore((state) => state.terminalFontSize); const setTerminalFontSize = useSettingsStore((state) => state.setTerminalFontSize); + const storedPresentation = useSettingsStore( + (state) => state.terminalPresentationBySession[historySessionId] + ); + const setTerminalPresentation = useSettingsStore((state) => state.setTerminalPresentation); + const terminalPresentation = storedPresentation ?? (preferLocalChat ? 'chat' : 'terminal'); const tmuxPrefix = useSettingsStore((state) => hostId ? state.tmuxPrefixByHost[hostId] : undefined ); @@ -133,6 +146,13 @@ export function TerminalView({ (terminal: XTerminal, data: string | Uint8Array) => { handleScrollOutputWritten(terminal); handleCommandMarksOutput(terminal, data); + if (preferLocalChatRef.current) { + if (chatRefreshTimerRef.current !== null) window.clearTimeout(chatRefreshTimerRef.current); + chatRefreshTimerRef.current = window.setTimeout(() => { + chatRefreshTimerRef.current = null; + setChatRefreshToken((token) => token + 1); + }, 750); + } }, [handleCommandMarksOutput, handleScrollOutputWritten] ); @@ -214,11 +234,13 @@ export function TerminalView({ errorMessage, lagMessage, readOnly, + reconcilingViewer, connect, disconnect, suspend, takeControl, navigate, + focusPane, sendInput, } = useTerminalConnection({ sessionId, @@ -232,7 +254,9 @@ export function TerminalView({ getDimensions, onOutputStart: handleOutputStart, onOutputWritten: handleTerminalOutputWritten, + interactionBlocked, }); + const effectiveInteractionBlocked = interactionBlocked || reconcilingViewer; const terminalWritable = status === 'connected' && !readOnly; controllerReadOnlyRef.current = readOnly; const cacheScrollMode = useCallback((targetSessionId: string, mode: TerminalScrollMode) => { @@ -335,12 +359,20 @@ export function TerminalView({ resetTouchModes(); setHistoryOverlaySessionId(null); }, [resetTouchModes, status]); - const closeHistoryOverlay = useCallback(() => setHistoryOverlaySessionId(null), []); + const closeHistoryOverlay = useCallback(() => { + setHistoryOverlaySessionId(null); + if (preferLocalChat) setTerminalPresentation(historySessionId, 'terminal'); + }, [historySessionId, preferLocalChat, setTerminalPresentation]); const openHistoryOverlay = useCallback(() => { if (!tmuxSessionKey || !historySessionId) return; + if (preferLocalChat) setTerminalPresentation(historySessionId, 'chat'); setHistoryOverlaySessionId(historySessionId); - }, [historySessionId, tmuxSessionKey]); + }, [historySessionId, preferLocalChat, setTerminalPresentation, tmuxSessionKey]); const historyOverlayOpen = historyOverlaySessionId === historySessionId; + useEffect(() => { + if (!preferLocalChat || terminalPresentation !== 'chat' || status !== 'connected') return; + setHistoryOverlaySessionId(historySessionId); + }, [historySessionId, preferLocalChat, status, terminalPresentation]); useEffect(() => { if (historyOverlaySessionId && historyOverlaySessionId !== historySessionId) { setHistoryOverlaySessionId(null); @@ -402,6 +434,7 @@ export function TerminalView({ suspend, takeControl, navigate, + focusPane, resetTouchModes, focus: () => terminalRef.current?.focus(), copySelection, @@ -432,6 +465,7 @@ export function TerminalView({ disconnect, onControllerChange, navigate, + focusPane, paste, resetTouchModes, terminalRef, @@ -451,6 +485,10 @@ export function TerminalView({ useEffect(() => { const touchState = touchScrollRef.current; return () => { + if (chatRefreshTimerRef.current !== null) { + window.clearTimeout(chatRefreshTimerRef.current); + chatRefreshTimerRef.current = null; + } if (touchState.momentumRaf !== null) { cancelAnimationFrame(touchState.momentumRaf); touchState.momentumRaf = null; @@ -472,7 +510,11 @@ export function TerminalView({ return (
diff --git a/apps/dashboard/src/components/terminal/PersistentTerminalHost.tsx b/apps/dashboard/src/components/terminal/PersistentTerminalHost.tsx index ff56123..89f01e8 100644 --- a/apps/dashboard/src/components/terminal/PersistentTerminalHost.tsx +++ b/apps/dashboard/src/components/terminal/PersistentTerminalHost.tsx @@ -44,6 +44,7 @@ export function PersistentTerminalSlot({ tmuxSessionKey, autoAttach, letterbox, + preferLocalChat, className, controllerRef, }: PersistentTerminalSlotProps) { @@ -56,7 +57,15 @@ export function PersistentTerminalSlot({ const unregister = terminalHostStore.registerSurface({ id, - descriptor: { sessionId, hostId, paneId, tmuxSessionKey, autoAttach, letterbox }, + descriptor: { + sessionId, + hostId, + paneId, + tmuxSessionKey, + autoAttach, + letterbox, + preferLocalChat, + }, target, visible: isSurfaceVisible(target), controllerRef, @@ -70,7 +79,7 @@ export function PersistentTerminalSlot({ resizeObserver.disconnect(); unregister(); }; - }, [autoAttach, controllerRef, hostId, id, letterbox, paneId, sessionId, tmuxSessionKey]); + }, [autoAttach, controllerRef, hostId, id, letterbox, paneId, preferLocalChat, sessionId, tmuxSessionKey]); return (
diff --git a/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.test.ts b/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.test.ts new file mode 100644 index 0000000..7843c8e --- /dev/null +++ b/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from 'vitest'; +import { mergeLatestChatPage, type ChatPage } from './TerminalHistoryOverlay'; + +function page(firstEntry: number, messages: string[], totalEntries: number): ChatPage { + return { + type: 'chat', + firstEntry, + totalEntries, + entries: messages.map((content) => ({ message: { role: 'assistant', content } })), + }; +} + +describe('live Claude chat pages', () => { + it('replaces the overlapping tail while preserving older pages exactly once', () => { + const older = page(0, ['old 0', 'old 1'], 4); + const previousTail = page(2, ['old 2', 'old 3'], 4); + const latestTail = page(2, ['old 2', 'old 3', 'new 4'], 5); + + expect(mergeLatestChatPage([older, previousTail], latestTail)).toEqual([ + page(0, ['old 0', 'old 1'], 5), + latestTail, + ]); + }); + + it('trims an overlapping older page before appending the refreshed tail', () => { + const overlap = page(0, ['old 0', 'old 1', 'old 2'], 3); + const latestTail = page(2, ['old 2', 'new 3'], 4); + + expect(mergeLatestChatPage([overlap], latestTail)).toEqual([ + page(0, ['old 0', 'old 1'], 4), + latestTail, + ]); + }); +}); diff --git a/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx b/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx index 02c593e..81f1041 100644 --- a/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx +++ b/apps/dashboard/src/components/terminal/TerminalHistoryOverlay.tsx @@ -24,6 +24,8 @@ interface TerminalHistoryOverlayProps { sessionId: string; open: boolean; fontSize: number; + preferChat?: boolean; + refreshToken?: number; onScrollModeResolved: (mode: TerminalScrollMode) => void; onClose: () => void; } @@ -34,7 +36,7 @@ interface HistoryPage { lines: string[]; } -interface ChatPage { +export interface ChatPage { type: 'chat'; entries: TranscriptEntry[]; firstEntry: number; @@ -46,6 +48,20 @@ const TRANSCRIPT_PAGE_ENTRIES = 200; type OverlayPage = HistoryPage | ChatPage; +export function mergeLatestChatPage(pages: OverlayPage[], latest: ChatPage): OverlayPage[] { + const preserved = pages.flatMap((page): OverlayPage[] => { + if (page.type !== 'chat') return [page]; + const keepCount = Math.max(0, Math.min(page.entries.length, latest.firstEntry - page.firstEntry)); + if (keepCount === 0) return []; + return [{ + ...page, + entries: page.entries.slice(0, keepCount), + totalEntries: latest.totalEntries, + }]; + }); + return [...preserved, latest]; +} + interface OverlayLine { key: string; text: string; @@ -56,6 +72,8 @@ export function TerminalHistoryOverlay({ sessionId, open, fontSize, + preferChat = false, + refreshToken = 0, onScrollModeResolved, onClose, }: TerminalHistoryOverlayProps) { @@ -65,6 +83,7 @@ export function TerminalHistoryOverlay({ const [loadingOlder, setLoadingOlder] = useState(false); const [hasOlder, setHasOlder] = useState(true); const [error, setError] = useState(null); + const [unreadEntries, setUnreadEntries] = useState(0); const [scrollTop, setScrollTop] = useState(0); const [viewportHeight, setViewportHeight] = useState(0); const [viewportWidth, setViewportWidth] = useState(0); @@ -72,6 +91,8 @@ export function TerminalHistoryOverlay({ const generationRef = useRef(0); const loadingOlderRef = useRef(false); const overscrollStartRef = useRef<{ y: number; atBottom: boolean } | null>(null); + const lastRefreshTokenRef = useRef(refreshToken); + const followLatestRef = useRef(true); const lineHeight = Math.max(16, Math.round(fontSize * 1.2)); const fetchHistoryPage = useCallback( @@ -124,26 +145,58 @@ export function TerminalHistoryOverlay({ setPages([]); setMode(null); setHasOlder(true); + setUnreadEntries(0); + followLatestRef.current = true; setScrollTop(0); + const showChat = (chatPage: ChatPage) => { + followLatestRef.current = true; + setMode('chat'); + setPages([chatPage]); + setHasOlder(chatPage.firstEntry > 0); + onScrollModeResolved('chat'); + requestAnimationFrame(() => { + const element = scrollRef.current; + if (!element || generationRef.current !== generation) return; + element.scrollTop = element.scrollHeight; + setScrollTop(element.scrollTop); + setViewportHeight(element.clientHeight); + setViewportWidth(element.clientWidth); + }); + }; try { + let chatAttempted = false; + if (preferChat) { + chatAttempted = true; + try { + const chatPage = await fetchChatPage(); + if (generationRef.current !== generation) return; + showChat(chatPage); + return; + } catch (chatError) { + if (generationRef.current !== generation) return; + setMode('chat'); + setHasOlder(false); + onScrollModeResolved('chat'); + setError( + chatError instanceof Error + ? `Claude chat is unavailable: ${chatError.message}` + : 'Claude chat is unavailable.' + ); + return; + } + } const { page, scrollMode } = await fetchHistoryPage(initialScrollbackRange()); if (generationRef.current !== generation) return; if (scrollMode === 'app-scroll') { + if (chatAttempted) { + onScrollModeResolved('app-scroll'); + onClose(); + return; + } try { const chatPage = await fetchChatPage(); if (generationRef.current !== generation) return; - setMode('chat'); - setPages([chatPage]); - setHasOlder(chatPage.firstEntry > 0); - onScrollModeResolved('chat'); - requestAnimationFrame(() => { - const element = scrollRef.current; - if (!element || generationRef.current !== generation) return; - element.scrollTop = element.scrollHeight; - setScrollTop(element.scrollTop); - setViewportHeight(element.clientHeight); - setViewportWidth(element.clientWidth); - }); + showChat(chatPage); } catch { if (generationRef.current !== generation) return; onScrollModeResolved('app-scroll'); @@ -171,7 +224,45 @@ export function TerminalHistoryOverlay({ } finally { if (generationRef.current === generation) setLoadingInitial(false); } - }, [fetchChatPage, fetchHistoryPage, onClose, onScrollModeResolved]); + }, [fetchChatPage, fetchHistoryPage, onClose, onScrollModeResolved, preferChat]); + + const refreshLatestChat = useCallback(async () => { + const generation = generationRef.current; + const element = scrollRef.current; + const wasFollowing = !element + || element.scrollHeight - element.clientHeight - element.scrollTop <= lineHeight * 2; + followLatestRef.current = wasFollowing; + const previousTotal = pages.reduce((total, page) => ( + page.type === 'chat' ? Math.max(total, page.totalEntries) : total + ), 0); + try { + const latest = await fetchChatPage(); + if (generationRef.current !== generation) return; + const added = Math.max(0, latest.totalEntries - previousTotal); + setPages((current) => mergeLatestChatPage(current, latest)); + setHasOlder((current) => current || latest.firstEntry > 0); + setError(null); + requestAnimationFrame(() => { + if (!element || generationRef.current !== generation) return; + if (wasFollowing) { + element.scrollTop = element.scrollHeight; + setScrollTop(element.scrollTop); + setUnreadEntries(0); + } else if (added > 0) { + setUnreadEntries((current) => current + added); + } + setViewportHeight(element.clientHeight); + setViewportWidth(element.clientWidth); + }); + } catch (refreshError) { + if (generationRef.current !== generation) return; + setError( + refreshError instanceof Error + ? `Claude chat could not refresh: ${refreshError.message}` + : 'Claude chat could not refresh.' + ); + } + }, [fetchChatPage, lineHeight, pages]); useEffect(() => { if (!open) { @@ -184,6 +275,16 @@ export function TerminalHistoryOverlay({ void loadInitial(); }, [loadInitial, open]); + useEffect(() => { + if (!open) lastRefreshTokenRef.current = refreshToken; + }, [open, refreshToken]); + + useEffect(() => { + if (!open || mode !== 'chat' || refreshToken === lastRefreshTokenRef.current) return; + lastRefreshTokenRef.current = refreshToken; + void refreshLatestChat(); + }, [mode, open, refreshLatestChat, refreshToken]); + useEffect(() => { if (!open) return; const element = scrollRef.current; @@ -203,6 +304,7 @@ export function TerminalHistoryOverlay({ const generation = generationRef.current; const element = scrollRef.current; const previousHeight = element?.scrollHeight ?? 0; + followLatestRef.current = false; loadingOlderRef.current = true; setLoadingOlder(true); setError(null); @@ -284,6 +386,19 @@ export function TerminalHistoryOverlay({ }); const visibleLines = allLines.slice(virtualWindow.startIndex, virtualWindow.endIndex); + useEffect(() => { + if (!open || mode !== 'chat' || !followLatestRef.current) return; + const frame = requestAnimationFrame(() => { + const element = scrollRef.current; + if (!element || !followLatestRef.current) return; + element.scrollTop = element.scrollHeight; + setScrollTop(element.scrollTop); + setViewportHeight(element.clientHeight); + setViewportWidth(element.clientWidth); + }); + return () => cancelAnimationFrame(frame); + }, [allLines.length, mode, open]); + if (!open) return null; return ( @@ -303,17 +418,37 @@ export function TerminalHistoryOverlay({ ? mode === 'chat' ? 'Chat' : 'History' : mode === 'chat' ? 'Start of chat' : 'Start of history'}
- +
+ {unreadEntries > 0 && ( + + )} + +
{error && ( @@ -343,6 +478,9 @@ export function TerminalHistoryOverlay({ aria-label="Inline terminal history" onScroll={(event) => { const element = event.currentTarget; + followLatestRef.current = element.scrollHeight + - element.clientHeight + - element.scrollTop <= lineHeight * 2; setScrollTop(element.scrollTop); setViewportHeight(element.clientHeight); setViewportWidth(element.clientWidth); @@ -379,7 +517,7 @@ export function TerminalHistoryOverlay({ role="status" >