diff --git a/components/Terminal.tsx b/components/Terminal.tsx index 10757cab1..ab73f8668 100644 --- a/components/Terminal.tsx +++ b/components/Terminal.tsx @@ -25,6 +25,13 @@ import { type TerminalHostUpdate, } from "../domain/terminalAppearance"; import { resolveRestoreCwdIntent } from "../domain/sessionRestore"; +import { + buildTerminalContextReadResult, + buildTerminalContextSnapshotText, + normalizeTerminalContextRange, + resolveTerminalContextLineWindow, + type TerminalContextReader, +} from "../domain/terminalContextRead"; import { classifyDistroId, shouldProbeSessionCwd } from "../domain/host"; import { supportsZmodemTerminalDragDrop } from "../lib/zmodemDragDrop"; import { resolveHostAuth } from "../domain/sshAuth"; @@ -89,6 +96,7 @@ import { import { createTerminalCwdTracker, resolvePreferredTerminalCwd } from "./terminal/sftpCwd"; import { useTerminalEffects } from "./terminal/useTerminalEffects"; import { useTerminalHibernateEffect } from "./terminal/useTerminalHibernateEffect"; +import { readActiveTerminalBufferTextRange } from "./terminal/terminalContextBuffer"; import { appendHibernatePendingBuffer, isTerminalAlternateScreenActive, @@ -194,6 +202,7 @@ const TerminalComponent: React.FC = ({ onTerminalTitleChange, onTerminalBell, onTerminalOutput, + onTerminalContextReaderChange, onOpenScripts, onOpenHistory, onOpenTheme, @@ -245,6 +254,9 @@ const TerminalComponent: React.FC = ({ const hibernateSnapshotRef = useRef(""); const hibernateViewportSnapshotRef = useRef(""); const hibernateScrollbackSnapshotRef = useRef(""); + const hibernateContextSnapshotRef = useRef(""); + const hibernateContextViewportSnapshotRef = useRef(""); + const hibernateContextScrollbackSnapshotRef = useRef(""); const hibernatePendingBufferRef = useRef(""); const hibernateAlternateScreenRef = useRef(false); const wakeInProgressRef = useRef(false); @@ -305,6 +317,90 @@ const TerminalComponent: React.FC = ({ return connectionLogBufferRef.current.toString(); }, []); + const readTerminalContext = useCallback(async (request) => { + if (request.sessionId !== sessionId) { + return { ok: false, error: `Terminal context reader is registered for "${sessionId}", not "${request.sessionId}".` }; + } + + const range = normalizeTerminalContextRange(request.range); + const term = termRef.current; + if (term) { + const alternateScreen = isTerminalAlternateScreenActive(term); + const activeBuffer = term.buffer.active as typeof term.buffer.active & { + viewportY?: number; + }; + const totalLines = Math.max(0, activeBuffer.length); + const viewportStartLine = alternateScreen + ? 0 + : Math.max(0, activeBuffer.viewportY ?? Math.max(0, totalLines - term.rows)); + const viewportEndLine = totalLines > 0 + ? Math.min(totalLines - 1, viewportStartLine + Math.max(1, term.rows) - 1) + : -1; + const lineWindow = resolveTerminalContextLineWindow({ + range, + totalLines, + viewportStartLine, + viewportEndLine, + startLine: request.startLine, + maxLines: request.maxLines, + }); + let content = ''; + if (lineWindow.endLine >= lineWindow.startLine) { + content = readActiveTerminalBufferTextRange(term, { + startLine: lineWindow.startLine, + endLine: lineWindow.endLine, + }); + } + + return { + ok: true, + sessionId, + label: sessionDisplayName ?? host.label, + range, + content, + totalLines, + startLine: lineWindow.startLine, + endLine: lineWindow.endLine, + returnedLines: lineWindow.endLine >= lineWindow.startLine + ? lineWindow.endLine - lineWindow.startLine + 1 + : 0, + hasMoreBefore: lineWindow.startLine > 0, + hasMoreAfter: lineWindow.endLine >= 0 && lineWindow.endLine < totalLines - 1, + source: 'live', + alternateScreen, + }; + } + + const snapshot = buildTerminalContextSnapshotText({ + scrollbackText: hibernateContextScrollbackSnapshotRef.current, + viewportText: hibernateContextViewportSnapshotRef.current, + pendingText: hibernatePendingBufferRef.current, + }); + const fullText = snapshot.fullText || hibernateContextSnapshotRef.current; + + if (!fullText) { + return { ok: false, error: `Terminal session "${sessionId}" has no readable terminal buffer yet.` }; + } + + return buildTerminalContextReadResult({ + sessionId, + label: sessionDisplayName ?? host.label, + fullText, + range, + startLine: request.startLine, + maxLines: request.maxLines, + source: 'snapshot', + alternateScreen: hibernateAlternateScreenRef.current, + viewportStartLine: snapshot.viewportStartLine, + viewportEndLine: snapshot.viewportEndLine, + }); + }, [host.label, sessionDisplayName, sessionId]); + + useEffect(() => { + onTerminalContextReaderChange?.(sessionId, readTerminalContext); + return () => onTerminalContextReaderChange?.(sessionId, null); + }, [onTerminalContextReaderChange, readTerminalContext, sessionId]); + useEffect(() => { commandLogRewriterRef.current = createProgrammaticCommandLogRewriter(); }, [sessionId]); @@ -856,6 +952,9 @@ const TerminalComponent: React.FC = ({ hibernateSnapshotRef.current = ""; hibernateViewportSnapshotRef.current = ""; hibernateScrollbackSnapshotRef.current = ""; + hibernateContextSnapshotRef.current = ""; + hibernateContextViewportSnapshotRef.current = ""; + hibernateContextScrollbackSnapshotRef.current = ""; hibernatePendingBufferRef.current = ""; hibernateAlternateScreenRef.current = false; terminalHiddenRendererStore.clearSoftHidden(sessionId); @@ -894,12 +993,18 @@ const TerminalComponent: React.FC = ({ snapshot: string; viewportSnapshot: string; scrollbackSnapshot: string; + contextSnapshot?: string; + contextViewportSnapshot?: string; + contextScrollbackSnapshot?: string; alternateScreen: boolean; }, ) => { hibernateSnapshotRef.current = snapshot.snapshot; hibernateViewportSnapshotRef.current = snapshot.viewportSnapshot; hibernateScrollbackSnapshotRef.current = snapshot.scrollbackSnapshot; + hibernateContextSnapshotRef.current = snapshot.contextSnapshot ?? ""; + hibernateContextViewportSnapshotRef.current = snapshot.contextViewportSnapshot ?? ""; + hibernateContextScrollbackSnapshotRef.current = snapshot.contextScrollbackSnapshot ?? ""; hibernateAlternateScreenRef.current = snapshot.alternateScreen; }, []); @@ -1874,6 +1979,9 @@ const TerminalComponent: React.FC = ({ hibernateSnapshotRef, hibernateViewportSnapshotRef, hibernateScrollbackSnapshotRef, + hibernateContextSnapshotRef, + hibernateContextViewportSnapshotRef, + hibernateContextScrollbackSnapshotRef, hibernateAlternateScreenRef, hasRuntimeRef, onHibernate: hibernateRuntime, diff --git a/components/ai/ChatMessageList.tsx b/components/ai/ChatMessageList.tsx index 75a009fc4..25cf5b0c8 100644 --- a/components/ai/ChatMessageList.tsx +++ b/components/ai/ChatMessageList.tsx @@ -23,6 +23,8 @@ import ToolCallGroup from './ToolCallGroup'; import { VaultArtifactNavigationProvider, } from './toolArtifacts/VaultArtifactNavigationContext'; +import { parseTerminalToolArtifact } from './toolArtifacts/terminalToolArtifact'; +import { TerminalArtifactToolResult } from './toolArtifacts/TerminalArtifactToolResult'; import { parseVaultToolArtifact } from './toolArtifacts/vaultToolArtifact'; import { VaultArtifactToolResult } from './toolArtifacts/VaultArtifactToolResult'; import type { Host, VaultNote } from '../../types'; @@ -268,6 +270,19 @@ const ChatMessageList: React.FC = ({ && displayedMessages[end].role === "assistant"; const renderToolResultItem = (item: typeof toolResults[number]) => { + const terminalArtifact = parseTerminalToolArtifact(item.name, item.content); + if (terminalArtifact) { + return ( + + ); + } const artifact = parseVaultToolArtifact(item.name, item.content); if (artifact) { return ( diff --git a/components/ai/toolArtifacts/TerminalArtifactCard.test.tsx b/components/ai/toolArtifacts/TerminalArtifactCard.test.tsx new file mode 100644 index 000000000..af4aa54ec --- /dev/null +++ b/components/ai/toolArtifacts/TerminalArtifactCard.test.tsx @@ -0,0 +1,45 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import React from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; + +import { TerminalArtifactCard } from './TerminalArtifactCard.tsx'; + +test('TerminalArtifactCard renders terminal context summary', () => { + const html = renderToStaticMarkup( + , + ); + + assert.match(html, /prod/); + assert.match(html, /lines 101-103 \/ 120/); + assert.doesNotMatch(html, /alpha/); +}); + +test('TerminalArtifactCard renders terminal read errors', () => { + const html = renderToStaticMarkup( + , + ); + + assert.match(html, /Terminal read failed/); + assert.match(html, /Terminal context reader is unavailable/); +}); diff --git a/components/ai/toolArtifacts/TerminalArtifactCard.tsx b/components/ai/toolArtifacts/TerminalArtifactCard.tsx new file mode 100644 index 000000000..0664d227a --- /dev/null +++ b/components/ai/toolArtifacts/TerminalArtifactCard.tsx @@ -0,0 +1,73 @@ +import { AlertCircle, SquareTerminal } from 'lucide-react'; +import React from 'react'; +import { cn } from '../../../lib/utils'; +import type { TerminalToolArtifact } from './terminalToolArtifact'; + +interface TerminalArtifactCardProps { + artifact: TerminalToolArtifact; + className?: string; +} + +function formatLineRange(artifact: Extract): string { + if (artifact.returnedLines === 0) { + return `0 / ${artifact.totalLines} lines`; + } + return `lines ${artifact.startLine + 1}-${artifact.endLine + 1} / ${artifact.totalLines}`; +} + +function formatSubtitle(artifact: Extract): string { + const parts = [ + formatLineRange(artifact), + artifact.source, + artifact.hasMoreBefore || artifact.hasMoreAfter ? 'more available' : null, + ].filter(Boolean); + return parts.join(' | '); +} + +export const TerminalArtifactCard = React.forwardRef(({ + artifact, + className, +}, ref) => { + if (artifact.kind === 'error') { + return ( +
+
+ +
+
+
+ Terminal read failed +
+
+ {artifact.message} +
+
+
+ ); + } + + const title = artifact.label || artifact.sessionId; + + return ( +
+
+ +
+
+
+ {title} +
+
+ {formatSubtitle(artifact)} +
+
+
+ ); +}); +TerminalArtifactCard.displayName = 'TerminalArtifactCard'; diff --git a/components/ai/toolArtifacts/TerminalArtifactToolResult.tsx b/components/ai/toolArtifacts/TerminalArtifactToolResult.tsx new file mode 100644 index 000000000..84c110439 --- /dev/null +++ b/components/ai/toolArtifacts/TerminalArtifactToolResult.tsx @@ -0,0 +1,38 @@ +import React from 'react'; +import { Tooltip, TooltipContent, TooltipTrigger } from '../../ui/tooltip'; +import { formatTerminalToolTooltip } from './formatTerminalToolTooltip'; +import { TerminalArtifactCard } from './TerminalArtifactCard'; +import type { TerminalToolArtifact } from './terminalToolArtifact'; + +interface TerminalArtifactToolResultProps { + artifact: TerminalToolArtifact; + toolName: string; + args?: Record; + result?: unknown; + isError?: boolean; +} + +export const TerminalArtifactToolResult: React.FC = ({ + artifact, + toolName, + args, + result, + isError, +}) => { + const tooltip = formatTerminalToolTooltip(toolName, args, result, isError); + + return ( + + + + + + {tooltip} + + + ); +}; diff --git a/components/ai/toolArtifacts/formatTerminalToolTooltip.ts b/components/ai/toolArtifacts/formatTerminalToolTooltip.ts new file mode 100644 index 000000000..1076428cd --- /dev/null +++ b/components/ai/toolArtifacts/formatTerminalToolTooltip.ts @@ -0,0 +1,25 @@ +function serialize(value: unknown): string { + if (value == null) return ''; + if (typeof value === 'string') return value; + try { + return JSON.stringify(value, null, 2); + } catch { + return String(value); + } +} + +export function formatTerminalToolTooltip( + toolName: string, + args?: Record, + result?: unknown, + isError?: boolean, +): string { + const sections = [ + `Tool: ${toolName}`, + args ? `Args:\n${serialize(args)}` : null, + result ? `Result:\n${serialize(result)}` : null, + isError ? 'Status: error' : null, + ].filter(Boolean); + + return sections.join('\n\n'); +} diff --git a/components/ai/toolArtifacts/terminalToolArtifact.test.ts b/components/ai/toolArtifacts/terminalToolArtifact.test.ts new file mode 100644 index 000000000..b3183b765 --- /dev/null +++ b/components/ai/toolArtifacts/terminalToolArtifact.test.ts @@ -0,0 +1,48 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { parseTerminalToolArtifact } from './terminalToolArtifact.ts'; + +test('parseTerminalToolArtifact maps terminal context reads', () => { + const artifact = parseTerminalToolArtifact('terminal_read_context', { + ok: true, + sessionId: 'session-1', + label: 'prod', + range: 'tail', + content: 'alpha\nbeta\ngamma', + totalLines: 120, + startLine: 100, + endLine: 102, + returnedLines: 3, + hasMoreBefore: true, + hasMoreAfter: true, + source: 'live', + }); + + assert.deepEqual(artifact, { + kind: 'terminal.context', + sessionId: 'session-1', + label: 'prod', + range: 'tail', + totalLines: 120, + startLine: 100, + endLine: 102, + returnedLines: 3, + hasMoreBefore: true, + hasMoreAfter: true, + source: 'live', + preview: 'alpha\nbeta\ngamma', + }); +}); + +test('parseTerminalToolArtifact maps errors', () => { + const artifact = parseTerminalToolArtifact('terminal_read_context', { + ok: false, + error: 'Terminal session not found.', + }); + + assert.deepEqual(artifact, { + kind: 'error', + message: 'Terminal session not found.', + }); +}); diff --git a/components/ai/toolArtifacts/terminalToolArtifact.ts b/components/ai/toolArtifacts/terminalToolArtifact.ts new file mode 100644 index 000000000..954012ed5 --- /dev/null +++ b/components/ai/toolArtifacts/terminalToolArtifact.ts @@ -0,0 +1,96 @@ +export type TerminalToolArtifact = + | { + kind: 'terminal.context'; + sessionId: string; + label?: string; + range: string; + totalLines: number; + startLine: number; + endLine: number; + returnedLines: number; + hasMoreBefore: boolean; + hasMoreAfter: boolean; + source?: string; + preview: string; + } + | { + kind: 'error'; + message: string; + }; + +const TERMINAL_ARTIFACT_TOOL_NAMES = new Set([ + 'terminal_read_context', +]); + +function parseResultPayload(result: unknown): Record | null { + if (result == null) return null; + if (typeof result === 'string') { + try { + const parsed = JSON.parse(result) as unknown; + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + return parsed as Record; + } + return null; + } catch { + return null; + } + } + if (typeof result === 'object' && !Array.isArray(result)) { + return result as Record; + } + return null; +} + +function readString(value: unknown): string | undefined { + return typeof value === 'string' && value.trim() ? value.trim() : undefined; +} + +function readNumber(value: unknown): number | undefined { + return typeof value === 'number' && Number.isFinite(value) ? value : undefined; +} + +function readBoolean(value: unknown): boolean { + return value === true; +} + +export function parseTerminalToolArtifact( + toolName: string, + result: unknown, +): TerminalToolArtifact | null { + if (!TERMINAL_ARTIFACT_TOOL_NAMES.has(toolName)) return null; + + const payload = parseResultPayload(result); + if (!payload) return null; + + if (payload.ok === false || payload.isError === true || typeof payload.error === 'string') { + return { + kind: 'error', + message: readString(payload.error) ?? 'Terminal context read failed.', + }; + } + + const sessionId = readString(payload.sessionId); + const content = typeof payload.content === 'string' ? payload.content : ''; + const totalLines = readNumber(payload.totalLines); + const startLine = readNumber(payload.startLine); + const endLine = readNumber(payload.endLine); + const returnedLines = readNumber(payload.returnedLines); + if (!sessionId || totalLines == null || startLine == null || endLine == null || returnedLines == null) { + return null; + } + + return { + kind: 'terminal.context', + sessionId, + label: readString(payload.label), + range: readString(payload.range) ?? 'viewport', + totalLines, + startLine, + endLine, + returnedLines, + hasMoreBefore: readBoolean(payload.hasMoreBefore), + hasMoreAfter: readBoolean(payload.hasMoreAfter), + source: readString(payload.source), + preview: content.split('\n').slice(0, 6).join('\n'), + }; +} diff --git a/components/terminal/terminalContextBuffer.test.ts b/components/terminal/terminalContextBuffer.test.ts new file mode 100644 index 000000000..15a2818e7 --- /dev/null +++ b/components/terminal/terminalContextBuffer.test.ts @@ -0,0 +1,59 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + readActiveTerminalBufferTextRange, + readTerminalBufferTextRange, +} from "./terminalContextBuffer.ts"; + +function createBuffer(lines: string[]) { + return { + getLine(index: number) { + const value = lines[index]; + if (value === undefined) return undefined; + return { + translateToString(trimRight?: boolean, startColumn = 0, endColumn?: number) { + const sliced = value.slice(startColumn, endColumn); + return trimRight ? sliced.trimEnd() : sliced; + }, + }; + }, + }; +} + +test("readTerminalBufferTextRange returns only the requested rows", () => { + const buffer = createBuffer([ + "normal-history", + "top header", + "cpu 12%", + "mem 44%", + "bottom prompt", + ]); + + assert.equal( + readTerminalBufferTextRange(buffer as never, { + startLine: 1, + endLine: 3, + cols: 80, + }), + "top header\ncpu 12%\nmem 44%", + ); +}); + +test("readActiveTerminalBufferTextRange reads the active alternate buffer without normal scrollback", () => { + const normalBuffer = createBuffer(["old normal scrollback"]); + const alternateBuffer = createBuffer(["vim title", "file body", ":"]); + const term = { + cols: 80, + buffer: { + active: alternateBuffer, + normal: normalBuffer, + alternate: alternateBuffer, + }, + }; + + assert.equal( + readActiveTerminalBufferTextRange(term as never, { startLine: 0, endLine: 2 }), + "vim title\nfile body\n:", + ); +}); diff --git a/components/terminal/terminalContextBuffer.ts b/components/terminal/terminalContextBuffer.ts new file mode 100644 index 000000000..ee45562bd --- /dev/null +++ b/components/terminal/terminalContextBuffer.ts @@ -0,0 +1,42 @@ +import type { IBuffer, Terminal as XTerm } from "@xterm/xterm"; + +export type TerminalTextRange = { + startLine: number; + endLine: number; +}; + +type TerminalBufferTextSource = Pick; + +export function readActiveTerminalBufferTextRange( + term: TerminalBufferTextSource, + range: TerminalTextRange, +): string { + const startLine = Math.max(0, Math.floor(range.startLine)); + const endLine = Math.max(-1, Math.floor(range.endLine)); + if (endLine < startLine) return ""; + + return readTerminalBufferTextRange(term.buffer.active, { + ...range, + cols: term.cols, + }); +} + +export function readTerminalBufferTextRange( + buffer: Pick, + range: TerminalTextRange & { cols?: number }, +): string { + const startLine = Math.max(0, Math.floor(range.startLine)); + const endLine = Math.max(-1, Math.floor(range.endLine)); + if (endLine < startLine) return ""; + + const cols = typeof range.cols === "number" && Number.isFinite(range.cols) + ? Math.max(0, Math.floor(range.cols)) + : undefined; + + const lines: string[] = []; + for (let lineIndex = startLine; lineIndex <= endLine; lineIndex += 1) { + const line = buffer.getLine(lineIndex); + lines.push(line?.translateToString(true, 0, cols) ?? ""); + } + return lines.join("\n"); +} diff --git a/components/terminal/terminalHelpers.ts b/components/terminal/terminalHelpers.ts index 8cde79884..1cc4c7f3e 100644 --- a/components/terminal/terminalHelpers.ts +++ b/components/terminal/terminalHelpers.ts @@ -1,6 +1,7 @@ import type { DragEvent, PointerEvent } from "react"; import { Terminal as XTerm } from "@xterm/xterm"; +import type { TerminalContextReader } from "../../domain/terminalContextRead"; import { getSessionConnectionLabel, resolveSessionTabTitle } from "../../domain/sessionTabTitle"; import { logger } from "../../lib/logger"; import { getPathForFile, type DropEntry } from "../../lib/sftpFileUtils"; @@ -178,6 +179,7 @@ export interface TerminalProps { onTerminalTitleChange?: (sessionId: string, title: string | null) => void; onTerminalBell?: (sessionId: string) => void; onTerminalOutput?: (sessionId: string, chunk: string) => void; + onTerminalContextReaderChange?: (sessionId: string, reader: TerminalContextReader | null) => void; onOpenScripts?: () => void; onOpenHistory?: () => void; onOpenTheme?: () => void; diff --git a/components/terminal/terminalHibernateRuntime.test.ts b/components/terminal/terminalHibernateRuntime.test.ts index 9e32efbf7..baafda697 100644 --- a/components/terminal/terminalHibernateRuntime.test.ts +++ b/components/terminal/terminalHibernateRuntime.test.ts @@ -10,10 +10,16 @@ import { const createFakeTerm = (bufferType: "normal" | "alternate", rows = 24, length = 30) => ({ rows, + cols: 80, buffer: { active: { type: bufferType, length, + getLine(index: number) { + return { + translateToString: () => `screen-${index}`, + }; + }, }, }, }); @@ -67,12 +73,12 @@ test("serializeTerminalForHibernate preserves alternate screen when serialize th throw new Error("serialize failed"); }, }; - assert.deepEqual(await serializeTerminalForHibernate(term as never, serializeAddon as never), { - snapshot: "", - viewportSnapshot: "", - scrollbackSnapshot: "", - alternateScreen: true, - }); + const result = await serializeTerminalForHibernate(term as never, serializeAddon as never); + assert.equal(result.snapshot, ""); + assert.equal(result.viewportSnapshot, ""); + assert.equal(result.scrollbackSnapshot, ""); + assert.equal(result.contextViewportSnapshot?.startsWith("screen-0\nscreen-1"), true); + assert.equal(result.alternateScreen, true); }); test("serializeTerminalForHibernate requests viewport-only range on alternate screen", async () => { @@ -86,5 +92,28 @@ test("serializeTerminalForHibernate requests viewport-only range on alternate sc }; const result = await serializeTerminalForHibernate(term as never, serializeAddon as never); assert.equal(result.snapshot, "alt-viewport"); + assert.equal(result.contextViewportSnapshot, Array.from({ length: 24 }, (_, index) => `screen-${index}`).join("\n")); assert.deepEqual(capturedOptions?.range, { start: 0, end: 23 }); }); + +test("serializeTerminalForHibernate preserves plain text context for normal screen", async () => { + const capturedRanges: unknown[] = []; + const term = createFakeTerm("normal", 3, 5); + const serializeAddon = { + serialize: (options?: Record) => { + capturedRanges.push(options?.range); + return "serialized"; + }, + }; + const result = await serializeTerminalForHibernate(term as never, serializeAddon as never); + assert.equal(result.viewportSnapshot, "serialized"); + assert.equal(result.scrollbackSnapshot, "serialized"); + assert.equal(result.contextScrollbackSnapshot, "screen-0\nscreen-1"); + assert.equal(result.contextViewportSnapshot, "screen-2\nscreen-3\nscreen-4"); + assert.equal(result.contextSnapshot, "screen-0\nscreen-1\nscreen-2\nscreen-3\nscreen-4"); + assert.deepEqual(capturedRanges, [ + { start: 2, end: 4 }, + { start: 0, end: 1 }, + undefined, + ]); +}); diff --git a/components/terminal/terminalHibernateRuntime.ts b/components/terminal/terminalHibernateRuntime.ts index f48d66cd3..3f40c4f5d 100644 --- a/components/terminal/terminalHibernateRuntime.ts +++ b/components/terminal/terminalHibernateRuntime.ts @@ -8,6 +8,7 @@ import { type TerminalHibernateWakePayload, } from "../../domain/terminalHibernate"; import type { XTermRuntime } from "./runtime/createXTermRuntime"; +import { readActiveTerminalBufferTextRange } from "./terminalContextBuffer"; import { serializeTerminalBuffer } from "./terminalSerialize"; import { writeTerminalPayloadChunked, @@ -36,6 +37,9 @@ export type TerminalHibernateSnapshot = { snapshot: string; viewportSnapshot: string; scrollbackSnapshot: string; + contextSnapshot?: string; + contextViewportSnapshot?: string; + contextScrollbackSnapshot?: string; alternateScreen: boolean; }; @@ -82,10 +86,17 @@ export async function serializeTerminalForHibernate( }, preferWasm), rows, ); + const contextViewportSnapshot = readActiveTerminalBufferTextRange(term, { + startLine: 0, + endLine: endRow, + }); return { snapshot: viewportSnapshot, viewportSnapshot, scrollbackSnapshot: "", + contextSnapshot: contextViewportSnapshot, + contextViewportSnapshot, + contextScrollbackSnapshot: "", alternateScreen: true, }; } @@ -97,8 +108,13 @@ export async function serializeTerminalForHibernate( excludeModes, range: { start: viewportStart, end: viewportEnd }, }, preferWasm); + const contextViewportSnapshot = readActiveTerminalBufferTextRange(term, { + startLine: viewportStart, + endLine: viewportEnd, + }); let scrollbackSnapshot = ""; + let contextScrollbackSnapshot = ""; if (viewportStart > 0) { const scrollbackStart = Math.max(0, viewportStart - TERMINAL_HIBERNATE_SNAPSHOT_MAX_LINES); scrollbackSnapshot = capHibernateBufferByLines( @@ -109,6 +125,10 @@ export async function serializeTerminalForHibernate( }, preferWasm), TERMINAL_HIBERNATE_SNAPSHOT_MAX_LINES, ); + contextScrollbackSnapshot = readActiveTerminalBufferTextRange(term, { + startLine: scrollbackStart, + endLine: viewportStart - 1, + }); } const snapshot = capHibernateBufferByLines( @@ -123,6 +143,9 @@ export async function serializeTerminalForHibernate( snapshot, viewportSnapshot, scrollbackSnapshot, + contextSnapshot: [contextScrollbackSnapshot, contextViewportSnapshot].filter(Boolean).join("\n"), + contextViewportSnapshot, + contextScrollbackSnapshot, alternateScreen: false, }; } catch { diff --git a/components/terminal/terminalMemo.test.ts b/components/terminal/terminalMemo.test.ts index 29fe084b3..a9b4659d6 100644 --- a/components/terminal/terminalMemo.test.ts +++ b/components/terminal/terminalMemo.test.ts @@ -30,3 +30,13 @@ test("terminal memo refreshes when restored local shell type changes", () => { false, ); }); + +test("terminal memo refreshes when terminal context reader callback changes", () => { + assert.equal( + terminalPropsAreEqual(baseProps, { + ...baseProps, + onTerminalContextReaderChange: () => {}, + }), + false, + ); +}); diff --git a/components/terminal/terminalMemo.ts b/components/terminal/terminalMemo.ts index a38c1905e..15f70808a 100644 --- a/components/terminal/terminalMemo.ts +++ b/components/terminal/terminalMemo.ts @@ -70,6 +70,7 @@ export const terminalPropsAreEqual = ( && prev.onTerminalTitleChange === next.onTerminalTitleChange && prev.onTerminalBell === next.onTerminalBell && prev.onTerminalOutput === next.onTerminalOutput + && prev.onTerminalContextReaderChange === next.onTerminalContextReaderChange && prev.onOpenScripts === next.onOpenScripts && prev.onOpenHistory === next.onOpenHistory && prev.onOpenTheme === next.onOpenTheme diff --git a/components/terminal/useTerminalHibernateEffect.ts b/components/terminal/useTerminalHibernateEffect.ts index 6e19f4ab4..21f812254 100644 --- a/components/terminal/useTerminalHibernateEffect.ts +++ b/components/terminal/useTerminalHibernateEffect.ts @@ -26,6 +26,9 @@ type UseTerminalHibernateEffectOptions = { hibernateSnapshotRef: React.MutableRefObject; hibernateViewportSnapshotRef: React.MutableRefObject; hibernateScrollbackSnapshotRef: React.MutableRefObject; + hibernateContextSnapshotRef: React.MutableRefObject; + hibernateContextViewportSnapshotRef: React.MutableRefObject; + hibernateContextScrollbackSnapshotRef: React.MutableRefObject; hibernateAlternateScreenRef: React.MutableRefObject; hasRuntimeRef: React.MutableRefObject; onHibernate: () => void; @@ -52,6 +55,9 @@ export function useTerminalHibernateEffect({ hibernateSnapshotRef, hibernateViewportSnapshotRef, hibernateScrollbackSnapshotRef, + hibernateContextSnapshotRef, + hibernateContextViewportSnapshotRef, + hibernateContextScrollbackSnapshotRef, hibernateAlternateScreenRef, hasRuntimeRef, onHibernate, @@ -82,6 +88,9 @@ export function useTerminalHibernateEffect({ hibernateSnapshotRef.current = ""; hibernateViewportSnapshotRef.current = ""; hibernateScrollbackSnapshotRef.current = ""; + hibernateContextSnapshotRef.current = ""; + hibernateContextViewportSnapshotRef.current = ""; + hibernateContextScrollbackSnapshotRef.current = ""; hibernatePendingBufferRef.current = ""; hibernateAlternateScreenRef.current = false; hibernatedRef.current = false; @@ -187,6 +196,9 @@ export function useTerminalHibernateEffect({ hibernateAlternateScreenRef, hibernateDelayMs, hibernateEnabled, + hibernateContextScrollbackSnapshotRef, + hibernateContextSnapshotRef, + hibernateContextViewportSnapshotRef, hibernatePendingBufferRef, hibernateScrollbackSnapshotRef, hibernateSnapshotRef, diff --git a/components/terminalLayer/TerminalLayerSupport.tsx b/components/terminalLayer/TerminalLayerSupport.tsx index 49b5164f6..c29848253 100644 --- a/components/terminalLayer/TerminalLayerSupport.tsx +++ b/components/terminalLayer/TerminalLayerSupport.tsx @@ -19,6 +19,7 @@ import type { ExecutorContext } from '../../infrastructure/ai/cattyAgent/executo import Terminal from '../Terminal'; import { removePaneVisible, setPaneVisible } from '../terminal/paneVisibilityStore'; import type { TerminalBroadcastInputOptions } from '../terminal/terminalHelpers'; +import type { TerminalContextReader } from '../../domain/terminalContextRead'; import { getTerminalPaneRenderSnapshot, parseTerminalPaneRenderSnapshot, @@ -733,6 +734,7 @@ interface TerminalPaneProps { onTerminalTitleChange?: (sessionId: string, title: string | null) => void; onTerminalBell?: (sessionId: string) => void; onTerminalOutput?: (sessionId: string, chunk: string) => void; + onTerminalContextReaderChange?: (sessionId: string, reader: TerminalContextReader | null) => void; onOpenScripts: () => void; onOpenHistory?: () => void; onOpenTheme: () => void; @@ -846,6 +848,7 @@ const terminalPanePropsAreEqual = ( prev.onTerminalTitleChange === next.onTerminalTitleChange && prev.onTerminalBell === next.onTerminalBell && prev.onTerminalOutput === next.onTerminalOutput && + prev.onTerminalContextReaderChange === next.onTerminalContextReaderChange && prev.onOpenScripts === next.onOpenScripts && prev.onOpenHistory === next.onOpenHistory && prev.onOpenTheme === next.onOpenTheme && @@ -914,6 +917,7 @@ const TerminalPane: React.FC = memo(({ onTerminalTitleChange, onTerminalBell, onTerminalOutput, + onTerminalContextReaderChange, onOpenScripts, onOpenHistory, onOpenTheme, @@ -1295,6 +1299,7 @@ const TerminalPane: React.FC = memo(({ onTerminalTitleChange={onTerminalTitleChange} onTerminalBell={onTerminalBell} onTerminalOutput={onTerminalOutput} + onTerminalContextReaderChange={onTerminalContextReaderChange} onOpenScripts={onOpenScripts} onOpenHistory={onOpenHistory} onOpenTheme={onOpenTheme} @@ -1377,6 +1382,7 @@ interface TerminalPanesHostProps { onTerminalTitleChange?: TerminalPaneProps['onTerminalTitleChange']; onTerminalBell?: TerminalPaneProps['onTerminalBell']; onTerminalOutput?: TerminalPaneProps['onTerminalOutput']; + onTerminalContextReaderChange?: TerminalPaneProps['onTerminalContextReaderChange']; onOpenScripts: () => void; onOpenHistory?: () => void; onOpenTheme: () => void; @@ -1455,6 +1461,7 @@ const terminalPanesHostPropsAreEqual = ( if (prev.onTerminalTitleChange !== next.onTerminalTitleChange) return false; if (prev.onTerminalBell !== next.onTerminalBell) return false; if (prev.onTerminalOutput !== next.onTerminalOutput) return false; + if (prev.onTerminalContextReaderChange !== next.onTerminalContextReaderChange) return false; if (prev.onOpenScripts !== next.onOpenScripts) return false; if (prev.onOpenHistory !== next.onOpenHistory) return false; if (prev.onOpenTheme !== next.onOpenTheme) return false; diff --git a/components/terminalLayer/TerminalLayerTabBridge.tsx b/components/terminalLayer/TerminalLayerTabBridge.tsx index 148fa842b..7d6d23918 100644 --- a/components/terminalLayer/TerminalLayerTabBridge.tsx +++ b/components/terminalLayer/TerminalLayerTabBridge.tsx @@ -6,6 +6,7 @@ import { sessionCapabilitiesStore } from '../../application/state/sessionCapabil import { useSystemManagerBackend } from '../../application/state/useSystemManagerBackend'; import { canReuseTerminalConnection } from '../../application/state/terminalConnectionReuse'; import { resolveSystemSidebarSession } from '../../domain/systemManager/resolveSystemSession'; +import type { TerminalContextReader } from '../../domain/terminalContextRead'; import { useSystemCapabilitiesWarmup } from '../systemManager/hooks/useSystemManager'; import { cn } from '../../lib/utils'; import type { Host, TerminalSession, Workspace } from '../../types'; @@ -22,6 +23,7 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef }) const s = stableRef.current; const activeTabId = useActiveTabId(); const systemBackend = useSystemManagerBackend(); + const terminalContextReadersRef = useRef>(new Map()); s.activeTabIdRef.current = activeTabId; @@ -205,10 +207,22 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef }) sessionHostsMap, sessions, sessionsRef: s.sessionsRef, + terminalContextReadersRef, workspaces: s.workspaces, workspacesRef: s.workspacesRef, }); + const handleTerminalContextReaderChange = React.useCallback(( + sessionId: string, + reader: TerminalContextReader | null, + ) => { + if (reader) { + terminalContextReadersRef.current.set(sessionId, reader); + } else { + terminalContextReadersRef.current.delete(sessionId); + } + }, []); + const prevFocusedSessionIdRef = useRef(undefined); useTerminalLayerEffects({ @@ -377,6 +391,7 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef }) handleTerminalBell: s.handleTerminalBell, handleTerminalOutput: s.handleTerminalOutput, handleTerminalDataCapture: s.handleTerminalDataCapture, + handleTerminalContextReaderChange, handleTerminalFontSizeChange: s.handleTerminalFontSizeChange, handleThemeChangeForFocusedSession: themeState.handleThemeChangeForFocusedSession, handleThemeResetForFocusedSession: themeState.handleThemeResetForFocusedSession, @@ -520,6 +535,7 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef }) s.notes, s.noteGroups, handleWorkspaceDrop, + handleTerminalContextReaderChange, historySessionId, isFocusMode, isSidePanelOpenForCurrentTab, diff --git a/components/terminalLayer/TerminalLayerWorkspaceSection.tsx b/components/terminalLayer/TerminalLayerWorkspaceSection.tsx index 61216c2df..7f50d22b9 100644 --- a/components/terminalLayer/TerminalLayerWorkspaceSection.tsx +++ b/components/terminalLayer/TerminalLayerWorkspaceSection.tsx @@ -55,6 +55,7 @@ function TerminalLayerWorkspaceSectionInner({ ctx }: { ctx: WorkspaceContext }) handleTerminalTitleChange, handleTerminalBell, handleTerminalOutput, + handleTerminalContextReaderChange, handleOpenScripts, handleOpenHistory, handleOpenSystem, @@ -176,6 +177,7 @@ function TerminalLayerWorkspaceSectionInner({ ctx }: { ctx: WorkspaceContext }) onTerminalTitleChange={handleTerminalTitleChange} onTerminalBell={handleTerminalBell} onTerminalOutput={handleTerminalOutput} + onTerminalContextReaderChange={handleTerminalContextReaderChange} onOpenScripts={handleOpenScripts} onOpenHistory={handleOpenHistory} onOpenSystem={handleOpenSystem} diff --git a/components/terminalLayer/terminalLayerViewMemo.ts b/components/terminalLayer/terminalLayerViewMemo.ts index 0727d1c26..898742725 100644 --- a/components/terminalLayer/terminalLayerViewMemo.ts +++ b/components/terminalLayer/terminalLayerViewMemo.ts @@ -265,6 +265,7 @@ const WORKSPACE_CTX_KEYS = [ 'handleTerminalTitleChange', 'handleTerminalBell', 'handleTerminalOutput', + 'handleTerminalContextReaderChange', 'handleOpenScripts', 'handleOpenHistory', 'handleOpenSystem', diff --git a/components/terminalLayer/useTerminalAiContexts.ts b/components/terminalLayer/useTerminalAiContexts.ts index 4f05f8a9c..908e82bac 100644 --- a/components/terminalLayer/useTerminalAiContexts.ts +++ b/components/terminalLayer/useTerminalAiContexts.ts @@ -2,6 +2,7 @@ import type React from 'react'; import { useCallback, useMemo } from 'react'; import { collectSessionIds } from '../../domain/workspace'; +import type { TerminalContextReader } from '../../domain/terminalContextRead'; import { detectLocalOs } from '../../lib/localShell'; import type { Host, PortForwardingRule, TerminalSession, Workspace } from '../../types'; import { buildAITerminalSessionInfo, type AIPanelContext } from './TerminalLayerSupport'; @@ -15,6 +16,7 @@ interface UseTerminalAiContextsOptions { sessionHostsMap: Map; sessions: TerminalSession[]; sessionsRef: React.MutableRefObject; + terminalContextReadersRef: React.MutableRefObject>; workspaces: Workspace[]; workspacesRef: React.MutableRefObject; } @@ -28,6 +30,7 @@ export function useTerminalAiContexts({ sessionHostsMap, sessions, sessionsRef, + terminalContextReadersRef, workspaces, workspacesRef, }: UseTerminalAiContextsOptions) { @@ -35,7 +38,7 @@ export function useTerminalAiContexts({ const localOs = detectLocalOs(navigator.userAgent || navigator.platform); const sessionById = new Map(sessions.map((session) => [session.id, session])); const workspaceById = new Map(workspaces.map((workspace) => [workspace.id, workspace])); - const allHosts = hostsRef.current; + const allHosts = hosts; const tabIds = new Set(mountedAiTabIds); const contexts = new Map(); @@ -116,8 +119,18 @@ export function useTerminalAiContexts({ }), workspaceId: scope.type === 'workspace' ? scope.targetId : undefined, workspaceName, + readTerminalContext: (request: Parameters[0]) => { + const reader = terminalContextReadersRef.current.get(request.sessionId); + if (!reader) { + return Promise.resolve({ + ok: false as const, + error: `Terminal session "${request.sessionId}" has no readable terminal buffer.`, + }); + } + return reader(request); + }, }; - }, [hostsRef, portForwardingRulesRef, sessionsRef, workspacesRef]); + }, [hostsRef, portForwardingRulesRef, sessionsRef, terminalContextReadersRef, workspacesRef]); return { aiContextsByTabId, diff --git a/domain/terminalContextRead.test.ts b/domain/terminalContextRead.test.ts new file mode 100644 index 000000000..1236f92e5 --- /dev/null +++ b/domain/terminalContextRead.test.ts @@ -0,0 +1,98 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + buildTerminalContextReadResult, + buildTerminalContextSnapshotText, + resolveTerminalContextLineWindow, +} from "./terminalContextRead.ts"; + +test("resolveTerminalContextLineWindow returns the visible viewport range", () => { + assert.deepEqual(resolveTerminalContextLineWindow({ + range: "viewport", + totalLines: 200, + viewportStartLine: 150, + viewportEndLine: 173, + }), { + startLine: 150, + endLine: 173, + maxLines: 80, + }); +}); + +test("resolveTerminalContextLineWindow clamps tail reads to the configured max lines", () => { + assert.deepEqual(resolveTerminalContextLineWindow({ + range: "tail", + totalLines: 500, + maxLines: 120, + }), { + startLine: 380, + endLine: 499, + maxLines: 120, + }); +}); + +test("buildTerminalContextReadResult reports paging metadata for selected lines", () => { + const text = Array.from({ length: 20 }, (_, index) => `line-${index}`).join("\n"); + const result = buildTerminalContextReadResult({ + sessionId: "session-1", + label: "prod", + fullText: text, + range: "lines", + startLine: 5, + maxLines: 4, + source: "snapshot", + }); + + assert.equal(result.ok, true); + assert.equal(result.sessionId, "session-1"); + assert.equal(result.label, "prod"); + assert.equal(result.content, "line-5\nline-6\nline-7\nline-8"); + assert.equal(result.totalLines, 20); + assert.equal(result.startLine, 5); + assert.equal(result.endLine, 8); + assert.equal(result.returnedLines, 4); + assert.equal(result.hasMoreBefore, true); + assert.equal(result.hasMoreAfter, true); + assert.equal(result.source, "snapshot"); +}); + +test("buildTerminalContextSnapshotText extends viewport to pending output", () => { + const snapshot = buildTerminalContextSnapshotText({ + scrollbackText: "old-1\nold-2", + viewportText: "visible-1\nvisible-2", + pendingText: "pending-1", + }); + const result = buildTerminalContextReadResult({ + sessionId: "session-1", + fullText: snapshot.fullText, + range: "viewport", + source: "snapshot", + viewportStartLine: snapshot.viewportStartLine, + viewportEndLine: snapshot.viewportEndLine, + }); + + assert.equal(snapshot.fullText, "old-1\nold-2\nvisible-1\nvisible-2\npending-1"); + assert.equal(result.content, "visible-1\nvisible-2\npending-1"); + assert.equal(result.startLine, 2); + assert.equal(result.endLine, 4); + assert.equal(result.hasMoreBefore, true); + assert.equal(result.hasMoreAfter, false); +}); + +test("viewport reads keep the newest lines when the snapshot viewport exceeds max lines", () => { + const text = Array.from({ length: 10 }, (_, index) => `line-${index}`).join("\n"); + const result = buildTerminalContextReadResult({ + sessionId: "session-1", + fullText: text, + range: "viewport", + source: "snapshot", + maxLines: 4, + viewportStartLine: 2, + viewportEndLine: 9, + }); + + assert.equal(result.content, "line-6\nline-7\nline-8\nline-9"); + assert.equal(result.startLine, 6); + assert.equal(result.endLine, 9); +}); diff --git a/domain/terminalContextRead.ts b/domain/terminalContextRead.ts new file mode 100644 index 000000000..3102a3ea8 --- /dev/null +++ b/domain/terminalContextRead.ts @@ -0,0 +1,214 @@ +export type TerminalContextReadRange = "viewport" | "tail" | "head" | "lines"; + +export type TerminalContextReadSource = "live" | "snapshot"; + +export const TERMINAL_CONTEXT_DEFAULT_MAX_LINES = 80; +export const TERMINAL_CONTEXT_MAX_LINES = 300; + +export interface TerminalContextReadRequest { + sessionId?: string; + range?: TerminalContextReadRange; + startLine?: number; + maxLines?: number; +} + +export interface TerminalContextLineWindowInput { + range?: TerminalContextReadRange; + totalLines: number; + viewportStartLine?: number; + viewportEndLine?: number; + startLine?: number; + maxLines?: number; +} + +export interface TerminalContextLineWindow { + startLine: number; + endLine: number; + maxLines: number; +} + +export interface TerminalContextReadResult { + ok: true; + sessionId: string; + label?: string; + range: TerminalContextReadRange; + content: string; + totalLines: number; + startLine: number; + endLine: number; + returnedLines: number; + hasMoreBefore: boolean; + hasMoreAfter: boolean; + source: TerminalContextReadSource; + alternateScreen?: boolean; +} + +export type TerminalContextReader = ( + request: TerminalContextReadRequest & { sessionId: string }, +) => Promise; + +export interface BuildTerminalContextReadResultInput { + sessionId: string; + label?: string; + fullText: string; + range?: TerminalContextReadRange; + startLine?: number; + maxLines?: number; + source: TerminalContextReadSource; + alternateScreen?: boolean; + viewportStartLine?: number; + viewportEndLine?: number; +} + +export interface TerminalContextSnapshotTextInput { + scrollbackText?: string; + viewportText?: string; + pendingText?: string; +} + +export interface TerminalContextSnapshotText { + fullText: string; + viewportStartLine?: number; + viewportEndLine?: number; +} + +export function normalizeTerminalContextMaxLines(value: unknown): number { + if (typeof value !== "number" || !Number.isFinite(value)) { + return TERMINAL_CONTEXT_DEFAULT_MAX_LINES; + } + return Math.min( + TERMINAL_CONTEXT_MAX_LINES, + Math.max(1, Math.round(value)), + ); +} + +export function normalizeTerminalContextRange(value: unknown): TerminalContextReadRange { + if ( + value === "viewport" || + value === "tail" || + value === "head" || + value === "lines" + ) { + return value; + } + return "viewport"; +} + +export function resolveTerminalContextLineWindow( + input: TerminalContextLineWindowInput, +): TerminalContextLineWindow { + const range = normalizeTerminalContextRange(input.range); + const maxLines = normalizeTerminalContextMaxLines(input.maxLines); + const totalLines = Math.max(0, Math.floor(input.totalLines)); + + if (totalLines === 0) { + return { startLine: 0, endLine: -1, maxLines }; + } + + if (range === "head") { + return { + startLine: 0, + endLine: Math.min(totalLines - 1, maxLines - 1), + maxLines, + }; + } + + if (range === "tail") { + return { + startLine: Math.max(0, totalLines - maxLines), + endLine: totalLines - 1, + maxLines, + }; + } + + if (range === "lines") { + const start = clampLine(input.startLine, totalLines); + return { + startLine: start, + endLine: Math.min(totalLines - 1, start + maxLines - 1), + maxLines, + }; + } + + const viewportStart = clampLine(input.viewportStartLine, totalLines); + const viewportEnd = clampLine(input.viewportEndLine, totalLines); + const rawStart = Math.min(viewportStart, viewportEnd); + const end = Math.max(viewportStart, viewportEnd); + const start = Math.max(rawStart, end - maxLines + 1); + return { startLine: start, endLine: end, maxLines }; +} + +export function buildTerminalContextReadResult( + input: BuildTerminalContextReadResultInput, +): TerminalContextReadResult { + const range = normalizeTerminalContextRange(input.range); + const lines = splitTerminalContextLines(input.fullText); + const totalLines = lines.length; + const window = resolveTerminalContextLineWindow({ + range, + totalLines, + viewportStartLine: input.viewportStartLine, + viewportEndLine: input.viewportEndLine, + startLine: input.startLine, + maxLines: input.maxLines, + }); + const selectedLines = window.endLine >= window.startLine + ? lines.slice(window.startLine, window.endLine + 1) + : []; + + return { + ok: true, + sessionId: input.sessionId, + label: input.label, + range, + content: selectedLines.join("\n"), + totalLines, + startLine: window.startLine, + endLine: window.endLine, + returnedLines: selectedLines.length, + hasMoreBefore: window.startLine > 0, + hasMoreAfter: window.endLine >= 0 && window.endLine < totalLines - 1, + source: input.source, + alternateScreen: input.alternateScreen, + }; +} + +export function buildTerminalContextSnapshotText( + input: TerminalContextSnapshotTextInput, +): TerminalContextSnapshotText { + const parts: Array<{ kind: "scrollback" | "viewport" | "pending"; text: string }> = []; + if (input.scrollbackText) parts.push({ kind: "scrollback", text: input.scrollbackText }); + if (input.viewportText) parts.push({ kind: "viewport", text: input.viewportText }); + if (input.pendingText) parts.push({ kind: "pending", text: input.pendingText }); + + let lineOffset = 0; + let viewportStartLine: number | undefined; + let viewportEndLine: number | undefined; + for (const part of parts) { + const lineCount = splitTerminalContextLines(part.text).length; + if (part.kind === "viewport") { + viewportStartLine = lineOffset; + viewportEndLine = lineOffset + lineCount - 1; + } else if (part.kind === "pending" && viewportStartLine !== undefined) { + viewportEndLine = lineOffset + lineCount - 1; + } + lineOffset += lineCount; + } + + return { + fullText: parts.map((part) => part.text).join("\n"), + viewportStartLine, + viewportEndLine, + }; +} + +function splitTerminalContextLines(text: string): string[] { + if (!text) return []; + return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n"); +} + +function clampLine(value: unknown, totalLines: number): number { + if (totalLines <= 0) return 0; + if (typeof value !== "number" || !Number.isFinite(value)) return 0; + return Math.min(totalLines - 1, Math.max(0, Math.floor(value))); +} diff --git a/electron/capabilities/catalog/harness.cjs b/electron/capabilities/catalog/harness.cjs index a0dcb803d..4dcd0b923 100644 --- a/electron/capabilities/catalog/harness.cjs +++ b/electron/capabilities/catalog/harness.cjs @@ -59,6 +59,24 @@ const HARNESS_CAPABILITIES = [ catty: { toolName: "workspace_get_session_info" }, }, }, + { + id: "harness.terminal.read_context", + domain: "harness", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Read a bounded slice of the current terminal screen or scrollback from the active AI scope.", + policy: { + write: false, + sensitiveRead: false, + longRunning: false, + requiresChatSession: true, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + catty: { toolName: "terminal_read_context" }, + }, + }, { id: "harness.web.search", domain: "harness", diff --git a/electron/capabilities/catalog/integrity.test.cjs b/electron/capabilities/catalog/integrity.test.cjs index ebfcde465..bfb7ec655 100644 --- a/electron/capabilities/catalog/integrity.test.cjs +++ b/electron/capabilities/catalog/integrity.test.cjs @@ -54,8 +54,9 @@ test("implemented capabilities expose at least one surface binding", () => { assert.ok(surfaces.length > 0, `${capability.id} has no surfaces`); const hasRpc = surfaces.some((surface) => capability.surfaces[surface]?.rpcMethod); const hasCli = surfaces.some((surface) => capability.surfaces[surface]?.command); + const hasCattyTool = surfaces.some((surface) => capability.surfaces[surface]?.toolName); assert.ok( - hasRpc || hasCli || capability.surfaces[CAPABILITY_SURFACES.BUILTIN]?.mcpTool, + hasRpc || hasCli || hasCattyTool || capability.surfaces[CAPABILITY_SURFACES.BUILTIN]?.mcpTool, `${capability.id} has no rpc/cli/mcp binding`, ); } diff --git a/electron/capabilities/codegen/toolSurfaces.test.cjs b/electron/capabilities/codegen/toolSurfaces.test.cjs index 9e7b49388..938fdd54a 100644 --- a/electron/capabilities/codegen/toolSurfaces.test.cjs +++ b/electron/capabilities/codegen/toolSurfaces.test.cjs @@ -82,7 +82,7 @@ test("listCattyToolSpecs includes harness catty-only tools with local execution" const specs = listCattyToolSpecs(); assert.ok(specs.length >= 40); const harness = specs.filter((spec) => spec.capabilityId.startsWith("harness.")); - assert.equal(harness.length, 5); + assert.equal(harness.length, 6); for (const spec of harness) { assert.equal(spec.localExecution, true); assert.equal(spec.rpcMethod, null); @@ -90,6 +90,7 @@ test("listCattyToolSpecs includes harness catty-only tools with local execution" const harnessIds = harness.map((spec) => spec.capabilityId); assert.ok(harnessIds.includes("harness.tool_output.read")); assert.ok(harnessIds.includes("harness.workspace.get_info")); + assert.ok(harnessIds.includes("harness.terminal.read_context")); }); test("harness capabilities are not exposed on MCP", () => { diff --git a/electron/capabilities/schemas/toolInputs.cjs b/electron/capabilities/schemas/toolInputs.cjs index 1d2c9de69..4a59eb09b 100644 --- a/electron/capabilities/schemas/toolInputs.cjs +++ b/electron/capabilities/schemas/toolInputs.cjs @@ -169,6 +169,12 @@ const TOOL_INPUT_FIELDS = Object.freeze({ "harness.workspace.get_session_info": { sessionId: { type: "string", description: "The session ID to get information about." }, }, + "harness.terminal.read_context": { + sessionId: { type: "string", optional: true, description: "Terminal session ID. Required when the current AI scope contains more than one terminal." }, + range: { type: "string", optional: true, description: "Which terminal slice to read: viewport, tail, head, or lines. Defaults to viewport." }, + startLine: { type: "number", optional: true, description: "Zero-based terminal buffer line to start from when range is lines." }, + maxLines: { type: "number", optional: true, description: "Maximum terminal rows to return. Defaults to 80, capped at 300." }, + }, "harness.web.search": { query: { type: "string", description: "The search query to look up on the web." }, maxResults: { type: "number", optional: true, description: "Maximum number of search results to return." }, diff --git a/infrastructure/ai/cattyAgent/executor.ts b/infrastructure/ai/cattyAgent/executor.ts index f60616c92..5c86c78d3 100644 --- a/infrastructure/ai/cattyAgent/executor.ts +++ b/infrastructure/ai/cattyAgent/executor.ts @@ -1,4 +1,7 @@ import type { ToolCall, ToolResult, AIPermissionMode, WebSearchConfig } from '../types'; +import type { + TerminalContextReader, +} from '../../../domain/terminalContextRead'; import { executeTerminalExecute, executeWorkspaceGetInfo, @@ -59,6 +62,7 @@ export interface ExecutorContext { // Workspace info workspaceId?: string; workspaceName?: string; + readTerminalContext?: TerminalContextReader; } /** Convert a shared ToolExecResult into the executor's ToolResult format. */ diff --git a/infrastructure/ai/harness/capabilityTools.test.ts b/infrastructure/ai/harness/capabilityTools.test.ts index 80f0ab97f..fdeabbc58 100644 --- a/infrastructure/ai/harness/capabilityTools.test.ts +++ b/infrastructure/ai/harness/capabilityTools.test.ts @@ -92,3 +92,117 @@ describe('capabilityTools result fitting', () => { assert.equal(result.content, body); }); }); + +describe('capabilityTools terminal context reader', () => { + it('reads terminal context from the only scoped terminal when sessionId is omitted', async () => { + const tools = createCattyToolsFromCatalog( + {}, + { + sessions: [{ + sessionId: 'session-1', + hostId: 'host-1', + hostname: 'prod.internal', + label: 'prod', + connected: true, + }], + readTerminalContext: async (request) => ({ + ok: true, + sessionId: request.sessionId, + label: 'prod', + range: request.range ?? 'viewport', + content: 'line-a\nline-b', + totalLines: 2, + startLine: 0, + endLine: 1, + returnedLines: 2, + hasMoreBefore: false, + hasMoreAfter: false, + source: 'live', + }), + }, + [], + 'auto', + undefined, + 'chat-1', + ); + + const result = await tools.terminal_read_context.execute( + { range: 'tail', maxLines: 20 }, + { toolCallId: 'call-1', messages: [] }, + ) as { sessionId: string; content: string; range: string }; + + assert.equal(result.sessionId, 'session-1'); + assert.equal(result.range, 'tail'); + assert.equal(result.content, 'line-a\nline-b'); + }); + + it('fits large terminal context reads through the shared tool output store', async () => { + const store = new ToolOutputStore(); + const body = `${'terminal line output '.repeat(900)}important ending`; + const tools = createCattyToolsFromCatalog( + {}, + { + sessions: [{ + sessionId: 'session-1', + hostId: 'host-1', + hostname: 'prod.internal', + label: 'prod', + connected: true, + }], + readTerminalContext: async (request) => ({ + ok: true, + sessionId: request.sessionId, + label: 'prod', + range: request.range ?? 'viewport', + content: body, + totalLines: 1, + startLine: 0, + endLine: 0, + returnedLines: 1, + hasMoreBefore: false, + hasMoreAfter: false, + source: 'live', + }), + }, + [], + 'auto', + undefined, + 'chat-1', + store, + ); + + const result = await tools.terminal_read_context.execute( + { range: 'viewport' }, + { toolCallId: 'call-1', messages: [] }, + ) as { content: string }; + + assert.notEqual(result.content, body); + assert.match(result.content, /tool output handle/); + const handleId = result.content.match(/handleId=(tool-output-[^\]\s]+)/)?.[1]; + assert.ok(handleId); + assert.equal(store.read({ handleId, mode: 'full', maxChars: body.length + 100 }, 'chat-1'), body); + }); + + it('asks for sessionId when multiple scoped terminals are available', async () => { + const tools = createCattyToolsFromCatalog( + {}, + { + sessions: [ + { sessionId: 'session-1', hostId: 'host-1', hostname: 'a', label: 'a', connected: true }, + { sessionId: 'session-2', hostId: 'host-2', hostname: 'b', label: 'b', connected: true }, + ], + }, + [], + 'auto', + undefined, + 'chat-1', + ); + + const result = await tools.terminal_read_context.execute( + { range: 'viewport' }, + { toolCallId: 'call-1', messages: [] }, + ) as { error?: string }; + + assert.match(result.error ?? '', /sessionId/); + }); +}); diff --git a/infrastructure/ai/harness/capabilityTools.ts b/infrastructure/ai/harness/capabilityTools.ts index c48538af6..aabbac2d9 100644 --- a/infrastructure/ai/harness/capabilityTools.ts +++ b/infrastructure/ai/harness/capabilityTools.ts @@ -1,6 +1,7 @@ import { tool } from 'ai'; import { z } from 'zod'; import type { NetcattyBridge } from '../cattyAgent/executor'; +import type { TerminalContextReadRange } from '../../../domain/terminalContextRead'; import type { AIPermissionMode } from '../types'; import type { WebSearchConfig } from '../types'; import { isWebSearchReady } from '../types'; @@ -209,6 +210,44 @@ async function executeLocalCattyCapability(ctx: LocalExecutionContext): Promise< } return local.data; } + case 'harness.terminal.read_context': { + const scopeCtx = resolveContext(); + const sessions = scopeCtx.sessions ?? []; + const requestedSessionId = typeof args.sessionId === 'string' && args.sessionId.trim() + ? args.sessionId.trim() + : undefined; + const sessionId = requestedSessionId + ?? (sessions.length === 1 ? sessions[0].sessionId : undefined); + + if (!sessionId) { + return { + ok: false, + error: 'sessionId is required because the current AI scope contains multiple terminal sessions.', + }; + } + + const session = sessions.find((entry) => entry.sessionId === sessionId); + if (!session) { + return { + ok: false, + error: `Terminal session "${sessionId}" is not in the current AI scope.`, + }; + } + + if (!scopeCtx.readTerminalContext) { + return { + ok: false, + error: 'Terminal context reader is unavailable for this AI scope.', + }; + } + + return scopeCtx.readTerminalContext({ + sessionId, + range: typeof args.range === 'string' ? args.range as TerminalContextReadRange : undefined, + startLine: typeof args.startLine === 'number' ? args.startLine : undefined, + maxLines: typeof args.maxLines === 'number' ? args.maxLines : undefined, + }); + } case 'harness.web.search': { const { query, maxResults } = args as { query: string; maxResults?: number }; return unwrap(await executeWebSearch(deps, { query, maxResults })); diff --git a/infrastructure/ai/harness/generated/cattyToolSpecs.json b/infrastructure/ai/harness/generated/cattyToolSpecs.json index 18d13e643..4d681e4c5 100644 --- a/infrastructure/ai/harness/generated/cattyToolSpecs.json +++ b/infrastructure/ai/harness/generated/cattyToolSpecs.json @@ -1020,6 +1020,44 @@ "bypassesChatCancel": true } }, + { + "capabilityId": "harness.terminal.read_context", + "toolName": "terminal_read_context", + "rpcMethod": null, + "localExecution": true, + "description": "Read a bounded slice of the current terminal screen or scrollback from the active AI scope.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": true, + "description": "Terminal session ID. Required when the current AI scope contains more than one terminal." + }, + "range": { + "type": "string", + "optional": true, + "description": "Which terminal slice to read: viewport, tail, head, or lines. Defaults to viewport." + }, + "startLine": { + "type": "number", + "optional": true, + "description": "Zero-based terminal buffer line to start from when range is lines." + }, + "maxLines": { + "type": "number", + "optional": true, + "description": "Maximum terminal rows to return. Defaults to 80, capped at 300." + } + }, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, { "capabilityId": "harness.web.search", "toolName": "web_search", diff --git a/package.json b/package.json index cab4c4062..ac72d90df 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,7 @@ "generate:capability-tools": "node scripts/generate-capability-tools.cjs", "lint": "eslint .", "lint:fix": "eslint . --fix", - "test": "node --test --import tsx electron/*.test.cjs electron/capabilities/*.test.cjs electron/capabilities/*/*.test.cjs electron/capabilities/*/*/*.test.cjs electron/cli/*.test.cjs electron/bridges/*.test.cjs electron/bridges/*/*.test.cjs electron/bridges/aiBridge/sdk/*.test.cjs scripts/*.test.cjs application/*.test.ts application/app/*.test.ts application/i18n/locales/*.test.ts application/state/*.test.ts application/state/*/*.test.ts components/*.test.ts components/*.test.tsx components/editor/*.test.ts components/editor/*.test.tsx components/notes/*.test.tsx components/port-forwarding/*.test.ts components/systemManager/*.test.ts components/terminalLayer/*.test.ts components/settings/*.test.tsx components/settings/tabs/*.test.ts components/settings/tabs/ai/*.test.ts components/settings/tabs/ai/*.test.tsx components/ai/*.test.ts components/ai/*.test.tsx components/ai-elements/*.test.tsx components/sftp/*.test.ts components/terminal/*.test.ts components/terminal/*.test.tsx components/terminal/runtime/*.test.ts components/vault/*.test.ts components/vault/*.test.tsx domain/*.test.ts domain/*/*.test.ts infrastructure/ai/*.test.ts infrastructure/ai/*/*.test.ts infrastructure/ai/sdk/*.test.ts infrastructure/config/*.test.ts infrastructure/persistence/*.test.ts infrastructure/services/*/*.test.ts lib/*.test.ts" + "test": "node --test --import tsx electron/*.test.cjs electron/capabilities/*.test.cjs electron/capabilities/*/*.test.cjs electron/capabilities/*/*/*.test.cjs electron/cli/*.test.cjs electron/bridges/*.test.cjs electron/bridges/*/*.test.cjs electron/bridges/aiBridge/sdk/*.test.cjs scripts/*.test.cjs application/*.test.ts application/app/*.test.ts application/i18n/locales/*.test.ts application/state/*.test.ts application/state/*/*.test.ts components/*.test.ts components/*.test.tsx components/editor/*.test.ts components/editor/*.test.tsx components/notes/*.test.tsx components/port-forwarding/*.test.ts components/systemManager/*.test.ts components/terminalLayer/*.test.ts components/settings/*.test.tsx components/settings/tabs/*.test.ts components/settings/tabs/ai/*.test.ts components/settings/tabs/ai/*.test.tsx components/ai/*.test.ts components/ai/*.test.tsx components/ai/toolArtifacts/*.test.ts components/ai/toolArtifacts/*.test.tsx components/ai-elements/*.test.tsx components/sftp/*.test.ts components/terminal/*.test.ts components/terminal/*.test.tsx components/terminal/runtime/*.test.ts components/vault/*.test.ts components/vault/*.test.tsx domain/*.test.ts domain/*/*.test.ts infrastructure/ai/*.test.ts infrastructure/ai/*/*.test.ts infrastructure/ai/sdk/*.test.ts infrastructure/config/*.test.ts infrastructure/persistence/*.test.ts infrastructure/services/*/*.test.ts lib/*.test.ts" }, "dependencies": { "@ai-sdk/anthropic": "^3.0.58",