mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-21 23:50:45 +00:00
Add terminal context read tool for AI
This commit is contained in:
1 parent
46d2a6e50a
commit
d010065da1
32 files changed
+1209
-11
No files matched your search
@@ -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<TerminalProps> = ({
|
||||
onTerminalTitleChange,
|
||||
onTerminalBell,
|
||||
onTerminalOutput,
|
||||
onTerminalContextReaderChange,
|
||||
onOpenScripts,
|
||||
onOpenHistory,
|
||||
onOpenTheme,
|
||||
@@ -245,6 +254,9 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
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<TerminalProps> = ({
|
||||
return connectionLogBufferRef.current.toString();
|
||||
}, []);
|
||||
|
||||
const readTerminalContext = useCallback<TerminalContextReader>(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<TerminalProps> = ({
|
||||
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<TerminalProps> = ({
|
||||
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<TerminalProps> = ({
|
||||
hibernateSnapshotRef,
|
||||
hibernateViewportSnapshotRef,
|
||||
hibernateScrollbackSnapshotRef,
|
||||
hibernateContextSnapshotRef,
|
||||
hibernateContextViewportSnapshotRef,
|
||||
hibernateContextScrollbackSnapshotRef,
|
||||
hibernateAlternateScreenRef,
|
||||
hasRuntimeRef,
|
||||
onHibernate: hibernateRuntime,
|
||||
|
||||
@@ -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<ChatMessageListProps> = ({
|
||||
&& displayedMessages[end].role === "assistant";
|
||||
|
||||
const renderToolResultItem = (item: typeof toolResults[number]) => {
|
||||
const terminalArtifact = parseTerminalToolArtifact(item.name, item.content);
|
||||
if (terminalArtifact) {
|
||||
return (
|
||||
<TerminalArtifactToolResult
|
||||
key={item.toolCallId}
|
||||
artifact={terminalArtifact}
|
||||
toolName={item.name}
|
||||
args={item.args}
|
||||
result={item.content}
|
||||
isError={item.isError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const artifact = parseVaultToolArtifact(item.name, item.content);
|
||||
if (artifact) {
|
||||
return (
|
||||
|
||||
@@ -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(
|
||||
<TerminalArtifactCard
|
||||
artifact={{
|
||||
kind: 'terminal.context',
|
||||
sessionId: 'session-1',
|
||||
label: 'prod',
|
||||
range: 'tail',
|
||||
totalLines: 120,
|
||||
startLine: 100,
|
||||
endLine: 102,
|
||||
returnedLines: 3,
|
||||
hasMoreBefore: true,
|
||||
hasMoreAfter: false,
|
||||
source: 'live',
|
||||
preview: 'alpha\nbeta\ngamma',
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
assert.match(html, /prod/);
|
||||
assert.match(html, /lines 101-103 \/ 120/);
|
||||
assert.doesNotMatch(html, /alpha/);
|
||||
});
|
||||
|
||||
test('TerminalArtifactCard renders terminal read errors', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<TerminalArtifactCard
|
||||
artifact={{
|
||||
kind: 'error',
|
||||
message: 'Terminal context reader is unavailable.',
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
assert.match(html, /Terminal read failed/);
|
||||
assert.match(html, /Terminal context reader is unavailable/);
|
||||
});
|
||||
@@ -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<TerminalToolArtifact, { kind: 'terminal.context' }>): string {
|
||||
if (artifact.returnedLines === 0) {
|
||||
return `0 / ${artifact.totalLines} lines`;
|
||||
}
|
||||
return `lines ${artifact.startLine + 1}-${artifact.endLine + 1} / ${artifact.totalLines}`;
|
||||
}
|
||||
|
||||
function formatSubtitle(artifact: Extract<TerminalToolArtifact, { kind: 'terminal.context' }>): string {
|
||||
const parts = [
|
||||
formatLineRange(artifact),
|
||||
artifact.source,
|
||||
artifact.hasMoreBefore || artifact.hasMoreAfter ? 'more available' : null,
|
||||
].filter(Boolean);
|
||||
return parts.join(' | ');
|
||||
}
|
||||
|
||||
export const TerminalArtifactCard = React.forwardRef<HTMLDivElement, TerminalArtifactCardProps>(({
|
||||
artifact,
|
||||
className,
|
||||
}, ref) => {
|
||||
if (artifact.kind === 'error') {
|
||||
return (
|
||||
<div className={cn(
|
||||
'flex w-full items-center gap-2.5 rounded-md border border-destructive/25 bg-destructive/5 px-2.5 py-2',
|
||||
className,
|
||||
)} ref={ref}>
|
||||
<div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-destructive/10 text-destructive">
|
||||
<AlertCircle size={15} />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 text-left">
|
||||
<div className="truncate text-[12px] font-medium text-foreground/85">
|
||||
Terminal read failed
|
||||
</div>
|
||||
<div className="truncate text-[11px] text-muted-foreground/60">
|
||||
{artifact.message}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const title = artifact.label || artifact.sessionId;
|
||||
|
||||
return (
|
||||
<div className={cn(
|
||||
'flex w-full items-center gap-2.5 rounded-md border border-border/25 bg-muted/10 px-2.5 py-2',
|
||||
className,
|
||||
)} ref={ref}>
|
||||
<div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-emerald-500/10 text-emerald-500">
|
||||
<SquareTerminal size={15} />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 text-left">
|
||||
<div className="truncate text-[12px] font-medium text-foreground/85">
|
||||
{title}
|
||||
</div>
|
||||
<div className="truncate text-[11px] text-muted-foreground/60">
|
||||
{formatSubtitle(artifact)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
TerminalArtifactCard.displayName = 'TerminalArtifactCard';
|
||||
@@ -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<string, unknown>;
|
||||
result?: unknown;
|
||||
isError?: boolean;
|
||||
}
|
||||
|
||||
export const TerminalArtifactToolResult: React.FC<TerminalArtifactToolResultProps> = ({
|
||||
artifact,
|
||||
toolName,
|
||||
args,
|
||||
result,
|
||||
isError,
|
||||
}) => {
|
||||
const tooltip = formatTerminalToolTooltip(toolName, args, result, isError);
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<TerminalArtifactCard artifact={artifact} />
|
||||
</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side="top"
|
||||
align="start"
|
||||
className="max-w-md whitespace-pre-wrap break-words font-mono text-[11px] leading-relaxed"
|
||||
>
|
||||
{tooltip}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
};
|
||||
@@ -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<string, unknown>,
|
||||
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');
|
||||
}
|
||||
@@ -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.',
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown> | 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<string, unknown>;
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (typeof result === 'object' && !Array.isArray(result)) {
|
||||
return result as Record<string, unknown>;
|
||||
}
|
||||
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'),
|
||||
};
|
||||
}
|
||||
@@ -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:",
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { IBuffer, Terminal as XTerm } from "@xterm/xterm";
|
||||
|
||||
export type TerminalTextRange = {
|
||||
startLine: number;
|
||||
endLine: number;
|
||||
};
|
||||
|
||||
type TerminalBufferTextSource = Pick<XTerm, "buffer" | "cols">;
|
||||
|
||||
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<IBuffer, "getLine">,
|
||||
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");
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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<string, unknown>) => {
|
||||
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,
|
||||
]);
|
||||
});
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
});
|
||||
@@ -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
|
||||
|
||||
@@ -26,6 +26,9 @@ type UseTerminalHibernateEffectOptions = {
|
||||
hibernateSnapshotRef: React.MutableRefObject<string>;
|
||||
hibernateViewportSnapshotRef: React.MutableRefObject<string>;
|
||||
hibernateScrollbackSnapshotRef: React.MutableRefObject<string>;
|
||||
hibernateContextSnapshotRef: React.MutableRefObject<string>;
|
||||
hibernateContextViewportSnapshotRef: React.MutableRefObject<string>;
|
||||
hibernateContextScrollbackSnapshotRef: React.MutableRefObject<string>;
|
||||
hibernateAlternateScreenRef: React.MutableRefObject<boolean>;
|
||||
hasRuntimeRef: React.MutableRefObject<boolean>;
|
||||
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,
|
||||
|
||||
@@ -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<TerminalPaneProps> = memo(({
|
||||
onTerminalTitleChange,
|
||||
onTerminalBell,
|
||||
onTerminalOutput,
|
||||
onTerminalContextReaderChange,
|
||||
onOpenScripts,
|
||||
onOpenHistory,
|
||||
onOpenTheme,
|
||||
@@ -1295,6 +1299,7 @@ const TerminalPane: React.FC<TerminalPaneProps> = 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;
|
||||
|
||||
@@ -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<Map<string, TerminalContextReader>>(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<string | undefined>(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,
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -265,6 +265,7 @@ const WORKSPACE_CTX_KEYS = [
|
||||
'handleTerminalTitleChange',
|
||||
'handleTerminalBell',
|
||||
'handleTerminalOutput',
|
||||
'handleTerminalContextReaderChange',
|
||||
'handleOpenScripts',
|
||||
'handleOpenHistory',
|
||||
'handleOpenSystem',
|
||||
|
||||
@@ -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<string, Host>;
|
||||
sessions: TerminalSession[];
|
||||
sessionsRef: React.MutableRefObject<TerminalSession[]>;
|
||||
terminalContextReadersRef: React.MutableRefObject<Map<string, TerminalContextReader>>;
|
||||
workspaces: Workspace[];
|
||||
workspacesRef: React.MutableRefObject<Workspace[]>;
|
||||
}
|
||||
@@ -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<string, TerminalSession>(sessions.map((session) => [session.id, session]));
|
||||
const workspaceById = new Map<string, Workspace>(workspaces.map((workspace) => [workspace.id, workspace]));
|
||||
const allHosts = hostsRef.current;
|
||||
const allHosts = hosts;
|
||||
const tabIds = new Set<string>(mountedAiTabIds);
|
||||
|
||||
const contexts = new Map<string, AIPanelContext>();
|
||||
@@ -116,8 +119,18 @@ export function useTerminalAiContexts({
|
||||
}),
|
||||
workspaceId: scope.type === 'workspace' ? scope.targetId : undefined,
|
||||
workspaceName,
|
||||
readTerminalContext: (request: Parameters<TerminalContextReader>[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,
|
||||
|
||||
Reference in new issue
Block a user