diff --git a/agents/agentd/cmd/agentd/main.go b/agents/agentd/cmd/agentd/main.go index 9a939134..bad269fc 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 8c01013f..d9a38fa9 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 80f50b4c..84a230ee 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 5e8bc205..5c99ffc4 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 f960b55c..50fedba4 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 6b82b606..5f44f209 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 1aeafc22..3c124249 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 8e0d3d65..9f899477 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 cf4ba25a..c7559205 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 ff561236..89f01e89 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 00000000..7843c8ee --- /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 02c593e5..81f10410 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" >