From 99003f9716e6566b4cc21cc7880382971843f460 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 01:20:28 +0800 Subject: [PATCH 001/228] fix: stop SFTP cwd toggling when OSC 7 tracking is active (#1602) Skip backend pwd probes after commands once the shell reports OSC 7, even when the path is unchanged, so sudo sessions no longer alternate between login-shell fallback and the interactive cwd. Also silence OSC 7 setup script status text in the terminal since the toast already confirms success. Co-authored-by: Cursor --- components/TerminalLayer.tsx | 18 +++++++++++---- components/terminal/osc7Setup.ts | 6 ++--- components/terminal/sftpCwd.test.ts | 23 ++++++++++++++----- components/terminal/sftpCwd.ts | 16 ++++++------- components/terminal/terminalHelpers.ts | 2 +- components/terminal/useTerminalEffects.ts | 2 +- .../terminalLayer/TerminalLayerSupport.tsx | 2 +- 7 files changed, 44 insertions(+), 25 deletions(-) diff --git a/components/TerminalLayer.tsx b/components/TerminalLayer.tsx index dcd0a1a85..3ff34f5d7 100644 --- a/components/TerminalLayer.tsx +++ b/components/TerminalLayer.tsx @@ -195,6 +195,7 @@ const TerminalLayerInner: React.FC = ({ const focusedSessionIdRef = useRef(undefined); const terminalCwdRevisionRef = useRef(0); const [terminalCwdRevision, setTerminalCwdRevision] = useState(0); + const terminalOsc7SignalBySessionRef = useRef>(new Map()); const cwdProbeCancelersRef = useRef void>>(new Map()); const cwdProbeGenerationRef = useRef>(new Map()); @@ -208,7 +209,16 @@ const TerminalLayerInner: React.FC = ({ return () => window.clearTimeout(timeoutId); }, []); - const handleTerminalCwdChange = useCallback((sessionId: string, cwd: string | null) => { + const handleTerminalCwdChange = useCallback(( + sessionId: string, + cwd: string | null, + meta?: { source?: 'osc7' }, + ) => { + if (meta?.source === 'osc7') { + const nextSignal = (terminalOsc7SignalBySessionRef.current.get(sessionId) ?? 0) + 1; + terminalOsc7SignalBySessionRef.current.set(sessionId, nextSignal); + } + const currentCwd = terminalRendererCwdBySessionRef.current.get(sessionId) ?? null; const nextCwd = cwd && cwd.trim().length > 0 ? cwd : null; if (currentCwd === nextCwd) return; @@ -707,14 +717,14 @@ const TerminalLayerInner: React.FC = ({ const followHost = resolveSftpFollowTerminalCwdTargetHost(visibleSftpHost, sessionHost); if (!resolveHostFollowTerminalCwd(followHost?.sftpFollowTerminalCwd, sftpFollowTerminalCwdRef.current)) return; - const revisionAtCommand = terminalCwdRevisionRef.current; + const osc7SignalAtCommand = terminalOsc7SignalBySessionRef.current.get(sessionId) ?? 0; const probeGeneration = (cwdProbeGenerationRef.current.get(sessionId) ?? 0) + 1; cwdProbeGenerationRef.current.set(sessionId, probeGeneration); cwdProbeCancelersRef.current.get(sessionId)?.(); const cancelProbe = scheduleBackendCwdProbeAfterCommand({ sessionId, - cwdRevisionAtCommand: revisionAtCommand, - getCwdRevision: () => terminalCwdRevisionRef.current, + osc7SignalAtCommand, + getOsc7Signal: () => terminalOsc7SignalBySessionRef.current.get(sessionId) ?? 0, getSessionPwd: (id, options) => terminalBackend.getSessionPwd(id, options), canProbe: async () => { if (cwdProbeGenerationRef.current.get(sessionId) !== probeGeneration) return false; diff --git a/components/terminal/osc7Setup.ts b/components/terminal/osc7Setup.ts index 43d4b6a88..e45292d53 100644 --- a/components/terminal/osc7Setup.ts +++ b/components/terminal/osc7Setup.ts @@ -79,7 +79,7 @@ __netcatty_osc7_url_path() { mkdir -p "$(dirname "$config")" touch "$config" if grep -F "$marker" "$config" >/dev/null 2>&1; then - printf "Netcatty OSC 7 cwd tracking is already configured in %s\n" "$config" + : else case "$shell_name" in bash) @@ -141,12 +141,10 @@ end NETCATTY_OSC7_FISH ;; esac - printf "Netcatty OSC 7 cwd tracking configured in %s\n" "$config" fi host=$(hostname 2>/dev/null || printf localhost) -printf '\033]7;file://%s%s\a' "$host" "$(__netcatty_osc7_url_path "$PWD")" -printf "\nRestart this shell, or open a new one, to keep tracking future directory changes.\n"`; +printf '\033]7;file://%s%s\a' "$host" "$(__netcatty_osc7_url_path "$PWD")"`; export const buildOsc7SetupCommand = (): string => `set +u 2>/dev/null || true; printf "%s\\n" ${quoteForSingleQuotedShellString(POSIX_SETUP_SCRIPT)} | env NETCATTY_ZDOTDIR="$ZDOTDIR" NETCATTY_XDG_CONFIG_HOME="$XDG_CONFIG_HOME" sh\n`; diff --git a/components/terminal/sftpCwd.test.ts b/components/terminal/sftpCwd.test.ts index 2f46ec3be..65d555b3d 100644 --- a/components/terminal/sftpCwd.test.ts +++ b/components/terminal/sftpCwd.test.ts @@ -93,12 +93,12 @@ test("terminal cwd tracker clears stale renderer cwd before falling back to back assert.equal(cwd, "/home/fresh-session"); }); -test("probeBackendSessionCwdAfterCommand skips when cwd revision already advanced", async () => { +test("probeBackendSessionCwdAfterCommand skips when OSC 7 already reported after command", async () => { let backendCalls = 0; const cwd = await probeBackendSessionCwdAfterCommand({ sessionId: "session-1", - cwdRevisionAtCommand: 1, - getCwdRevision: () => 2, + osc7SignalAtCommand: 1, + getOsc7Signal: () => 2, getSessionPwd: async () => { backendCalls += 1; return { success: true, cwd: "/tmp" }; @@ -109,11 +109,11 @@ test("probeBackendSessionCwdAfterCommand skips when cwd revision already advance assert.equal(backendCalls, 0); }); -test("probeBackendSessionCwdAfterCommand probes backend when revision is unchanged", async () => { +test("probeBackendSessionCwdAfterCommand probes backend when OSC 7 did not report", async () => { const cwd = await probeBackendSessionCwdAfterCommand({ sessionId: "session-1", - cwdRevisionAtCommand: 3, - getCwdRevision: () => 3, + osc7SignalAtCommand: 3, + getOsc7Signal: () => 3, getSessionPwd: async (sessionId) => { assert.equal(sessionId, "session-1"); return { success: true, cwd: "/var/log" }; @@ -122,3 +122,14 @@ test("probeBackendSessionCwdAfterCommand probes backend when revision is unchang assert.equal(cwd, "/var/log"); }); + +test("probeBackendSessionCwdAfterCommand still probes when cwd path is unchanged but OSC 7 did not fire", async () => { + const cwd = await probeBackendSessionCwdAfterCommand({ + sessionId: "session-1", + osc7SignalAtCommand: 5, + getOsc7Signal: () => 5, + getSessionPwd: async () => ({ success: true, cwd: "/srv/app" }), + }); + + assert.equal(cwd, "/srv/app"); +}); diff --git a/components/terminal/sftpCwd.ts b/components/terminal/sftpCwd.ts index 0c3176479..17305d424 100644 --- a/components/terminal/sftpCwd.ts +++ b/components/terminal/sftpCwd.ts @@ -67,27 +67,27 @@ export const PROBE_SESSION_CWD_AFTER_COMMAND_MS = 150; export type ProbeBackendSessionCwdAfterCommandOptions = { sessionId: string; - cwdRevisionAtCommand: number; - getCwdRevision: () => number; + osc7SignalAtCommand: number; + getOsc7Signal: () => number; getSessionPwd: (sessionId: string, options?: SessionPwdOptions) => Promise; canProbe?: () => boolean | Promise; }; -/** Probe backend pwd when OSC 7 did not update cwd after a command. */ +/** Probe backend pwd when OSC 7 did not report after a command. */ export const probeBackendSessionCwdAfterCommand = async ({ sessionId, - cwdRevisionAtCommand, - getCwdRevision, + osc7SignalAtCommand, + getOsc7Signal, getSessionPwd, canProbe = () => true, }: ProbeBackendSessionCwdAfterCommandOptions): Promise => { - if (getCwdRevision() !== cwdRevisionAtCommand) return null; + if (getOsc7Signal() !== osc7SignalAtCommand) return null; const allowed = await canProbe(); - if (!allowed || getCwdRevision() !== cwdRevisionAtCommand) return null; + if (!allowed || getOsc7Signal() !== osc7SignalAtCommand) return null; try { const result = await getSessionPwd(sessionId); - if (getCwdRevision() !== cwdRevisionAtCommand) return null; + if (getOsc7Signal() !== osc7SignalAtCommand) return null; return result.success ? normalizeCwd(result.cwd) : null; } catch { return null; diff --git a/components/terminal/terminalHelpers.ts b/components/terminal/terminalHelpers.ts index 5c5cdbd48..8cde79884 100644 --- a/components/terminal/terminalHelpers.ts +++ b/components/terminal/terminalHelpers.ts @@ -174,7 +174,7 @@ export interface TerminalProps { pendingUploadEntries?: DropEntry[], sourceSessionId?: string, ) => void; - onTerminalCwdChange?: (sessionId: string, cwd: string | null) => void; + onTerminalCwdChange?: (sessionId: string, cwd: string | null, meta?: { source?: 'osc7' }) => void; onTerminalTitleChange?: (sessionId: string, title: string | null) => void; onTerminalBell?: (sessionId: string) => void; onTerminalOutput?: (sessionId: string, chunk: string) => void; diff --git a/components/terminal/useTerminalEffects.ts b/components/terminal/useTerminalEffects.ts index 17f65c413..0fcf67fc6 100644 --- a/components/terminal/useTerminalEffects.ts +++ b/components/terminal/useTerminalEffects.ts @@ -280,7 +280,7 @@ export function useTerminalEffects(ctx: TerminalEffectsContext) { onCwdChange: (cwd: string) => { terminalCwdTracker.setRendererCwd(cwd); knownCwdRef.current = cwd; - onTerminalCwdChange?.(sessionId, cwd); + onTerminalCwdChange?.(sessionId, cwd, { source: 'osc7' }); }, onTitleChange: (title: string | null) => { onTerminalTitleChange?.(sessionId, title); diff --git a/components/terminalLayer/TerminalLayerSupport.tsx b/components/terminalLayer/TerminalLayerSupport.tsx index dbb450691..97d65ebcb 100644 --- a/components/terminalLayer/TerminalLayerSupport.tsx +++ b/components/terminalLayer/TerminalLayerSupport.tsx @@ -663,7 +663,7 @@ interface TerminalPaneProps { pendingUploadEntries?: DropEntry[], sourceSessionId?: string, ) => void; - onTerminalCwdChange: (sessionId: string, cwd: string | null) => void; + onTerminalCwdChange: (sessionId: string, cwd: string | null, meta?: { source?: 'osc7' }) => void; onTerminalTitleChange?: (sessionId: string, title: string | null) => void; onTerminalBell?: (sessionId: string) => void; onTerminalOutput?: (sessionId: string, chunk: string) => void; From c7de55007bc244d231fa0c4aabba3d1e5bde9b63 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 01:27:20 +0800 Subject: [PATCH 002/228] test: document OSC 7 probe suppression for unchanged cwd paths Co-authored-by: Cursor --- components/TerminalLayer.tsx | 4 ++++ components/terminal/sftpCwd.test.ts | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/components/TerminalLayer.tsx b/components/TerminalLayer.tsx index 3ff34f5d7..522871090 100644 --- a/components/TerminalLayer.tsx +++ b/components/TerminalLayer.tsx @@ -215,6 +215,10 @@ const TerminalLayerInner: React.FC = ({ meta?: { source?: 'osc7' }, ) => { if (meta?.source === 'osc7') { + // Bump on every OSC 7 report, even when the decoded path is unchanged. + // PROMPT_COMMAND/precmd emits OSC 7 after each command; skipping the + // backend pwd probe in that case prevents SFTP follow from toggling + // between OSC 7 cwd and login-shell fallback pwd (notably after sudo). const nextSignal = (terminalOsc7SignalBySessionRef.current.get(sessionId) ?? 0) + 1; terminalOsc7SignalBySessionRef.current.set(sessionId, nextSignal); } diff --git a/components/terminal/sftpCwd.test.ts b/components/terminal/sftpCwd.test.ts index 65d555b3d..90c0a20f5 100644 --- a/components/terminal/sftpCwd.test.ts +++ b/components/terminal/sftpCwd.test.ts @@ -123,6 +123,22 @@ test("probeBackendSessionCwdAfterCommand probes backend when OSC 7 did not repor assert.equal(cwd, "/var/log"); }); +test("probeBackendSessionCwdAfterCommand skips when OSC 7 confirms unchanged cwd after command", async () => { + let backendCalls = 0; + const cwd = await probeBackendSessionCwdAfterCommand({ + sessionId: "session-1", + osc7SignalAtCommand: 2, + getOsc7Signal: () => 3, + getSessionPwd: async () => { + backendCalls += 1; + return { success: true, cwd: "/home/user" }; + }, + }); + + assert.equal(cwd, null); + assert.equal(backendCalls, 0); +}); + test("probeBackendSessionCwdAfterCommand still probes when cwd path is unchanged but OSC 7 did not fire", async () => { const cwd = await probeBackendSessionCwdAfterCommand({ sessionId: "session-1", From a7c35f28139457dd62fcace620f5d610ba841fae Mon Sep 17 00:00:00 2001 From: mam15mon Date: Wed, 24 Jun 2026 11:09:08 +0800 Subject: [PATCH 003/228] add improved host search matching --- App.tsx | 22 +- components/QuickSwitcher.tsx | 52 ++- components/SelectHostPanel.tsx | 8 +- .../terminalLayer/TerminalHostTreeSidebar.tsx | 10 +- components/vault/useVaultHostCollections.tsx | 9 +- domain/searchMatcher.test.ts | 123 ++++++ lib/searchMatcher.ts | 352 ++++++++++++++++++ package-lock.json | 7 + package.json | 1 + 9 files changed, 548 insertions(+), 36 deletions(-) create mode 100644 domain/searchMatcher.test.ts create mode 100644 lib/searchMatcher.ts diff --git a/App.tsx b/App.tsx index 3fd7c23c0..8c0df87cc 100755 --- a/App.tsx +++ b/App.tsx @@ -59,6 +59,7 @@ import { VaultSection } from './components/VaultView'; import { KeyboardInteractiveRequest } from './components/KeyboardInteractiveModal'; import { PassphraseRequest } from './components/PassphraseModal'; import { classifyLocalShellType } from './lib/localShell'; +import { getHostSearchMatch } from './lib/searchMatcher'; import { useDiscoveredShells, resolveShellSetting } from './lib/useDiscoveredShells'; import { Host, HostProtocol, KnownHost, SerialConfig, Snippet, SSHKey, TerminalSession } from './types'; import { resolveSnippetCommand } from './components/SnippetExecutionProvider'; @@ -825,15 +826,18 @@ function App({ settings }: { settings: SettingsState }) { const quickResults = useMemo(() => { if (!isQuickSwitcherOpen) return []; - const term = quickSearch.trim().toLowerCase(); - const filtered = term - ? hosts.filter(h => - h.label.toLowerCase().includes(term) || - h.hostname.toLowerCase().includes(term) || - (h.group || '').toLowerCase().includes(term) - ) - : hosts; - return filtered; + const term = quickSearch.trim(); + if (!term) return hosts; + return hosts + .map((host) => ({ host, match: getHostSearchMatch(term, host) })) + .filter((entry) => entry.match.matched) + .sort((left, right) => { + if (left.match.score !== right.match.score) { + return right.match.score - left.match.score; + } + return left.host.label.localeCompare(right.host.label); + }) + .map((entry) => entry.host); }, [quickSearch, hosts, isQuickSwitcherOpen]); const handleDeleteHost = useCallback((hostId: string) => { diff --git a/components/QuickSwitcher.tsx b/components/QuickSwitcher.tsx index acad9dbc0..f23b3312b 100644 --- a/components/QuickSwitcher.tsx +++ b/components/QuickSwitcher.tsx @@ -11,6 +11,7 @@ import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from " import { useI18n } from "../application/i18n/I18nProvider"; import { Host, TerminalSession, Workspace } from "../types"; import { KeyBinding } from "../domain/models"; +import { matchesSearchQuery } from "../lib/searchMatcher"; import { useDiscoveredShells, getShellIconPath, isMonochromeShellIcon } from "../lib/useDiscoveredShells"; type QuickSwitcherItem = { @@ -96,7 +97,7 @@ const QuickSwitcherInner: React.FC = ({ const list = !query.trim() ? discoveredShells : discoveredShells.filter( - (s) => s.name.toLowerCase().includes(query.toLowerCase()) || s.id.toLowerCase().includes(query.toLowerCase()) + (s) => matchesSearchQuery(query, s.name, s.id) ); // Default shell first return [...list].sort((a, b) => (a.isDefault === b.isDefault ? 0 : a.isDefault ? -1 : 1)); @@ -150,6 +151,36 @@ const QuickSwitcherInner: React.FC = ({ () => sessions.filter((s) => !s.workspaceId), [sessions] ); + const trimmedQuery = query.trim(); + const builtInTabs = useMemo(() => { + if (!trimmedQuery) return showSftpTab ? ["vault", "sftp"] : ["vault"]; + const matched: string[] = []; + if (matchesSearchQuery(trimmedQuery, "Vaults", "vault", "hosts", "connections")) { + matched.push("vault"); + } + if (showSftpTab && matchesSearchQuery(trimmedQuery, "SFTP", "files", "transfer", "sftp")) { + matched.push("sftp"); + } + return matched; + }, [showSftpTab, trimmedQuery]); + const filteredOrphanSessions = useMemo(() => { + if (!trimmedQuery) return orphanSessions; + return orphanSessions.filter((session) => + matchesSearchQuery( + trimmedQuery, + session.hostLabel || "", + session.hostname || "", + session.id, + ), + ); + }, [orphanSessions, trimmedQuery]); + const filteredWorkspaces = useMemo(() => { + if (!trimmedQuery) return workspaces; + return workspaces.filter((workspace) => + matchesSearchQuery(trimmedQuery, workspace.title, workspace.id), + ); + }, [trimmedQuery, workspaces]); + const shouldShowLocalTerminalFallback = filteredShells.length === 0 && !!onCreateLocalTerminal && !trimmedQuery; // Always show categorized view (Hosts/Tabs/Quick connect) const showCategorized = true; @@ -164,12 +195,13 @@ const QuickSwitcherInner: React.FC = ({ items.push({ type: "host", id: host.id, data: host }), ); // Tabs (built-in + sessions + workspaces) - items.push({ type: "tab", id: "vault" }); - if (showSftpTab) items.push({ type: "tab", id: "sftp" }); - orphanSessions.forEach((s) => + builtInTabs.forEach((tabId) => { + items.push({ type: "tab", id: tabId }); + }); + filteredOrphanSessions.forEach((s) => items.push({ type: "tab", id: s.id, data: s }), ); - workspaces.forEach((w) => + filteredWorkspaces.forEach((w) => items.push({ type: "workspace", id: w.id, data: w }), ); // Local shells (or fallback action if discovery not ready) @@ -177,7 +209,7 @@ const QuickSwitcherInner: React.FC = ({ filteredShells.forEach((shell) => items.push({ type: "shell", id: shell.id }), ); - } else { + } else if (shouldShowLocalTerminalFallback) { items.push({ type: "action", id: "local-terminal" }); } } else { @@ -198,7 +230,7 @@ const QuickSwitcherInner: React.FC = ({ }); return { flatItems: items, itemIndexMap: indexMap }; - }, [showCategorized, results, orphanSessions, workspaces, filteredShells, showSftpTab]); + }, [showCategorized, results, builtInTabs, filteredOrphanSessions, filteredWorkspaces, filteredShells, shouldShowLocalTerminalFallback]); // O(1) index lookup const getItemIndex = useCallback((type: string, id: string) => { @@ -334,7 +366,7 @@ const QuickSwitcherInner: React.FC = ({ {/* Built-in tabs */} - {(showSftpTab ? ["vault", "sftp"] : ["vault"]).map((tabId) => { + {builtInTabs.map((tabId) => { const idx = getItemIndex("tab", tabId); const isSelected = idx === selectedIndex; const icon = @@ -365,7 +397,7 @@ const QuickSwitcherInner: React.FC = ({ })} {/* Workspaces */} - {workspaces.map((workspace) => { + {filteredWorkspaces.map((workspace) => { const idx = getItemIndex("workspace", workspace.id); const isSelected = idx === selectedIndex; @@ -391,7 +423,7 @@ const QuickSwitcherInner: React.FC = ({ })} {/* Orphan sessions */} - {orphanSessions.map((session) => { + {filteredOrphanSessions.map((session) => { const idx = getItemIndex("tab", session.id); const isSelected = idx === selectedIndex; diff --git a/components/SelectHostPanel.tsx b/components/SelectHostPanel.tsx index 67ee2851d..a191e5193 100644 --- a/components/SelectHostPanel.tsx +++ b/components/SelectHostPanel.tsx @@ -7,6 +7,7 @@ import { } from "lucide-react"; import React, { useMemo, useState } from "react"; import { cn } from "../lib/utils"; +import { matchesHostSearchQuery, matchesSearchQuery } from "../lib/searchMatcher"; import { useI18n } from "../application/i18n/I18nProvider"; import { Host, ProxyProfile, SSHKey } from "../types"; import { ManagedSource } from "../domain/models"; @@ -169,13 +170,10 @@ const SelectHostPanel: React.FC = ({ // Filter by search if (searchQuery) { - const q = searchQuery.toLowerCase(); result = result.filter( (h) => - h.label.toLowerCase().includes(q) || - h.hostname.toLowerCase().includes(q) || - h.username.toLowerCase().includes(q) || - (h.notes?.toLowerCase().includes(q) ?? false), + matchesHostSearchQuery(searchQuery, h) || + matchesSearchQuery(searchQuery, h.username, h.notes), ); } diff --git a/components/terminalLayer/TerminalHostTreeSidebar.tsx b/components/terminalLayer/TerminalHostTreeSidebar.tsx index c4936639e..b7833bb8b 100644 --- a/components/terminalLayer/TerminalHostTreeSidebar.tsx +++ b/components/terminalLayer/TerminalHostTreeSidebar.tsx @@ -37,6 +37,7 @@ import { STORAGE_KEY_VAULT_HOSTS_TREE_EXPANDED, } from '../../infrastructure/config/storageKeys'; import { cn } from '../../lib/utils'; +import { matchesHostSearchQuery, matchesSearchQuery } from '../../lib/searchMatcher'; import type { GroupConfig, GroupNode, Host, TerminalTheme } from '../../types'; import { HostTreeGroupContextMenuContent, HostTreeHostContextMenuContent } from '../host/HostTreeContextMenus'; import { HostTreeGroupInlineRenameInput } from '../host/HostTreeGroupInlineRenameInput'; @@ -199,13 +200,8 @@ export function getTerminalHostTreeMeasuredLayoutWidth( } function hostMatchesSearch(host: Host, search: string): boolean { - const s = search.toLowerCase(); - return ( - host.label.toLowerCase().includes(s) - || host.hostname.toLowerCase().includes(s) - || host.tags.some((tag) => tag.toLowerCase().includes(s)) - || (host.notes?.toLowerCase().includes(s) ?? false) - ); + return matchesHostSearchQuery(search, host) + || matchesSearchQuery(search, host.username, host.notes); } function filterGroupNode( diff --git a/components/vault/useVaultHostCollections.tsx b/components/vault/useVaultHostCollections.tsx index cb7cbf6ed..ecbe8cd66 100644 --- a/components/vault/useVaultHostCollections.tsx +++ b/components/vault/useVaultHostCollections.tsx @@ -2,6 +2,7 @@ import React, { useCallback, useMemo } from "react"; import { upsertKnownHost } from "../../domain/knownHosts"; import { sortByVaultOrder, sortVaultStringsByOrder } from "../../domain/vaultOrder"; +import { matchesHostSearchQuery, matchesSearchQuery } from "../../lib/searchMatcher"; import type { GroupConfig, GroupNode, Host, KnownHost } from "../../types"; import KnownHostsManager from "../KnownHostsManager"; import type { SortMode } from "../ui/sort-dropdown"; @@ -47,17 +48,15 @@ export function useVaultHostCollections({ ); }, [groupConfigs]); - const searchTerm = useMemo(() => search.trim().toLowerCase(), [search]); + const searchTerm = useMemo(() => search.trim(), [search]); const selectedTagSet = useMemo(() => new Set(selectedTags), [selectedTags]); const hasSelectedTags = selectedTags.length > 0; const hostMatchesSearchAndTags = useCallback((host: Host): boolean => { if (searchTerm) { const matchesSearch = - host.label.toLowerCase().includes(searchTerm) || - host.hostname.toLowerCase().includes(searchTerm) || - host.tags.some((tag) => tag.toLowerCase().includes(searchTerm)) || - (host.notes?.toLowerCase().includes(searchTerm) ?? false); + matchesHostSearchQuery(searchTerm, host) || + matchesSearchQuery(searchTerm, host.username, host.notes); if (!matchesSearch) return false; } if (hasSelectedTags && !host.tags?.some((tag) => selectedTagSet.has(tag))) { diff --git a/domain/searchMatcher.test.ts b/domain/searchMatcher.test.ts new file mode 100644 index 000000000..fa9a9e27c --- /dev/null +++ b/domain/searchMatcher.test.ts @@ -0,0 +1,123 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + getHostSearchMatch, + matchesHostSearchQuery, + matchesSearchQuery, +} from "../lib/searchMatcher.ts"; + +test("matches mixed Chinese and dash-separated numeric suffix with spaced query", () => { + assert.equal( + matchesSearchQuery("山东 6-1", "山东-业务交换机6-1"), + true, + ); +}); + +test("matches mixed Chinese and em-dash separator with spaced query", () => { + assert.equal( + matchesSearchQuery("山东 6-1", "山东—业务交换机6—1"), + true, + ); +}); + +test("matches IPv4-like query only on contiguous dotted address", () => { + assert.equal( + matchesSearchQuery("192.168.6.1", "192.168.6.1"), + true, + ); + assert.equal( + matchesSearchQuery("192.168.6.1", "192.168.16.10"), + false, + ); +}); + +test("matches compact form across separators", () => { + assert.equal( + matchesSearchQuery("prod api 01", "prod-api-01"), + true, + ); +}); + +test("host search does not mix human tokens with hostname IP tokens", () => { + assert.equal( + matchesHostSearchQuery("山东 6-1", { + label: "山东-业务交换机2-2", + hostname: "10.6.1.88", + group: "铁塔网络设备/山东", + tags: [], + }), + false, + ); +}); + +test("host search still supports direct IP matching", () => { + assert.equal( + matchesHostSearchQuery("10.6.1.88", { + label: "山东-业务交换机2-2", + hostname: "10.6.1.88", + group: "铁塔网络设备/山东", + tags: [], + }), + true, + ); +}); + +test("host search keeps trailing dash semantic and avoids loose numeric fallback", () => { + assert.equal( + matchesHostSearchQuery("山东 6-", { + label: "山东-IPMI交换机6", + hostname: "10.6.1.88", + group: "铁塔/山东", + tags: [], + }), + false, + ); + assert.equal( + matchesHostSearchQuery("山东 6-", { + label: "山东-管理交换机6-1", + hostname: "10.6.1.81", + group: "铁塔/山东", + tags: [], + }), + true, + ); +}); + +test("host search scoring prefers strict punctuation match over loose compact match", () => { + const strict = getHostSearchMatch("山东 6-", { + label: "山东-管理交换机6-1", + hostname: "10.6.1.81", + group: "铁塔/山东", + tags: [], + }); + const loose = getHostSearchMatch("山东 61", { + label: "山东-管理交换机6-1", + hostname: "10.6.1.81", + group: "铁塔/山东", + tags: [], + }); + assert.equal(strict.matched, true); + assert.equal(loose.matched, true); + assert.equal(strict.phase, "strict"); + assert.equal(loose.phase, "loose"); + assert.equal(strict.score > loose.score, true); +}); + +test("host search scoring favors label over group when both match", () => { + const labelHit = getHostSearchMatch("山东 6-1", { + label: "山东-业务交换机6-1", + hostname: "10.8.2.10", + group: "网络设备/核心", + tags: [], + }); + const groupHit = getHostSearchMatch("山东 6-1", { + label: "核心交换机", + hostname: "10.8.2.11", + group: "山东/业务交换机6-1", + tags: [], + }); + assert.equal(labelHit.matched, true); + assert.equal(groupHit.matched, true); + assert.equal(labelHit.score > groupHit.score, true); +}); diff --git a/lib/searchMatcher.ts b/lib/searchMatcher.ts new file mode 100644 index 000000000..d0bbc938e --- /dev/null +++ b/lib/searchMatcher.ts @@ -0,0 +1,352 @@ +import { pinyin } from "pinyin-pro"; + +const SEARCH_SPLIT_REGEX = /[\s\p{Pd}_/\\|.,,。;;::!!??()()[\]{}<>《》、"'`~·]+/u; +const SEARCH_REMOVE_REGEX = /[\s\p{Pd}_/\\|.,,。;;::!!??()()[\]{}<>《》、"'`~·]+/gu; +const SEARCH_QUERY_SEGMENT_SPLIT_REGEX = /\s+/u; +const SEARCH_QUERY_PUNCT_REGEX = /[\p{Pd}_/\\|.,,。;;::!!??()()[\]{}<>《》、"'`~·]/u; +const PINYIN_CACHE = new Map(); +const IPV4_LIKE_REGEX = /^\d{1,3}(?:\.\d{1,3})+$/; +const HOST_PHASE_SCORE_BONUS = { + strict: 1_000_000, + loose: 100_000, +} as const; +const HOST_FIELD_SCORE = { + label: 500, + hostname: 380, + group: 280, + tag: 220, +} as const; +const HOST_METHOD_SCORE = { + literal: 50, + compact: 25, + pinyinFull: 12, + pinyinInitials: 8, +} as const; + +function normalizeText(input: string): string { + return input.normalize("NFKC").toLowerCase().trim(); +} + +function compactText(input: string): string { + return normalizeText(input).replace(SEARCH_REMOVE_REGEX, ""); +} + +function getPinyinVariants(sourceText: string): { full: string; initials: string } { + const cacheKey = normalizeText(sourceText); + const cached = PINYIN_CACHE.get(cacheKey); + if (cached) return cached; + + let full = ""; + let initials = ""; + + try { + full = compactText( + pinyin(sourceText, { + toneType: "none", + }), + ); + initials = compactText( + pinyin(sourceText, { + pattern: "first", + toneType: "none", + }), + ); + } catch { + // ignore conversion failures + } + + const next = { full, initials }; + PINYIN_CACHE.set(cacheKey, next); + return next; +} + +export function tokenizeSearchQuery(query: string): string[] { + const normalized = normalizeText(query); + if (!normalized) return []; + return normalized.split(SEARCH_SPLIT_REGEX).filter(Boolean); +} + +export function matchesSearchQuery( + query: string, + ...fields: Array +): boolean { + const normalizedQuery = normalizeText(query); + if (!normalizedQuery) return true; + + const normalizedFields = fields + .filter((field): field is string => typeof field === "string" && field.trim().length > 0) + .map((field) => normalizeText(field)); + if (normalizedFields.length === 0) return false; + + // For dotted numeric input (IPv4-like), require contiguous literal match. + if (IPV4_LIKE_REGEX.test(normalizedQuery)) { + return normalizedFields.some((field) => field.includes(normalizedQuery)); + } + + const sourceText = normalizedFields.join(" "); + const haystack = sourceText; + if (haystack.includes(normalizedQuery)) { + return true; + } + + const haystackCompact = compactText(sourceText); + const compactQuery = compactText(normalizedQuery); + if (compactQuery && haystackCompact.includes(compactQuery)) { + return true; + } + + const tokens = tokenizeSearchQuery(normalizedQuery); + if (tokens.length === 0) return true; + + if (tokens.every((token) => haystack.includes(token))) { + return true; + } + + const hasLatinToken = tokens.some((token) => /[a-z]/i.test(token)); + if (!hasLatinToken) return false; + + const { full, initials } = getPinyinVariants(sourceText); + if (!full && !initials) return false; + + return tokens.every((token) => { + if (haystack.includes(token)) return true; + const compactToken = compactText(token); + return ( + (full && full.includes(compactToken)) || + (initials && initials.includes(compactToken)) + ); + }); +} + +/** + * Host search should avoid mixing label/group tokens with hostname/IP tokens. + * Otherwise queries like "山东 6-1" can accidentally match: + * - "山东" from group/label + * - "6" / "1" from hostname IP + * across different fields. + */ +export function matchesHostSearchQuery( + query: string, + hostLike: { + label?: string | null; + hostname?: string | null; + group?: string | null; + tags?: Array | null; + }, +): boolean { + return getHostSearchMatch(query, hostLike).matched; +} + +type HostMatchField = "label" | "hostname" | "group" | "tag"; +type HostMatchMethod = "literal" | "compact" | "pinyinFull" | "pinyinInitials"; +type HostMatchPhase = "strict" | "loose"; + +export type HostSearchMatchDetail = { + segment: string; + field: HostMatchField; + method: HostMatchMethod; + phase: HostMatchPhase; +}; + +export type HostSearchMatchResult = { + matched: boolean; + phase: HostMatchPhase | "none"; + score: number; + details: HostSearchMatchDetail[]; +}; + +type HostSearchFieldSource = { + field: HostMatchField; + allowPinyin: boolean; + text: string; + compact: string; +}; + +function scoreHostMatch(detail: HostSearchMatchDetail): number { + return HOST_FIELD_SCORE[detail.field] + HOST_METHOD_SCORE[detail.method]; +} + +function selectBetterHostMatch( + left: HostSearchMatchResult, + right: HostSearchMatchResult, +): HostSearchMatchResult { + if (!left.matched) return right; + if (!right.matched) return left; + if (left.score !== right.score) { + return left.score > right.score ? left : right; + } + if (left.details.length !== right.details.length) { + return left.details.length < right.details.length ? left : right; + } + return left; +} + +function matchSegmentAgainstSource( + segment: string, + source: HostSearchFieldSource, +): HostSearchMatchDetail | null { + if (source.text.includes(segment)) { + return { + segment, + field: source.field, + method: "literal", + phase: "strict", + }; + } + + // Keep punctuation semantic (e.g. 6-, 6-1, 10.6.1.8): no compact fallback. + if (SEARCH_QUERY_PUNCT_REGEX.test(segment)) return null; + + const compactSegment = compactText(segment); + if (compactSegment && source.compact.includes(compactSegment)) { + return { + segment, + field: source.field, + method: "compact", + phase: "loose", + }; + } + + if (!source.allowPinyin || !/[a-z]/i.test(segment)) return null; + + const { full, initials } = getPinyinVariants(source.text); + if (full && full.includes(compactSegment)) { + return { + segment, + field: source.field, + method: "pinyinFull", + phase: "loose", + }; + } + if (initials && initials.includes(compactSegment)) { + return { + segment, + field: source.field, + method: "pinyinInitials", + phase: "loose", + }; + } + + return null; +} + +function evaluateHostFieldGroup( + segments: string[], + sources: HostSearchFieldSource[], +): HostSearchMatchResult { + if (sources.length === 0) { + return { matched: false, phase: "none", score: 0, details: [] }; + } + + const details: HostSearchMatchDetail[] = []; + let isStrict = true; + + for (const segment of segments) { + let best: HostSearchMatchDetail | null = null; + let bestScore = -1; + + for (const source of sources) { + const detail = matchSegmentAgainstSource(segment, source); + if (!detail) continue; + + const score = scoreHostMatch(detail); + if (score > bestScore) { + best = detail; + bestScore = score; + } + } + + if (!best) { + return { matched: false, phase: "none", score: 0, details: [] }; + } + if (best.phase !== "strict") { + isStrict = false; + } + details.push(best); + } + + const phase: HostMatchPhase = isStrict ? "strict" : "loose"; + const baseScore = details.reduce((sum, detail) => sum + scoreHostMatch(detail), 0); + return { + matched: true, + phase, + score: baseScore + HOST_PHASE_SCORE_BONUS[phase], + details, + }; +} + +export function getHostSearchMatch( + query: string, + hostLike: { + label?: string | null; + hostname?: string | null; + group?: string | null; + tags?: Array | null; + }, +): HostSearchMatchResult { + const normalizedQuery = normalizeText(query); + if (!normalizedQuery) { + return { matched: true, phase: "strict", score: HOST_PHASE_SCORE_BONUS.strict, details: [] }; + } + + const querySegments = normalizedQuery + .split(SEARCH_QUERY_SEGMENT_SPLIT_REGEX) + .map((segment) => segment.trim()) + .filter(Boolean); + if (querySegments.length === 0) { + return { matched: true, phase: "strict", score: HOST_PHASE_SCORE_BONUS.strict, details: [] }; + } + + const label = normalizeText(hostLike.label ?? ""); + const group = normalizeText(hostLike.group ?? ""); + const hostname = normalizeText(hostLike.hostname ?? ""); + const tags = (hostLike.tags ?? []) + .filter((tag): tag is string => typeof tag === "string" && tag.trim().length > 0) + .map((tag) => normalizeText(tag)); + + const humanSources: HostSearchFieldSource[] = []; + if (label) { + humanSources.push({ + field: "label", + allowPinyin: true, + text: label, + compact: compactText(label), + }); + } + if (group) { + humanSources.push({ + field: "group", + allowPinyin: true, + text: group, + compact: compactText(group), + }); + } + for (const tag of tags) { + humanSources.push({ + field: "tag", + allowPinyin: true, + text: tag, + compact: compactText(tag), + }); + } + + const networkSources: HostSearchFieldSource[] = hostname + ? [{ + field: "hostname", + allowPinyin: false, + text: hostname, + compact: compactText(hostname), + }] + : []; + + const humanResult = evaluateHostFieldGroup(querySegments, humanSources); + const networkResult = evaluateHostFieldGroup(querySegments, networkSources); + return selectBetterHostMatch(humanResult, networkResult); +} + +export function getHostSearchReason(match: HostSearchMatchResult): string { + if (!match.matched || match.details.length === 0) return ""; + const uniqueFields = Array.from(new Set(match.details.map((detail) => detail.field))); + const phaseLabel = match.phase === "strict" ? "strict" : "loose"; + return `${phaseLabel}:${uniqueFields.join("/")}`; +} diff --git a/package-lock.json b/package-lock.json index ed0bb3f4e..2790f1df8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -46,6 +46,7 @@ "lucide-react": "0.560.0", "monaco-editor": "^0.55.1", "node-pty": "1.1.0", + "pinyin-pro": "^3.28.1", "react": "^19.2.1", "react-dom": "^19.2.1", "serialport": "^13.0.0", @@ -15883,6 +15884,12 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pinyin-pro": { + "version": "3.28.1", + "resolved": "https://registry.npmjs.org/pinyin-pro/-/pinyin-pro-3.28.1.tgz", + "integrity": "sha512-oqz8ulwRgtUXRi0vbqEfGNly19zpyCxYrjhkk5TibGcgSW6eNwS5woajCXRwqURi8Ehc2yOFTiB4uNoZ+NJOnA==", + "license": "MIT" + }, "node_modules/pkce-challenge": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", diff --git a/package.json b/package.json index 982f3d923..7cb1ec376 100644 --- a/package.json +++ b/package.json @@ -74,6 +74,7 @@ "lucide-react": "0.560.0", "monaco-editor": "^0.55.1", "node-pty": "1.1.0", + "pinyin-pro": "^3.28.1", "react": "^19.2.1", "react-dom": "^19.2.1", "serialport": "^13.0.0", From 977c5c56e1b5ac3cac9c8ad0500f51ebd19f2237 Mon Sep 17 00:00:00 2001 From: mam15mon Date: Wed, 24 Jun 2026 11:26:33 +0800 Subject: [PATCH 004/228] address search review feedback --- components/QuickSwitcher.tsx | 2 +- domain/searchMatcher.test.ts | 12 ++++++++++++ lib/searchMatcher.ts | 3 ++- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/components/QuickSwitcher.tsx b/components/QuickSwitcher.tsx index f23b3312b..d2bcce693 100644 --- a/components/QuickSwitcher.tsx +++ b/components/QuickSwitcher.tsx @@ -490,7 +490,7 @@ const QuickSwitcherInner: React.FC = ({ ); })} - ) : onCreateLocalTerminal && ( + ) : shouldShowLocalTerminalFallback && (
diff --git a/domain/searchMatcher.test.ts b/domain/searchMatcher.test.ts index fa9a9e27c..a8f6f5f39 100644 --- a/domain/searchMatcher.test.ts +++ b/domain/searchMatcher.test.ts @@ -51,6 +51,18 @@ test("host search does not mix human tokens with hostname IP tokens", () => { ); }); +test("host search treats equivalent dash separators as strict punctuation matches", () => { + const match = getHostSearchMatch("山东 6-1", { + label: "山东—业务交换机6—1", + hostname: "10.6.1.88", + group: "铁塔/山东", + tags: [], + }); + + assert.equal(match.matched, true); + assert.equal(match.phase, "strict"); +}); + test("host search still supports direct IP matching", () => { assert.equal( matchesHostSearchQuery("10.6.1.88", { diff --git a/lib/searchMatcher.ts b/lib/searchMatcher.ts index d0bbc938e..274874598 100644 --- a/lib/searchMatcher.ts +++ b/lib/searchMatcher.ts @@ -4,6 +4,7 @@ const SEARCH_SPLIT_REGEX = /[\s\p{Pd}_/\\|.,,。;;::!!??()()[\]{}< const SEARCH_REMOVE_REGEX = /[\s\p{Pd}_/\\|.,,。;;::!!??()()[\]{}<>《》、"'`~·]+/gu; const SEARCH_QUERY_SEGMENT_SPLIT_REGEX = /\s+/u; const SEARCH_QUERY_PUNCT_REGEX = /[\p{Pd}_/\\|.,,。;;::!!??()()[\]{}<>《》、"'`~·]/u; +const DASH_SEPARATOR_REGEX = /[\u2010-\u2015\u2212\uFE58\uFE63\uFF0D]/gu; const PINYIN_CACHE = new Map(); const IPV4_LIKE_REGEX = /^\d{1,3}(?:\.\d{1,3})+$/; const HOST_PHASE_SCORE_BONUS = { @@ -24,7 +25,7 @@ const HOST_METHOD_SCORE = { } as const; function normalizeText(input: string): string { - return input.normalize("NFKC").toLowerCase().trim(); + return input.normalize("NFKC").replace(DASH_SEPARATOR_REGEX, "-").toLowerCase().trim(); } function compactText(input: string): string { From b17835bf58793986f5a816495197b6339acaaf19 Mon Sep 17 00:00:00 2001 From: shixu Date: Wed, 24 Jun 2026 11:56:51 +0800 Subject: [PATCH 005/228] Fix GB18030 terminal decoding for locale charsets --- components/Terminal.tsx | 16 ++++++++++++++-- electron/bridges/sshBridge.cjs | 9 +++++++-- electron/bridges/sshBridge/sessionOps.cjs | 2 +- electron/bridges/sshBridge/startSession.cjs | 4 ++-- electron/bridges/terminalEncoding.cjs | 17 +++++++++++++---- electron/bridges/terminalEncoding.test.cjs | 4 ++++ 6 files changed, 41 insertions(+), 11 deletions(-) diff --git a/components/Terminal.tsx b/components/Terminal.tsx index 048a246ed..ce4adbbf6 100644 --- a/components/Terminal.tsx +++ b/components/Terminal.tsx @@ -95,6 +95,19 @@ import { } from "./terminal/terminalHelpers"; import { terminalPropsAreEqual } from "./terminal/terminalMemo"; +const resolveInitialTerminalEncoding = (charset?: string): 'utf-8' | 'gb18030' => { + if (!charset) return 'utf-8'; + const raw = String(charset).trim().toLowerCase(); + const localeCodeset = raw.match(/\.([^@]+)(?:@.*)?$/)?.[1]; + const candidates = [raw, localeCodeset].filter((value): value is string => Boolean(value)); + return candidates.some((candidate) => { + const normalized = candidate.replace(/[^a-z0-9]/g, ""); + return ["gb18030", "gbk", "gb2312", "cp936", "ms936"].includes(normalized); + }) + ? 'gb18030' + : 'utf-8'; +}; + const TerminalComponent: React.FC = ({ host, keys, @@ -319,8 +332,7 @@ const TerminalComponent: React.FC = ({ // pendingUploadEntries removed - drag-drop uploads now handled by SftpSidePanel const [isComposeBarOpen, setIsComposeBarOpen] = useState(false); const [terminalEncoding, setTerminalEncoding] = useState<'utf-8' | 'gb18030'>(() => { - if (host?.charset && /^gb/i.test(String(host.charset).trim())) return 'gb18030'; - return 'utf-8'; + return resolveInitialTerminalEncoding(host?.charset); }); const terminalEncodingRef = useRef(terminalEncoding); terminalEncodingRef.current = terminalEncoding; diff --git a/electron/bridges/sshBridge.cjs b/electron/bridges/sshBridge.cjs index f64f8f7d5..6e7db809c 100644 --- a/electron/bridges/sshBridge.cjs +++ b/electron/bridges/sshBridge.cjs @@ -392,7 +392,7 @@ const sessionEncodings = new Map(); // Per-session stateful iconv decoders (keyed by sessionId, value: { stdout, stderr }) const sessionDecoders = new Map(); const iconv = require("iconv-lite"); -const { encodeTerminalInput } = require("./terminalEncoding.cjs"); +const { encodeTerminalInput, normalizeTerminalEncoding } = require("./terminalEncoding.cjs"); function getSessionDecoder(sessionId, stream) { let decoders = sessionDecoders.get(sessionId); @@ -447,6 +447,9 @@ function resolveLangFromCharset(charset) { if (/^utf-?8$/i.test(trimmed) || /^utf8$/i.test(trimmed)) { return "en_US.UTF-8"; } + if (normalizeTerminalEncoding(trimmed) === "gb18030" && !trimmed.includes(".")) { + return "zh_CN.GB18030"; + } return trimmed; } @@ -802,6 +805,7 @@ const startSessionApi = createStartSessionApi({ createProxySocket, attachX11Forwarding, createPtyOutputBuffer, sessionLogStreamManager, trackSessionIdlePrompt, looksLikeIdleAutoLogout, createZmodemSentry, enableSshNoDelay, enableTcpNoDelay, iconv, getSessionDecoder, resetSessionDecoders, sessionEncodings, sessionDecoders, encodeTerminalInput, + normalizeTerminalEncoding, connectThroughChain, getAvailableAgentSocket, getCachedAuthMethod, setCachedAuthMethod, clearCachedAuthMethod, attachSshDebugLogger, logSshAlgorithms, resolveLangFromCharset, safeSend, zmodemOverwritePending, shouldLogSshDebugMessage, log, createSshDiagnosticLogger, @@ -1010,7 +1014,8 @@ const sessionOpsApi = createSessionOpsApi({ get sessions() { return sessions; }, get electronModule() { return electronModule; }, fs, path, os, exec, randomUUID, iconv, Buffer, process, console, setTimeout, clearTimeout, - getSessionDecoder, resetSessionDecoders, sessionEncodings, resolveLangFromCharset, safeSend, + getSessionDecoder, resetSessionDecoders, sessionEncodings, normalizeTerminalEncoding, + resolveLangFromCharset, safeSend, quoteShellArg, log, ensureMoshStatsConnection, ensureEtStatsConnection, execOnEtSession: (...args) => require("./terminalBridge.cjs").execOnEtSession(...args), getServerStats: undefined, diff --git a/electron/bridges/sshBridge/sessionOps.cjs b/electron/bridges/sshBridge/sessionOps.cjs index 6c89d5846..e59e567b7 100644 --- a/electron/bridges/sshBridge/sessionOps.cjs +++ b/electron/bridges/sshBridge/sessionOps.cjs @@ -1102,7 +1102,7 @@ function createSessionOpsApi(ctx) { if (!session || !session.stream) { return { ok: false, encoding: encoding || "utf-8" }; } - const enc = String(encoding || "utf-8").toLowerCase(); + const enc = normalizeTerminalEncoding(encoding); if (!iconv.encodingExists(enc)) { return { ok: false, encoding: enc }; } diff --git a/electron/bridges/sshBridge/startSession.cjs b/electron/bridges/sshBridge/startSession.cjs index f8cf3e581..c80cc2489 100644 --- a/electron/bridges/sshBridge/startSession.cjs +++ b/electron/bridges/sshBridge/startSession.cjs @@ -231,8 +231,8 @@ function createStartSessionApi(ctx) { // (Terminal.tsx) so behavior for other/arbitrary charsets is unchanged: // the renderer pushes the effective encoding via setEncoding on attach, // and that handler keeps both halves in sync. - const gbCharset = options.charset && /^gb/i.test(String(options.charset).trim()); - if (gbCharset) { + const initialEncoding = normalizeTerminalEncoding(options.charset); + if (initialEncoding === "gb18030") { sessionEncodings.set(sessionId, "gb18030"); session.encoding = "gb18030"; } diff --git a/electron/bridges/terminalEncoding.cjs b/electron/bridges/terminalEncoding.cjs index c74f7a076..c6e75655b 100644 --- a/electron/bridges/terminalEncoding.cjs +++ b/electron/bridges/terminalEncoding.cjs @@ -23,10 +23,19 @@ const iconv = require("iconv-lite"); function normalizeTerminalEncoding(charset) { if (!charset) return "utf-8"; const raw = String(charset).trim().toLowerCase(); - const normalized = raw.replace(/[^a-z0-9]/g, ""); - if (["utf8", "utf-8"].includes(normalized)) return "utf-8"; - if (normalized === "gb18030" || normalized === "gbk" || normalized === "gb2312") return "gb18030"; - return iconv.encodingExists(raw) ? raw : "utf-8"; + const localeCodeset = raw.match(/\.([^@]+)(?:@.*)?$/)?.[1]; + const candidates = [raw, localeCodeset].filter(Boolean); + + for (const candidate of candidates) { + const normalized = candidate.replace(/[^a-z0-9]/g, ""); + if (normalized === "utf8") return "utf-8"; + if (["gb18030", "gbk", "gb2312", "cp936", "ms936"].includes(normalized)) { + return "gb18030"; + } + if (iconv.encodingExists(candidate)) return candidate; + } + + return "utf-8"; } // True when the encoding is UTF-8 (the JS/Node default for string → bytes). diff --git a/electron/bridges/terminalEncoding.test.cjs b/electron/bridges/terminalEncoding.test.cjs index 2647874f7..d1f066f1a 100644 --- a/electron/bridges/terminalEncoding.test.cjs +++ b/electron/bridges/terminalEncoding.test.cjs @@ -12,6 +12,10 @@ test("normalizeTerminalEncoding maps GB variants onto the gb18030 superset", () assert.equal(normalizeTerminalEncoding("gbk"), "gb18030"); assert.equal(normalizeTerminalEncoding("GB2312"), "gb18030"); assert.equal(normalizeTerminalEncoding("gb-18030"), "gb18030"); + assert.equal(normalizeTerminalEncoding("zh_CN.GB18030"), "gb18030"); + assert.equal(normalizeTerminalEncoding("zh_CN.GBK"), "gb18030"); + assert.equal(normalizeTerminalEncoding("zh_CN.cp936"), "gb18030"); + assert.equal(normalizeTerminalEncoding("zh_CN.GB18030@custom"), "gb18030"); }); test("normalizeTerminalEncoding normalizes utf-8 spellings and defaults", () => { From 61a2473a7cd8b571927a1c4fe6cbda47b6f15729 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 13:13:57 +0800 Subject: [PATCH 006/228] feat(capabilities): shared agent capability layer for MCP and CLI (#1616) * feat(capabilities): add shared agent capability layer for MCP and CLI Introduce a registry-driven capability foundation so terminal, SFTP, vault, and port-forward tools can be extended from one policy and surface definition. Wire mcpServerBridge permission checks and the Skills CLI RPC client through the shared layer without changing existing AI runtime behavior. Co-authored-by: Cursor * fix(capabilities): restore SFTP cancel gating and home RPC timeout Match legacy mcpServerBridge behavior by blocking SFTP write RPCs after chat cancel and treating sftp/home as a long-running operation for timeout budget calculation. Co-authored-by: Cursor --------- Co-authored-by: Cursor --- electron/bridges/mcpServerBridge.cjs | 61 ++---- electron/capabilities/adapters/cliAdapter.cjs | 44 ++++ .../capabilities/adapters/cliAdapter.test.cjs | 24 ++ electron/capabilities/adapters/index.cjs | 9 + electron/capabilities/adapters/mcpAdapter.cjs | 38 ++++ .../capabilities/adapters/mcpAdapter.test.cjs | 33 +++ electron/capabilities/catalog/index.cjs | 24 ++ .../capabilities/catalog/integrity.test.cjs | 57 +++++ electron/capabilities/catalog/meta.cjs | 142 ++++++++++++ electron/capabilities/catalog/portforward.cjs | 89 ++++++++ electron/capabilities/catalog/sftp.cjs | 137 ++++++++++++ electron/capabilities/catalog/terminal.cjs | 89 ++++++++ electron/capabilities/catalog/vault.cjs | 127 +++++++++++ electron/capabilities/constants.cjs | 37 ++++ electron/capabilities/dispatch.cjs | 39 ++++ electron/capabilities/dispatch.test.cjs | 46 ++++ electron/capabilities/index.cjs | 25 +++ electron/capabilities/policy.cjs | 143 ++++++++++++ electron/capabilities/policy.test.cjs | 148 +++++++++++++ electron/capabilities/registry.cjs | 101 +++++++++ electron/capabilities/registry.test.cjs | 47 ++++ electron/capabilities/rpcTimeouts.cjs | 67 ++++++ electron/capabilities/rpcTimeouts.test.cjs | 57 +++++ electron/capabilities/rpcTransport.cjs | 190 ++++++++++++++++ electron/capabilities/rpcTransport.test.cjs | 113 ++++++++++ electron/capabilities/scope.cjs | 41 ++++ electron/capabilities/scope.test.cjs | 19 ++ electron/capabilities/services/index.cjs | 11 + .../capabilities/services/notImplemented.cjs | 18 ++ .../services/portforwardService.cjs | 20 ++ .../capabilities/services/vaultService.cjs | 22 ++ .../services/vaultService.test.cjs | 13 ++ electron/capabilities/types.cjs | 43 ++++ .../netcatty-tool-cli.capabilities.test.cjs | 17 ++ electron/cli/netcatty-tool-cli.cjs | 23 ++ electron/cli/netcattyRpcClient.cjs | 205 ++---------------- package.json | 2 +- 37 files changed, 2102 insertions(+), 219 deletions(-) create mode 100644 electron/capabilities/adapters/cliAdapter.cjs create mode 100644 electron/capabilities/adapters/cliAdapter.test.cjs create mode 100644 electron/capabilities/adapters/index.cjs create mode 100644 electron/capabilities/adapters/mcpAdapter.cjs create mode 100644 electron/capabilities/adapters/mcpAdapter.test.cjs create mode 100644 electron/capabilities/catalog/index.cjs create mode 100644 electron/capabilities/catalog/integrity.test.cjs create mode 100644 electron/capabilities/catalog/meta.cjs create mode 100644 electron/capabilities/catalog/portforward.cjs create mode 100644 electron/capabilities/catalog/sftp.cjs create mode 100644 electron/capabilities/catalog/terminal.cjs create mode 100644 electron/capabilities/catalog/vault.cjs create mode 100644 electron/capabilities/constants.cjs create mode 100644 electron/capabilities/dispatch.cjs create mode 100644 electron/capabilities/dispatch.test.cjs create mode 100644 electron/capabilities/index.cjs create mode 100644 electron/capabilities/policy.cjs create mode 100644 electron/capabilities/policy.test.cjs create mode 100644 electron/capabilities/registry.cjs create mode 100644 electron/capabilities/registry.test.cjs create mode 100644 electron/capabilities/rpcTimeouts.cjs create mode 100644 electron/capabilities/rpcTimeouts.test.cjs create mode 100644 electron/capabilities/rpcTransport.cjs create mode 100644 electron/capabilities/rpcTransport.test.cjs create mode 100644 electron/capabilities/scope.cjs create mode 100644 electron/capabilities/scope.test.cjs create mode 100644 electron/capabilities/services/index.cjs create mode 100644 electron/capabilities/services/notImplemented.cjs create mode 100644 electron/capabilities/services/portforwardService.cjs create mode 100644 electron/capabilities/services/vaultService.cjs create mode 100644 electron/capabilities/services/vaultService.test.cjs create mode 100644 electron/capabilities/types.cjs create mode 100644 electron/cli/netcatty-tool-cli.capabilities.test.cjs diff --git a/electron/bridges/mcpServerBridge.cjs b/electron/bridges/mcpServerBridge.cjs index 26b63ac32..c9204b40b 100644 --- a/electron/bridges/mcpServerBridge.cjs +++ b/electron/bridges/mcpServerBridge.cjs @@ -780,19 +780,12 @@ async function handleMessage(socket, line) { // ── RPC Dispatch ── -// Methods that modify remote state — blocked in observer mode -const WRITE_METHODS = new Set([ - "netcatty/exec", - "netcatty/sftp/write", - "netcatty/sftp/download", - "netcatty/sftp/upload", - "netcatty/sftp/mkdir", - "netcatty/sftp/delete", - "netcatty/sftp/rename", - "netcatty/sftp/chmod", - "netcatty/jobStart", - "netcatty/jobStop", -]); +const { + evaluateRpcPermission, + USER_DENIED_MESSAGE, +} = require("../capabilities/policy.cjs"); +const { CAPABILITY_SURFACES } = require("../capabilities/constants.cjs"); +const { getCapabilityByRpcMethod } = require("../capabilities/registry.cjs"); /** * Validate that a sessionId is allowed in the current scope. @@ -822,29 +815,23 @@ function validateSessionScope(sessionId, chatSessionId, explicitScopedIds = null async function dispatch(method, params) { debugLog("dispatch", { method, params, permissionMode }); - const sessionWriteLockId = (method === "netcatty/exec" || method === "netcatty/jobStart") ? params?.sessionId : null; + const capability = getCapabilityByRpcMethod(method, CAPABILITY_SURFACES.BUILTIN); + const sessionWriteLockId = (capability?.id === "terminal.execute" || capability?.id === "terminal.start") + ? params?.sessionId + : null; pruneCompletedBackgroundJobs(); - // Observer mode: block all write operations *except* netcatty/jobStop, - // which must remain available so users can interrupt long-running jobs - // they started before switching to observer mode (otherwise the job - // would hold the per-session lock until it exits on its own). - if (permissionMode === "observer" && WRITE_METHODS.has(method) && method !== "netcatty/jobStop") { - return { ok: false, error: `Operation denied: permission mode is "observer" (read-only). Change to "confirm" or "autonomous" in Settings → AI → Safety to allow this action.` }; - } - - if (WRITE_METHODS.has(method) && !params?.chatSessionId) { - return { - ok: false, - error: "chatSessionId is required for write operations.", - }; - } - - // netcatty/jobStop must remain callable after SDK agent cancel so users can stop - // a long-running terminal_start job (which intentionally survives SDK Stop) - // even from a chat session whose write methods are otherwise blocked. - if (WRITE_METHODS.has(method) && method !== "netcatty/jobStop" && isChatSessionCancelled(params?.chatSessionId)) { - return { ok: false, error: "Operation cancelled: the SDK agent session was stopped." }; + const permission = evaluateRpcPermission({ + rpcMethod: method, + surface: CAPABILITY_SURFACES.BUILTIN, + permissionMode, + params, + context: { + chatSessionCancelled: isChatSessionCancelled(params?.chatSessionId), + }, + }); + if (!permission.allowed) { + return { ok: false, error: permission.error }; } // Validate session scope *first* so out-of-scope callers cannot infer the @@ -855,7 +842,7 @@ async function dispatch(method, params) { if (scopeErr) return { ok: false, error: scopeErr }; } - if ((method === "netcatty/exec" || method === "netcatty/jobStart") && params?.sessionId) { + if ((capability?.id === "terminal.execute" || capability?.id === "terminal.start") && params?.sessionId) { const busy = getSessionBusyError(params.sessionId); if (busy) return busy; } @@ -876,11 +863,11 @@ async function dispatch(method, params) { // netcatty/jobStop bypasses approval — it's a stop/cancel action that // must remain available even if the renderer is unavailable; otherwise // a runaway terminal_start job could not be interrupted at all. - if (permissionMode === "confirm" && WRITE_METHODS.has(method) && method !== "netcatty/jobStop") { + if (permission.requiresApproval) { const { chatSessionId, ...toolArgs } = params || {}; const approved = await requestApprovalFromRenderer(method, toolArgs, chatSessionId); if (!approved) { - return { ok: false, error: "Operation denied by user." }; + return { ok: false, error: USER_DENIED_MESSAGE }; } } switch (method) { diff --git a/electron/capabilities/adapters/cliAdapter.cjs b/electron/capabilities/adapters/cliAdapter.cjs new file mode 100644 index 000000000..31dba5f88 --- /dev/null +++ b/electron/capabilities/adapters/cliAdapter.cjs @@ -0,0 +1,44 @@ +"use strict"; + +const { CAPABILITY_STATUS, CAPABILITY_SURFACES } = require("../constants.cjs"); +const { + getCapabilityByCliCommand, + listCapabilities, +} = require("../registry.cjs"); + +function getCliRpcMethod(commandParts) { + const capability = getCapabilityByCliCommand(commandParts); + if (!capability) return null; + return capability.surfaces?.[CAPABILITY_SURFACES.BUILTIN]?.rpcMethod || null; +} + +function listCliCapabilities(options = {}) { + const surface = options.surface || CAPABILITY_SURFACES.CLI; + const status = Object.prototype.hasOwnProperty.call(options, "status") + ? options.status + : CAPABILITY_STATUS.IMPLEMENTED; + return listCapabilities({ surface, status: status || undefined }) + .filter((capability) => Array.isArray(capability.surfaces?.[surface]?.command)) + .map((capability) => ({ + id: capability.id, + domain: capability.domain, + status: capability.status, + description: capability.description, + command: capability.surfaces[surface].command, + rpcMethod: capability.surfaces?.[CAPABILITY_SURFACES.BUILTIN]?.rpcMethod || null, + policy: capability.policy, + })); +} + +function formatCliHelpLines(options = {}) { + return listCliCapabilities(options).flatMap((entry) => { + const statusSuffix = entry.status === CAPABILITY_STATUS.PLANNED ? " (planned)" : ""; + return [` netcatty-tool-cli ${entry.command.join(" ")}${statusSuffix}`]; + }); +} + +module.exports = { + getCliRpcMethod, + listCliCapabilities, + formatCliHelpLines, +}; diff --git a/electron/capabilities/adapters/cliAdapter.test.cjs b/electron/capabilities/adapters/cliAdapter.test.cjs new file mode 100644 index 000000000..a0ba57dfb --- /dev/null +++ b/electron/capabilities/adapters/cliAdapter.test.cjs @@ -0,0 +1,24 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { getCliRpcMethod, listCliCapabilities } = require("./cliAdapter.cjs"); +const { CAPABILITY_STATUS } = require("../constants.cjs"); + +test("getCliRpcMethod resolves implemented cli commands to builtin rpc methods", () => { + assert.equal(getCliRpcMethod(["exec"]), "netcatty/exec"); + assert.equal(getCliRpcMethod(["sftp", "list"]), "netcatty/sftp/list"); + assert.equal(getCliRpcMethod(["capabilities"]), null); +}); + +test("listCliCapabilities returns implemented commands by default", () => { + const entries = listCliCapabilities(); + assert.ok(entries.some((entry) => entry.id === "terminal.execute")); + assert.ok(entries.every((entry) => entry.status === CAPABILITY_STATUS.IMPLEMENTED)); +}); + +test("listCliCapabilities can include planned commands", () => { + const entries = listCliCapabilities({ status: CAPABILITY_STATUS.PLANNED }); + assert.ok(entries.some((entry) => entry.id === "vault.host.notes.get")); +}); diff --git a/electron/capabilities/adapters/index.cjs b/electron/capabilities/adapters/index.cjs new file mode 100644 index 000000000..c7fd0137b --- /dev/null +++ b/electron/capabilities/adapters/index.cjs @@ -0,0 +1,9 @@ +"use strict"; + +const cliAdapter = require("./cliAdapter.cjs"); +const mcpAdapter = require("./mcpAdapter.cjs"); + +module.exports = { + ...cliAdapter, + ...mcpAdapter, +}; diff --git a/electron/capabilities/adapters/mcpAdapter.cjs b/electron/capabilities/adapters/mcpAdapter.cjs new file mode 100644 index 000000000..78616ea86 --- /dev/null +++ b/electron/capabilities/adapters/mcpAdapter.cjs @@ -0,0 +1,38 @@ +"use strict"; + +const { CAPABILITY_STATUS, CAPABILITY_SURFACES } = require("../constants.cjs"); +const { + getCapabilityByMcpTool, + getCapabilityByRpcMethod, + listCapabilities, +} = require("../registry.cjs"); + +function listMcpTools(surface = CAPABILITY_SURFACES.BUILTIN, options = {}) { + const status = options.status || CAPABILITY_STATUS.IMPLEMENTED; + return listCapabilities({ surface, status }) + .filter((capability) => capability.surfaces?.[surface]?.mcpTool) + .map((capability) => ({ + id: capability.id, + toolName: capability.surfaces[surface].mcpTool, + rpcMethod: capability.surfaces[surface].rpcMethod, + description: capability.description, + policy: capability.policy, + status: capability.status, + })); +} + +function getMcpToolRpcMethod(toolName, surface = CAPABILITY_SURFACES.BUILTIN) { + const capability = getCapabilityByMcpTool(toolName, surface); + return capability?.surfaces?.[surface]?.rpcMethod || null; +} + +function getMcpToolNameForRpcMethod(rpcMethod, surface = CAPABILITY_SURFACES.BUILTIN) { + const capability = getCapabilityByRpcMethod(rpcMethod, surface); + return capability?.surfaces?.[surface]?.mcpTool || null; +} + +module.exports = { + listMcpTools, + getMcpToolRpcMethod, + getMcpToolNameForRpcMethod, +}; diff --git a/electron/capabilities/adapters/mcpAdapter.test.cjs b/electron/capabilities/adapters/mcpAdapter.test.cjs new file mode 100644 index 000000000..79f363563 --- /dev/null +++ b/electron/capabilities/adapters/mcpAdapter.test.cjs @@ -0,0 +1,33 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { + listMcpTools, + getMcpToolRpcMethod, + getMcpToolNameForRpcMethod, +} = require("./mcpAdapter.cjs"); +const { CAPABILITY_SURFACES } = require("../constants.cjs"); + +test("listMcpTools exposes builtin terminal tools", () => { + const tools = listMcpTools(CAPABILITY_SURFACES.BUILTIN); + assert.ok(tools.some((tool) => tool.toolName === "terminal_execute")); + assert.ok(tools.every((tool) => tool.rpcMethod)); +}); + +test("getMcpToolRpcMethod resolves tool names", () => { + assert.equal( + getMcpToolRpcMethod("terminal_execute", CAPABILITY_SURFACES.BUILTIN), + "netcatty/exec", + ); +}); + +test("public surface includes sftp tools for future public mcp registration", () => { + const tools = listMcpTools(CAPABILITY_SURFACES.PUBLIC); + assert.ok(tools.some((tool) => tool.toolName === "sftp_list")); + assert.equal( + getMcpToolNameForRpcMethod("public/sftp/list", CAPABILITY_SURFACES.PUBLIC), + "sftp_list", + ); +}); diff --git a/electron/capabilities/catalog/index.cjs b/electron/capabilities/catalog/index.cjs new file mode 100644 index 000000000..c353c96ac --- /dev/null +++ b/electron/capabilities/catalog/index.cjs @@ -0,0 +1,24 @@ +"use strict"; + +const { META_CAPABILITIES } = require("./meta.cjs"); +const { TERMINAL_CAPABILITIES } = require("./terminal.cjs"); +const { SFTP_CAPABILITIES } = require("./sftp.cjs"); +const { VAULT_CAPABILITIES } = require("./vault.cjs"); +const { PORT_FORWARD_CAPABILITIES } = require("./portforward.cjs"); + +const ALL_CAPABILITIES = Object.freeze([ + ...META_CAPABILITIES, + ...TERMINAL_CAPABILITIES, + ...SFTP_CAPABILITIES, + ...VAULT_CAPABILITIES, + ...PORT_FORWARD_CAPABILITIES, +]); + +module.exports = { + META_CAPABILITIES, + TERMINAL_CAPABILITIES, + SFTP_CAPABILITIES, + VAULT_CAPABILITIES, + PORT_FORWARD_CAPABILITIES, + ALL_CAPABILITIES, +}; diff --git a/electron/capabilities/catalog/integrity.test.cjs b/electron/capabilities/catalog/integrity.test.cjs new file mode 100644 index 000000000..8f7899412 --- /dev/null +++ b/electron/capabilities/catalog/integrity.test.cjs @@ -0,0 +1,57 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { ALL_CAPABILITIES } = require("../index.cjs"); +const { CAPABILITY_STATUS, CAPABILITY_SURFACES } = require("../constants.cjs"); +const { getCliRpcMethod } = require("../adapters/cliAdapter.cjs"); + +const IMPLEMENTED_CLI_COMMANDS = [ + ["status"], + ["env"], + ["session"], + ["exec"], + ["job-start"], + ["job-poll"], + ["job-stop"], + ["sftp", "list"], + ["sftp", "read"], + ["sftp", "write"], + ["sftp", "download"], + ["sftp", "upload"], + ["sftp", "mkdir"], + ["sftp", "delete"], + ["sftp", "rename"], + ["sftp", "stat"], + ["sftp", "chmod"], + ["sftp", "home"], + ["cancel"], + ["resume"], +]; + +test("every implemented cli command maps to a builtin rpc method", () => { + for (const command of IMPLEMENTED_CLI_COMMANDS) { + const rpcMethod = getCliRpcMethod(command); + assert.ok(rpcMethod, `missing rpc mapping for ${command.join(" ")}`); + } +}); + +test("implemented capabilities expose at least one surface binding", () => { + for (const capability of ALL_CAPABILITIES) { + if (capability.status !== CAPABILITY_STATUS.IMPLEMENTED) continue; + const surfaces = Object.keys(capability.surfaces || {}); + 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); + assert.ok( + hasRpc || hasCli || capability.surfaces[CAPABILITY_SURFACES.BUILTIN]?.mcpTool, + `${capability.id} has no rpc/cli/mcp binding`, + ); + } +}); + +test("capability ids are unique", () => { + const ids = ALL_CAPABILITIES.map((capability) => capability.id); + assert.equal(new Set(ids).size, ids.length); +}); diff --git a/electron/capabilities/catalog/meta.cjs b/electron/capabilities/catalog/meta.cjs new file mode 100644 index 000000000..e37cbb9e0 --- /dev/null +++ b/electron/capabilities/catalog/meta.cjs @@ -0,0 +1,142 @@ +"use strict"; + +const { CAPABILITY_STATUS } = require("../constants.cjs"); + +/** @type {import("../types.cjs").CapabilityDefinition[]} */ +const META_CAPABILITIES = [ + { + id: "session.environment", + domain: "session", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "List scoped terminal sessions available to the agent.", + policy: { + write: false, + sensitiveRead: false, + longRunning: false, + requiresChatSession: true, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + builtin: { rpcMethod: "netcatty/getContext", mcpTool: "get_environment" }, + public: { rpcMethod: "public/getEnvironment", mcpTool: "get_environment" }, + cli: { command: ["env"] }, + }, + }, + { + id: "meta.status", + domain: "meta", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Return bridge runtime status and policy configuration.", + policy: { + write: false, + sensitiveRead: false, + longRunning: false, + requiresChatSession: false, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + builtin: { rpcMethod: "netcatty/getStatus" }, + public: { rpcMethod: "public/getStatus" }, + cli: { command: ["status"] }, + }, + }, + { + id: "attachment.list", + domain: "attachment", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "List user-attached files in the current AI chat scope.", + policy: { + write: false, + sensitiveRead: false, + longRunning: false, + requiresChatSession: true, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + builtin: { rpcMethod: "netcatty/listAttachments", mcpTool: "list_attachments" }, + }, + }, + { + id: "attachment.read", + domain: "attachment", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Read a user-attached file from the current AI chat scope.", + policy: { + write: false, + sensitiveRead: true, + longRunning: false, + requiresChatSession: true, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + builtin: { rpcMethod: "netcatty/readAttachment", mcpTool: "read_attachment" }, + }, + }, + { + id: "session.cancel", + domain: "session", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Cancel in-flight operations for a chat session.", + policy: { + write: false, + sensitiveRead: false, + longRunning: false, + requiresChatSession: true, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + builtin: { rpcMethod: "netcatty/setCancelled" }, + cli: { command: ["cancel"] }, + }, + }, + { + id: "session.resume", + domain: "session", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Resume write operations for a cancelled chat session.", + policy: { + write: false, + sensitiveRead: false, + longRunning: false, + requiresChatSession: true, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + builtin: { rpcMethod: "netcatty/setCancelled" }, + cli: { command: ["resume"] }, + }, + }, + { + id: "session.get", + domain: "session", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Get metadata for a single scoped session.", + policy: { + write: false, + sensitiveRead: false, + longRunning: false, + requiresChatSession: true, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + builtin: { rpcMethod: "netcatty/getContext" }, + cli: { command: ["session"] }, + }, + }, +]; + +module.exports = { META_CAPABILITIES }; diff --git a/electron/capabilities/catalog/portforward.cjs b/electron/capabilities/catalog/portforward.cjs new file mode 100644 index 000000000..a9375a3b3 --- /dev/null +++ b/electron/capabilities/catalog/portforward.cjs @@ -0,0 +1,89 @@ +"use strict"; + +const { CAPABILITY_STATUS } = require("../constants.cjs"); + +/** @type {import("../types.cjs").CapabilityDefinition[]} */ +const PORT_FORWARD_CAPABILITIES = [ + { + id: "portforward.rules.list", + domain: "portforward", + status: CAPABILITY_STATUS.PLANNED, + description: "List persisted port forwarding rules.", + policy: { + write: false, + sensitiveRead: false, + longRunning: false, + requiresChatSession: false, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + cli: { command: ["portforward", "rules", "list"] }, + global: { rpcMethod: "portforward/rules/list" }, + public: { rpcMethod: "public/portforward/rules/list", mcpTool: "portforward_rules_list" }, + }, + }, + { + id: "portforward.tunnels.list", + domain: "portforward", + status: CAPABILITY_STATUS.PLANNED, + description: "List active port forwarding tunnels.", + policy: { + write: false, + sensitiveRead: false, + longRunning: false, + requiresChatSession: false, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + cli: { command: ["portforward", "tunnels", "list"] }, + global: { rpcMethod: "portforward/tunnels/list" }, + public: { rpcMethod: "public/portforward/tunnels/list", mcpTool: "portforward_tunnels_list" }, + }, + }, + { + id: "portforward.start", + domain: "portforward", + status: CAPABILITY_STATUS.PLANNED, + description: "Start a port forwarding tunnel for a rule.", + policy: { + write: true, + sensitiveRead: false, + longRunning: true, + requiresChatSession: false, + bypassesObserverBlock: false, + bypassesApproval: false, + bypassesChatCancel: false, + }, + surfaces: { + cli: { command: ["portforward", "start"] }, + global: { rpcMethod: "portforward/start" }, + public: { rpcMethod: "public/portforward/start", mcpTool: "portforward_start" }, + }, + }, + { + id: "portforward.stop", + domain: "portforward", + status: CAPABILITY_STATUS.PLANNED, + description: "Stop an active port forwarding tunnel.", + policy: { + write: true, + sensitiveRead: false, + longRunning: false, + requiresChatSession: false, + bypassesObserverBlock: false, + bypassesApproval: false, + bypassesChatCancel: false, + }, + surfaces: { + cli: { command: ["portforward", "stop"] }, + global: { rpcMethod: "portforward/stop" }, + public: { rpcMethod: "public/portforward/stop", mcpTool: "portforward_stop" }, + }, + }, +]; + +module.exports = { PORT_FORWARD_CAPABILITIES }; diff --git a/electron/capabilities/catalog/sftp.cjs b/electron/capabilities/catalog/sftp.cjs new file mode 100644 index 000000000..200522c09 --- /dev/null +++ b/electron/capabilities/catalog/sftp.cjs @@ -0,0 +1,137 @@ +"use strict"; + +const { CAPABILITY_STATUS } = require("../constants.cjs"); + +function sftpCapability(id, description, policyOverrides, surfaces) { + return { + id, + domain: "sftp", + status: CAPABILITY_STATUS.IMPLEMENTED, + description, + policy: { + write: false, + sensitiveRead: false, + longRunning: true, + requiresChatSession: true, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + ...policyOverrides, + }, + surfaces, + }; +} + +/** @type {import("../types.cjs").CapabilityDefinition[]} */ +const SFTP_CAPABILITIES = [ + sftpCapability( + "sftp.list", + "List a remote directory over SFTP.", + { sensitiveRead: true }, + { + builtin: { rpcMethod: "netcatty/sftp/list" }, + public: { rpcMethod: "public/sftp/list", mcpTool: "sftp_list", confirmInConfirmMode: true }, + cli: { command: ["sftp", "list"] }, + }, + ), + sftpCapability( + "sftp.read", + "Read a remote file over SFTP.", + { sensitiveRead: true }, + { + builtin: { rpcMethod: "netcatty/sftp/read" }, + public: { rpcMethod: "public/sftp/readFile", mcpTool: "sftp_read_file", confirmInConfirmMode: true }, + cli: { command: ["sftp", "read"] }, + }, + ), + sftpCapability( + "sftp.write", + "Write a remote file over SFTP.", + { write: true, bypassesApproval: false, bypassesChatCancel: false }, + { + builtin: { rpcMethod: "netcatty/sftp/write" }, + public: { rpcMethod: "public/sftp/writeFile", mcpTool: "sftp_write_file" }, + cli: { command: ["sftp", "write"] }, + }, + ), + sftpCapability( + "sftp.download", + "Download a remote file to a local path.", + { write: true, bypassesApproval: false, bypassesChatCancel: false }, + { + builtin: { rpcMethod: "netcatty/sftp/download" }, + cli: { command: ["sftp", "download"] }, + }, + ), + sftpCapability( + "sftp.upload", + "Upload a local file to a remote path.", + { write: true, bypassesApproval: false, bypassesChatCancel: false }, + { + builtin: { rpcMethod: "netcatty/sftp/upload" }, + cli: { command: ["sftp", "upload"] }, + }, + ), + sftpCapability( + "sftp.stat", + "Get remote file metadata over SFTP.", + { sensitiveRead: true }, + { + builtin: { rpcMethod: "netcatty/sftp/stat" }, + public: { rpcMethod: "public/sftp/stat", mcpTool: "sftp_stat", confirmInConfirmMode: true }, + cli: { command: ["sftp", "stat"] }, + }, + ), + sftpCapability( + "sftp.home", + "Get the remote home directory for a session.", + { sensitiveRead: true }, + { + builtin: { rpcMethod: "netcatty/sftp/home" }, + public: { rpcMethod: "public/sftp/home", mcpTool: "sftp_home", confirmInConfirmMode: true }, + cli: { command: ["sftp", "home"] }, + }, + ), + sftpCapability( + "sftp.mkdir", + "Create a remote directory over SFTP.", + { write: true, bypassesApproval: false, bypassesChatCancel: false }, + { + builtin: { rpcMethod: "netcatty/sftp/mkdir" }, + public: { rpcMethod: "public/sftp/mkdir", mcpTool: "sftp_mkdir" }, + cli: { command: ["sftp", "mkdir"] }, + }, + ), + sftpCapability( + "sftp.delete", + "Delete a remote file or directory over SFTP.", + { write: true, bypassesApproval: false, bypassesChatCancel: false }, + { + builtin: { rpcMethod: "netcatty/sftp/delete" }, + public: { rpcMethod: "public/sftp/delete", mcpTool: "sftp_delete" }, + cli: { command: ["sftp", "delete"] }, + }, + ), + sftpCapability( + "sftp.rename", + "Rename a remote file or directory over SFTP.", + { write: true, bypassesApproval: false, bypassesChatCancel: false }, + { + builtin: { rpcMethod: "netcatty/sftp/rename" }, + public: { rpcMethod: "public/sftp/rename", mcpTool: "sftp_rename" }, + cli: { command: ["sftp", "rename"] }, + }, + ), + sftpCapability( + "sftp.chmod", + "Change remote file permissions over SFTP.", + { write: true, bypassesApproval: false, bypassesChatCancel: false }, + { + builtin: { rpcMethod: "netcatty/sftp/chmod" }, + public: { rpcMethod: "public/sftp/chmod", mcpTool: "sftp_chmod" }, + cli: { command: ["sftp", "chmod"] }, + }, + ), +]; + +module.exports = { SFTP_CAPABILITIES }; diff --git a/electron/capabilities/catalog/terminal.cjs b/electron/capabilities/catalog/terminal.cjs new file mode 100644 index 000000000..e74ac9647 --- /dev/null +++ b/electron/capabilities/catalog/terminal.cjs @@ -0,0 +1,89 @@ +"use strict"; + +const { CAPABILITY_STATUS } = require("../constants.cjs"); + +/** @type {import("../types.cjs").CapabilityDefinition[]} */ +const TERMINAL_CAPABILITIES = [ + { + id: "terminal.execute", + domain: "terminal", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Execute a short command in a terminal session and wait for completion.", + policy: { + write: true, + sensitiveRead: false, + longRunning: true, + requiresChatSession: true, + bypassesObserverBlock: false, + bypassesApproval: false, + bypassesChatCancel: false, + }, + surfaces: { + builtin: { rpcMethod: "netcatty/exec", mcpTool: "terminal_execute" }, + public: { rpcMethod: "public/terminalExecute", mcpTool: "terminal_execute" }, + cli: { command: ["exec"] }, + }, + }, + { + id: "terminal.start", + domain: "terminal", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Start a long-running command in a terminal session.", + policy: { + write: true, + sensitiveRead: false, + longRunning: true, + requiresChatSession: true, + bypassesObserverBlock: false, + bypassesApproval: false, + bypassesChatCancel: false, + }, + surfaces: { + builtin: { rpcMethod: "netcatty/jobStart", mcpTool: "terminal_start" }, + public: { rpcMethod: "public/terminalStart", mcpTool: "terminal_start" }, + cli: { command: ["job-start"] }, + }, + }, + { + id: "terminal.poll", + domain: "terminal", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Poll incremental output from a long-running terminal job.", + policy: { + write: false, + sensitiveRead: false, + longRunning: false, + requiresChatSession: true, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + builtin: { rpcMethod: "netcatty/jobPoll", mcpTool: "terminal_poll" }, + public: { rpcMethod: "public/terminalPoll", mcpTool: "terminal_poll" }, + cli: { command: ["job-poll"] }, + }, + }, + { + id: "terminal.stop", + domain: "terminal", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Stop a long-running terminal job.", + policy: { + write: true, + sensitiveRead: false, + longRunning: false, + requiresChatSession: true, + bypassesObserverBlock: true, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + builtin: { rpcMethod: "netcatty/jobStop", mcpTool: "terminal_stop" }, + public: { rpcMethod: "public/terminalStop", mcpTool: "terminal_stop" }, + cli: { command: ["job-stop"] }, + }, + }, +]; + +module.exports = { TERMINAL_CAPABILITIES }; diff --git a/electron/capabilities/catalog/vault.cjs b/electron/capabilities/catalog/vault.cjs new file mode 100644 index 000000000..f030c9114 --- /dev/null +++ b/electron/capabilities/catalog/vault.cjs @@ -0,0 +1,127 @@ +"use strict"; + +const { CAPABILITY_STATUS } = require("../constants.cjs"); + +/** @type {import("../types.cjs").CapabilityDefinition[]} */ +const VAULT_CAPABILITIES = [ + { + id: "vault.host.get", + domain: "vault", + status: CAPABILITY_STATUS.PLANNED, + description: "Get host metadata from the vault.", + policy: { + write: false, + sensitiveRead: true, + longRunning: false, + requiresChatSession: false, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + cli: { command: ["vault", "host", "get"] }, + global: { rpcMethod: "vault/host/get" }, + }, + }, + { + id: "vault.host.notes.get", + domain: "vault", + status: CAPABILITY_STATUS.PLANNED, + description: "Read host notes from the vault.", + policy: { + write: false, + sensitiveRead: true, + longRunning: false, + requiresChatSession: false, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + cli: { command: ["vault", "host-notes", "get"] }, + global: { rpcMethod: "vault/host/notes/get" }, + public: { rpcMethod: "public/vault/hostNotes/get", mcpTool: "host_notes_get" }, + }, + }, + { + id: "vault.host.notes.set", + domain: "vault", + status: CAPABILITY_STATUS.PLANNED, + description: "Update host notes in the vault.", + policy: { + write: true, + sensitiveRead: false, + longRunning: false, + requiresChatSession: false, + bypassesObserverBlock: false, + bypassesApproval: false, + bypassesChatCancel: false, + }, + surfaces: { + cli: { command: ["vault", "host-notes", "set"] }, + global: { rpcMethod: "vault/host/notes/set" }, + }, + }, + { + id: "vault.snippets.list", + domain: "vault", + status: CAPABILITY_STATUS.PLANNED, + description: "List code snippets stored in the vault.", + policy: { + write: false, + sensitiveRead: false, + longRunning: false, + requiresChatSession: false, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + cli: { command: ["snippets", "list"] }, + global: { rpcMethod: "vault/snippets/list" }, + public: { rpcMethod: "public/vault/snippets/list", mcpTool: "snippets_list" }, + }, + }, + { + id: "vault.snippets.get", + domain: "vault", + status: CAPABILITY_STATUS.PLANNED, + description: "Get a single code snippet from the vault.", + policy: { + write: false, + sensitiveRead: false, + longRunning: false, + requiresChatSession: false, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + cli: { command: ["snippets", "get"] }, + global: { rpcMethod: "vault/snippets/get" }, + public: { rpcMethod: "public/vault/snippets/get", mcpTool: "snippets_get" }, + }, + }, + { + id: "vault.snippets.run", + domain: "vault", + status: CAPABILITY_STATUS.PLANNED, + description: "Resolve snippet variables and execute a snippet in a terminal session.", + policy: { + write: true, + sensitiveRead: false, + longRunning: true, + requiresChatSession: true, + bypassesObserverBlock: false, + bypassesApproval: false, + bypassesChatCancel: false, + }, + surfaces: { + cli: { command: ["snippets", "run"] }, + global: { rpcMethod: "vault/snippets/run" }, + public: { rpcMethod: "public/vault/snippets/run", mcpTool: "snippets_run" }, + }, + }, +]; + +module.exports = { VAULT_CAPABILITIES }; diff --git a/electron/capabilities/constants.cjs b/electron/capabilities/constants.cjs new file mode 100644 index 000000000..ee96c70bd --- /dev/null +++ b/electron/capabilities/constants.cjs @@ -0,0 +1,37 @@ +"use strict"; + +/** @typedef {'builtin' | 'public' | 'cli' | 'global'} CapabilitySurface */ +/** @typedef {'implemented' | 'planned'} CapabilityStatus */ +/** @typedef {'observer' | 'confirm' | 'autonomous'} PermissionMode */ + +const CAPABILITY_SURFACES = Object.freeze({ + BUILTIN: "builtin", + PUBLIC: "public", + CLI: "cli", + GLOBAL: "global", +}); + +const CAPABILITY_STATUS = Object.freeze({ + IMPLEMENTED: "implemented", + PLANNED: "planned", +}); + +const PERMISSION_MODES = Object.freeze({ + OBSERVER: "observer", + CONFIRM: "confirm", + AUTONOMOUS: "autonomous", +}); + +const RPC_TIMEOUT_DEFAULTS = Object.freeze({ + DEFAULT_RPC_TIMEOUT_MS: 30_000, + DEFAULT_OPERATION_TIMEOUT_MS: 60_000, + RPC_TIMEOUT_BUFFER_MS: 5_000, + DEFAULT_APPROVAL_TIMEOUT_MS: 110_000, +}); + +module.exports = { + CAPABILITY_SURFACES, + CAPABILITY_STATUS, + PERMISSION_MODES, + RPC_TIMEOUT_DEFAULTS, +}; diff --git a/electron/capabilities/dispatch.cjs b/electron/capabilities/dispatch.cjs new file mode 100644 index 000000000..8cfcc6b33 --- /dev/null +++ b/electron/capabilities/dispatch.cjs @@ -0,0 +1,39 @@ +"use strict"; + +const { CAPABILITY_STATUS, CAPABILITY_SURFACES } = require("./constants.cjs"); +const { getCapabilityByRpcMethod } = require("./registry.cjs"); + +function createRegistryDispatcher({ + surface = CAPABILITY_SURFACES.BUILTIN, + handlers = {}, + fallback, +}) { + if (typeof fallback !== "function") { + throw new Error("fallback handler is required"); + } + + return async function dispatchRpc(rpcMethod, params = {}) { + const capability = getCapabilityByRpcMethod(rpcMethod, surface); + if (!capability) { + return fallback(rpcMethod, params); + } + if (capability.status !== CAPABILITY_STATUS.IMPLEMENTED) { + return { + ok: false, + error: `Capability "${capability.id}" is not implemented yet.`, + code: "CAPABILITY_NOT_IMPLEMENTED", + }; + } + + const handler = handlers[capability.id]; + if (typeof handler !== "function") { + return fallback(rpcMethod, params, capability); + } + + return await handler(params, capability); + }; +} + +module.exports = { + createRegistryDispatcher, +}; diff --git a/electron/capabilities/dispatch.test.cjs b/electron/capabilities/dispatch.test.cjs new file mode 100644 index 000000000..df0559fbd --- /dev/null +++ b/electron/capabilities/dispatch.test.cjs @@ -0,0 +1,46 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { createRegistryDispatcher } = require("./dispatch.cjs"); +const { CAPABILITY_SURFACES } = require("./constants.cjs"); + +test("createRegistryDispatcher routes implemented capabilities to handlers", async () => { + const calls = []; + const dispatch = createRegistryDispatcher({ + surface: CAPABILITY_SURFACES.BUILTIN, + handlers: { + "meta.status": async (params) => ({ ok: true, params }), + }, + fallback: async (method) => ({ ok: false, error: `unknown:${method}` }), + }); + + const result = await dispatch("netcatty/getStatus", { chatSessionId: "chat-1" }); + assert.equal(result.ok, true); + assert.equal(result.params.chatSessionId, "chat-1"); + assert.equal(calls.length, 0); +}); + +test("createRegistryDispatcher returns not-implemented for planned capabilities", async () => { + const dispatch = createRegistryDispatcher({ + surface: CAPABILITY_SURFACES.GLOBAL, + handlers: {}, + fallback: async (method) => ({ ok: false, error: `unknown:${method}` }), + }); + + const result = await dispatch("vault/host/notes/get", { hostId: "host-1" }); + assert.equal(result.ok, false); + assert.equal(result.code, "CAPABILITY_NOT_IMPLEMENTED"); +}); + +test("createRegistryDispatcher falls back for unknown rpc methods", async () => { + const dispatch = createRegistryDispatcher({ + surface: CAPABILITY_SURFACES.BUILTIN, + handlers: {}, + fallback: async (method) => ({ ok: false, error: `unknown:${method}` }), + }); + + const result = await dispatch("auth/verify", { token: "abc" }); + assert.equal(result.error, "unknown:auth/verify"); +}); diff --git a/electron/capabilities/index.cjs b/electron/capabilities/index.cjs new file mode 100644 index 000000000..2b6b1329a --- /dev/null +++ b/electron/capabilities/index.cjs @@ -0,0 +1,25 @@ +"use strict"; + +const constants = require("./constants.cjs"); +const catalog = require("./catalog/index.cjs"); +const registry = require("./registry.cjs"); +const policy = require("./policy.cjs"); +const rpcTimeouts = require("./rpcTimeouts.cjs"); +const rpcTransport = require("./rpcTransport.cjs"); +const dispatch = require("./dispatch.cjs"); +const scope = require("./scope.cjs"); +const adapters = require("./adapters/index.cjs"); +const services = require("./services/index.cjs"); + +module.exports = { + ...constants, + ...catalog, + ...registry, + ...policy, + ...rpcTimeouts, + ...rpcTransport, + ...dispatch, + ...scope, + ...adapters, + ...services, +}; diff --git a/electron/capabilities/policy.cjs b/electron/capabilities/policy.cjs new file mode 100644 index 000000000..1198c2c67 --- /dev/null +++ b/electron/capabilities/policy.cjs @@ -0,0 +1,143 @@ +"use strict"; + +const { CAPABILITY_SURFACES, PERMISSION_MODES } = require("./constants.cjs"); +const { getCapabilityByRpcMethod } = require("./registry.cjs"); + +const OBSERVER_DENY_MESSAGE = 'Operation denied: permission mode is "observer" (read-only). Change to "confirm" or "autonomous" in Settings → AI → Safety to allow this action.'; +const CHAT_SESSION_REQUIRED_MESSAGE = "chatSessionId is required for write operations."; +const CHAT_SESSION_CANCELLED_MESSAGE = "Operation cancelled: the SDK agent session was stopped."; +const USER_DENIED_MESSAGE = "Operation denied by user."; + +function requiresApprovalInConfirmMode(capability, surface) { + if (!capability) return false; + const binding = capability.surfaces?.[surface]; + if (binding?.confirmInConfirmMode === true) return true; + if (capability.policy.bypassesApproval) return false; + if (capability.policy.write) return true; + if (capability.policy.sensitiveRead && binding?.confirmInConfirmMode !== false) { + return binding?.confirmInConfirmMode === true; + } + return false; +} + +function isBlockedInObserverMode(capability) { + if (!capability) return false; + if (capability.policy.bypassesObserverBlock) return false; + return capability.policy.write; +} + +function evaluateRpcPermission({ + rpcMethod, + surface = CAPABILITY_SURFACES.BUILTIN, + permissionMode = PERMISSION_MODES.CONFIRM, + params = {}, + context = {}, +}) { + const capability = getCapabilityByRpcMethod(rpcMethod, surface); + if (!capability) { + return { + allowed: true, + requiresApproval: false, + capability: null, + }; + } + + if (capability?.policy.write && !params?.chatSessionId && surface === CAPABILITY_SURFACES.BUILTIN) { + return { + allowed: false, + requiresApproval: false, + error: CHAT_SESSION_REQUIRED_MESSAGE, + capability, + }; + } + + if ( + capability?.policy.write + && !capability.policy.bypassesChatCancel + && context.chatSessionCancelled + && surface === CAPABILITY_SURFACES.BUILTIN + ) { + return { + allowed: false, + requiresApproval: false, + error: CHAT_SESSION_CANCELLED_MESSAGE, + capability, + }; + } + + if (permissionMode === PERMISSION_MODES.OBSERVER && isBlockedInObserverMode(capability)) { + return { + allowed: false, + requiresApproval: false, + error: OBSERVER_DENY_MESSAGE, + capability, + }; + } + + const requiresApproval = permissionMode === PERMISSION_MODES.CONFIRM + && requiresApprovalInConfirmMode(capability, surface); + + return { + allowed: true, + requiresApproval, + capability, + }; +} + +function buildRpcMethodSet(surface, predicate) { + const { getRpcMethodsForSurface } = require("./registry.cjs"); + const methods = new Set(); + for (const rpcMethod of getRpcMethodsForSurface(surface)) { + const capability = getCapabilityByRpcMethod(rpcMethod, surface); + if (!capability || capability.status !== "implemented") continue; + if (predicate(capability, rpcMethod)) { + methods.add(rpcMethod); + } + } + return methods; +} + +const BUILTIN_WRITE_RPC_METHODS = buildRpcMethodSet(CAPABILITY_SURFACES.BUILTIN, (capability) => capability.policy.write); +const BUILTIN_APPROVAL_RPC_METHODS = buildRpcMethodSet( + CAPABILITY_SURFACES.BUILTIN, + (capability, rpcMethod) => requiresApprovalInConfirmMode(capability, CAPABILITY_SURFACES.BUILTIN), +); +const PUBLIC_WRITE_RPC_METHODS = buildRpcMethodSet(CAPABILITY_SURFACES.PUBLIC, (capability) => capability.policy.write); +const PUBLIC_CONFIRM_RPC_METHODS = buildRpcMethodSet( + CAPABILITY_SURFACES.PUBLIC, + (capability) => requiresApprovalInConfirmMode(capability, CAPABILITY_SURFACES.PUBLIC), +); + +function isBuiltinWriteRpcMethod(method) { + return BUILTIN_WRITE_RPC_METHODS.has(method); +} + +function isBuiltinApprovalRpcMethod(method) { + return BUILTIN_APPROVAL_RPC_METHODS.has(method); +} + +function isPublicWriteRpcMethod(method) { + return PUBLIC_WRITE_RPC_METHODS.has(method); +} + +function isPublicConfirmRpcMethod(method) { + return PUBLIC_CONFIRM_RPC_METHODS.has(method); +} + +module.exports = { + OBSERVER_DENY_MESSAGE, + CHAT_SESSION_REQUIRED_MESSAGE, + CHAT_SESSION_CANCELLED_MESSAGE, + USER_DENIED_MESSAGE, + requiresApprovalInConfirmMode, + isBlockedInObserverMode, + evaluateRpcPermission, + BUILTIN_WRITE_RPC_METHODS, + BUILTIN_APPROVAL_RPC_METHODS, + PUBLIC_WRITE_RPC_METHODS, + PUBLIC_CONFIRM_RPC_METHODS, + isBuiltinWriteRpcMethod, + isBuiltinApprovalRpcMethod, + isPublicWriteRpcMethod, + isPublicConfirmRpcMethod, +}; diff --git a/electron/capabilities/policy.test.cjs b/electron/capabilities/policy.test.cjs new file mode 100644 index 000000000..dd692db6f --- /dev/null +++ b/electron/capabilities/policy.test.cjs @@ -0,0 +1,148 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { + BUILTIN_WRITE_RPC_METHODS, + BUILTIN_APPROVAL_RPC_METHODS, + PUBLIC_CONFIRM_RPC_METHODS, + evaluateRpcPermission, + OBSERVER_DENY_MESSAGE, +} = require("./policy.cjs"); +const { CAPABILITY_SURFACES, PERMISSION_MODES } = require("./constants.cjs"); + +test("builtin write methods match legacy mcpServerBridge write set", () => { + const legacyWriteMethods = [ + "netcatty/exec", + "netcatty/sftp/write", + "netcatty/sftp/download", + "netcatty/sftp/upload", + "netcatty/sftp/mkdir", + "netcatty/sftp/delete", + "netcatty/sftp/rename", + "netcatty/sftp/chmod", + "netcatty/jobStart", + "netcatty/jobStop", + ]; + assert.deepEqual(new Set(legacyWriteMethods), BUILTIN_WRITE_RPC_METHODS); +}); + +test("builtin approval methods exclude jobStop and non-write control rpc", () => { + assert.equal(BUILTIN_APPROVAL_RPC_METHODS.has("netcatty/jobStop"), false); + assert.equal(BUILTIN_APPROVAL_RPC_METHODS.has("netcatty/setCancelled"), false); + assert.equal(BUILTIN_APPROVAL_RPC_METHODS.has("netcatty/exec"), true); + assert.equal(BUILTIN_APPROVAL_RPC_METHODS.has("netcatty/sftp/write"), true); +}); + +test("observer mode blocks writes but allows terminal poll", () => { + const denied = evaluateRpcPermission({ + rpcMethod: "netcatty/exec", + permissionMode: PERMISSION_MODES.OBSERVER, + params: { chatSessionId: "chat-1" }, + }); + assert.equal(denied.allowed, false); + assert.match(denied.error, /observer/i); + + const allowed = evaluateRpcPermission({ + rpcMethod: "netcatty/jobPoll", + permissionMode: PERMISSION_MODES.OBSERVER, + params: { chatSessionId: "chat-1" }, + }); + assert.equal(allowed.allowed, true); + assert.equal(allowed.requiresApproval, false); +}); + +test("confirm mode requires approval for writes but not sftp list on builtin surface", () => { + const writeDecision = evaluateRpcPermission({ + rpcMethod: "netcatty/sftp/write", + permissionMode: PERMISSION_MODES.CONFIRM, + params: { chatSessionId: "chat-1" }, + }); + assert.equal(writeDecision.allowed, true); + assert.equal(writeDecision.requiresApproval, true); + + const readDecision = evaluateRpcPermission({ + rpcMethod: "netcatty/sftp/list", + permissionMode: PERMISSION_MODES.CONFIRM, + params: { chatSessionId: "chat-1" }, + }); + assert.equal(readDecision.allowed, true); + assert.equal(readDecision.requiresApproval, false); +}); + +test("public surface treats sensitive reads as confirm-gated", () => { + const decision = evaluateRpcPermission({ + rpcMethod: "public/sftp/list", + surface: CAPABILITY_SURFACES.PUBLIC, + permissionMode: PERMISSION_MODES.CONFIRM, + params: { sessionId: "sess-1" }, + }); + assert.equal(decision.allowed, true); + assert.equal(decision.requiresApproval, true); + assert.equal(PUBLIC_CONFIRM_RPC_METHODS.has("public/sftp/list"), true); +}); + +test("write operations require chatSessionId on builtin surface", () => { + const decision = evaluateRpcPermission({ + rpcMethod: "netcatty/exec", + permissionMode: PERMISSION_MODES.AUTONOMOUS, + params: {}, + }); + assert.equal(decision.allowed, false); + assert.match(decision.error, /chatSessionId/i); +}); + +test("cancelled chat sessions block terminal writes", () => { + const decision = evaluateRpcPermission({ + rpcMethod: "netcatty/exec", + permissionMode: PERMISSION_MODES.AUTONOMOUS, + params: { chatSessionId: "chat-1" }, + context: { chatSessionCancelled: true }, + }); + assert.equal(decision.allowed, false); + assert.match(decision.error, /cancelled/i); +}); + +test("cancelled chat sessions block sftp writes", () => { + const decision = evaluateRpcPermission({ + rpcMethod: "netcatty/sftp/write", + permissionMode: PERMISSION_MODES.AUTONOMOUS, + params: { chatSessionId: "chat-1" }, + context: { chatSessionCancelled: true }, + }); + assert.equal(decision.allowed, false); + assert.match(decision.error, /cancelled/i); +}); + +test("cancelled chat sessions still allow sftp reads", () => { + const decision = evaluateRpcPermission({ + rpcMethod: "netcatty/sftp/list", + permissionMode: PERMISSION_MODES.AUTONOMOUS, + params: { chatSessionId: "chat-1" }, + context: { chatSessionCancelled: true }, + }); + assert.equal(decision.allowed, true); +}); + +test("jobStop bypasses observer and cancelled chat checks", () => { + const observerDecision = evaluateRpcPermission({ + rpcMethod: "netcatty/jobStop", + permissionMode: PERMISSION_MODES.OBSERVER, + params: { chatSessionId: "chat-1" }, + context: { chatSessionCancelled: true }, + }); + assert.equal(observerDecision.allowed, true); + assert.notEqual(observerDecision.error, OBSERVER_DENY_MESSAGE); +}); + +test("unknown rpc methods pass through policy checks", () => { + const decision = evaluateRpcPermission({ + rpcMethod: "auth/verify", + permissionMode: PERMISSION_MODES.OBSERVER, + params: {}, + }); + assert.equal(decision.allowed, true); + assert.equal(decision.requiresApproval, false); + assert.equal(decision.capability, null); +}); diff --git a/electron/capabilities/registry.cjs b/electron/capabilities/registry.cjs new file mode 100644 index 000000000..0179343f1 --- /dev/null +++ b/electron/capabilities/registry.cjs @@ -0,0 +1,101 @@ +"use strict"; + +const { ALL_CAPABILITIES } = require("./catalog/index.cjs"); +const { CAPABILITY_STATUS, CAPABILITY_SURFACES } = require("./constants.cjs"); + +function buildRegistryIndex(capabilities) { + const byId = new Map(); + const byRpcMethod = new Map(); + const byMcpTool = new Map(); + const byCliCommand = new Map(); + const byDomain = new Map(); + + for (const capability of capabilities) { + byId.set(capability.id, capability); + + const domainList = byDomain.get(capability.domain) || []; + domainList.push(capability); + byDomain.set(capability.domain, domainList); + + for (const [surfaceName, binding] of Object.entries(capability.surfaces || {})) { + if (binding?.rpcMethod) { + byRpcMethod.set(`${surfaceName}:${binding.rpcMethod}`, capability); + } + if (binding?.mcpTool) { + byMcpTool.set(`${surfaceName}:${binding.mcpTool}`, capability); + } + if (Array.isArray(binding?.command) && binding.command.length > 0) { + byCliCommand.set(binding.command.join(" "), capability); + } + } + } + + return { + capabilities, + byId, + byRpcMethod, + byMcpTool, + byCliCommand, + byDomain, + }; +} + +const registryIndex = buildRegistryIndex(ALL_CAPABILITIES); + +function listCapabilities(options = {}) { + const { status, domain, surface } = options; + return registryIndex.capabilities.filter((capability) => { + if (status && capability.status !== status) return false; + if (domain && capability.domain !== domain) return false; + if (surface && !capability.surfaces?.[surface]) return false; + return true; + }); +} + +function getCapabilityById(id) { + return registryIndex.byId.get(id) || null; +} + +function getCapabilityByRpcMethod(rpcMethod, surface = CAPABILITY_SURFACES.BUILTIN) { + return registryIndex.byRpcMethod.get(`${surface}:${rpcMethod}`) || null; +} + +function getCapabilityByMcpTool(toolName, surface = CAPABILITY_SURFACES.BUILTIN) { + return registryIndex.byMcpTool.get(`${surface}:${toolName}`) || null; +} + +function getCapabilityByCliCommand(commandParts) { + const key = Array.isArray(commandParts) ? commandParts.join(" ") : String(commandParts || ""); + return registryIndex.byCliCommand.get(key) || null; +} + +function getRpcMethodsForSurface(surface, filter = {}) { + const methods = new Set(); + for (const capability of registryIndex.capabilities) { + const binding = capability.surfaces?.[surface]; + if (!binding?.rpcMethod) continue; + if (filter.status && capability.status !== filter.status) continue; + if (filter.write === true && !capability.policy.write) continue; + if (filter.write === false && capability.policy.write) continue; + if (filter.longRunning === true && !capability.policy.longRunning) continue; + if (filter.longRunning === false && capability.policy.longRunning) continue; + methods.add(binding.rpcMethod); + } + return methods; +} + +function getImplementedRpcMethodsForSurface(surface) { + return getRpcMethodsForSurface(surface, { status: CAPABILITY_STATUS.IMPLEMENTED }); +} + +module.exports = { + ALL_CAPABILITIES, + listCapabilities, + getCapabilityById, + getCapabilityByRpcMethod, + getCapabilityByMcpTool, + getCapabilityByCliCommand, + getRpcMethodsForSurface, + getImplementedRpcMethodsForSurface, + buildRegistryIndex, +}; diff --git a/electron/capabilities/registry.test.cjs b/electron/capabilities/registry.test.cjs new file mode 100644 index 000000000..bf56bd5ed --- /dev/null +++ b/electron/capabilities/registry.test.cjs @@ -0,0 +1,47 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { + ALL_CAPABILITIES, + getCapabilityById, + getCapabilityByRpcMethod, + getCapabilityByMcpTool, + getCapabilityByCliCommand, + listCapabilities, +} = require("./registry.cjs"); +const { CAPABILITY_STATUS, CAPABILITY_SURFACES } = require("./constants.cjs"); + +test("registry contains implemented and planned capabilities", () => { + assert.ok(ALL_CAPABILITIES.length >= 20); + const implemented = listCapabilities({ status: CAPABILITY_STATUS.IMPLEMENTED }); + const planned = listCapabilities({ status: CAPABILITY_STATUS.PLANNED }); + assert.ok(implemented.length > 0); + assert.ok(planned.length > 0); +}); + +test("registry resolves builtin rpc methods and mcp tools", () => { + const exec = getCapabilityByRpcMethod("netcatty/exec", CAPABILITY_SURFACES.BUILTIN); + assert.equal(exec?.id, "terminal.execute"); + const tool = getCapabilityByMcpTool("terminal_execute", CAPABILITY_SURFACES.BUILTIN); + assert.equal(tool?.id, "terminal.execute"); +}); + +test("registry resolves public rpc aliases for future surfaces", () => { + const publicExec = getCapabilityByRpcMethod("public/terminalExecute", CAPABILITY_SURFACES.PUBLIC); + assert.equal(publicExec?.id, "terminal.execute"); + assert.equal(publicExec?.status, CAPABILITY_STATUS.IMPLEMENTED); +}); + +test("registry resolves cli commands", () => { + const env = getCapabilityByCliCommand(["env"]); + assert.equal(env?.id, "session.environment"); + const sftpList = getCapabilityByCliCommand(["sftp", "list"]); + assert.equal(sftpList?.id, "sftp.list"); +}); + +test("planned vault and portforward capabilities are registered", () => { + assert.equal(getCapabilityById("vault.host.notes.get")?.status, CAPABILITY_STATUS.PLANNED); + assert.equal(getCapabilityById("portforward.start")?.status, CAPABILITY_STATUS.PLANNED); +}); diff --git a/electron/capabilities/rpcTimeouts.cjs b/electron/capabilities/rpcTimeouts.cjs new file mode 100644 index 000000000..6c88c588d --- /dev/null +++ b/electron/capabilities/rpcTimeouts.cjs @@ -0,0 +1,67 @@ +"use strict"; + +const { CAPABILITY_SURFACES, PERMISSION_MODES, RPC_TIMEOUT_DEFAULTS } = require("./constants.cjs"); +const { getCapabilityByRpcMethod } = require("./registry.cjs"); +const { requiresApprovalInConfirmMode } = require("./policy.cjs"); + +const { + DEFAULT_RPC_TIMEOUT_MS, + DEFAULT_OPERATION_TIMEOUT_MS, + RPC_TIMEOUT_BUFFER_MS, + DEFAULT_APPROVAL_TIMEOUT_MS, +} = RPC_TIMEOUT_DEFAULTS; + +function isLongRunningRpcMethod(method, surface = CAPABILITY_SURFACES.BUILTIN) { + const capability = getCapabilityByRpcMethod(method, surface); + return Boolean(capability?.policy.longRunning); +} + +function isApprovalWaitRpcMethod(method, surface, permissionMode) { + if (permissionMode !== PERMISSION_MODES.CONFIRM) return false; + const capability = getCapabilityByRpcMethod(method, surface); + return requiresApprovalInConfirmMode(capability, surface); +} + +function resolveRpcTimeoutMs( + method, + { + surface = CAPABILITY_SURFACES.BUILTIN, + bridgeCommandTimeoutMs = null, + bridgePermissionMode = null, + bridgeApprovalTimeoutMs = null, + defaultOperationTimeoutMs = DEFAULT_OPERATION_TIMEOUT_MS, + defaultApprovalTimeoutMs = DEFAULT_APPROVAL_TIMEOUT_MS, + defaultRpcTimeoutMs = DEFAULT_RPC_TIMEOUT_MS, + timeoutBufferMs = RPC_TIMEOUT_BUFFER_MS, + } = {}, +) { + const operationTimeoutMs = isLongRunningRpcMethod(method, surface) + ? (Number.isFinite(bridgeCommandTimeoutMs) && bridgeCommandTimeoutMs > 0 + ? bridgeCommandTimeoutMs + : defaultOperationTimeoutMs) + : 0; + + const approvalTimeoutMs = isApprovalWaitRpcMethod(method, surface, bridgePermissionMode) + ? (Number.isFinite(bridgeApprovalTimeoutMs) && bridgeApprovalTimeoutMs > 0 + ? bridgeApprovalTimeoutMs + : defaultApprovalTimeoutMs) + : 0; + + if (operationTimeoutMs > 0 && approvalTimeoutMs > 0) { + return Math.max(defaultRpcTimeoutMs, approvalTimeoutMs + operationTimeoutMs + timeoutBufferMs); + } + if (operationTimeoutMs > 0) { + return Math.max(defaultRpcTimeoutMs, operationTimeoutMs + timeoutBufferMs); + } + if (approvalTimeoutMs > 0) { + return Math.max(defaultRpcTimeoutMs, approvalTimeoutMs + timeoutBufferMs); + } + return defaultRpcTimeoutMs; +} + +module.exports = { + isLongRunningRpcMethod, + isApprovalWaitRpcMethod, + resolveRpcTimeoutMs, + RPC_TIMEOUT_DEFAULTS, +}; diff --git a/electron/capabilities/rpcTimeouts.test.cjs b/electron/capabilities/rpcTimeouts.test.cjs new file mode 100644 index 000000000..a5b2c13b6 --- /dev/null +++ b/electron/capabilities/rpcTimeouts.test.cjs @@ -0,0 +1,57 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { resolveRpcTimeoutMs, isLongRunningRpcMethod, isApprovalWaitRpcMethod } = require("./rpcTimeouts.cjs"); +const { CAPABILITY_SURFACES, PERMISSION_MODES, RPC_TIMEOUT_DEFAULTS } = require("./constants.cjs"); + +test("long-running rpc methods include exec and sftp home", () => { + assert.equal(isLongRunningRpcMethod("netcatty/exec"), true); + assert.equal(isLongRunningRpcMethod("netcatty/sftp/read"), true); + assert.equal(isLongRunningRpcMethod("netcatty/sftp/home"), true); + assert.equal(isLongRunningRpcMethod("netcatty/jobPoll"), false); +}); + +test("approval wait methods follow confirm mode and capability policy", () => { + assert.equal( + isApprovalWaitRpcMethod("netcatty/exec", CAPABILITY_SURFACES.BUILTIN, PERMISSION_MODES.CONFIRM), + true, + ); + assert.equal( + isApprovalWaitRpcMethod("netcatty/jobStop", CAPABILITY_SURFACES.BUILTIN, PERMISSION_MODES.CONFIRM), + false, + ); + assert.equal( + isApprovalWaitRpcMethod("netcatty/sftp/list", CAPABILITY_SURFACES.BUILTIN, PERMISSION_MODES.CONFIRM), + false, + ); + assert.equal( + isApprovalWaitRpcMethod("public/sftp/list", CAPABILITY_SURFACES.PUBLIC, PERMISSION_MODES.CONFIRM), + true, + ); +}); + +test("resolveRpcTimeoutMs combines operation and approval budgets", () => { + const timeoutMs = resolveRpcTimeoutMs("netcatty/exec", { + surface: CAPABILITY_SURFACES.BUILTIN, + bridgeCommandTimeoutMs: 60_000, + bridgePermissionMode: PERMISSION_MODES.CONFIRM, + bridgeApprovalTimeoutMs: 110_000, + }); + assert.equal( + timeoutMs, + Math.max( + RPC_TIMEOUT_DEFAULTS.DEFAULT_RPC_TIMEOUT_MS, + 110_000 + 60_000 + RPC_TIMEOUT_DEFAULTS.RPC_TIMEOUT_BUFFER_MS, + ), + ); +}); + +test("resolveRpcTimeoutMs falls back to default for lightweight rpc", () => { + const timeoutMs = resolveRpcTimeoutMs("netcatty/getStatus", { + surface: CAPABILITY_SURFACES.BUILTIN, + bridgePermissionMode: PERMISSION_MODES.CONFIRM, + }); + assert.equal(timeoutMs, RPC_TIMEOUT_DEFAULTS.DEFAULT_RPC_TIMEOUT_MS); +}); diff --git a/electron/capabilities/rpcTransport.cjs b/electron/capabilities/rpcTransport.cjs new file mode 100644 index 000000000..ddb7d75de --- /dev/null +++ b/electron/capabilities/rpcTransport.cjs @@ -0,0 +1,190 @@ +"use strict"; + +const { CAPABILITY_SURFACES } = require("./constants.cjs"); +const { resolveRpcTimeoutMs } = require("./rpcTimeouts.cjs"); + +function createTaggedError(code, message) { + const error = new Error(message); + error.code = code; + return error; +} + +function createUnavailableError(message) { + return createTaggedError("RPC_UNAVAILABLE", message); +} + +function createRpcTimeoutError(method, timeoutMs, createError = createTaggedError) { + return createError( + "RPC_TIMEOUT", + `Timed out waiting for RPC response to "${method}" after ${timeoutMs}ms.`, + ); +} + +/** + * Create a newline-delimited JSON-RPC client over an existing TCP socket. + */ +function createNdjsonRpcClient({ + socket, + surface = CAPABILITY_SURFACES.BUILTIN, + setTimeoutImpl = setTimeout, + clearTimeoutImpl = clearTimeout, + onBridgeStatus, + createError = createTaggedError, + messages = {}, +}) { + if (!socket) { + throw new Error("socket is required"); + } + + const connectionClosedMessage = messages.connectionClosed + || "RPC connection closed."; + const connectionClosedWhileCallMessage = messages.connectionClosedWhileCall + || connectionClosedMessage; + const connectionErrorMessage = messages.connectionError + || ((error) => `RPC connection failed: ${error?.message || error}`); + const rpcTimeoutMessage = messages.rpcTimeout + || ((method, timeoutMs) => `Timed out waiting for RPC response to "${method}" after ${timeoutMs}ms.`); + const writeFailedMessage = messages.writeFailed + || ((method, error) => `Failed to send RPC "${method}": ${error?.message || error}`); + + let nextRpcId = 1; + let buffer = ""; + const pending = new Map(); + let bridgeCommandTimeoutMs = null; + let bridgePermissionMode = null; + let bridgeApprovalTimeoutMs = null; + + function settle(id, resolve, reject, payload) { + pending.delete(id); + clearTimeoutImpl(payload.timeoutId); + if (payload.error) { + reject(payload.error); + return; + } + resolve(payload.result); + } + + function rejectAll(error) { + for (const [id, entry] of pending) { + settle(id, entry.resolve, entry.reject, { timeoutId: entry.timeoutId, error }); + } + } + + socket.on("data", (chunk) => { + buffer += chunk; + let newlineIndex; + while ((newlineIndex = buffer.indexOf("\n")) !== -1) { + const line = buffer.slice(0, newlineIndex); + buffer = buffer.slice(newlineIndex + 1); + if (!line.trim()) continue; + + let message; + try { + message = JSON.parse(line); + } catch { + continue; + } + if (message?.id == null) continue; + const entry = pending.get(message.id); + if (!entry) continue; + + if (message.error) { + settle(message.id, entry.resolve, entry.reject, { + timeoutId: entry.timeoutId, + error: createError( + "RPC_ERROR", + message.error.message || JSON.stringify(message.error), + ), + }); + } else { + settle(message.id, entry.resolve, entry.reject, { + timeoutId: entry.timeoutId, + result: message.result, + }); + } + } + }); + + socket.on("error", (error) => { + rejectAll(createError("CONNECTION_ERROR", connectionErrorMessage(error))); + }); + + socket.on("close", () => { + rejectAll(createError("CONNECTION_CLOSED", connectionClosedMessage)); + }); + + async function call(method, params) { + if (socket.destroyed || !socket.writable) { + throw createError("CONNECTION_CLOSED", connectionClosedWhileCallMessage); + } + + const id = nextRpcId++; + const timeoutMs = resolveRpcTimeoutMs(method, { + surface, + bridgeCommandTimeoutMs, + bridgePermissionMode, + bridgeApprovalTimeoutMs, + }); + + return await new Promise((resolve, reject) => { + const timeoutId = setTimeoutImpl(() => { + pending.delete(id); + reject(createError("RPC_TIMEOUT", rpcTimeoutMessage(method, timeoutMs))); + }, timeoutMs); + + pending.set(id, { resolve, reject, timeoutId }); + + const payload = `${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`; + try { + socket.write(payload, (writeError) => { + if (!writeError) return; + settle(id, resolve, reject, { + timeoutId, + error: createError("WRITE_FAILED", writeFailedMessage(method, writeError)), + }); + }); + } catch (writeError) { + settle(id, resolve, reject, { + timeoutId, + error: createError("WRITE_FAILED", writeFailedMessage(method, writeError)), + }); + } + }); + } + + function ingestBridgeStatus(statusResult) { + if (Number.isFinite(statusResult?.commandTimeoutMs) && statusResult.commandTimeoutMs > 0) { + bridgeCommandTimeoutMs = statusResult.commandTimeoutMs; + } + if (typeof statusResult?.permissionMode === "string") { + bridgePermissionMode = statusResult.permissionMode; + } + if (Number.isFinite(statusResult?.approvalTimeoutMs) && statusResult.approvalTimeoutMs > 0) { + bridgeApprovalTimeoutMs = statusResult.approvalTimeoutMs; + } + onBridgeStatus?.({ + bridgeCommandTimeoutMs, + bridgePermissionMode, + bridgeApprovalTimeoutMs, + }); + } + + return { + call, + ingestBridgeStatus, + close() { + try { + socket.end(); + } catch { + // Ignore shutdown errors. + } + }, + }; +} + +module.exports = { + createTaggedError, + createUnavailableError, + createRpcTimeoutError, + createNdjsonRpcClient, +}; diff --git a/electron/capabilities/rpcTransport.test.cjs b/electron/capabilities/rpcTransport.test.cjs new file mode 100644 index 000000000..fdf457b6a --- /dev/null +++ b/electron/capabilities/rpcTransport.test.cjs @@ -0,0 +1,113 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { EventEmitter } = require("node:events"); + +const { + createNdjsonRpcClient, + createTaggedError, +} = require("./rpcTransport.cjs"); +const { CAPABILITY_SURFACES } = require("./constants.cjs"); + +function createFakeSocket() { + const socket = new EventEmitter(); + socket.destroyed = false; + socket.writable = true; + socket.setEncoding = () => {}; + socket.end = () => { + socket.writable = false; + socket.destroyed = true; + socket.emit("close"); + }; + socket.write = (line, callback) => { + const request = JSON.parse(line); + socket.emit("data", `${JSON.stringify({ jsonrpc: "2.0", id: request.id, result: { ok: true } })}\n`); + callback?.(null); + return true; + }; + return socket; +} + +test("createNdjsonRpcClient resolves rpc responses", async () => { + const socket = createFakeSocket(); + const client = createNdjsonRpcClient({ socket, surface: CAPABILITY_SURFACES.BUILTIN }); + + const result = await client.call("netcatty/getStatus", {}); + assert.deepEqual(result, { ok: true }); +}); + +test("createNdjsonRpcClient surfaces RPC_ERROR with code for bridge failures", async () => { + const socket = new EventEmitter(); + socket.destroyed = false; + socket.writable = true; + socket.setEncoding = () => {}; + socket.write = (line, callback) => { + const request = JSON.parse(line); + socket.emit("data", `${JSON.stringify({ + jsonrpc: "2.0", + id: request.id, + error: { message: "Operation denied by user." }, + })}\n`); + callback?.(null); + return true; + }; + + const client = createNdjsonRpcClient({ + socket, + surface: CAPABILITY_SURFACES.BUILTIN, + createError: createTaggedError, + }); + + await assert.rejects( + () => client.call("netcatty/exec", { sessionId: "sess-1", command: "pwd" }), + (error) => error.code === "RPC_ERROR" && error.message === "Operation denied by user.", + ); +}); + +test("createNdjsonRpcClient uses injectable cli-compatible timeout messages", async () => { + const socket = createFakeSocket(); + const client = createNdjsonRpcClient({ + socket, + surface: CAPABILITY_SURFACES.BUILTIN, + createError: createTaggedError, + setTimeoutImpl: (callback) => { + callback(); + return 1; + }, + messages: { + rpcTimeout: (method, timeoutMs) => ( + `Timed out waiting for Netcatty RPC response to "${method}" after ${timeoutMs}ms.` + ), + }, + }); + + await assert.rejects( + () => client.call("netcatty/exec", { sessionId: "sess-1", command: "pwd", chatSessionId: "chat-1" }), + (error) => error.code === "RPC_TIMEOUT" && /Netcatty RPC response/.test(error.message), + ); +}); + +test("createNdjsonRpcClient ingests bridge status for timeout calculation", async () => { + const socket = createFakeSocket(); + let captured = null; + const client = createNdjsonRpcClient({ + socket, + surface: CAPABILITY_SURFACES.BUILTIN, + onBridgeStatus: (status) => { + captured = status; + }, + }); + + client.ingestBridgeStatus({ + commandTimeoutMs: 45_000, + permissionMode: "confirm", + approvalTimeoutMs: 120_000, + }); + + assert.deepEqual(captured, { + bridgeCommandTimeoutMs: 45_000, + bridgePermissionMode: "confirm", + bridgeApprovalTimeoutMs: 120_000, + }); +}); diff --git a/electron/capabilities/scope.cjs b/electron/capabilities/scope.cjs new file mode 100644 index 000000000..8d607bad9 --- /dev/null +++ b/electron/capabilities/scope.cjs @@ -0,0 +1,41 @@ +"use strict"; + +/** + * Scope helpers for capability execution boundaries. + * + * Concrete scope implementations (chat-scoped, public-exposure, global) will + * live with their bridges. This module defines shared validation helpers. + */ + +function createScopeError(code, message) { + return { ok: false, code, error: message }; +} + +function validateSessionInList(sessionId, allowedSessionIds) { + if (!sessionId) { + return createScopeError("SESSION_REQUIRED", "sessionId is required."); + } + if (!Array.isArray(allowedSessionIds)) { + return createScopeError("SCOPE_UNAVAILABLE", "Session scope is unavailable."); + } + if (allowedSessionIds.length === 0) { + return createScopeError("SESSION_NOT_IN_SCOPE", "No sessions are available in the current scope."); + } + if (!allowedSessionIds.includes(sessionId)) { + return createScopeError("SESSION_NOT_IN_SCOPE", `Session "${sessionId}" is not in the current scope.`); + } + return { ok: true }; +} + +function intersectSessionIds(primaryIds, secondaryIds) { + if (!Array.isArray(primaryIds)) return Array.isArray(secondaryIds) ? [...secondaryIds] : null; + if (!Array.isArray(secondaryIds)) return [...primaryIds]; + const secondary = new Set(secondaryIds); + return primaryIds.filter((sessionId) => secondary.has(sessionId)); +} + +module.exports = { + createScopeError, + validateSessionInList, + intersectSessionIds, +}; diff --git a/electron/capabilities/scope.test.cjs b/electron/capabilities/scope.test.cjs new file mode 100644 index 000000000..6d977a6f5 --- /dev/null +++ b/electron/capabilities/scope.test.cjs @@ -0,0 +1,19 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { validateSessionInList, intersectSessionIds } = require("./scope.cjs"); + +test("validateSessionInList rejects unknown sessions", () => { + const result = validateSessionInList("sess-2", ["sess-1"]); + assert.equal(result.ok, false); + assert.equal(result.code, "SESSION_NOT_IN_SCOPE"); +}); + +test("intersectSessionIds narrows explicit scope", () => { + assert.deepEqual( + intersectSessionIds(["a", "b", "c"], ["b", "c", "d"]), + ["b", "c"], + ); +}); diff --git a/electron/capabilities/services/index.cjs b/electron/capabilities/services/index.cjs new file mode 100644 index 000000000..225f5b5fa --- /dev/null +++ b/electron/capabilities/services/index.cjs @@ -0,0 +1,11 @@ +"use strict"; + +const notImplemented = require("./notImplemented.cjs"); +const vaultService = require("./vaultService.cjs"); +const portforwardService = require("./portforwardService.cjs"); + +module.exports = { + ...notImplemented, + ...vaultService, + ...portforwardService, +}; diff --git a/electron/capabilities/services/notImplemented.cjs b/electron/capabilities/services/notImplemented.cjs new file mode 100644 index 000000000..ce4e301fd --- /dev/null +++ b/electron/capabilities/services/notImplemented.cjs @@ -0,0 +1,18 @@ +"use strict"; + +function createNotImplementedResult(capabilityId) { + return { + ok: false, + code: "CAPABILITY_NOT_IMPLEMENTED", + error: `Capability "${capabilityId}" is not implemented yet.`, + }; +} + +function createNotImplementedHandler(capabilityId) { + return async () => createNotImplementedResult(capabilityId); +} + +module.exports = { + createNotImplementedResult, + createNotImplementedHandler, +}; diff --git a/electron/capabilities/services/portforwardService.cjs b/electron/capabilities/services/portforwardService.cjs new file mode 100644 index 000000000..b3bba4b25 --- /dev/null +++ b/electron/capabilities/services/portforwardService.cjs @@ -0,0 +1,20 @@ +"use strict"; + +const { createNotImplementedHandler } = require("./notImplemented.cjs"); + +/** + * Port forwarding domain service skeleton. Implementation will delegate to + * portForwardingBridge once rules are accessible from the main process. + */ +function createPortForwardService(_ctx = {}) { + return { + listRules: createNotImplementedHandler("portforward.rules.list"), + listTunnels: createNotImplementedHandler("portforward.tunnels.list"), + start: createNotImplementedHandler("portforward.start"), + stop: createNotImplementedHandler("portforward.stop"), + }; +} + +module.exports = { + createPortForwardService, +}; diff --git a/electron/capabilities/services/vaultService.cjs b/electron/capabilities/services/vaultService.cjs new file mode 100644 index 000000000..5f2ca1255 --- /dev/null +++ b/electron/capabilities/services/vaultService.cjs @@ -0,0 +1,22 @@ +"use strict"; + +const { createNotImplementedHandler } = require("./notImplemented.cjs"); + +/** + * Vault domain service skeleton. Handlers will be wired to a VaultFacade bridge + * in a follow-up PR; registry entries already describe the public contract. + */ +function createVaultService(_ctx = {}) { + return { + getHost: createNotImplementedHandler("vault.host.get"), + getHostNotes: createNotImplementedHandler("vault.host.notes.get"), + setHostNotes: createNotImplementedHandler("vault.host.notes.set"), + listSnippets: createNotImplementedHandler("vault.snippets.list"), + getSnippet: createNotImplementedHandler("vault.snippets.get"), + runSnippet: createNotImplementedHandler("vault.snippets.run"), + }; +} + +module.exports = { + createVaultService, +}; diff --git a/electron/capabilities/services/vaultService.test.cjs b/electron/capabilities/services/vaultService.test.cjs new file mode 100644 index 000000000..a174fc30c --- /dev/null +++ b/electron/capabilities/services/vaultService.test.cjs @@ -0,0 +1,13 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { createVaultService } = require("./vaultService.cjs"); + +test("vault service skeleton returns not-implemented for all handlers", async () => { + const service = createVaultService(); + const result = await service.getHostNotes({ hostId: "host-1" }); + assert.equal(result.ok, false); + assert.equal(result.code, "CAPABILITY_NOT_IMPLEMENTED"); +}); diff --git a/electron/capabilities/types.cjs b/electron/capabilities/types.cjs new file mode 100644 index 000000000..28689262e --- /dev/null +++ b/electron/capabilities/types.cjs @@ -0,0 +1,43 @@ +"use strict"; + +/** + * Shared capability layer types (JSDoc only). + * + * @typedef {import('./constants.cjs').CapabilitySurface} CapabilitySurface + * @typedef {import('./constants.cjs').CapabilityStatus} CapabilityStatus + * @typedef {import('./constants.cjs').PermissionMode} PermissionMode + * + * @typedef {Object} CapabilitySurfaceBinding + * @property {string} [rpcMethod] + * @property {string} [mcpTool] + * @property {string[]} [command] + * @property {boolean} [confirmInConfirmMode] + * + * @typedef {Object} CapabilityPolicy + * @property {boolean} write + * @property {boolean} sensitiveRead + * @property {boolean} longRunning + * @property {boolean} requiresChatSession + * @property {boolean} bypassesObserverBlock + * @property {boolean} bypassesApproval + * @property {boolean} bypassesChatCancel + * + * @typedef {Object} CapabilityDefinition + * @property {string} id + * @property {string} domain + * @property {CapabilityStatus} status + * @property {string} description + * @property {CapabilityPolicy} policy + * @property {Partial>} surfaces + * + * @typedef {Object} RpcPermissionContext + * @property {boolean} [chatSessionCancelled] + * + * @typedef {Object} RpcPermissionDecision + * @property {boolean} allowed + * @property {boolean} requiresApproval + * @property {string} [error] + * @property {CapabilityDefinition} [capability] + */ + +module.exports = {}; diff --git a/electron/cli/netcatty-tool-cli.capabilities.test.cjs b/electron/cli/netcatty-tool-cli.capabilities.test.cjs new file mode 100644 index 000000000..6ee6402cd --- /dev/null +++ b/electron/cli/netcatty-tool-cli.capabilities.test.cjs @@ -0,0 +1,17 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { spawnSync } = require("node:child_process"); +const path = require("node:path"); + +test("netcatty-tool-cli capabilities lists implemented commands without app connection", () => { + const cliPath = path.join(__dirname, "..", "cli", "netcatty-tool-cli.cjs"); + const result = spawnSync(process.execPath, [cliPath, "capabilities", "--json"], { + encoding: "utf8", + }); + assert.equal(result.status, 0, result.stderr); + const payload = JSON.parse(result.stdout); + assert.equal(payload.ok, true); + assert.ok(payload.capabilities.some((entry) => entry.id === "terminal.execute")); +}); diff --git a/electron/cli/netcatty-tool-cli.cjs b/electron/cli/netcatty-tool-cli.cjs index 820133308..90b8ee483 100644 --- a/electron/cli/netcatty-tool-cli.cjs +++ b/electron/cli/netcatty-tool-cli.cjs @@ -4,6 +4,8 @@ const path = require("node:path"); const { connectClient, createError } = require("./netcattyRpcClient.cjs"); +const { listCliCapabilities } = require("../capabilities/adapters/cliAdapter.cjs"); +const { CAPABILITY_STATUS } = require("../capabilities/constants.cjs"); function printHelp() { process.stdout.write( @@ -29,6 +31,7 @@ function printHelp() { " netcatty-tool-cli sftp home --session --chat-session [--json] [--scope-session ...]\n" + " netcatty-tool-cli cancel --chat-session [--json]\n" + " netcatty-tool-cli resume --chat-session [--json]\n" + + " netcatty-tool-cli capabilities [--json] [--status implemented|planned|all]\n" + " netcatty-tool-cli help\n\n" + "Examples:\n" + " netcatty-tool-cli status --json\n" + @@ -350,6 +353,26 @@ async function run() { process.exit(0); } + if (command === "capabilities") { + const hasStatusFlag = process.argv.includes("--status"); + const statusArg = hasStatusFlag + ? process.argv[process.argv.indexOf("--status") + 1] + : CAPABILITY_STATUS.IMPLEMENTED; + const status = statusArg === "all" ? null : statusArg; + const payload = { + ok: true, + capabilities: listCliCapabilities( + hasStatusFlag && statusArg === "all" + ? { status: null } + : { status }, + ), + }; + process.stdout.write(opts.json + ? `${JSON.stringify(payload, null, 2)}\n` + : `${payload.capabilities.map((entry) => entry.command.join(" ")).join("\n")}\n`); + process.exit(0); + } + let client = null; try { client = await connectClient(); diff --git a/electron/cli/netcattyRpcClient.cjs b/electron/cli/netcattyRpcClient.cjs index 977a0f093..35534fa79 100644 --- a/electron/cli/netcattyRpcClient.cjs +++ b/electron/cli/netcattyRpcClient.cjs @@ -4,37 +4,10 @@ const fs = require("node:fs"); const net = require("node:net"); const { getCliDiscoveryFilePath } = require("./discoveryPath.cjs"); - -const DEFAULT_RPC_TIMEOUT_MS = 30_000; -const DEFAULT_EXEC_TIMEOUT_MS = 60_000; -const EXEC_RPC_TIMEOUT_BUFFER_MS = 5_000; -const DEFAULT_APPROVAL_TIMEOUT_MS = 110_000; -const LONG_RUNNING_METHODS = new Set([ - "netcatty/exec", - "netcatty/jobStart", - "netcatty/sftp/list", - "netcatty/sftp/read", - "netcatty/sftp/upload", - "netcatty/sftp/write", - "netcatty/sftp/download", - "netcatty/sftp/mkdir", - "netcatty/sftp/delete", - "netcatty/sftp/rename", - "netcatty/sftp/stat", - "netcatty/sftp/chmod", - "netcatty/sftp/home", -]); -const APPROVAL_WAIT_METHODS = new Set([ - "netcatty/exec", - "netcatty/jobStart", - "netcatty/sftp/write", - "netcatty/sftp/download", - "netcatty/sftp/upload", - "netcatty/sftp/mkdir", - "netcatty/sftp/delete", - "netcatty/sftp/rename", - "netcatty/sftp/chmod", -]); +const { + CAPABILITY_SURFACES, + createNdjsonRpcClient, +} = require("../capabilities/index.cjs"); function createError(code, message) { const err = new Error(message); @@ -42,33 +15,6 @@ function createError(code, message) { return err; } -function resolveRpcTimeoutMs(method, bridgeCommandTimeoutMs, bridgePermissionMode, bridgeApprovalTimeoutMs) { - const execTimeoutMs = LONG_RUNNING_METHODS.has(method) - ? (Number.isFinite(bridgeCommandTimeoutMs) && bridgeCommandTimeoutMs > 0 - ? bridgeCommandTimeoutMs - : DEFAULT_EXEC_TIMEOUT_MS) - : 0; - const approvalTimeoutMs = (bridgePermissionMode === "confirm" && APPROVAL_WAIT_METHODS.has(method)) - ? (Number.isFinite(bridgeApprovalTimeoutMs) && bridgeApprovalTimeoutMs > 0 - ? bridgeApprovalTimeoutMs - : DEFAULT_APPROVAL_TIMEOUT_MS) - : 0; - - if (execTimeoutMs > 0 && approvalTimeoutMs > 0) { - return Math.max( - DEFAULT_RPC_TIMEOUT_MS, - approvalTimeoutMs + execTimeoutMs + EXEC_RPC_TIMEOUT_BUFFER_MS, - ); - } - if (execTimeoutMs > 0) { - return Math.max(DEFAULT_RPC_TIMEOUT_MS, execTimeoutMs + EXEC_RPC_TIMEOUT_BUFFER_MS); - } - if (approvalTimeoutMs > 0) { - return Math.max(DEFAULT_RPC_TIMEOUT_MS, approvalTimeoutMs + EXEC_RPC_TIMEOUT_BUFFER_MS); - } - return DEFAULT_RPC_TIMEOUT_MS; -} - function loadDiscovery() { const discoveryPath = getCliDiscoveryFilePath(); let raw; @@ -111,130 +57,31 @@ async function connectClient() { }); }); - let nextRpcId = 1; - let buffer = ""; - const pending = new Map(); - - function rejectPending(id, error) { - const entry = pending.get(id); - if (!entry) return; - pending.delete(id); - clearTimeout(entry.timeoutId); - entry.reject(error); - } - - function settlePending(id, result, error) { - const entry = pending.get(id); - if (!entry) return; - pending.delete(id); - clearTimeout(entry.timeoutId); - if (error) { - entry.reject(error); - return; - } - entry.resolve(result); - } - - function rejectAllPending(error) { - for (const id of pending.keys()) { - rejectPending(id, error); - } - } - - socket.on("data", (chunk) => { - buffer += chunk; - let newlineIdx; - while ((newlineIdx = buffer.indexOf("\n")) !== -1) { - const line = buffer.slice(0, newlineIdx); - buffer = buffer.slice(newlineIdx + 1); - if (!line.trim()) continue; - let msg; - try { - msg = JSON.parse(line); - } catch { - continue; - } - if (msg?.id == null || !pending.has(msg.id)) continue; - if (msg.error) { - settlePending(msg.id, null, createError("RPC_ERROR", msg.error.message || JSON.stringify(msg.error))); - } else { - settlePending(msg.id, msg.result, null); - } - } + const client = createNdjsonRpcClient({ + socket, + surface: CAPABILITY_SURFACES.BUILTIN, + createError, + messages: { + connectionClosed: "Connection to Netcatty TCP bridge closed.", + connectionClosedWhileCall: "Connection to Netcatty TCP bridge is closed.", + connectionError: (error) => `Connection to Netcatty TCP bridge failed: ${error?.message || error}`, + rpcTimeout: (method, timeoutMs) => ( + `Timed out waiting for Netcatty RPC response to "${method}" after ${timeoutMs}ms.` + ), + writeFailed: (method, error) => ( + `Failed to send Netcatty RPC "${method}": ${error?.message || error}` + ), + }, }); - socket.on("error", (err) => { - rejectAllPending( - createError("CONNECTION_ERROR", `Connection to Netcatty TCP bridge failed: ${err?.message || err}`), - ); - }); - - socket.on("close", () => { - rejectAllPending(createError("CONNECTION_CLOSED", "Connection to Netcatty TCP bridge closed.")); - }); - - let bridgeCommandTimeoutMs = null; - let bridgePermissionMode = null; - let bridgeApprovalTimeoutMs = null; - - async function call(method, params) { - if (socket.destroyed || !socket.writable) { - throw createError("CONNECTION_CLOSED", "Connection to Netcatty TCP bridge is closed."); - } - const id = nextRpcId++; - const timeoutMs = resolveRpcTimeoutMs( - method, - bridgeCommandTimeoutMs, - bridgePermissionMode, - bridgeApprovalTimeoutMs, - ); - return await new Promise((resolve, reject) => { - const timeoutId = setTimeout(() => { - rejectPending( - id, - createError("RPC_TIMEOUT", `Timed out waiting for Netcatty RPC response to "${method}" after ${timeoutMs}ms.`), - ); - }, timeoutMs); - - pending.set(id, { resolve, reject, timeoutId }); - - try { - socket.write( - `${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`, - (err) => { - if (err) { - rejectPending( - id, - createError("WRITE_FAILED", `Failed to send Netcatty RPC "${method}": ${err?.message || err}`), - ); - } - }, - ); - } catch (err) { - rejectPending( - id, - createError("WRITE_FAILED", `Failed to send Netcatty RPC "${method}": ${err?.message || err}`), - ); - } - }); - } - - const authResult = await call("auth/verify", { token: discovery.token }); + const authResult = await client.call("auth/verify", { token: discovery.token }); if (!authResult?.ok) { throw createError("AUTH_FAILED", "Failed to authenticate to Netcatty TCP bridge."); } try { - const statusResult = await call("netcatty/getStatus", {}); - if (Number.isFinite(statusResult?.commandTimeoutMs) && statusResult.commandTimeoutMs > 0) { - bridgeCommandTimeoutMs = statusResult.commandTimeoutMs; - } - if (typeof statusResult?.permissionMode === "string") { - bridgePermissionMode = statusResult.permissionMode; - } - if (Number.isFinite(statusResult?.approvalTimeoutMs) && statusResult.approvalTimeoutMs > 0) { - bridgeApprovalTimeoutMs = statusResult.approvalTimeoutMs; - } + const statusResult = await client.call("netcatty/getStatus", {}); + client.ingestBridgeStatus(statusResult); } catch { // Keep the default RPC timeout when bridge status cannot be fetched. } @@ -242,14 +89,10 @@ async function connectClient() { return { discovery, async call(method, params) { - return await call(method, params); + return await client.call(method, params); }, close() { - try { - socket.end(); - } catch { - // ignore shutdown errors - } + client.close(); }, }; } diff --git a/package.json b/package.json index 982f3d923..8b0d91d04 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,7 @@ "tool:cli": "node electron/cli/netcatty-tool-cli.cjs", "lint": "eslint .", "lint:fix": "eslint . --fix", - "test": "node --test --import tsx electron/*.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/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/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/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/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/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", From 355488f4d04dd82f86f642f90dc42ddb493cd229 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 13:59:39 +0800 Subject: [PATCH 007/228] feat(copilot): Skills CLI mode for Copilot backend (#1617) * feat(copilot): support Skills CLI mode alongside MCP Wire Copilot sessions to respect toolIntegrationMode: MCP keeps the existing netcatty-mcp-only gate, while Skills exposes bash/skill tools, passes CLI discovery env to the runtime, and approves shell commands that invoke netcatty-tool-cli. Co-authored-by: Cursor * test(copilot): restore driver tests and cover skills CLI mode Merge the new Skills-mode assertions with the existing copilot driver suite instead of replacing it. Co-authored-by: Cursor * fix(copilot): harden Skills shell gate against chained commands Validate only the local netcatty-tool-cli prefix (before exec `--` payloads), reject shell wrappers/chaining operators, and require the invocation to start with the CLI launcher or script path. Co-authored-by: Cursor * fix(copilot): block backtick substitution and drop skill builtin Reject backticks in the local CLI prefix and expose only builtin:bash in Skills mode; CLI workflow instructions already come from the host prompt. Co-authored-by: Cursor * fix(copilot): quote-aware shell gate and strict CLI name match Use the last unquoted exec delimiter for local-prefix checks, scan metachars outside quotes only, and require an exact netcatty-tool-cli launcher token. Co-authored-by: Cursor * fix(copilot): tighten exec delimiter and Windows CLI launcher match Only honor ` -- ` payloads for exec/job-start, scan full local commands for redirection/chaining, and accept netcatty-tool-cli.cmd with Windows paths. Co-authored-by: Cursor * fix(copilot): reject quoted substitution and unqualified CLI paths Block $(...) and backticks inside double quotes, require absolute/relative path prefixes for non-node launchers, and fix quoted launcher path matching. Co-authored-by: Cursor * fix(copilot): anchor shell metachar scan and block exec chaining Match metacharacters only at the current scan offset, scan the full shell command for exec turns, and require quoted remote payloads for chained ops. Co-authored-by: Cursor --------- Co-authored-by: Cursor --- .../bridges/aiBridge/sdk/copilotDriver.cjs | 205 +++++++++++++++++- .../aiBridge/sdk/copilotDriver.test.cjs | 96 +++++++- electron/bridges/aiBridge/sdk/index.cjs | 3 + 3 files changed, 296 insertions(+), 8 deletions(-) diff --git a/electron/bridges/aiBridge/sdk/copilotDriver.cjs b/electron/bridges/aiBridge/sdk/copilotDriver.cjs index 6ece31e58..f35dbed22 100644 --- a/electron/bridges/aiBridge/sdk/copilotDriver.cjs +++ b/electron/bridges/aiBridge/sdk/copilotDriver.cjs @@ -11,9 +11,14 @@ * (bring-your-own-CLI), so we MUST point `connection` at the user's system * `copilot` binary via RuntimeConnection.forStdio({ path }) — otherwise the SDK * falls back to the (absent) bundled runtime in the shipped app. - * - Side effects route through the injected netcatty MCP server (stdio). The - * SDK-level permission handler rejects local Copilot tools and allows only - * MCP requests; netcatty MCP then enforces approval/scope/blocklist. + * - MCP mode: side effects route through the injected netcatty MCP server + * (stdio). The permission handler rejects local Copilot tools and allows + * only MCP requests; netcatty MCP then enforces approval/scope/blocklist. + * - Skills mode: only builtin bash is exposed (CLI instructions are injected via + * the host prompt; the skill builtin is omitted because its read/custom-tool + * permission kinds are not shell-safe to auto-approve). Shell permission + * requests are approved only for Netcatty CLI invocations; discovery env is + * passed to the Copilot runtime so `netcatty-tool-cli` can reach the host. * * 🔬 SMOKE-CALIBRATE [copilot-stream]: sendAndWait returns only the final * assistant text. A follow-up can subscribe via session.on(handler) to stream @@ -48,7 +53,13 @@ function toCopilotMcpServers(injectedMcpServers) { return map; } -function buildCopilotSessionOptions({ model, injectedMcpServers }) { +const COPILOT_SKILLS_AVAILABLE_TOOLS = ["builtin:bash"]; + +function copilotBuiltinTools(toolIntegrationMode) { + return toolIntegrationMode === "skills" ? [...COPILOT_SKILLS_AVAILABLE_TOOLS] : null; +} + +function buildCopilotSessionOptions({ model, injectedMcpServers, toolIntegrationMode }) { // onPermissionRequest is wired in runCopilotTurn (it needs the SDK's approveAll). const options = { mcpServers: toCopilotMcpServers(injectedMcpServers), @@ -58,10 +69,145 @@ function buildCopilotSessionOptions({ model, injectedMcpServers }) { // has live reasoning to render. streaming: true, }; + const availableTools = copilotBuiltinTools(toolIntegrationMode); + if (availableTools) options.availableTools = availableTools; if (model) options.model = model; return options; } +// Shell chaining/redirection in the local Netcatty CLI prefix (not after exec `--`). +const LOCAL_SHELL_METACHAR_PATTERN = /(?:[;&|`]|&&|\|\||\$\(|\$\{|<{1,2}|\r?\n)/; +const LOCAL_SHELL_WRAPPER_PATTERN = /^(?:\/[^\s]+\/)?(?:ba|z|fi)?sh(?:\.exe)?\s+-c\b/i; +const NETCATTY_CLI_TOKEN = String.raw`netcatty-tool-cli(?:\.(?:cjs|cmd))?`; +const NETCATTY_CLI_PATH_SUFFIX = String.raw`(?:[\\/]|^)${NETCATTY_CLI_TOKEN}`; + +/** Find the last exec/job-start payload separator outside shell quotes. */ +function findExecPayloadSeparatorIndex(command) { + const text = String(command || ""); + let inSingle = false; + let inDouble = false; + let escape = false; + let lastIndex = -1; + + for (let i = 0; i < text.length; i += 1) { + const ch = text[i]; + if (escape) { + escape = false; + continue; + } + if (ch === "\\" && (inSingle || inDouble)) { + escape = true; + continue; + } + if (!inDouble && ch === "'") { + inSingle = !inSingle; + continue; + } + if (!inSingle && ch === '"') { + inDouble = !inDouble; + continue; + } + if (!inSingle && !inDouble && text.startsWith(" -- ", i)) { + lastIndex = i; + i += 3; + } + } + return lastIndex; +} + +function matchesShellMetacharAt(text, index) { + const match = LOCAL_SHELL_METACHAR_PATTERN.exec(String(text || "").slice(index)); + return Boolean(match && match.index === 0); +} + +function containsUnsafeShellMetachar(text) { + let inSingle = false; + let inDouble = false; + let escape = false; + + for (let i = 0; i < text.length; i += 1) { + const ch = text[i]; + if (escape) { + escape = false; + continue; + } + if (ch === "\\" && (inSingle || inDouble)) { + escape = true; + continue; + } + if (!inDouble && ch === "'") { + inSingle = !inSingle; + continue; + } + if (!inSingle && ch === '"') { + inDouble = !inDouble; + continue; + } + if (inSingle) continue; + if (inDouble) { + if (text.startsWith("$(", i) || ch === "`") return true; + continue; + } + if (matchesShellMetacharAt(text, i)) return true; + } + return false; +} + +/** Split before the final exec/job-start remote payload (` -- cmd`), not flag values. */ +function getLocalNetcattyCliPrefix(fullCommandText) { + const command = String(fullCommandText || "").trim(); + const splitAt = findExecPayloadSeparatorIndex(command); + if (splitAt >= 0) { + return command.slice(0, splitAt).trim(); + } + return command; +} + +function isNetcattyCliInvocationPrefix(localPart) { + const text = String(localPart || "").trim(); + if (!text) return false; + const pathPrefix = String.raw`(?:\.\./|\./|/|[A-Za-z]:[\\/])[\w. \\-]*[\\/]`; + const invocation = new RegExp( + String.raw`^(?:(?:[A-Za-z_][\w.-]*=[^\s]+\s+)*)?(?:` + + String.raw`"[^"]*${NETCATTY_CLI_PATH_SUFFIX}"|` + + String.raw `'[^']*${NETCATTY_CLI_PATH_SUFFIX}'|` + + String.raw `${NETCATTY_CLI_TOKEN}(?=\s|$)|` + + String.raw `${pathPrefix}${NETCATTY_CLI_TOKEN}(?=\s|$)|` + + String.raw `node\s+(?:${NETCATTY_CLI_TOKEN}(?=\s|$)|${pathPrefix}${NETCATTY_CLI_TOKEN}(?=\s|$)|` + + String.raw `(?:[\w.-]+(?:[\\/][\w.-]+)*[\\/])?${NETCATTY_CLI_TOKEN}(?=\s|$)|` + + String.raw `"[^"]*${NETCATTY_CLI_PATH_SUFFIX}"|'[^']*${NETCATTY_CLI_PATH_SUFFIX}'))`, + "i", + ); + return invocation.test(text); +} + +function hasExecPayloadSubcommand(localPart) { + return /\b(?:exec|job-start)\b/i.test(String(localPart || "")); +} + +function isLikelyNetcattyCliShellCommand(fullCommandText) { + const command = String(fullCommandText || "").trim(); + if (!command) return false; + + const splitAt = findExecPayloadSeparatorIndex(command); + const localPart = splitAt >= 0 ? command.slice(0, splitAt).trim() : command; + const remotePayload = splitAt >= 0 ? command.slice(splitAt + 4).trim() : ""; + + if (!localPart || LOCAL_SHELL_WRAPPER_PATTERN.test(localPart)) return false; + if (!isNetcattyCliInvocationPrefix(localPart)) return false; + + if (remotePayload) { + if (!hasExecPayloadSubcommand(localPart)) return false; + if (containsUnsafeShellMetachar(localPart)) return false; + // The runtime executes fullCommandText in a local shell; scan all of it so + // tokens after `--` cannot chain additional local commands unless quoted. + if (containsUnsafeShellMetachar(command)) return false; + return true; + } + + return !containsUnsafeShellMetachar(command); +} + function approveNetcattyMcpOnly(request) { if (request?.kind === "mcp" && request?.toolName) { return { kind: "approve-once" }; @@ -72,6 +218,28 @@ function approveNetcattyMcpOnly(request) { }; } +function approveNetcattyCliShellOnly(request) { + if (request?.kind === "shell") { + const fullCommandText = request.fullCommandText || ""; + if (isLikelyNetcattyCliShellCommand(fullCommandText)) { + return { kind: "approve-once" }; + } + return { + kind: "reject", + feedback: + "Only Netcatty CLI shell commands are allowed. Invoke the netcatty-tool-cli launcher or script prefix provided in the host context, and include --chat-session on every call.", + }; + } + return { + kind: "reject", + feedback: "Only Netcatty CLI shell commands are allowed from this integration.", + }; +} + +function buildCopilotPermissionHandler(toolIntegrationMode) { + return toolIntegrationMode === "skills" ? approveNetcattyCliShellOnly : approveNetcattyMcpOnly; +} + function extractCopilotContent(response) { return (response && response.data && response.data.content) || ""; } @@ -178,7 +346,18 @@ function translateCopilotEvent(event, emitter, state) { * @param {AbortSignal} [args.signal] * @param {object} [args.sdkModule] inject the @github/copilot-sdk module (for tests) */ -async function runCopilotTurn({ prompt, attachments, clientOptions, sessionOptions, resumeSessionId, emitter, signal, sdkModule }) { +async function runCopilotTurn({ + prompt, + attachments, + clientOptions, + sessionOptions, + resumeSessionId, + toolIntegrationMode, + runtimeEnv, + emitter, + signal, + sdkModule, +}) { let resolvedModule = sdkModule; if (!resolvedModule) { try { resolvedModule = await import("@github/copilot-sdk"); } catch { emitter.emitError("GitHub Copilot SDK not installed. Run: npm install @github/copilot-sdk"); return { sessionId: null }; } @@ -190,6 +369,9 @@ async function runCopilotTurn({ prompt, attachments, clientOptions, sessionOptio // (the bundled runtime is excluded from packaging) and authenticate as the // logged-in user (gh CLI / stored OAuth). const realClientOptions = { useLoggedInUser: true }; + if (runtimeEnv && typeof runtimeEnv === "object") { + realClientOptions.env = runtimeEnv; + } if (clientOptions?.cliPath && RuntimeConnection?.forStdio) { realClientOptions.connection = RuntimeConnection.forStdio({ path: clientOptions.cliPath }); } @@ -202,8 +384,8 @@ async function runCopilotTurn({ prompt, attachments, clientOptions, sessionOptio const sessionConfig = { ...sessionOptions, streaming: true, - // Allow only MCP calls; netcatty MCP performs scope/approval/blocklist checks. - onPermissionRequest: approveNetcattyMcpOnly, + // MCP mode: only netcatty MCP. Skills mode: only Netcatty CLI shell commands. + onPermissionRequest: buildCopilotPermissionHandler(toolIntegrationMode), }; // Resume the prior conversation so context carries ACROSS turns (incl. after // a Stop). Always (re)apply sessionConfig so the FRESH netcatty MCP server @@ -335,7 +517,16 @@ module.exports = { buildCopilotClientOptions, buildCopilotSessionOptions, buildCopilotMessageOptions, + buildCopilotPermissionHandler, approveNetcattyMcpOnly, + approveNetcattyCliShellOnly, + isLikelyNetcattyCliShellCommand, + getLocalNetcattyCliPrefix, + findExecPayloadSeparatorIndex, + containsUnsafeShellMetachar, + matchesShellMetacharAt, + hasExecPayloadSubcommand, + copilotBuiltinTools, toCopilotMcpServers, extractCopilotContent, extractCopilotResultText, diff --git a/electron/bridges/aiBridge/sdk/copilotDriver.test.cjs b/electron/bridges/aiBridge/sdk/copilotDriver.test.cjs index e08dc5732..9c60f3082 100644 --- a/electron/bridges/aiBridge/sdk/copilotDriver.test.cjs +++ b/electron/bridges/aiBridge/sdk/copilotDriver.test.cjs @@ -1,6 +1,6 @@ const test = require("node:test"); const assert = require("node:assert/strict"); -const { approveNetcattyMcpOnly, buildCopilotClientOptions, buildCopilotSessionOptions, buildCopilotMessageOptions, extractCopilotContent, mapCopilotModels, runCopilotTurn, translateCopilotEvent } = require("./copilotDriver.cjs"); +const { approveNetcattyMcpOnly, approveNetcattyCliShellOnly, buildCopilotClientOptions, buildCopilotPermissionHandler, buildCopilotSessionOptions, buildCopilotMessageOptions, copilotBuiltinTools, extractCopilotContent, isLikelyNetcattyCliShellCommand, mapCopilotModels, runCopilotTurn, translateCopilotEvent } = require("./copilotDriver.cjs"); function collector() { const events = []; @@ -26,6 +26,7 @@ function makeSdk(captured) { async sendAndWait({ prompt }) { captured.prompt = prompt; return { data: { content: "reply:" + sessionId } }; }, }); class CopilotClient { + constructor(options) { captured.clientOptions = options; } async createSession(cfg) { captured.created = cfg; return makeSession("sess-new"); } async resumeSession(id, cfg) { captured.resumed = { id, cfg }; return makeSession(id); } async stop() {} @@ -261,3 +262,96 @@ test("runCopilotTurn aborts the active Copilot session when the signal aborts", assert.equal(events.some((event) => event.k === "text" && event.t === "late text"), false); assert.equal(events.some((event) => event.k === "done"), false); }); + +test("copilotBuiltinTools exposes bash only in skills mode", () => { + assert.equal(copilotBuiltinTools("mcp"), null); + assert.deepEqual(copilotBuiltinTools("skills"), ["builtin:bash"]); +}); + +test("buildCopilotSessionOptions whitelists bash in skills mode", () => { + const skills = buildCopilotSessionOptions({ + model: "gpt-5", + injectedMcpServers: [], + toolIntegrationMode: "skills", + }); + assert.deepEqual(skills.availableTools, ["builtin:bash"]); + assert.deepEqual(skills.mcpServers, {}); +}); + +test("approveNetcattyCliShellOnly allows Netcatty CLI shell commands only", () => { + assert.deepEqual( + approveNetcattyCliShellOnly({ + kind: "shell", + fullCommandText: 'node "/Applications/Netcatty.app/netcatty-tool-cli.cjs" env --chat-session abc --json', + }), + { kind: "approve-once" }, + ); + assert.equal( + approveNetcattyCliShellOnly({ kind: "shell", fullCommandText: "pwd" }).kind, + "reject", + ); +}); + +test("buildCopilotPermissionHandler selects MCP vs skills gate", () => { + assert.equal(buildCopilotPermissionHandler("mcp"), approveNetcattyMcpOnly); + assert.equal(buildCopilotPermissionHandler("skills"), approveNetcattyCliShellOnly); +}); + +test("isLikelyNetcattyCliShellCommand matches launcher and script invocations", () => { + assert.equal(isLikelyNetcattyCliShellCommand("netcatty-tool-cli status --json"), true); + assert.equal(isLikelyNetcattyCliShellCommand("node electron/cli/netcatty-tool-cli.cjs env --json"), true); + assert.equal(isLikelyNetcattyCliShellCommand("ls -la"), false); +}); + +test("isLikelyNetcattyCliShellCommand rejects chained or wrapped local commands", () => { + assert.equal(isLikelyNetcattyCliShellCommand("rm -rf /; netcatty-tool-cli status --json"), false); + assert.equal(isLikelyNetcattyCliShellCommand("netcatty-tool-cli status --json && curl evil"), false); + assert.equal(isLikelyNetcattyCliShellCommand('bash -c "netcatty-tool-cli status --json"'), false); + assert.equal(isLikelyNetcattyCliShellCommand("malicious netcatty-tool-cli status --json"), false); + assert.equal(isLikelyNetcattyCliShellCommand("netcatty-tool-cli status `id` --json"), false); +}); + +test("isLikelyNetcattyCliShellCommand allows quoted remote exec payloads after --", () => { + assert.equal( + isLikelyNetcattyCliShellCommand('netcatty-tool-cli exec --session s1 --chat-session c1 --json -- "hostname && whoami"'), + true, + ); + assert.equal( + isLikelyNetcattyCliShellCommand("netcatty-tool-cli exec --session s1 --chat-session c1 --json -- hostname && whoami"), + false, + ); +}); + +test("isLikelyNetcattyCliShellCommand rejects impostor binaries and quoted -- bypasses", () => { + assert.equal(isLikelyNetcattyCliShellCommand("netcatty-tool-cli-backup status --json"), false); + assert.equal(isLikelyNetcattyCliShellCommand("netcatty-tool-cli.evil status --json"), false); + assert.equal( + isLikelyNetcattyCliShellCommand('netcatty-tool-cli sftp read --remote-path "a -- b" ; rm -rf /'), + false, + ); + assert.equal( + isLikelyNetcattyCliShellCommand('netcatty-tool-cli sftp read --remote-path "a -- b" --session s1 --json'), + true, + ); + assert.equal(isLikelyNetcattyCliShellCommand("netcatty-tool-cli status --json -- ; rm -rf /"), false); + assert.equal(isLikelyNetcattyCliShellCommand("netcatty-tool-cli status --json > /tmp/out"), false); + assert.equal(isLikelyNetcattyCliShellCommand('"C:\\Apps\\Netcatty\\netcatty-tool-cli.cmd" status --json'), true); + assert.equal(isLikelyNetcattyCliShellCommand("attacker/netcatty-tool-cli status --json"), false); + assert.equal(isLikelyNetcattyCliShellCommand('netcatty-tool-cli status "$(id)" --json'), false); +}); + +test("runCopilotTurn passes runtime env and skills permission handler", async () => { + const { emitter } = collector(); + const captured = {}; + await runCopilotTurn({ + prompt: "hi", + clientOptions: { cliPath: "/c" }, + sessionOptions: { model: "m" }, + toolIntegrationMode: "skills", + runtimeEnv: { NETCATTY_TOOL_CLI_DISCOVERY_FILE: "/tmp/discovery.json" }, + emitter, + sdkModule: makeSdk(captured), + }); + assert.deepEqual(captured.clientOptions.env, { NETCATTY_TOOL_CLI_DISCOVERY_FILE: "/tmp/discovery.json" }); + assert.equal(captured.created.onPermissionRequest, approveNetcattyCliShellOnly); +}); diff --git a/electron/bridges/aiBridge/sdk/index.cjs b/electron/bridges/aiBridge/sdk/index.cjs index 8c723ebfa..d02136439 100644 --- a/electron/bridges/aiBridge/sdk/index.cjs +++ b/electron/bridges/aiBridge/sdk/index.cjs @@ -65,6 +65,7 @@ const DRIVER_REGISTRY = { const sessionOptions = copilot.buildCopilotSessionOptions({ model: ctx.model, injectedMcpServers: ctx.injectedMcpServers, + toolIntegrationMode: ctx.toolIntegrationMode, }); return copilot.runCopilotTurn({ prompt: ctx.prompt, @@ -72,6 +73,8 @@ const DRIVER_REGISTRY = { clientOptions, sessionOptions, resumeSessionId: ctx.resumeSessionId, + toolIntegrationMode: ctx.toolIntegrationMode, + runtimeEnv: ctx.env, emitter: ctx.emitter, signal: ctx.signal, }); From b6da5e60c92639820d3eb87e920f538cebca5040 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 14:10:17 +0800 Subject: [PATCH 008/228] fix(notes): allow clearing default note title (#1610) (#1618) * fix(notes): allow clearing the default note title while editing Stop sanitizeNoteTitle from forcing empty titles back to "Untitled note", so users can delete the placeholder and type a custom title. Co-authored-by: Cursor * fix(notes): allow clearing titles from tree rename Remove the empty-title guard in sidebar tree rename so it matches the main title editor behavior. Co-authored-by: Cursor --------- Co-authored-by: Cursor --- components/notes/NotesManager.test.tsx | 14 ++++++++++++++ components/notes/NotesManager.tsx | 10 +++++----- domain/notes.test.ts | 10 +++++++++- domain/notes.ts | 6 ++---- 4 files changed, 30 insertions(+), 10 deletions(-) diff --git a/components/notes/NotesManager.test.tsx b/components/notes/NotesManager.test.tsx index 658994027..97b123be3 100644 --- a/components/notes/NotesManager.test.tsx +++ b/components/notes/NotesManager.test.tsx @@ -228,6 +228,20 @@ test("NotesManager exposes markdown import controls", () => { assert.match(source, /multiple/); }); +test("NotesManager shows placeholder label for notes without titles", () => { + const markup = renderNotes([note({ title: "" })]); + + assert.match(markup, /Note title/); +}); + +test("NotesManager tree rename allows clearing note titles", () => { + const source = readFileSync(new URL("./NotesManager.tsx", import.meta.url), "utf8"); + const renameBlock = source.match(/onRenameCommit=\{\(name\) => \{[\s\S]*?\}\}/)?.[0] ?? ""; + + assert.match(renameBlock, /saveNote\(\{ \.\.\.note, title: name\.trim\(\)/); + assert.doesNotMatch(renameBlock, /if \(!title\) return/); +}); + test("NotesManager sidebar mode renders list without editor by default", () => { const markup = renderNotes([note()], "sidebar"); diff --git a/components/notes/NotesManager.tsx b/components/notes/NotesManager.tsx index d13f1473c..684150c67 100644 --- a/components/notes/NotesManager.tsx +++ b/components/notes/NotesManager.tsx @@ -181,7 +181,7 @@ const createNote = (group: string | null, order: number): VaultNote => { const now = Date.now(); return { id: crypto.randomUUID(), - title: "Untitled note", + title: "", content: "", group: group || undefined, createdAt: now, @@ -934,22 +934,22 @@ export const NotesManager: React.FC = ({ ); }; + const noteDisplayTitle = (title: string) => title || t("notes.title.placeholder"); + const renderNoteRow = (note: VaultNote, depth: number) => { if (!noteMatches(note)) return null; return ( { setEditingNoteId(null); - const title = name.trim(); - if (!title) return; - saveNote({ ...note, title, updatedAt: Date.now() }); + saveNote({ ...note, title: name.trim(), updatedAt: Date.now() }); }} onRenameCancel={() => setEditingNoteId(null)} icon={} diff --git a/domain/notes.test.ts b/domain/notes.test.ts index a3fbae1e6..211b6207c 100644 --- a/domain/notes.test.ts +++ b/domain/notes.test.ts @@ -11,17 +11,25 @@ import { remapExpandedNoteGroupPaths, resolveMovedNoteGroupPath, resolveRenderedMarkdownLinkHref, + sanitizeNoteTitle, sanitizeVaultNote, } from "./notes"; test("sanitizeVaultNote supplies safe defaults", () => { const note = sanitizeVaultNote({ title: " ", content: 123 as never }); - assert.equal(note.title, "Untitled note"); + assert.equal(note.title, ""); assert.equal(note.content, ""); assert.equal(typeof note.id, "string"); assert.equal(typeof note.createdAt, "number"); }); +test("sanitizeNoteTitle preserves non-empty titles and allows empty titles", () => { + assert.equal(sanitizeNoteTitle(" My note "), "My note"); + assert.equal(sanitizeNoteTitle(""), ""); + assert.equal(sanitizeNoteTitle(" "), ""); + assert.equal(sanitizeNoteTitle(undefined), ""); +}); + test("normalizeVaultNotes trims group and de-duplicates tags", () => { const notes = normalizeVaultNotes([ { diff --git a/domain/notes.ts b/domain/notes.ts index 2103ed378..c34ac6c68 100644 --- a/domain/notes.ts +++ b/domain/notes.ts @@ -14,10 +14,8 @@ const cleanStringArray = (values: unknown): string[] | undefined => { return cleaned.length ? cleaned : undefined; }; -export const sanitizeNoteTitle = (title: unknown): string => { - const value = typeof title === "string" ? title.trim() : ""; - return value || "Untitled note"; -}; +export const sanitizeNoteTitle = (title: unknown): string => + typeof title === "string" ? title.trim() : ""; export const sanitizeVaultNote = (note: Partial): VaultNote => { const now = Date.now(); From 278f528deb6259b4d7d0312ec37a5091b6eb63a2 Mon Sep 17 00:00:00 2001 From: mam15mon Date: Wed, 24 Jun 2026 14:16:16 +0800 Subject: [PATCH 009/228] Improve terminal keyword highlight refresh (#1619) * improve terminal keyword highlight refresh * fix(terminal): address Codex review on keyword highlight refresh Map viewport probe diffs to line numbers so off-cursor ANSI redraws mark the rewritten line dirty without forcing full-viewport rescans on normal typing, and cache wrapped-line context per processLineRange to avoid repeated scans. Co-authored-by: Cursor --------- Co-authored-by: mam15mon Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com> Co-authored-by: Cursor --- components/terminal/keywordHighlight.ts | 1162 +++++++++++++++-- .../terminal/keywordHighlightRegex.test.ts | 38 + components/terminal/keywordHighlightRegex.ts | 24 + infrastructure/config/xtermPerformance.ts | 18 +- lib/regexSafety.ts | 53 + 5 files changed, 1172 insertions(+), 123 deletions(-) create mode 100644 components/terminal/keywordHighlightRegex.test.ts create mode 100644 components/terminal/keywordHighlightRegex.ts create mode 100644 lib/regexSafety.ts diff --git a/components/terminal/keywordHighlight.ts b/components/terminal/keywordHighlight.ts index a029419f9..58a3f805a 100644 --- a/components/terminal/keywordHighlight.ts +++ b/components/terminal/keywordHighlight.ts @@ -1,19 +1,54 @@ -import { Terminal as XTerm, IDecoration, IDisposable, IMarker, IBufferLine } from "@xterm/xterm"; +import { Terminal as XTerm, IDecoration, IDisposable, IMarker, IBuffer, IBufferLine } from "@xterm/xterm"; import { KeywordHighlightRule } from "../../types"; import { XTERM_PERFORMANCE_CONFIG } from "../../infrastructure/config/xtermPerformance"; +import { checkRegexSafetyPattern } from "../../lib/regexSafety"; +import { forEachNonEmptyRegexMatch } from "./keywordHighlightRegex"; /** Pre-compiled rule with regex ready for matching */ interface CompiledRule { regex: RegExp; color: string; + priority: number; } interface CachedDecorationRange { x: number; width: number; color: string; + priority: number; +} + +interface DirtyLineSegment { + start: number; + end: number; +} + +interface LineDecorationState { + marker: IMarker; + decorations: IDecoration[]; + signature: string; +} + +type RefreshReason = "scroll" | "write" | "full"; + +interface BufferSnapshot { + length: number; + baseY: number; + viewportY: number; + cursorAbsoluteY: number; + viewportProbe: readonly ViewportProbeSample[]; +} + +interface ViewportProbeSample { + lineY: number; + hash: number; +} + +interface WrappedBlockContext { + logicalLineText: string; + segmentBounds: Map; } /** Shared empty array for non-matching lines to avoid per-call allocations. */ @@ -31,7 +66,7 @@ const RE_ASCII_ONLY = /^[\x00-\x7f]*$/; export class KeywordHighlighter implements IDisposable { private term: XTerm; private compiledRules: CompiledRule[] = []; - private decorations: { decoration: IDecoration; marker: IMarker }[] = []; + private lineDecorations = new Map(); private debounceTimer: NodeJS.Timeout | null = null; private animationFrameId: number | null = null; private lastRefreshTime: number = 0; @@ -39,6 +74,29 @@ export class KeywordHighlighter implements IDisposable { private enabled: boolean = false; private disposables: IDisposable[] = []; private lastViewportY: number = -1; + private lastViewportRange: { start: number; end: number } | null = null; + private lastRenderRange: { start: number; end: number } | null = null; + private pendingRefreshReason: RefreshReason = "write"; + private dirtySegments: DirtyLineSegment[] = []; + private dirtyLineCount = 0; + private dirtyAllInRenderRange = false; + private activeRefreshViewport: DirtyLineSegment | null = null; + private pendingTerminalRefreshRange: DirtyLineSegment | null = null; + private lastBufferSnapshot: BufferSnapshot | null = null; + private recentWriteBurst = 0; + private lastWriteAt = 0; + private lastBurstDecayAt = 0; + private forceViewportReconcileOnNextScroll = false; + private static readonly DIRTY_SCAN_PADDING = XTERM_PERFORMANCE_CONFIG.highlighting.dirtyScanPadding; + private static readonly WRITE_BURST_INTERVAL_MS = 28; + private static readonly WRITE_BURST_DECAY_MS = 80; + private static readonly WRITE_BURST_THRESHOLD = 6; + private static readonly WRITE_BURST_OVERSCAN_SCALE = 0.35; + private static readonly WRITE_BURST_BUDGET_SCALE = 0.5; + private static readonly WRITE_BURST_CHUNK_SCALE = 0.5; + private static readonly WRITE_BURST_DEBOUNCE_MS = 140; + private static readonly WRITE_BURST_IMMEDIATE_MIN_INTERVAL_MS = 32; + private static readonly WRITE_BURST_HIGHLIGHT_PAUSE_MS = 180; constructor(term: XTerm) { this.term = term; @@ -47,25 +105,27 @@ export class KeywordHighlighter implements IDisposable { this.disposables.push( // When user scrolls, refresh visible area this.term.onScroll(() => { - this.triggerRefresh("debounced"); + this.triggerRefresh("immediate", "scroll"); }), // When new data is written, refresh on the next frame so highlights land // with the freshly rendered content instead of trailing behind it. this.term.onWriteParsed(() => { - this.triggerRefresh("immediate"); + this.markDirtyFromWrite(); + this.triggerRefresh("immediate", "write"); }), // Also refresh on resize as viewport content changes - this.term.onResize(() => this.triggerRefresh("debounced")), + this.term.onResize(() => this.triggerRefresh("debounced", "full")), // onRender fires after each render cycle - catch scrolls that onScroll might miss this.term.onRender(() => { // Only trigger refresh if viewport position changed const currentViewportY = this.term.buffer.active?.viewportY ?? 0; if (currentViewportY !== this.lastViewportY) { this.lastViewportY = currentViewportY; - this.triggerRefresh("debounced"); + this.triggerRefresh("immediate", "scroll"); } }) ); + this.lastBufferSnapshot = this.readBufferSnapshot(); } public setRules(rules: KeywordHighlightRule[], enabled: boolean) { @@ -75,13 +135,20 @@ export class KeywordHighlighter implements IDisposable { // Pre-compile all patterns into regexes for better performance // This avoids creating new RegExp objects on every viewport refresh this.compiledRules = []; - for (const rule of rules) { + for (const [ruleIndex, rule] of rules.entries()) { if (!rule.enabled || rule.patterns.length === 0) continue; for (const pattern of rule.patterns) { + if (!pattern) continue; // Skip empty patterns — RegExp("") is valid but matches nothing useful + const safetyCheck = checkRegexSafetyPattern(pattern); + if (safetyCheck.safe === false) { + console.warn("[KeywordHighlight] Skipping unsafe regex pattern:", pattern, "reason:", safetyCheck.reason); + continue; + } try { this.compiledRules.push({ regex: new RegExp(pattern, "gi"), color: rule.color, + priority: ruleIndex, }); } catch (err) { console.error("Invalid regex pattern:", pattern, err); @@ -92,7 +159,7 @@ export class KeywordHighlighter implements IDisposable { // Clear existing and force an immediate refresh if enabling this.clearDecorations(); if (this.enabled && this.compiledRules.length > 0) { - this.triggerRefresh("immediate"); + this.triggerRefresh("immediate", "full"); } } @@ -110,69 +177,6 @@ export class KeywordHighlighter implements IDisposable { this.matchCache.clear(); } - private triggerRefresh(mode: "immediate" | "debounced") { - if (!this.enabled || this.compiledRules.length === 0) return; - - // Optimization: Disable highlighting in Alternate Buffer (e.g. Vim, Htop) - // These apps manage their own highlighting and have rapid repaints. - if (this.term.buffer.active.type === 'alternate') { - if (this.decorations.length > 0) { - this.clearDecorations(); - } - return; - } - - if (mode === "immediate") { - // Throttle: skip if a rAF is already pending. - // Don't clear the debounce timer here — in a hidden tab rAF never - // fires, so the fallback timer is the only path that will run. - if (this.animationFrameId !== null) { - return; - } - const now = performance.now(); - const minInterval = XTERM_PERFORMANCE_CONFIG.highlighting.immediateMinIntervalMs; - if (now - this.lastRefreshTime < minInterval) { - // Too soon — fall through to debounced path instead of dropping - this.triggerRefresh("debounced"); - return; - } - this.animationFrameId = requestAnimationFrame(() => { - this.animationFrameId = null; - // rAF fired — cancel the fallback timer to avoid a redundant refresh - if (this.debounceTimer) { - clearTimeout(this.debounceTimer); - this.debounceTimer = null; - } - this.executeRefresh(); - }); - // Arm a debounced fallback: rAF does not fire in background/hidden - // tabs (Chromium throttles it), so the timer ensures highlights - // still update for ongoing output. If rAF fires first it cancels - // this timer (see above), preventing a double refresh. - if (!this.debounceTimer) { - this.debounceTimer = setTimeout(() => { - this.debounceTimer = null; - this.executeRefresh(); - }, XTERM_PERFORMANCE_CONFIG.highlighting.debounceMs); - } - return; - } - - if (this.animationFrameId !== null) { - return; - } - - if (this.debounceTimer) { - clearTimeout(this.debounceTimer); - } - - const delay = XTERM_PERFORMANCE_CONFIG.highlighting.debounceMs; - this.debounceTimer = setTimeout(() => { - this.debounceTimer = null; - this.executeRefresh(); - }, delay); - } - /** Shared refresh execution for both rAF and timer callbacks. */ private executeRefresh() { // Cancel any stale rAF that will never fire (e.g. hidden tab) @@ -183,19 +187,106 @@ export class KeywordHighlighter implements IDisposable { // Re-check state: may have changed since the refresh was scheduled if (!this.enabled || this.compiledRules.length === 0) return; if (this.term.buffer.active.type === 'alternate') { - if (this.decorations.length > 0) this.clearDecorations(); + if (this.lineDecorations.size > 0) this.clearDecorations(); return; } this.lastRefreshTime = performance.now(); - this.refreshViewport(); + const reason = this.pendingRefreshReason; + this.pendingRefreshReason = "write"; + this.refreshViewport(reason); + this.lastBufferSnapshot = this.readBufferSnapshot(); } private clearDecorations() { - this.decorations.forEach(({ decoration, marker }) => { - decoration.dispose(); + const hadDecorations = this.lineDecorations.size > 0; + for (const [lineY, state] of this.lineDecorations) { + this.disposeLineDecorations(lineY, state); + } + this.lineDecorations.clear(); + this.lastViewportRange = null; + this.lastRenderRange = null; + this.clearDirtySegments(); + this.dirtyAllInRenderRange = false; + if (hadDecorations) { + this.term.refresh(0, this.term.rows - 1); + } + } + + private disposeLineDecorations(lineY: number, state?: LineDecorationState) { + const target = state ?? this.lineDecorations.get(lineY); + if (!target) return; + const removedLineY = this.removeLineDecorationState(target, lineY); + const markerLineBeforeDispose = target.marker.isDisposed ? -1 : target.marker.line; + target.decorations.forEach((decoration) => decoration.dispose()); + target.marker.dispose(); + const refreshLine = removedLineY ?? (markerLineBeforeDispose >= 0 ? markerLineBeforeDispose : lineY); + this.markTerminalRefreshNeeded(refreshLine); + } + + private removeLineDecorationState(target: LineDecorationState, lineHint?: number): number | null { + if (lineHint != null) { + const hinted = this.lineDecorations.get(lineHint); + if (hinted === target) { + this.lineDecorations.delete(lineHint); + return lineHint; + } + } + for (const [mappedLineY, mappedState] of this.lineDecorations) { + if (mappedState === target) { + this.lineDecorations.delete(mappedLineY); + return mappedLineY; + } + } + return null; + } + + private buildRangesSignature(ranges: readonly CachedDecorationRange[]): string { + if (ranges.length === 0) return ""; + let signature = ""; + for (const range of ranges) { + signature += `${range.x}:${range.width}:${range.color};`; + } + return signature; + } + + private applyLineDecorations( + lineY: number, + ranges: readonly CachedDecorationRange[], + signature: string, + cursorAbsoluteY: number, + ) { + const offset = lineY - cursorAbsoluteY; + const marker = this.term.registerMarker(offset); + if (!marker) { + this.lineDecorations.delete(lineY); + return; + } + + const decorations: IDecoration[] = []; + for (const range of ranges) { + const decoration = this.term.registerDecoration({ + marker, + x: range.x, + width: range.width, + foregroundColor: range.color, + }); + if (decoration) { + decorations.push(decoration); + } + } + + if (decorations.length === 0) { marker.dispose(); + this.lineDecorations.delete(lineY); + return; + } + + this.lineDecorations.set(lineY, { + marker, + decorations, + signature, }); - this.decorations = []; + this.markTerminalRefreshNeeded(lineY); } /** @@ -241,55 +332,724 @@ export class KeywordHighlighter implements IDisposable { return map; } - private refreshViewport() { + private triggerRefresh(mode: "immediate" | "debounced" | "continuation", reason: RefreshReason = "full") { + if (!this.enabled || this.compiledRules.length === 0) return; + this.pendingRefreshReason = this.mergeRefreshReason(this.pendingRefreshReason, reason); + + // Optimization: Disable highlighting in Alternate Buffer (e.g. Vim, Htop) + // These apps manage their own highlighting and have rapid repaints. + if (this.term.buffer.active.type === 'alternate') { + if (this.lineDecorations.size > 0) { + this.clearDecorations(); + } + return; + } + + const now = performance.now(); + if (this.shouldDeferRefreshForWriteBurst(mode, reason, now)) { + // Only cancel a pending rAF when the merged reason is still "write" + // (pure write burst, no scroll pending). If a scroll event has been + // merged, keep the rAF alive so the viewport highlight runs on time. + if (this.pendingRefreshReason === "write" && this.animationFrameId !== null) { + cancelAnimationFrame(this.animationFrameId); + this.animationFrameId = null; + } + if (this.debounceTimer) { + clearTimeout(this.debounceTimer); + } + const delay = this.getWriteBurstDeferDelay(now); + this.debounceTimer = setTimeout(() => { + this.debounceTimer = null; + this.executeRefresh(); + }, delay); + return; + } + + // Prefer true "what you see is what gets highlighted" behavior on scroll: + // process the current viewport immediately instead of waiting for next rAF. + if (mode === "immediate" && reason === "scroll") { + if (this.animationFrameId !== null) { + cancelAnimationFrame(this.animationFrameId); + this.animationFrameId = null; + } + if (this.debounceTimer) { + clearTimeout(this.debounceTimer); + this.debounceTimer = null; + } + this.forceViewportReconcileOnNextScroll = true; + this.executeRefresh(); + return; + } + + if (mode === "continuation") { + if (this.animationFrameId !== null) { + return; + } + this.animationFrameId = requestAnimationFrame(() => { + this.animationFrameId = null; + if (this.debounceTimer) { + clearTimeout(this.debounceTimer); + this.debounceTimer = null; + } + this.executeRefresh(); + }); + // Hidden/background tabs may pause rAF. Keep a timer fallback so + // continuation does not stall indefinitely. + if (!this.debounceTimer) { + this.debounceTimer = setTimeout(() => { + this.debounceTimer = null; + this.executeRefresh(); + }, this.getAdaptiveHighlightingProfile().debounceMs); + } + return; + } + + if (mode === "immediate") { + if (this.animationFrameId !== null) { + // Scroll should preempt queued continuation/write work. + // Cancel the pending frame and reschedule with current viewport intent. + if (reason === "scroll") { + cancelAnimationFrame(this.animationFrameId); + this.animationFrameId = null; + this.forceViewportReconcileOnNextScroll = true; + if (this.debounceTimer) { + clearTimeout(this.debounceTimer); + this.debounceTimer = null; + } + } else { + // Throttle non-scroll immediate refreshes when a frame is already pending. + // Don't clear the debounce timer here — in a hidden tab rAF never + // fires, so the fallback timer is the only path that will run. + return; + } + } + if (this.animationFrameId !== null) { + return; + } + const now = performance.now(); + const minInterval = this.getAdaptiveHighlightingProfile(now).immediateMinIntervalMs; + if (reason !== "scroll" && now - this.lastRefreshTime < minInterval) { + // Too soon — fall through to debounced path instead of dropping + this.triggerRefresh("debounced", reason); + return; + } + this.animationFrameId = requestAnimationFrame(() => { + this.animationFrameId = null; + // rAF fired — cancel the fallback timer to avoid a redundant refresh + if (this.debounceTimer) { + clearTimeout(this.debounceTimer); + this.debounceTimer = null; + } + this.executeRefresh(); + }); + // Arm a debounced fallback: rAF does not fire in background/hidden + // tabs (Chromium throttles it), so the timer ensures highlights + // still update for ongoing output. If rAF fires first it cancels + // this timer (see above), preventing a double refresh. + if (!this.debounceTimer) { + this.debounceTimer = setTimeout(() => { + this.debounceTimer = null; + this.executeRefresh(); + }, this.getAdaptiveHighlightingProfile().debounceMs); + } + return; + } + + if (this.animationFrameId !== null) { + return; + } + + if (this.debounceTimer) { + clearTimeout(this.debounceTimer); + } + + const delay = this.getAdaptiveHighlightingProfile().debounceMs; + this.debounceTimer = setTimeout(() => { + this.debounceTimer = null; + this.executeRefresh(); + }, delay); + } + + private refreshViewport(reason: RefreshReason) { // Safety check just in case if (!this.term?.buffer?.active) return; - const buffer = this.term.buffer.active; const viewportY = buffer.viewportY; const rows = this.term.rows; const cursorY = buffer.cursorY; const baseY = buffer.baseY; const cursorAbsoluteY = baseY + cursorY; + const overscan = this.getOverscanLines(reason); + const viewportStart = viewportY; + const viewportEnd = viewportY + rows - 1; + const rangeStart = Math.max(0, viewportY - overscan); + const rangeEnd = viewportEnd + overscan; - // Clear old decorations to avoid duplicates/memory leaks - this.clearDecorations(); + const previousRange = this.lastRenderRange; + this.beginTerminalRefreshTracking(viewportStart, viewportEnd); + try { + this.reindexLineDecorationsFromMarkers(); - // Iterate only over the visible rows - for (let y = 0; y < rows; y++) { - const lineY = viewportY + y; - const line = buffer.getLine(lineY); - if (!line) continue; + if (reason === "write") { + this.processDirtyLinesInRange(rangeStart, rangeEnd, cursorAbsoluteY, "write"); + } else if (reason === "scroll") { + // Hard scroll mode: rebuild the whole render window synchronously + // (viewport + overscan), avoiding dirty-range races under fast wheel drags. + this.clearLineDecorationsInRange(rangeStart, rangeEnd); + this.processLineRange(rangeStart, rangeEnd, cursorAbsoluteY); + this.removeDirtyRange(rangeStart, rangeEnd); + this.dirtyAllInRenderRange = false; + this.forceViewportReconcileOnNextScroll = false; + } else if (previousRange !== null && this.lineDecorations.size > 0) { + if (rangeStart < previousRange.start) { + this.processLineRange(rangeStart, Math.min(rangeEnd, previousRange.start - 1), cursorAbsoluteY); + } + if (rangeEnd > previousRange.end) { + this.processLineRange(Math.max(rangeStart, previousRange.end + 1), rangeEnd, cursorAbsoluteY); + } + } else { + this.processLineRange(rangeStart, rangeEnd, cursorAbsoluteY); + } - const lineText = line.translateToString(true); // true = trim right whitespace - if (!lineText) continue; - - const cachedRanges = this.getCachedRanges(line, lineText); - if (cachedRanges.length === 0) continue; - - // Calculate offset relative to the absolute cursor position - // offset = targetLineAbs - (baseY + cursorY) - const offset = lineY - cursorAbsoluteY; - - for (const range of cachedRanges) { - const marker = this.term.registerMarker(offset); - - if (marker) { - const deco = this.term.registerDecoration({ - marker, - x: range.x, - width: range.width, - foregroundColor: range.color, - }); - - if (deco) { - this.decorations.push({ decoration: deco, marker }); - } else { - // If decoration failed, cleanup marker - marker.dispose(); - } + for (const [lineY, state] of this.lineDecorations) { + if (lineY < rangeStart || lineY > rangeEnd || state.marker.isDisposed) { + this.disposeLineDecorations(lineY, state); } } + + // `write` refresh only processes dirty lines and does NOT guarantee the whole + // viewport/render range is covered. If we still persist these ranges, later + // scroll refreshes may take an incremental path and incorrectly skip lines. + if (reason === "write") { + this.lastViewportRange = null; + this.lastRenderRange = null; + } else { + this.lastViewportRange = { start: viewportStart, end: viewportEnd }; + const scrollRangeFullyProcessed = + reason !== "scroll" || !this.hasDirtyRangeInWindow(rangeStart, rangeEnd); + this.lastRenderRange = scrollRangeFullyProcessed + ? { start: rangeStart, end: rangeEnd } + : { start: viewportStart, end: viewportEnd }; + } + } finally { + this.flushTerminalRefresh(); + } + } + + private hasDirtyRangeInWindow(start: number, end: number): boolean { + if (end < start) return false; + if (this.dirtyAllInRenderRange) return true; + for (const segment of this.dirtySegments) { + if (segment.end < start) continue; + if (segment.start > end) return false; + return true; + } + return false; + } + + private beginTerminalRefreshTracking(viewportStart: number, viewportEnd: number) { + this.activeRefreshViewport = { start: viewportStart, end: viewportEnd }; + this.pendingTerminalRefreshRange = null; + } + + private markTerminalRefreshNeeded(lineY: number) { + const viewport = this.activeRefreshViewport; + if (!viewport || lineY < viewport.start || lineY > viewport.end) return; + if (!this.pendingTerminalRefreshRange) { + this.pendingTerminalRefreshRange = { start: lineY, end: lineY }; + return; + } + this.pendingTerminalRefreshRange.start = Math.min(this.pendingTerminalRefreshRange.start, lineY); + this.pendingTerminalRefreshRange.end = Math.max(this.pendingTerminalRefreshRange.end, lineY); + } + + private flushTerminalRefresh() { + const viewport = this.activeRefreshViewport; + const refreshRange = this.pendingTerminalRefreshRange; + this.activeRefreshViewport = null; + this.pendingTerminalRefreshRange = null; + if (!viewport || !refreshRange) return; + + const startRow = Math.max(0, refreshRange.start - viewport.start); + const endRow = Math.min(this.term.rows - 1, refreshRange.end - viewport.start); + if (startRow <= endRow) { + this.term.refresh(startRow, endRow); + } + } + + private reindexLineDecorationsFromMarkers() { + if (this.lineDecorations.size === 0) return; + const nextLineDecorations = new Map(); + const staleStates = new Set(); + + for (const state of this.lineDecorations.values()) { + if (state.marker.isDisposed || state.marker.line < 0) { + staleStates.add(state); + continue; + } + const markerLine = state.marker.line; + const existing = nextLineDecorations.get(markerLine); + if (existing && existing !== state) { + staleStates.add(existing); + } + nextLineDecorations.set(markerLine, state); + } + + for (const state of nextLineDecorations.values()) { + staleStates.delete(state); + } + + this.lineDecorations = nextLineDecorations; + + for (const state of staleStates) { + const markerLineBeforeDispose = state.marker.isDisposed ? -1 : state.marker.line; + state.decorations.forEach((decoration) => decoration.dispose()); + state.marker.dispose(); + if (markerLineBeforeDispose >= 0) { + this.markTerminalRefreshNeeded(markerLineBeforeDispose); + } + } + } + + private processDirtyLinesInRange( + rangeStart: number, + rangeEnd: number, + cursorAbsoluteY: number, + continuationReason: RefreshReason + ) { + if (this.dirtyAllInRenderRange) { + this.processLineRange(rangeStart, rangeEnd, cursorAbsoluteY); + this.dirtyAllInRenderRange = false; + this.clearDirtySegments(); + return; + } + + if (this.dirtySegments.length === 0) { + return; + } + + const dirtyInRange: DirtyLineSegment[] = []; + for (const segment of this.dirtySegments) { + if (segment.end < rangeStart) continue; + if (segment.start > rangeEnd) break; + dirtyInRange.push({ + start: Math.max(segment.start, rangeStart), + end: Math.min(segment.end, rangeEnd), + }); + } + + if (dirtyInRange.length === 0) { + return; + } + + const { writeRefreshBudgetMs, dirtySegmentChunkSize } = this.getAdaptiveHighlightingProfile(); + const segmentChunkSize = Math.max(1, dirtySegmentChunkSize); + const startTime = performance.now(); + + for (const segment of dirtyInRange) { + let chunkStart = segment.start; + while (chunkStart <= segment.end) { + const chunkEnd = Math.min(segment.end, chunkStart + segmentChunkSize - 1); + this.processLineRange(chunkStart, chunkEnd, cursorAbsoluteY); + this.removeDirtyRange(chunkStart, chunkEnd); + chunkStart = chunkEnd + 1; + + if (chunkStart <= segment.end && performance.now() - startTime >= writeRefreshBudgetMs) { + this.triggerRefresh("continuation", continuationReason); + return; + } + } + if (performance.now() - startTime >= writeRefreshBudgetMs) { + this.triggerRefresh("continuation", continuationReason); + return; + } + } + } + + private mergeRefreshReason(current: RefreshReason, next: RefreshReason): RefreshReason { + // Scroll refresh must outrank write refresh. During rapid wheel scroll with + // concurrent output, choosing "write" can skip viewport line scans and leave + // visible gaps until another scroll/render cycle lands. + const weight: Record = { write: 0, scroll: 1, full: 2 }; + return weight[next] > weight[current] ? next : current; + } + + private readBufferSnapshot(): BufferSnapshot | null { + const buffer = this.term?.buffer?.active; + if (!buffer) return null; + return { + length: buffer.length, + baseY: buffer.baseY, + viewportY: buffer.viewportY, + cursorAbsoluteY: buffer.baseY + buffer.cursorY, + viewportProbe: this.buildViewportProbe(buffer, this.term.rows), + }; + } + + private buildViewportProbe(buffer: IBuffer, rows: number): readonly ViewportProbeSample[] { + if (rows <= 0) return []; + const viewportStart = buffer.viewportY; + const viewportEnd = viewportStart + rows - 1; + const offsets = [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1]; + const lineSet = new Set(); + for (const offset of offsets) { + const targetLine = viewportStart + Math.round((rows - 1) * offset); + lineSet.add(Math.max(viewportStart, Math.min(viewportEnd, targetLine))); + } + + const probe: ViewportProbeSample[] = []; + for (const lineY of lineSet) { + const lineText = buffer.getLine(lineY)?.translateToString(true) ?? ""; + probe.push({ lineY, hash: this.hashProbeText(lineText) }); + } + probe.sort((left, right) => left.lineY - right.lineY); + return probe; + } + + private hashProbeText(text: string): number { + const sampleLimit = 512; + let hash = 2166136261; + const maxLen = Math.min(text.length, sampleLimit); + for (let index = 0; index < maxLen; index += 1) { + hash ^= text.charCodeAt(index); + hash = Math.imul(hash, 16777619); + } + hash ^= text.length; + return hash >>> 0; + } + + private collectViewportProbeDiffLines( + currentProbe: readonly ViewportProbeSample[], + previousProbe: readonly ViewportProbeSample[], + ): number[] { + const previousByLine = new Map(previousProbe.map((sample) => [sample.lineY, sample.hash])); + const changedLines: number[] = []; + for (const sample of currentProbe) { + if (previousByLine.get(sample.lineY) !== sample.hash) { + changedLines.push(sample.lineY); + } + } + return changedLines; + } + + private markVisibleRangeDirty() { + this.dirtyAllInRenderRange = true; + this.clearDirtySegments(); + } + + private clearDirtySegments() { + this.dirtySegments = []; + this.dirtyLineCount = 0; + } + + private rebuildDirtyLineCount() { + let total = 0; + for (const segment of this.dirtySegments) { + total += segment.end - segment.start + 1; + } + this.dirtyLineCount = total; + } + + private removeDirtyRange(start: number, end: number) { + if (end < start || this.dirtySegments.length === 0) return; + const next: DirtyLineSegment[] = []; + + for (const segment of this.dirtySegments) { + if (segment.end < start || segment.start > end) { + next.push(segment); + continue; + } + if (segment.start < start) { + next.push({ start: segment.start, end: start - 1 }); + } + if (segment.end > end) { + next.push({ start: end + 1, end: segment.end }); + } + } + + this.dirtySegments = next; + this.rebuildDirtyLineCount(); + } + + private addDirtyRange(start: number, end: number) { + if (this.dirtyAllInRenderRange) return; + if (end < start) return; + const maxDirtyLines = this.getMaxDirtyLines(); + const clampedStart = Math.max(0, start); + const clampedEnd = Math.max(clampedStart, end); + const rangeSize = clampedEnd - clampedStart + 1; + if (rangeSize > maxDirtyLines) { + this.markVisibleRangeDirty(); + return; + } + const merged: DirtyLineSegment[] = []; + let mergeStart = clampedStart; + let mergeEnd = clampedEnd; + let inserted = false; + + for (const segment of this.dirtySegments) { + if (segment.end + 1 < mergeStart) { + merged.push(segment); + continue; + } + if (mergeEnd + 1 < segment.start) { + if (!inserted) { + merged.push({ start: mergeStart, end: mergeEnd }); + inserted = true; + } + merged.push(segment); + continue; + } + mergeStart = Math.min(mergeStart, segment.start); + mergeEnd = Math.max(mergeEnd, segment.end); + } + + if (!inserted) { + merged.push({ start: mergeStart, end: mergeEnd }); + } + + this.dirtySegments = merged; + this.rebuildDirtyLineCount(); + if (this.dirtyLineCount > maxDirtyLines) { + this.markVisibleRangeDirty(); + } + } + + private getMaxDirtyLines(): number { + const rows = Math.max(1, this.term.rows); + const perViewportRow = XTERM_PERFORMANCE_CONFIG.highlighting.dirtyLinesPerViewportRow; + const minDirtyLines = XTERM_PERFORMANCE_CONFIG.highlighting.minDirtyLines; + const maxDirtyLines = XTERM_PERFORMANCE_CONFIG.highlighting.maxDirtyLines; + const dynamicDirtyLines = Math.round(rows * perViewportRow); + return Math.min(maxDirtyLines, Math.max(minDirtyLines, dynamicDirtyLines)); + } + + private markDirtyFromWrite() { + this.updateWriteBurst(); + const snapshot = this.readBufferSnapshot(); + if (!snapshot) { + this.markVisibleRangeDirty(); + return; + } + + if (!this.enabled || this.compiledRules.length === 0) { + this.lastBufferSnapshot = snapshot; + return; + } + + const prev = this.lastBufferSnapshot; + this.lastBufferSnapshot = snapshot; + + if (!prev) { + this.markVisibleRangeDirty(); + return; + } + + if (snapshot.length < prev.length || snapshot.baseY < prev.baseY) { + this.markVisibleRangeDirty(); + return; + } + + const rows = this.term.rows; + const padding = KeywordHighlighter.DIRTY_SCAN_PADDING; + const cursorSpan = Math.abs(snapshot.cursorAbsoluteY - prev.cursorAbsoluteY); + const baseSpan = Math.abs(snapshot.baseY - prev.baseY); + const largeDeltaThreshold = rows * 4; + + if (cursorSpan > largeDeltaThreshold || baseSpan > largeDeltaThreshold) { + this.markVisibleRangeDirty(); + return; + } + + const sameWindow = + snapshot.length === prev.length && + snapshot.baseY === prev.baseY && + snapshot.viewportY === prev.viewportY; + const changedProbeLines = this.collectViewportProbeDiffLines( + snapshot.viewportProbe, + prev.viewportProbe, + ); + const probeDiffCount = changedProbeLines.length; + const cursorStart = Math.min(prev.cursorAbsoluteY, snapshot.cursorAbsoluteY) - padding; + const cursorEnd = Math.max(prev.cursorAbsoluteY, snapshot.cursorAbsoluteY) + padding; + // Detect in-place ANSI redraw chunks (cursor returns near original line while + // multiple viewport regions are actually rewritten). + if (sameWindow && cursorSpan <= Math.max(1, padding * 2) && probeDiffCount >= 2) { + this.markVisibleRangeDirty(); + return; + } + // Single-line ANSI redraw via save/restore: also mark the rewritten probe + // line dirty when it is away from the cursor. + if (sameWindow && cursorSpan <= Math.max(1, padding * 2) && probeDiffCount === 1) { + const changedLine = changedProbeLines[0]; + if (changedLine < cursorStart || changedLine > cursorEnd) { + this.addDirtyRange(changedLine - padding, changedLine + padding); + } + } + + this.addDirtyRange(cursorStart, cursorEnd); + + if (snapshot.viewportY !== prev.viewportY) { + const prevViewportEnd = prev.viewportY + rows - 1; + const currViewportEnd = snapshot.viewportY + rows - 1; + if (snapshot.viewportY > prev.viewportY) { + this.addDirtyRange(prevViewportEnd + 1 - padding, currViewportEnd + padding); + } else { + this.addDirtyRange(snapshot.viewportY - padding, prev.viewportY - 1 + padding); + } + } + } + + private decayWriteBurst(now: number) { + if (this.lastBurstDecayAt === 0) { + this.lastBurstDecayAt = now; + return; + } + const elapsed = now - this.lastBurstDecayAt; + if (elapsed < KeywordHighlighter.WRITE_BURST_DECAY_MS) return; + const steps = Math.floor(elapsed / KeywordHighlighter.WRITE_BURST_DECAY_MS); + if (steps <= 0) return; + this.recentWriteBurst = Math.max(0, this.recentWriteBurst - steps); + this.lastBurstDecayAt += steps * KeywordHighlighter.WRITE_BURST_DECAY_MS; + } + + private updateWriteBurst() { + const now = performance.now(); + this.decayWriteBurst(now); + if (this.lastWriteAt === 0) { + this.recentWriteBurst = 1; + this.lastWriteAt = now; + this.lastBurstDecayAt = now; + return; + } + + const interval = now - this.lastWriteAt; + if (interval <= KeywordHighlighter.WRITE_BURST_INTERVAL_MS) { + this.recentWriteBurst = Math.min(64, this.recentWriteBurst + 1); + } else { + this.recentWriteBurst = Math.max(1, this.recentWriteBurst - 1); + } + this.lastWriteAt = now; + this.lastBurstDecayAt = now; + } + + private isWriteBurstActive(now: number): boolean { + this.decayWriteBurst(now); + if (this.recentWriteBurst < KeywordHighlighter.WRITE_BURST_THRESHOLD) { + return false; + } + return now - this.lastWriteAt <= KeywordHighlighter.WRITE_BURST_DECAY_MS * 2; + } + + private getAdaptiveHighlightingProfile(now = performance.now()) { + const config = XTERM_PERFORMANCE_CONFIG.highlighting; + const overscanLines = this.getBaseOverscanLines(); + if (!this.isWriteBurstActive(now)) { + return { + overscanLines, + writeRefreshBudgetMs: config.writeRefreshBudgetMs, + dirtySegmentChunkSize: config.dirtySegmentChunkSize, + debounceMs: config.debounceMs, + immediateMinIntervalMs: config.immediateMinIntervalMs, + }; + } + + return { + overscanLines: Math.max(8, Math.round(overscanLines * KeywordHighlighter.WRITE_BURST_OVERSCAN_SCALE)), + writeRefreshBudgetMs: Math.max(1, config.writeRefreshBudgetMs * KeywordHighlighter.WRITE_BURST_BUDGET_SCALE), + dirtySegmentChunkSize: Math.max(8, Math.round(config.dirtySegmentChunkSize * KeywordHighlighter.WRITE_BURST_CHUNK_SCALE)), + debounceMs: Math.max(config.debounceMs, KeywordHighlighter.WRITE_BURST_DEBOUNCE_MS), + immediateMinIntervalMs: Math.max( + config.immediateMinIntervalMs, + KeywordHighlighter.WRITE_BURST_IMMEDIATE_MIN_INTERVAL_MS + ), + }; + } + + private shouldDeferRefreshForWriteBurst( + mode: "immediate" | "debounced" | "continuation", + reason: RefreshReason, + now: number + ): boolean { + if (mode !== "immediate") return false; + if (!this.isWriteBurstActive(now)) return false; + return reason === "write"; + } + + private getOverscanLines(reason: RefreshReason): number { + if (reason === "write") { + return this.getAdaptiveHighlightingProfile().overscanLines; + } + return this.getBaseOverscanLines(); + } + + private getBaseOverscanLines(): number { + const ratio = XTERM_PERFORMANCE_CONFIG.highlighting.overscanViewportRatio; + return Math.max(1, Math.round(this.term.rows * ratio)); + } + + private getWriteBurstDeferDelay(now: number): number { + const quietWindow = Math.max( + KeywordHighlighter.WRITE_BURST_HIGHLIGHT_PAUSE_MS, + this.getAdaptiveHighlightingProfile(now).debounceMs + ); + if (this.lastWriteAt <= 0) { + return quietWindow; + } + const elapsedSinceWrite = now - this.lastWriteAt; + return Math.max(16, quietWindow - elapsedSinceWrite); + } + + private processLineRange(start: number, end: number, cursorAbsoluteY: number) { + if (end < start) return; + const buffer = this.term.buffer.active; + const wrappedBlockCache = new Map(); + for (let lineY = start; lineY <= end; lineY++) { + const line = buffer.getLine(lineY); + if (!line) { + this.disposeLineDecorations(lineY); + continue; + } + + const lineText = line.translateToString(true); // true = trim right whitespace + if (!lineText) { + this.disposeLineDecorations(lineY); + continue; + } + + const hasWrappedContext = this.hasWrappedNeighbor(buffer, lineY, line); + const cachedRanges = hasWrappedContext + ? this.scanWrappedLine(buffer, lineY, line, lineText, wrappedBlockCache) + : this.getCachedRanges(line, lineText); + if (cachedRanges.length === 0) { + this.disposeLineDecorations(lineY); + continue; + } + + const signature = this.buildRangesSignature(cachedRanges); + const existing = this.lineDecorations.get(lineY); + if ( + existing && + !existing.marker.isDisposed && + existing.decorations.length > 0 && + existing.decorations.every((decoration) => !decoration.isDisposed) && + existing.marker.line === lineY && + existing.signature === signature + ) { + continue; + } + + this.disposeLineDecorations(lineY, existing); + this.applyLineDecorations(lineY, cachedRanges, signature, cursorAbsoluteY); + } + } + + private clearLineDecorationsInRange(start: number, end: number) { + if (end < start || this.lineDecorations.size === 0) return; + const entries = Array.from(this.lineDecorations.entries()); + for (const [lineY, state] of entries) { + if (lineY < start || lineY > end) continue; + this.disposeLineDecorations(lineY, state); } } @@ -316,6 +1076,136 @@ export class KeywordHighlighter implements IDisposable { return ranges; } + private hasWrappedNeighbor(buffer: IBuffer, lineY: number, line: IBufferLine): boolean { + if (line.isWrapped) return true; + const nextLine = buffer.getLine(lineY + 1); + return !!nextLine?.isWrapped; + } + + private findWrappedBlockStart(buffer: IBuffer, lineY: number): number { + let startY = lineY; + while (startY > 0) { + const current = buffer.getLine(startY); + if (!current?.isWrapped) break; + startY -= 1; + } + return startY; + } + + private buildWrappedBlockContext(buffer: IBuffer, startY: number): WrappedBlockContext | null { + let logicalLineText = ""; + const segmentBounds = new Map(); + let cursorY = startY; + + while (true) { + const segment = buffer.getLine(cursorY); + if (!segment) break; + const segmentText = segment.translateToString(true); + const lineStart = logicalLineText.length; + const lineEnd = lineStart + segmentText.length; + segmentBounds.set(cursorY, { lineStart, lineEnd }); + logicalLineText += segmentText; + + const nextLine = buffer.getLine(cursorY + 1); + if (!nextLine?.isWrapped) break; + cursorY += 1; + } + + if (segmentBounds.size === 0) return null; + return { logicalLineText, segmentBounds }; + } + + private getWrappedContext( + buffer: IBuffer, + lineY: number, + cache: Map, + ): { logicalLineText: string; lineStart: number; lineEnd: number } | null { + const startY = this.findWrappedBlockStart(buffer, lineY); + let block = cache.get(startY); + if (!block) { + block = this.buildWrappedBlockContext(buffer, startY) ?? undefined; + if (block) { + cache.set(startY, block); + } + } + if (!block) return null; + const bounds = block.segmentBounds.get(lineY); + if (!bounds) return null; + return { + logicalLineText: block.logicalLineText, + lineStart: bounds.lineStart, + lineEnd: bounds.lineEnd, + }; + } + + private scanWrappedLine( + buffer: IBuffer, + lineY: number, + line: IBufferLine, + lineText: string, + wrappedBlockCache: Map, + ): CachedDecorationRange[] { + const context = this.getWrappedContext(buffer, lineY, wrappedBlockCache); + if (!context || context.logicalLineText === lineText) { + return this.scanLine(line, lineText); + } + + const asciiOnly = RE_ASCII_ONLY.test(lineText); + let cellMap: number[] | null = null; + let ranges: CachedDecorationRange[] | null = null; + + for (const { regex, color, priority } of this.compiledRules) { + forEachNonEmptyRegexMatch(regex, context.logicalLineText, (match) => { + const matchStart = match.index; + const matchEnd = matchStart + match[0].length; + if (matchEnd <= context.lineStart || matchStart >= context.lineEnd) { + return; + } + + const localStart = Math.max(matchStart, context.lineStart) - context.lineStart; + const localEnd = Math.min(matchEnd, context.lineEnd) - context.lineStart; + if (localEnd <= localStart) return; + + let cellStartCol: number; + let cellEndCol: number; + + if (asciiOnly) { + cellStartCol = localStart; + cellEndCol = localEnd; + } else { + if (cellMap === null) { + cellMap = this.buildStringToCellMap(line); + } + cellStartCol = cellMap[localStart] ?? localStart; + cellEndCol = localEnd < cellMap.length + ? (cellMap[localEnd] ?? localEnd) + : (cellMap[cellMap.length - 1] ?? localEnd); + } + + const cellWidth = cellEndCol - cellStartCol; + if (cellWidth <= 0) return; + + if (ranges === null) { + ranges = []; + } + ranges.push({ + x: cellStartCol, + width: cellWidth, + color, + priority, + }); + }); + } + + if (!ranges || ranges.length === 0) { + return EMPTY_RANGES as CachedDecorationRange[]; + } + if (ranges.length === 1) { + return ranges; + } + return this.mergeDecorationRanges(ranges); + } + private scanLine(line: IBufferLine, lineText: string): CachedDecorationRange[] { // ASCII-only lines have a 1:1 string-index-to-cell-column mapping, // so we can skip the expensive buildStringToCellMap call entirely. @@ -324,12 +1214,8 @@ export class KeywordHighlighter implements IDisposable { let ranges: CachedDecorationRange[] | null = null; // Process each pre-compiled rule - for (const { regex, color } of this.compiledRules) { - // Reset regex state for reuse (global flag maintains lastIndex) - regex.lastIndex = 0; - let match; - - while ((match = regex.exec(lineText)) !== null) { + for (const { regex, color, priority } of this.compiledRules) { + forEachNonEmptyRegexMatch(regex, lineText, (match) => { const strStart = match.index; const strEnd = strStart + match[0].length; @@ -345,13 +1231,15 @@ export class KeywordHighlighter implements IDisposable { cellMap = this.buildStringToCellMap(line); } cellStartCol = cellMap[strStart] ?? strStart; - cellEndCol = cellMap[strEnd] ?? strEnd; + cellEndCol = strEnd < cellMap.length + ? (cellMap[strEnd] ?? strEnd) + : (cellMap[cellMap.length - 1] ?? strEnd); } const cellWidth = cellEndCol - cellStartCol; // Skip if width is 0 or negative (shouldn't happen, but be safe) - if (cellWidth <= 0) continue; + if (cellWidth <= 0) return; if (ranges === null) { ranges = []; @@ -360,10 +1248,42 @@ export class KeywordHighlighter implements IDisposable { x: cellStartCol, width: cellWidth, color, + priority, }); + }); + } + + if (!ranges || ranges.length === 0) { + return EMPTY_RANGES as CachedDecorationRange[]; + } + if (ranges.length === 1) { + return ranges; + } + return this.mergeDecorationRanges(ranges); + } + + private mergeDecorationRanges(ranges: CachedDecorationRange[]): CachedDecorationRange[] { + // Preserve rule priority (lower index first), and only merge ranges + // within the same priority/color layer. + ranges.sort((a, b) => a.priority - b.priority || a.x - b.x); + const merged: CachedDecorationRange[] = [ranges[0]]; + + for (let index = 1; index < ranges.length; index += 1) { + const current = ranges[index]; + const previous = merged[merged.length - 1]; + if ( + current.priority === previous.priority && + current.color === previous.color && + current.x >= previous.x && + current.x <= previous.x + previous.width + ) { + const mergedEnd = Math.max(previous.x + previous.width, current.x + current.width); + previous.width = mergedEnd - previous.x; + } else { + merged.push(current); } } - return ranges ?? (EMPTY_RANGES as CachedDecorationRange[]); + return merged; } } diff --git a/components/terminal/keywordHighlightRegex.test.ts b/components/terminal/keywordHighlightRegex.test.ts new file mode 100644 index 000000000..8925c0348 --- /dev/null +++ b/components/terminal/keywordHighlightRegex.test.ts @@ -0,0 +1,38 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { forEachNonEmptyRegexMatch } from "./keywordHighlightRegex.ts"; + +test("forEachNonEmptyRegexMatch returns normal consuming matches", () => { + const regex = /\bfoo\b/gi; + const indices: number[] = []; + + forEachNonEmptyRegexMatch(regex, "foo bar foo", (match) => { + indices.push(match.index); + }); + + assert.deepEqual(indices, [0, 8]); +}); + +test("forEachNonEmptyRegexMatch skips zero-width matches without looping forever", () => { + const regex = /(?=foo)/g; + const indices: number[] = []; + + forEachNonEmptyRegexMatch(regex, "foo foo", (match) => { + indices.push(match.index); + }); + + assert.deepEqual(indices, []); +}); + +test("forEachNonEmptyRegexMatch resets reused regex state before scanning", () => { + const regex = /\d+/g; + const indices: number[] = []; + + regex.lastIndex = 99; + forEachNonEmptyRegexMatch(regex, "1 22 333", (match) => { + indices.push(match.index); + }); + + assert.deepEqual(indices, [0, 2, 5]); +}); diff --git a/components/terminal/keywordHighlightRegex.ts b/components/terminal/keywordHighlightRegex.ts new file mode 100644 index 000000000..e01eeffbc --- /dev/null +++ b/components/terminal/keywordHighlightRegex.ts @@ -0,0 +1,24 @@ +export function forEachNonEmptyRegexMatch( + regex: RegExp, + text: string, + onMatch: (match: RegExpExecArray) => void, +) { + regex.lastIndex = 0; + + let match: RegExpExecArray | null; + while ((match = regex.exec(text)) !== null) { + if (match[0].length === 0) { + if (regex.lastIndex <= match.index) { + // Advance past the full code point to avoid landing inside a surrogate pair + const code = text.charCodeAt(match.index); + regex.lastIndex = match.index + (code >= 0xD800 && code <= 0xDBFF ? 2 : 1); + } + if (regex.lastIndex > text.length) { + break; + } + continue; + } + + onMatch(match); + } +} diff --git a/infrastructure/config/xtermPerformance.ts b/infrastructure/config/xtermPerformance.ts index c6b652a77..9a6efe509 100644 --- a/infrastructure/config/xtermPerformance.ts +++ b/infrastructure/config/xtermPerformance.ts @@ -104,12 +104,26 @@ export const XTERM_PERFORMANCE_CONFIG = { highlighting: { // Debounce time for viewport scanning (ms) // Higher values = better scrolling performance, but slower highlight "catch up" - debounceMs: 200, + debounceMs: 100, // Minimum interval between immediate (rAF) refreshes in ms. // Prevents heavy output (e.g. tail -f) from refreshing every frame. - immediateMinIntervalMs: 50, + immediateMinIntervalMs: 16, // Number of unique line scan results to keep cached. cacheEntries: 1200, + // Keep decorations for lines just outside the viewport so small scrolls + // don't constantly dispose/recreate them. Scales with current terminal rows. + overscanViewportRatio: 2.0, + // Dirty scan padding around cursor/viewport deltas for write bursts. + dirtyScanPadding: 2, + // Dynamic dirty-line cap scales with viewport rows. + dirtyLinesPerViewportRow: 6, + // Clamp the dynamic dirty-line cap to avoid extremes. + minDirtyLines: 200, + maxDirtyLines: 1200, + // Max processing time per refresh pass when handling dirty lines (ms). + writeRefreshBudgetMs: 4, + // Process dirty contiguous lines in chunks so budget checks can preempt. + dirtySegmentChunkSize: 48, }, }; diff --git a/lib/regexSafety.ts b/lib/regexSafety.ts new file mode 100644 index 000000000..9284ee575 --- /dev/null +++ b/lib/regexSafety.ts @@ -0,0 +1,53 @@ +/** + * Best-effort regex safety guard for user-provided patterns. + * + * Reject nested quantifier shapes such as `(a+)+`, `(a*)*`, `(a+){2,}` + * that are common catastrophic-backtracking sources. + */ +export type RegexSafetyReason = "nested_quantifier"; + +export type RegexValidationIssue = "syntax_invalid" | "safety_rejected"; + +export type RegexSafetyCheckResult = + | { safe: true } + | { safe: false; reason: RegexSafetyReason }; + +export type RegexValidationResult = + | { valid: true } + | { valid: false; issue: RegexValidationIssue; reason?: RegexSafetyReason; errorMessage?: string }; + +export function checkRegexSafetyPattern(pattern: string): RegexSafetyCheckResult { + const nestedUnboundedQuantifier = /\((?:\?:)?[^)]*(?:\+|\*|\{\d+,\}|\{,\d+\})[^)]*\)(?:\+|\*|\{\d+,\}|\{,\d+\})/; + if (nestedUnboundedQuantifier.test(pattern)) { + return { safe: false, reason: "nested_quantifier" }; + } + return { safe: true }; +} + +export function validateUserRegexPattern(pattern: string, flags = "gi"): RegexValidationResult { + try { + // Syntax validation only. + new RegExp(pattern, flags); + } catch (err) { + return { + valid: false, + issue: "syntax_invalid", + errorMessage: err instanceof Error ? err.message : String(err), + }; + } + + const safety = checkRegexSafetyPattern(pattern); + if (safety.safe === false) { + return { + valid: false, + issue: "safety_rejected", + reason: safety.reason, + }; + } + + return { valid: true }; +} + +export function isSafeRegexPattern(pattern: string): boolean { + return checkRegexSafetyPattern(pattern).safe; +} From 6fad3f0b761ecf361fb27923945e748aa024bd5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 14:31:23 +0800 Subject: [PATCH 010/228] fix(sftp): reconnect terminal side panel after SSH session loss (#1608) (#1621) * fix(sftp): reconnect terminal side panel after SSH session loss When SSH disconnects while the terminal SFTP side panel is browsing a stale path, auto-connect reused a dead tab and left the pane stuck on loading. Rebind SFTP when the terminal session changes and skip reuse unless the backend session is healthy; also stop follow-terminal-cwd retry loops to missing directories. Fixes #1608 Co-authored-by: Cursor * fix(sftp): address review findings for side panel reconnect Harden auto-connect after bugbot review: skip tab reuse on SSH session change, move follow-cwd backoff ref into the interactive body, and make navigateTo return reached/failed/aborted so follow mode only backs off on real path failures. Co-authored-by: Cursor --------- Co-authored-by: Cursor --- application/state/sftp/useSftpPaneActions.ts | 22 +++-- components/SftpSidePanel.tsx | 64 ++++++++++-- .../sftp/sftpSidePanelAutoConnect.test.ts | 98 +++++++++++++++++++ components/sftp/sftpSidePanelAutoConnect.ts | 57 +++++++++++ 4 files changed, 226 insertions(+), 15 deletions(-) create mode 100644 components/sftp/sftpSidePanelAutoConnect.test.ts create mode 100644 components/sftp/sftpSidePanelAutoConnect.ts diff --git a/application/state/sftp/useSftpPaneActions.ts b/application/state/sftp/useSftpPaneActions.ts index 7be5a0e63..6e0d21470 100644 --- a/application/state/sftp/useSftpPaneActions.ts +++ b/application/state/sftp/useSftpPaneActions.ts @@ -43,8 +43,10 @@ interface UseSftpPaneActionsParams { dirCacheTtlMs: number; } +export type SftpNavigateResult = "reached" | "failed" | "aborted"; + interface UseSftpPaneActionsResult { - navigateTo: (side: "left" | "right", path: string, options?: { force?: boolean; tabId?: string }) => Promise; + navigateTo: (side: "left" | "right", path: string, options?: { force?: boolean; tabId?: string }) => Promise; refresh: (side: "left" | "right", options?: { tabId?: string }) => Promise; navigateUp: (side: "left" | "right") => Promise; openEntry: (side: "left" | "right", entry: SftpFileEntry) => Promise; @@ -160,7 +162,7 @@ export const useSftpPaneActions = ({ side: "left" | "right", path: string, options?: { force?: boolean; tabId?: string }, - ) => { + ): Promise => { const sideTabs = side === "left" ? leftTabsRef.current : rightTabsRef.current; // When tabId is specified, target that specific tab instead of the active one. // This allows refreshing a background tab (e.g. after a transfer completes @@ -171,7 +173,7 @@ export const useSftpPaneActions = ({ : getActivePane(side); if (!pane?.connection || !targetTabId) { - return; + return "aborted"; } const connectionId = pane.connection.id; @@ -220,7 +222,7 @@ export const useSftpPaneActions = ({ filenameEncoding: pane.filenameEncoding, }); } - return; + return "reached"; } // Re-seed confirmed state whenever the pane is settled (not loading), or @@ -277,7 +279,7 @@ export const useSftpPaneActions = ({ } else { handleSessionError(side, new Error("SFTP session lost")); } - return; + return "aborted"; } try { @@ -295,7 +297,7 @@ export const useSftpPaneActions = ({ } else { handleSessionError(side, err as Error); } - return; + return "aborted"; } throw err as Error; } @@ -306,7 +308,7 @@ export const useSftpPaneActions = ({ // a connect/disconnect. Check if THIS tab's request is still current. if (tabNavSeqRef.current.get(targetTabId) !== requestId) { // This tab also has a newer navigation — drop completely. - return; + return "aborted"; } // Side was superseded by another tab, but this tab's request is // still current. The fetched files are valid — fall through to @@ -344,18 +346,21 @@ export const useSftpPaneActions = ({ filenameEncoding: pane.filenameEncoding, }); } + return "reached"; } catch (err) { if (navSeqRef.current[side] !== requestId) { if (tabNavSeqRef.current.get(targetTabId) !== requestId) { - return; + return "aborted"; } // Side superseded by another tab, but this tab's request is // current — fall through to show the error on this tab. } + let navigationFailed = false; updateTab(side, targetTabId, (prev) => { if (prev.connection?.id !== connectionId) { return prev; } + navigationFailed = true; return { ...prev, connection: { ...prev.connection, currentPath: previousPath }, @@ -367,6 +372,7 @@ export const useSftpPaneActions = ({ loading: false, }; }); + return navigationFailed ? "failed" : "aborted"; } }, [ diff --git a/components/SftpSidePanel.tsx b/components/SftpSidePanel.tsx index 276af3fdc..5d3841763 100644 --- a/components/SftpSidePanel.tsx +++ b/components/SftpSidePanel.tsx @@ -45,6 +45,11 @@ import { resolveHostFollowTerminalCwd, shouldFollowTerminalCwdNavigate, } from "./sftp/sftpFollowTerminalCwd"; +import { + findReusableSftpSidePanelTab, + shouldResetSftpSidePanelSourceSession, + shouldSkipSftpSidePanelAutoConnect, +} from "./sftp/sftpSidePanelAutoConnect"; interface SftpSidePanelProps { hosts: Host[]; @@ -211,6 +216,7 @@ const SftpSidePanelInner: React.FC = ({ const connectedKeyRef = useRef(null); const connectedHostObjRef = useRef(null); + const lastSourceSessionIdRef = useRef(null); const lastAppliedInitialLocationKeyRef = useRef(null); const handledPendingUploadIdRef = useRef(null); const tabConnectionKeyMapRef = useRef>(new Map()); @@ -264,7 +270,31 @@ const SftpSidePanelInner: React.FC = ({ activeHost.sftpSudo, activeHost.username, ); - if (connectedKeyRef.current === connectionKey) return; + const sessionChanged = shouldResetSftpSidePanelSourceSession( + lastSourceSessionIdRef.current, + activeSessionId, + ); + if (sessionChanged) { + connectedKeyRef.current = null; + } + if (activeSessionId) { + lastSourceSessionIdRef.current = activeSessionId; + } + + const hasBackendSession = (connectionId: string) => !!s.getSftpIdForConnection(connectionId); + const activeTab = s.leftTabs.tabs.find((tab) => tab.id === s.leftTabs.activeTabId) ?? null; + const activeConnectionId = activeTab?.connection?.id; + if ( + !sessionChanged + && shouldSkipSftpSidePanelAutoConnect( + connectionKey, + connectedKeyRef.current, + activeTab, + activeConnectionId ? hasBackendSession(activeConnectionId) : false, + ) + ) { + return; + } if (hasActiveWork) return; logger.info("[SftpSidePanel] Auto-connect triggered", { @@ -275,11 +305,15 @@ const SftpSidePanelInner: React.FC = ({ }); const tabs = s.leftTabs.tabs; - const existingTab = tabs.find((tab) => { - if (!tab.connection || tab.connection.hostId !== activeHost.id) return false; - if (tab.connection.status === "error" || tab.connection.status === "disconnected") return false; - return tabConnectionKeyMapRef.current.get(tab.id) === connectionKey; - }); + const existingTab = sessionChanged + ? null + : findReusableSftpSidePanelTab( + tabs, + activeHost.id, + connectionKey, + tabConnectionKeyMapRef.current, + hasBackendSession, + ); if (existingTab) { s.selectTab("left", existingTab.id); connectedKeyRef.current = connectionKey; @@ -694,6 +728,12 @@ const SftpSidePanelInteractiveBody: React.FC const hasActiveWork = showTextEditor || !!permissionsState || showFileOpenerDialog || (sftp.activeFileWatchCountRef?.current ?? 0) > 0; + const lastFailedFollowCwdRef = useRef(null); + + useEffect(() => { + lastFailedFollowCwdRef.current = null; + }, [sftp.leftPane.connection?.id]); + const handleGoToTerminalCwd = useCallback(async () => { if (!onGetTerminalCwd) return; const cwd = await onGetTerminalCwd({ preferFreshBackend: true }); @@ -712,6 +752,7 @@ const SftpSidePanelInteractiveBody: React.FC terminalCwd = await onGetTerminalCwd({ preferFreshBackend: true }); } if (!terminalCwd) return; + if (lastFailedFollowCwdRef.current === terminalCwd) return; const connection = sftpRef.current.leftPane.connection; if (!shouldFollowTerminalCwdNavigate({ @@ -725,7 +766,12 @@ const SftpSidePanelInteractiveBody: React.FC return; } - await sftpRef.current.navigateTo("left", terminalCwd); + const navigateResult = await sftpRef.current.navigateTo("left", terminalCwd); + if (navigateResult === "failed") { + lastFailedFollowCwdRef.current = terminalCwd; + } else if (navigateResult === "reached") { + lastFailedFollowCwdRef.current = null; + } }, [ activeTerminalCwd, canFollowTerminalCwd, @@ -740,6 +786,10 @@ const SftpSidePanelInteractiveBody: React.FC onSftpFollowTerminalCwdChange?.(!effectiveFollowTerminalCwd, followTerminalCwdHost); }, [effectiveFollowTerminalCwd, followTerminalCwdHost, onSftpFollowTerminalCwdChange]); + useEffect(() => { + lastFailedFollowCwdRef.current = null; + }, [activeTerminalCwd]); + useEffect(() => { if (!effectiveFollowTerminalCwd || !canFollowTerminalCwd || !isVisible || hasActiveWork) return; void syncFollowToTerminalCwd(); diff --git a/components/sftp/sftpSidePanelAutoConnect.test.ts b/components/sftp/sftpSidePanelAutoConnect.test.ts new file mode 100644 index 000000000..71082fbde --- /dev/null +++ b/components/sftp/sftpSidePanelAutoConnect.test.ts @@ -0,0 +1,98 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import type { SftpPane } from "../../application/state/sftp/types"; +import { + findReusableSftpSidePanelTab, + isRemoteSftpTabHealthy, + shouldResetSftpSidePanelSourceSession, + shouldSkipSftpSidePanelAutoConnect, +} from "./sftpSidePanelAutoConnect"; + +const remoteConnectedTab = (overrides: Partial = {}): SftpPane => ({ + id: "tab-1", + connection: { + id: "conn-1", + hostId: "host-1", + hostLabel: "server", + isLocal: false, + status: "connected", + currentPath: "/var/www", + }, + files: [], + loading: false, + reconnecting: false, + error: null, + connectionLogs: [], + selectedFiles: new Set(), + filter: "", + filenameEncoding: "auto", + showHiddenFiles: false, + transferMutationToken: 0, + ...overrides, +}); + +test("isRemoteSftpTabHealthy rejects loading tabs", () => { + const tab = remoteConnectedTab({ loading: true }); + assert.equal(isRemoteSftpTabHealthy(tab, true), false); +}); + +test("isRemoteSftpTabHealthy rejects tabs without a backend SFTP session", () => { + const tab = remoteConnectedTab(); + assert.equal(isRemoteSftpTabHealthy(tab, false), false); +}); + +test("isRemoteSftpTabHealthy rejects connecting tabs", () => { + const tab = remoteConnectedTab({ + connection: { + ...remoteConnectedTab().connection!, + status: "connecting", + }, + }); + assert.equal(isRemoteSftpTabHealthy(tab, true), false); +}); + +test("shouldSkipSftpSidePanelAutoConnect returns false for stale connected keys", () => { + const tab = remoteConnectedTab({ loading: true }); + assert.equal( + shouldSkipSftpSidePanelAutoConnect("host-key", "host-key", tab, true), + false, + ); +}); + +test("findReusableSftpSidePanelTab ignores tabs stuck in loading after SSH disconnect", () => { + const tab = remoteConnectedTab({ loading: true }); + const map = new Map([[tab.id, "host-key"]]); + assert.equal( + findReusableSftpSidePanelTab([tab], "host-1", "host-key", map, () => true), + null, + ); +}); + +test("findReusableSftpSidePanelTab returns healthy tabs", () => { + const tab = remoteConnectedTab(); + const map = new Map([[tab.id, "host-key"]]); + assert.equal( + findReusableSftpSidePanelTab([tab], "host-1", "host-key", map, () => true), + tab, + ); +}); + +test("shouldResetSftpSidePanelSourceSession detects terminal session changes", () => { + assert.equal(shouldResetSftpSidePanelSourceSession("sess-a", "sess-b"), true); + assert.equal(shouldResetSftpSidePanelSourceSession("sess-a", "sess-a"), false); + assert.equal(shouldResetSftpSidePanelSourceSession(null, "sess-a"), false); + assert.equal(shouldResetSftpSidePanelSourceSession("sess-a", null), false); +}); + +test("shouldSkipSftpSidePanelAutoConnect returns false after terminal session changes", () => { + const tab = remoteConnectedTab(); + assert.equal( + shouldSkipSftpSidePanelAutoConnect("host-key", "host-key", tab, true), + true, + ); + // Caller gates on sessionChanged before invoking skip — stale reuse must not win. + assert.equal( + shouldResetSftpSidePanelSourceSession("sess-a", "sess-b"), + true, + ); +}); diff --git a/components/sftp/sftpSidePanelAutoConnect.ts b/components/sftp/sftpSidePanelAutoConnect.ts new file mode 100644 index 000000000..069a53735 --- /dev/null +++ b/components/sftp/sftpSidePanelAutoConnect.ts @@ -0,0 +1,57 @@ +import type { SftpPane } from "../../application/state/sftp/types"; + +export type SftpSidePanelTabHealth = Pick; + +/** Whether a remote SFTP tab is safe to reuse without reconnecting. */ +export function isRemoteSftpTabHealthy( + tab: SftpSidePanelTabHealth, + hasBackendSession: boolean, +): boolean { + const conn = tab.connection; + if (!conn || conn.isLocal) return true; + if (conn.status !== "connected") return false; + if (tab.loading || tab.reconnecting) return false; + if (!hasBackendSession) return false; + return true; +} + +/** Skip auto-connect only when the active tab is already bound to this endpoint and healthy. */ +export function shouldSkipSftpSidePanelAutoConnect( + connectionKey: string, + connectedKey: string | null, + activeTab: SftpSidePanelTabHealth | null | undefined, + hasBackendSession: boolean, +): boolean { + if (connectedKey !== connectionKey) return false; + if (!activeTab) return false; + return isRemoteSftpTabHealthy(activeTab, hasBackendSession); +} + +export function findReusableSftpSidePanelTab( + tabs: SftpPane[], + hostId: string, + connectionKey: string, + tabConnectionKeyMap: ReadonlyMap, + hasBackendSession: (connectionId: string) => boolean, +): SftpPane | null { + const candidate = tabs.find((tab) => { + if (!tab.connection || tab.connection.hostId !== hostId) return false; + if (tab.connection.status === "error" || tab.connection.status === "disconnected") return false; + return tabConnectionKeyMap.get(tab.id) === connectionKey; + }); + if (!candidate?.connection) return null; + if (!isRemoteSftpTabHealthy(candidate, hasBackendSession(candidate.connection.id))) { + return null; + } + return candidate; +} + +/** True when the linked terminal SSH session changed and SFTP must rebind. */ +export function shouldResetSftpSidePanelSourceSession( + previousSessionId: string | null | undefined, + nextSessionId: string | null | undefined, +): boolean { + if (!nextSessionId) return false; + if (!previousSessionId) return false; + return nextSessionId !== previousSessionId; +} From 3235f118704a687db115f437558ac2988e84fd44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 14:36:11 +0800 Subject: [PATCH 011/228] =?UTF-8?q?[Bug]=20=E9=80=89=E6=8B=A9=20Keychain?= =?UTF-8?q?=20=E5=BC=95=E7=94=A8=E5=AF=86=E9=92=A5=E5=90=8E=E4=B8=8D?= =?UTF-8?q?=E5=86=8D=E5=B0=9D=E8=AF=95=E9=BB=98=E8=AE=A4=20SSH=20key=20(#1?= =?UTF-8?q?620)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fix default SSH key fallback after Keychain reference key selection. Treat identityFilePaths as an explicit user key choice so terminal SSH sessions no longer fall back to ~/.ssh/id_* when a host uses a Keychain file-referenced key. Fixes #1614 Co-authored-by: Cursor * Skip default-key primaries when explicit key config fails to load. Address Codex review: if identityFilePaths were set but loadFirstIdentityFileForAuth returns null, do not install ~/.ssh/id_* as the primary auth method. Co-authored-by: Cursor --------- Co-authored-by: Cursor --- electron/bridges/sshAuthHelper.cjs | 17 +++++++++ .../sshAuthHelper.userConfiguredKey.test.cjs | 38 +++++++++++++++++++ electron/bridges/sshBridge.cjs | 3 +- electron/bridges/sshBridge/startSession.cjs | 12 +++--- 4 files changed, 64 insertions(+), 6 deletions(-) create mode 100644 electron/bridges/sshAuthHelper.userConfiguredKey.test.cjs diff --git a/electron/bridges/sshAuthHelper.cjs b/electron/bridges/sshAuthHelper.cjs index 46becfe93..7d0ac4024 100644 --- a/electron/bridges/sshAuthHelper.cjs +++ b/electron/bridges/sshAuthHelper.cjs @@ -483,6 +483,22 @@ async function getAvailableAgentSocket() { return getSshAgentSocket(); } +/** + * True when the session options carry an explicit user key choice — either + * inline private key material or identity file paths from a Keychain reference + * key (issue #1614). + * @param {Object} options + * @param {string} [options.privateKey] + * @param {string[]} [options.identityFilePaths] + * @returns {boolean} + */ +function hasUserConfiguredKey(options) { + if (typeof options?.privateKey === "string" && options.privateKey.trim().length > 0) { + return true; + } + return Array.isArray(options?.identityFilePaths) && options.identityFilePaths.length > 0; +} + /** * Build authentication handler with default key fallback support * @param {Object} options @@ -1012,6 +1028,7 @@ module.exports = { preparePrivateKeyForAuth, loadIdentityFileForAuth, loadFirstIdentityFileForAuth, + hasUserConfiguredKey, PassphraseCancelledError, isPassphraseCancelledError, }; diff --git a/electron/bridges/sshAuthHelper.userConfiguredKey.test.cjs b/electron/bridges/sshAuthHelper.userConfiguredKey.test.cjs new file mode 100644 index 000000000..e95407792 --- /dev/null +++ b/electron/bridges/sshAuthHelper.userConfiguredKey.test.cjs @@ -0,0 +1,38 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { hasUserConfiguredKey } = require("./sshAuthHelper.cjs"); + +test("hasUserConfiguredKey is true for inline private key material", () => { + assert.equal(hasUserConfiguredKey({ privateKey: "-----BEGIN OPENSSH PRIVATE KEY-----" }), true); +}); + +test("hasUserConfiguredKey is false for empty or whitespace inline keys", () => { + assert.equal(hasUserConfiguredKey({ privateKey: "" }), false); + assert.equal(hasUserConfiguredKey({ privateKey: " " }), false); + assert.equal(hasUserConfiguredKey({}), false); +}); + +test("hasUserConfiguredKey is true for Keychain reference identity file paths", () => { + assert.equal( + hasUserConfiguredKey({ identityFilePaths: ["/Users/alice/.ssh/id_ed25519"] }), + true, + ); +}); + +test("hasUserConfiguredKey is false for empty identity file path lists", () => { + assert.equal(hasUserConfiguredKey({ identityFilePaths: [] }), false); + assert.equal(hasUserConfiguredKey({ identityFilePaths: null }), false); +}); + +test("hasUserConfiguredKey prefers explicit inline key over empty paths", () => { + assert.equal( + hasUserConfiguredKey({ + privateKey: "-----BEGIN OPENSSH PRIVATE KEY-----", + identityFilePaths: [], + }), + true, + ); +}); diff --git a/electron/bridges/sshBridge.cjs b/electron/bridges/sshBridge.cjs index 6e7db809c..30e0aecf4 100644 --- a/electron/bridges/sshBridge.cjs +++ b/electron/bridges/sshBridge.cjs @@ -32,6 +32,7 @@ const { preparePrivateKeyForAuth, loadIdentityFileForAuth, loadFirstIdentityFileForAuth, + hasUserConfiguredKey, PassphraseCancelledError, isPassphraseCancelledError, } = require("./sshAuthHelper.cjs"); @@ -810,7 +811,7 @@ const startSessionApi = createStartSessionApi({ attachSshDebugLogger, logSshAlgorithms, resolveLangFromCharset, safeSend, zmodemOverwritePending, shouldLogSshDebugMessage, log, createSshDiagnosticLogger, buildAlgorithms, randomUUID, findDefaultPrivateKey, findAllDefaultPrivateKeys, - preparePrivateKeyForAuth, loadFirstIdentityFileForAuth, createKeyboardInteractiveHandler, + preparePrivateKeyForAuth, loadFirstIdentityFileForAuth, hasUserConfiguredKey, createKeyboardInteractiveHandler, createConnectionRef, acquireConnectionRef, releaseConnectionRef, findReusableSession, get probeReceiveConflicts() { return probeReceiveConflicts; }, get removeRemoteFiles() { return removeRemoteFiles; }, diff --git a/electron/bridges/sshBridge/startSession.cjs b/electron/bridges/sshBridge/startSession.cjs index c80cc2489..8aede2b73 100644 --- a/electron/bridges/sshBridge/startSession.cjs +++ b/electron/bridges/sshBridge/startSession.cjs @@ -601,7 +601,9 @@ function createStartSessionApi(ctx) { }); } - // If no primary auth method configured, try ssh-agent first, then ALL default keys + // If no primary auth method configured, try ssh-agent first, then ALL default keys. + // Skip default-key primaries when the user explicitly chose a key (inline or + // identityFilePaths) even if loading that key failed (issue #1614). if (!connectOpts.privateKey && !connectOpts.password && !connectOpts.agent) { // First, try to use ssh-agent if available (this is what regular SSH does) const sshAgentSocket = await getAvailableAgentSocket(); @@ -612,12 +614,12 @@ function createStartSessionApi(ctx) { } // Mark that we need to try all default keys (handled in authMethods below) - if (allDefaultKeys.length > 0) { + if (!hasUserConfiguredKey(options) && allDefaultKeys.length > 0) { log("Will try all default SSH keys as fallback", { count: allDefaultKeys.length, keyNames: allDefaultKeys.map(k => k.keyName) }); // Set first key for connectOpts.privateKey (required for ssh2 to allow publickey auth) connectOpts.privateKey = allDefaultKeys[0].privateKey; usedDefaultKeyAsPrimary = true; - } else { + } else if (allDefaultKeys.length === 0) { log("No default SSH key found in ~/.ssh directory"); } } @@ -656,7 +658,7 @@ function createStartSessionApi(ctx) { if (connectOpts.password) order.push("password"); // Add default key fallback if available and no user key configured // Must also set connectOpts.privateKey for ssh2 to actually try publickey auth - if (defaultKeyInfo && !options.privateKey) { + if (defaultKeyInfo && !hasUserConfiguredKey(options)) { connectOpts.privateKey = defaultKeyInfo.privateKey; order.push("publickey"); } @@ -693,7 +695,7 @@ function createStartSessionApi(ctx) { id: `publickey-default-${keyInfo.keyName}` }); } - } else if (defaultKeyInfo && !options.privateKey && !usedDefaultKeyAsPrimary) { + } else if (defaultKeyInfo && !hasUserConfiguredKey(options) && !usedDefaultKeyAsPrimary) { // Single default key fallback (when user has configured other auth methods) authMethods.push({ type: "publickey", key: defaultKeyInfo.privateKey, isDefault: true, id: "publickey-default" }); } From d071827a1efb4c35c3e5ecabf4fba797aeca7114 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 14:48:22 +0800 Subject: [PATCH 012/228] fix host search punctuation-only and hostname compact false positives Reject separator-only queries before substring matching and skip compact matching on hostname fields to avoid IP digit false positives. Co-authored-by: Cursor --- domain/searchMatcher.test.ts | 17 +++++++++++++++++ lib/searchMatcher.ts | 12 ++++++++---- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/domain/searchMatcher.test.ts b/domain/searchMatcher.test.ts index a8f6f5f39..a99e68191 100644 --- a/domain/searchMatcher.test.ts +++ b/domain/searchMatcher.test.ts @@ -116,6 +116,23 @@ test("host search scoring prefers strict punctuation match over loose compact ma assert.equal(strict.score > loose.score, true); }); +test("punctuation-only query does not match every field", () => { + assert.equal(matchesSearchQuery("---", "prod-api-01"), false); + assert.equal(matchesSearchQuery("-", "some-host"), false); +}); + +test("host search avoids compact hostname false positives on numeric segments", () => { + assert.equal( + matchesHostSearchQuery("61", { + label: "核心交换机", + hostname: "10.6.1.88", + group: "网络设备", + tags: [], + }), + false, + ); +}); + test("host search scoring favors label over group when both match", () => { const labelHit = getHostSearchMatch("山东 6-1", { label: "山东-业务交换机6-1", diff --git a/lib/searchMatcher.ts b/lib/searchMatcher.ts index 274874598..4ca3b0072 100644 --- a/lib/searchMatcher.ts +++ b/lib/searchMatcher.ts @@ -84,6 +84,9 @@ export function matchesSearchQuery( return normalizedFields.some((field) => field.includes(normalizedQuery)); } + const tokens = tokenizeSearchQuery(normalizedQuery); + if (tokens.length === 0) return false; + const sourceText = normalizedFields.join(" "); const haystack = sourceText; if (haystack.includes(normalizedQuery)) { @@ -96,9 +99,6 @@ export function matchesSearchQuery( return true; } - const tokens = tokenizeSearchQuery(normalizedQuery); - if (tokens.length === 0) return true; - if (tokens.every((token) => haystack.includes(token))) { return true; } @@ -199,7 +199,11 @@ function matchSegmentAgainstSource( if (SEARCH_QUERY_PUNCT_REGEX.test(segment)) return null; const compactSegment = compactText(segment); - if (compactSegment && source.compact.includes(compactSegment)) { + if ( + compactSegment + && source.field !== "hostname" + && source.compact.includes(compactSegment) + ) { return { segment, field: source.field, From 0ceec3d45cfd64adcb2308dc698f611e193ad9c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 19:27:20 +0800 Subject: [PATCH 013/228] fix(sftp): stop follow-terminal-cwd retry loop on unreachable paths (#1629) * fix(sftp): stop follow-terminal-cwd retry loop on unreachable paths When per-host follow navigates to a terminal cwd that SFTP cannot reach, stop retrying and allow the toolbar toggle to update immediately. Co-authored-by: Cursor * fix(sftp): address Codex review on follow-terminal-cwd blocking Return navigateTo success explicitly and scope blocked follow paths per connection so successful navigations and host switches are not misclassified. Co-authored-by: Cursor * fix(sftp): clear follow block after manual go-to-terminal-cwd Co-authored-by: Cursor * fix(sftp): honor cleared follow-cwd overrides from vault sync Use an explicit pending toggle override instead of stale session host values when the vault clears per-host follow settings back to inherit-global. Co-authored-by: Cursor * fix(sftp): ignore stale follow navigation when follow is disabled mid-flight Bump a follow-sync generation when follow is turned off so pending navigateTo failures cannot restore a blocked cwd after the user disables and re-enables follow. Co-authored-by: Cursor --------- Co-authored-by: Cursor --- components/SftpSidePanel.tsx | 123 +++++++++++++++--- components/sftp/sftpFollowTerminalCwd.test.ts | 100 ++++++++++++++ components/sftp/sftpFollowTerminalCwd.ts | 38 +++++- 3 files changed, 242 insertions(+), 19 deletions(-) diff --git a/components/SftpSidePanel.tsx b/components/SftpSidePanel.tsx index 5d3841763..6c38eeb71 100644 --- a/components/SftpSidePanel.tsx +++ b/components/SftpSidePanel.tsx @@ -43,7 +43,9 @@ import { KeyBinding, HotkeyScheme } from "../domain/models"; import { mergeLatestFollowTerminalCwdHostSetting, resolveHostFollowTerminalCwd, + shouldClearBlockedFollowOnReach, shouldFollowTerminalCwdNavigate, + type SftpFollowTerminalCwdBlock, } from "./sftp/sftpFollowTerminalCwd"; import { findReusableSftpSidePanelTab, @@ -570,6 +572,10 @@ const SftpSidePanelInteractiveBody: React.FC const panelRootRef = useRef(null); const dialogActionScopeIdRef = useRef(`sftp-side-panel:${crypto.randomUUID()}`); const [hasPaneFocus, setHasPaneFocus] = useState(false); + const [pendingFollowOverride, setPendingFollowOverride] = useState<{ + hostId: string; + value: boolean; + } | null>(null); useSftpKeyboardShortcuts({ keyBindings, @@ -697,15 +703,34 @@ const SftpSidePanelInteractiveBody: React.FC const conn = sftp.leftPane.connection; if (conn && !conn.isLocal) { const latestHost = hosts.find((h) => h.id === conn.hostId) ?? null; + const pendingFollowValue = pendingFollowOverride?.hostId === conn.hostId + ? pendingFollowOverride.value + : undefined; // Prefer the stored Host object from connect time — it preserves // session-time overrides that the vault host may lack. if (connectedHostObjRef.current && connectedHostObjRef.current.id === conn.hostId) { - return mergeLatestFollowTerminalCwdHostSetting(connectedHostObjRef.current, latestHost); + return mergeLatestFollowTerminalCwdHostSetting( + connectedHostObjRef.current, + latestHost, + pendingFollowValue, + ); } return latestHost ?? activeHost; } return activeHost; - }, [activeHost, connectedHostObjRef, hosts, sftp.leftPane.connection]); + }, [activeHost, connectedHostObjRef, hosts, pendingFollowOverride, sftp.leftPane.connection]); + + useEffect(() => { + if (!pendingFollowOverride) return; + const latestHost = hosts.find((host) => host.id === pendingFollowOverride.hostId); + if (latestHost?.sftpFollowTerminalCwd === pendingFollowOverride.value) { + setPendingFollowOverride(null); + } + }, [hosts, pendingFollowOverride]); + + useEffect(() => { + setPendingFollowOverride(null); + }, [sftp.leftPane.connection?.id]); const followTerminalCwdHost = useMemo(() => { if (sftp.leftPane.connection?.isLocal) return null; @@ -728,17 +753,53 @@ const SftpSidePanelInteractiveBody: React.FC const hasActiveWork = showTextEditor || !!permissionsState || showFileOpenerDialog || (sftp.activeFileWatchCountRef?.current ?? 0) > 0; - const lastFailedFollowCwdRef = useRef(null); + const blockedFollowRef = useRef(null); + const followSyncGenerationRef = useRef(0); + const effectiveFollowTerminalCwdRef = useRef(effectiveFollowTerminalCwd); + const canFollowTerminalCwdRef = useRef(canFollowTerminalCwd); + effectiveFollowTerminalCwdRef.current = effectiveFollowTerminalCwd; + canFollowTerminalCwdRef.current = canFollowTerminalCwd; + const connectionId = sftp.leftPane.connection?.id ?? null; + const connectionPath = sftp.leftPane.connection?.currentPath ?? null; + + const invalidateInFlightFollowSync = useCallback(() => { + followSyncGenerationRef.current += 1; + blockedFollowRef.current = null; + }, []); useEffect(() => { - lastFailedFollowCwdRef.current = null; - }, [sftp.leftPane.connection?.id]); + blockedFollowRef.current = null; + }, [ + activeTerminalCwd, + followTerminalCwdHost?.id, + connectionId, + ]); + + useEffect(() => { + if (effectiveFollowTerminalCwd) return; + invalidateInFlightFollowSync(); + }, [effectiveFollowTerminalCwd, invalidateInFlightFollowSync]); + + useEffect(() => { + if ( + shouldClearBlockedFollowOnReach( + blockedFollowRef.current, + connectionId, + connectionPath, + sftp.leftPane.loading, + ) + ) { + blockedFollowRef.current = null; + } + }, [connectionId, connectionPath, sftp.leftPane.loading]); const handleGoToTerminalCwd = useCallback(async () => { if (!onGetTerminalCwd) return; const cwd = await onGetTerminalCwd({ preferFreshBackend: true }); - if (cwd) { - sftpRef.current.navigateTo("left", cwd); + if (!cwd) return; + const navigateResult = await sftpRef.current.navigateTo("left", cwd); + if (navigateResult === "reached") { + blockedFollowRef.current = null; } }, [onGetTerminalCwd, sftpRef]); @@ -747,30 +808,53 @@ const SftpSidePanelInteractiveBody: React.FC return; } + const syncGeneration = followSyncGenerationRef.current; + let terminalCwd = activeTerminalCwd; if (!terminalCwd) { terminalCwd = await onGetTerminalCwd({ preferFreshBackend: true }); } if (!terminalCwd) return; - if (lastFailedFollowCwdRef.current === terminalCwd) return; + if ( + syncGeneration !== followSyncGenerationRef.current + || !effectiveFollowTerminalCwdRef.current + || !canFollowTerminalCwdRef.current + ) { + return; + } const connection = sftpRef.current.leftPane.connection; if (!shouldFollowTerminalCwdNavigate({ - followEnabled: effectiveFollowTerminalCwd, + followEnabled: effectiveFollowTerminalCwdRef.current, isVisible, terminalCwd, currentPath: connection?.currentPath, + connectionId: connection?.id, hasActiveWork, isConnected: Boolean(connection && !connection.isLocal && connection.status === "connected"), + blockedFollow: blockedFollowRef.current, })) { return; } const navigateResult = await sftpRef.current.navigateTo("left", terminalCwd); - if (navigateResult === "failed") { - lastFailedFollowCwdRef.current = terminalCwd; + if ( + syncGeneration !== followSyncGenerationRef.current + || !effectiveFollowTerminalCwdRef.current + || !canFollowTerminalCwdRef.current + ) { + return; + } + + const currentConnection = sftpRef.current.leftPane.connection; + if (!currentConnection || currentConnection.id !== connection?.id) { + return; + } + + if (navigateResult === "failed" && currentConnection.id) { + blockedFollowRef.current = { connectionId: currentConnection.id, terminalCwd }; } else if (navigateResult === "reached") { - lastFailedFollowCwdRef.current = null; + blockedFollowRef.current = null; } }, [ activeTerminalCwd, @@ -783,12 +867,15 @@ const SftpSidePanelInteractiveBody: React.FC ]); const handleToggleFollowTerminalCwd = useCallback(() => { - onSftpFollowTerminalCwdChange?.(!effectiveFollowTerminalCwd, followTerminalCwdHost); - }, [effectiveFollowTerminalCwd, followTerminalCwdHost, onSftpFollowTerminalCwdChange]); - - useEffect(() => { - lastFailedFollowCwdRef.current = null; - }, [activeTerminalCwd]); + const nextEnabled = !effectiveFollowTerminalCwd; + if (!nextEnabled) { + invalidateInFlightFollowSync(); + } + if (followTerminalCwdHost?.id) { + setPendingFollowOverride({ hostId: followTerminalCwdHost.id, value: nextEnabled }); + } + onSftpFollowTerminalCwdChange?.(nextEnabled, followTerminalCwdHost); + }, [effectiveFollowTerminalCwd, followTerminalCwdHost, invalidateInFlightFollowSync, onSftpFollowTerminalCwdChange]); useEffect(() => { if (!effectiveFollowTerminalCwd || !canFollowTerminalCwd || !isVisible || hasActiveWork) return; diff --git a/components/sftp/sftpFollowTerminalCwd.test.ts b/components/sftp/sftpFollowTerminalCwd.test.ts index dde0f35a0..93bb01e2b 100644 --- a/components/sftp/sftpFollowTerminalCwd.test.ts +++ b/components/sftp/sftpFollowTerminalCwd.test.ts @@ -4,6 +4,7 @@ import { mergeLatestFollowTerminalCwdHostSetting, resolveHostFollowTerminalCwd, resolveSftpFollowTerminalCwdTargetHost, + shouldClearBlockedFollowOnReach, shouldFollowTerminalCwdNavigate, } from "./sftpFollowTerminalCwd"; @@ -12,6 +13,7 @@ const base = { isVisible: true, terminalCwd: "/home/user/project", currentPath: "/home/user", + connectionId: "conn-1", hasActiveWork: false, isConnected: true, }; @@ -39,6 +41,38 @@ test("shouldFollowTerminalCwdNavigate returns false without a known terminal cwd assert.equal(shouldFollowTerminalCwdNavigate({ ...base, terminalCwd: null }), false); }); +test("shouldFollowTerminalCwdNavigate returns false when cwd is blocked after a failed follow", () => { + assert.equal( + shouldFollowTerminalCwdNavigate({ + ...base, + blockedFollow: { connectionId: "conn-1", terminalCwd: "/home/user/project" }, + }), + false, + ); +}); + +test("shouldFollowTerminalCwdNavigate ignores blocked cwd for a different connection", () => { + assert.equal( + shouldFollowTerminalCwdNavigate({ + ...base, + connectionId: "conn-2", + blockedFollow: { connectionId: "conn-1", terminalCwd: "/home/user/project" }, + }), + true, + ); +}); + +test("shouldFollowTerminalCwdNavigate ignores blocked cwd when terminal cwd changed", () => { + assert.equal( + shouldFollowTerminalCwdNavigate({ + ...base, + terminalCwd: "/home/user/other", + blockedFollow: { connectionId: "conn-1", terminalCwd: "/home/user/project" }, + }), + true, + ); +}); + test("resolveHostFollowTerminalCwd inherits the global setting until the host overrides it", () => { assert.equal(resolveHostFollowTerminalCwd(undefined, true), true); assert.equal(resolveHostFollowTerminalCwd(undefined, false), false); @@ -89,3 +123,69 @@ test("mergeLatestFollowTerminalCwdHostSetting refreshes the follow flag without }, ); }); + +test("mergeLatestFollowTerminalCwdHostSetting keeps optimistic session override until vault updates", () => { + const connectedHost = { + id: "host-1", + hostname: "session.example.com", + sftpFollowTerminalCwd: false, + }; + const latestHost = { + id: "host-1", + hostname: "vault.example.com", + }; + + assert.deepEqual( + mergeLatestFollowTerminalCwdHostSetting(connectedHost, latestHost, false), + { + id: "host-1", + hostname: "session.example.com", + sftpFollowTerminalCwd: false, + }, + ); +}); + +test("mergeLatestFollowTerminalCwdHostSetting drops stale session override when vault clears the follow flag", () => { + const connectedHost = { + id: "host-1", + hostname: "session.example.com", + sftpFollowTerminalCwd: true, + }; + const latestHost = { + id: "host-1", + hostname: "vault.example.com", + }; + + assert.deepEqual( + mergeLatestFollowTerminalCwdHostSetting(connectedHost, latestHost), + { + id: "host-1", + hostname: "session.example.com", + sftpFollowTerminalCwd: undefined, + }, + ); +}); + +test("shouldClearBlockedFollowOnReach clears when the active connection reaches the blocked cwd", () => { + assert.equal( + shouldClearBlockedFollowOnReach( + { connectionId: "conn-1", terminalCwd: "/home/user/project" }, + "conn-1", + "/home/user/project", + false, + ), + true, + ); +}); + +test("shouldClearBlockedFollowOnReach keeps block while navigation is still loading", () => { + assert.equal( + shouldClearBlockedFollowOnReach( + { connectionId: "conn-1", terminalCwd: "/home/user/project" }, + "conn-1", + "/home/user/project", + true, + ), + false, + ); +}); diff --git a/components/sftp/sftpFollowTerminalCwd.ts b/components/sftp/sftpFollowTerminalCwd.ts index 4ec6f74ab..028714021 100644 --- a/components/sftp/sftpFollowTerminalCwd.ts +++ b/components/sftp/sftpFollowTerminalCwd.ts @@ -1,10 +1,18 @@ +export type SftpFollowTerminalCwdBlock = { + connectionId: string; + terminalCwd: string; +}; + export type SftpFollowTerminalCwdContext = { followEnabled: boolean; isVisible: boolean; terminalCwd?: string | null; currentPath?: string | null; + connectionId?: string | null; hasActiveWork: boolean; isConnected: boolean; + /** Skip auto-follow while this terminal cwd cannot be reached on SFTP. */ + blockedFollow?: SftpFollowTerminalCwdBlock | null; }; export const resolveHostFollowTerminalCwd = ( @@ -22,6 +30,7 @@ export const mergeLatestFollowTerminalCwdHostSetting = < >( displayHost: T | null | undefined, latestHost: T | null | undefined, + pendingFollowOverride?: boolean, ): T | null => { if (!displayHost) return latestHost ?? null; if (!latestHost || latestHost.id !== displayHost.id) return displayHost; @@ -29,22 +38,49 @@ export const mergeLatestFollowTerminalCwdHostSetting = < return { ...latestHost, ...displayHost, - sftpFollowTerminalCwd: latestHost.sftpFollowTerminalCwd, + sftpFollowTerminalCwd: + latestHost.sftpFollowTerminalCwd !== undefined + ? latestHost.sftpFollowTerminalCwd + : pendingFollowOverride, }; }; +/** Clear a follow block once the user reaches the blocked cwd through any navigation. */ +export const shouldClearBlockedFollowOnReach = ( + blockedFollow: SftpFollowTerminalCwdBlock | null | undefined, + connectionId: string | null | undefined, + currentPath: string | null | undefined, + loading: boolean, +): boolean => { + if (loading || !blockedFollow || !connectionId || !currentPath) return false; + return ( + blockedFollow.connectionId === connectionId + && blockedFollow.terminalCwd === currentPath + ); +}; + /** Whether SFTP should auto-navigate to match the linked terminal cwd. */ export const shouldFollowTerminalCwdNavigate = ({ followEnabled, isVisible, terminalCwd, currentPath, + connectionId, hasActiveWork, isConnected, + blockedFollow, }: SftpFollowTerminalCwdContext): boolean => { if (!followEnabled || !isVisible || !isConnected) return false; if (hasActiveWork) return false; if (!terminalCwd || terminalCwd.trim().length === 0) return false; + if ( + blockedFollow + && connectionId + && blockedFollow.connectionId === connectionId + && blockedFollow.terminalCwd === terminalCwd + ) { + return false; + } if (!currentPath || currentPath === terminalCwd) return false; return true; }; From d79353942b09afde1b8865ab52358fcf5aecc7f8 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 19:34:36 +0800 Subject: [PATCH 014/228] fix: keep host tree toolbar close button visible when sidebar is narrow Pin the collapse control outside the clipped action row and fade overflow so narrow widths stay usable without hiding the close button. Co-authored-by: Cursor --- .../terminalLayer/TerminalHostTreeSidebar.tsx | 14 +- .../TerminalHostTreeToolbar.test.ts | 62 +++++ .../terminalLayer/TerminalHostTreeToolbar.tsx | 257 ++++++++++-------- 3 files changed, 224 insertions(+), 109 deletions(-) create mode 100644 components/terminalLayer/TerminalHostTreeToolbar.test.ts diff --git a/components/terminalLayer/TerminalHostTreeSidebar.tsx b/components/terminalLayer/TerminalHostTreeSidebar.tsx index b7833bb8b..9543dc411 100644 --- a/components/terminalLayer/TerminalHostTreeSidebar.tsx +++ b/components/terminalLayer/TerminalHostTreeSidebar.tsx @@ -48,6 +48,8 @@ import { HoverCard, HoverCardContent, HoverCardTrigger } from '../ui/hover-card' import { TREE_ROW_HEIGHT } from '../sftp/SftpPaneTreeNode'; import { FixedSizeVirtualList, type FixedSizeVirtualListHandle } from '../ui/FixedSizeVirtualList'; import { + shouldCompactTerminalHostTreeToolbar, + shouldShowTerminalHostTreeExpandCollapseControls, TerminalHostTreeToolbar, type HostTreeToolbarPanel, } from './TerminalHostTreeToolbar'; @@ -741,8 +743,6 @@ const TerminalHostTreeSidebarInner: React.FC = ({ collapseAll(); }, [collapseAll]); - const canExpandCollapse = allGroupPaths.length > 0 && !searchActive && !tagsActive; - const handleCollapse = useCallback(() => { terminalHostTreeStore.setIsOpen(false); }, []); @@ -957,6 +957,13 @@ const TerminalHostTreeSidebarInner: React.FC = ({ }, [isVisible, persistSidebarWidth, setSidebarWidth, sidebarWidth]); const displayWidth = resizePreviewWidth ?? sidebarWidth; + const compactToolbarActions = shouldCompactTerminalHostTreeToolbar(displayWidth); + const showExpandCollapseControls = shouldShowTerminalHostTreeExpandCollapseControls( + allGroupPaths.length, + searchActive, + tagsActive, + compactToolbarActions, + ); const targetLayoutWidth = getTerminalHostTreeLayoutTargetWidth(isVisible, displayWidth); const hiddenSurfaceShellWidth = getTerminalHostTreeHiddenSurfaceShellWidth(isOpen, enabled, displayWidth); const [shellWidth, setShellWidth] = useState(getTerminalHostTreeInitialLayoutWidth); @@ -1093,9 +1100,10 @@ const TerminalHostTreeSidebarInner: React.FC = ({ canNewGroup={Boolean(menuActions)} onCreateLocalTerminal={handleCreateLocalTerminal} canCreateLocalTerminal={Boolean(onCreateLocalTerminal)} + compactActions={compactToolbarActions} onExpandAll={handleExpandAll} onCollapseAll={handleCollapseAll} - canExpandCollapse={canExpandCollapse} + showExpandCollapseControls={showExpandCollapseControls} onCollapse={handleCollapse} /> diff --git a/components/terminalLayer/TerminalHostTreeToolbar.test.ts b/components/terminalLayer/TerminalHostTreeToolbar.test.ts new file mode 100644 index 000000000..892f0cfe5 --- /dev/null +++ b/components/terminalLayer/TerminalHostTreeToolbar.test.ts @@ -0,0 +1,62 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import test from 'node:test'; + +const storage = new Map(); +Object.defineProperty(globalThis, 'localStorage', { + configurable: true, + value: { + getItem: (key: string) => storage.get(key) ?? null, + setItem: (key: string, value: string) => storage.set(key, value), + removeItem: (key: string) => storage.delete(key), + }, +}); + +const { TERMINAL_HOST_TREE_MIN_WIDTH } = await import('../../application/state/terminalHostTreeStore.ts'); +const { + shouldCompactTerminalHostTreeToolbar, + shouldShowTerminalHostTreeExpandCollapseControls, +} = await import('./TerminalHostTreeToolbar.tsx'); + +test('shouldCompactTerminalHostTreeToolbar activates near the sidebar minimum width', () => { + assert.equal(shouldCompactTerminalHostTreeToolbar(0), false); + assert.equal(shouldCompactTerminalHostTreeToolbar(TERMINAL_HOST_TREE_MIN_WIDTH + 24), true); + assert.equal(shouldCompactTerminalHostTreeToolbar(TERMINAL_HOST_TREE_MIN_WIDTH + 25), false); +}); + +test('shouldShowTerminalHostTreeExpandCollapseControls hides controls in compact mode', () => { + assert.equal( + shouldShowTerminalHostTreeExpandCollapseControls(3, false, false, true), + false, + ); + assert.equal( + shouldShowTerminalHostTreeExpandCollapseControls(3, false, false, false), + true, + ); + assert.equal( + shouldShowTerminalHostTreeExpandCollapseControls(0, false, false, false), + false, + ); + assert.equal( + shouldShowTerminalHostTreeExpandCollapseControls(3, true, false, false), + false, + ); +}); + +test('host tree toolbar keeps the close button outside the clipped action row', () => { + const source = readFileSync(new URL('./TerminalHostTreeToolbar.tsx', import.meta.url), 'utf8'); + + assert.match(source, /data-section="terminal-host-tree-toolbar-actions"/); + assert.match(source, /data-section="terminal-host-tree-toolbar-close"/); + assert.match(source, /data-section="terminal-host-tree-toolbar-actions-fade"/); + assert.match(source, /linear-gradient\(to right, transparent, var\(--terminal-host-tree-bg/); + assert.doesNotMatch(source, /flex-1 min-w-0" \/>/); +}); + +test('host tree sidebar passes compact toolbar state from display width', () => { + const source = readFileSync(new URL('./TerminalHostTreeSidebar.tsx', import.meta.url), 'utf8'); + + assert.match(source, /compactActions=\{compactToolbarActions\}/); + assert.match(source, /showExpandCollapseControls=\{showExpandCollapseControls\}/); + assert.match(source, /shouldCompactTerminalHostTreeToolbar\(displayWidth\)/); +}); diff --git a/components/terminalLayer/TerminalHostTreeToolbar.tsx b/components/terminalLayer/TerminalHostTreeToolbar.tsx index d283d16b3..788aadc50 100644 --- a/components/terminalLayer/TerminalHostTreeToolbar.tsx +++ b/components/terminalLayer/TerminalHostTreeToolbar.tsx @@ -2,6 +2,9 @@ import { Check, Expand, FolderPlus, Minimize2, Search, Tag, TerminalSquare, X } import React, { useEffect, useRef } from 'react'; import { useI18n } from '../../application/i18n/I18nProvider'; +import { + TERMINAL_HOST_TREE_MIN_WIDTH, +} from '../../application/state/terminalHostTreeStore'; import { cn } from '../../lib/utils'; import { Button } from '../ui/button'; import { Input } from '../ui/input'; @@ -29,14 +32,29 @@ interface TerminalHostTreeToolbarProps { canNewGroup?: boolean; onCreateLocalTerminal: () => void; canCreateLocalTerminal?: boolean; + compactActions?: boolean; onExpandAll: () => void; onCollapseAll: () => void; - canExpandCollapse?: boolean; + showExpandCollapseControls?: boolean; onCollapse: () => void; } const iconButtonClass = 'netcatty-tab h-7 w-7 shrink-0 rounded-md p-0 hover:bg-transparent'; +/** Hide low-priority toolbar actions once the sidebar reaches its minimum width. */ +export function shouldCompactTerminalHostTreeToolbar(displayWidth: number): boolean { + return displayWidth > 0 && displayWidth <= TERMINAL_HOST_TREE_MIN_WIDTH + 24; +} + +export function shouldShowTerminalHostTreeExpandCollapseControls( + groupPathCount: number, + searchActive: boolean, + tagsActive: boolean, + compactToolbar: boolean, +): boolean { + return groupPathCount > 0 && !searchActive && !tagsActive && !compactToolbar; +} + export const TerminalHostTreeToolbar: React.FC = ({ theme, expandedPanel, @@ -50,9 +68,10 @@ export const TerminalHostTreeToolbar: React.FC = ( canNewGroup = true, onCreateLocalTerminal, canCreateLocalTerminal = true, + compactActions = false, onExpandAll, onCollapseAll, - canExpandCollapse = true, + showExpandCollapseControls = true, onCollapse, }) => { const { t } = useI18n(); @@ -84,119 +103,145 @@ export const TerminalHostTreeToolbar: React.FC = ( return (
- - - - - {t('terminal.layer.hostTree.searchButton')} - +
+
+ + + + + {t('terminal.layer.hostTree.searchButton')} + - - - - - {t('terminal.layer.hostTree.tagsButton')} - + + + + + {t('terminal.layer.hostTree.tagsButton')} + - - - - - {t('terminal.layer.hostTree.newGroup')} - + {!compactActions && ( + <> + + + + + {t('terminal.layer.hostTree.newGroup')} + - - - - - {t('terminal.layer.hostTree.localShell')} - + + + + + {t('terminal.layer.hostTree.localShell')} + + + )} - - - - - {t('vault.tree.expandAll')} - + {showExpandCollapseControls && ( + <> + + + + + {t('vault.tree.expandAll')} + - - - - - {t('vault.tree.collapseAll')} - + + + + + {t('vault.tree.collapseAll')} + + + )} +
-
+
+
- - - - - {t('terminal.layer.hostTree.collapse')} - +
+ + + + + {t('terminal.layer.hostTree.collapse')} + +
Date: Wed, 24 Jun 2026 19:37:55 +0800 Subject: [PATCH 015/228] Improve network device vendor detection (#1624) * restore h3c network device detection * ignore release build artifacts in lint * restore h3c mpssh banner detection * detect network device vendor banners * Map mpSSH banners to HPE iLO --------- Co-authored-by: mam15mon --- application/i18n/locales/en/vault.ts | 3 ++- application/i18n/locales/ru/vault.ts | 3 ++- application/i18n/locales/zh-CN/vault.ts | 3 ++- components/DistroAvatar.test.tsx | 13 ++++++++++ components/DistroAvatar.tsx | 4 ++- .../runtime/terminalDistroDetection.test.ts | 13 +++++++--- .../runtime/terminalDistroDetection.ts | 8 +++--- components/top-tabs/TopTabItems.tsx | 2 +- domain/host.test.ts | 10 +++++++ domain/host.ts | 10 ++++--- eslint.config.js | 2 +- public/distro/h3c.svg | 26 +++++++++++++++++++ 12 files changed, 79 insertions(+), 18 deletions(-) create mode 100644 public/distro/h3c.svg diff --git a/application/i18n/locales/en/vault.ts b/application/i18n/locales/en/vault.ts index 0d0221420..15edd5da6 100644 --- a/application/i18n/locales/en/vault.ts +++ b/application/i18n/locales/en/vault.ts @@ -583,7 +583,8 @@ export const enVaultMessages: Messages = { 'hostDetails.distro.option.cisco': 'Cisco', 'hostDetails.distro.option.juniper': 'Juniper Networks', 'hostDetails.distro.option.huawei': 'Huawei', - 'hostDetails.distro.option.hpe': 'HPE / H3C', + 'hostDetails.distro.option.h3c': 'H3C', + 'hostDetails.distro.option.hpe': 'HPE', 'hostDetails.distro.option.mikrotik': 'MikroTik', 'hostDetails.distro.option.fortinet': 'Fortinet', 'hostDetails.distro.option.paloalto': 'Palo Alto Networks', diff --git a/application/i18n/locales/ru/vault.ts b/application/i18n/locales/ru/vault.ts index 9cee28e02..0db2c4d01 100644 --- a/application/i18n/locales/ru/vault.ts +++ b/application/i18n/locales/ru/vault.ts @@ -618,7 +618,8 @@ export const ruVaultMessages: Messages = { 'hostDetails.distro.option.cisco': 'Cisco', 'hostDetails.distro.option.juniper': 'Juniper Networks', 'hostDetails.distro.option.huawei': 'Huawei', - 'hostDetails.distro.option.hpe': 'HPE / H3C', + 'hostDetails.distro.option.h3c': 'H3C', + 'hostDetails.distro.option.hpe': 'HPE', 'hostDetails.distro.option.mikrotik': 'MikroTik', 'hostDetails.distro.option.fortinet': 'Fortinet', 'hostDetails.distro.option.paloalto': 'Palo Alto Networks', diff --git a/application/i18n/locales/zh-CN/vault.ts b/application/i18n/locales/zh-CN/vault.ts index 98f40f3a5..91733be69 100644 --- a/application/i18n/locales/zh-CN/vault.ts +++ b/application/i18n/locales/zh-CN/vault.ts @@ -157,7 +157,8 @@ export const zhCNVaultMessages: Messages = { 'hostDetails.distro.option.cisco': '思科', 'hostDetails.distro.option.juniper': '瞻博网络', 'hostDetails.distro.option.huawei': '华为', - 'hostDetails.distro.option.hpe': '慧与 / H3C', + 'hostDetails.distro.option.h3c': '新华三 / H3C', + 'hostDetails.distro.option.hpe': '慧与 / HPE', 'hostDetails.distro.option.mikrotik': 'MikroTik', 'hostDetails.distro.option.fortinet': '飞塔', 'hostDetails.distro.option.paloalto': 'Palo Alto Networks', diff --git a/components/DistroAvatar.test.tsx b/components/DistroAvatar.test.tsx index 1d53d406b..f24969ef1 100644 --- a/components/DistroAvatar.test.tsx +++ b/components/DistroAvatar.test.tsx @@ -60,3 +60,16 @@ test("DistroAvatar keeps distro icon and applies custom palette color when icon assert.match(markup, /src="\/distro\/ubuntu.svg"/); assert.doesNotMatch(markup, /bg-\[#E95420\]/); }); + +test("DistroAvatar renders H3C logo without monochrome inversion", () => { + const markup = renderToStaticMarkup( + , + ); + + assert.match(markup, /src="\/distro\/h3c.svg"/); + assert.match(markup, /bg-white/); + assert.doesNotMatch(markup, /invert brightness-0/); +}); diff --git a/components/DistroAvatar.tsx b/components/DistroAvatar.tsx index 904ce400c..47e288bdf 100644 --- a/components/DistroAvatar.tsx +++ b/components/DistroAvatar.tsx @@ -31,6 +31,7 @@ export const DISTRO_LOGOS: Record = { cisco: "/distro/cisco.svg", juniper: "/distro/juniper.svg", huawei: "/distro/huawei.svg", + h3c: "/distro/h3c.svg", hpe: "/distro/hpe.svg", mikrotik: "/distro/mikrotik.svg", fortinet: "/distro/fortinet.svg", @@ -62,6 +63,7 @@ export const DISTRO_COLORS: Record = { cisco: "bg-[#1BA0D7]", juniper: "bg-[#0A6EB4]", huawei: "bg-[#CF0A2C]", + h3c: "bg-white", hpe: "bg-[#01A982]", mikrotik: "bg-[#293239]", fortinet: "bg-[#EE3124]", @@ -158,7 +160,7 @@ const DistroAvatarInner: React.FC = ({ {distro setErrored(true)} />
diff --git a/components/terminal/runtime/terminalDistroDetection.test.ts b/components/terminal/runtime/terminalDistroDetection.test.ts index d9e15e773..506230e1a 100644 --- a/components/terminal/runtime/terminalDistroDetection.test.ts +++ b/components/terminal/runtime/terminalDistroDetection.test.ts @@ -6,15 +6,16 @@ import { runDistroDetection, } from "./terminalDistroDetection.ts"; -test("runDistroDetection skips POSIX probes for manually marked network devices", async () => { +test("runDistroDetection uses SSH banner but skips POSIX probes for manually marked network devices", async () => { let remoteInfoCalls = 0; let distroProbeCalls = 0; + const detected: string[] = []; const token = registerConnectionToken("ssh-session"); await runDistroDetection({ host: { id: "host-1", - label: "Ruijie AP", + label: "HPE iLO", hostname: "192.168.2.2", username: "root", deviceType: "network", @@ -22,15 +23,19 @@ test("runDistroDetection skips POSIX probes for manually marked network devices" terminalBackend: { getSessionRemoteInfo: async () => { remoteInfoCalls += 1; - return { success: true, remoteSshVersion: "RGOS_SSH" }; + return { success: true, remoteSshVersion: "SSH-2.0-mpSSH_0.2.1" }; }, getSessionDistroInfo: async () => { distroProbeCalls += 1; return { success: false, error: "network device closed the extra channel" }; }, }, + onOsDetected: (_hostId: string, distro: string) => { + detected.push(distro); + }, } as never, "ssh-session", token); - assert.equal(remoteInfoCalls, 0); + assert.equal(remoteInfoCalls, 1); assert.equal(distroProbeCalls, 0); + assert.deepEqual(detected, ["hpe"]); }); diff --git a/components/terminal/runtime/terminalDistroDetection.ts b/components/terminal/runtime/terminalDistroDetection.ts index 738ae44fb..bd1d5ab28 100644 --- a/components/terminal/runtime/terminalDistroDetection.ts +++ b/components/terminal/runtime/terminalDistroDetection.ts @@ -44,12 +44,9 @@ export const runDistroDetection = async ( const isStillCurrent = () => isConnectionTokenCurrent(sessionId, connectionToken); if (!isStillCurrent()) return; - if ( + const isKnownNetworkDevice = ctx.host.deviceType === "network" || - classifyDistroId(ctx.host.distro) === "network-device" - ) { - return; - } + classifyDistroId(ctx.host.distro) === "network-device"; // Step 1: try to classify from the SSH server identification string // captured at handshake time. This is free (no extra channel) and @@ -73,6 +70,7 @@ export const runDistroDetection = async ( } if (!isStillCurrent()) return; + if (isKnownNetworkDevice) return; // Step 2: unknown or generic OpenSSH/Dropbear — fall back to the // /etc/os-release probe to pick a distro-specific icon. We deliberately diff --git a/components/top-tabs/TopTabItems.tsx b/components/top-tabs/TopTabItems.tsx index cfbd97b3d..b04413b8f 100644 --- a/components/top-tabs/TopTabItems.tsx +++ b/components/top-tabs/TopTabItems.tsx @@ -125,7 +125,7 @@ const SessionTabIcon: React.FC<{ {distro
); diff --git a/domain/host.test.ts b/domain/host.test.ts index 37ae16a52..6daa01a40 100644 --- a/domain/host.test.ts +++ b/domain/host.test.ts @@ -279,6 +279,16 @@ test("detectVendorFromSshVersion recognizes Ruijie RGOS banner", () => { assert.equal(detectVendorFromSshVersion("SSH-2.0-RGOS_SSH"), "ruijie"); }); +test("detectVendorFromSshVersion recognizes H3C and Comware banners", () => { + assert.equal(detectVendorFromSshVersion("H3C-Comware-7.1.064"), "h3c"); + assert.equal(detectVendorFromSshVersion("SSH-2.0-Comware-7.1.064"), "h3c"); + assert.equal(detectVendorFromSshVersion("SSH-2.0-3Com OS"), "h3c"); +}); + +test("detectVendorFromSshVersion maps mpSSH banners to HPE iLO", () => { + assert.equal(detectVendorFromSshVersion("SSH-2.0-mpSSH_0.2.1"), "hpe"); +}); + test("normalizeDistroId maps Alibaba Cloud Linux os-release ID to alinux", () => { // /etc/os-release ID="alinux" — the canonical signal from Alibaba Cloud // Linux 3 (issue #1200). Regression guard: 'alinux'.includes('linux') is diff --git a/domain/host.ts b/domain/host.ts index 59bb02cd0..ad9ee3a30 100644 --- a/domain/host.ts +++ b/domain/host.ts @@ -62,6 +62,7 @@ export const NETWORK_DEVICE_OPTIONS = [ 'cisco', 'juniper', 'huawei', + 'h3c', 'hpe', 'mikrotik', 'fortinet', @@ -142,9 +143,12 @@ export const detectVendorFromSshVersion = (softwareVersion?: string): '' | Netwo if (/^HUAWEI[-_]/i.test(s)) return 'huawei'; if (/^VRP-/i.test(s)) return 'huawei'; - // HPE / H3C — Comware switches, Integrated Lights-Out (iLO), legacy 3Com - if (/^Comware-/i.test(s)) return 'hpe'; - if (/^3Com\s*OS/i.test(s)) return 'hpe'; + // H3C / 3Com Comware switches + if (/^H3C[-_\s]/i.test(s)) return 'h3c'; + if (/^Comware-/i.test(s)) return 'h3c'; + if (/^3Com\s*OS/i.test(s)) return 'h3c'; + + // HPE iLO if (/^mpSSH_/i.test(s)) return 'hpe'; // MikroTik RouterOS diff --git a/eslint.config.js b/eslint.config.js index 2d8713b30..2f75ec4b3 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -12,7 +12,7 @@ export default [ // every other electron/ file matches no config and stays unlinted as before. { ...js.configs.recommended, ignores: ["electron/**"] }, { - ignores: ["node_modules/**", "dist/**", "scripts/**", "public/monaco/**", ".github/**", ".claude/**", "release/**", ".worktrees/**"], + ignores: ["node_modules/**", "dist/**", "scripts/**", "public/monaco/**", ".github/**", ".claude/**", "release/**", "release-build/**", ".worktrees/**"], }, { files: ["**/*.{ts,tsx}"], diff --git a/public/distro/h3c.svg b/public/distro/h3c.svg new file mode 100644 index 000000000..eadc3e5ae --- /dev/null +++ b/public/distro/h3c.svg @@ -0,0 +1,26 @@ + + + + + + + + + + From 344674957327473c47b8c88bda332e629b6d376f Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 19:39:38 +0800 Subject: [PATCH 016/228] fix: clip host tree toolbar actions instead of hiding them when narrow Keep all action buttons in the overflow row so the toolbar does not leave empty gaps beside the pinned close control. Co-authored-by: Cursor --- .../terminalLayer/TerminalHostTreeSidebar.tsx | 13 +- .../TerminalHostTreeToolbar.test.ts | 59 ++----- .../terminalLayer/TerminalHostTreeToolbar.tsx | 151 ++++++++---------- 3 files changed, 79 insertions(+), 144 deletions(-) diff --git a/components/terminalLayer/TerminalHostTreeSidebar.tsx b/components/terminalLayer/TerminalHostTreeSidebar.tsx index 9543dc411..e8578389f 100644 --- a/components/terminalLayer/TerminalHostTreeSidebar.tsx +++ b/components/terminalLayer/TerminalHostTreeSidebar.tsx @@ -48,8 +48,6 @@ import { HoverCard, HoverCardContent, HoverCardTrigger } from '../ui/hover-card' import { TREE_ROW_HEIGHT } from '../sftp/SftpPaneTreeNode'; import { FixedSizeVirtualList, type FixedSizeVirtualListHandle } from '../ui/FixedSizeVirtualList'; import { - shouldCompactTerminalHostTreeToolbar, - shouldShowTerminalHostTreeExpandCollapseControls, TerminalHostTreeToolbar, type HostTreeToolbarPanel, } from './TerminalHostTreeToolbar'; @@ -957,13 +955,7 @@ const TerminalHostTreeSidebarInner: React.FC = ({ }, [isVisible, persistSidebarWidth, setSidebarWidth, sidebarWidth]); const displayWidth = resizePreviewWidth ?? sidebarWidth; - const compactToolbarActions = shouldCompactTerminalHostTreeToolbar(displayWidth); - const showExpandCollapseControls = shouldShowTerminalHostTreeExpandCollapseControls( - allGroupPaths.length, - searchActive, - tagsActive, - compactToolbarActions, - ); + const canExpandCollapse = allGroupPaths.length > 0 && !searchActive && !tagsActive; const targetLayoutWidth = getTerminalHostTreeLayoutTargetWidth(isVisible, displayWidth); const hiddenSurfaceShellWidth = getTerminalHostTreeHiddenSurfaceShellWidth(isOpen, enabled, displayWidth); const [shellWidth, setShellWidth] = useState(getTerminalHostTreeInitialLayoutWidth); @@ -1100,10 +1092,9 @@ const TerminalHostTreeSidebarInner: React.FC = ({ canNewGroup={Boolean(menuActions)} onCreateLocalTerminal={handleCreateLocalTerminal} canCreateLocalTerminal={Boolean(onCreateLocalTerminal)} - compactActions={compactToolbarActions} onExpandAll={handleExpandAll} onCollapseAll={handleCollapseAll} - showExpandCollapseControls={showExpandCollapseControls} + canExpandCollapse={canExpandCollapse} onCollapse={handleCollapse} /> diff --git a/components/terminalLayer/TerminalHostTreeToolbar.test.ts b/components/terminalLayer/TerminalHostTreeToolbar.test.ts index 892f0cfe5..01a11f06d 100644 --- a/components/terminalLayer/TerminalHostTreeToolbar.test.ts +++ b/components/terminalLayer/TerminalHostTreeToolbar.test.ts @@ -2,47 +2,6 @@ import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import test from 'node:test'; -const storage = new Map(); -Object.defineProperty(globalThis, 'localStorage', { - configurable: true, - value: { - getItem: (key: string) => storage.get(key) ?? null, - setItem: (key: string, value: string) => storage.set(key, value), - removeItem: (key: string) => storage.delete(key), - }, -}); - -const { TERMINAL_HOST_TREE_MIN_WIDTH } = await import('../../application/state/terminalHostTreeStore.ts'); -const { - shouldCompactTerminalHostTreeToolbar, - shouldShowTerminalHostTreeExpandCollapseControls, -} = await import('./TerminalHostTreeToolbar.tsx'); - -test('shouldCompactTerminalHostTreeToolbar activates near the sidebar minimum width', () => { - assert.equal(shouldCompactTerminalHostTreeToolbar(0), false); - assert.equal(shouldCompactTerminalHostTreeToolbar(TERMINAL_HOST_TREE_MIN_WIDTH + 24), true); - assert.equal(shouldCompactTerminalHostTreeToolbar(TERMINAL_HOST_TREE_MIN_WIDTH + 25), false); -}); - -test('shouldShowTerminalHostTreeExpandCollapseControls hides controls in compact mode', () => { - assert.equal( - shouldShowTerminalHostTreeExpandCollapseControls(3, false, false, true), - false, - ); - assert.equal( - shouldShowTerminalHostTreeExpandCollapseControls(3, false, false, false), - true, - ); - assert.equal( - shouldShowTerminalHostTreeExpandCollapseControls(0, false, false, false), - false, - ); - assert.equal( - shouldShowTerminalHostTreeExpandCollapseControls(3, true, false, false), - false, - ); -}); - test('host tree toolbar keeps the close button outside the clipped action row', () => { const source = readFileSync(new URL('./TerminalHostTreeToolbar.tsx', import.meta.url), 'utf8'); @@ -50,13 +9,23 @@ test('host tree toolbar keeps the close button outside the clipped action row', assert.match(source, /data-section="terminal-host-tree-toolbar-close"/); assert.match(source, /data-section="terminal-host-tree-toolbar-actions-fade"/); assert.match(source, /linear-gradient\(to right, transparent, var\(--terminal-host-tree-bg/); + assert.doesNotMatch(source, /compactActions/); assert.doesNotMatch(source, /flex-1 min-w-0" \/>/); }); -test('host tree sidebar passes compact toolbar state from display width', () => { +test('host tree toolbar keeps action buttons in the clipped row instead of hiding them', () => { + const source = readFileSync(new URL('./TerminalHostTreeToolbar.tsx', import.meta.url), 'utf8'); + + assert.match(source, //); + assert.match(source, //); + assert.match(source, //); + assert.match(source, /disabled=\{!canExpandCollapse\}/); +}); + +test('host tree sidebar wires expand/collapse availability without compact hiding', () => { const source = readFileSync(new URL('./TerminalHostTreeSidebar.tsx', import.meta.url), 'utf8'); - assert.match(source, /compactActions=\{compactToolbarActions\}/); - assert.match(source, /showExpandCollapseControls=\{showExpandCollapseControls\}/); - assert.match(source, /shouldCompactTerminalHostTreeToolbar\(displayWidth\)/); + assert.match(source, /canExpandCollapse=\{canExpandCollapse\}/); + assert.doesNotMatch(source, /compactActions/); + assert.doesNotMatch(source, /shouldCompactTerminalHostTreeToolbar/); }); diff --git a/components/terminalLayer/TerminalHostTreeToolbar.tsx b/components/terminalLayer/TerminalHostTreeToolbar.tsx index 788aadc50..b47b98146 100644 --- a/components/terminalLayer/TerminalHostTreeToolbar.tsx +++ b/components/terminalLayer/TerminalHostTreeToolbar.tsx @@ -2,9 +2,6 @@ import { Check, Expand, FolderPlus, Minimize2, Search, Tag, TerminalSquare, X } import React, { useEffect, useRef } from 'react'; import { useI18n } from '../../application/i18n/I18nProvider'; -import { - TERMINAL_HOST_TREE_MIN_WIDTH, -} from '../../application/state/terminalHostTreeStore'; import { cn } from '../../lib/utils'; import { Button } from '../ui/button'; import { Input } from '../ui/input'; @@ -32,29 +29,14 @@ interface TerminalHostTreeToolbarProps { canNewGroup?: boolean; onCreateLocalTerminal: () => void; canCreateLocalTerminal?: boolean; - compactActions?: boolean; onExpandAll: () => void; onCollapseAll: () => void; - showExpandCollapseControls?: boolean; + canExpandCollapse?: boolean; onCollapse: () => void; } const iconButtonClass = 'netcatty-tab h-7 w-7 shrink-0 rounded-md p-0 hover:bg-transparent'; -/** Hide low-priority toolbar actions once the sidebar reaches its minimum width. */ -export function shouldCompactTerminalHostTreeToolbar(displayWidth: number): boolean { - return displayWidth > 0 && displayWidth <= TERMINAL_HOST_TREE_MIN_WIDTH + 24; -} - -export function shouldShowTerminalHostTreeExpandCollapseControls( - groupPathCount: number, - searchActive: boolean, - tagsActive: boolean, - compactToolbar: boolean, -): boolean { - return groupPathCount > 0 && !searchActive && !tagsActive && !compactToolbar; -} - export const TerminalHostTreeToolbar: React.FC = ({ theme, expandedPanel, @@ -68,10 +50,9 @@ export const TerminalHostTreeToolbar: React.FC = ( canNewGroup = true, onCreateLocalTerminal, canCreateLocalTerminal = true, - compactActions = false, onExpandAll, onCollapseAll, - showExpandCollapseControls = true, + canExpandCollapse = true, onCollapse, }) => { const { t } = useI18n(); @@ -111,7 +92,7 @@ export const TerminalHostTreeToolbar: React.FC = ( className="relative flex min-w-0 flex-1 items-center overflow-hidden" data-section="terminal-host-tree-toolbar-actions" > -
+
- - {t('terminal.layer.hostTree.newGroup')} - + + + + + {t('terminal.layer.hostTree.newGroup')} + - - - - - {t('terminal.layer.hostTree.localShell')} - - - )} + + + + + {t('terminal.layer.hostTree.localShell')} + - {showExpandCollapseControls && ( - <> - - - - - {t('vault.tree.expandAll')} - + + + + + {t('vault.tree.expandAll')} + - - - - - {t('vault.tree.collapseAll')} - - - )} + + + + + {t('vault.tree.collapseAll')} +
Date: Wed, 24 Jun 2026 20:15:36 +0800 Subject: [PATCH 017/228] fix(terminal): strip sync-block clear-screen for Codex/Claude Code scrollback Filter `\x1b[2J` inside DEC 2026 synchronized-output blocks before PTY data reaches xterm.js so full-screen coding CLI redraws no longer reset viewportY and make earlier output appear eaten. Fixes #1612 Co-authored-by: Cursor --- .../runtime/createTerminalSessionStarters.ts | 2 + .../runtime/filterSyncBlockClears.test.ts | 58 +++++++++++++++++ .../terminal/runtime/filterSyncBlockClears.ts | 62 +++++++++++++++++++ .../runtime/terminalSessionAttachment.ts | 16 +++-- .../runtime/terminalSyncBlockFilter.ts | 25 ++++++++ 5 files changed, 158 insertions(+), 5 deletions(-) create mode 100644 components/terminal/runtime/filterSyncBlockClears.test.ts create mode 100644 components/terminal/runtime/filterSyncBlockClears.ts create mode 100644 components/terminal/runtime/terminalSyncBlockFilter.ts diff --git a/components/terminal/runtime/createTerminalSessionStarters.ts b/components/terminal/runtime/createTerminalSessionStarters.ts index fd4e87d6f..fa9d7083a 100644 --- a/components/terminal/runtime/createTerminalSessionStarters.ts +++ b/components/terminal/runtime/createTerminalSessionStarters.ts @@ -15,6 +15,7 @@ import { writeSessionData, writeTerminalLine, } from "./terminalSessionAttachment"; +import { resetTerminalSyncBlockFilter } from "./terminalSyncBlockFilter"; import { isConnectionTokenCurrent, registerConnectionToken, runDistroDetection } from "./terminalDistroDetection"; import { resolveStartupCommand, scheduleStartupCommand } from "./terminalStartupCommands"; import { markPromptLineBreakCommandPending } from "./promptLineBreak"; @@ -1096,6 +1097,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex ctx.sessionRef.current = id; getFlowController(ctx, term).reset(); + resetTerminalSyncBlockFilter(term); resetTerminalLineTimestampState(term); ctx.disposeDataRef.current = ctx.terminalBackend.onSessionData(id, (chunk) => { writeSessionData(ctx, term, chunk); diff --git a/components/terminal/runtime/filterSyncBlockClears.test.ts b/components/terminal/runtime/filterSyncBlockClears.test.ts new file mode 100644 index 000000000..59e161188 --- /dev/null +++ b/components/terminal/runtime/filterSyncBlockClears.test.ts @@ -0,0 +1,58 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + createSyncBlockFilterState, + filterSyncBlockClears, +} from "./filterSyncBlockClears.ts"; + +const SYNC_START = "\x1b[?2026h"; +const SYNC_END = "\x1b[?2026l"; +const CLEAR = "\x1b[2J"; + +test("passes through data with no synchronized-output sequences", () => { + const state = createSyncBlockFilterState(); + const input = "hello\r\n\x1b[2Jworld\r\n"; + + assert.equal(filterSyncBlockClears(input, state), input); + assert.equal(state.inSyncBlock, false); +}); + +test("strips clear-screen inside a synchronized-output block", () => { + const state = createSyncBlockFilterState(); + const input = `${SYNC_START}${CLEAR}frame${SYNC_END}`; + + assert.equal(filterSyncBlockClears(input, state), `${SYNC_START}frame${SYNC_END}`); + assert.equal(state.inSyncBlock, false); +}); + +test("does not strip clear-screen outside synchronized-output blocks", () => { + const state = createSyncBlockFilterState(); + + assert.equal(filterSyncBlockClears(CLEAR, state), CLEAR); + assert.equal(state.inSyncBlock, false); +}); + +test("tracks synchronized-output state across chunks", () => { + const state = createSyncBlockFilterState(); + + assert.equal(filterSyncBlockClears(SYNC_START, state), SYNC_START); + assert.equal(state.inSyncBlock, true); + + assert.equal(filterSyncBlockClears(`${CLEAR}partial`, state), "partial"); + assert.equal(state.inSyncBlock, true); + + assert.equal(filterSyncBlockClears(`${CLEAR}done${SYNC_END}`, state), `done${SYNC_END}`); + assert.equal(state.inSyncBlock, false); +}); + +test("leaves non-clear redraw sequences inside synchronized-output blocks intact", () => { + const state = createSyncBlockFilterState(); + const cursorHome = "\x1b[H"; + const input = `${SYNC_START}${cursorHome}${CLEAR}text${SYNC_END}`; + + assert.equal( + filterSyncBlockClears(input, state), + `${SYNC_START}${cursorHome}text${SYNC_END}`, + ); +}); diff --git a/components/terminal/runtime/filterSyncBlockClears.ts b/components/terminal/runtime/filterSyncBlockClears.ts new file mode 100644 index 000000000..62be0455a --- /dev/null +++ b/components/terminal/runtime/filterSyncBlockClears.ts @@ -0,0 +1,62 @@ +/** + * Strip `\x1b[2J` (ED — erase display) inside DEC Mode 2026 synchronized-output + * blocks before data reaches xterm.js. + * + * Coding CLIs such as Codex and Claude Code wrap full-screen redraws in + * `\x1b[?2026h` … `\x1b[?2026l`. Native terminals treat the enclosed clear as + * part of the atomic update, but xterm.js resets viewportY on every `\x1b[2J`, + * which yanks scroll position and makes earlier output appear "eaten". + * + * @see https://github.com/xtermjs/xterm.js/issues/5801 + * @see https://github.com/openai/codex/issues/14277 + */ + +export type SyncBlockFilterState = { + inSyncBlock: boolean; +}; + +const SYNC_START = "\x1b[?2026h"; +const SYNC_END = "\x1b[?2026l"; +const CLEAR = "\x1b[2J"; + +export const filterSyncBlockClears = ( + data: string, + state: SyncBlockFilterState, +): string => { + if (!state.inSyncBlock && !data.includes(SYNC_START)) { + return data; + } + + let result = ""; + let index = 0; + + while (index < data.length) { + if (data.startsWith(SYNC_START, index)) { + state.inSyncBlock = true; + result += SYNC_START; + index += SYNC_START.length; + continue; + } + + if (data.startsWith(SYNC_END, index)) { + state.inSyncBlock = false; + result += SYNC_END; + index += SYNC_END.length; + continue; + } + + if (state.inSyncBlock && data.startsWith(CLEAR, index)) { + index += CLEAR.length; + continue; + } + + result += data[index]; + index += 1; + } + + return result; +}; + +export const createSyncBlockFilterState = (): SyncBlockFilterState => ({ + inSyncBlock: false, +}); diff --git a/components/terminal/runtime/terminalSessionAttachment.ts b/components/terminal/runtime/terminalSessionAttachment.ts index c7412def0..583a4bdea 100644 --- a/components/terminal/runtime/terminalSessionAttachment.ts +++ b/components/terminal/runtime/terminalSessionAttachment.ts @@ -18,6 +18,10 @@ import { writeTerminalDataWithLineTimestamps, } from "./terminalLineTimestamps"; import { createSudoPasswordAutofill } from "./terminalSudoAutofill"; +import { + filterTerminalSessionData, + resetTerminalSyncBlockFilter, +} from "./terminalSyncBlockFilter"; export const buildTermEnv = (host: Host, terminalSettings?: TerminalSettings) => { const env: Record = { @@ -141,8 +145,9 @@ export const writeSessionData = ( term: XTerm, data: string, ) => { + const displayData = filterTerminalSessionData(term, data); const flow = getFlowController(ctx, term); - flow.received(data.length); + flow.received(displayData.length); enqueueTerminalWrite(term, (done) => { const settings = ctx.terminalSettingsRef?.current ?? ctx.terminalSettings; const forcePromptNewLine = settings?.forcePromptNewLine ?? false; @@ -150,8 +155,8 @@ export const writeSessionData = ( ctx.promptLineBreakStateRef.current.pendingCommand = false; ctx.promptLineBreakStateRef.current.suppressNextPromptCache = false; } - const pasteDisplayData = prepareTerminalDataForUserPasteDisplay(term, data); - const displayData = prepareTerminalDataForPromptLineBreak( + const pasteDisplayData = prepareTerminalDataForUserPasteDisplay(term, displayData); + const preparedDisplayData = prepareTerminalDataForPromptLineBreak( term, pasteDisplayData, ctx.promptLineBreakStateRef?.current, @@ -177,10 +182,10 @@ export const writeSessionData = ( } done(); // Acknowledge the chunk so back-pressure can ease once xterm catches up. - flow.written(data.length); + flow.written(displayData.length); }; - writeTerminalDataWithLineTimestamps(term, displayData, afterWrite); + writeTerminalDataWithLineTimestamps(term, preparedDisplayData, afterWrite); }); }; @@ -246,6 +251,7 @@ export const attachSessionToTerminal = ( ctx.sessionRef.current = id; // Clear any stale back-pressure accounting from a prior session on this term. getFlowController(ctx, term).reset(); + resetTerminalSyncBlockFilter(term); resetTerminalLineTimestamps(term); ctx.onSessionAttached?.(id); const sudoAutofill = createSudoPasswordAutofill({ diff --git a/components/terminal/runtime/terminalSyncBlockFilter.ts b/components/terminal/runtime/terminalSyncBlockFilter.ts new file mode 100644 index 000000000..c682160ce --- /dev/null +++ b/components/terminal/runtime/terminalSyncBlockFilter.ts @@ -0,0 +1,25 @@ +import type { Terminal as XTerm } from "@xterm/xterm"; + +import { + createSyncBlockFilterState, + filterSyncBlockClears, + type SyncBlockFilterState, +} from "./filterSyncBlockClears.ts"; + +const syncBlockFilterStates = new WeakMap(); + +export const resetTerminalSyncBlockFilter = (term: XTerm): void => { + syncBlockFilterStates.set(term, createSyncBlockFilterState()); +}; + +const getSyncBlockFilterState = (term: XTerm): SyncBlockFilterState => { + let state = syncBlockFilterStates.get(term); + if (!state) { + state = createSyncBlockFilterState(); + syncBlockFilterStates.set(term, state); + } + return state; +}; + +export const filterTerminalSessionData = (term: XTerm, data: string): string => + filterSyncBlockClears(data, getSyncBlockFilterState(term)); From 7c707bf3b0dc4714a7ff4c8ea592d938a1e52921 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 20:45:56 +0800 Subject: [PATCH 018/228] fix(terminal): hold partial sync markers across PTY chunks Address Codex review: DEC 2026 start/end and clear-screen sequences can be split across arbitrary PTY/IPC chunk boundaries. Keep a pending suffix between calls so the sync-block filter still strips in-block clears. Co-authored-by: Cursor --- .../runtime/filterSyncBlockClears.test.ts | 33 ++++++++++++ .../terminal/runtime/filterSyncBlockClears.ts | 54 ++++++++++++++----- 2 files changed, 75 insertions(+), 12 deletions(-) diff --git a/components/terminal/runtime/filterSyncBlockClears.test.ts b/components/terminal/runtime/filterSyncBlockClears.test.ts index 59e161188..1fc2c1252 100644 --- a/components/terminal/runtime/filterSyncBlockClears.test.ts +++ b/components/terminal/runtime/filterSyncBlockClears.test.ts @@ -56,3 +56,36 @@ test("leaves non-clear redraw sequences inside synchronized-output blocks intact `${SYNC_START}${cursorHome}text${SYNC_END}`, ); }); + +test("handles sync start marker split across chunks", () => { + const state = createSyncBlockFilterState(); + const startPrefix = SYNC_START.slice(0, -1); + const startSuffix = SYNC_START.slice(-1); + + assert.equal(filterSyncBlockClears(startPrefix, state), ""); + assert.equal(state.pending, startPrefix); + assert.equal(state.inSyncBlock, false); + + assert.equal( + filterSyncBlockClears(`${startSuffix}${CLEAR}frame${SYNC_END}`, state), + `${SYNC_START}frame${SYNC_END}`, + ); + assert.equal(state.inSyncBlock, false); + assert.equal(state.pending, ""); +}); + +test("handles clear-screen marker split across chunks inside sync block", () => { + const state = createSyncBlockFilterState(); + const clearPrefix = CLEAR.slice(0, -1); + const clearSuffix = CLEAR.slice(-1); + + assert.equal(filterSyncBlockClears(SYNC_START, state), SYNC_START); + assert.equal(state.inSyncBlock, true); + + assert.equal(filterSyncBlockClears(`${clearPrefix}`, state), ""); + assert.equal(state.pending, clearPrefix); + + assert.equal(filterSyncBlockClears(`${clearSuffix}frame${SYNC_END}`, state), `frame${SYNC_END}`); + assert.equal(state.inSyncBlock, false); + assert.equal(state.pending, ""); +}); diff --git a/components/terminal/runtime/filterSyncBlockClears.ts b/components/terminal/runtime/filterSyncBlockClears.ts index 62be0455a..c05e9e002 100644 --- a/components/terminal/runtime/filterSyncBlockClears.ts +++ b/components/terminal/runtime/filterSyncBlockClears.ts @@ -7,56 +7,86 @@ * part of the atomic update, but xterm.js resets viewportY on every `\x1b[2J`, * which yanks scroll position and makes earlier output appear "eaten". * + * PTY/IPC chunks can split escape sequences at arbitrary byte boundaries, so a + * trailing partial marker is held in `pending` until the next chunk completes it. + * * @see https://github.com/xtermjs/xterm.js/issues/5801 * @see https://github.com/openai/codex/issues/14277 */ export type SyncBlockFilterState = { inSyncBlock: boolean; + /** Trailing bytes that may complete a marker in the next chunk. */ + pending: string; }; const SYNC_START = "\x1b[?2026h"; const SYNC_END = "\x1b[?2026l"; const CLEAR = "\x1b[2J"; -export const filterSyncBlockClears = ( - data: string, - state: SyncBlockFilterState, -): string => { - if (!state.inSyncBlock && !data.includes(SYNC_START)) { - return data; - } +const MARKERS = [SYNC_START, SYNC_END, CLEAR] as const; +const maxMarkerPrefixLength = Math.max(...MARKERS.map((marker) => marker.length)) - 1; + +const splitPendingMarkerSuffix = (input: string): { emit: string; pending: string } => { + const maxLength = Math.min(input.length, maxMarkerPrefixLength); + for (let length = maxLength; length > 0; length -= 1) { + const suffix = input.slice(-length); + if (MARKERS.some((marker) => marker.startsWith(suffix) && marker.length > suffix.length)) { + return { + emit: input.slice(0, -length), + pending: suffix, + }; + } + } + return { emit: input, pending: "" }; +}; + +const scanSyncBlockClears = (input: string, state: SyncBlockFilterState): string => { let result = ""; let index = 0; - while (index < data.length) { - if (data.startsWith(SYNC_START, index)) { + while (index < input.length) { + if (input.startsWith(SYNC_START, index)) { state.inSyncBlock = true; result += SYNC_START; index += SYNC_START.length; continue; } - if (data.startsWith(SYNC_END, index)) { + if (input.startsWith(SYNC_END, index)) { state.inSyncBlock = false; result += SYNC_END; index += SYNC_END.length; continue; } - if (state.inSyncBlock && data.startsWith(CLEAR, index)) { + if (state.inSyncBlock && input.startsWith(CLEAR, index)) { index += CLEAR.length; continue; } - result += data[index]; + result += input[index]; index += 1; } return result; }; +export const filterSyncBlockClears = ( + data: string, + state: SyncBlockFilterState, +): string => { + const { emit, pending } = splitPendingMarkerSuffix(`${state.pending}${data}`); + state.pending = pending; + if (!emit) { + return ""; + } + + return scanSyncBlockClears(emit, state); +}; + export const createSyncBlockFilterState = (): SyncBlockFilterState => ({ inSyncBlock: false, + pending: "", }); From c1ebedcc1f002148f0bdd03bc62b59c20cee661d Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 21:12:01 +0800 Subject: [PATCH 019/228] test(terminal): cover split sync-end and trailing ESC chunk edges Add regression tests for SYNC_END marker splits and for releasing a held trailing ESC when the following chunk is ordinary terminal text. Co-authored-by: Cursor --- .../runtime/filterSyncBlockClears.test.ts | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/components/terminal/runtime/filterSyncBlockClears.test.ts b/components/terminal/runtime/filterSyncBlockClears.test.ts index 1fc2c1252..4e9f9615f 100644 --- a/components/terminal/runtime/filterSyncBlockClears.test.ts +++ b/components/terminal/runtime/filterSyncBlockClears.test.ts @@ -89,3 +89,27 @@ test("handles clear-screen marker split across chunks inside sync block", () => assert.equal(state.inSyncBlock, false); assert.equal(state.pending, ""); }); + +test("handles sync end marker split across chunks", () => { + const state = createSyncBlockFilterState(); + const endPrefix = SYNC_END.slice(0, -1); + const endSuffix = SYNC_END.slice(-1); + + assert.equal(filterSyncBlockClears(`${SYNC_START}frame${endPrefix}`, state), `${SYNC_START}frame`); + assert.equal(state.inSyncBlock, true); + assert.equal(state.pending, endPrefix); + + assert.equal(filterSyncBlockClears(endSuffix, state), SYNC_END); + assert.equal(state.inSyncBlock, false); + assert.equal(state.pending, ""); +}); + +test("releases a trailing ESC when the next chunk is ordinary text", () => { + const state = createSyncBlockFilterState(); + + assert.equal(filterSyncBlockClears("prompt\x1b", state), "prompt"); + assert.equal(state.pending, "\x1b"); + + assert.equal(filterSyncBlockClears("more output", state), "\x1bmore output"); + assert.equal(state.pending, ""); +}); From d9ed716b01f784c6622b4ae8eb53423fe79839a3 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 21:17:23 +0800 Subject: [PATCH 020/228] fix(terminal): expire abandoned DEC 2026 sync blocks after 1s Mirror xterm.js synchronized-output safety timeout so an unclosed sync block cannot keep stripping later clear-screen sequences in the session. Co-authored-by: Cursor --- .../runtime/terminalSyncBlockFilter.test.ts | 49 +++++++++++++++++++ .../runtime/terminalSyncBlockFilter.ts | 49 ++++++++++++++++++- 2 files changed, 96 insertions(+), 2 deletions(-) create mode 100644 components/terminal/runtime/terminalSyncBlockFilter.test.ts diff --git a/components/terminal/runtime/terminalSyncBlockFilter.test.ts b/components/terminal/runtime/terminalSyncBlockFilter.test.ts new file mode 100644 index 000000000..f2f55abb4 --- /dev/null +++ b/components/terminal/runtime/terminalSyncBlockFilter.test.ts @@ -0,0 +1,49 @@ +import assert from "node:assert/strict"; +import { mock, test } from "node:test"; + +import type { Terminal as XTerm } from "@xterm/xterm"; + +import { + filterTerminalSessionData, + resetTerminalSyncBlockFilter, + SYNC_BLOCK_TIMEOUT_MS, +} from "./terminalSyncBlockFilter.ts"; + +const SYNC_START = "\x1b[?2026h"; +const CLEAR = "\x1b[2J"; + +const term = {} as XTerm; + +test("abandoned sync blocks stop stripping clear-screen after timeout", () => { + mock.timers.enable({ apis: ["setTimeout"] }); + + try { + resetTerminalSyncBlockFilter(term); + assert.equal(filterTerminalSessionData(term, SYNC_START), SYNC_START); + assert.equal(filterTerminalSessionData(term, CLEAR), ""); + + mock.timers.tick(SYNC_BLOCK_TIMEOUT_MS); + assert.equal(filterTerminalSessionData(term, CLEAR), CLEAR); + } finally { + resetTerminalSyncBlockFilter(term); + mock.timers.reset(); + } +}); + +test("completed sync blocks clear the timeout without waiting", () => { + mock.timers.enable({ apis: ["setTimeout"] }); + + try { + resetTerminalSyncBlockFilter(term); + assert.equal( + filterTerminalSessionData(term, `${SYNC_START}frame\x1b[?2026l`), + `${SYNC_START}frame\x1b[?2026l`, + ); + + mock.timers.tick(SYNC_BLOCK_TIMEOUT_MS); + assert.equal(filterTerminalSessionData(term, CLEAR), CLEAR); + } finally { + resetTerminalSyncBlockFilter(term); + mock.timers.reset(); + } +}); diff --git a/components/terminal/runtime/terminalSyncBlockFilter.ts b/components/terminal/runtime/terminalSyncBlockFilter.ts index c682160ce..cbe58acc9 100644 --- a/components/terminal/runtime/terminalSyncBlockFilter.ts +++ b/components/terminal/runtime/terminalSyncBlockFilter.ts @@ -6,9 +6,46 @@ import { type SyncBlockFilterState, } from "./filterSyncBlockClears.ts"; +/** Matches @xterm/xterm RenderService SYNCHRONIZED_OUTPUT_TIMEOUT_MS. */ +export const SYNC_BLOCK_TIMEOUT_MS = 1000; + const syncBlockFilterStates = new WeakMap(); +const syncBlockTimers = new WeakMap>(); + +const clearSyncBlockTimer = (term: XTerm): void => { + const timer = syncBlockTimers.get(term); + if (timer === undefined) { + return; + } + clearTimeout(timer); + syncBlockTimers.delete(term); +}; + +const abandonSyncBlock = (term: XTerm, state: SyncBlockFilterState): void => { + state.inSyncBlock = false; + state.pending = ""; + clearSyncBlockTimer(term); +}; + +const scheduleSyncBlockTimeout = (term: XTerm, state: SyncBlockFilterState): void => { + clearSyncBlockTimer(term); + if (!state.inSyncBlock) { + return; + } + syncBlockTimers.set( + term, + setTimeout(() => { + syncBlockTimers.delete(term); + abandonSyncBlock(term, state); + }, SYNC_BLOCK_TIMEOUT_MS), + ); +}; export const resetTerminalSyncBlockFilter = (term: XTerm): void => { + const state = syncBlockFilterStates.get(term); + if (state) { + abandonSyncBlock(term, state); + } syncBlockFilterStates.set(term, createSyncBlockFilterState()); }; @@ -21,5 +58,13 @@ const getSyncBlockFilterState = (term: XTerm): SyncBlockFilterState => { return state; }; -export const filterTerminalSessionData = (term: XTerm, data: string): string => - filterSyncBlockClears(data, getSyncBlockFilterState(term)); +export const filterTerminalSessionData = (term: XTerm, data: string): string => { + const state = getSyncBlockFilterState(term); + const filtered = filterSyncBlockClears(data, state); + if (state.inSyncBlock) { + scheduleSyncBlockTimeout(term, state); + } else { + clearSyncBlockTimer(term); + } + return filtered; +}; From 51f5fd908886323914ba9232dbd9825e69349dab Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 21:20:39 +0800 Subject: [PATCH 021/228] fix(terminal): arm sync-block timeout once and keep pending bytes Only start the DEC 2026 abandonment timer when entering a block, and preserve trailing partial marker bytes when the timeout fires. Co-authored-by: Cursor --- .../runtime/terminalSyncBlockFilter.test.ts | 36 ++++++++++++++++ .../runtime/terminalSyncBlockFilter.ts | 43 +++++++++---------- 2 files changed, 57 insertions(+), 22 deletions(-) diff --git a/components/terminal/runtime/terminalSyncBlockFilter.test.ts b/components/terminal/runtime/terminalSyncBlockFilter.test.ts index f2f55abb4..d6e80940b 100644 --- a/components/terminal/runtime/terminalSyncBlockFilter.test.ts +++ b/components/terminal/runtime/terminalSyncBlockFilter.test.ts @@ -47,3 +47,39 @@ test("completed sync blocks clear the timeout without waiting", () => { mock.timers.reset(); } }); + +test("sync block timeout is armed once even when output keeps streaming", () => { + mock.timers.enable({ apis: ["setTimeout"] }); + + try { + resetTerminalSyncBlockFilter(term); + assert.equal(filterTerminalSessionData(term, SYNC_START), SYNC_START); + assert.equal(filterTerminalSessionData(term, "frame-1"), "frame-1"); + assert.equal(filterTerminalSessionData(term, "frame-2"), "frame-2"); + + mock.timers.tick(SYNC_BLOCK_TIMEOUT_MS - 1); + assert.equal(filterTerminalSessionData(term, CLEAR), ""); + + mock.timers.tick(1); + assert.equal(filterTerminalSessionData(term, CLEAR), CLEAR); + } finally { + resetTerminalSyncBlockFilter(term); + mock.timers.reset(); + } +}); + +test("sync block timeout preserves pending partial marker bytes", () => { + mock.timers.enable({ apis: ["setTimeout"] }); + + try { + resetTerminalSyncBlockFilter(term); + assert.equal(filterTerminalSessionData(term, SYNC_START), SYNC_START); + assert.equal(filterTerminalSessionData(term, "color\x1b"), "color"); + + mock.timers.tick(SYNC_BLOCK_TIMEOUT_MS); + assert.equal(filterTerminalSessionData(term, "[31mtext"), "\x1b[31mtext"); + } finally { + resetTerminalSyncBlockFilter(term); + mock.timers.reset(); + } +}); diff --git a/components/terminal/runtime/terminalSyncBlockFilter.ts b/components/terminal/runtime/terminalSyncBlockFilter.ts index cbe58acc9..9e341d4a1 100644 --- a/components/terminal/runtime/terminalSyncBlockFilter.ts +++ b/components/terminal/runtime/terminalSyncBlockFilter.ts @@ -21,31 +21,13 @@ const clearSyncBlockTimer = (term: XTerm): void => { syncBlockTimers.delete(term); }; -const abandonSyncBlock = (term: XTerm, state: SyncBlockFilterState): void => { +const expireSyncBlock = (term: XTerm, state: SyncBlockFilterState): void => { state.inSyncBlock = false; - state.pending = ""; clearSyncBlockTimer(term); }; -const scheduleSyncBlockTimeout = (term: XTerm, state: SyncBlockFilterState): void => { - clearSyncBlockTimer(term); - if (!state.inSyncBlock) { - return; - } - syncBlockTimers.set( - term, - setTimeout(() => { - syncBlockTimers.delete(term); - abandonSyncBlock(term, state); - }, SYNC_BLOCK_TIMEOUT_MS), - ); -}; - export const resetTerminalSyncBlockFilter = (term: XTerm): void => { - const state = syncBlockFilterStates.get(term); - if (state) { - abandonSyncBlock(term, state); - } + clearSyncBlockTimer(term); syncBlockFilterStates.set(term, createSyncBlockFilterState()); }; @@ -58,13 +40,30 @@ const getSyncBlockFilterState = (term: XTerm): SyncBlockFilterState => { return state; }; +const scheduleSyncBlockTimeout = (term: XTerm, state: SyncBlockFilterState): void => { + if (syncBlockTimers.has(term) || !state.inSyncBlock) { + return; + } + + syncBlockTimers.set( + term, + setTimeout(() => { + syncBlockTimers.delete(term); + expireSyncBlock(term, state); + }, SYNC_BLOCK_TIMEOUT_MS), + ); +}; + export const filterTerminalSessionData = (term: XTerm, data: string): string => { const state = getSyncBlockFilterState(term); + const wasInSyncBlock = state.inSyncBlock; const filtered = filterSyncBlockClears(data, state); - if (state.inSyncBlock) { + + if (state.inSyncBlock && !wasInSyncBlock) { scheduleSyncBlockTimeout(term, state); - } else { + } else if (!state.inSyncBlock) { clearSyncBlockTimer(term); } + return filtered; }; From 825bd722d1077ff614dfcba594af1fa2c5736ccb Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 21:27:54 +0800 Subject: [PATCH 022/228] fix(terminal): only strip sync-block clears while viewport is scrolled up Preserve `\x1b[2J` inside DEC 2026 blocks for alternate-screen TUIs and for normal-buffer redraws at the bottom, while still preventing xterm.js viewport jumps when the user is reading scrollback history. Co-authored-by: Cursor --- .../runtime/filterSyncBlockClears.test.ts | 34 ++++++++++++++ .../terminal/runtime/filterSyncBlockClears.ts | 43 +++++++++++++++-- .../runtime/terminalSyncBlockFilter.test.ts | 46 ++++++++++++++++++- .../runtime/terminalSyncBlockFilter.ts | 5 +- 4 files changed, 121 insertions(+), 7 deletions(-) diff --git a/components/terminal/runtime/filterSyncBlockClears.test.ts b/components/terminal/runtime/filterSyncBlockClears.test.ts index 4e9f9615f..ad0f42533 100644 --- a/components/terminal/runtime/filterSyncBlockClears.test.ts +++ b/components/terminal/runtime/filterSyncBlockClears.test.ts @@ -4,6 +4,7 @@ import test from "node:test"; import { createSyncBlockFilterState, filterSyncBlockClears, + isTerminalViewportScrolledUp, } from "./filterSyncBlockClears.ts"; const SYNC_START = "\x1b[?2026h"; @@ -113,3 +114,36 @@ test("releases a trailing ESC when the next chunk is ordinary text", () => { assert.equal(filterSyncBlockClears("more output", state), "\x1bmore output"); assert.equal(state.pending, ""); }); + +test("keeps clear-screen inside sync blocks when stripping is disabled", () => { + const state = createSyncBlockFilterState(); + const input = `${SYNC_START}${CLEAR}frame${SYNC_END}`; + + assert.equal( + filterSyncBlockClears(input, state, { stripClearsInSyncBlock: false }), + input, + ); +}); + +test("isTerminalViewportScrolledUp is false on alternate-screen buffers", () => { + const term = { + rows: 24, + buffer: { active: { type: "alternate", baseY: 0, length: 24 } }, + } as never; + + assert.equal(isTerminalViewportScrolledUp(term), false); +}); + +test("isTerminalViewportScrolledUp detects normal-buffer scrollback", () => { + const atBottom = { + rows: 24, + buffer: { active: { type: "normal", baseY: 76, length: 100 } }, + } as never; + const scrolledUp = { + rows: 24, + buffer: { active: { type: "normal", baseY: 10, length: 100 } }, + } as never; + + assert.equal(isTerminalViewportScrolledUp(atBottom), false); + assert.equal(isTerminalViewportScrolledUp(scrolledUp), true); +}); diff --git a/components/terminal/runtime/filterSyncBlockClears.ts b/components/terminal/runtime/filterSyncBlockClears.ts index c05e9e002..59c99e5f3 100644 --- a/components/terminal/runtime/filterSyncBlockClears.ts +++ b/components/terminal/runtime/filterSyncBlockClears.ts @@ -1,11 +1,18 @@ +import type { Terminal as XTerm } from "@xterm/xterm"; + /** * Strip `\x1b[2J` (ED — erase display) inside DEC Mode 2026 synchronized-output * blocks before data reaches xterm.js. * * Coding CLIs such as Codex and Claude Code wrap full-screen redraws in * `\x1b[?2026h` … `\x1b[?2026l`. Native terminals treat the enclosed clear as - * part of the atomic update, but xterm.js resets viewportY on every `\x1b[2J`, - * which yanks scroll position and makes earlier output appear "eaten". + * part of the atomic update, but xterm.js resets viewportY on every `\x1b[2J` + * when the user has scrolled up in the normal buffer, which yanks scroll + * position and makes earlier output appear "eaten". + * + * Alternate-screen TUIs still need the clear to remove stale cells from shorter + * redraw frames, so callers should only enable stripping while the viewport is + * scrolled up in the normal buffer. * * PTY/IPC chunks can split escape sequences at arbitrary byte boundaries, so a * trailing partial marker is held in `pending` until the next chunk completes it. @@ -20,6 +27,10 @@ export type SyncBlockFilterState = { pending: string; }; +export type SyncBlockClearFilterOptions = { + stripClearsInSyncBlock: boolean; +}; + const SYNC_START = "\x1b[?2026h"; const SYNC_END = "\x1b[?2026l"; const CLEAR = "\x1b[2J"; @@ -42,7 +53,11 @@ const splitPendingMarkerSuffix = (input: string): { emit: string; pending: strin return { emit: input, pending: "" }; }; -const scanSyncBlockClears = (input: string, state: SyncBlockFilterState): string => { +const scanSyncBlockClears = ( + input: string, + state: SyncBlockFilterState, + stripClearsInSyncBlock: boolean, +): string => { let result = ""; let index = 0; @@ -61,7 +76,11 @@ const scanSyncBlockClears = (input: string, state: SyncBlockFilterState): string continue; } - if (state.inSyncBlock && input.startsWith(CLEAR, index)) { + if ( + stripClearsInSyncBlock + && state.inSyncBlock + && input.startsWith(CLEAR, index) + ) { index += CLEAR.length; continue; } @@ -76,6 +95,7 @@ const scanSyncBlockClears = (input: string, state: SyncBlockFilterState): string export const filterSyncBlockClears = ( data: string, state: SyncBlockFilterState, + options: SyncBlockClearFilterOptions = { stripClearsInSyncBlock: true }, ): string => { const { emit, pending } = splitPendingMarkerSuffix(`${state.pending}${data}`); state.pending = pending; @@ -83,10 +103,23 @@ export const filterSyncBlockClears = ( return ""; } - return scanSyncBlockClears(emit, state); + return scanSyncBlockClears(emit, state, options.stripClearsInSyncBlock); }; export const createSyncBlockFilterState = (): SyncBlockFilterState => ({ inSyncBlock: false, pending: "", }); + +export const isTerminalViewportScrolledUp = (term: XTerm): boolean => { + const buffer = term.buffer.active; + if (buffer.type === "alternate") { + return false; + } + + const maxBaseY = Math.max(0, buffer.length - term.rows); + return buffer.baseY < maxBaseY; +}; + +export const shouldStripSyncBlockClears = (term: XTerm): boolean => + isTerminalViewportScrolledUp(term); diff --git a/components/terminal/runtime/terminalSyncBlockFilter.test.ts b/components/terminal/runtime/terminalSyncBlockFilter.test.ts index d6e80940b..8027673aa 100644 --- a/components/terminal/runtime/terminalSyncBlockFilter.test.ts +++ b/components/terminal/runtime/terminalSyncBlockFilter.test.ts @@ -12,10 +12,31 @@ import { const SYNC_START = "\x1b[?2026h"; const CLEAR = "\x1b[2J"; -const term = {} as XTerm; +const createMockTerm = ({ + type = "normal", + baseY = 76, + length = 100, + rows = 24, +}: { + type?: "normal" | "alternate"; + baseY?: number; + length?: number; + rows?: number; +} = {}): XTerm => ({ + rows, + buffer: { + active: { + type, + baseY, + length, + viewportY: baseY, + }, + }, +} as unknown as XTerm); test("abandoned sync blocks stop stripping clear-screen after timeout", () => { mock.timers.enable({ apis: ["setTimeout"] }); + const term = createMockTerm({ baseY: 10 }); try { resetTerminalSyncBlockFilter(term); @@ -32,6 +53,7 @@ test("abandoned sync blocks stop stripping clear-screen after timeout", () => { test("completed sync blocks clear the timeout without waiting", () => { mock.timers.enable({ apis: ["setTimeout"] }); + const term = createMockTerm({ baseY: 10 }); try { resetTerminalSyncBlockFilter(term); @@ -50,6 +72,7 @@ test("completed sync blocks clear the timeout without waiting", () => { test("sync block timeout is armed once even when output keeps streaming", () => { mock.timers.enable({ apis: ["setTimeout"] }); + const term = createMockTerm({ baseY: 10 }); try { resetTerminalSyncBlockFilter(term); @@ -70,6 +93,7 @@ test("sync block timeout is armed once even when output keeps streaming", () => test("sync block timeout preserves pending partial marker bytes", () => { mock.timers.enable({ apis: ["setTimeout"] }); + const term = createMockTerm({ baseY: 10 }); try { resetTerminalSyncBlockFilter(term); @@ -83,3 +107,23 @@ test("sync block timeout preserves pending partial marker bytes", () => { mock.timers.reset(); } }); + +test("preserves clear-screen redraws on alternate-screen buffers", () => { + const term = createMockTerm({ type: "alternate", baseY: 0, length: 24 }); + resetTerminalSyncBlockFilter(term); + + assert.equal( + filterTerminalSessionData(term, `${SYNC_START}${CLEAR}frame\x1b[?2026l`), + `${SYNC_START}${CLEAR}frame\x1b[?2026l`, + ); +}); + +test("preserves clear-screen redraws when the viewport is at the bottom", () => { + const term = createMockTerm({ baseY: 76, length: 100 }); + resetTerminalSyncBlockFilter(term); + + assert.equal( + filterTerminalSessionData(term, `${SYNC_START}${CLEAR}frame\x1b[?2026l`), + `${SYNC_START}${CLEAR}frame\x1b[?2026l`, + ); +}); diff --git a/components/terminal/runtime/terminalSyncBlockFilter.ts b/components/terminal/runtime/terminalSyncBlockFilter.ts index 9e341d4a1..097f8f0d2 100644 --- a/components/terminal/runtime/terminalSyncBlockFilter.ts +++ b/components/terminal/runtime/terminalSyncBlockFilter.ts @@ -3,6 +3,7 @@ import type { Terminal as XTerm } from "@xterm/xterm"; import { createSyncBlockFilterState, filterSyncBlockClears, + shouldStripSyncBlockClears, type SyncBlockFilterState, } from "./filterSyncBlockClears.ts"; @@ -57,7 +58,9 @@ const scheduleSyncBlockTimeout = (term: XTerm, state: SyncBlockFilterState): voi export const filterTerminalSessionData = (term: XTerm, data: string): string => { const state = getSyncBlockFilterState(term); const wasInSyncBlock = state.inSyncBlock; - const filtered = filterSyncBlockClears(data, state); + const filtered = filterSyncBlockClears(data, state, { + stripClearsInSyncBlock: shouldStripSyncBlockClears(term), + }); if (state.inSyncBlock && !wasInSyncBlock) { scheduleSyncBlockTimeout(term, state); From 07e837b21c74a610c3ed855715cb11e62f3ea803 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 21:31:46 +0800 Subject: [PATCH 023/228] fix(terminal): detect scrollback via viewportY and restart block timers Use xterm viewportY/baseY to decide when sync-block clears may be stripped, and re-arm the abandonment timeout whenever a new DEC 2026 block starts. Co-authored-by: Cursor --- .../runtime/filterSyncBlockClears.test.ts | 4 +- .../terminal/runtime/filterSyncBlockClears.ts | 38 ++++++++++++------- .../runtime/terminalSyncBlockFilter.test.ts | 38 +++++++++++++++---- .../runtime/terminalSyncBlockFilter.ts | 12 +++--- 4 files changed, 64 insertions(+), 28 deletions(-) diff --git a/components/terminal/runtime/filterSyncBlockClears.test.ts b/components/terminal/runtime/filterSyncBlockClears.test.ts index ad0f42533..322a7237e 100644 --- a/components/terminal/runtime/filterSyncBlockClears.test.ts +++ b/components/terminal/runtime/filterSyncBlockClears.test.ts @@ -137,11 +137,11 @@ test("isTerminalViewportScrolledUp is false on alternate-screen buffers", () => test("isTerminalViewportScrolledUp detects normal-buffer scrollback", () => { const atBottom = { rows: 24, - buffer: { active: { type: "normal", baseY: 76, length: 100 } }, + buffer: { active: { type: "normal", viewportY: 76, baseY: 76, length: 100 } }, } as never; const scrolledUp = { rows: 24, - buffer: { active: { type: "normal", baseY: 10, length: 100 } }, + buffer: { active: { type: "normal", viewportY: 10, baseY: 76, length: 100 } }, } as never; assert.equal(isTerminalViewportScrolledUp(atBottom), false); diff --git a/components/terminal/runtime/filterSyncBlockClears.ts b/components/terminal/runtime/filterSyncBlockClears.ts index 59c99e5f3..8ba942d6f 100644 --- a/components/terminal/runtime/filterSyncBlockClears.ts +++ b/components/terminal/runtime/filterSyncBlockClears.ts @@ -31,6 +31,11 @@ export type SyncBlockClearFilterOptions = { stripClearsInSyncBlock: boolean; }; +export type SyncBlockClearFilterResult = { + output: string; + startedSyncBlock: boolean; +}; + const SYNC_START = "\x1b[?2026h"; const SYNC_END = "\x1b[?2026l"; const CLEAR = "\x1b[2J"; @@ -57,13 +62,15 @@ const scanSyncBlockClears = ( input: string, state: SyncBlockFilterState, stripClearsInSyncBlock: boolean, -): string => { +): SyncBlockClearFilterResult => { let result = ""; + let startedSyncBlock = false; let index = 0; while (index < input.length) { if (input.startsWith(SYNC_START, index)) { state.inSyncBlock = true; + startedSyncBlock = true; result += SYNC_START; index += SYNC_START.length; continue; @@ -89,22 +96,28 @@ const scanSyncBlockClears = ( index += 1; } - return result; + return { output: result, startedSyncBlock }; +}; + +export const filterSyncBlockClearsWithMeta = ( + data: string, + state: SyncBlockFilterState, + options: SyncBlockClearFilterOptions = { stripClearsInSyncBlock: true }, +): SyncBlockClearFilterResult => { + const { emit, pending } = splitPendingMarkerSuffix(`${state.pending}${data}`); + state.pending = pending; + if (!emit) { + return { output: "", startedSyncBlock: false }; + } + + return scanSyncBlockClears(emit, state, options.stripClearsInSyncBlock); }; export const filterSyncBlockClears = ( data: string, state: SyncBlockFilterState, options: SyncBlockClearFilterOptions = { stripClearsInSyncBlock: true }, -): string => { - const { emit, pending } = splitPendingMarkerSuffix(`${state.pending}${data}`); - state.pending = pending; - if (!emit) { - return ""; - } - - return scanSyncBlockClears(emit, state, options.stripClearsInSyncBlock); -}; +): string => filterSyncBlockClearsWithMeta(data, state, options).output; export const createSyncBlockFilterState = (): SyncBlockFilterState => ({ inSyncBlock: false, @@ -117,8 +130,7 @@ export const isTerminalViewportScrolledUp = (term: XTerm): boolean => { return false; } - const maxBaseY = Math.max(0, buffer.length - term.rows); - return buffer.baseY < maxBaseY; + return buffer.viewportY < buffer.baseY; }; export const shouldStripSyncBlockClears = (term: XTerm): boolean => diff --git a/components/terminal/runtime/terminalSyncBlockFilter.test.ts b/components/terminal/runtime/terminalSyncBlockFilter.test.ts index 8027673aa..3f084afd6 100644 --- a/components/terminal/runtime/terminalSyncBlockFilter.test.ts +++ b/components/terminal/runtime/terminalSyncBlockFilter.test.ts @@ -14,11 +14,13 @@ const CLEAR = "\x1b[2J"; const createMockTerm = ({ type = "normal", + viewportY = 10, baseY = 76, length = 100, rows = 24, }: { type?: "normal" | "alternate"; + viewportY?: number; baseY?: number; length?: number; rows?: number; @@ -29,14 +31,14 @@ const createMockTerm = ({ type, baseY, length, - viewportY: baseY, + viewportY, }, }, } as unknown as XTerm); test("abandoned sync blocks stop stripping clear-screen after timeout", () => { mock.timers.enable({ apis: ["setTimeout"] }); - const term = createMockTerm({ baseY: 10 }); + const term = createMockTerm({ viewportY: 10, baseY: 76 }); try { resetTerminalSyncBlockFilter(term); @@ -53,7 +55,7 @@ test("abandoned sync blocks stop stripping clear-screen after timeout", () => { test("completed sync blocks clear the timeout without waiting", () => { mock.timers.enable({ apis: ["setTimeout"] }); - const term = createMockTerm({ baseY: 10 }); + const term = createMockTerm({ viewportY: 10, baseY: 76 }); try { resetTerminalSyncBlockFilter(term); @@ -72,7 +74,7 @@ test("completed sync blocks clear the timeout without waiting", () => { test("sync block timeout is armed once even when output keeps streaming", () => { mock.timers.enable({ apis: ["setTimeout"] }); - const term = createMockTerm({ baseY: 10 }); + const term = createMockTerm({ viewportY: 10, baseY: 76 }); try { resetTerminalSyncBlockFilter(term); @@ -93,7 +95,7 @@ test("sync block timeout is armed once even when output keeps streaming", () => test("sync block timeout preserves pending partial marker bytes", () => { mock.timers.enable({ apis: ["setTimeout"] }); - const term = createMockTerm({ baseY: 10 }); + const term = createMockTerm({ viewportY: 10, baseY: 76 }); try { resetTerminalSyncBlockFilter(term); @@ -109,7 +111,7 @@ test("sync block timeout preserves pending partial marker bytes", () => { }); test("preserves clear-screen redraws on alternate-screen buffers", () => { - const term = createMockTerm({ type: "alternate", baseY: 0, length: 24 }); + const term = createMockTerm({ type: "alternate", viewportY: 0, baseY: 0, length: 24 }); resetTerminalSyncBlockFilter(term); assert.equal( @@ -119,7 +121,7 @@ test("preserves clear-screen redraws on alternate-screen buffers", () => { }); test("preserves clear-screen redraws when the viewport is at the bottom", () => { - const term = createMockTerm({ baseY: 76, length: 100 }); + const term = createMockTerm({ viewportY: 76, baseY: 76, length: 100 }); resetTerminalSyncBlockFilter(term); assert.equal( @@ -127,3 +129,25 @@ test("preserves clear-screen redraws when the viewport is at the bottom", () => `${SYNC_START}${CLEAR}frame\x1b[?2026l`, ); }); + +test("restarts sync timeout when back-to-back blocks arrive in one chunk", () => { + mock.timers.enable({ apis: ["setTimeout"] }); + const term = createMockTerm({ viewportY: 10, baseY: 76 }); + + try { + resetTerminalSyncBlockFilter(term); + assert.equal(filterTerminalSessionData(term, SYNC_START), SYNC_START); + + mock.timers.tick(SYNC_BLOCK_TIMEOUT_MS - 1); + assert.equal( + filterTerminalSessionData(term, `\x1b[?2026l${SYNC_START}${CLEAR}`), + `\x1b[?2026l${SYNC_START}`, + ); + + mock.timers.tick(1); + assert.equal(filterTerminalSessionData(term, CLEAR), ""); + } finally { + resetTerminalSyncBlockFilter(term); + mock.timers.reset(); + } +}); diff --git a/components/terminal/runtime/terminalSyncBlockFilter.ts b/components/terminal/runtime/terminalSyncBlockFilter.ts index 097f8f0d2..73f8f5ecd 100644 --- a/components/terminal/runtime/terminalSyncBlockFilter.ts +++ b/components/terminal/runtime/terminalSyncBlockFilter.ts @@ -2,7 +2,7 @@ import type { Terminal as XTerm } from "@xterm/xterm"; import { createSyncBlockFilterState, - filterSyncBlockClears, + filterSyncBlockClearsWithMeta, shouldStripSyncBlockClears, type SyncBlockFilterState, } from "./filterSyncBlockClears.ts"; @@ -42,7 +42,7 @@ const getSyncBlockFilterState = (term: XTerm): SyncBlockFilterState => { }; const scheduleSyncBlockTimeout = (term: XTerm, state: SyncBlockFilterState): void => { - if (syncBlockTimers.has(term) || !state.inSyncBlock) { + if (!state.inSyncBlock) { return; } @@ -57,16 +57,16 @@ const scheduleSyncBlockTimeout = (term: XTerm, state: SyncBlockFilterState): voi export const filterTerminalSessionData = (term: XTerm, data: string): string => { const state = getSyncBlockFilterState(term); - const wasInSyncBlock = state.inSyncBlock; - const filtered = filterSyncBlockClears(data, state, { + const { output, startedSyncBlock } = filterSyncBlockClearsWithMeta(data, state, { stripClearsInSyncBlock: shouldStripSyncBlockClears(term), }); - if (state.inSyncBlock && !wasInSyncBlock) { + if (startedSyncBlock) { + clearSyncBlockTimer(term); scheduleSyncBlockTimeout(term, state); } else if (!state.inSyncBlock) { clearSyncBlockTimer(term); } - return filtered; + return output; }; From 12d7d6c73019d8e13980a6263d3bd879e1149467 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 21:35:17 +0800 Subject: [PATCH 024/228] fix(terminal): guard sync-block scroll detection when buffer is missing Minimal terminal stubs used in session-starter tests do not expose xterm buffer state; treat that as "not scrolled up" instead of throwing. Co-authored-by: Cursor --- components/terminal/runtime/filterSyncBlockClears.test.ts | 4 ++++ components/terminal/runtime/filterSyncBlockClears.ts | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/components/terminal/runtime/filterSyncBlockClears.test.ts b/components/terminal/runtime/filterSyncBlockClears.test.ts index 322a7237e..94b77c61b 100644 --- a/components/terminal/runtime/filterSyncBlockClears.test.ts +++ b/components/terminal/runtime/filterSyncBlockClears.test.ts @@ -125,6 +125,10 @@ test("keeps clear-screen inside sync blocks when stripping is disabled", () => { ); }); +test("isTerminalViewportScrolledUp is false when buffer state is unavailable", () => { + assert.equal(isTerminalViewportScrolledUp({} as never), false); +}); + test("isTerminalViewportScrolledUp is false on alternate-screen buffers", () => { const term = { rows: 24, diff --git a/components/terminal/runtime/filterSyncBlockClears.ts b/components/terminal/runtime/filterSyncBlockClears.ts index 8ba942d6f..a710193e0 100644 --- a/components/terminal/runtime/filterSyncBlockClears.ts +++ b/components/terminal/runtime/filterSyncBlockClears.ts @@ -125,8 +125,8 @@ export const createSyncBlockFilterState = (): SyncBlockFilterState => ({ }); export const isTerminalViewportScrolledUp = (term: XTerm): boolean => { - const buffer = term.buffer.active; - if (buffer.type === "alternate") { + const buffer = term.buffer?.active; + if (!buffer || buffer.type === "alternate") { return false; } From 20b613d1bbb3f77fbd687400f73cf0df4ec1ccdc Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 21:39:30 +0800 Subject: [PATCH 025/228] fix(terminal): track alternate-screen transitions in sync-block filter Parse alternate-screen enter/leave sequences in-band so bundled PTY chunks preserve `\x1b[2J` redraws before xterm applies buffer switches. Co-authored-by: Cursor --- .../runtime/filterSyncBlockClears.test.ts | 126 +++++++++++------- .../terminal/runtime/filterSyncBlockClears.ts | 74 +++++++--- .../runtime/terminalSyncBlockFilter.ts | 9 +- 3 files changed, 140 insertions(+), 69 deletions(-) diff --git a/components/terminal/runtime/filterSyncBlockClears.test.ts b/components/terminal/runtime/filterSyncBlockClears.test.ts index 94b77c61b..5302c19ec 100644 --- a/components/terminal/runtime/filterSyncBlockClears.test.ts +++ b/components/terminal/runtime/filterSyncBlockClears.test.ts @@ -1,6 +1,8 @@ import assert from "node:assert/strict"; import test from "node:test"; +import type { Terminal as XTerm } from "@xterm/xterm"; + import { createSyncBlockFilterState, filterSyncBlockClears, @@ -10,65 +12,96 @@ import { const SYNC_START = "\x1b[?2026h"; const SYNC_END = "\x1b[?2026l"; const CLEAR = "\x1b[2J"; +const ALT_SCREEN_ENTER = "\x1b[?1049h"; + +const createMockTerm = ({ + type = "normal", + viewportY = 10, + baseY = 76, + length = 100, + rows = 24, +}: { + type?: "normal" | "alternate"; + viewportY?: number; + baseY?: number; + length?: number; + rows?: number; +} = {}): XTerm => ({ + rows, + buffer: { + active: { + type, + baseY, + length, + viewportY, + }, + }, +} as unknown as XTerm); + +const scrolledUpTerm = createMockTerm(); +const bottomTerm = createMockTerm({ viewportY: 76, baseY: 76 }); test("passes through data with no synchronized-output sequences", () => { - const state = createSyncBlockFilterState(); + const state = createSyncBlockFilterState(scrolledUpTerm); const input = "hello\r\n\x1b[2Jworld\r\n"; - assert.equal(filterSyncBlockClears(input, state), input); + assert.equal(filterSyncBlockClears(input, state, scrolledUpTerm), input); assert.equal(state.inSyncBlock, false); }); test("strips clear-screen inside a synchronized-output block", () => { - const state = createSyncBlockFilterState(); + const state = createSyncBlockFilterState(scrolledUpTerm); const input = `${SYNC_START}${CLEAR}frame${SYNC_END}`; - assert.equal(filterSyncBlockClears(input, state), `${SYNC_START}frame${SYNC_END}`); + assert.equal(filterSyncBlockClears(input, state, scrolledUpTerm), `${SYNC_START}frame${SYNC_END}`); assert.equal(state.inSyncBlock, false); }); test("does not strip clear-screen outside synchronized-output blocks", () => { - const state = createSyncBlockFilterState(); + const state = createSyncBlockFilterState(scrolledUpTerm); - assert.equal(filterSyncBlockClears(CLEAR, state), CLEAR); + assert.equal(filterSyncBlockClears(CLEAR, state, scrolledUpTerm), CLEAR); assert.equal(state.inSyncBlock, false); }); test("tracks synchronized-output state across chunks", () => { - const state = createSyncBlockFilterState(); + const state = createSyncBlockFilterState(scrolledUpTerm); - assert.equal(filterSyncBlockClears(SYNC_START, state), SYNC_START); + assert.equal(filterSyncBlockClears(SYNC_START, state, scrolledUpTerm), SYNC_START); assert.equal(state.inSyncBlock, true); - assert.equal(filterSyncBlockClears(`${CLEAR}partial`, state), "partial"); + assert.equal(filterSyncBlockClears(`${CLEAR}partial`, state, scrolledUpTerm), "partial"); assert.equal(state.inSyncBlock, true); - assert.equal(filterSyncBlockClears(`${CLEAR}done${SYNC_END}`, state), `done${SYNC_END}`); + assert.equal( + filterSyncBlockClears(`${CLEAR}done${SYNC_END}`, state, scrolledUpTerm), + `done${SYNC_END}`, + ); assert.equal(state.inSyncBlock, false); }); test("leaves non-clear redraw sequences inside synchronized-output blocks intact", () => { - const state = createSyncBlockFilterState(); + const state = createSyncBlockFilterState(scrolledUpTerm); const cursorHome = "\x1b[H"; const input = `${SYNC_START}${cursorHome}${CLEAR}text${SYNC_END}`; assert.equal( - filterSyncBlockClears(input, state), + filterSyncBlockClears(input, state, scrolledUpTerm), `${SYNC_START}${cursorHome}text${SYNC_END}`, ); }); test("handles sync start marker split across chunks", () => { - const state = createSyncBlockFilterState(); + const state = createSyncBlockFilterState(scrolledUpTerm); const startPrefix = SYNC_START.slice(0, -1); const startSuffix = SYNC_START.slice(-1); - assert.equal(filterSyncBlockClears(startPrefix, state), ""); + assert.equal(filterSyncBlockClears(startPrefix, state, scrolledUpTerm), ""); assert.equal(state.pending, startPrefix); assert.equal(state.inSyncBlock, false); assert.equal( - filterSyncBlockClears(`${startSuffix}${CLEAR}frame${SYNC_END}`, state), + filterSyncBlockClears(`${startSuffix}${CLEAR}frame${SYNC_END}`, state, scrolledUpTerm), `${SYNC_START}frame${SYNC_END}`, ); assert.equal(state.inSyncBlock, false); @@ -76,53 +109,64 @@ test("handles sync start marker split across chunks", () => { }); test("handles clear-screen marker split across chunks inside sync block", () => { - const state = createSyncBlockFilterState(); + const state = createSyncBlockFilterState(scrolledUpTerm); const clearPrefix = CLEAR.slice(0, -1); const clearSuffix = CLEAR.slice(-1); - assert.equal(filterSyncBlockClears(SYNC_START, state), SYNC_START); + assert.equal(filterSyncBlockClears(SYNC_START, state, scrolledUpTerm), SYNC_START); assert.equal(state.inSyncBlock, true); - assert.equal(filterSyncBlockClears(`${clearPrefix}`, state), ""); + assert.equal(filterSyncBlockClears(`${clearPrefix}`, state, scrolledUpTerm), ""); assert.equal(state.pending, clearPrefix); - assert.equal(filterSyncBlockClears(`${clearSuffix}frame${SYNC_END}`, state), `frame${SYNC_END}`); + assert.equal( + filterSyncBlockClears(`${clearSuffix}frame${SYNC_END}`, state, scrolledUpTerm), + `frame${SYNC_END}`, + ); assert.equal(state.inSyncBlock, false); assert.equal(state.pending, ""); }); test("handles sync end marker split across chunks", () => { - const state = createSyncBlockFilterState(); + const state = createSyncBlockFilterState(scrolledUpTerm); const endPrefix = SYNC_END.slice(0, -1); const endSuffix = SYNC_END.slice(-1); - assert.equal(filterSyncBlockClears(`${SYNC_START}frame${endPrefix}`, state), `${SYNC_START}frame`); + assert.equal( + filterSyncBlockClears(`${SYNC_START}frame${endPrefix}`, state, scrolledUpTerm), + `${SYNC_START}frame`, + ); assert.equal(state.inSyncBlock, true); assert.equal(state.pending, endPrefix); - assert.equal(filterSyncBlockClears(endSuffix, state), SYNC_END); + assert.equal(filterSyncBlockClears(endSuffix, state, scrolledUpTerm), SYNC_END); assert.equal(state.inSyncBlock, false); assert.equal(state.pending, ""); }); test("releases a trailing ESC when the next chunk is ordinary text", () => { - const state = createSyncBlockFilterState(); + const state = createSyncBlockFilterState(scrolledUpTerm); - assert.equal(filterSyncBlockClears("prompt\x1b", state), "prompt"); + assert.equal(filterSyncBlockClears("prompt\x1b", state, scrolledUpTerm), "prompt"); assert.equal(state.pending, "\x1b"); - assert.equal(filterSyncBlockClears("more output", state), "\x1bmore output"); + assert.equal(filterSyncBlockClears("more output", state, scrolledUpTerm), "\x1bmore output"); assert.equal(state.pending, ""); }); -test("keeps clear-screen inside sync blocks when stripping is disabled", () => { - const state = createSyncBlockFilterState(); +test("preserves clear-screen when alternate-screen entry precedes sync redraw", () => { + const state = createSyncBlockFilterState(scrolledUpTerm); + const input = `${ALT_SCREEN_ENTER}${SYNC_START}${CLEAR}frame${SYNC_END}`; + + assert.equal(filterSyncBlockClears(input, state, scrolledUpTerm), input); + assert.equal(state.inAlternateScreen, true); +}); + +test("preserves clear-screen inside sync blocks when viewport is at bottom", () => { + const state = createSyncBlockFilterState(bottomTerm); const input = `${SYNC_START}${CLEAR}frame${SYNC_END}`; - assert.equal( - filterSyncBlockClears(input, state, { stripClearsInSyncBlock: false }), - input, - ); + assert.equal(filterSyncBlockClears(input, state, bottomTerm), input); }); test("isTerminalViewportScrolledUp is false when buffer state is unavailable", () => { @@ -130,24 +174,10 @@ test("isTerminalViewportScrolledUp is false when buffer state is unavailable", ( }); test("isTerminalViewportScrolledUp is false on alternate-screen buffers", () => { - const term = { - rows: 24, - buffer: { active: { type: "alternate", baseY: 0, length: 24 } }, - } as never; - - assert.equal(isTerminalViewportScrolledUp(term), false); + assert.equal(isTerminalViewportScrolledUp(createMockTerm({ type: "alternate", viewportY: 0, baseY: 0, length: 24 })), false); }); test("isTerminalViewportScrolledUp detects normal-buffer scrollback", () => { - const atBottom = { - rows: 24, - buffer: { active: { type: "normal", viewportY: 76, baseY: 76, length: 100 } }, - } as never; - const scrolledUp = { - rows: 24, - buffer: { active: { type: "normal", viewportY: 10, baseY: 76, length: 100 } }, - } as never; - - assert.equal(isTerminalViewportScrolledUp(atBottom), false); - assert.equal(isTerminalViewportScrolledUp(scrolledUp), true); + assert.equal(isTerminalViewportScrolledUp(bottomTerm), false); + assert.equal(isTerminalViewportScrolledUp(scrolledUpTerm), true); }); diff --git a/components/terminal/runtime/filterSyncBlockClears.ts b/components/terminal/runtime/filterSyncBlockClears.ts index a710193e0..70ae9adcd 100644 --- a/components/terminal/runtime/filterSyncBlockClears.ts +++ b/components/terminal/runtime/filterSyncBlockClears.ts @@ -11,8 +11,9 @@ import type { Terminal as XTerm } from "@xterm/xterm"; * position and makes earlier output appear "eaten". * * Alternate-screen TUIs still need the clear to remove stale cells from shorter - * redraw frames, so callers should only enable stripping while the viewport is - * scrolled up in the normal buffer. + * redraw frames. Because PTY chunks can enter alternate screen before xterm has + * applied the switch, this filter tracks alternate-screen transitions in-band + * and only strips clears while the normal buffer is scrolled up. * * PTY/IPC chunks can split escape sequences at arbitrary byte boundaries, so a * trailing partial marker is held in `pending` until the next chunk completes it. @@ -23,14 +24,11 @@ import type { Terminal as XTerm } from "@xterm/xterm"; export type SyncBlockFilterState = { inSyncBlock: boolean; + inAlternateScreen: boolean; /** Trailing bytes that may complete a marker in the next chunk. */ pending: string; }; -export type SyncBlockClearFilterOptions = { - stripClearsInSyncBlock: boolean; -}; - export type SyncBlockClearFilterResult = { output: string; startedSyncBlock: boolean; @@ -39,8 +37,16 @@ export type SyncBlockClearFilterResult = { const SYNC_START = "\x1b[?2026h"; const SYNC_END = "\x1b[?2026l"; const CLEAR = "\x1b[2J"; +const ALT_SCREEN_ENTER = ["\x1b[?1049h", "\x1b[?1047h", "\x1b[?47h"] as const; +const ALT_SCREEN_LEAVE = ["\x1b[?1049l", "\x1b[?1047l", "\x1b[?47l"] as const; -const MARKERS = [SYNC_START, SYNC_END, CLEAR] as const; +const MARKERS = [ + SYNC_START, + SYNC_END, + CLEAR, + ...ALT_SCREEN_ENTER, + ...ALT_SCREEN_LEAVE, +] as const; const maxMarkerPrefixLength = Math.max(...MARKERS.map((marker) => marker.length)) - 1; @@ -58,16 +64,51 @@ const splitPendingMarkerSuffix = (input: string): { emit: string; pending: strin return { emit: input, pending: "" }; }; +const matchMarker = (input: string, index: number, markers: readonly string[]): string | null => { + for (const marker of markers) { + if (input.startsWith(marker, index)) { + return marker; + } + } + return null; +}; + +const shouldStripClearInSyncBlock = ( + state: SyncBlockFilterState, + term: XTerm, +): boolean => { + if (state.inAlternateScreen) { + return false; + } + return isTerminalViewportScrolledUp(term); +}; + const scanSyncBlockClears = ( input: string, state: SyncBlockFilterState, - stripClearsInSyncBlock: boolean, + term: XTerm, ): SyncBlockClearFilterResult => { let result = ""; let startedSyncBlock = false; let index = 0; while (index < input.length) { + const alternateEnter = matchMarker(input, index, ALT_SCREEN_ENTER); + if (alternateEnter) { + state.inAlternateScreen = true; + result += alternateEnter; + index += alternateEnter.length; + continue; + } + + const alternateLeave = matchMarker(input, index, ALT_SCREEN_LEAVE); + if (alternateLeave) { + state.inAlternateScreen = false; + result += alternateLeave; + index += alternateLeave.length; + continue; + } + if (input.startsWith(SYNC_START, index)) { state.inSyncBlock = true; startedSyncBlock = true; @@ -84,8 +125,8 @@ const scanSyncBlockClears = ( } if ( - stripClearsInSyncBlock - && state.inSyncBlock + state.inSyncBlock + && shouldStripClearInSyncBlock(state, term) && input.startsWith(CLEAR, index) ) { index += CLEAR.length; @@ -102,7 +143,7 @@ const scanSyncBlockClears = ( export const filterSyncBlockClearsWithMeta = ( data: string, state: SyncBlockFilterState, - options: SyncBlockClearFilterOptions = { stripClearsInSyncBlock: true }, + term: XTerm, ): SyncBlockClearFilterResult => { const { emit, pending } = splitPendingMarkerSuffix(`${state.pending}${data}`); state.pending = pending; @@ -110,17 +151,20 @@ export const filterSyncBlockClearsWithMeta = ( return { output: "", startedSyncBlock: false }; } - return scanSyncBlockClears(emit, state, options.stripClearsInSyncBlock); + return scanSyncBlockClears(emit, state, term); }; export const filterSyncBlockClears = ( data: string, state: SyncBlockFilterState, - options: SyncBlockClearFilterOptions = { stripClearsInSyncBlock: true }, -): string => filterSyncBlockClearsWithMeta(data, state, options).output; + term: XTerm, +): string => filterSyncBlockClearsWithMeta(data, state, term).output; -export const createSyncBlockFilterState = (): SyncBlockFilterState => ({ +export const createSyncBlockFilterState = ( + term?: Pick, +): SyncBlockFilterState => ({ inSyncBlock: false, + inAlternateScreen: term?.buffer?.active?.type === "alternate", pending: "", }); diff --git a/components/terminal/runtime/terminalSyncBlockFilter.ts b/components/terminal/runtime/terminalSyncBlockFilter.ts index 73f8f5ecd..d3939da4a 100644 --- a/components/terminal/runtime/terminalSyncBlockFilter.ts +++ b/components/terminal/runtime/terminalSyncBlockFilter.ts @@ -3,7 +3,6 @@ import type { Terminal as XTerm } from "@xterm/xterm"; import { createSyncBlockFilterState, filterSyncBlockClearsWithMeta, - shouldStripSyncBlockClears, type SyncBlockFilterState, } from "./filterSyncBlockClears.ts"; @@ -29,13 +28,13 @@ const expireSyncBlock = (term: XTerm, state: SyncBlockFilterState): void => { export const resetTerminalSyncBlockFilter = (term: XTerm): void => { clearSyncBlockTimer(term); - syncBlockFilterStates.set(term, createSyncBlockFilterState()); + syncBlockFilterStates.set(term, createSyncBlockFilterState(term)); }; const getSyncBlockFilterState = (term: XTerm): SyncBlockFilterState => { let state = syncBlockFilterStates.get(term); if (!state) { - state = createSyncBlockFilterState(); + state = createSyncBlockFilterState(term); syncBlockFilterStates.set(term, state); } return state; @@ -57,9 +56,7 @@ const scheduleSyncBlockTimeout = (term: XTerm, state: SyncBlockFilterState): voi export const filterTerminalSessionData = (term: XTerm, data: string): string => { const state = getSyncBlockFilterState(term); - const { output, startedSyncBlock } = filterSyncBlockClearsWithMeta(data, state, { - stripClearsInSyncBlock: shouldStripSyncBlockClears(term), - }); + const { output, startedSyncBlock } = filterSyncBlockClearsWithMeta(data, state, term); if (startedSyncBlock) { clearSyncBlockTimer(term); From 9ef868f7ed782e2389fdcb9aac1c0e5b230ca8f4 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 21:46:18 +0800 Subject: [PATCH 026/228] fix(terminal): parse combined alternate-screen private-mode CSIs Recognize `\x1b[?1049;1000h`-style sequences when deciding whether sync-block clears must be preserved, without swallowing DEC 2026 markers. Co-authored-by: Cursor --- .../runtime/filterSyncBlockClears.test.ts | 8 ++ .../terminal/runtime/filterSyncBlockClears.ts | 95 +++++++++++++------ 2 files changed, 73 insertions(+), 30 deletions(-) diff --git a/components/terminal/runtime/filterSyncBlockClears.test.ts b/components/terminal/runtime/filterSyncBlockClears.test.ts index 5302c19ec..4d18dfd8e 100644 --- a/components/terminal/runtime/filterSyncBlockClears.test.ts +++ b/components/terminal/runtime/filterSyncBlockClears.test.ts @@ -162,6 +162,14 @@ test("preserves clear-screen when alternate-screen entry precedes sync redraw", assert.equal(state.inAlternateScreen, true); }); +test("preserves clear-screen for combined alternate-screen private-mode sequences", () => { + const state = createSyncBlockFilterState(scrolledUpTerm); + const input = `\x1b[?1049;1000h${SYNC_START}${CLEAR}frame${SYNC_END}`; + + assert.equal(filterSyncBlockClears(input, state, scrolledUpTerm), input); + assert.equal(state.inAlternateScreen, true); +}); + test("preserves clear-screen inside sync blocks when viewport is at bottom", () => { const state = createSyncBlockFilterState(bottomTerm); const input = `${SYNC_START}${CLEAR}frame${SYNC_END}`; diff --git a/components/terminal/runtime/filterSyncBlockClears.ts b/components/terminal/runtime/filterSyncBlockClears.ts index 70ae9adcd..fe906b3f6 100644 --- a/components/terminal/runtime/filterSyncBlockClears.ts +++ b/components/terminal/runtime/filterSyncBlockClears.ts @@ -37,19 +37,28 @@ export type SyncBlockClearFilterResult = { const SYNC_START = "\x1b[?2026h"; const SYNC_END = "\x1b[?2026l"; const CLEAR = "\x1b[2J"; -const ALT_SCREEN_ENTER = ["\x1b[?1049h", "\x1b[?1047h", "\x1b[?47h"] as const; -const ALT_SCREEN_LEAVE = ["\x1b[?1049l", "\x1b[?1047l", "\x1b[?47l"] as const; -const MARKERS = [ - SYNC_START, - SYNC_END, - CLEAR, - ...ALT_SCREEN_ENTER, - ...ALT_SCREEN_LEAVE, -] as const; +const MARKERS = [SYNC_START, SYNC_END, CLEAR] as const; +const ALTERNATE_SCREEN_MODES = new Set([47, 1047, 1049]); const maxMarkerPrefixLength = Math.max(...MARKERS.map((marker) => marker.length)) - 1; +const isCsiFinal = (ch: string): boolean => ch >= "@" && ch <= "~"; + +const isIncompleteEscapePrefix = (suffix: string): boolean => { + if (!suffix.startsWith("\x1b")) { + return false; + } + if (suffix === "\x1b") { + return true; + } + if (!suffix.startsWith("\x1b[")) { + return false; + } + const final = suffix[suffix.length - 1]; + return !isCsiFinal(final); +}; + const splitPendingMarkerSuffix = (input: string): { emit: string; pending: string } => { const maxLength = Math.min(input.length, maxMarkerPrefixLength); for (let length = maxLength; length > 0; length -= 1) { @@ -60,16 +69,46 @@ const splitPendingMarkerSuffix = (input: string): { emit: string; pending: strin pending: suffix, }; } + if (isIncompleteEscapePrefix(suffix)) { + return { + emit: input.slice(0, -length), + pending: suffix, + }; + } } return { emit: input, pending: "" }; }; -const matchMarker = (input: string, index: number, markers: readonly string[]): string | null => { - for (const marker of markers) { - if (input.startsWith(marker, index)) { - return marker; - } +const readPrivateModeCsi = ( + input: string, + index: number, +): { raw: string; end: number; setsAlternate: boolean | null } | null => { + if (!input.startsWith("\x1b[?", index)) { + return null; } + + for (let end = index + 3; end < input.length; end += 1) { + const final = input[end]; + if (final !== "h" && final !== "l") { + continue; + } + + const params = input.slice(index + 3, end).split(";"); + let setsAlternate: boolean | null = null; + for (const param of params) { + const mode = Number.parseInt(param, 10); + if (ALTERNATE_SCREEN_MODES.has(mode)) { + setsAlternate = final === "h"; + } + } + + return { + raw: input.slice(index, end + 1), + end: end + 1, + setsAlternate, + }; + } + return null; }; @@ -93,22 +132,6 @@ const scanSyncBlockClears = ( let index = 0; while (index < input.length) { - const alternateEnter = matchMarker(input, index, ALT_SCREEN_ENTER); - if (alternateEnter) { - state.inAlternateScreen = true; - result += alternateEnter; - index += alternateEnter.length; - continue; - } - - const alternateLeave = matchMarker(input, index, ALT_SCREEN_LEAVE); - if (alternateLeave) { - state.inAlternateScreen = false; - result += alternateLeave; - index += alternateLeave.length; - continue; - } - if (input.startsWith(SYNC_START, index)) { state.inSyncBlock = true; startedSyncBlock = true; @@ -124,6 +147,18 @@ const scanSyncBlockClears = ( continue; } + const privateMode = readPrivateModeCsi(input, index); + if (privateMode) { + if (privateMode.setsAlternate === true) { + state.inAlternateScreen = true; + } else if (privateMode.setsAlternate === false) { + state.inAlternateScreen = false; + } + result += privateMode.raw; + index = privateMode.end; + continue; + } + if ( state.inSyncBlock && shouldStripClearInSyncBlock(state, term) From 0913c6188f92d825287d78e6ba7a6a0bbc8e2303 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 21:51:15 +0800 Subject: [PATCH 027/228] fix(terminal): harden split CSI detection for sync-block filter Hold long incomplete private-mode sequences across chunks, terminate CSI parsing at the real final byte, and avoid treating complete `\x1b[2J` output as an unfinished escape prefix. Co-authored-by: Cursor --- .../runtime/filterSyncBlockClears.test.ts | 25 +++++++++ .../terminal/runtime/filterSyncBlockClears.ts | 55 +++++++++++++++---- 2 files changed, 70 insertions(+), 10 deletions(-) diff --git a/components/terminal/runtime/filterSyncBlockClears.test.ts b/components/terminal/runtime/filterSyncBlockClears.test.ts index 4d18dfd8e..24541a8fc 100644 --- a/components/terminal/runtime/filterSyncBlockClears.test.ts +++ b/components/terminal/runtime/filterSyncBlockClears.test.ts @@ -170,6 +170,31 @@ test("preserves clear-screen for combined alternate-screen private-mode sequence assert.equal(state.inAlternateScreen, true); }); +test("handles split combined alternate-screen sequences across chunks", () => { + const state = createSyncBlockFilterState(scrolledUpTerm); + const prefix = "\x1b[?1049;"; + const suffix = `1000h${SYNC_START}${CLEAR}frame${SYNC_END}`; + + assert.equal(filterSyncBlockClears(prefix, state, scrolledUpTerm), ""); + assert.equal(state.pending, prefix); + + assert.equal( + filterSyncBlockClears(suffix, state, scrolledUpTerm), + `\x1b[?1049;1000h${SYNC_START}${CLEAR}frame${SYNC_END}`, + ); + assert.equal(state.inAlternateScreen, true); +}); + +test("does not treat later text as part of a private-mode CSI", () => { + const state = createSyncBlockFilterState(scrolledUpTerm); + + assert.equal( + filterSyncBlockClears("\x1b[?1049shello", state, scrolledUpTerm), + "\x1b[?1049shello", + ); + assert.equal(state.inAlternateScreen, false); +}); + test("preserves clear-screen inside sync blocks when viewport is at bottom", () => { const state = createSyncBlockFilterState(bottomTerm); const input = `${SYNC_START}${CLEAR}frame${SYNC_END}`; diff --git a/components/terminal/runtime/filterSyncBlockClears.ts b/components/terminal/runtime/filterSyncBlockClears.ts index fe906b3f6..fcb85f963 100644 --- a/components/terminal/runtime/filterSyncBlockClears.ts +++ b/components/terminal/runtime/filterSyncBlockClears.ts @@ -49,19 +49,41 @@ const isIncompleteEscapePrefix = (suffix: string): boolean => { if (!suffix.startsWith("\x1b")) { return false; } - if (suffix === "\x1b") { - return true; + + let index = 0; + while (index < suffix.length) { + if (suffix.startsWith("\x1b[", index)) { + let hasFinal = false; + for (let i = index + 2; i < suffix.length; i += 1) { + if (isCsiFinal(suffix[i])) { + index = i + 1; + hasFinal = true; + break; + } + } + if (!hasFinal) { + return true; + } + continue; + } + + if (suffix[index] === "\x1b") { + if (index === suffix.length - 1) { + return true; + } + index += 1; + continue; + } + + index += 1; } - if (!suffix.startsWith("\x1b[")) { - return false; - } - const final = suffix[suffix.length - 1]; - return !isCsiFinal(final); + + return false; }; const splitPendingMarkerSuffix = (input: string): { emit: string; pending: string } => { - const maxLength = Math.min(input.length, maxMarkerPrefixLength); - for (let length = maxLength; length > 0; length -= 1) { + const markerMax = Math.min(input.length, maxMarkerPrefixLength); + for (let length = markerMax; length > 0; length -= 1) { const suffix = input.slice(-length); if (MARKERS.some((marker) => marker.startsWith(suffix) && marker.length > suffix.length)) { return { @@ -69,6 +91,10 @@ const splitPendingMarkerSuffix = (input: string): { emit: string; pending: strin pending: suffix, }; } + } + + for (let length = input.length; length > 0; length -= 1) { + const suffix = input.slice(-length); if (isIncompleteEscapePrefix(suffix)) { return { emit: input.slice(0, -length), @@ -76,6 +102,7 @@ const splitPendingMarkerSuffix = (input: string): { emit: string; pending: strin }; } } + return { emit: input, pending: "" }; }; @@ -89,10 +116,18 @@ const readPrivateModeCsi = ( for (let end = index + 3; end < input.length; end += 1) { const final = input[end]; - if (final !== "h" && final !== "l") { + if (!isCsiFinal(final)) { continue; } + if (final !== "h" && final !== "l") { + return { + raw: input.slice(index, end + 1), + end: end + 1, + setsAlternate: null, + }; + } + const params = input.slice(index + 3, end).split(";"); let setsAlternate: boolean | null = null; for (const param of params) { From 12835ab0e51d960e1f10b7488243c6813f125f30 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 23:07:16 +0800 Subject: [PATCH 028/228] fix(terminal): coalesce agent TUI writes and refine DEC 2026 redraw handling Batch PTY output per animation frame (superset write-coalescer) so Codex and Claude Code frames render atomically. Distinguish full H+2J redraws from incremental sync blocks, skip preserve-before-clear inside DEC 2026, and preserve viewport position across terminal resize. Co-authored-by: Cursor --- components/Terminal.tsx | 16 ++ .../terminal/clearTerminalViewport.test.ts | 27 ++ components/terminal/clearTerminalViewport.ts | 15 + .../runtime/createTerminalSessionStarters.ts | 2 + .../terminal/runtime/createXTermRuntime.ts | 28 +- .../runtime/filterSyncBlockClears.test.ts | 272 +++++++----------- .../terminal/runtime/filterSyncBlockClears.ts | 203 +++++++------ .../runtime/terminalSessionAttachment.ts | 21 +- .../runtime/terminalSyncBlockFilter.test.ts | 107 ++----- .../runtime/terminalSyncBlockFilter.ts | 6 +- .../runtime/terminalWriteCoalescer.ts | 27 ++ .../terminal/runtime/writeCoalescer.test.ts | 104 +++++++ components/terminal/runtime/writeCoalescer.ts | 72 +++++ 13 files changed, 543 insertions(+), 357 deletions(-) create mode 100644 components/terminal/clearTerminalViewport.test.ts create mode 100644 components/terminal/runtime/terminalWriteCoalescer.ts create mode 100644 components/terminal/runtime/writeCoalescer.test.ts create mode 100644 components/terminal/runtime/writeCoalescer.ts diff --git a/components/Terminal.tsx b/components/Terminal.tsx index 9d01c6fca..7c72be4c3 100644 --- a/components/Terminal.tsx +++ b/components/Terminal.tsx @@ -1031,6 +1031,10 @@ const TerminalComponent: React.FC = ({ const term = termRef.current; if (!term) return; + const buffer = term.buffer.active; + const wasPinnedToBottom = buffer.viewportY >= buffer.baseY; + const savedViewportY = buffer.viewportY; + const dimensions = fitAddon.proposeDimensions(); if (!dimensions || Number.isNaN(dimensions.cols) || Number.isNaN(dimensions.rows)) return; @@ -1043,6 +1047,18 @@ const TerminalComponent: React.FC = ({ term.resize(dimensions.cols, dimensions.rows); forceSyncRenderAfterResize(term); } + + // Preserve scroll position across resize (superset/Tabby pattern). + if (wasPinnedToBottom) { + term.scrollToBottom(); + } else { + const targetY = Math.min(savedViewportY, term.buffer.active.baseY); + if (term.buffer.active.viewportY !== targetY) { + term.scrollToLine(targetY); + } + } + term.refresh(0, Math.max(0, term.rows - 1)); + if (typeof requestAnimationFrame === "function") { requestAnimationFrame(() => { autocompleteRepositionRef.current?.(); diff --git a/components/terminal/clearTerminalViewport.test.ts b/components/terminal/clearTerminalViewport.test.ts new file mode 100644 index 000000000..229f63ca3 --- /dev/null +++ b/components/terminal/clearTerminalViewport.test.ts @@ -0,0 +1,27 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { shouldPreserveViewportBeforeFullErase } from "./clearTerminalViewport.ts"; + +const createMockTerm = (bufferType: "normal" | "alternate"): { buffer: { active: { type: "normal" | "alternate" } } } => ({ + buffer: { + active: { + type: bufferType, + }, + }, +}); + +test("preserves viewport before full erase on the normal screen outside sync blocks", () => { + const term = createMockTerm("normal"); + assert.equal(shouldPreserveViewportBeforeFullErase(term as never, false), true); +}); + +test("skips viewport preservation inside DEC 2026 sync blocks", () => { + const term = createMockTerm("normal"); + assert.equal(shouldPreserveViewportBeforeFullErase(term as never, true), false); +}); + +test("skips viewport preservation on the alternate screen", () => { + const term = createMockTerm("alternate"); + assert.equal(shouldPreserveViewportBeforeFullErase(term as never, false), false); +}); diff --git a/components/terminal/clearTerminalViewport.ts b/components/terminal/clearTerminalViewport.ts index 8cb24b043..c518919e5 100644 --- a/components/terminal/clearTerminalViewport.ts +++ b/components/terminal/clearTerminalViewport.ts @@ -83,3 +83,18 @@ export const isEraseScrollbackSequence = (params: CsiParam[]): boolean => export const isEraseViewportSequence = (params: CsiParam[]): boolean => params.length > 0 && params[0] === 2; + +/** + * Netcatty preserves visible rows in scrollback before CSI 2 J so shell `clear` + * does not discard history. TUIs inside DEC 2026 sync blocks or the alternate + * screen expect an in-place erase instead. + */ +export const shouldPreserveViewportBeforeFullErase = ( + term: XTerm, + inDec2026SyncBlock: boolean, +): boolean => { + if (inDec2026SyncBlock) { + return false; + } + return term.buffer.active.type === "normal"; +}; diff --git a/components/terminal/runtime/createTerminalSessionStarters.ts b/components/terminal/runtime/createTerminalSessionStarters.ts index fa9d7083a..7350ff352 100644 --- a/components/terminal/runtime/createTerminalSessionStarters.ts +++ b/components/terminal/runtime/createTerminalSessionStarters.ts @@ -16,6 +16,7 @@ import { writeTerminalLine, } from "./terminalSessionAttachment"; import { resetTerminalSyncBlockFilter } from "./terminalSyncBlockFilter"; +import { resetTerminalWriteCoalescer } from "./terminalWriteCoalescer"; import { isConnectionTokenCurrent, registerConnectionToken, runDistroDetection } from "./terminalDistroDetection"; import { resolveStartupCommand, scheduleStartupCommand } from "./terminalStartupCommands"; import { markPromptLineBreakCommandPending } from "./promptLineBreak"; @@ -1097,6 +1098,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex ctx.sessionRef.current = id; getFlowController(ctx, term).reset(); + resetTerminalWriteCoalescer(term); resetTerminalSyncBlockFilter(term); resetTerminalLineTimestampState(term); ctx.disposeDataRef.current = ctx.terminalBackend.onSessionData(id, (chunk) => { diff --git a/components/terminal/runtime/createXTermRuntime.ts b/components/terminal/runtime/createXTermRuntime.ts index 91c8e7471..f25ebd25a 100644 --- a/components/terminal/runtime/createXTermRuntime.ts +++ b/components/terminal/runtime/createXTermRuntime.ts @@ -35,9 +35,10 @@ import { isMacPlatform } from "../../../lib/utils"; import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge"; import { clearTerminalViewport, - isEraseViewportSequence, isEraseScrollbackSequence, + isEraseViewportSequence, preserveTerminalViewportInScrollback, + shouldPreserveViewportBeforeFullErase, } from "../clearTerminalViewport"; import { createKittyKeyboardModeState, @@ -1058,9 +1059,30 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime // OSC 7 format: \x1b]7;file://hostname/path\x07 or \x1b]7;file://hostname/path\x1b\\ let currentCwd: string | undefined = undefined; + // Track DEC 2026 synchronized-output blocks so CSI 2 J can erase in place for + // Codex/Claude Code TUIs instead of pushing visible rows into scrollback. + let inDec2026SyncBlock = false; + + const dec2026SyncStartDisposable = term.parser.registerCsiHandler( + { prefix: "?", final: "h", params: [2026] }, + () => { + inDec2026SyncBlock = true; + return false; + }, + ); + const dec2026SyncEndDisposable = term.parser.registerCsiHandler( + { prefix: "?", final: "l", params: [2026] }, + () => { + inDec2026SyncBlock = false; + return false; + }, + ); + const eraseScrollbackDisposable = term.parser.registerCsiHandler({ final: "J" }, (params) => { if (isEraseViewportSequence(params)) { - preserveTerminalViewportInScrollback(term); + if (shouldPreserveViewportBeforeFullErase(term, inDec2026SyncBlock)) { + preserveTerminalViewportInScrollback(term); + } return false; } if (!isEraseScrollbackSequence(params)) { @@ -1251,6 +1273,8 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime stopDprWatch(); keywordHighlighter.dispose(); eraseScrollbackDisposable.dispose(); + dec2026SyncStartDisposable.dispose(); + dec2026SyncEndDisposable.dispose(); for (const disposable of cursorPositionReportRequestDisposables) { disposable.dispose(); } diff --git a/components/terminal/runtime/filterSyncBlockClears.test.ts b/components/terminal/runtime/filterSyncBlockClears.test.ts index 24541a8fc..d801c09cb 100644 --- a/components/terminal/runtime/filterSyncBlockClears.test.ts +++ b/components/terminal/runtime/filterSyncBlockClears.test.ts @@ -1,8 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import type { Terminal as XTerm } from "@xterm/xterm"; - import { createSyncBlockFilterState, filterSyncBlockClears, @@ -12,205 +10,135 @@ import { const SYNC_START = "\x1b[?2026h"; const SYNC_END = "\x1b[?2026l"; const CLEAR = "\x1b[2J"; -const ALT_SCREEN_ENTER = "\x1b[?1049h"; +const CURSOR_HOME = "\x1b[H"; -const createMockTerm = ({ - type = "normal", - viewportY = 10, - baseY = 76, - length = 100, - rows = 24, -}: { - type?: "normal" | "alternate"; - viewportY?: number; - baseY?: number; - length?: number; - rows?: number; -} = {}): XTerm => ({ - rows, - buffer: { - active: { - type, - baseY, - length, - viewportY, - }, - }, -} as unknown as XTerm); +const scrolledUpTerm = { + rows: 24, + buffer: { active: { type: "normal" as const, viewportY: 0, baseY: 5 } }, +}; -const scrolledUpTerm = createMockTerm(); -const bottomTerm = createMockTerm({ viewportY: 76, baseY: 76 }); +const liveBottomTerm = { + rows: 24, + buffer: { active: { type: "normal" as const, viewportY: 10, baseY: 10 } }, +}; test("passes through data with no synchronized-output sequences", () => { - const state = createSyncBlockFilterState(scrolledUpTerm); + const state = createSyncBlockFilterState(); const input = "hello\r\n\x1b[2Jworld\r\n"; - assert.equal(filterSyncBlockClears(input, state, scrolledUpTerm), input); + assert.equal(filterSyncBlockClears(input, state), input); assert.equal(state.inSyncBlock, false); }); -test("strips clear-screen inside a synchronized-output block", () => { - const state = createSyncBlockFilterState(scrolledUpTerm); - const input = `${SYNC_START}${CLEAR}frame${SYNC_END}`; - - assert.equal(filterSyncBlockClears(input, state, scrolledUpTerm), `${SYNC_START}frame${SYNC_END}`); - assert.equal(state.inSyncBlock, false); -}); - -test("does not strip clear-screen outside synchronized-output blocks", () => { - const state = createSyncBlockFilterState(scrolledUpTerm); - - assert.equal(filterSyncBlockClears(CLEAR, state, scrolledUpTerm), CLEAR); - assert.equal(state.inSyncBlock, false); -}); - -test("tracks synchronized-output state across chunks", () => { - const state = createSyncBlockFilterState(scrolledUpTerm); - - assert.equal(filterSyncBlockClears(SYNC_START, state, scrolledUpTerm), SYNC_START); - assert.equal(state.inSyncBlock, true); - - assert.equal(filterSyncBlockClears(`${CLEAR}partial`, state, scrolledUpTerm), "partial"); - assert.equal(state.inSyncBlock, true); +test("strips home and clear for full-screen redraw sync blocks", () => { + const state = createSyncBlockFilterState(); + const input = `${SYNC_START}${CURSOR_HOME}${CLEAR}frame${SYNC_END}`; assert.equal( - filterSyncBlockClears(`${CLEAR}done${SYNC_END}`, state, scrolledUpTerm), - `done${SYNC_END}`, - ); - assert.equal(state.inSyncBlock, false); -}); - -test("leaves non-clear redraw sequences inside synchronized-output blocks intact", () => { - const state = createSyncBlockFilterState(scrolledUpTerm); - const cursorHome = "\x1b[H"; - const input = `${SYNC_START}${cursorHome}${CLEAR}text${SYNC_END}`; - - assert.equal( - filterSyncBlockClears(input, state, scrolledUpTerm), - `${SYNC_START}${cursorHome}text${SYNC_END}`, - ); -}); - -test("handles sync start marker split across chunks", () => { - const state = createSyncBlockFilterState(scrolledUpTerm); - const startPrefix = SYNC_START.slice(0, -1); - const startSuffix = SYNC_START.slice(-1); - - assert.equal(filterSyncBlockClears(startPrefix, state, scrolledUpTerm), ""); - assert.equal(state.pending, startPrefix); - assert.equal(state.inSyncBlock, false); - - assert.equal( - filterSyncBlockClears(`${startSuffix}${CLEAR}frame${SYNC_END}`, state, scrolledUpTerm), + filterSyncBlockClears(input, state, scrolledUpTerm as never), `${SYNC_START}frame${SYNC_END}`, ); assert.equal(state.inSyncBlock, false); - assert.equal(state.pending, ""); }); -test("handles clear-screen marker split across chunks inside sync block", () => { - const state = createSyncBlockFilterState(scrolledUpTerm); +test("passes full-screen redraw clears through at the live bottom", () => { + const state = createSyncBlockFilterState(); + const input = `${SYNC_START}${CURSOR_HOME}${CLEAR}frame${SYNC_END}`; + + assert.equal(filterSyncBlockClears(input, state, liveBottomTerm as never), input); +}); + +test("passes incremental sync blocks through unchanged", () => { + const state = createSyncBlockFilterState(); + const rowMove = "\x1b[5;1H"; + const input = `${SYNC_START}${rowMove}partial${SYNC_END}`; + + assert.equal(filterSyncBlockClears(input, state), input); +}); + +test("passes clear-screen outside synchronized-output blocks", () => { + const state = createSyncBlockFilterState(); + + assert.equal(filterSyncBlockClears(CLEAR, state), CLEAR); +}); + +test("passes standalone clear inside sync blocks that are not full redraws", () => { + const state = createSyncBlockFilterState(); + const input = `${SYNC_START}${CLEAR}frame${SYNC_END}`; + + assert.equal(filterSyncBlockClears(input, state), input); +}); + +test("tracks full redraw state across chunks", () => { + const state = createSyncBlockFilterState(); + + assert.equal(filterSyncBlockClears(SYNC_START, state, scrolledUpTerm as never), SYNC_START); + assert.equal(filterSyncBlockClears(CURSOR_HOME, state, scrolledUpTerm as never), ""); + assert.equal(state.pendingCursorHome, CURSOR_HOME); + + assert.equal(filterSyncBlockClears(CLEAR, state, scrolledUpTerm as never), ""); + assert.equal( + filterSyncBlockClears(`frame${SYNC_END}`, state, scrolledUpTerm as never), + `frame${SYNC_END}`, + ); +}); + +test("releases held cursor-home when sync block ends without clear", () => { + const state = createSyncBlockFilterState(); + + assert.equal(filterSyncBlockClears(SYNC_START, state, scrolledUpTerm as never), SYNC_START); + assert.equal(filterSyncBlockClears(CURSOR_HOME, state, scrolledUpTerm as never), ""); + assert.equal( + filterSyncBlockClears(`partial${SYNC_END}`, state, scrolledUpTerm as never), + `${CURSOR_HOME}partial${SYNC_END}`, + ); +}); + +test("handles sync markers split across chunks", () => { + const state = createSyncBlockFilterState(); + const startPrefix = SYNC_START.slice(0, -1); + const startSuffix = SYNC_START.slice(-1); + + assert.equal(filterSyncBlockClears(startPrefix, state, scrolledUpTerm as never), ""); + assert.equal( + filterSyncBlockClears( + `${startSuffix}${CURSOR_HOME}${CLEAR}frame${SYNC_END}`, + state, + scrolledUpTerm as never, + ), + `${SYNC_START}frame${SYNC_END}`, + ); +}); + +test("handles clear-screen marker split across chunks inside full redraw block", () => { + const state = createSyncBlockFilterState(); const clearPrefix = CLEAR.slice(0, -1); const clearSuffix = CLEAR.slice(-1); - assert.equal(filterSyncBlockClears(SYNC_START, state, scrolledUpTerm), SYNC_START); - assert.equal(state.inSyncBlock, true); - - assert.equal(filterSyncBlockClears(`${clearPrefix}`, state, scrolledUpTerm), ""); - assert.equal(state.pending, clearPrefix); - + assert.equal(filterSyncBlockClears(SYNC_START, state, scrolledUpTerm as never), SYNC_START); + assert.equal(filterSyncBlockClears(CURSOR_HOME, state, scrolledUpTerm as never), ""); + assert.equal(filterSyncBlockClears(clearPrefix, state, scrolledUpTerm as never), ""); assert.equal( - filterSyncBlockClears(`${clearSuffix}frame${SYNC_END}`, state, scrolledUpTerm), + filterSyncBlockClears(`${clearSuffix}frame${SYNC_END}`, state, scrolledUpTerm as never), `frame${SYNC_END}`, ); - assert.equal(state.inSyncBlock, false); - assert.equal(state.pending, ""); }); -test("handles sync end marker split across chunks", () => { - const state = createSyncBlockFilterState(scrolledUpTerm); - const endPrefix = SYNC_END.slice(0, -1); - const endSuffix = SYNC_END.slice(-1); +test("leaves non-home redraw sequences inside full redraw blocks intact", () => { + const state = createSyncBlockFilterState(); + const cursorHome = "\x1b[1;1H"; + const input = `${SYNC_START}${cursorHome}${CLEAR}text${SYNC_END}`; assert.equal( - filterSyncBlockClears(`${SYNC_START}frame${endPrefix}`, state, scrolledUpTerm), - `${SYNC_START}frame`, + filterSyncBlockClears(input, state, scrolledUpTerm as never), + `${SYNC_START}text${SYNC_END}`, ); - assert.equal(state.inSyncBlock, true); - assert.equal(state.pending, endPrefix); - - assert.equal(filterSyncBlockClears(endSuffix, state, scrolledUpTerm), SYNC_END); - assert.equal(state.inSyncBlock, false); - assert.equal(state.pending, ""); }); -test("releases a trailing ESC when the next chunk is ordinary text", () => { - const state = createSyncBlockFilterState(scrolledUpTerm); - - assert.equal(filterSyncBlockClears("prompt\x1b", state, scrolledUpTerm), "prompt"); - assert.equal(state.pending, "\x1b"); - - assert.equal(filterSyncBlockClears("more output", state, scrolledUpTerm), "\x1bmore output"); - assert.equal(state.pending, ""); +test("isTerminalViewportScrolledUp is false at the live bottom", () => { + assert.equal(isTerminalViewportScrolledUp(liveBottomTerm as never), false); }); -test("preserves clear-screen when alternate-screen entry precedes sync redraw", () => { - const state = createSyncBlockFilterState(scrolledUpTerm); - const input = `${ALT_SCREEN_ENTER}${SYNC_START}${CLEAR}frame${SYNC_END}`; - - assert.equal(filterSyncBlockClears(input, state, scrolledUpTerm), input); - assert.equal(state.inAlternateScreen, true); -}); - -test("preserves clear-screen for combined alternate-screen private-mode sequences", () => { - const state = createSyncBlockFilterState(scrolledUpTerm); - const input = `\x1b[?1049;1000h${SYNC_START}${CLEAR}frame${SYNC_END}`; - - assert.equal(filterSyncBlockClears(input, state, scrolledUpTerm), input); - assert.equal(state.inAlternateScreen, true); -}); - -test("handles split combined alternate-screen sequences across chunks", () => { - const state = createSyncBlockFilterState(scrolledUpTerm); - const prefix = "\x1b[?1049;"; - const suffix = `1000h${SYNC_START}${CLEAR}frame${SYNC_END}`; - - assert.equal(filterSyncBlockClears(prefix, state, scrolledUpTerm), ""); - assert.equal(state.pending, prefix); - - assert.equal( - filterSyncBlockClears(suffix, state, scrolledUpTerm), - `\x1b[?1049;1000h${SYNC_START}${CLEAR}frame${SYNC_END}`, - ); - assert.equal(state.inAlternateScreen, true); -}); - -test("does not treat later text as part of a private-mode CSI", () => { - const state = createSyncBlockFilterState(scrolledUpTerm); - - assert.equal( - filterSyncBlockClears("\x1b[?1049shello", state, scrolledUpTerm), - "\x1b[?1049shello", - ); - assert.equal(state.inAlternateScreen, false); -}); - -test("preserves clear-screen inside sync blocks when viewport is at bottom", () => { - const state = createSyncBlockFilterState(bottomTerm); - const input = `${SYNC_START}${CLEAR}frame${SYNC_END}`; - - assert.equal(filterSyncBlockClears(input, state, bottomTerm), input); -}); - -test("isTerminalViewportScrolledUp is false when buffer state is unavailable", () => { - assert.equal(isTerminalViewportScrolledUp({} as never), false); -}); - -test("isTerminalViewportScrolledUp is false on alternate-screen buffers", () => { - assert.equal(isTerminalViewportScrolledUp(createMockTerm({ type: "alternate", viewportY: 0, baseY: 0, length: 24 })), false); -}); - -test("isTerminalViewportScrolledUp detects normal-buffer scrollback", () => { - assert.equal(isTerminalViewportScrolledUp(bottomTerm), false); - assert.equal(isTerminalViewportScrolledUp(scrolledUpTerm), true); +test("isTerminalViewportScrolledUp is true when reading scrollback", () => { + assert.equal(isTerminalViewportScrolledUp(scrolledUpTerm as never), true); }); diff --git a/components/terminal/runtime/filterSyncBlockClears.ts b/components/terminal/runtime/filterSyncBlockClears.ts index fcb85f963..79eb0f5b7 100644 --- a/components/terminal/runtime/filterSyncBlockClears.ts +++ b/components/terminal/runtime/filterSyncBlockClears.ts @@ -1,32 +1,30 @@ import type { Terminal as XTerm } from "@xterm/xterm"; /** - * Strip `\x1b[2J` (ED — erase display) inside DEC Mode 2026 synchronized-output + * Strip full-screen redraw sequences inside DEC Mode 2026 synchronized-output * blocks before data reaches xterm.js. * - * Coding CLIs such as Codex and Claude Code wrap full-screen redraws in - * `\x1b[?2026h` … `\x1b[?2026l`. Native terminals treat the enclosed clear as - * part of the atomic update, but xterm.js resets viewportY on every `\x1b[2J` - * when the user has scrolled up in the normal buffer, which yanks scroll - * position and makes earlier output appear "eaten". + * Codex and Claude Code emit `\x1b[H` + `\x1b[2J` inside sync blocks for + * full-screen frames. xterm.js resets viewportY on `\x1b[2J`, which yanks + * scroll position. Incremental sync blocks must pass through untouched. * - * Alternate-screen TUIs still need the clear to remove stale cells from shorter - * redraw frames. Because PTY chunks can enter alternate screen before xterm has - * applied the switch, this filter tracks alternate-screen transitions in-band - * and only strips clears while the normal buffer is scrolled up. - * - * PTY/IPC chunks can split escape sequences at arbitrary byte boundaries, so a - * trailing partial marker is held in `pending` until the next chunk completes it. + * Detection follows anthropics/claude-code#35580: only blocks that contain + * both cursor-home and erase-display are treated as full redraws. Pane (#120) + * strips `\x1b[2J`; we also hold the leading `\x1b[H` until `\x1b[2J` confirms + * the redraw so incremental blocks that never emit `\x1b[2J` still work. * + * @see https://github.com/Dcouple-Inc/Pane/pull/120 + * @see https://github.com/anthropics/claude-code/issues/35580 * @see https://github.com/xtermjs/xterm.js/issues/5801 - * @see https://github.com/openai/codex/issues/14277 */ export type SyncBlockFilterState = { inSyncBlock: boolean; - inAlternateScreen: boolean; - /** Trailing bytes that may complete a marker in the next chunk. */ pending: string; + /** Leading `\x1b[H` held until `\x1b[2J` confirms a full redraw. */ + pendingCursorHome: string | null; + /** null = unknown; true = strip home+clear; false = pass block through. */ + fullRedrawBlock: boolean | null; }; export type SyncBlockClearFilterResult = { @@ -37,19 +35,20 @@ export type SyncBlockClearFilterResult = { const SYNC_START = "\x1b[?2026h"; const SYNC_END = "\x1b[?2026l"; const CLEAR = "\x1b[2J"; +const CURSOR_HOME = "\x1b[H"; +const CURSOR_HOME_EXPLICIT = "\x1b[1;1H"; -const MARKERS = [SYNC_START, SYNC_END, CLEAR] as const; -const ALTERNATE_SCREEN_MODES = new Set([47, 1047, 1049]); +const MARKERS = [SYNC_START, SYNC_END, CLEAR, CURSOR_HOME, CURSOR_HOME_EXPLICIT] as const; const maxMarkerPrefixLength = Math.max(...MARKERS.map((marker) => marker.length)) - 1; -const isCsiFinal = (ch: string): boolean => ch >= "@" && ch <= "~"; - const isIncompleteEscapePrefix = (suffix: string): boolean => { if (!suffix.startsWith("\x1b")) { return false; } + const isCsiFinal = (ch: string): boolean => ch >= "@" && ch <= "~"; + let index = 0; while (index < suffix.length) { if (suffix.startsWith("\x1b[", index)) { @@ -106,61 +105,50 @@ const splitPendingMarkerSuffix = (input: string): { emit: string; pending: strin return { emit: input, pending: "" }; }; -const readPrivateModeCsi = ( +const readBlockCursorHome = ( input: string, index: number, -): { raw: string; end: number; setsAlternate: boolean | null } | null => { - if (!input.startsWith("\x1b[?", index)) { - return null; +): { raw: string; end: number } | null => { + if (input.startsWith(CURSOR_HOME_EXPLICIT, index)) { + return { raw: CURSOR_HOME_EXPLICIT, end: index + CURSOR_HOME_EXPLICIT.length }; } - - for (let end = index + 3; end < input.length; end += 1) { - const final = input[end]; - if (!isCsiFinal(final)) { - continue; - } - - if (final !== "h" && final !== "l") { - return { - raw: input.slice(index, end + 1), - end: end + 1, - setsAlternate: null, - }; - } - - const params = input.slice(index + 3, end).split(";"); - let setsAlternate: boolean | null = null; - for (const param of params) { - const mode = Number.parseInt(param, 10); - if (ALTERNATE_SCREEN_MODES.has(mode)) { - setsAlternate = final === "h"; - } - } - - return { - raw: input.slice(index, end + 1), - end: end + 1, - setsAlternate, - }; + if (input.startsWith(CURSOR_HOME, index)) { + return { raw: CURSOR_HOME, end: index + CURSOR_HOME.length }; } - return null; }; -const shouldStripClearInSyncBlock = ( - state: SyncBlockFilterState, - term: XTerm, -): boolean => { - if (state.inAlternateScreen) { +const releasePendingCursorHome = (state: SyncBlockFilterState, result: string): string => { + if (!state.pendingCursorHome) { + return result; + } + const released = `${result}${state.pendingCursorHome}`; + state.pendingCursorHome = null; + return released; +}; + +const resetSyncBlockState = (state: SyncBlockFilterState): void => { + state.inSyncBlock = false; + state.pendingCursorHome = null; + state.fullRedrawBlock = null; +}; + +/** True when the user has scrolled up into scrollback history. */ +export const isTerminalViewportScrolledUp = (term: XTerm): boolean => { + const buffer = term.buffer.active; + if (buffer.type !== "normal") { return false; } - return isTerminalViewportScrolledUp(term); + return buffer.viewportY < buffer.baseY; }; +const shouldStripFullRedrawClear = (term?: XTerm): boolean => + term !== undefined && isTerminalViewportScrolledUp(term); + const scanSyncBlockClears = ( input: string, state: SyncBlockFilterState, - term: XTerm, + term?: XTerm, ): SyncBlockClearFilterResult => { let result = ""; let startedSyncBlock = false; @@ -168,6 +156,7 @@ const scanSyncBlockClears = ( while (index < input.length) { if (input.startsWith(SYNC_START, index)) { + resetSyncBlockState(state); state.inSyncBlock = true; startedSyncBlock = true; result += SYNC_START; @@ -176,33 +165,68 @@ const scanSyncBlockClears = ( } if (input.startsWith(SYNC_END, index)) { - state.inSyncBlock = false; + result = releasePendingCursorHome(state, result); + resetSyncBlockState(state); result += SYNC_END; index += SYNC_END.length; continue; } - const privateMode = readPrivateModeCsi(input, index); - if (privateMode) { - if (privateMode.setsAlternate === true) { - state.inAlternateScreen = true; - } else if (privateMode.setsAlternate === false) { - state.inAlternateScreen = false; - } - result += privateMode.raw; - index = privateMode.end; + if (!state.inSyncBlock) { + result += input[index]; + index += 1; continue; } - if ( - state.inSyncBlock - && shouldStripClearInSyncBlock(state, term) - && input.startsWith(CLEAR, index) - ) { + if (state.fullRedrawBlock === false) { + result += input[index]; + index += 1; + continue; + } + + const cursorHome = readBlockCursorHome(input, index); + if (cursorHome) { + if (state.fullRedrawBlock === true) { + index = cursorHome.end; + continue; + } + if (!shouldStripFullRedrawClear(term)) { + result += cursorHome.raw; + index = cursorHome.end; + continue; + } + state.pendingCursorHome = cursorHome.raw; + index = cursorHome.end; + continue; + } + + if (input.startsWith(CLEAR, index)) { + if (state.pendingCursorHome !== null) { + state.pendingCursorHome = null; + state.fullRedrawBlock = true; + index += CLEAR.length; + continue; + } + if (state.fullRedrawBlock === true) { + index += CLEAR.length; + continue; + } + if (!shouldStripFullRedrawClear(term)) { + result += CLEAR; + index += CLEAR.length; + continue; + } + state.fullRedrawBlock = false; + result += CLEAR; index += CLEAR.length; continue; } + if (state.pendingCursorHome !== null) { + result += state.pendingCursorHome; + state.pendingCursorHome = null; + } + result += input[index]; index += 1; } @@ -213,8 +237,12 @@ const scanSyncBlockClears = ( export const filterSyncBlockClearsWithMeta = ( data: string, state: SyncBlockFilterState, - term: XTerm, + term?: XTerm, ): SyncBlockClearFilterResult => { + if (!state.inSyncBlock && !state.pending && !data.includes("\x1b")) { + return { output: data, startedSyncBlock: false }; + } + const { emit, pending } = splitPendingMarkerSuffix(`${state.pending}${data}`); state.pending = pending; if (!emit) { @@ -227,25 +255,12 @@ export const filterSyncBlockClearsWithMeta = ( export const filterSyncBlockClears = ( data: string, state: SyncBlockFilterState, - term: XTerm, + term?: XTerm, ): string => filterSyncBlockClearsWithMeta(data, state, term).output; -export const createSyncBlockFilterState = ( - term?: Pick, -): SyncBlockFilterState => ({ +export const createSyncBlockFilterState = (): SyncBlockFilterState => ({ inSyncBlock: false, - inAlternateScreen: term?.buffer?.active?.type === "alternate", pending: "", + pendingCursorHome: null, + fullRedrawBlock: null, }); - -export const isTerminalViewportScrolledUp = (term: XTerm): boolean => { - const buffer = term.buffer?.active; - if (!buffer || buffer.type === "alternate") { - return false; - } - - return buffer.viewportY < buffer.baseY; -}; - -export const shouldStripSyncBlockClears = (term: XTerm): boolean => - isTerminalViewportScrolledUp(term); diff --git a/components/terminal/runtime/terminalSessionAttachment.ts b/components/terminal/runtime/terminalSessionAttachment.ts index 583a4bdea..504682b95 100644 --- a/components/terminal/runtime/terminalSessionAttachment.ts +++ b/components/terminal/runtime/terminalSessionAttachment.ts @@ -22,6 +22,11 @@ import { filterTerminalSessionData, resetTerminalSyncBlockFilter, } from "./terminalSyncBlockFilter"; +import { + enqueueCoalescedTerminalWrite, + flushTerminalWriteCoalescer, + resetTerminalWriteCoalescer, +} from "./terminalWriteCoalescer"; export const buildTermEnv = (host: Host, terminalSettings?: TerminalSettings) => { const env: Record = { @@ -145,10 +150,20 @@ export const writeSessionData = ( term: XTerm, data: string, ) => { - const displayData = filterTerminalSessionData(term, data); + enqueueCoalescedTerminalWrite(term, data, (batch) => { + writeSessionDataImmediate(ctx, term, batch); + }); +}; + +const writeSessionDataImmediate = ( + ctx: TerminalSessionStartersContext, + term: XTerm, + data: string, +) => { const flow = getFlowController(ctx, term); - flow.received(displayData.length); + flow.received(data.length); enqueueTerminalWrite(term, (done) => { + const displayData = filterTerminalSessionData(term, data); const settings = ctx.terminalSettingsRef?.current ?? ctx.terminalSettings; const forcePromptNewLine = settings?.forcePromptNewLine ?? false; if (!forcePromptNewLine && ctx.promptLineBreakStateRef?.current) { @@ -251,6 +266,8 @@ export const attachSessionToTerminal = ( ctx.sessionRef.current = id; // Clear any stale back-pressure accounting from a prior session on this term. getFlowController(ctx, term).reset(); + flushTerminalWriteCoalescer(term); + resetTerminalWriteCoalescer(term); resetTerminalSyncBlockFilter(term); resetTerminalLineTimestamps(term); ctx.onSessionAttached?.(id); diff --git a/components/terminal/runtime/terminalSyncBlockFilter.test.ts b/components/terminal/runtime/terminalSyncBlockFilter.test.ts index 3f084afd6..c1fa88a1b 100644 --- a/components/terminal/runtime/terminalSyncBlockFilter.test.ts +++ b/components/terminal/runtime/terminalSyncBlockFilter.test.ts @@ -10,39 +10,29 @@ import { } from "./terminalSyncBlockFilter.ts"; const SYNC_START = "\x1b[?2026h"; +const SYNC_END = "\x1b[?2026l"; const CLEAR = "\x1b[2J"; +const CURSOR_HOME = "\x1b[H"; -const createMockTerm = ({ - type = "normal", - viewportY = 10, - baseY = 76, - length = 100, - rows = 24, -}: { - type?: "normal" | "alternate"; - viewportY?: number; - baseY?: number; - length?: number; - rows?: number; -} = {}): XTerm => ({ - rows, +const createMockTerm = (): XTerm => ({ + rows: 24, buffer: { active: { - type, - baseY, - length, - viewportY, + type: "normal", + viewportY: 0, + baseY: 5, }, }, -} as unknown as XTerm); +} as XTerm); -test("abandoned sync blocks stop stripping clear-screen after timeout", () => { +test("abandoned sync blocks stop stripping full redraw clears after timeout", () => { mock.timers.enable({ apis: ["setTimeout"] }); - const term = createMockTerm({ viewportY: 10, baseY: 76 }); + const term = createMockTerm(); try { resetTerminalSyncBlockFilter(term); assert.equal(filterTerminalSessionData(term, SYNC_START), SYNC_START); + assert.equal(filterTerminalSessionData(term, CURSOR_HOME), ""); assert.equal(filterTerminalSessionData(term, CLEAR), ""); mock.timers.tick(SYNC_BLOCK_TIMEOUT_MS); @@ -55,13 +45,13 @@ test("abandoned sync blocks stop stripping clear-screen after timeout", () => { test("completed sync blocks clear the timeout without waiting", () => { mock.timers.enable({ apis: ["setTimeout"] }); - const term = createMockTerm({ viewportY: 10, baseY: 76 }); + const term = createMockTerm(); try { resetTerminalSyncBlockFilter(term); assert.equal( - filterTerminalSessionData(term, `${SYNC_START}frame\x1b[?2026l`), - `${SYNC_START}frame\x1b[?2026l`, + filterTerminalSessionData(term, `${SYNC_START}${CURSOR_HOME}${CLEAR}frame${SYNC_END}`), + `${SYNC_START}frame${SYNC_END}`, ); mock.timers.tick(SYNC_BLOCK_TIMEOUT_MS); @@ -72,30 +62,19 @@ test("completed sync blocks clear the timeout without waiting", () => { } }); -test("sync block timeout is armed once even when output keeps streaming", () => { - mock.timers.enable({ apis: ["setTimeout"] }); - const term = createMockTerm({ viewportY: 10, baseY: 76 }); +test("passes incremental sync blocks through unchanged", () => { + const term = createMockTerm(); + resetTerminalSyncBlockFilter(term); - try { - resetTerminalSyncBlockFilter(term); - assert.equal(filterTerminalSessionData(term, SYNC_START), SYNC_START); - assert.equal(filterTerminalSessionData(term, "frame-1"), "frame-1"); - assert.equal(filterTerminalSessionData(term, "frame-2"), "frame-2"); - - mock.timers.tick(SYNC_BLOCK_TIMEOUT_MS - 1); - assert.equal(filterTerminalSessionData(term, CLEAR), ""); - - mock.timers.tick(1); - assert.equal(filterTerminalSessionData(term, CLEAR), CLEAR); - } finally { - resetTerminalSyncBlockFilter(term); - mock.timers.reset(); - } + assert.equal( + filterTerminalSessionData(term, `${SYNC_START}\x1b[5;1Hframe${SYNC_END}`), + `${SYNC_START}\x1b[5;1Hframe${SYNC_END}`, + ); }); test("sync block timeout preserves pending partial marker bytes", () => { mock.timers.enable({ apis: ["setTimeout"] }); - const term = createMockTerm({ viewportY: 10, baseY: 76 }); + const term = createMockTerm(); try { resetTerminalSyncBlockFilter(term); @@ -109,45 +88,3 @@ test("sync block timeout preserves pending partial marker bytes", () => { mock.timers.reset(); } }); - -test("preserves clear-screen redraws on alternate-screen buffers", () => { - const term = createMockTerm({ type: "alternate", viewportY: 0, baseY: 0, length: 24 }); - resetTerminalSyncBlockFilter(term); - - assert.equal( - filterTerminalSessionData(term, `${SYNC_START}${CLEAR}frame\x1b[?2026l`), - `${SYNC_START}${CLEAR}frame\x1b[?2026l`, - ); -}); - -test("preserves clear-screen redraws when the viewport is at the bottom", () => { - const term = createMockTerm({ viewportY: 76, baseY: 76, length: 100 }); - resetTerminalSyncBlockFilter(term); - - assert.equal( - filterTerminalSessionData(term, `${SYNC_START}${CLEAR}frame\x1b[?2026l`), - `${SYNC_START}${CLEAR}frame\x1b[?2026l`, - ); -}); - -test("restarts sync timeout when back-to-back blocks arrive in one chunk", () => { - mock.timers.enable({ apis: ["setTimeout"] }); - const term = createMockTerm({ viewportY: 10, baseY: 76 }); - - try { - resetTerminalSyncBlockFilter(term); - assert.equal(filterTerminalSessionData(term, SYNC_START), SYNC_START); - - mock.timers.tick(SYNC_BLOCK_TIMEOUT_MS - 1); - assert.equal( - filterTerminalSessionData(term, `\x1b[?2026l${SYNC_START}${CLEAR}`), - `\x1b[?2026l${SYNC_START}`, - ); - - mock.timers.tick(1); - assert.equal(filterTerminalSessionData(term, CLEAR), ""); - } finally { - resetTerminalSyncBlockFilter(term); - mock.timers.reset(); - } -}); diff --git a/components/terminal/runtime/terminalSyncBlockFilter.ts b/components/terminal/runtime/terminalSyncBlockFilter.ts index d3939da4a..d97d14179 100644 --- a/components/terminal/runtime/terminalSyncBlockFilter.ts +++ b/components/terminal/runtime/terminalSyncBlockFilter.ts @@ -23,18 +23,20 @@ const clearSyncBlockTimer = (term: XTerm): void => { const expireSyncBlock = (term: XTerm, state: SyncBlockFilterState): void => { state.inSyncBlock = false; + state.pendingCursorHome = null; + state.fullRedrawBlock = null; clearSyncBlockTimer(term); }; export const resetTerminalSyncBlockFilter = (term: XTerm): void => { clearSyncBlockTimer(term); - syncBlockFilterStates.set(term, createSyncBlockFilterState(term)); + syncBlockFilterStates.set(term, createSyncBlockFilterState()); }; const getSyncBlockFilterState = (term: XTerm): SyncBlockFilterState => { let state = syncBlockFilterStates.get(term); if (!state) { - state = createSyncBlockFilterState(term); + state = createSyncBlockFilterState(); syncBlockFilterStates.set(term, state); } return state; diff --git a/components/terminal/runtime/terminalWriteCoalescer.ts b/components/terminal/runtime/terminalWriteCoalescer.ts new file mode 100644 index 000000000..6c696d97e --- /dev/null +++ b/components/terminal/runtime/terminalWriteCoalescer.ts @@ -0,0 +1,27 @@ +import type { Terminal as XTerm } from "@xterm/xterm"; + +import { createWriteCoalescer, type WriteCoalescer } from "./writeCoalescer.ts"; + +const terminalWriteCoalescers = new WeakMap(); + +export const enqueueCoalescedTerminalWrite = ( + term: XTerm, + data: string, + writeNow: (data: string) => void, +): void => { + let coalescer = terminalWriteCoalescers.get(term); + if (!coalescer) { + coalescer = createWriteCoalescer(writeNow); + terminalWriteCoalescers.set(term, coalescer); + } + coalescer.push(data); +}; + +export const flushTerminalWriteCoalescer = (term: XTerm): void => { + terminalWriteCoalescers.get(term)?.flushSync(); +}; + +export const resetTerminalWriteCoalescer = (term: XTerm): void => { + terminalWriteCoalescers.get(term)?.dispose(); + terminalWriteCoalescers.delete(term); +}; diff --git a/components/terminal/runtime/writeCoalescer.test.ts b/components/terminal/runtime/writeCoalescer.test.ts new file mode 100644 index 000000000..2811075a8 --- /dev/null +++ b/components/terminal/runtime/writeCoalescer.test.ts @@ -0,0 +1,104 @@ +import assert from "node:assert/strict"; +import { afterEach, beforeEach, test } from "node:test"; + +import { + createWriteCoalescer, + MAX_PENDING_WRITE_COALESCE_BYTES, +} from "./writeCoalescer.ts"; + +type FrameCallback = (time: number) => void; + +let frameCallbacks: Map; +let nextFrameId: number; +let originalRaf: typeof requestAnimationFrame; +let originalCancelRaf: typeof cancelAnimationFrame; + +const fireFrame = (): void => { + const callbacks = [...frameCallbacks.values()]; + frameCallbacks.clear(); + for (const callback of callbacks) { + callback(performance.now()); + } +}; + +beforeEach(() => { + frameCallbacks = new Map(); + nextFrameId = 1; + originalRaf = globalThis.requestAnimationFrame; + originalCancelRaf = globalThis.cancelAnimationFrame; + globalThis.requestAnimationFrame = (callback: FrameCallback) => { + const id = nextFrameId; + nextFrameId += 1; + frameCallbacks.set(id, callback); + return id; + }; + globalThis.cancelAnimationFrame = (id: number) => { + frameCallbacks.delete(id); + }; +}); + +afterEach(() => { + globalThis.requestAnimationFrame = originalRaf; + globalThis.cancelAnimationFrame = originalCancelRaf; +}); + +test("coalesces chunks in the same frame into one write", () => { + const writes: string[] = []; + const coalescer = createWriteCoalescer((data) => writes.push(data)); + + coalescer.push("foo"); + coalescer.push("bar"); + coalescer.push("baz"); + assert.equal(writes.length, 0); + + fireFrame(); + assert.deepEqual(writes, ["foobarbaz"]); +}); + +test("schedules a new frame for data arriving after a flush", () => { + const writes: string[] = []; + const coalescer = createWriteCoalescer((data) => writes.push(data)); + + coalescer.push("first"); + fireFrame(); + coalescer.push("second"); + fireFrame(); + + assert.deepEqual(writes, ["first", "second"]); +}); + +test("flushSync writes pending bytes immediately and cancels the scheduled frame", () => { + const writes: string[] = []; + const coalescer = createWriteCoalescer((data) => writes.push(data)); + + coalescer.push("pending"); + coalescer.flushSync(); + assert.deepEqual(writes, ["pending"]); + + fireFrame(); + assert.deepEqual(writes, ["pending"]); +}); + +test("flushes synchronously when pending bytes exceed the cap", () => { + const writes: string[] = []; + const coalescer = createWriteCoalescer((data) => writes.push(data)); + const chunk = "x".repeat(MAX_PENDING_WRITE_COALESCE_BYTES); + + coalescer.push(chunk); + coalescer.push("y"); + assert.equal(writes.length, 1); + assert.equal(writes[0]?.length, MAX_PENDING_WRITE_COALESCE_BYTES + 1); +}); + +test("dispose flushes remaining bytes and stops accepting new chunks", () => { + const writes: string[] = []; + const coalescer = createWriteCoalescer((data) => writes.push(data)); + + coalescer.push("tail"); + coalescer.dispose(); + assert.deepEqual(writes, ["tail"]); + + coalescer.push("ignored"); + fireFrame(); + assert.deepEqual(writes, ["tail"]); +}); diff --git a/components/terminal/runtime/writeCoalescer.ts b/components/terminal/runtime/writeCoalescer.ts new file mode 100644 index 000000000..8f6190353 --- /dev/null +++ b/components/terminal/runtime/writeCoalescer.ts @@ -0,0 +1,72 @@ +/** + * Coalesces PTY output chunks into one xterm.write() per animation frame. + * + * Agent CLIs (Codex, Claude Code) emit full-screen repaints as many small PTY + * chunks. Writing each chunk individually triggers an xterm parse/render cycle + * per chunk, which can tear TUI frames (missing box borders, clipped bottom + * rows). Batching to the display refresh rate keeps rendering atomic per frame. + * + * Ported from superset-sh/superset (issues #2241 / #2244): + * apps/desktop/src/renderer/lib/terminal/write-coalescer.ts + */ + +/** Pending-byte ceiling when rAF is throttled (hidden window). */ +export const MAX_PENDING_WRITE_COALESCE_BYTES = 1024 * 1024; + +export type WriteCoalescer = { + push(chunk: string): void; + /** Flush pending bytes synchronously before ordered writes (exit notices). */ + flushSync(): void; + dispose(): void; +}; + +export const createWriteCoalescer = (write: (data: string) => void): WriteCoalescer => { + let pending: string[] = []; + let pendingBytes = 0; + let frameId: number | null = null; + let disposed = false; + + const flushSync = (): void => { + if (frameId !== null) { + cancelAnimationFrame(frameId); + frameId = null; + } + if (pendingBytes === 0) { + return; + } + const batch = pending.length === 1 ? pending[0]! : pending.join(""); + pending = []; + pendingBytes = 0; + write(batch); + }; + + const push = (chunk: string): void => { + if (disposed || chunk.length === 0) { + return; + } + pending.push(chunk); + pendingBytes += chunk.length; + if (pendingBytes > MAX_PENDING_WRITE_COALESCE_BYTES) { + flushSync(); + return; + } + if (frameId === null) { + frameId = requestAnimationFrame(() => { + frameId = null; + flushSync(); + }); + } + }; + + return { + push, + flushSync, + dispose() { + if (disposed) { + return; + } + flushSync(); + disposed = true; + }, + }; +}; From 599c8ff2005fe1982443c3e150cf315483d2f07d Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 23:25:45 +0800 Subject: [PATCH 029/228] fix(telnet): dismiss connection overlay for silent no-auth sessions Mark Telnet as connected once the socket session attaches so devices that send no banner until client input no longer leave the connecting overlay blocking keyboard input (fixes #1632). Co-authored-by: Cursor --- ...eateTerminalSessionStarters.telnet.test.ts | 70 +++++++++++++++++++ .../runtime/createTerminalSessionStarters.ts | 8 +++ 2 files changed, 78 insertions(+) diff --git a/components/terminal/runtime/createTerminalSessionStarters.telnet.test.ts b/components/terminal/runtime/createTerminalSessionStarters.telnet.test.ts index f1e2c5517..d37d28ee1 100644 --- a/components/terminal/runtime/createTerminalSessionStarters.telnet.test.ts +++ b/components/terminal/runtime/createTerminalSessionStarters.telnet.test.ts @@ -237,6 +237,76 @@ test("startTelnet preserves an explicitly cleared telnet password", async () => assert.equal(capturedOptions.password, ""); }); +test("startTelnet marks the session connected before the server sends output", async () => { + let status = "connecting"; + let progressValue = 0; + + const terminalBackend = { + backendAvailable: () => true, + telnetAvailable: () => true, + moshAvailable: () => true, + localAvailable: () => true, + serialAvailable: () => true, + execAvailable: () => true, + startSSHSession: async () => "ssh-session", + startTelnetSession: async () => "telnet-session", + startMoshSession: async () => "mosh-session", + startLocalSession: async () => "local-session", + startSerialSession: async () => "serial-session", + execCommand: async () => ({}), + onSessionData: () => noop, + onSessionExit: () => noop, + onChainProgress: () => noop, + writeToSession: noop, + resizeSession: noop, + }; + + const ctx = { + host: { + id: "host-1", + label: "Example", + hostname: "example.test", + telnetPort: 23, + }, + keys: [], + resolvedChainHosts: [], + sessionId: "session-1", + terminalSettings: {}, + terminalBackend, + sessionRef: { current: null }, + hasConnectedRef: { current: false }, + hasRunStartupCommandRef: { current: false }, + disposeDataRef: { current: null }, + disposeExitRef: { current: null }, + fitAddonRef: { current: null }, + serializeAddonRef: { current: null }, + pendingAuthRef: { current: null }, + updateStatus: (next: string) => { status = next; }, + setStatus: noop, + setError: noop, + setNeedsAuth: noop, + setAuthRetryMessage: noop, + setAuthPassword: noop, + setProgressLogs: noop, + setProgressValue: (value: number) => { progressValue = value; }, + setChainProgress: noop, + }; + + const term = { + cols: 120, + rows: 32, + write: noop, + writeln: noop, + scrollToBottom: noop, + }; + + await createTerminalSessionStarters(ctx as never).startTelnet(term as never); + + assert.equal(status, "connected"); + assert.equal(progressValue, 100); + assert.equal(ctx.sessionRef.current, "telnet-session"); +}); + test("startTelnet rejects unreadable saved telnet passwords before connecting", async () => { let started = false; let error = ""; diff --git a/components/terminal/runtime/createTerminalSessionStarters.ts b/components/terminal/runtime/createTerminalSessionStarters.ts index fd4e87d6f..cdcdaf96d 100644 --- a/components/terminal/runtime/createTerminalSessionStarters.ts +++ b/components/terminal/runtime/createTerminalSessionStarters.ts @@ -649,6 +649,14 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex cleanupTelnetStartupWait(); disposeTelnetExit?.(); }; + + // Many telnet endpoints (especially no-auth devices) stay silent until + // the client sends data. Mark connected once the socket session is + // attached so the connection overlay dismisses and keyboard input works + // (issue #1632). + ctx.updateStatus("connected"); + ctx.setProgressValue(100); + if (waitsForAutoLogin) { return; } From 8083aece6648f9e946c16b0fc92b1f8d3ee61ae6 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 23:36:32 +0800 Subject: [PATCH 030/228] fix(ui): defer terminal layout suppress notifications to avoid render warnings Schedule layout suppress store updates on the next animation frame so tab switches and resize drags no longer trigger React setState-during-render warnings in TerminalComponent. Co-authored-by: Cursor --- .../state/terminalLayoutSuppressStore.test.ts | 23 +++++++++++++++++++ .../state/terminalLayoutSuppressStore.ts | 18 +++++++++++---- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/application/state/terminalLayoutSuppressStore.test.ts b/application/state/terminalLayoutSuppressStore.test.ts index d3291087e..211305005 100644 --- a/application/state/terminalLayoutSuppressStore.test.ts +++ b/application/state/terminalLayoutSuppressStore.test.ts @@ -14,3 +14,26 @@ test('terminalLayoutSuppressStore tracks nested begin/end', () => { terminalLayoutSuppressStore.end(); assert.equal(terminalLayoutSuppressStore.getActive(), false); }); + +test('terminalLayoutSuppressStore defers subscriber notifications', async () => { + let notifyCount = 0; + const unsubscribe = terminalLayoutSuppressStore.subscribe(() => { + notifyCount += 1; + }); + + terminalLayoutSuppressStore.begin(); + assert.equal(notifyCount, 0, 'begin should not notify synchronously'); + assert.equal(terminalLayoutSuppressStore.getActive(), true); + + await new Promise((resolve) => setTimeout(resolve, 0)); + assert.equal(notifyCount, 1, 'begin should notify after the current turn'); + + terminalLayoutSuppressStore.end(); + assert.equal(notifyCount, 1, 'end should not notify synchronously'); + assert.equal(terminalLayoutSuppressStore.getActive(), false); + + await new Promise((resolve) => setTimeout(resolve, 0)); + assert.equal(notifyCount, 2, 'end should notify after the current turn'); + + unsubscribe(); +}); diff --git a/application/state/terminalLayoutSuppressStore.ts b/application/state/terminalLayoutSuppressStore.ts index 164152a73..f26dc4924 100644 --- a/application/state/terminalLayoutSuppressStore.ts +++ b/application/state/terminalLayoutSuppressStore.ts @@ -4,9 +4,19 @@ type Listener = () => void; let suppressDepth = 0; const listeners = new Set(); +let notifyRafId: number | null = null; -function emit() { - listeners.forEach((listener) => listener()); +const scheduleFrame = + typeof requestAnimationFrame === 'function' + ? requestAnimationFrame + : (cb: () => void) => setTimeout(cb, 0) as unknown as number; + +function scheduleEmit() { + if (notifyRafId !== null) return; + notifyRafId = scheduleFrame(() => { + notifyRafId = null; + listeners.forEach((listener) => listener()); + }); } export const terminalLayoutSuppressStore = { @@ -19,14 +29,14 @@ export const terminalLayoutSuppressStore = { begin: () => { suppressDepth += 1; - emit(); + scheduleEmit(); }, end: () => { const wasActive = suppressDepth > 0; suppressDepth = Math.max(0, suppressDepth - 1); if (wasActive) { - emit(); + scheduleEmit(); } }, }; From 53328ca50d2cdd5128d19bc2824cae9bec418ef2 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Wed, 24 Jun 2026 23:52:03 +0800 Subject: [PATCH 031/228] feat(terminal): optimize hibernate wake for large buffers Add chunked replay, deferred WebGL during restore, alt-screen hibernate policies, soft-hide LRU, two-phase viewport/scrollback snapshots, and a main-process headless xterm mirror for faster wake serialization. Co-authored-by: Cursor --- application/i18n/locales/en/core.ts | 10 ++ application/i18n/locales/zh-CN/terminal.ts | 10 ++ .../state/terminalHiddenRendererStore.test.ts | 14 ++ .../state/terminalHiddenRendererStore.ts | 55 ++++++ application/state/terminalMirrorSnapshot.ts | 12 ++ application/state/useTerminalBackend.ts | 12 ++ components/Terminal.tsx | 161 ++++++++++++++--- .../settings/tabs/SettingsTerminalTab.tsx | 66 +++++++ .../terminal/runtime/createXTermRuntime.ts | 27 ++- .../terminal/terminalHibernateRuntime.test.ts | 28 ++- .../terminal/terminalHibernateRuntime.ts | 166 +++++++++++++++--- components/terminal/terminalReplay.test.ts | 22 +++ components/terminal/terminalReplay.ts | 54 ++++++ components/terminal/terminalRuntimeMount.ts | 32 +++- components/terminal/terminalSerialize.ts | 21 +++ components/terminal/terminalSerializeWasm.ts | 33 ++++ .../terminal/useTerminalHibernateEffect.ts | 35 +++- domain/models/terminal.ts | 27 ++- .../terminalHibernate.optimizations.test.ts | 33 ++++ domain/terminalHibernate.ts | 78 ++++++++ electron/bridges/emitTerminalSessionData.cjs | 48 +++++ electron/bridges/sshBridge/startSession.cjs | 16 +- electron/bridges/terminalBridge.cjs | 16 +- electron/bridges/terminalBridge/etSession.cjs | 6 +- .../bridges/terminalBridge/moshSession.cjs | 7 +- .../bridges/terminalBridge/telnetSession.cjs | 4 +- electron/bridges/terminalHeadlessMirror.cjs | 100 +++++++++++ .../bridges/terminalHeadlessMirror.test.cjs | 21 +++ electron/main/registerBridges.cjs | 2 + electron/preload/api.cjs | 3 + package-lock.json | 109 +++++------- package.json | 1 + types/global/netcatty-bridge-session.d.ts | 4 + 33 files changed, 1107 insertions(+), 126 deletions(-) create mode 100644 application/state/terminalHiddenRendererStore.test.ts create mode 100644 application/state/terminalHiddenRendererStore.ts create mode 100644 application/state/terminalMirrorSnapshot.ts create mode 100644 components/terminal/terminalReplay.test.ts create mode 100644 components/terminal/terminalReplay.ts create mode 100644 components/terminal/terminalSerialize.ts create mode 100644 components/terminal/terminalSerializeWasm.ts create mode 100644 domain/terminalHibernate.optimizations.test.ts create mode 100644 electron/bridges/emitTerminalSessionData.cjs create mode 100644 electron/bridges/terminalHeadlessMirror.cjs create mode 100644 electron/bridges/terminalHeadlessMirror.test.cjs diff --git a/application/i18n/locales/en/core.ts b/application/i18n/locales/en/core.ts index dbc3ee61c..9f131e9a4 100644 --- a/application/i18n/locales/en/core.ts +++ b/application/i18n/locales/en/core.ts @@ -483,6 +483,16 @@ export const enCoreMessages: Messages = { 'settings.terminal.rendering.hibernateHiddenTabs.desc': 'Dispose the terminal renderer for off-screen tabs to save memory while keeping the SSH session connected. Skipped during file transfers.', 'settings.terminal.rendering.hibernateHiddenTabsDelay': 'Hibernate delay', 'settings.terminal.rendering.hibernateHiddenTabsDelay.desc': 'How long a tab must stay off-screen before its renderer is released (5–600 seconds).', + 'settings.terminal.rendering.hibernateSkipAltScreen': 'Skip hibernate on full-screen apps', + 'settings.terminal.rendering.hibernateSkipAltScreen.desc': 'Keep the terminal renderer alive while vim, htop, or agent TUIs own the alternate screen buffer.', + 'settings.terminal.rendering.hibernateKeepRendererCount': 'Keep hidden renderers', + 'settings.terminal.rendering.hibernateKeepRendererCount.desc': 'How many off-screen tabs keep their renderer alive (WebGL suspended) before full hibernate.', + 'settings.terminal.rendering.hibernateUseHeadlessMirror': 'Main-process terminal mirror', + 'settings.terminal.rendering.hibernateUseHeadlessMirror.desc': 'Mirror PTY output in a headless xterm on the main process for faster wake snapshots.', + 'settings.terminal.rendering.hibernateReplayChunkBytes': 'Wake replay chunk size', + 'settings.terminal.rendering.hibernateReplayChunkBytes.desc': 'Bytes replayed per animation frame when restoring a hibernated terminal (4–64 KB).', + 'settings.terminal.rendering.hibernatePreferWasmSerialize': 'Prefer WASM serialize', + 'settings.terminal.rendering.hibernatePreferWasmSerialize.desc': 'Use WASM terminal serialization when available; falls back to the JS serializer.', // Settings > Terminal > Workspace Focus Indicator 'settings.terminal.section.workspaceFocus': 'Workspace Focus Indicator', diff --git a/application/i18n/locales/zh-CN/terminal.ts b/application/i18n/locales/zh-CN/terminal.ts index 0f1cadd6a..c57df9e7a 100644 --- a/application/i18n/locales/zh-CN/terminal.ts +++ b/application/i18n/locales/zh-CN/terminal.ts @@ -355,6 +355,16 @@ export const zhCNTerminalMessages: Messages = { 'settings.terminal.rendering.hibernateHiddenTabs.desc': '标签页离开视野后释放终端渲染器以节省内存,SSH 连接保持不断。文件传输期间不会休眠。', 'settings.terminal.rendering.hibernateHiddenTabsDelay': '休眠延迟', 'settings.terminal.rendering.hibernateHiddenTabsDelay.desc': '标签页离开视野多久后释放渲染器(5–600 秒)。', + 'settings.terminal.rendering.hibernateSkipAltScreen': '全屏 TUI 跳过休眠', + 'settings.terminal.rendering.hibernateSkipAltScreen.desc': 'vim、htop 或 Agent TUI 占用 alternate screen 时保持终端渲染器,避免慢恢复。', + 'settings.terminal.rendering.hibernateKeepRendererCount': '保留隐藏渲染器数量', + 'settings.terminal.rendering.hibernateKeepRendererCount.desc': '多少个不可见标签页仅暂停 WebGL、不销毁 xterm,超出后才完整休眠。', + 'settings.terminal.rendering.hibernateUseHeadlessMirror': '主进程终端镜像', + 'settings.terminal.rendering.hibernateUseHeadlessMirror.desc': '在主进程用 headless xterm 镜像 PTY 输出,加快休眠唤醒时的快照获取。', + 'settings.terminal.rendering.hibernateReplayChunkBytes': '唤醒分片大小', + 'settings.terminal.rendering.hibernateReplayChunkBytes.desc': '恢复休眠终端时每帧回放的 ANSI 字节数(4–64 KB)。', + 'settings.terminal.rendering.hibernatePreferWasmSerialize': '优先 WASM 序列化', + 'settings.terminal.rendering.hibernatePreferWasmSerialize.desc': '在可用时使用 WASM 终端序列化,否则回退到 JS SerializeAddon。', // Settings > Terminal > Workspace Focus Indicator 'settings.terminal.section.workspaceFocus': '工作区焦点提示', diff --git a/application/state/terminalHiddenRendererStore.test.ts b/application/state/terminalHiddenRendererStore.test.ts new file mode 100644 index 000000000..42f39da97 --- /dev/null +++ b/application/state/terminalHiddenRendererStore.test.ts @@ -0,0 +1,14 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { terminalHiddenRendererStore } from "./terminalHiddenRendererStore.ts"; + +test("terminalHiddenRendererStore evicts oldest soft-hidden session", () => { + terminalHiddenRendererStore.clearSoftHidden("a"); + terminalHiddenRendererStore.clearSoftHidden("b"); + terminalHiddenRendererStore.markSoftHidden("a"); + terminalHiddenRendererStore.markSoftHidden("b"); + assert.equal(terminalHiddenRendererStore.pickEvictionCandidate(2), "a"); + terminalHiddenRendererStore.clearSoftHidden("a"); + terminalHiddenRendererStore.clearSoftHidden("b"); +}); diff --git a/application/state/terminalHiddenRendererStore.ts b/application/state/terminalHiddenRendererStore.ts new file mode 100644 index 000000000..8c42ce4b3 --- /dev/null +++ b/application/state/terminalHiddenRendererStore.ts @@ -0,0 +1,55 @@ +type Listener = () => void; + +const softHiddenSessions = new Map(); +const listeners = new Set(); +let evictionRequestSessionId: string | null = null; + +function emit(): void { + listeners.forEach((listener) => listener()); +} + +export const terminalHiddenRendererStore = { + getSoftHiddenCount: () => softHiddenSessions.size, + + isSoftHidden: (sessionId: string) => softHiddenSessions.has(sessionId), + + markSoftHidden: (sessionId: string) => { + softHiddenSessions.set(sessionId, Date.now()); + emit(); + }, + + clearSoftHidden: (sessionId: string) => { + if (!softHiddenSessions.delete(sessionId)) return; + emit(); + }, + + /** Returns the oldest soft-hidden session id when over the keep limit. */ + pickEvictionCandidate: (keepCount: number): string | null => { + if (softHiddenSessions.size < keepCount) return null; + let oldestId: string | null = null; + let oldestTs = Number.POSITIVE_INFINITY; + for (const [sessionId, ts] of softHiddenSessions) { + if (ts < oldestTs) { + oldestTs = ts; + oldestId = sessionId; + } + } + return oldestId; + }, + + requestEviction: (sessionId: string) => { + evictionRequestSessionId = sessionId; + emit(); + }, + + consumeEvictionRequest: (sessionId: string): boolean => { + if (evictionRequestSessionId !== sessionId) return false; + evictionRequestSessionId = null; + return true; + }, + + subscribe: (listener: Listener) => { + listeners.add(listener); + return () => listeners.delete(listener); + }, +}; diff --git a/application/state/terminalMirrorSnapshot.ts b/application/state/terminalMirrorSnapshot.ts new file mode 100644 index 000000000..026be4ee0 --- /dev/null +++ b/application/state/terminalMirrorSnapshot.ts @@ -0,0 +1,12 @@ +import type { TerminalHibernateSnapshot } from "../../components/terminal/terminalHibernateRuntime"; + +export function mirrorSnapshotToHibernateSnapshot( + mirror: { snapshot: string; alternateScreen: boolean }, +): TerminalHibernateSnapshot { + return { + snapshot: mirror.snapshot, + viewportSnapshot: mirror.snapshot, + scrollbackSnapshot: "", + alternateScreen: mirror.alternateScreen, + }; +} diff --git a/application/state/useTerminalBackend.ts b/application/state/useTerminalBackend.ts index f420214ad..6b658ff54 100644 --- a/application/state/useTerminalBackend.ts +++ b/application/state/useTerminalBackend.ts @@ -100,6 +100,16 @@ export const useTerminalBackend = () => { return bridge.setSessionEncoding(sessionId, encoding); }, []); + const getTerminalMirrorSnapshot = useCallback(async (sessionId: string) => { + const bridge = netcattyBridge.get(); + if (!bridge?.getTerminalMirrorSnapshot) return null; + try { + return await bridge.getTerminalMirrorSnapshot(sessionId); + } catch { + return null; + } + }, []); + const onSessionData = useCallback((sessionId: string, cb: (data: string) => void) => { const bridge = netcattyBridge.get(); if (!bridge?.onSessionData) throw new Error("onSessionData unavailable"); @@ -328,6 +338,7 @@ export const useTerminalBackend = () => { setSessionFlowPaused, closeSession, setSessionEncoding, + getTerminalMirrorSnapshot, onSessionData, onSessionExit, onTelnetAutoLoginComplete, @@ -376,6 +387,7 @@ export const useTerminalBackend = () => { setSessionFlowPaused, closeSession, setSessionEncoding, + getTerminalMirrorSnapshot, onSessionData, onSessionExit, onTelnetAutoLoginComplete, diff --git a/components/Terminal.tsx b/components/Terminal.tsx index 7c72be4c3..c98521575 100644 --- a/components/Terminal.tsx +++ b/components/Terminal.tsx @@ -88,14 +88,22 @@ import { useTerminalEffects } from "./terminal/useTerminalEffects"; import { useTerminalHibernateEffect } from "./terminal/useTerminalHibernateEffect"; import { appendHibernatePendingBuffer, + isTerminalAlternateScreenActive, serializeTerminalForHibernate, } from "./terminal/terminalHibernateRuntime"; import { isTerminalFileTransferActive, + resolveHibernateKeepRendererCount, + resolveHibernatePreferWasmSerialize, + resolveHibernateSkipAltScreen, + resolveHibernateUseHeadlessMirror, resolveTerminalHibernateDelayMs, resolveTerminalHibernateEnabled, + resolveTerminalHibernateReplayChunkBytes, type TerminalHibernateWakePayload, } from "../domain/terminalHibernate"; +import { terminalHiddenRendererStore } from "../application/state/terminalHiddenRendererStore"; +import { mirrorSnapshotToHibernateSnapshot } from "../application/state/terminalMirrorSnapshot"; import { wakeTerminalFromHibernate, type TerminalRuntimeRefs, @@ -230,8 +238,12 @@ const TerminalComponent: React.FC = ({ const disposeDataRef = useRef<(() => void) | null>(null); const disposeExitRef = useRef<(() => void) | null>(null); const hibernatedRef = useRef(false); + const softHiddenRef = useRef(false); const hasRuntimeRef = useRef(false); const hibernateSnapshotRef = useRef(""); + const hibernateViewportSnapshotRef = useRef(""); + const hibernateScrollbackSnapshotRef = useRef(""); + const hibernateMirrorPreferredRef = useRef(false); const hibernatePendingBufferRef = useRef(""); const hibernateAlternateScreenRef = useRef(false); const wakeInProgressRef = useRef(false); @@ -827,30 +839,17 @@ const TerminalComponent: React.FC = ({ } sessionRef.current = null; hibernatedRef.current = false; + softHiddenRef.current = false; hibernateSnapshotRef.current = ""; + hibernateViewportSnapshotRef.current = ""; + hibernateScrollbackSnapshotRef.current = ""; + hibernateMirrorPreferredRef.current = false; hibernatePendingBufferRef.current = ""; hibernateAlternateScreenRef.current = false; + terminalHiddenRendererStore.clearSoftHidden(sessionId); }, [handleTerminalDataCaptureOnce, sessionId, terminalBackend]); - const hibernateRuntime = useCallback(() => { - if (hibernatedRef.current || !termRef.current || !serializeAddonRef.current) return; - const backendId = sessionRef.current; - if (!backendId) return; - - const { snapshot, alternateScreen } = serializeTerminalForHibernate( - termRef.current, - serializeAddonRef.current, - ); - if (alternateScreen && snapshot.length === 0) { - logger.info("[Terminal] Skipping hibernate: alternate screen snapshot unavailable", { sessionId }); - return; - } - - hibernateSnapshotRef.current = snapshot; - hibernateAlternateScreenRef.current = alternateScreen; - isBootActiveRef.current = false; - disposeRuntimeOnly(); - + const beginHibernatedSessionListeners = useCallback((backendId: string) => { disposeDataRef.current?.(); hibernatePendingBufferRef.current = ""; disposeDataRef.current = terminalBackend.onSessionData(backendId, (chunk) => { @@ -873,14 +872,107 @@ const TerminalComponent: React.FC = ({ ); onSessionExit?.(sessionId, evt); }); + }, [onSessionExit, sessionId, terminalBackend]); + const applyHibernateSnapshot = useCallback(( + snapshot: { + snapshot: string; + viewportSnapshot: string; + scrollbackSnapshot: string; + alternateScreen: boolean; + }, + mirrorPreferred: boolean, + ) => { + hibernateSnapshotRef.current = snapshot.snapshot; + hibernateViewportSnapshotRef.current = snapshot.viewportSnapshot; + hibernateScrollbackSnapshotRef.current = snapshot.scrollbackSnapshot; + hibernateAlternateScreenRef.current = snapshot.alternateScreen; + hibernateMirrorPreferredRef.current = mirrorPreferred; + }, []); + + const fullHibernateRuntime = useCallback(async () => { + if (hibernatedRef.current || softHiddenRef.current || !termRef.current || !serializeAddonRef.current) return; + const backendId = sessionRef.current; + if (!backendId) return; + + terminalHiddenRendererStore.clearSoftHidden(sessionId); + softHiddenRef.current = false; + + let snapshot = await serializeTerminalForHibernate( + termRef.current, + serializeAddonRef.current, + { preferWasm: resolveHibernatePreferWasmSerialize(terminalSettings) }, + ); + let mirrorPreferred = false; + + if (resolveHibernateUseHeadlessMirror(terminalSettings)) { + const mirror = await terminalBackend.getTerminalMirrorSnapshot(backendId); + if (mirror && mirror.snapshot.length > 0) { + snapshot = mirrorSnapshotToHibernateSnapshot(mirror); + mirrorPreferred = true; + } + } + + if (snapshot.alternateScreen && snapshot.snapshot.length === 0) { + logger.info("[Terminal] Skipping hibernate: alternate screen snapshot unavailable", { sessionId }); + return; + } + + applyHibernateSnapshot(snapshot, mirrorPreferred); + isBootActiveRef.current = false; + disposeRuntimeOnly(); + beginHibernatedSessionListeners(backendId); hibernatedRef.current = true; logger.info("[Terminal] Hibernated runtime", { sessionId, snapshotChars: hibernateSnapshotRef.current.length, - alternateScreen, + viewportChars: hibernateViewportSnapshotRef.current.length, + scrollbackChars: hibernateScrollbackSnapshotRef.current.length, + alternateScreen: snapshot.alternateScreen, + mirrorPreferred, }); - }, [onSessionExit, sessionId, terminalBackend]); + }, [ + applyHibernateSnapshot, + beginHibernatedSessionListeners, + sessionId, + terminalBackend, + terminalSettings, + ]); + + const hideRuntimeOnly = useCallback(() => { + if (hibernatedRef.current || softHiddenRef.current || !hasRuntimeRef.current) return; + xtermRuntimeRef.current?.suspendWebglRenderer(); + terminalHiddenRendererStore.markSoftHidden(sessionId); + softHiddenRef.current = true; + logger.info("[Terminal] Soft-hidden runtime", { sessionId }); + }, [sessionId]); + + const hibernateRuntime = useCallback(() => { + if (hibernatedRef.current || softHiddenRef.current || !termRef.current) return; + + if ( + isTerminalAlternateScreenActive(termRef.current) + && resolveHibernateSkipAltScreen(terminalSettings) + ) { + logger.info("[Terminal] Skipping hibernate: alternate screen active", { sessionId }); + return; + } + + const keepCount = resolveHibernateKeepRendererCount(terminalSettings); + if (keepCount > 0 && terminalHiddenRendererStore.getSoftHiddenCount() < keepCount) { + hideRuntimeOnly(); + return; + } + + if (keepCount > 0) { + const victim = terminalHiddenRendererStore.pickEvictionCandidate(keepCount); + if (victim && victim !== sessionId) { + terminalHiddenRendererStore.requestEviction(victim); + } + } + + void fullHibernateRuntime(); + }, [fullHibernateRuntime, hideRuntimeOnly, sessionId, terminalSettings]); const terminalRuntimeRefs = useMemo(() => ({ xtermRuntimeRef, @@ -1602,6 +1694,25 @@ const TerminalComponent: React.FC = ({ const safeFitRef = useRef(safeFit); safeFitRef.current = safeFit; + const wakeSoftHiddenRuntime = useCallback(() => { + if (!softHiddenRef.current) return; + terminalHiddenRendererStore.clearSoftHidden(sessionId); + softHiddenRef.current = false; + xtermRuntimeRef.current?.ensureWebglRenderer(); + xtermRuntimeRef.current?.clearTextureAtlas(); + safeFitRef.current({ force: true }); + }, [sessionId]); + + useEffect(() => { + return terminalHiddenRendererStore.subscribe(() => { + if (!terminalHiddenRendererStore.consumeEvictionRequest(sessionId)) return; + if (!softHiddenRef.current || hibernatedRef.current) return; + softHiddenRef.current = false; + terminalHiddenRendererStore.clearSoftHidden(sessionId); + void fullHibernateRuntime(); + }); + }, [fullHibernateRuntime, sessionId]); + const wakeFromHibernateRuntime = useCallback(( getPayload: () => TerminalHibernateWakePayload, options: { sessionConnected: boolean }, @@ -1656,13 +1767,14 @@ const TerminalComponent: React.FC = ({ isBootActiveRef, sessionId, updateStatus: (next) => updateStatusRef.current(next), + replayChunkBytes: resolveTerminalHibernateReplayChunkBytes(terminalSettings), }).then((ok) => ok).catch((err) => { logger.error("[Terminal] Failed to resume from hibernate", err); return false; }).finally(() => { wakeInProgressRef.current = false; }); - }, [sessionId, terminalRuntimeRefs, resizeSession]); + }, [sessionId, terminalRuntimeRefs, resizeSession, terminalSettings]); useTerminalHibernateEffect({ sessionId, @@ -1679,11 +1791,16 @@ const TerminalComponent: React.FC = ({ isDraggingOver, }), hibernatedRef, + softHiddenRef, hibernatePendingBufferRef, hibernateSnapshotRef, + hibernateViewportSnapshotRef, + hibernateScrollbackSnapshotRef, + hibernateMirrorPreferredRef, hibernateAlternateScreenRef, hasRuntimeRef, onHibernate: hibernateRuntime, + onSoftHideWake: wakeSoftHiddenRuntime, onWake: wakeFromHibernateRuntime, }); diff --git a/components/settings/tabs/SettingsTerminalTab.tsx b/components/settings/tabs/SettingsTerminalTab.tsx index 8c2fa8449..528cd9ef1 100644 --- a/components/settings/tabs/SettingsTerminalTab.tsx +++ b/components/settings/tabs/SettingsTerminalTab.tsx @@ -989,6 +989,7 @@ function SettingsTerminalTab(props: { /> {terminalSettings.hibernateHiddenTabs && ( + <> {t("settings.terminal.serverStats.seconds")}
+ + updateTerminalSetting("hibernateSkipAltScreen", v)} + /> + + + { + const val = parseInt(e.target.value, 10); + if (!Number.isNaN(val) && val >= 0 && val <= 12) { + updateTerminalSetting("hibernateKeepRendererCount", val); + } + }} + className="w-20" + /> + + + updateTerminalSetting("hibernateUseHeadlessMirror", v)} + /> + + + { + const val = parseInt(e.target.value, 10); + if (!Number.isNaN(val) && val >= 4096 && val <= 65536) { + updateTerminalSetting("hibernateReplayChunkBytes", val); + } + }} + className="w-28" + /> + + + updateTerminalSetting("hibernatePreferWasmSerialize", v)} + /> + + )}
{/* Autocomplete */} diff --git a/components/terminal/runtime/createXTermRuntime.ts b/components/terminal/runtime/createXTermRuntime.ts index f25ebd25a..1cf02a836 100644 --- a/components/terminal/runtime/createXTermRuntime.ts +++ b/components/terminal/runtime/createXTermRuntime.ts @@ -126,6 +126,8 @@ export type XTermRuntime = { * active. Called when a deferred pane first becomes visible. */ ensureWebglRenderer: () => void; + /** Drop the WebGL addon while keeping the terminal alive (soft-hide). */ + suspendWebglRenderer: () => void; }; export type CreateXTermRuntimeContext = { @@ -212,6 +214,8 @@ export type CreateXTermRuntimeContext = { // background tabs) to avoid spinning up many WebGL contexts at once. Defaults // to visible (immediate WebGL) when omitted. initiallyVisible?: boolean; + /** When true, keep the DOM renderer until replay completes (hibernate wake). */ + deferWebglUntilReplayComplete?: boolean; }; const detectPlatform = (): XTermPlatform => { @@ -439,6 +443,8 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime webglAddon.onContextLoss(() => { logger.warn("[XTerm] WebGL context loss detected, disposing addon"); webglAddon?.dispose(); + webglAddon = null; + webglLoaded = false; }); term.loadAddon(webglAddon); webglLoaded = true; @@ -451,6 +457,22 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime scopedWindow.__xtermWebGLLoaded = webglLoaded; }; + const suspendWebglRenderer = () => { + if (!webglAddon) { + webglLoaded = false; + scopedWindow.__xtermWebGLLoaded = false; + return; + } + try { + webglAddon.dispose(); + } catch (webglErr) { + logger.warn("[XTerm] Failed to suspend WebGL renderer", webglErr); + } + webglAddon = null; + webglLoaded = false; + scopedWindow.__xtermWebGLLoaded = false; + }; + if (!performanceConfig.useWebGLAddon) { logger.info( "[XTerm] Skipping WebGL addon (DOM preferred for low-memory devices)", @@ -459,9 +481,9 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime shouldDeferWebglUntilVisible({ useWebGLAddon: performanceConfig.useWebGLAddon, initiallyVisible: ctx.initiallyVisible ?? true, - }) + }) || ctx.deferWebglUntilReplayComplete ) { - logger.info("[XTerm] Deferring WebGL addon until pane becomes visible"); + logger.info("[XTerm] Deferring WebGL addon until pane becomes visible or replay completes"); } else { loadWebglRenderer(); } @@ -1253,6 +1275,7 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime keywordHighlighter, clearTextureAtlas: clearWebglTextureAtlas, ensureWebglRenderer: loadWebglRenderer, + suspendWebglRenderer, dispose: () => { ctx.container.removeEventListener( "wheel", diff --git a/components/terminal/terminalHibernateRuntime.test.ts b/components/terminal/terminalHibernateRuntime.test.ts index 5ab7afe74..9e32efbf7 100644 --- a/components/terminal/terminalHibernateRuntime.test.ts +++ b/components/terminal/terminalHibernateRuntime.test.ts @@ -8,9 +8,13 @@ import { serializeTerminalForHibernate, } from "./terminalHibernateRuntime.ts"; -const createFakeTerm = (bufferType: "normal" | "alternate") => ({ +const createFakeTerm = (bufferType: "normal" | "alternate", rows = 24, length = 30) => ({ + rows, buffer: { - active: { type: bufferType }, + active: { + type: bufferType, + length, + }, }, }); @@ -56,15 +60,31 @@ test("refreshTerminalViewport refreshes the full viewport", () => { assert.deepEqual(refreshed, [0, 23]); }); -test("serializeTerminalForHibernate preserves alternate screen when serialize throws", () => { +test("serializeTerminalForHibernate preserves alternate screen when serialize throws", async () => { const term = createFakeTerm("alternate"); const serializeAddon = { serialize: () => { throw new Error("serialize failed"); }, }; - assert.deepEqual(serializeTerminalForHibernate(term as never, serializeAddon as never), { + assert.deepEqual(await serializeTerminalForHibernate(term as never, serializeAddon as never), { snapshot: "", + viewportSnapshot: "", + scrollbackSnapshot: "", alternateScreen: true, }); }); + +test("serializeTerminalForHibernate requests viewport-only range on alternate screen", async () => { + let capturedOptions: Record | undefined; + const term = createFakeTerm("alternate", 24); + const serializeAddon = { + serialize: (options?: Record) => { + capturedOptions = options; + return "alt-viewport"; + }, + }; + const result = await serializeTerminalForHibernate(term as never, serializeAddon as never); + assert.equal(result.snapshot, "alt-viewport"); + assert.deepEqual(capturedOptions?.range, { start: 0, end: 23 }); +}); diff --git a/components/terminal/terminalHibernateRuntime.ts b/components/terminal/terminalHibernateRuntime.ts index 4468b0c61..b63d73717 100644 --- a/components/terminal/terminalHibernateRuntime.ts +++ b/components/terminal/terminalHibernateRuntime.ts @@ -8,6 +8,12 @@ import { type TerminalHibernateWakePayload, } from "../../domain/terminalHibernate"; import type { XTermRuntime } from "./runtime/createXTermRuntime"; +import { serializeTerminalBuffer } from "./terminalSerialize"; +import { + writeTerminalPayloadChunked, + writeTerminalReplaySequence, + type TerminalReplayOptions, +} from "./terminalReplay"; export function isTerminalAlternateScreenActive(term: XTerm): boolean { return (term.buffer.active as { type?: string }).type === "alternate"; @@ -26,23 +32,104 @@ export function resolveHibernateSerializeOptions(term: XTerm): { }; } -export function serializeTerminalForHibernate(term: XTerm, serializeAddon: SerializeAddon): { +export type TerminalHibernateSnapshot = { snapshot: string; + viewportSnapshot: string; + scrollbackSnapshot: string; alternateScreen: boolean; -} { +}; + +function resolveActiveBufferLength(term: XTerm): number { + return term.buffer.active.length; +} + +async function serializeWithOptions( + term: XTerm, + serializeAddon: SerializeAddon, + options: Record, + preferWasm: boolean, +): Promise { try { - const { excludeAltBuffer, excludeModes, alternateScreen } = resolveHibernateSerializeOptions(term); - const raw = serializeAddon.serialize({ + return await serializeTerminalBuffer({ + term, + serializeAddon, + options, + preferWasm, + }); + } catch { + return ""; + } +} + +export async function serializeTerminalForHibernate( + term: XTerm, + serializeAddon: SerializeAddon, + options: { preferWasm?: boolean } = {}, +): Promise { + const { excludeAltBuffer, excludeModes, alternateScreen } = resolveHibernateSerializeOptions(term); + const preferWasm = options.preferWasm === true; + const rows = Math.max(1, term.rows); + const bufferLength = resolveActiveBufferLength(term); + + try { + if (alternateScreen) { + const endRow = Math.max(0, rows - 1); + const viewportSnapshot = capHibernateBufferByLines( + await serializeWithOptions(term, serializeAddon, { + excludeAltBuffer: false, + excludeModes: false, + range: { start: 0, end: endRow }, + }, preferWasm), + rows, + ); + return { + snapshot: viewportSnapshot, + viewportSnapshot, + scrollbackSnapshot: "", + alternateScreen: true, + }; + } + + const viewportStart = Math.max(0, bufferLength - rows); + const viewportEnd = Math.max(0, bufferLength - 1); + const viewportSnapshot = await serializeWithOptions(term, serializeAddon, { excludeAltBuffer, excludeModes, - }); + range: { start: viewportStart, end: viewportEnd }, + }, preferWasm); + + let scrollbackSnapshot = ""; + if (viewportStart > 0) { + const scrollbackStart = Math.max(0, viewportStart - TERMINAL_HIBERNATE_SNAPSHOT_MAX_LINES); + scrollbackSnapshot = capHibernateBufferByLines( + await serializeWithOptions(term, serializeAddon, { + excludeAltBuffer, + excludeModes, + range: { start: scrollbackStart, end: viewportStart - 1 }, + }, preferWasm), + TERMINAL_HIBERNATE_SNAPSHOT_MAX_LINES, + ); + } + + const snapshot = capHibernateBufferByLines( + await serializeWithOptions(term, serializeAddon, { + excludeAltBuffer, + excludeModes, + }, preferWasm), + TERMINAL_HIBERNATE_SNAPSHOT_MAX_LINES, + ); + return { - snapshot: capHibernateBufferByLines(raw, TERMINAL_HIBERNATE_SNAPSHOT_MAX_LINES), - alternateScreen, + snapshot, + viewportSnapshot, + scrollbackSnapshot, + alternateScreen: false, }; } catch { return { snapshot: "", + viewportSnapshot: "", + scrollbackSnapshot: "", alternateScreen: isTerminalAlternateScreenActive(term), }; } @@ -52,35 +139,59 @@ export function appendHibernatePendingBuffer(current: string, chunk: string): st return capHibernateBuffer(current + chunk); } -const writeTerminalPayload = (term: XTerm, data: string): Promise => { - if (!data) return Promise.resolve(); - return new Promise((resolve) => { - term.write(data, () => resolve()); - }); -}; - export function refreshTerminalViewport(term: XTerm): void { const endRow = term.rows - 1; if (endRow < 0) return; term.refresh(0, endRow); } -export async function appendTerminalReplayData(term: XTerm, data: string): Promise { - return writeTerminalPayload(term, data); +export async function appendTerminalReplayData( + term: XTerm, + data: string, + replayOptions?: TerminalReplayOptions, +): Promise { + return writeTerminalPayloadChunked(term, data, replayOptions); } +export type ApplyHibernateWakeOptions = { + replayOptions?: TerminalReplayOptions; + deferWebgl?: boolean; +}; + +const scheduleIdle = (callback: () => void): void => { + if (typeof requestIdleCallback === "function") { + requestIdleCallback(() => callback(), { timeout: 500 }); + return; + } + setTimeout(callback, 0); +}; + export async function applyHibernateWakeToTerminal( term: XTerm, runtime: XTermRuntime, payload: TerminalHibernateWakePayload, + options: ApplyHibernateWakeOptions = {}, ): Promise { - await writeTerminalPayload(term, payload.snapshot); - await writeTerminalPayload(term, payload.pendingBuffer); - runtime.ensureWebglRenderer(); - runtime.clearTextureAtlas(); + const replayOptions = options.replayOptions; + const viewport = payload.viewportSnapshot ?? payload.snapshot; + const scrollback = payload.scrollbackSnapshot ?? ""; + + await writeTerminalReplaySequence(term, [viewport, payload.pendingBuffer], replayOptions); + + if (!options.deferWebgl) { + runtime.ensureWebglRenderer(); + runtime.clearTextureAtlas(); + } + if (payload.alternateScreen) { refreshTerminalViewport(term); } + + if (scrollback) { + scheduleIdle(() => { + void writeTerminalPayloadChunked(term, scrollback, replayOptions); + }); + } } export function nudgeAlternateScreenRedraw(term: XTerm): void { @@ -93,3 +204,18 @@ export function nudgeAlternateScreenRedraw(term: XTerm): void { refreshTerminalViewport(term); } } + +export function buildHibernateWakePayload( + snapshot: TerminalHibernateSnapshot, + pendingBuffer: string, + mirrorPreferred = false, +): TerminalHibernateWakePayload { + return { + snapshot: snapshot.snapshot, + viewportSnapshot: snapshot.viewportSnapshot, + scrollbackSnapshot: snapshot.scrollbackSnapshot, + pendingBuffer, + alternateScreen: snapshot.alternateScreen, + mirrorPreferred, + }; +} diff --git a/components/terminal/terminalReplay.test.ts b/components/terminal/terminalReplay.test.ts new file mode 100644 index 000000000..cc411cc8e --- /dev/null +++ b/components/terminal/terminalReplay.test.ts @@ -0,0 +1,22 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import type { Terminal as XTerm } from "@xterm/xterm"; + +import { writeTerminalPayloadChunked } from "./terminalReplay.ts"; + +test("writeTerminalPayloadChunked writes large payloads in multiple chunks", async () => { + const writes: string[] = []; + const term = { + write: (data: string, cb: () => void) => { + writes.push(data); + cb(); + }, + } as unknown as XTerm; + + const payload = "x".repeat(40_000); + await writeTerminalPayloadChunked(term, payload, { chunkBytes: 16_384 }); + + assert.ok(writes.length >= 2); + assert.equal(writes.join(""), payload); +}); diff --git a/components/terminal/terminalReplay.ts b/components/terminal/terminalReplay.ts new file mode 100644 index 000000000..9a5a04193 --- /dev/null +++ b/components/terminal/terminalReplay.ts @@ -0,0 +1,54 @@ +import type { Terminal as XTerm } from "@xterm/xterm"; + +export type TerminalReplayOptions = { + chunkBytes?: number; +}; + +const scheduleFrame = (): Promise => new Promise((resolve) => { + if (typeof requestAnimationFrame === "function") { + requestAnimationFrame(() => resolve()); + return; + } + setTimeout(resolve, 0); +}); + +const writeChunk = (term: XTerm, data: string): Promise => { + if (!data) return Promise.resolve(); + return new Promise((resolve) => { + term.write(data, () => resolve()); + }); +}; + +export async function writeTerminalPayloadChunked( + term: XTerm, + data: string, + options: TerminalReplayOptions = {}, +): Promise { + const chunkBytes = Math.max(1024, options.chunkBytes ?? 16 * 1024); + if (!data) return; + if (data.length <= chunkBytes) { + await writeChunk(term, data); + return; + } + + let offset = 0; + while (offset < data.length) { + const end = Math.min(data.length, offset + chunkBytes); + await writeChunk(term, data.slice(offset, end)); + offset = end; + if (offset < data.length) { + await scheduleFrame(); + } + } +} + +export async function writeTerminalReplaySequence( + term: XTerm, + segments: string[], + options: TerminalReplayOptions = {}, +): Promise { + for (const segment of segments) { + if (!segment) continue; + await writeTerminalPayloadChunked(term, segment, options); + } +} diff --git a/components/terminal/terminalRuntimeMount.ts b/components/terminal/terminalRuntimeMount.ts index bb1d3e647..33d9fcf41 100644 --- a/components/terminal/terminalRuntimeMount.ts +++ b/components/terminal/terminalRuntimeMount.ts @@ -60,7 +60,7 @@ export function applyTerminalKeywordHighlightRules( export type WakeTerminalFromHibernateOptions = { refs: TerminalRuntimeRefs; - runtimeContext: Omit; + runtimeContext: Omit; container: HTMLDivElement; getPayload: () => TerminalHibernateWakePayload; /** Stop hibernate IPC listeners before reading the final replay payload. */ @@ -76,6 +76,7 @@ export type WakeTerminalFromHibernateOptions = { /** When false, recreate xterm and replay output without reattaching or forcing connected status. */ sessionConnected?: boolean; getSessionConnected?: () => boolean; + replayChunkBytes?: number; }; export async function wakeTerminalFromHibernate( @@ -97,6 +98,7 @@ export async function wakeTerminalFromHibernate( updateStatus, sessionConnected = true, getSessionConnected, + replayChunkBytes = 16 * 1024, } = options; if (refs.hasRuntimeRef.current) { @@ -118,6 +120,7 @@ export async function wakeTerminalFromHibernate( ...runtimeContext, container, initiallyVisible: true, + deferWebglUntilReplayComplete: true, }); assignTerminalRuntimeRefs(refs, runtime); @@ -126,19 +129,34 @@ export async function wakeTerminalFromHibernate( const term = runtime.term; const initialPayload = getPayload(); const pendingAtApplyStart = initialPayload.pendingBuffer; - await applyHibernateWakeToTerminal(term, runtime, initialPayload); + const replayOptions = { chunkBytes: replayChunkBytes }; + + await applyHibernateWakeToTerminal(term, runtime, initialPayload, { + replayOptions, + deferWebgl: true, + }); + let replayedPendingLength = pendingAtApplyStart.length; for (let drainPass = 0; drainPass < 16; drainPass += 1) { const pending = getPayload().pendingBuffer; if (pending.length <= replayedPendingLength) break; - await appendTerminalReplayData(term, pending.slice(replayedPendingLength)); + await appendTerminalReplayData( + term, + pending.slice(replayedPendingLength), + replayOptions, + ); replayedPendingLength = pending.length; } const finalPending = getPayload().pendingBuffer; if (finalPending.length > replayedPendingLength) { - await appendTerminalReplayData(term, finalPending.slice(replayedPendingLength)); + await appendTerminalReplayData( + term, + finalPending.slice(replayedPendingLength), + replayOptions, + ); replayedPendingLength = finalPending.length; } + stopHibernateListeners(); const shouldReattach = sessionConnected && (getSessionConnected?.() ?? true); if (shouldReattach) { @@ -146,6 +164,9 @@ export async function wakeTerminalFromHibernate( updateStatus("connected"); } + runtime.ensureWebglRenderer(); + runtime.clearTextureAtlas(); + safeFit({ force: true }); resizeSession(); forceSyncRenderAfterResize(term); @@ -174,8 +195,11 @@ export async function wakeTerminalFromHibernate( logger.info("[Terminal] Resumed from hibernate", { sessionId, snapshotChars: initialPayload.snapshot.length, + viewportChars: initialPayload.viewportSnapshot?.length ?? initialPayload.snapshot.length, + scrollbackChars: initialPayload.scrollbackSnapshot?.length ?? 0, pendingChars: replayedPendingLength, alternateScreen: initialPayload.alternateScreen, + mirrorPreferred: initialPayload.mirrorPreferred === true, }); return true; } diff --git a/components/terminal/terminalSerialize.ts b/components/terminal/terminalSerialize.ts new file mode 100644 index 000000000..0c0193bac --- /dev/null +++ b/components/terminal/terminalSerialize.ts @@ -0,0 +1,21 @@ +import type { Terminal as XTerm } from "@xterm/xterm"; +import type { SerializeAddon } from "@xterm/addon-serialize"; + +import { resolveTerminalSerializeFn } from "./terminalSerializeWasm"; + +export type TerminalSerializeRequest = { + term: XTerm; + serializeAddon: SerializeAddon; + options?: Record; + preferWasm?: boolean; +}; + +export async function serializeTerminalBuffer( + request: TerminalSerializeRequest, +): Promise { + const serialize = await resolveTerminalSerializeFn( + (options) => request.serializeAddon.serialize(options), + request.preferWasm === true, + ); + return serialize(request.options); +} diff --git a/components/terminal/terminalSerializeWasm.ts b/components/terminal/terminalSerializeWasm.ts new file mode 100644 index 000000000..559718c3d --- /dev/null +++ b/components/terminal/terminalSerializeWasm.ts @@ -0,0 +1,33 @@ +/** + * Optional WASM-backed terminal serialize hook. + * + * xterm.js upstream is exploring a WASM serialize addon (~10x faster for large + * scrollback). Until a stable package ships alongside @xterm/addon-serialize, + * this module feature-detects and falls back to the JS SerializeAddon. + */ + +export type TerminalSerializeFn = (options?: Record) => string; + +let wasmSerializeLoader: (() => Promise) | null = null; + +export function registerWasmSerializeLoader( + loader: () => Promise, +): void { + wasmSerializeLoader = loader; +} + +export async function resolveTerminalSerializeFn( + jsSerialize: TerminalSerializeFn, + preferWasm: boolean, +): Promise { + if (!preferWasm || !wasmSerializeLoader) { + return jsSerialize; + } + try { + const wasmSerialize = await wasmSerializeLoader(); + if (wasmSerialize) return wasmSerialize; + } catch { + // Fall back to JS serialize below. + } + return jsSerialize; +} diff --git a/components/terminal/useTerminalHibernateEffect.ts b/components/terminal/useTerminalHibernateEffect.ts index 3e108a43a..f5f602ec1 100644 --- a/components/terminal/useTerminalHibernateEffect.ts +++ b/components/terminal/useTerminalHibernateEffect.ts @@ -21,11 +21,16 @@ type UseTerminalHibernateEffectOptions = { hibernateDelayMs: number; fileTransferActive: boolean; hibernatedRef: React.MutableRefObject; + softHiddenRef: React.MutableRefObject; hibernatePendingBufferRef: React.MutableRefObject; hibernateSnapshotRef: React.MutableRefObject; + hibernateViewportSnapshotRef: React.MutableRefObject; + hibernateScrollbackSnapshotRef: React.MutableRefObject; + hibernateMirrorPreferredRef: React.MutableRefObject; hibernateAlternateScreenRef: React.MutableRefObject; hasRuntimeRef: React.MutableRefObject; onHibernate: () => void; + onSoftHideWake: () => void; onWake: ( getPayload: () => TerminalHibernateWakePayload, options: { sessionConnected: boolean }, @@ -43,19 +48,26 @@ export function useTerminalHibernateEffect({ hibernateDelayMs, fileTransferActive, hibernatedRef, + softHiddenRef, hibernatePendingBufferRef, hibernateSnapshotRef, + hibernateViewportSnapshotRef, + hibernateScrollbackSnapshotRef, + hibernateMirrorPreferredRef, hibernateAlternateScreenRef, hasRuntimeRef, onHibernate, + onSoftHideWake, onWake, }: UseTerminalHibernateEffectOptions): void { const hiddenSinceRef = useRef(null); const hibernateTimerRef = useRef(null); const paneVisibleRef = useRef(resolvePaneVisible(sessionId, isVisible)); const onHibernateRef = useRef(onHibernate); + const onSoftHideWakeRef = useRef(onSoftHideWake); const onWakeRef = useRef(onWake); onHibernateRef.current = onHibernate; + onSoftHideWakeRef.current = onSoftHideWake; onWakeRef.current = onWake; useEffect(() => { @@ -70,8 +82,11 @@ export function useTerminalHibernateEffect({ const clearHibernateState = () => { hibernateSnapshotRef.current = ""; + hibernateViewportSnapshotRef.current = ""; + hibernateScrollbackSnapshotRef.current = ""; hibernatePendingBufferRef.current = ""; hibernateAlternateScreenRef.current = false; + hibernateMirrorPreferredRef.current = false; hibernatedRef.current = false; }; @@ -94,17 +109,27 @@ export function useTerminalHibernateEffect({ }; const tryWake = () => { + if (softHiddenRef.current) { + softHiddenRef.current = false; + onSoftHideWakeRef.current(); + return; + } if (!hibernatedRef.current) return; const sessionConnected = getSessionConnectedRef.current(); const getPayload = (): TerminalHibernateWakePayload => ({ snapshot: hibernateSnapshotRef.current, + viewportSnapshot: hibernateViewportSnapshotRef.current || hibernateSnapshotRef.current, + scrollbackSnapshot: hibernateScrollbackSnapshotRef.current, pendingBuffer: hibernatePendingBufferRef.current, alternateScreen: hibernateAlternateScreenRef.current, + mirrorPreferred: hibernateMirrorPreferredRef.current, }); logger.info("[Terminal] Waking from hibernate", { sessionId, snapshotChars: hibernateSnapshotRef.current.length, + viewportChars: hibernateViewportSnapshotRef.current.length, + scrollbackChars: hibernateScrollbackSnapshotRef.current.length, pendingChars: hibernatePendingBufferRef.current.length, sessionConnected, }); @@ -120,11 +145,11 @@ export function useTerminalHibernateEffect({ if (!hibernateEnabled) { clearHibernateTimer(); - if (hibernatedRef.current) { + if (hibernatedRef.current || softHiddenRef.current) { tryWake(); } const unsubscribeDisabled = subscribePaneVisible(sessionId, () => { - if (hibernatedRef.current && resolveVisible()) { + if ((hibernatedRef.current || softHiddenRef.current) && resolveVisible()) { tryWake(); } }); @@ -163,16 +188,20 @@ export function useTerminalHibernateEffect({ fileTransferActive, getSessionConnectedRef, hasRuntimeRef, + hibernateAlternateScreenRef, hibernateDelayMs, hibernateEnabled, + hibernateMirrorPreferredRef, hibernatePendingBufferRef, + hibernateScrollbackSnapshotRef, hibernateSnapshotRef, - hibernateAlternateScreenRef, + hibernateViewportSnapshotRef, hibernatedRef, isSearchOpen, isVisible, isVisibleRef, sessionId, + softHiddenRef, status, ]); } diff --git a/domain/models/terminal.ts b/domain/models/terminal.ts index ce9ec436c..f93ce5eec 100644 --- a/domain/models/terminal.ts +++ b/domain/models/terminal.ts @@ -1,6 +1,10 @@ import type { SerialConfig } from './connection'; import type { CodingCliProviderId } from '../codingCliProviders'; -import { normalizeHibernateHiddenTabsDelaySec } from '../terminalHibernate'; +import { + normalizeHibernateHiddenTabsDelaySec, + normalizeHibernateKeepRendererCount, + normalizeHibernateReplayChunkBytes, +} from '../terminalHibernate'; // Terminal appearance settings export type CursorShape = 'block' | 'bar' | 'underline'; @@ -122,6 +126,16 @@ export interface TerminalSettings { hibernateHiddenTabs: boolean; /** Seconds after a tab leaves view before hibernating (see hibernateHiddenTabs). */ hibernateHiddenTabsDelaySec: number; + /** Skip full hibernate while a full-screen TUI owns the alternate screen buffer. */ + hibernateSkipAltScreen: boolean; + /** Hidden tabs whose renderer is kept alive (WebGL suspended) before full hibernate. */ + hibernateKeepRendererCount: number; + /** Mirror PTY output in a main-process headless xterm for faster wake snapshots. */ + hibernateUseHeadlessMirror: boolean; + /** Bytes per animation frame when replaying hibernate snapshots in the renderer. */ + hibernateReplayChunkBytes: number; + /** Prefer WASM terminal serialize when available (falls back to JS). */ + hibernatePreferWasmSerialize: boolean; showLineTimestamps: boolean; // Show output timestamps in a side gutter // Autocomplete @@ -269,6 +283,12 @@ export const normalizeTerminalSettings = ( hibernateHiddenTabsDelaySec: normalizeHibernateHiddenTabsDelaySec( mergedSettings.hibernateHiddenTabsDelaySec, ), + hibernateKeepRendererCount: normalizeHibernateKeepRendererCount( + mergedSettings.hibernateKeepRendererCount, + ), + hibernateReplayChunkBytes: normalizeHibernateReplayChunkBytes( + mergedSettings.hibernateReplayChunkBytes, + ), autocompleteGhostText: mergedSettings.autocompletePopupMenu ? false : mergedSettings.autocompleteGhostText, @@ -333,6 +353,11 @@ const DEFAULT_TERMINAL_SETTINGS: TerminalSettings = { rendererType: 'auto', // Auto-detect best renderer based on hardware hibernateHiddenTabs: true, hibernateHiddenTabsDelaySec: 5, + hibernateSkipAltScreen: true, + hibernateKeepRendererCount: 2, + hibernateUseHeadlessMirror: true, + hibernateReplayChunkBytes: 16 * 1024, + hibernatePreferWasmSerialize: false, showLineTimestamps: false, // Opt-in: shows output timestamps beside terminal lines autocompleteEnabled: true, // Autocomplete enabled by default autocompleteGhostText: false, // Mutually exclusive with popup menu diff --git a/domain/terminalHibernate.optimizations.test.ts b/domain/terminalHibernate.optimizations.test.ts new file mode 100644 index 000000000..1287b0cf0 --- /dev/null +++ b/domain/terminalHibernate.optimizations.test.ts @@ -0,0 +1,33 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + normalizeHibernateKeepRendererCount, + normalizeHibernateReplayChunkBytes, + resolveHibernateSkipAltScreen, + resolveHibernateUseHeadlessMirror, +} from "./terminalHibernate.ts"; + +test("normalizeHibernateReplayChunkBytes clamps to allowed range", () => { + assert.equal(normalizeHibernateReplayChunkBytes(undefined), 16 * 1024); + assert.equal(normalizeHibernateReplayChunkBytes(8 * 1024), 8 * 1024); + assert.equal(normalizeHibernateReplayChunkBytes(1), 4 * 1024); + assert.equal(normalizeHibernateReplayChunkBytes(999_999), 64 * 1024); +}); + +test("normalizeHibernateKeepRendererCount clamps to allowed range", () => { + assert.equal(normalizeHibernateKeepRendererCount(undefined), 2); + assert.equal(normalizeHibernateKeepRendererCount(4), 4); + assert.equal(normalizeHibernateKeepRendererCount(-1), 0); + assert.equal(normalizeHibernateKeepRendererCount(99), 12); +}); + +test("resolveHibernateSkipAltScreen defaults to enabled", () => { + assert.equal(resolveHibernateSkipAltScreen(), true); + assert.equal(resolveHibernateSkipAltScreen({ hibernateSkipAltScreen: false }), false); +}); + +test("resolveHibernateUseHeadlessMirror defaults to enabled", () => { + assert.equal(resolveHibernateUseHeadlessMirror(), true); + assert.equal(resolveHibernateUseHeadlessMirror({ hibernateUseHeadlessMirror: false }), false); +}); diff --git a/domain/terminalHibernate.ts b/domain/terminalHibernate.ts index 20a83b55d..c475f9ece 100644 --- a/domain/terminalHibernate.ts +++ b/domain/terminalHibernate.ts @@ -48,6 +48,20 @@ export function isTerminalFileTransferActive(options: { /** Lines kept when snapshotting xterm scrollback before hibernate. */ export const TERMINAL_HIBERNATE_SNAPSHOT_MAX_LINES = 3_000; +/** Default chunk size for replaying hibernate snapshots without blocking the main thread. */ +export const TERMINAL_HIBERNATE_REPLAY_CHUNK_BYTES_DEFAULT = 16 * 1024; + +export const TERMINAL_HIBERNATE_REPLAY_CHUNK_BYTES_MIN = 4 * 1024; + +export const TERMINAL_HIBERNATE_REPLAY_CHUNK_BYTES_MAX = 64 * 1024; + +/** Hidden tabs whose xterm runtime is kept alive (WebGL suspended) before full hibernate. */ +export const TERMINAL_HIBERNATE_KEEP_RENDERER_COUNT_DEFAULT = 2; + +export const TERMINAL_HIBERNATE_KEEP_RENDERER_COUNT_MIN = 0; + +export const TERMINAL_HIBERNATE_KEEP_RENDERER_COUNT_MAX = 12; + /** Max chars buffered in renderer while xterm is hibernated (post-snapshot output). */ export const TERMINAL_HIBERNATE_BUFFER_MAX_CHARS = 512 * 1024; @@ -63,10 +77,74 @@ export function capHibernateBufferByLines(text: string, maxLines: number): strin return lines.slice(lines.length - maxLines).join("\n"); } +export function normalizeHibernateReplayChunkBytes(value: unknown): number { + if (typeof value !== "number" || !Number.isFinite(value)) { + return TERMINAL_HIBERNATE_REPLAY_CHUNK_BYTES_DEFAULT; + } + return Math.min( + TERMINAL_HIBERNATE_REPLAY_CHUNK_BYTES_MAX, + Math.max(TERMINAL_HIBERNATE_REPLAY_CHUNK_BYTES_MIN, Math.round(value)), + ); +} + +export function normalizeHibernateKeepRendererCount(value: unknown): number { + if (typeof value !== "number" || !Number.isFinite(value)) { + return TERMINAL_HIBERNATE_KEEP_RENDERER_COUNT_DEFAULT; + } + return Math.min( + TERMINAL_HIBERNATE_KEEP_RENDERER_COUNT_MAX, + Math.max(TERMINAL_HIBERNATE_KEEP_RENDERER_COUNT_MIN, Math.round(value)), + ); +} + +export function resolveTerminalHibernateReplayChunkBytes( + settings?: Pick | null, +): number { + return normalizeHibernateReplayChunkBytes(settings?.hibernateReplayChunkBytes); +} + +export function resolveHibernateKeepRendererCount( + settings?: Pick | null, +): number { + return normalizeHibernateKeepRendererCount(settings?.hibernateKeepRendererCount); +} + +export function resolveHibernateSkipAltScreen( + settings?: Pick | null, +): boolean { + return settings?.hibernateSkipAltScreen !== false; +} + +export function resolveHibernateUseHeadlessMirror( + settings?: Pick | null, +): boolean { + return settings?.hibernateUseHeadlessMirror !== false; +} + +export function resolveHibernatePreferWasmSerialize( + settings?: Pick | null, +): boolean { + return settings?.hibernatePreferWasmSerialize === true; +} + +export function shouldSkipHibernateForAltScreen( + alternateScreen: boolean, + settings?: Pick | null, +): boolean { + return alternateScreen && resolveHibernateSkipAltScreen(settings); +} + /** Snapshot + buffered output to replay when recreating xterm after hibernate. */ export type TerminalHibernateWakePayload = { + /** Full serialized terminal state (legacy combined snapshot). */ snapshot: string; + /** Visible viewport rows for fast first paint during wake. */ + viewportSnapshot?: string; + /** Older scrollback rows replayed lazily after viewport + pending. */ + scrollbackSnapshot?: string; pendingBuffer: string; /** True when the pane was hibernated while a full-screen app owned the alt buffer. */ alternateScreen: boolean; + /** When true, snapshot was sourced from the main-process headless mirror. */ + mirrorPreferred?: boolean; }; diff --git a/electron/bridges/emitTerminalSessionData.cjs b/electron/bridges/emitTerminalSessionData.cjs new file mode 100644 index 000000000..342c2bd0a --- /dev/null +++ b/electron/bridges/emitTerminalSessionData.cjs @@ -0,0 +1,48 @@ +"use strict"; + +const { + writeMirror, + resizeMirror, + serializeMirror, + disposeMirror, +} = require("./terminalHeadlessMirror.cjs"); + +/** + * Deliver terminal output to the renderer and optionally mirror it in a + * headless xterm on the main process for fast hibernate snapshots. + */ +function emitTerminalSessionData(contents, sessionId, data, options = {}) { + const { cols, rows, mirrorEnabled = true } = options; + if (mirrorEnabled && data) { + writeMirror(sessionId, data, cols, rows); + } + contents?.send("netcatty:data", { sessionId, data }); +} + +function registerTerminalMirrorHandlers(ipcMain) { + ipcMain.handle("netcatty:mirror:snapshot", (_event, payload = {}) => { + const sessionId = payload.sessionId; + if (!sessionId) return { snapshot: "", alternateScreen: false }; + return serializeMirror(sessionId); + }); + + ipcMain.handle("netcatty:mirror:resize", (_event, payload = {}) => { + const { sessionId, cols, rows } = payload; + if (!sessionId || !cols || !rows) return { ok: false }; + resizeMirror(sessionId, cols, rows); + return { ok: true }; + }); + + ipcMain.handle("netcatty:mirror:dispose", (_event, payload = {}) => { + const sessionId = payload.sessionId; + if (!sessionId) return { ok: false }; + disposeMirror(sessionId); + return { ok: true }; + }); +} + +module.exports = { + emitTerminalSessionData, + registerTerminalMirrorHandlers, + disposeMirror, +}; diff --git a/electron/bridges/sshBridge/startSession.cjs b/electron/bridges/sshBridge/startSession.cjs index 8aede2b73..fc334e68f 100644 --- a/electron/bridges/sshBridge/startSession.cjs +++ b/electron/bridges/sshBridge/startSession.cjs @@ -1,4 +1,6 @@ /* eslint-disable no-undef */ +const { emitTerminalSessionData } = require("../emitTerminalSessionData.cjs"); + function createStartSessionApi(ctx) { with (ctx) { /** @@ -61,6 +63,8 @@ function createStartSessionApi(ctx) { port: options.port || 22, username: options.username || 'root', }, + cols: options.cols || 80, + rows: options.rows || 24, }; sessions.set(sessionId, session); @@ -95,7 +99,11 @@ function createStartSessionApi(ctx) { // cap still forces an immediate flush for bursts of output. const { bufferData, flush: flushBuffer } = createPtyOutputBuffer((data) => { const contents = event.sender; - safeSend(contents, "netcatty:data", { sessionId, data }); + const current = sessions.get(sessionId); + emitTerminalSessionData(contents, sessionId, data, { + cols: current?.cols, + rows: current?.rows, + }); }); const sshZmodemSentry = createZmodemSentry({ @@ -1017,7 +1025,11 @@ function createStartSessionApi(ctx) { sendProgress(totalHops, totalHops, options.hostname, 'shell'); const sendTerminalMessage = (data) => { - safeSend(event.sender, "netcatty:data", { sessionId, data }); + const current = sessions.get(sessionId); + emitTerminalSessionData(event.sender, sessionId, data, { + cols: current?.cols, + rows: current?.rows, + }); }; const x11FakeCookie = options.x11Forwarding diff --git a/electron/bridges/terminalBridge.cjs b/electron/bridges/terminalBridge.cjs index 619e53964..8484f4f09 100644 --- a/electron/bridges/terminalBridge.cjs +++ b/electron/bridges/terminalBridge.cjs @@ -13,6 +13,8 @@ const { promisify } = require("node:util"); const { StringDecoder } = require("node:string_decoder"); const pty = require("node-pty"); const { SerialPort } = require("serialport"); +const { emitTerminalSessionData, disposeMirror } = require("./emitTerminalSessionData.cjs"); +const { resizeMirror } = require("./terminalHeadlessMirror.cjs"); const iconv = require("iconv-lite"); const ptyProcessTree = require("./ptyProcessTree.cjs"); @@ -404,7 +406,10 @@ function startLocalSession(event, payload) { const { bufferData: bufferLocalData, flush: flushLocal } = createPtyOutputBuffer((data) => { const contents = electronModule.webContents.fromId(session.webContentsId); - contents?.send("netcatty:data", { sessionId, data }); + emitTerminalSessionData(contents, sessionId, data, { + cols: session.cols, + rows: session.rows, + }); }); session.flushPendingData = flushLocal; @@ -626,7 +631,10 @@ async function startSerialSession(event, options) { const decoded = serialDecoderRef.current.write(buf); if (!decoded) return; const contents = electronModule.webContents.fromId(session.webContentsId); - contents?.send("netcatty:data", { sessionId, data: decoded }); + emitTerminalSessionData(contents, sessionId, decoded, { + cols: session.cols, + rows: session.rows, + }); sessionLogStreamManager.appendData(sessionId, decoded); }, writeToRemote(buf) { @@ -944,6 +952,9 @@ function resizeSession(event, payload) { if (!session) return; if (Number.isFinite(payload.cols)) session.cols = payload.cols; if (Number.isFinite(payload.rows)) session.rows = payload.rows; + if (Number.isFinite(payload.cols) && Number.isFinite(payload.rows)) { + resizeMirror(payload.sessionId, payload.cols, payload.rows); + } try { if (session.stream) { @@ -980,6 +991,7 @@ function resizeSession(event, payload) { function closeSession(event, payload) { const session = sessions.get(payload.sessionId); if (!session) return; + disposeMirror(payload.sessionId); session.closed = true; try { diff --git a/electron/bridges/terminalBridge/etSession.cjs b/electron/bridges/terminalBridge/etSession.cjs index 26b078c65..567aeb7c4 100644 --- a/electron/bridges/terminalBridge/etSession.cjs +++ b/electron/bridges/terminalBridge/etSession.cjs @@ -1,6 +1,7 @@ /* eslint-disable no-undef */ const crypto = require("node:crypto"); const { createSystemKnownHostsApi } = require("../sshBridge/systemKnownHosts.cjs"); +const { emitTerminalSessionData } = require("../emitTerminalSessionData.cjs"); // // EternalTerminal session backend, factored into the createXxxSessionApi @@ -818,7 +819,10 @@ main(); const { bufferData: bufferEtData, flush: flushEt } = createPtyOutputBuffer((data) => { const contents = electronModule.webContents.fromId(session.webContentsId); - contents?.send("netcatty:data", { sessionId, data }); + emitTerminalSessionData(contents, sessionId, data, { + cols: session.cols, + rows: session.rows, + }); }); session.flushPendingData = flushEt; diff --git a/electron/bridges/terminalBridge/moshSession.cjs b/electron/bridges/terminalBridge/moshSession.cjs index 52b0fc456..a1017f3a8 100644 --- a/electron/bridges/terminalBridge/moshSession.cjs +++ b/electron/bridges/terminalBridge/moshSession.cjs @@ -1,4 +1,6 @@ /* eslint-disable no-undef */ +const { emitTerminalSessionData } = require("../emitTerminalSessionData.cjs"); + function createMoshSessionApi(ctx) { with (ctx) { function resolveBareMoshClient(_options, opts = {}) { @@ -425,7 +427,10 @@ function createMoshSessionApi(ctx) { const { bufferData, flush } = createPtyOutputBuffer((data) => { const contents = electronModule.webContents.fromId(session.webContentsId); - contents?.send("netcatty:data", { sessionId, data }); + emitTerminalSessionData(contents, sessionId, data, { + cols: session.cols, + rows: session.rows, + }); }); session.flushPendingData = flush; diff --git a/electron/bridges/terminalBridge/telnetSession.cjs b/electron/bridges/terminalBridge/telnetSession.cjs index 4cb8c9a91..b9f57be8b 100644 --- a/electron/bridges/terminalBridge/telnetSession.cjs +++ b/electron/bridges/terminalBridge/telnetSession.cjs @@ -1,4 +1,6 @@ /* eslint-disable no-undef */ +const { emitTerminalSessionData } = require("../emitTerminalSessionData.cjs"); + function createTelnetSessionApi(ctx) { with (ctx) { async function startTelnetSession(event, options) { @@ -154,7 +156,7 @@ function createTelnetSessionApi(ctx) { const telnetWebContentsId = event.sender.id; const { bufferData: bufferTelnetData, flush: flushTelnet } = createPtyOutputBuffer((data) => { const contents = electronModule.webContents.fromId(telnetWebContentsId); - contents?.send("netcatty:data", { sessionId, data }); + emitTerminalSessionData(contents, sessionId, data, { cols, rows }); }); const telnetZmodemSentry = createZmodemSentry({ diff --git a/electron/bridges/terminalHeadlessMirror.cjs b/electron/bridges/terminalHeadlessMirror.cjs new file mode 100644 index 000000000..9e83de30d --- /dev/null +++ b/electron/bridges/terminalHeadlessMirror.cjs @@ -0,0 +1,100 @@ +"use strict"; + +const { SerializeAddon } = require("@xterm/addon-serialize"); +const { Terminal: HeadlessTerminal } = require("@xterm/headless"); + +const DEFAULT_COLS = 80; +const DEFAULT_ROWS = 24; +const DEFAULT_SCROLLBACK = 3000; + +/** @type {Map} */ +const mirrors = new Map(); + +function isAlternateScreenActive(headless) { + return headless.buffer.active.type === "alternate"; +} + +function createMirror(cols, rows) { + const headless = new HeadlessTerminal({ + cols, + rows, + scrollback: DEFAULT_SCROLLBACK, + allowProposedApi: true, + }); + const serializer = new SerializeAddon(); + headless.loadAddon(serializer); + return { headless, serializer, cols, rows }; +} + +function ensureMirror(sessionId, cols = DEFAULT_COLS, rows = DEFAULT_ROWS) { + let mirror = mirrors.get(sessionId); + if (!mirror) { + mirror = createMirror(cols, rows); + mirrors.set(sessionId, mirror); + return mirror; + } + if (mirror.cols !== cols || mirror.rows !== rows) { + try { + mirror.headless.resize(cols, rows); + } catch { + // Ignore resize failures on disposed mirrors. + } + mirror.cols = cols; + mirror.rows = rows; + } + return mirror; +} + +function writeMirror(sessionId, data, cols, rows) { + if (!data) return; + const mirror = ensureMirror(sessionId, cols, rows); + mirror.headless.write(data); +} + +function resizeMirror(sessionId, cols, rows) { + if (!mirrors.has(sessionId)) return; + const mirror = ensureMirror(sessionId, cols, rows); + try { + mirror.headless.resize(cols, rows); + } catch { + mirrors.delete(sessionId); + } +} + +function serializeMirror(sessionId) { + const mirror = mirrors.get(sessionId); + if (!mirror) { + return { snapshot: "", alternateScreen: false }; + } + const alternateScreen = isAlternateScreenActive(mirror.headless); + try { + const snapshot = mirror.serializer.serialize({ + excludeAltBuffer: !alternateScreen, + excludeModes: !alternateScreen, + ...(alternateScreen + ? { range: { start: 0, end: Math.max(0, mirror.rows - 1) } } + : {}), + }); + return { snapshot, alternateScreen }; + } catch { + return { snapshot: "", alternateScreen }; + } +} + +function disposeMirror(sessionId) { + const mirror = mirrors.get(sessionId); + if (!mirror) return; + try { + mirror.headless.dispose(); + } catch { + // Ignore dispose failures. + } + mirrors.delete(sessionId); +} + +module.exports = { + writeMirror, + resizeMirror, + serializeMirror, + disposeMirror, +}; diff --git a/electron/bridges/terminalHeadlessMirror.test.cjs b/electron/bridges/terminalHeadlessMirror.test.cjs new file mode 100644 index 000000000..bfb6458d8 --- /dev/null +++ b/electron/bridges/terminalHeadlessMirror.test.cjs @@ -0,0 +1,21 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { + writeMirror, + serializeMirror, + disposeMirror, +} = require("./terminalHeadlessMirror.cjs"); + +test("terminalHeadlessMirror tracks output and serializes snapshot", async () => { + const sessionId = "mirror-test-session"; + disposeMirror(sessionId); + writeMirror(sessionId, "hello\r\n", 80, 24); + await new Promise((resolve) => setTimeout(resolve, 0)); + const { snapshot, alternateScreen } = serializeMirror(sessionId); + assert.equal(alternateScreen, false); + assert.match(snapshot, /hello/); + disposeMirror(sessionId); +}); diff --git a/electron/main/registerBridges.cjs b/electron/main/registerBridges.cjs index 37be77057..5bceae74f 100644 --- a/electron/main/registerBridges.cjs +++ b/electron/main/registerBridges.cjs @@ -170,6 +170,8 @@ function createBridgeRegistrar(context) { transferBridge.registerHandlers(ipcMain); portForwardingBridge.registerHandlers(ipcMain); terminalBridge.registerHandlers(ipcMain); + const { registerTerminalMirrorHandlers } = require("../bridges/emitTerminalSessionData.cjs"); + registerTerminalMirrorHandlers(ipcMain); const { createSystemManagerBridge } = require("../bridges/systemManagerBridge.cjs"); const systemManagerBridge = createSystemManagerBridge({ diff --git a/electron/preload/api.cjs b/electron/preload/api.cjs index a84b33b92..83486ae32 100644 --- a/electron/preload/api.cjs +++ b/electron/preload/api.cjs @@ -172,6 +172,9 @@ function createPreloadApi(ctx) { resizeSession: (sessionId, cols, rows) => { ipcRenderer.send("netcatty:resize", { sessionId, cols, rows }); }, + getTerminalMirrorSnapshot: (sessionId) => { + return ipcRenderer.invoke("netcatty:mirror:snapshot", { sessionId }); + }, setSessionFlowPaused: (sessionId, paused) => { ipcRenderer.send("netcatty:flow", { sessionId, paused: Boolean(paused) }); }, diff --git a/package-lock.json b/package-lock.json index 2790f1df8..8b58b2669 100644 --- a/package-lock.json +++ b/package-lock.json @@ -38,6 +38,7 @@ "@xterm/addon-unicode-graphemes": "0.5.0-beta.220", "@xterm/addon-web-links": "0.13.0-beta.220", "@xterm/addon-webgl": "0.20.0-beta.219", + "@xterm/headless": "^6.1.0-beta.220", "@xterm/xterm": "6.1.0-beta.220", "ai": "^6.0.116", "clsx": "2.1.1", @@ -340,29 +341,6 @@ "win32" ] }, - "node_modules/@anthropic-ai/sdk": { - "version": "0.99.0", - "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.99.0.tgz", - "integrity": "sha512-vdicFA9YjtvgpG8rxp39hqW4oxpkdRGPTq0QEts5TZhr2GkLozDduK/GiXrLQ7PzrKYBtIkQFdRW+QBjzlsABg==", - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "json-schema-to-ts": "^3.1.1", - "standardwebhooks": "^1.0.0" - }, - "bin": { - "anthropic-ai-sdk": "bin/cli" - }, - "peerDependencies": { - "zod": "^3.25.0 || ^4.0.0" - }, - "peerDependenciesMeta": { - "zod": { - "optional": true - } - } - }, "node_modules/@aws-crypto/crc32": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/@aws-crypto/crc32/-/crc32-5.2.0.tgz", @@ -1292,6 +1270,7 @@ "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", @@ -1572,13 +1551,6 @@ "node": ">=6.9.0" } }, - "node_modules/@bufbuild/protobuf": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-1.10.0.tgz", - "integrity": "sha512-QDdVFLoN93Zjg36NoQPZfsVH9tZew7wKDKyV5qRdj8ntT4wQCOradQjRaTdwMhWUYsgKsvCINKKm87FdEk96Ag==", - "license": "(Apache-2.0 AND BSD-3-Clause)", - "optional": true - }, "node_modules/@buttercup/fetch": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/@buttercup/fetch/-/fetch-0.2.1.tgz", @@ -1897,6 +1869,7 @@ "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.3.tgz", "integrity": "sha512-QwCZW6Tt1siP37Jet9Tb02Zs81TQt6qQrZR2H+eGMcFsL1zMrk2/b9CLC7/9ieP1fjIUMgviLWMmgiHoJrj+ZA==", "license": "MIT", + "peer": true, "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.23.0", @@ -1986,6 +1959,7 @@ "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.6.0.tgz", "integrity": "sha512-4nbvra5R5EtiCzr9BTHiTLc+MLXK2QGiAVYMyi8PkQd3SR+6ixar/Q/01Fa21TBIDOZXgeWV4WppsQolSreAPQ==", "license": "MIT", + "peer": true, "dependencies": { "@marijn/find-cluster-break": "^1.0.0" } @@ -1995,6 +1969,7 @@ "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.1.tgz", "integrity": "sha512-+BIjw/AG3tDQ4pJgTLPYdAW25eDE66YsvM4LKyVPgGzVgZ4a9Wj1SRX8kPVKgBDdPt8oHtZ15F0qx7p0oOHdHw==", "license": "MIT", + "peer": true, "dependencies": { "@codemirror/state": "^6.6.0", "crelt": "^1.0.6", @@ -2002,16 +1977,6 @@ "w3c-keyname": "^2.2.4" } }, - "node_modules/@connectrpc/connect": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/@connectrpc/connect/-/connect-1.7.0.tgz", - "integrity": "sha512-iNKdJRi69YP3mq6AePRT8F/HrxWCewrhxnLMNm0vpqXAR8biwzRtO6Hjx80C6UvtKJ5sFmffQT7I4Baecz389w==", - "license": "Apache-2.0", - "optional": true, - "peerDependencies": { - "@bufbuild/protobuf": "^1.10.0" - } - }, "node_modules/@connectrpc/connect-node": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/@connectrpc/connect-node/-/connect-node-1.7.0.tgz", @@ -2147,6 +2112,13 @@ "rg": "bin/rg.exe" } }, + "node_modules/@cursor/sdk/node_modules/@bufbuild/protobuf": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-1.10.0.tgz", + "integrity": "sha512-QDdVFLoN93Zjg36NoQPZfsVH9tZew7wKDKyV5qRdj8ntT4wQCOradQjRaTdwMhWUYsgKsvCINKKm87FdEk96Ag==", + "license": "(Apache-2.0 AND BSD-3-Clause)", + "optional": true + }, "node_modules/@cursor/sdk/node_modules/zod": { "version": "3.25.76", "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", @@ -2452,7 +2424,6 @@ "dev": true, "license": "BSD-2-Clause", "optional": true, - "peer": true, "dependencies": { "cross-dirname": "^0.1.0", "debug": "^4.3.4", @@ -2474,7 +2445,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", @@ -3884,6 +3854,7 @@ "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz", "integrity": "sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==", "license": "MIT", + "peer": true, "dependencies": { "@lezer/common": "^1.3.0" } @@ -4166,6 +4137,7 @@ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz", "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==", "license": "MIT", + "peer": true, "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", @@ -7588,8 +7560,7 @@ "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz", "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==", "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/@standard-schema/spec": { "version": "1.1.0", @@ -8213,6 +8184,7 @@ "integrity": "sha512-hAAP5io/7csFStuOmR782YmTthKBJ9ND3WVL60hcOjvtGFb+HJxH4O5huAcmcZ9v9G8P+JETiZ/G1B8MALnWZQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.54.0", @@ -8242,6 +8214,7 @@ "integrity": "sha512-BtE0k6cjwjLZoZixN0t5AKP0kSzlGu7FctRXYuPAm//aaiZhmfq1JwdYpYr1brzEspYyFeF+8XF5j2VK6oalrA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.54.0", "@typescript-eslint/types": "8.54.0", @@ -8590,11 +8563,21 @@ "@xterm/xterm": "^6.1.0-beta.220" } }, + "node_modules/@xterm/headless": { + "version": "6.1.0-beta.220", + "resolved": "https://registry.npmjs.org/@xterm/headless/-/headless-6.1.0-beta.220.tgz", + "integrity": "sha512-oc+cI28eP/ktv91ddk1MxsEdfS41dnNvB3eMjNxfP7v+SaM7aXgXAL8Kj0/zzbpX/dG0nbA9wi3YvsybzCN3OQ==", + "license": "MIT", + "workspaces": [ + "addons/*" + ] + }, "node_modules/@xterm/xterm": { "version": "6.1.0-beta.220", "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.1.0-beta.220.tgz", "integrity": "sha512-rwEKE75wfwfNWeGnjl0iQRA1W50HigKoGcGMeF3o5CqDSdI9IjmwzpV9xHXqLH6CYj6s9N1g6bbKFVDou9dJ/A==", "license": "MIT", + "peer": true, "workspaces": [ "addons/*" ] @@ -8659,6 +8642,7 @@ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "license": "MIT", + "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -9360,6 +9344,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", @@ -10185,8 +10170,7 @@ "integrity": "sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q==", "dev": true, "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/cross-env": { "version": "10.1.0", @@ -10483,6 +10467,7 @@ "integrity": "sha512-fMkjRqKyPtsz4Kzu/qGP0BGjqzMCIgp+/7kw/u6YH6lvn/8hvL3c0TXhoFayBoYdpPCnEinnCHztd4bW7/jetA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "app-builder-lib": "26.15.2", "builder-util": "26.15.0", @@ -10764,7 +10749,6 @@ "dev": true, "hasInstallScript": true, "license": "MIT", - "peer": true, "dependencies": { "@electron/asar": "^3.2.1", "debug": "^4.1.1", @@ -10785,7 +10769,6 @@ "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "graceful-fs": "^4.1.2", "jsonfile": "^4.0.0", @@ -10801,7 +10784,6 @@ "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", "dev": true, "license": "MIT", - "peer": true, "optionalDependencies": { "graceful-fs": "^4.1.6" } @@ -10812,7 +10794,6 @@ "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">= 4.0.0" } @@ -11037,6 +11018,7 @@ "integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.1", @@ -11490,8 +11472,7 @@ "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz", "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==", "license": "Unlicense", - "optional": true, - "peer": true + "optional": true }, "node_modules/fast-uri": { "version": "3.1.0", @@ -12428,6 +12409,7 @@ "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.14.tgz", "integrity": "sha512-am5zfg3yu6sqn5yjKBNqhnTX7Cv+m00ox+7jbaKkrLMRJ4rAdldd1xPd/JzbBWspqaQv6RSTrgFN95EsfhC+7w==", "license": "MIT", + "peer": true, "engines": { "node": ">=16.9.0" } @@ -12884,7 +12866,6 @@ "resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz", "integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==", "license": "MIT", - "peer": true, "funding": { "type": "GitHub Sponsors ❤", "url": "https://github.com/sponsors/dmonad" @@ -13006,7 +12987,6 @@ "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", "license": "MIT", "optional": true, - "peer": true, "dependencies": { "@babel/runtime": "^7.18.3", "ts-algebra": "^2.0.0" @@ -13164,7 +13144,6 @@ "resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.117.tgz", "integrity": "sha512-DeXj9X5xDCjgKLU/7RR+/HQEVzuuEUiwldwOGsHK/sfAfELGWEyTcf0x+uOvCvK3O2zPmZePXWL85vtia6GyZw==", "license": "MIT", - "peer": true, "dependencies": { "isomorphic.js": "^0.2.4" }, @@ -14110,6 +14089,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", @@ -15230,7 +15210,6 @@ "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "minimist": "^1.2.6" }, @@ -15250,6 +15229,7 @@ "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.55.1.tgz", "integrity": "sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A==", "license": "MIT", + "peer": true, "dependencies": { "dompurify": "3.2.7", "marked": "14.0.0" @@ -16000,7 +15980,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "commander": "^9.4.0" }, @@ -16018,7 +15997,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": "^12.20.0 || >=14" } @@ -16323,6 +16301,7 @@ "resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz", "integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==", "license": "MIT", + "peer": true, "engines": { "node": ">=0.10.0" } @@ -16332,6 +16311,7 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz", "integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==", "license": "MIT", + "peer": true, "dependencies": { "scheduler": "^0.27.0" }, @@ -17669,7 +17649,6 @@ "integrity": "sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==", "license": "MIT", "optional": true, - "peer": true, "dependencies": { "@stablelib/base64": "^1.0.0", "fast-sha256": "^1.3.0" @@ -17975,7 +17954,6 @@ "integrity": "sha512-yYrrsWnrXMcdsnu/7YMYAofM1ktpL5By7vZhf15CrXijWWrEYZks5AXBudalfSWJLlnen/QUJUB5aoB0kqZUGA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "mkdirp": "^0.5.1", "rimraf": "~2.6.2" @@ -18002,7 +17980,6 @@ "deprecated": "Rimraf versions prior to v4 are no longer supported", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "glob": "^7.1.3" }, @@ -18077,6 +18054,7 @@ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -18171,8 +18149,7 @@ "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/ts-api-utils": { "version": "2.4.0", @@ -18199,6 +18176,7 @@ "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "esbuild": "~0.27.0", "get-tsconfig": "^4.7.5" @@ -18310,6 +18288,7 @@ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -18350,6 +18329,7 @@ "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz", "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==", "license": "MIT", + "peer": true, "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", @@ -18725,6 +18705,7 @@ "integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", @@ -18818,6 +18799,7 @@ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -19105,6 +19087,7 @@ "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", "license": "MIT", + "peer": true, "funding": { "url": "https://github.com/sponsors/colinhacks" } diff --git a/package.json b/package.json index 35881e01f..d5d574956 100644 --- a/package.json +++ b/package.json @@ -66,6 +66,7 @@ "@xterm/addon-unicode-graphemes": "0.5.0-beta.220", "@xterm/addon-web-links": "0.13.0-beta.220", "@xterm/addon-webgl": "0.20.0-beta.219", + "@xterm/headless": "^6.1.0-beta.220", "@xterm/xterm": "6.1.0-beta.220", "ai": "^6.0.116", "clsx": "2.1.1", diff --git a/types/global/netcatty-bridge-session.d.ts b/types/global/netcatty-bridge-session.d.ts index 316295744..473013ff3 100644 --- a/types/global/netcatty-bridge-session.d.ts +++ b/types/global/netcatty-bridge-session.d.ts @@ -274,6 +274,10 @@ declare global { action: "overwrite" | "skip" | "cancel"; applyToRest: boolean; }): void; + getTerminalMirrorSnapshot?(sessionId: string): Promise<{ + snapshot: string; + alternateScreen: boolean; + }>; onSessionData(sessionId: string, cb: (data: string) => void): () => void; onSessionExit( sessionId: string, From 7faa0db866072916875297d767553962aa5b11da Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Thu, 25 Jun 2026 01:04:10 +0800 Subject: [PATCH 032/228] fix(terminal): disable hibernate hidden tabs by default Make tab hibernation opt-in so new users keep terminal renderers unless they explicitly enable memory-saving hibernate in settings. Co-authored-by: Cursor --- domain/models/terminal.ts | 2 +- domain/terminalHibernate.test.ts | 4 ++-- domain/terminalHibernate.ts | 2 +- domain/terminalSettings.test.ts | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/domain/models/terminal.ts b/domain/models/terminal.ts index f93ce5eec..14791f600 100644 --- a/domain/models/terminal.ts +++ b/domain/models/terminal.ts @@ -351,7 +351,7 @@ const DEFAULT_TERMINAL_SETTINGS: TerminalSettings = { forcePromptNewLine: false, // Opt-in: keep the next shell prompt visually separated from unterminated final output lines osc52Clipboard: 'write-only', // OSC-52: allow remote programs to write clipboard by default rendererType: 'auto', // Auto-detect best renderer based on hardware - hibernateHiddenTabs: true, + hibernateHiddenTabs: false, hibernateHiddenTabsDelaySec: 5, hibernateSkipAltScreen: true, hibernateKeepRendererCount: 2, diff --git a/domain/terminalHibernate.test.ts b/domain/terminalHibernate.test.ts index d071e6db8..5d22fc99d 100644 --- a/domain/terminalHibernate.test.ts +++ b/domain/terminalHibernate.test.ts @@ -26,8 +26,8 @@ test("capHibernateBufferByLines keeps the most recent lines", () => { assert.equal(capHibernateBufferByLines(input, 2), "line-3\nline-4"); }); -test("resolveTerminalHibernateEnabled defaults to enabled", () => { - assert.equal(resolveTerminalHibernateEnabled(), true); +test("resolveTerminalHibernateEnabled defaults to disabled", () => { + assert.equal(resolveTerminalHibernateEnabled(), false); assert.equal(resolveTerminalHibernateEnabled({ hibernateHiddenTabs: true }), true); assert.equal(resolveTerminalHibernateEnabled({ hibernateHiddenTabs: false }), false); }); diff --git a/domain/terminalHibernate.ts b/domain/terminalHibernate.ts index c475f9ece..643c63ac2 100644 --- a/domain/terminalHibernate.ts +++ b/domain/terminalHibernate.ts @@ -33,7 +33,7 @@ export function resolveTerminalHibernateEnabled( settings?: Pick | null, ): boolean { if (!TERMINAL_HIBERNATE_ENABLED) return false; - return settings?.hibernateHiddenTabs !== false; + return settings?.hibernateHiddenTabs === true; } /** Block hibernate while a file transfer or drag-drop session is in progress. */ diff --git a/domain/terminalSettings.test.ts b/domain/terminalSettings.test.ts index fc23c38a7..797ff92e6 100644 --- a/domain/terminalSettings.test.ts +++ b/domain/terminalSettings.test.ts @@ -17,8 +17,8 @@ test("normalizeTerminalSettings enables font smoothing by default", () => { assert.equal(normalizeTerminalSettings().fontSmoothing, true); }); -test("normalizeTerminalSettings enables hibernate for hidden tabs by default", () => { - assert.equal(normalizeTerminalSettings().hibernateHiddenTabs, true); +test("normalizeTerminalSettings disables hibernate for hidden tabs by default", () => { + assert.equal(normalizeTerminalSettings().hibernateHiddenTabs, false); assert.equal(normalizeTerminalSettings().hibernateHiddenTabsDelaySec, 5); }); From 4259be6f57cd5ec191781202732df34c8aa700d5 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Thu, 25 Jun 2026 01:20:19 +0800 Subject: [PATCH 033/228] fix(ai): allow Netcatty CLI paths for OpenCode skills mode OpenCode skills integration blocked netcatty-tool-cli because external_directory was globally denied. Allowlist launcher, CLI, skill, discovery, and runtime paths while keeping unrelated external access denied. Co-authored-by: Cursor --- electron/bridges/aiBridge/sdk/index.cjs | 1 + .../sdk/netcattySkillsOpenCodePermissions.cjs | 81 +++++++++++++++++++ ...netcattySkillsOpenCodePermissions.test.cjs | 67 +++++++++++++++ .../bridges/aiBridge/sdk/opencodeDriver.cjs | 25 +++--- .../aiBridge/sdk/opencodeDriver.test.cjs | 19 +++++ .../aiBridge/sdk/sdkStreamHandlers.cjs | 13 +++ 6 files changed, 197 insertions(+), 9 deletions(-) create mode 100644 electron/bridges/aiBridge/sdk/netcattySkillsOpenCodePermissions.cjs create mode 100644 electron/bridges/aiBridge/sdk/netcattySkillsOpenCodePermissions.test.cjs diff --git a/electron/bridges/aiBridge/sdk/index.cjs b/electron/bridges/aiBridge/sdk/index.cjs index d02136439..024b08da1 100644 --- a/electron/bridges/aiBridge/sdk/index.cjs +++ b/electron/bridges/aiBridge/sdk/index.cjs @@ -141,6 +141,7 @@ const DRIVER_REGISTRY = { binPath: ctx.binPath, injectedMcpServers: ctx.injectedMcpServers, toolIntegrationMode: ctx.toolIntegrationMode, + skillsPathAllowlist: ctx.skillsPathAllowlist, resumeSessionId: ctx.resumeSessionId, emitter: ctx.emitter, abortController: ctx.abortController, diff --git a/electron/bridges/aiBridge/sdk/netcattySkillsOpenCodePermissions.cjs b/electron/bridges/aiBridge/sdk/netcattySkillsOpenCodePermissions.cjs new file mode 100644 index 000000000..3679090ed --- /dev/null +++ b/electron/bridges/aiBridge/sdk/netcattySkillsOpenCodePermissions.cjs @@ -0,0 +1,81 @@ +"use strict"; + +const fs = require("node:fs"); +const path = require("node:path"); + +function normalizeOpenCodePath(targetPath) { + return process.platform === "win32" + ? targetPath.replace(/\\/g, "/") + : targetPath; +} + +function toOpenCodeDirectoryGlob(dirPath) { + if (!dirPath || typeof dirPath !== "string") return null; + try { + const resolved = path.resolve(dirPath); + let baseDir = resolved; + if (fs.existsSync(resolved) && fs.statSync(resolved).isFile()) { + baseDir = path.dirname(resolved); + } + return `${normalizeOpenCodePath(baseDir)}/**`; + } catch { + return null; + } +} + +function toOpenCodeFileParentGlob(filePath) { + if (!filePath || typeof filePath !== "string") return null; + try { + return toOpenCodeDirectoryGlob(path.dirname(path.resolve(filePath))); + } catch { + return null; + } +} + +function dedupePatterns(patterns) { + return [...new Set(patterns.filter(Boolean))]; +} + +function buildNetcattySkillsOpenCodePathAllowlist({ + launcherPath, + cliScriptPath, + skillPath, + discoveryFilePath, + cliStateDir, + runtimeBinaryPath, +} = {}) { + return dedupePatterns([ + launcherPath && toOpenCodeFileParentGlob(launcherPath), + cliScriptPath && toOpenCodeFileParentGlob(cliScriptPath), + skillPath && toOpenCodeFileParentGlob(skillPath), + discoveryFilePath && toOpenCodeFileParentGlob(discoveryFilePath), + cliStateDir && toOpenCodeDirectoryGlob(cliStateDir), + runtimeBinaryPath && toOpenCodeFileParentGlob(runtimeBinaryPath), + ]); +} + +function buildOpenCodeSkillsPermissionRules(pathAllowlist = []) { + const external_directory = { "*": "deny" }; + const read = {}; + for (const pattern of pathAllowlist) { + external_directory[pattern] = "allow"; + read[pattern] = "allow"; + } + + return { + bash: "allow", + read, + list: "deny", + glob: "deny", + grep: "deny", + skill: "allow", + external_directory, + }; +} + +module.exports = { + buildNetcattySkillsOpenCodePathAllowlist, + buildOpenCodeSkillsPermissionRules, + toOpenCodeDirectoryGlob, + toOpenCodeFileParentGlob, +}; diff --git a/electron/bridges/aiBridge/sdk/netcattySkillsOpenCodePermissions.test.cjs b/electron/bridges/aiBridge/sdk/netcattySkillsOpenCodePermissions.test.cjs new file mode 100644 index 000000000..9369b898d --- /dev/null +++ b/electron/bridges/aiBridge/sdk/netcattySkillsOpenCodePermissions.test.cjs @@ -0,0 +1,67 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { + buildNetcattySkillsOpenCodePathAllowlist, + buildOpenCodeSkillsPermissionRules, + toOpenCodeDirectoryGlob, + toOpenCodeFileParentGlob, +} = require("./netcattySkillsOpenCodePermissions.cjs"); + +test("toOpenCodeFileParentGlob maps files to parent directory globs", () => { + assert.equal( + toOpenCodeFileParentGlob("/Applications/Netcatty.app/Contents/MacOS/netcatty-tool-cli"), + "/Applications/Netcatty.app/Contents/MacOS/**", + ); + assert.equal( + toOpenCodeFileParentGlob("/tmp/netcatty/skills/netcatty-tool-cli/SKILL.md"), + "/tmp/netcatty/skills/netcatty-tool-cli/**", + ); +}); + +test("toOpenCodeDirectoryGlob keeps directory roots stable when missing on disk", () => { + assert.equal( + toOpenCodeDirectoryGlob("/Users/me/Library/Application Support/netcatty/netcatty-tool-cli"), + "/Users/me/Library/Application Support/netcatty/netcatty-tool-cli/**", + ); +}); + +test("buildNetcattySkillsOpenCodePathAllowlist dedupes launcher and script roots", () => { + const launcher = "/Applications/Netcatty.app/Contents/MacOS/netcatty-tool-cli"; + const script = "/Applications/Netcatty.app/Contents/Resources/app.asar.unpacked/electron/cli/netcatty-tool-cli.cjs"; + const skill = "/Applications/Netcatty.app/Contents/Resources/app.asar.unpacked/skills/netcatty-tool-cli/SKILL.md"; + const patterns = buildNetcattySkillsOpenCodePathAllowlist({ + launcherPath: launcher, + cliScriptPath: script, + skillPath: skill, + discoveryFilePath: "/Users/me/Library/Application Support/netcatty/netcatty-tool-cli/discovery.json", + cliStateDir: "/Users/me/Library/Application Support/netcatty/netcatty-tool-cli", + }); + + assert.deepEqual(patterns, [ + "/Applications/Netcatty.app/Contents/MacOS/**", + "/Applications/Netcatty.app/Contents/Resources/app.asar.unpacked/electron/cli/**", + "/Applications/Netcatty.app/Contents/Resources/app.asar.unpacked/skills/netcatty-tool-cli/**", + "/Users/me/Library/Application Support/netcatty/netcatty-tool-cli/**", + ]); +}); + +test("buildOpenCodeSkillsPermissionRules allowlists Netcatty CLI paths and denies other external access", () => { + const rules = buildOpenCodeSkillsPermissionRules([ + "/Applications/Netcatty.app/Contents/MacOS/**", + "/Users/me/Library/Application Support/netcatty/netcatty-tool-cli/**", + ]); + + assert.equal(rules.bash, "allow"); + assert.equal(rules.skill, "allow"); + assert.equal(rules.list, "deny"); + assert.deepEqual(rules.external_directory, { + "/Applications/Netcatty.app/Contents/MacOS/**": "allow", + "/Users/me/Library/Application Support/netcatty/netcatty-tool-cli/**": "allow", + "*": "deny", + }); + assert.deepEqual(rules.read, { + "/Applications/Netcatty.app/Contents/MacOS/**": "allow", + "/Users/me/Library/Application Support/netcatty/netcatty-tool-cli/**": "allow", + }); +}); diff --git a/electron/bridges/aiBridge/sdk/opencodeDriver.cjs b/electron/bridges/aiBridge/sdk/opencodeDriver.cjs index 0164e747b..a033ae014 100644 --- a/electron/bridges/aiBridge/sdk/opencodeDriver.cjs +++ b/electron/bridges/aiBridge/sdk/opencodeDriver.cjs @@ -5,6 +5,9 @@ const fs = require("node:fs"); const path = require("node:path"); const { pathToFileURL } = require("node:url"); const { mcpEnvPairsToObject } = require("./injectMcp.cjs"); +const { + buildOpenCodeSkillsPermissionRules, +} = require("./netcattySkillsOpenCodePermissions.cjs"); const OPENCODE_IMAGE_MEDIA_TYPES = new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]); const DEFAULT_OPENCODE_PORT = 4096; @@ -55,17 +58,21 @@ function toOpenCodeMcpConfig(injectedMcpServers) { return mcp; } -function buildOpenCodeConfig({ model, injectedMcpServers, toolIntegrationMode } = {}) { +function buildOpenCodeConfig({ model, injectedMcpServers, toolIntegrationMode, skillsPathAllowlist } = {}) { const allowBash = toolIntegrationMode === "skills"; + const permission = { + edit: "deny", + bash: allowBash ? "allow" : "deny", + webfetch: "deny", + external_directory: "deny", + }; + if (allowBash && Array.isArray(skillsPathAllowlist) && skillsPathAllowlist.length > 0) { + Object.assign(permission, buildOpenCodeSkillsPermissionRules(skillsPathAllowlist)); + } const config = { share: "disabled", autoupdate: false, - permission: { - edit: "deny", - bash: allowBash ? "allow" : "deny", - webfetch: "deny", - external_directory: "deny", - }, + permission, mcp: toOpenCodeMcpConfig(injectedMcpServers), }; if (model) config.model = model; @@ -505,9 +512,9 @@ function createStopWait() { async function runOpenCodeTurn({ prompt, systemPrompt, attachments, cwd, model, injectedMcpServers, toolIntegrationMode, - resumeSessionId, env, binPath, emitter, abortController, openCodeFactory, + skillsPathAllowlist, resumeSessionId, env, binPath, emitter, abortController, openCodeFactory, }) { - const config = buildOpenCodeConfig({ model, injectedMcpServers, toolIntegrationMode }); + const config = buildOpenCodeConfig({ model, injectedMcpServers, toolIntegrationMode, skillsPathAllowlist }); let opencode = null; let sessionId = resumeSessionId || null; let hasContent = false; diff --git a/electron/bridges/aiBridge/sdk/opencodeDriver.test.cjs b/electron/bridges/aiBridge/sdk/opencodeDriver.test.cjs index b4c84ec64..49b6f8204 100644 --- a/electron/bridges/aiBridge/sdk/opencodeDriver.test.cjs +++ b/electron/bridges/aiBridge/sdk/opencodeDriver.test.cjs @@ -64,6 +64,25 @@ test("buildOpenCodeConfig isolates local tools and injects Netcatty MCP", () => }); }); +test("buildOpenCodeConfig allowlists Netcatty CLI paths in skills mode", () => { + const cfg = buildOpenCodeConfig({ + toolIntegrationMode: "skills", + skillsPathAllowlist: [ + "/Applications/Netcatty.app/Contents/MacOS/**", + "/Users/me/Library/Application Support/netcatty/netcatty-tool-cli/**", + ], + }); + + assert.equal(cfg.permission.bash, "allow"); + assert.equal(cfg.permission.skill, "allow"); + assert.equal(cfg.permission.list, "deny"); + assert.deepEqual(cfg.permission.external_directory, { + "/Applications/Netcatty.app/Contents/MacOS/**": "allow", + "/Users/me/Library/Application Support/netcatty/netcatty-tool-cli/**": "allow", + "*": "deny", + }); +}); + test("buildOpenCodePromptParts includes supported images as file parts", () => { assert.deepEqual(buildOpenCodePromptParts("describe", [ { filename: "shot.png", mediaType: "image/png", filePath: "/tmp/shot.png", base64Data: "abc" }, diff --git a/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs b/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs index 6f152571e..bde997b6b 100644 --- a/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs +++ b/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs @@ -4,6 +4,8 @@ const { getDriver, listBackends } = require("./index.cjs"); const { buildSdkAgentEnv } = require("./env.cjs"); const { buildInjectedMcpServers } = require("./injectMcp.cjs"); const { createStreamEmitter } = require("./emit.cjs"); +const { buildNetcattySkillsOpenCodePathAllowlist } = require("./netcattySkillsOpenCodePermissions.cjs"); +const { getToolCliStateDir } = require("../../cli/discoveryPath.cjs"); const { realpathSync } = require("node:fs"); const VALID_BACKENDS = new Set(listBackends()); @@ -404,6 +406,16 @@ function registerSdkStreamHandlers(ctx) { } }, }; + const skillsPathAllowlist = effectiveMode === "skills" && backendKey === "opencode" + ? buildNetcattySkillsOpenCodePathAllowlist({ + launcherPath: NETCATTY_TOOL_LAUNCHER_PATH, + cliScriptPath: NETCATTY_TOOL_CLI_PATH, + skillPath: NETCATTY_TOOL_SKILL_PATH, + discoveryFilePath: cliDiscoveryFilePath, + cliStateDir: getToolCliStateDir(), + runtimeBinaryPath: process.execPath, + }) + : undefined; const result = await driver.runTurn({ prompt: backendKey === "opencode" ? turnPrompt : contextualPrompt, systemPrompt: backendKey === "opencode" ? systemContext : undefined, @@ -414,6 +426,7 @@ function registerSdkStreamHandlers(ctx) { injectedMcpServers, claudeSettings, toolIntegrationMode: effectiveMode, + skillsPathAllowlist, emitter: driverEmitter, signal: abortController.signal, abortController, From 1349df9c0c82ea5c893b434b40a0987de0d09b6c Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Thu, 25 Jun 2026 01:21:51 +0800 Subject: [PATCH 034/228] fix(ai): correct discoveryPath import in sdkStreamHandlers Use ../../../cli/discoveryPath.cjs from the sdk folder so Electron dev startup no longer fails with MODULE_NOT_FOUND. Co-authored-by: Cursor --- electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs b/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs index bde997b6b..01bb48c85 100644 --- a/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs +++ b/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs @@ -5,7 +5,7 @@ const { buildSdkAgentEnv } = require("./env.cjs"); const { buildInjectedMcpServers } = require("./injectMcp.cjs"); const { createStreamEmitter } = require("./emit.cjs"); const { buildNetcattySkillsOpenCodePathAllowlist } = require("./netcattySkillsOpenCodePermissions.cjs"); -const { getToolCliStateDir } = require("../../cli/discoveryPath.cjs"); +const { getToolCliStateDir } = require("../../../cli/discoveryPath.cjs"); const { realpathSync } = require("node:fs"); const VALID_BACKENDS = new Set(listBackends()); From 7ee58887954dc0e94b754ac714c9c2825ae479df Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Thu, 25 Jun 2026 01:30:16 +0800 Subject: [PATCH 035/228] fix(ai): align OpenCode skills allowlist with live app paths Use Electron userData for CLI state fallback, include Netcatty temp dir and staged attachment paths, and drop duplicate cliStateDir when discovery file is already scoped. Co-authored-by: Cursor --- .../sdk/netcattySkillsOpenCodePermissions.cjs | 17 ++++++++++++----- .../netcattySkillsOpenCodePermissions.test.cjs | 13 +++++++++++++ .../bridges/aiBridge/sdk/sdkStreamHandlers.cjs | 11 +++++++++-- 3 files changed, 34 insertions(+), 7 deletions(-) diff --git a/electron/bridges/aiBridge/sdk/netcattySkillsOpenCodePermissions.cjs b/electron/bridges/aiBridge/sdk/netcattySkillsOpenCodePermissions.cjs index 3679090ed..4c6579dd7 100644 --- a/electron/bridges/aiBridge/sdk/netcattySkillsOpenCodePermissions.cjs +++ b/electron/bridges/aiBridge/sdk/netcattySkillsOpenCodePermissions.cjs @@ -43,14 +43,21 @@ function buildNetcattySkillsOpenCodePathAllowlist({ discoveryFilePath, cliStateDir, runtimeBinaryPath, + tempDir, + extraFilePaths, } = {}) { + const filePaths = [ + launcherPath, + cliScriptPath, + skillPath, + discoveryFilePath, + runtimeBinaryPath, + ...(Array.isArray(extraFilePaths) ? extraFilePaths : []), + ]; return dedupePatterns([ - launcherPath && toOpenCodeFileParentGlob(launcherPath), - cliScriptPath && toOpenCodeFileParentGlob(cliScriptPath), - skillPath && toOpenCodeFileParentGlob(skillPath), - discoveryFilePath && toOpenCodeFileParentGlob(discoveryFilePath), + ...filePaths.map((filePath) => filePath && toOpenCodeFileParentGlob(filePath)), cliStateDir && toOpenCodeDirectoryGlob(cliStateDir), - runtimeBinaryPath && toOpenCodeFileParentGlob(runtimeBinaryPath), + tempDir && toOpenCodeDirectoryGlob(tempDir), ]); } diff --git a/electron/bridges/aiBridge/sdk/netcattySkillsOpenCodePermissions.test.cjs b/electron/bridges/aiBridge/sdk/netcattySkillsOpenCodePermissions.test.cjs index 9369b898d..94a32c93f 100644 --- a/electron/bridges/aiBridge/sdk/netcattySkillsOpenCodePermissions.test.cjs +++ b/electron/bridges/aiBridge/sdk/netcattySkillsOpenCodePermissions.test.cjs @@ -46,6 +46,19 @@ test("buildNetcattySkillsOpenCodePathAllowlist dedupes launcher and script roots ]); }); +test("buildNetcattySkillsOpenCodePathAllowlist includes temp dir and extra attachment paths", () => { + const patterns = buildNetcattySkillsOpenCodePathAllowlist({ + discoveryFilePath: "/Users/me/Library/Application Support/netcatty/netcatty-tool-cli/discovery.json", + tempDir: "/var/folders/tmp/Netcatty", + extraFilePaths: ["/var/folders/tmp/Netcatty/ai-attachment-1.png"], + }); + + assert.deepEqual(patterns, [ + "/Users/me/Library/Application Support/netcatty/netcatty-tool-cli/**", + "/var/folders/tmp/Netcatty/**", + ]); +}); + test("buildOpenCodeSkillsPermissionRules allowlists Netcatty CLI paths and denies other external access", () => { const rules = buildOpenCodeSkillsPermissionRules([ "/Applications/Netcatty.app/Contents/MacOS/**", diff --git a/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs b/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs index 01bb48c85..10633cd6d 100644 --- a/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs +++ b/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs @@ -6,6 +6,7 @@ const { buildInjectedMcpServers } = require("./injectMcp.cjs"); const { createStreamEmitter } = require("./emit.cjs"); const { buildNetcattySkillsOpenCodePathAllowlist } = require("./netcattySkillsOpenCodePermissions.cjs"); const { getToolCliStateDir } = require("../../../cli/discoveryPath.cjs"); +const tempDirBridge = require("../../tempDirBridge.cjs"); const { realpathSync } = require("node:fs"); const VALID_BACKENDS = new Set(listBackends()); @@ -411,9 +412,15 @@ function registerSdkStreamHandlers(ctx) { launcherPath: NETCATTY_TOOL_LAUNCHER_PATH, cliScriptPath: NETCATTY_TOOL_CLI_PATH, skillPath: NETCATTY_TOOL_SKILL_PATH, - discoveryFilePath: cliDiscoveryFilePath, - cliStateDir: getToolCliStateDir(), + discoveryFilePath: cliDiscoveryFilePath || undefined, + cliStateDir: cliDiscoveryFilePath + ? undefined + : getToolCliStateDir({ userDataDir: electronModule?.getPath?.("userData") }), runtimeBinaryPath: process.execPath, + tempDir: tempDirBridge.getTempDir(), + extraFilePaths: stagedAttachments + .map((attachment) => attachment?.filePath) + .filter(Boolean), }) : undefined; const result = await driver.runTurn({ From f0f858447ea9fe63cfa59309f09d6323024b4ca1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Thu, 25 Jun 2026 01:36:55 +0800 Subject: [PATCH 036/228] fix(ai): restore Codex thinking level picker in model dropdown (#1638) Inline thinking levels under each model row so they are not clipped by the scrollable model list container introduced for OpenCode. Co-authored-by: Cursor --- components/ai/ChatInput.tsx | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/components/ai/ChatInput.tsx b/components/ai/ChatInput.tsx index 34150e728..5c479dea0 100644 --- a/components/ai/ChatInput.tsx +++ b/components/ai/ChatInput.tsx @@ -512,6 +512,9 @@ const ChatInput: React.FC = ({ : (selectedPreset ? selectedPreset.name + (selectedThinking ? ` / ${formatThinkingLabel(selectedThinking)}` : '') : modelName || providerName || t('ai.chat.noModel')); + const modelChipMaxWidth = hasProviderSwitcher + ? 'max-w-[180px]' + : (selectedThinking ? 'max-w-[148px]' : 'max-w-[82px]'); const hasModelPicker = hasProviderSwitcher || (modelPresets.length > 0 && !!onModelSelect); const popoverMaxWidth = hasProviderSwitcher ? PROVIDER_PICKER_MAX_WIDTH : MODEL_PICKER_MAX_WIDTH; const chipClassName = @@ -819,6 +822,9 @@ const ChatInput: React.FC = ({ const left = Math.max(8, Math.min(rect.left, window.innerWidth - popoverMaxWidth - 8)); setMenuPos({ left, bottom: window.innerHeight - rect.top + 6 }); } + if (selectedPreset?.thinkingLevels?.length) { + setHoveredModelId(selectedPreset.id); + } setActiveMenu('model'); } else { closeAllMenus(); @@ -833,7 +839,7 @@ const ChatInput: React.FC = ({ ) : ( )} - {modelLabel} + {modelLabel} {hasModelPicker && } {showModelPicker && hasModelPicker && menuPos && createPortal( @@ -898,10 +904,10 @@ const ChatInput: React.FC = ({ {modelPresets.map(preset => { const isSelected = preset.id === selectedBaseModelId; const hasThinking = preset.thinkingLevels && preset.thinkingLevels.length > 0; + const showThinkingLevels = hasThinking && hoveredModelId === preset.id; return (
setHoveredModelId(hasThinking ? preset.id : null)} onFocus={() => { if (hasThinking) setHoveredModelId(preset.id); }} onBlur={(e) => { if (!e.currentTarget.contains(e.relatedTarget)) setHoveredModelId(null); }} @@ -910,21 +916,29 @@ const ChatInput: React.FC = ({ type="button" role="option" aria-selected={isSelected} + aria-expanded={hasThinking ? showThinkingLevels : undefined} onClick={() => { if (!hasThinking) { onModelSelect?.(preset.id); closeAllMenus(); + return; } + setHoveredModelId(showThinkingLevels ? null : preset.id); }} className="w-full min-w-0 flex items-center gap-1.5 px-3 py-1.5 text-left text-[12px] hover:bg-muted/30 transition-colors cursor-pointer" > {isSelected ? : } {preset.name} - {hasThinking && } + {hasThinking && ( + + )} - {/* Thinking level sub-menu */} - {hasThinking && hoveredModelId === preset.id && ( -
+ {/* Inline thinking levels — flyout submenus get clipped by overflow-y-auto above. */} + {showThinkingLevels && ( +
{preset.thinkingLevels!.map(level => { const fullId = `${preset.id}/${level}`; const isLevelSelected = selectedModelId === fullId; @@ -949,7 +963,7 @@ const ChatInput: React.FC = ({ closeAllMenus(); } }} - className="w-full flex items-center gap-1.5 px-3 py-1.5 text-left text-[12px] hover:bg-muted/30 transition-colors cursor-pointer whitespace-nowrap" + className="w-full flex items-center gap-1.5 pl-7 pr-3 py-1.5 text-left text-[12px] hover:bg-muted/30 transition-colors cursor-pointer whitespace-nowrap" > {isLevelSelected ? : } {formatThinkingLabel(level)} From 15baefaa57227d8eb96e404304c1e5f891866490 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Thu, 25 Jun 2026 02:21:10 +0800 Subject: [PATCH 037/228] fix(deps): resync package-lock.json for npm 10 npm ci (#1639) Restore peer dependency lock entries removed in #1635 so CI npm ci on Node 22 succeeds again. Co-authored-by: Cursor --- package-lock.json | 93 ++++++++++++++++++++++++++++++++--------------- 1 file changed, 64 insertions(+), 29 deletions(-) diff --git a/package-lock.json b/package-lock.json index 8b58b2669..dc787e140 100644 --- a/package-lock.json +++ b/package-lock.json @@ -341,6 +341,29 @@ "win32" ] }, + "node_modules/@anthropic-ai/sdk": { + "version": "0.105.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.105.0.tgz", + "integrity": "sha512-sDyu+aM9cE6uZE+HgRjjHRb+qqb87GHZOx+8bE0YlWetdL1YcVLxn8h9ltxGOflyChTe6PMEo50kMQV4cw0hfg==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "json-schema-to-ts": "^3.1.1", + "standardwebhooks": "^1.0.0" + }, + "bin": { + "anthropic-ai-sdk": "bin/cli" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } + } + }, "node_modules/@aws-crypto/crc32": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/@aws-crypto/crc32/-/crc32-5.2.0.tgz", @@ -1270,7 +1293,6 @@ "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", @@ -1551,6 +1573,14 @@ "node": ">=6.9.0" } }, + "node_modules/@bufbuild/protobuf": { + "version": "1.10.1", + "resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-1.10.1.tgz", + "integrity": "sha512-wJ8ReQbHxsAfXhrf9ixl0aYbZorRuOWpBNzm8pL8ftmSxQx/wnJD5Eg861NwJU/czy2VXFIebCeZnZrI9rktIQ==", + "license": "(Apache-2.0 AND BSD-3-Clause)", + "optional": true, + "peer": true + }, "node_modules/@buttercup/fetch": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/@buttercup/fetch/-/fetch-0.2.1.tgz", @@ -1869,7 +1899,6 @@ "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.3.tgz", "integrity": "sha512-QwCZW6Tt1siP37Jet9Tb02Zs81TQt6qQrZR2H+eGMcFsL1zMrk2/b9CLC7/9ieP1fjIUMgviLWMmgiHoJrj+ZA==", "license": "MIT", - "peer": true, "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.23.0", @@ -1959,7 +1988,6 @@ "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.6.0.tgz", "integrity": "sha512-4nbvra5R5EtiCzr9BTHiTLc+MLXK2QGiAVYMyi8PkQd3SR+6ixar/Q/01Fa21TBIDOZXgeWV4WppsQolSreAPQ==", "license": "MIT", - "peer": true, "dependencies": { "@marijn/find-cluster-break": "^1.0.0" } @@ -1969,7 +1997,6 @@ "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.1.tgz", "integrity": "sha512-+BIjw/AG3tDQ4pJgTLPYdAW25eDE66YsvM4LKyVPgGzVgZ4a9Wj1SRX8kPVKgBDdPt8oHtZ15F0qx7p0oOHdHw==", "license": "MIT", - "peer": true, "dependencies": { "@codemirror/state": "^6.6.0", "crelt": "^1.0.6", @@ -1977,6 +2004,16 @@ "w3c-keyname": "^2.2.4" } }, + "node_modules/@connectrpc/connect": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@connectrpc/connect/-/connect-1.7.0.tgz", + "integrity": "sha512-iNKdJRi69YP3mq6AePRT8F/HrxWCewrhxnLMNm0vpqXAR8biwzRtO6Hjx80C6UvtKJ5sFmffQT7I4Baecz389w==", + "license": "Apache-2.0", + "optional": true, + "peerDependencies": { + "@bufbuild/protobuf": "^1.10.0" + } + }, "node_modules/@connectrpc/connect-node": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/@connectrpc/connect-node/-/connect-node-1.7.0.tgz", @@ -2424,6 +2461,7 @@ "dev": true, "license": "BSD-2-Clause", "optional": true, + "peer": true, "dependencies": { "cross-dirname": "^0.1.0", "debug": "^4.3.4", @@ -2445,6 +2483,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", @@ -3854,7 +3893,6 @@ "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz", "integrity": "sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==", "license": "MIT", - "peer": true, "dependencies": { "@lezer/common": "^1.3.0" } @@ -4137,7 +4175,6 @@ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz", "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==", "license": "MIT", - "peer": true, "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", @@ -7560,7 +7597,8 @@ "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz", "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==", "license": "MIT", - "optional": true + "optional": true, + "peer": true }, "node_modules/@standard-schema/spec": { "version": "1.1.0", @@ -8184,7 +8222,6 @@ "integrity": "sha512-hAAP5io/7csFStuOmR782YmTthKBJ9ND3WVL60hcOjvtGFb+HJxH4O5huAcmcZ9v9G8P+JETiZ/G1B8MALnWZQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.54.0", @@ -8214,7 +8251,6 @@ "integrity": "sha512-BtE0k6cjwjLZoZixN0t5AKP0kSzlGu7FctRXYuPAm//aaiZhmfq1JwdYpYr1brzEspYyFeF+8XF5j2VK6oalrA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.54.0", "@typescript-eslint/types": "8.54.0", @@ -8577,7 +8613,6 @@ "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.1.0-beta.220.tgz", "integrity": "sha512-rwEKE75wfwfNWeGnjl0iQRA1W50HigKoGcGMeF3o5CqDSdI9IjmwzpV9xHXqLH6CYj6s9N1g6bbKFVDou9dJ/A==", "license": "MIT", - "peer": true, "workspaces": [ "addons/*" ] @@ -8642,7 +8677,6 @@ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -9344,7 +9378,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", @@ -10170,7 +10203,8 @@ "integrity": "sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q==", "dev": true, "license": "MIT", - "optional": true + "optional": true, + "peer": true }, "node_modules/cross-env": { "version": "10.1.0", @@ -10467,7 +10501,6 @@ "integrity": "sha512-fMkjRqKyPtsz4Kzu/qGP0BGjqzMCIgp+/7kw/u6YH6lvn/8hvL3c0TXhoFayBoYdpPCnEinnCHztd4bW7/jetA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "app-builder-lib": "26.15.2", "builder-util": "26.15.0", @@ -10749,6 +10782,7 @@ "dev": true, "hasInstallScript": true, "license": "MIT", + "peer": true, "dependencies": { "@electron/asar": "^3.2.1", "debug": "^4.1.1", @@ -10769,6 +10803,7 @@ "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "graceful-fs": "^4.1.2", "jsonfile": "^4.0.0", @@ -10784,6 +10819,7 @@ "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", "dev": true, "license": "MIT", + "peer": true, "optionalDependencies": { "graceful-fs": "^4.1.6" } @@ -10794,6 +10830,7 @@ "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">= 4.0.0" } @@ -11018,7 +11055,6 @@ "integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.1", @@ -11472,7 +11508,8 @@ "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz", "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==", "license": "Unlicense", - "optional": true + "optional": true, + "peer": true }, "node_modules/fast-uri": { "version": "3.1.0", @@ -12409,7 +12446,6 @@ "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.14.tgz", "integrity": "sha512-am5zfg3yu6sqn5yjKBNqhnTX7Cv+m00ox+7jbaKkrLMRJ4rAdldd1xPd/JzbBWspqaQv6RSTrgFN95EsfhC+7w==", "license": "MIT", - "peer": true, "engines": { "node": ">=16.9.0" } @@ -12866,6 +12902,7 @@ "resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz", "integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==", "license": "MIT", + "peer": true, "funding": { "type": "GitHub Sponsors ❤", "url": "https://github.com/sponsors/dmonad" @@ -12987,6 +13024,7 @@ "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", "license": "MIT", "optional": true, + "peer": true, "dependencies": { "@babel/runtime": "^7.18.3", "ts-algebra": "^2.0.0" @@ -13144,6 +13182,7 @@ "resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.117.tgz", "integrity": "sha512-DeXj9X5xDCjgKLU/7RR+/HQEVzuuEUiwldwOGsHK/sfAfELGWEyTcf0x+uOvCvK3O2zPmZePXWL85vtia6GyZw==", "license": "MIT", + "peer": true, "dependencies": { "isomorphic.js": "^0.2.4" }, @@ -14089,7 +14128,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", @@ -15210,6 +15248,7 @@ "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "minimist": "^1.2.6" }, @@ -15229,7 +15268,6 @@ "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.55.1.tgz", "integrity": "sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A==", "license": "MIT", - "peer": true, "dependencies": { "dompurify": "3.2.7", "marked": "14.0.0" @@ -15980,6 +16018,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "commander": "^9.4.0" }, @@ -15997,6 +16036,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": "^12.20.0 || >=14" } @@ -16301,7 +16341,6 @@ "resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz", "integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==", "license": "MIT", - "peer": true, "engines": { "node": ">=0.10.0" } @@ -16311,7 +16350,6 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz", "integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==", "license": "MIT", - "peer": true, "dependencies": { "scheduler": "^0.27.0" }, @@ -17649,6 +17687,7 @@ "integrity": "sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==", "license": "MIT", "optional": true, + "peer": true, "dependencies": { "@stablelib/base64": "^1.0.0", "fast-sha256": "^1.3.0" @@ -17954,6 +17993,7 @@ "integrity": "sha512-yYrrsWnrXMcdsnu/7YMYAofM1ktpL5By7vZhf15CrXijWWrEYZks5AXBudalfSWJLlnen/QUJUB5aoB0kqZUGA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "mkdirp": "^0.5.1", "rimraf": "~2.6.2" @@ -17980,6 +18020,7 @@ "deprecated": "Rimraf versions prior to v4 are no longer supported", "dev": true, "license": "ISC", + "peer": true, "dependencies": { "glob": "^7.1.3" }, @@ -18054,7 +18095,6 @@ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -18149,7 +18189,8 @@ "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", "license": "MIT", - "optional": true + "optional": true, + "peer": true }, "node_modules/ts-api-utils": { "version": "2.4.0", @@ -18176,7 +18217,6 @@ "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "esbuild": "~0.27.0", "get-tsconfig": "^4.7.5" @@ -18288,7 +18328,6 @@ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -18329,7 +18368,6 @@ "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz", "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==", "license": "MIT", - "peer": true, "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", @@ -18705,7 +18743,6 @@ "integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", @@ -18799,7 +18836,6 @@ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -19087,7 +19123,6 @@ "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", "license": "MIT", - "peer": true, "funding": { "url": "https://github.com/sponsors/colinhacks" } From bf723e73486a327efbafff0113685c2c52e257aa Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Thu, 25 Jun 2026 09:42:19 +0800 Subject: [PATCH 038/228] fix: remove terminal background mirror --- application/i18n/locales/en/core.ts | 2 - application/i18n/locales/zh-CN/terminal.ts | 2 - application/state/terminalMirrorSnapshot.ts | 12 --- application/state/useTerminalBackend.ts | 12 --- components/Terminal.tsx | 22 +--- .../settings/tabs/SettingsTerminalTab.tsx | 9 -- .../terminal/terminalHibernateRuntime.ts | 2 - components/terminal/terminalRuntimeMount.ts | 1 - .../terminal/useTerminalHibernateEffect.ts | 5 - domain/models/terminal.ts | 3 - .../terminalHibernate.optimizations.test.ts | 6 -- domain/terminalHibernate.ts | 8 -- electron/bridges/emitTerminalSessionData.cjs | 41 +------ electron/bridges/terminalBridge.cjs | 7 +- electron/bridges/terminalHeadlessMirror.cjs | 100 ------------------ .../bridges/terminalHeadlessMirror.test.cjs | 21 ---- electron/main/registerBridges.cjs | 2 - electron/preload/api.cjs | 3 - package-lock.json | 38 ------- package.json | 2 - types/global/netcatty-bridge-session.d.ts | 4 - 21 files changed, 4 insertions(+), 298 deletions(-) delete mode 100644 application/state/terminalMirrorSnapshot.ts delete mode 100644 electron/bridges/terminalHeadlessMirror.cjs delete mode 100644 electron/bridges/terminalHeadlessMirror.test.cjs diff --git a/application/i18n/locales/en/core.ts b/application/i18n/locales/en/core.ts index 9f131e9a4..d33a98928 100644 --- a/application/i18n/locales/en/core.ts +++ b/application/i18n/locales/en/core.ts @@ -487,8 +487,6 @@ export const enCoreMessages: Messages = { 'settings.terminal.rendering.hibernateSkipAltScreen.desc': 'Keep the terminal renderer alive while vim, htop, or agent TUIs own the alternate screen buffer.', 'settings.terminal.rendering.hibernateKeepRendererCount': 'Keep hidden renderers', 'settings.terminal.rendering.hibernateKeepRendererCount.desc': 'How many off-screen tabs keep their renderer alive (WebGL suspended) before full hibernate.', - 'settings.terminal.rendering.hibernateUseHeadlessMirror': 'Main-process terminal mirror', - 'settings.terminal.rendering.hibernateUseHeadlessMirror.desc': 'Mirror PTY output in a headless xterm on the main process for faster wake snapshots.', 'settings.terminal.rendering.hibernateReplayChunkBytes': 'Wake replay chunk size', 'settings.terminal.rendering.hibernateReplayChunkBytes.desc': 'Bytes replayed per animation frame when restoring a hibernated terminal (4–64 KB).', 'settings.terminal.rendering.hibernatePreferWasmSerialize': 'Prefer WASM serialize', diff --git a/application/i18n/locales/zh-CN/terminal.ts b/application/i18n/locales/zh-CN/terminal.ts index c57df9e7a..5a344142f 100644 --- a/application/i18n/locales/zh-CN/terminal.ts +++ b/application/i18n/locales/zh-CN/terminal.ts @@ -359,8 +359,6 @@ export const zhCNTerminalMessages: Messages = { 'settings.terminal.rendering.hibernateSkipAltScreen.desc': 'vim、htop 或 Agent TUI 占用 alternate screen 时保持终端渲染器,避免慢恢复。', 'settings.terminal.rendering.hibernateKeepRendererCount': '保留隐藏渲染器数量', 'settings.terminal.rendering.hibernateKeepRendererCount.desc': '多少个不可见标签页仅暂停 WebGL、不销毁 xterm,超出后才完整休眠。', - 'settings.terminal.rendering.hibernateUseHeadlessMirror': '主进程终端镜像', - 'settings.terminal.rendering.hibernateUseHeadlessMirror.desc': '在主进程用 headless xterm 镜像 PTY 输出,加快休眠唤醒时的快照获取。', 'settings.terminal.rendering.hibernateReplayChunkBytes': '唤醒分片大小', 'settings.terminal.rendering.hibernateReplayChunkBytes.desc': '恢复休眠终端时每帧回放的 ANSI 字节数(4–64 KB)。', 'settings.terminal.rendering.hibernatePreferWasmSerialize': '优先 WASM 序列化', diff --git a/application/state/terminalMirrorSnapshot.ts b/application/state/terminalMirrorSnapshot.ts deleted file mode 100644 index 026be4ee0..000000000 --- a/application/state/terminalMirrorSnapshot.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { TerminalHibernateSnapshot } from "../../components/terminal/terminalHibernateRuntime"; - -export function mirrorSnapshotToHibernateSnapshot( - mirror: { snapshot: string; alternateScreen: boolean }, -): TerminalHibernateSnapshot { - return { - snapshot: mirror.snapshot, - viewportSnapshot: mirror.snapshot, - scrollbackSnapshot: "", - alternateScreen: mirror.alternateScreen, - }; -} diff --git a/application/state/useTerminalBackend.ts b/application/state/useTerminalBackend.ts index 6b658ff54..f420214ad 100644 --- a/application/state/useTerminalBackend.ts +++ b/application/state/useTerminalBackend.ts @@ -100,16 +100,6 @@ export const useTerminalBackend = () => { return bridge.setSessionEncoding(sessionId, encoding); }, []); - const getTerminalMirrorSnapshot = useCallback(async (sessionId: string) => { - const bridge = netcattyBridge.get(); - if (!bridge?.getTerminalMirrorSnapshot) return null; - try { - return await bridge.getTerminalMirrorSnapshot(sessionId); - } catch { - return null; - } - }, []); - const onSessionData = useCallback((sessionId: string, cb: (data: string) => void) => { const bridge = netcattyBridge.get(); if (!bridge?.onSessionData) throw new Error("onSessionData unavailable"); @@ -338,7 +328,6 @@ export const useTerminalBackend = () => { setSessionFlowPaused, closeSession, setSessionEncoding, - getTerminalMirrorSnapshot, onSessionData, onSessionExit, onTelnetAutoLoginComplete, @@ -387,7 +376,6 @@ export const useTerminalBackend = () => { setSessionFlowPaused, closeSession, setSessionEncoding, - getTerminalMirrorSnapshot, onSessionData, onSessionExit, onTelnetAutoLoginComplete, diff --git a/components/Terminal.tsx b/components/Terminal.tsx index c98521575..ec9b4a022 100644 --- a/components/Terminal.tsx +++ b/components/Terminal.tsx @@ -96,14 +96,12 @@ import { resolveHibernateKeepRendererCount, resolveHibernatePreferWasmSerialize, resolveHibernateSkipAltScreen, - resolveHibernateUseHeadlessMirror, resolveTerminalHibernateDelayMs, resolveTerminalHibernateEnabled, resolveTerminalHibernateReplayChunkBytes, type TerminalHibernateWakePayload, } from "../domain/terminalHibernate"; import { terminalHiddenRendererStore } from "../application/state/terminalHiddenRendererStore"; -import { mirrorSnapshotToHibernateSnapshot } from "../application/state/terminalMirrorSnapshot"; import { wakeTerminalFromHibernate, type TerminalRuntimeRefs, @@ -243,7 +241,6 @@ const TerminalComponent: React.FC = ({ const hibernateSnapshotRef = useRef(""); const hibernateViewportSnapshotRef = useRef(""); const hibernateScrollbackSnapshotRef = useRef(""); - const hibernateMirrorPreferredRef = useRef(false); const hibernatePendingBufferRef = useRef(""); const hibernateAlternateScreenRef = useRef(false); const wakeInProgressRef = useRef(false); @@ -843,7 +840,6 @@ const TerminalComponent: React.FC = ({ hibernateSnapshotRef.current = ""; hibernateViewportSnapshotRef.current = ""; hibernateScrollbackSnapshotRef.current = ""; - hibernateMirrorPreferredRef.current = false; hibernatePendingBufferRef.current = ""; hibernateAlternateScreenRef.current = false; terminalHiddenRendererStore.clearSoftHidden(sessionId); @@ -881,13 +877,11 @@ const TerminalComponent: React.FC = ({ scrollbackSnapshot: string; alternateScreen: boolean; }, - mirrorPreferred: boolean, ) => { hibernateSnapshotRef.current = snapshot.snapshot; hibernateViewportSnapshotRef.current = snapshot.viewportSnapshot; hibernateScrollbackSnapshotRef.current = snapshot.scrollbackSnapshot; hibernateAlternateScreenRef.current = snapshot.alternateScreen; - hibernateMirrorPreferredRef.current = mirrorPreferred; }, []); const fullHibernateRuntime = useCallback(async () => { @@ -898,27 +892,18 @@ const TerminalComponent: React.FC = ({ terminalHiddenRendererStore.clearSoftHidden(sessionId); softHiddenRef.current = false; - let snapshot = await serializeTerminalForHibernate( + const snapshot = await serializeTerminalForHibernate( termRef.current, serializeAddonRef.current, { preferWasm: resolveHibernatePreferWasmSerialize(terminalSettings) }, ); - let mirrorPreferred = false; - - if (resolveHibernateUseHeadlessMirror(terminalSettings)) { - const mirror = await terminalBackend.getTerminalMirrorSnapshot(backendId); - if (mirror && mirror.snapshot.length > 0) { - snapshot = mirrorSnapshotToHibernateSnapshot(mirror); - mirrorPreferred = true; - } - } if (snapshot.alternateScreen && snapshot.snapshot.length === 0) { logger.info("[Terminal] Skipping hibernate: alternate screen snapshot unavailable", { sessionId }); return; } - applyHibernateSnapshot(snapshot, mirrorPreferred); + applyHibernateSnapshot(snapshot); isBootActiveRef.current = false; disposeRuntimeOnly(); beginHibernatedSessionListeners(backendId); @@ -929,13 +914,11 @@ const TerminalComponent: React.FC = ({ viewportChars: hibernateViewportSnapshotRef.current.length, scrollbackChars: hibernateScrollbackSnapshotRef.current.length, alternateScreen: snapshot.alternateScreen, - mirrorPreferred, }); }, [ applyHibernateSnapshot, beginHibernatedSessionListeners, sessionId, - terminalBackend, terminalSettings, ]); @@ -1796,7 +1779,6 @@ const TerminalComponent: React.FC = ({ hibernateSnapshotRef, hibernateViewportSnapshotRef, hibernateScrollbackSnapshotRef, - hibernateMirrorPreferredRef, hibernateAlternateScreenRef, hasRuntimeRef, onHibernate: hibernateRuntime, diff --git a/components/settings/tabs/SettingsTerminalTab.tsx b/components/settings/tabs/SettingsTerminalTab.tsx index 528cd9ef1..5340f8577 100644 --- a/components/settings/tabs/SettingsTerminalTab.tsx +++ b/components/settings/tabs/SettingsTerminalTab.tsx @@ -1038,15 +1038,6 @@ function SettingsTerminalTab(props: { className="w-20" /> - - updateTerminalSetting("hibernateUseHeadlessMirror", v)} - /> - ; hibernateViewportSnapshotRef: React.MutableRefObject; hibernateScrollbackSnapshotRef: React.MutableRefObject; - hibernateMirrorPreferredRef: React.MutableRefObject; hibernateAlternateScreenRef: React.MutableRefObject; hasRuntimeRef: React.MutableRefObject; onHibernate: () => void; @@ -53,7 +52,6 @@ export function useTerminalHibernateEffect({ hibernateSnapshotRef, hibernateViewportSnapshotRef, hibernateScrollbackSnapshotRef, - hibernateMirrorPreferredRef, hibernateAlternateScreenRef, hasRuntimeRef, onHibernate, @@ -86,7 +84,6 @@ export function useTerminalHibernateEffect({ hibernateScrollbackSnapshotRef.current = ""; hibernatePendingBufferRef.current = ""; hibernateAlternateScreenRef.current = false; - hibernateMirrorPreferredRef.current = false; hibernatedRef.current = false; }; @@ -123,7 +120,6 @@ export function useTerminalHibernateEffect({ scrollbackSnapshot: hibernateScrollbackSnapshotRef.current, pendingBuffer: hibernatePendingBufferRef.current, alternateScreen: hibernateAlternateScreenRef.current, - mirrorPreferred: hibernateMirrorPreferredRef.current, }); logger.info("[Terminal] Waking from hibernate", { sessionId, @@ -191,7 +187,6 @@ export function useTerminalHibernateEffect({ hibernateAlternateScreenRef, hibernateDelayMs, hibernateEnabled, - hibernateMirrorPreferredRef, hibernatePendingBufferRef, hibernateScrollbackSnapshotRef, hibernateSnapshotRef, diff --git a/domain/models/terminal.ts b/domain/models/terminal.ts index 14791f600..c1ed3a984 100644 --- a/domain/models/terminal.ts +++ b/domain/models/terminal.ts @@ -130,8 +130,6 @@ export interface TerminalSettings { hibernateSkipAltScreen: boolean; /** Hidden tabs whose renderer is kept alive (WebGL suspended) before full hibernate. */ hibernateKeepRendererCount: number; - /** Mirror PTY output in a main-process headless xterm for faster wake snapshots. */ - hibernateUseHeadlessMirror: boolean; /** Bytes per animation frame when replaying hibernate snapshots in the renderer. */ hibernateReplayChunkBytes: number; /** Prefer WASM terminal serialize when available (falls back to JS). */ @@ -355,7 +353,6 @@ const DEFAULT_TERMINAL_SETTINGS: TerminalSettings = { hibernateHiddenTabsDelaySec: 5, hibernateSkipAltScreen: true, hibernateKeepRendererCount: 2, - hibernateUseHeadlessMirror: true, hibernateReplayChunkBytes: 16 * 1024, hibernatePreferWasmSerialize: false, showLineTimestamps: false, // Opt-in: shows output timestamps beside terminal lines diff --git a/domain/terminalHibernate.optimizations.test.ts b/domain/terminalHibernate.optimizations.test.ts index 1287b0cf0..0516b3ebd 100644 --- a/domain/terminalHibernate.optimizations.test.ts +++ b/domain/terminalHibernate.optimizations.test.ts @@ -5,7 +5,6 @@ import { normalizeHibernateKeepRendererCount, normalizeHibernateReplayChunkBytes, resolveHibernateSkipAltScreen, - resolveHibernateUseHeadlessMirror, } from "./terminalHibernate.ts"; test("normalizeHibernateReplayChunkBytes clamps to allowed range", () => { @@ -26,8 +25,3 @@ test("resolveHibernateSkipAltScreen defaults to enabled", () => { assert.equal(resolveHibernateSkipAltScreen(), true); assert.equal(resolveHibernateSkipAltScreen({ hibernateSkipAltScreen: false }), false); }); - -test("resolveHibernateUseHeadlessMirror defaults to enabled", () => { - assert.equal(resolveHibernateUseHeadlessMirror(), true); - assert.equal(resolveHibernateUseHeadlessMirror({ hibernateUseHeadlessMirror: false }), false); -}); diff --git a/domain/terminalHibernate.ts b/domain/terminalHibernate.ts index 643c63ac2..8192e814f 100644 --- a/domain/terminalHibernate.ts +++ b/domain/terminalHibernate.ts @@ -115,12 +115,6 @@ export function resolveHibernateSkipAltScreen( return settings?.hibernateSkipAltScreen !== false; } -export function resolveHibernateUseHeadlessMirror( - settings?: Pick | null, -): boolean { - return settings?.hibernateUseHeadlessMirror !== false; -} - export function resolveHibernatePreferWasmSerialize( settings?: Pick | null, ): boolean { @@ -145,6 +139,4 @@ export type TerminalHibernateWakePayload = { pendingBuffer: string; /** True when the pane was hibernated while a full-screen app owned the alt buffer. */ alternateScreen: boolean; - /** When true, snapshot was sourced from the main-process headless mirror. */ - mirrorPreferred?: boolean; }; diff --git a/electron/bridges/emitTerminalSessionData.cjs b/electron/bridges/emitTerminalSessionData.cjs index 342c2bd0a..72162bdfb 100644 --- a/electron/bridges/emitTerminalSessionData.cjs +++ b/electron/bridges/emitTerminalSessionData.cjs @@ -1,48 +1,9 @@ "use strict"; -const { - writeMirror, - resizeMirror, - serializeMirror, - disposeMirror, -} = require("./terminalHeadlessMirror.cjs"); - -/** - * Deliver terminal output to the renderer and optionally mirror it in a - * headless xterm on the main process for fast hibernate snapshots. - */ -function emitTerminalSessionData(contents, sessionId, data, options = {}) { - const { cols, rows, mirrorEnabled = true } = options; - if (mirrorEnabled && data) { - writeMirror(sessionId, data, cols, rows); - } +function emitTerminalSessionData(contents, sessionId, data) { contents?.send("netcatty:data", { sessionId, data }); } -function registerTerminalMirrorHandlers(ipcMain) { - ipcMain.handle("netcatty:mirror:snapshot", (_event, payload = {}) => { - const sessionId = payload.sessionId; - if (!sessionId) return { snapshot: "", alternateScreen: false }; - return serializeMirror(sessionId); - }); - - ipcMain.handle("netcatty:mirror:resize", (_event, payload = {}) => { - const { sessionId, cols, rows } = payload; - if (!sessionId || !cols || !rows) return { ok: false }; - resizeMirror(sessionId, cols, rows); - return { ok: true }; - }); - - ipcMain.handle("netcatty:mirror:dispose", (_event, payload = {}) => { - const sessionId = payload.sessionId; - if (!sessionId) return { ok: false }; - disposeMirror(sessionId); - return { ok: true }; - }); -} - module.exports = { emitTerminalSessionData, - registerTerminalMirrorHandlers, - disposeMirror, }; diff --git a/electron/bridges/terminalBridge.cjs b/electron/bridges/terminalBridge.cjs index 8484f4f09..aec851bc9 100644 --- a/electron/bridges/terminalBridge.cjs +++ b/electron/bridges/terminalBridge.cjs @@ -13,8 +13,7 @@ const { promisify } = require("node:util"); const { StringDecoder } = require("node:string_decoder"); const pty = require("node-pty"); const { SerialPort } = require("serialport"); -const { emitTerminalSessionData, disposeMirror } = require("./emitTerminalSessionData.cjs"); -const { resizeMirror } = require("./terminalHeadlessMirror.cjs"); +const { emitTerminalSessionData } = require("./emitTerminalSessionData.cjs"); const iconv = require("iconv-lite"); const ptyProcessTree = require("./ptyProcessTree.cjs"); @@ -952,9 +951,6 @@ function resizeSession(event, payload) { if (!session) return; if (Number.isFinite(payload.cols)) session.cols = payload.cols; if (Number.isFinite(payload.rows)) session.rows = payload.rows; - if (Number.isFinite(payload.cols) && Number.isFinite(payload.rows)) { - resizeMirror(payload.sessionId, payload.cols, payload.rows); - } try { if (session.stream) { @@ -991,7 +987,6 @@ function resizeSession(event, payload) { function closeSession(event, payload) { const session = sessions.get(payload.sessionId); if (!session) return; - disposeMirror(payload.sessionId); session.closed = true; try { diff --git a/electron/bridges/terminalHeadlessMirror.cjs b/electron/bridges/terminalHeadlessMirror.cjs deleted file mode 100644 index 9e83de30d..000000000 --- a/electron/bridges/terminalHeadlessMirror.cjs +++ /dev/null @@ -1,100 +0,0 @@ -"use strict"; - -const { SerializeAddon } = require("@xterm/addon-serialize"); -const { Terminal: HeadlessTerminal } = require("@xterm/headless"); - -const DEFAULT_COLS = 80; -const DEFAULT_ROWS = 24; -const DEFAULT_SCROLLBACK = 3000; - -/** @type {Map} */ -const mirrors = new Map(); - -function isAlternateScreenActive(headless) { - return headless.buffer.active.type === "alternate"; -} - -function createMirror(cols, rows) { - const headless = new HeadlessTerminal({ - cols, - rows, - scrollback: DEFAULT_SCROLLBACK, - allowProposedApi: true, - }); - const serializer = new SerializeAddon(); - headless.loadAddon(serializer); - return { headless, serializer, cols, rows }; -} - -function ensureMirror(sessionId, cols = DEFAULT_COLS, rows = DEFAULT_ROWS) { - let mirror = mirrors.get(sessionId); - if (!mirror) { - mirror = createMirror(cols, rows); - mirrors.set(sessionId, mirror); - return mirror; - } - if (mirror.cols !== cols || mirror.rows !== rows) { - try { - mirror.headless.resize(cols, rows); - } catch { - // Ignore resize failures on disposed mirrors. - } - mirror.cols = cols; - mirror.rows = rows; - } - return mirror; -} - -function writeMirror(sessionId, data, cols, rows) { - if (!data) return; - const mirror = ensureMirror(sessionId, cols, rows); - mirror.headless.write(data); -} - -function resizeMirror(sessionId, cols, rows) { - if (!mirrors.has(sessionId)) return; - const mirror = ensureMirror(sessionId, cols, rows); - try { - mirror.headless.resize(cols, rows); - } catch { - mirrors.delete(sessionId); - } -} - -function serializeMirror(sessionId) { - const mirror = mirrors.get(sessionId); - if (!mirror) { - return { snapshot: "", alternateScreen: false }; - } - const alternateScreen = isAlternateScreenActive(mirror.headless); - try { - const snapshot = mirror.serializer.serialize({ - excludeAltBuffer: !alternateScreen, - excludeModes: !alternateScreen, - ...(alternateScreen - ? { range: { start: 0, end: Math.max(0, mirror.rows - 1) } } - : {}), - }); - return { snapshot, alternateScreen }; - } catch { - return { snapshot: "", alternateScreen }; - } -} - -function disposeMirror(sessionId) { - const mirror = mirrors.get(sessionId); - if (!mirror) return; - try { - mirror.headless.dispose(); - } catch { - // Ignore dispose failures. - } - mirrors.delete(sessionId); -} - -module.exports = { - writeMirror, - resizeMirror, - serializeMirror, - disposeMirror, -}; diff --git a/electron/bridges/terminalHeadlessMirror.test.cjs b/electron/bridges/terminalHeadlessMirror.test.cjs deleted file mode 100644 index bfb6458d8..000000000 --- a/electron/bridges/terminalHeadlessMirror.test.cjs +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; - -const test = require("node:test"); -const assert = require("node:assert/strict"); - -const { - writeMirror, - serializeMirror, - disposeMirror, -} = require("./terminalHeadlessMirror.cjs"); - -test("terminalHeadlessMirror tracks output and serializes snapshot", async () => { - const sessionId = "mirror-test-session"; - disposeMirror(sessionId); - writeMirror(sessionId, "hello\r\n", 80, 24); - await new Promise((resolve) => setTimeout(resolve, 0)); - const { snapshot, alternateScreen } = serializeMirror(sessionId); - assert.equal(alternateScreen, false); - assert.match(snapshot, /hello/); - disposeMirror(sessionId); -}); diff --git a/electron/main/registerBridges.cjs b/electron/main/registerBridges.cjs index 5bceae74f..37be77057 100644 --- a/electron/main/registerBridges.cjs +++ b/electron/main/registerBridges.cjs @@ -170,8 +170,6 @@ function createBridgeRegistrar(context) { transferBridge.registerHandlers(ipcMain); portForwardingBridge.registerHandlers(ipcMain); terminalBridge.registerHandlers(ipcMain); - const { registerTerminalMirrorHandlers } = require("../bridges/emitTerminalSessionData.cjs"); - registerTerminalMirrorHandlers(ipcMain); const { createSystemManagerBridge } = require("../bridges/systemManagerBridge.cjs"); const systemManagerBridge = createSystemManagerBridge({ diff --git a/electron/preload/api.cjs b/electron/preload/api.cjs index 83486ae32..a84b33b92 100644 --- a/electron/preload/api.cjs +++ b/electron/preload/api.cjs @@ -172,9 +172,6 @@ function createPreloadApi(ctx) { resizeSession: (sessionId, cols, rows) => { ipcRenderer.send("netcatty:resize", { sessionId, cols, rows }); }, - getTerminalMirrorSnapshot: (sessionId) => { - return ipcRenderer.invoke("netcatty:mirror:snapshot", { sessionId }); - }, setSessionFlowPaused: (sessionId, paused) => { ipcRenderer.send("netcatty:flow", { sessionId, paused: Boolean(paused) }); }, diff --git a/package-lock.json b/package-lock.json index dc787e140..378bdd3f3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -38,7 +38,6 @@ "@xterm/addon-unicode-graphemes": "0.5.0-beta.220", "@xterm/addon-web-links": "0.13.0-beta.220", "@xterm/addon-webgl": "0.20.0-beta.219", - "@xterm/headless": "^6.1.0-beta.220", "@xterm/xterm": "6.1.0-beta.220", "ai": "^6.0.116", "clsx": "2.1.1", @@ -65,7 +64,6 @@ }, "devDependencies": { "@eslint/js": "^9.39.1", - "@tailwindcss/postcss": "^4.1.17", "@tailwindcss/vite": "^4.1.17", "@types/node": "^25.0.0", "@typescript-eslint/eslint-plugin": "^8.49.0", @@ -199,19 +197,6 @@ "zod": "^3.25.76 || ^4.1.8" } }, - "node_modules/@alloc/quick-lru": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", - "integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/@anthropic-ai/claude-agent-sdk": { "version": "0.3.161", "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk/-/claude-agent-sdk-0.3.161.tgz", @@ -7979,20 +7964,6 @@ "node": ">= 10" } }, - "node_modules/@tailwindcss/postcss": { - "version": "4.1.18", - "resolved": "https://registry.npmjs.org/@tailwindcss/postcss/-/postcss-4.1.18.tgz", - "integrity": "sha512-Ce0GFnzAOuPyfV5SxjXGn0CubwGcuDB0zcdaPuCSzAa/2vII24JTkH+I6jcbXLb1ctjZMZZI6OjDaLPJQL1S0g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@alloc/quick-lru": "^5.2.0", - "@tailwindcss/node": "4.1.18", - "@tailwindcss/oxide": "4.1.18", - "postcss": "^8.4.41", - "tailwindcss": "4.1.18" - } - }, "node_modules/@tailwindcss/vite": { "version": "4.1.18", "resolved": "https://registry.npmjs.org/@tailwindcss/vite/-/vite-4.1.18.tgz", @@ -8599,15 +8570,6 @@ "@xterm/xterm": "^6.1.0-beta.220" } }, - "node_modules/@xterm/headless": { - "version": "6.1.0-beta.220", - "resolved": "https://registry.npmjs.org/@xterm/headless/-/headless-6.1.0-beta.220.tgz", - "integrity": "sha512-oc+cI28eP/ktv91ddk1MxsEdfS41dnNvB3eMjNxfP7v+SaM7aXgXAL8Kj0/zzbpX/dG0nbA9wi3YvsybzCN3OQ==", - "license": "MIT", - "workspaces": [ - "addons/*" - ] - }, "node_modules/@xterm/xterm": { "version": "6.1.0-beta.220", "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.1.0-beta.220.tgz", diff --git a/package.json b/package.json index d5d574956..bf068c578 100644 --- a/package.json +++ b/package.json @@ -66,7 +66,6 @@ "@xterm/addon-unicode-graphemes": "0.5.0-beta.220", "@xterm/addon-web-links": "0.13.0-beta.220", "@xterm/addon-webgl": "0.20.0-beta.219", - "@xterm/headless": "^6.1.0-beta.220", "@xterm/xterm": "6.1.0-beta.220", "ai": "^6.0.116", "clsx": "2.1.1", @@ -90,7 +89,6 @@ }, "devDependencies": { "@eslint/js": "^9.39.1", - "@tailwindcss/postcss": "^4.1.17", "@tailwindcss/vite": "^4.1.17", "@types/node": "^25.0.0", "@typescript-eslint/eslint-plugin": "^8.49.0", diff --git a/types/global/netcatty-bridge-session.d.ts b/types/global/netcatty-bridge-session.d.ts index 473013ff3..316295744 100644 --- a/types/global/netcatty-bridge-session.d.ts +++ b/types/global/netcatty-bridge-session.d.ts @@ -274,10 +274,6 @@ declare global { action: "overwrite" | "skip" | "cancel"; applyToRest: boolean; }): void; - getTerminalMirrorSnapshot?(sessionId: string): Promise<{ - snapshot: string; - alternateScreen: boolean; - }>; onSessionData(sessionId: string, cb: (data: string) => void): () => void; onSessionExit( sessionId: string, From 3943b4869fa8932ced377dd8924a0baacd1eb3ad Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Thu, 25 Jun 2026 09:52:22 +0800 Subject: [PATCH 039/228] fix: guard terminal write coalescing without raf --- .../terminal/runtime/writeCoalescer.test.ts | 42 ++++++++----------- components/terminal/runtime/writeCoalescer.ts | 40 ++++++++++++++---- 2 files changed, 50 insertions(+), 32 deletions(-) diff --git a/components/terminal/runtime/writeCoalescer.test.ts b/components/terminal/runtime/writeCoalescer.test.ts index 2811075a8..260e1ffae 100644 --- a/components/terminal/runtime/writeCoalescer.test.ts +++ b/components/terminal/runtime/writeCoalescer.test.ts @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { afterEach, beforeEach, test } from "node:test"; +import { beforeEach, test } from "node:test"; import { createWriteCoalescer, @@ -10,8 +10,18 @@ type FrameCallback = (time: number) => void; let frameCallbacks: Map; let nextFrameId: number; -let originalRaf: typeof requestAnimationFrame; -let originalCancelRaf: typeof cancelAnimationFrame; + +const createTestCoalescer = (write: (data: string) => void) => + createWriteCoalescer(write, { + scheduleFrame(callback) { + const id = nextFrameId; + nextFrameId += 1; + frameCallbacks.set(id, callback); + return () => { + frameCallbacks.delete(id); + }; + }, + }); const fireFrame = (): void => { const callbacks = [...frameCallbacks.values()]; @@ -24,27 +34,11 @@ const fireFrame = (): void => { beforeEach(() => { frameCallbacks = new Map(); nextFrameId = 1; - originalRaf = globalThis.requestAnimationFrame; - originalCancelRaf = globalThis.cancelAnimationFrame; - globalThis.requestAnimationFrame = (callback: FrameCallback) => { - const id = nextFrameId; - nextFrameId += 1; - frameCallbacks.set(id, callback); - return id; - }; - globalThis.cancelAnimationFrame = (id: number) => { - frameCallbacks.delete(id); - }; -}); - -afterEach(() => { - globalThis.requestAnimationFrame = originalRaf; - globalThis.cancelAnimationFrame = originalCancelRaf; }); test("coalesces chunks in the same frame into one write", () => { const writes: string[] = []; - const coalescer = createWriteCoalescer((data) => writes.push(data)); + const coalescer = createTestCoalescer((data) => writes.push(data)); coalescer.push("foo"); coalescer.push("bar"); @@ -57,7 +51,7 @@ test("coalesces chunks in the same frame into one write", () => { test("schedules a new frame for data arriving after a flush", () => { const writes: string[] = []; - const coalescer = createWriteCoalescer((data) => writes.push(data)); + const coalescer = createTestCoalescer((data) => writes.push(data)); coalescer.push("first"); fireFrame(); @@ -69,7 +63,7 @@ test("schedules a new frame for data arriving after a flush", () => { test("flushSync writes pending bytes immediately and cancels the scheduled frame", () => { const writes: string[] = []; - const coalescer = createWriteCoalescer((data) => writes.push(data)); + const coalescer = createTestCoalescer((data) => writes.push(data)); coalescer.push("pending"); coalescer.flushSync(); @@ -81,7 +75,7 @@ test("flushSync writes pending bytes immediately and cancels the scheduled frame test("flushes synchronously when pending bytes exceed the cap", () => { const writes: string[] = []; - const coalescer = createWriteCoalescer((data) => writes.push(data)); + const coalescer = createTestCoalescer((data) => writes.push(data)); const chunk = "x".repeat(MAX_PENDING_WRITE_COALESCE_BYTES); coalescer.push(chunk); @@ -92,7 +86,7 @@ test("flushes synchronously when pending bytes exceed the cap", () => { test("dispose flushes remaining bytes and stops accepting new chunks", () => { const writes: string[] = []; - const coalescer = createWriteCoalescer((data) => writes.push(data)); + const coalescer = createTestCoalescer((data) => writes.push(data)); coalescer.push("tail"); coalescer.dispose(); diff --git a/components/terminal/runtime/writeCoalescer.ts b/components/terminal/runtime/writeCoalescer.ts index 8f6190353..418132ea7 100644 --- a/components/terminal/runtime/writeCoalescer.ts +++ b/components/terminal/runtime/writeCoalescer.ts @@ -20,16 +20,35 @@ export type WriteCoalescer = { dispose(): void; }; -export const createWriteCoalescer = (write: (data: string) => void): WriteCoalescer => { +type ScheduleWriteFrame = (callback: () => void) => (() => void) | null; + +const scheduleWriteFrame = (callback: () => void): (() => void) | null => { + if (typeof globalThis.requestAnimationFrame === "function") { + const frameId = globalThis.requestAnimationFrame(callback); + return () => { + if (typeof globalThis.cancelAnimationFrame === "function") { + globalThis.cancelAnimationFrame(frameId); + } + }; + } + + return null; +}; + +export const createWriteCoalescer = ( + write: (data: string) => void, + options: { scheduleFrame?: ScheduleWriteFrame } = {}, +): WriteCoalescer => { let pending: string[] = []; let pendingBytes = 0; - let frameId: number | null = null; + let cancelPendingFrame: (() => void) | null = null; let disposed = false; + const scheduleFrame = options.scheduleFrame ?? scheduleWriteFrame; const flushSync = (): void => { - if (frameId !== null) { - cancelAnimationFrame(frameId); - frameId = null; + if (cancelPendingFrame !== null) { + cancelPendingFrame(); + cancelPendingFrame = null; } if (pendingBytes === 0) { return; @@ -50,11 +69,16 @@ export const createWriteCoalescer = (write: (data: string) => void): WriteCoales flushSync(); return; } - if (frameId === null) { - frameId = requestAnimationFrame(() => { - frameId = null; + if (cancelPendingFrame === null) { + const cancelFrame = scheduleFrame(() => { + cancelPendingFrame = null; flushSync(); }); + if (cancelFrame === null) { + flushSync(); + return; + } + cancelPendingFrame = cancelFrame; } }; From 95f39f11b78f1455a87dbe5318db89a5f4036259 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Thu, 25 Jun 2026 10:08:29 +0800 Subject: [PATCH 040/228] fix: route port forward jump auth externally --- electron/bridges/portForwardingBridge.cjs | 1 + .../portForwardingBridge.jumpScope.test.cjs | 111 ++++++++++++++++++ electron/bridges/sshBridge.cjs | 3 +- 3 files changed, 114 insertions(+), 1 deletion(-) create mode 100644 electron/bridges/portForwardingBridge.jumpScope.test.cjs diff --git a/electron/bridges/portForwardingBridge.cjs b/electron/bridges/portForwardingBridge.cjs index 8262c93a3..9550b7eaa 100644 --- a/electron/bridges/portForwardingBridge.cjs +++ b/electron/bridges/portForwardingBridge.cjs @@ -241,6 +241,7 @@ async function startPortForward(event, payload) { _connectionsRef: chainConnections, _tunnelRef: tunnelState, _passphraseSignal: passphraseAbortController.signal, + _keyboardInteractiveScope: "external", }, jumpHosts, hostname, diff --git a/electron/bridges/portForwardingBridge.jumpScope.test.cjs b/electron/bridges/portForwardingBridge.jumpScope.test.cjs new file mode 100644 index 000000000..4365e6ae7 --- /dev/null +++ b/electron/bridges/portForwardingBridge.jumpScope.test.cjs @@ -0,0 +1,111 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { EventEmitter } = require("node:events"); +const { Duplex } = require("node:stream"); +const Module = require("node:module"); + +function createSender() { + return { + id: 1, + isDestroyed: () => false, + send() {}, + }; +} + +function loadBridgeWithMocks(t) { + const originalLoad = Module._load; + let capturedChainOptions = null; + + class MockSshClient extends EventEmitter { + connect(options) { + this.options = options; + setImmediate(() => this.emit("ready")); + } + + forwardOut(_srcIP, _srcPort, _dstHost, _dstPort, callback) { + callback(null, new Duplex({ + read() {}, + write(_chunk, _encoding, done) { + done(); + }, + })); + } + + end() { + this.emit("close"); + } + } + + Module._load = function patchedLoad(request, parent, isMain) { + if (request === "ssh2") { + return { + Client: MockSshClient, + utils: { + parseKey: () => null, + }, + }; + } + if (request === "./sshBridge.cjs") { + return { + buildAlgorithms: () => ({}), + connectThroughChain: async (_event, options) => { + capturedChainOptions = options; + return { + socket: new Duplex({ + read() {}, + write(_chunk, _encoding, done) { + done(); + }, + }), + connections: [], + }; + }, + }; + } + return originalLoad.call(this, request, parent, isMain); + }; + + const bridgePath = require.resolve("./portForwardingBridge.cjs"); + delete require.cache[bridgePath]; + const bridge = require("./portForwardingBridge.cjs"); + + t.after(() => { + Module._load = originalLoad; + delete require.cache[bridgePath]; + }); + + return { bridge, getCapturedChainOptions: () => capturedChainOptions }; +} + +test("port forwarding routes jump-host keyboard-interactive prompts through the external scope", async (t) => { + const { bridge, getCapturedChainOptions } = loadBridgeWithMocks(t); + const event = { sender: createSender() }; + + try { + const result = await bridge.startPortForward(event, { + tunnelId: "pf-jump-scope", + type: "local", + localPort: 0, + bindAddress: "127.0.0.1", + remoteHost: "127.0.0.1", + remotePort: 3306, + hostname: "db.internal", + port: 22, + username: "dbuser", + password: "target-password", + jumpHosts: [{ + hostname: "jump.internal", + port: 22, + username: "jumpuser", + password: "jump-password", + }], + }); + + assert.equal(result.success, true); + assert.equal(getCapturedChainOptions()?._keyboardInteractiveScope, "external"); + } finally { + await bridge.stopPortForward(event, { tunnelId: "pf-jump-scope" }); + } +}); diff --git a/electron/bridges/sshBridge.cjs b/electron/bridges/sshBridge.cjs index 30e0aecf4..6f79a8ce7 100644 --- a/electron/bridges/sshBridge.cjs +++ b/electron/bridges/sshBridge.cjs @@ -479,6 +479,7 @@ async function connectThroughChain(event, options, jumpHosts, targetHost, target const sender = event.sender; const connections = options?._connectionsRef || []; const sshDiagnosticLogger = options?._sshDiagnosticLogger || log; + const keyboardInteractiveScope = options?._keyboardInteractiveScope || "terminal"; let currentSocket = null; const sendProgress = (hop, total, label, status, error) => { @@ -727,7 +728,7 @@ async function connectThroughChain(event, options, jumpHosts, targetHost, target hostname: hopLabel, password: jump.password, logPrefix: `[Chain] Hop ${i + 1}/${totalHops}`, - scope: "terminal", + scope: keyboardInteractiveScope, onAutoFill: () => sendProgress( i + 1, totalHops + 1, hopLabel, 'auth-attempt', 'using saved password', ), From d8304f3eec72255ddd60950755b09e47434ce864 Mon Sep 17 00:00:00 2001 From: mam15mon Date: Thu, 25 Jun 2026 10:15:39 +0800 Subject: [PATCH 041/228] Add manual session log toolbar button --- application/i18n/locales/en/terminal.ts | 2 + application/i18n/locales/ru/terminal.ts | 2 + application/i18n/locales/zh-CN/vault.ts | 2 + application/state/useSessionLogBackend.ts | 36 +++++ components/Terminal.tsx | 74 ++++++++++ components/terminal/TerminalToolbar.test.ts | 27 ++++ components/terminal/TerminalToolbar.tsx | 34 ++++- .../terminal/sessionLogInitialLine.test.ts | 39 +++++ components/terminal/sessionLogInitialLine.ts | 138 ++++++++++++++++++ electron/bridges/sessionLogStreamManager.cjs | 134 +++++++++++------ .../bridges/sessionLogStreamManager.test.cjs | 58 ++++++++ electron/bridges/sessionLogsBridge.cjs | 85 +++++++++++ electron/preload/api.cjs | 6 + types/global/netcatty-bridge-files.d.ts | 12 ++ 14 files changed, 603 insertions(+), 46 deletions(-) create mode 100644 application/state/useSessionLogBackend.ts create mode 100644 components/terminal/sessionLogInitialLine.test.ts create mode 100644 components/terminal/sessionLogInitialLine.ts diff --git a/application/i18n/locales/en/terminal.ts b/application/i18n/locales/en/terminal.ts index 0c68d92e9..df76d5a3d 100644 --- a/application/i18n/locales/en/terminal.ts +++ b/application/i18n/locales/en/terminal.ts @@ -32,6 +32,8 @@ export const enTerminalMessages: Messages = { 'terminal.toolbar.terminalSettings': 'Terminal settings', 'terminal.toolbar.searchTerminal': 'Search terminal', 'terminal.toolbar.search': 'Search', + 'terminal.toolbar.startSessionLog': 'Start session log', + 'terminal.toolbar.stopSessionLog': 'Stop session log', 'terminal.toolbar.timestampsEnable': 'Show timestamps', 'terminal.toolbar.timestampsDisable': 'Hide timestamps', 'terminal.toolbar.broadcast': 'Broadcast', diff --git a/application/i18n/locales/ru/terminal.ts b/application/i18n/locales/ru/terminal.ts index 906624dca..ebe135afd 100644 --- a/application/i18n/locales/ru/terminal.ts +++ b/application/i18n/locales/ru/terminal.ts @@ -53,6 +53,8 @@ export const ruTerminalMessages: Messages = { 'terminal.toolbar.terminalSettings': 'Настройки терминала', 'terminal.toolbar.searchTerminal': 'Поиск по терминалу', 'terminal.toolbar.search': 'Поиск', + 'terminal.toolbar.startSessionLog': 'Начать журнал сессии', + 'terminal.toolbar.stopSessionLog': 'Остановить журнал сессии', 'terminal.toolbar.timestampsEnable': 'Показать время', 'terminal.toolbar.timestampsDisable': 'Скрыть время', 'terminal.toolbar.broadcast': 'Трансляция', diff --git a/application/i18n/locales/zh-CN/vault.ts b/application/i18n/locales/zh-CN/vault.ts index 91733be69..66fe7f989 100644 --- a/application/i18n/locales/zh-CN/vault.ts +++ b/application/i18n/locales/zh-CN/vault.ts @@ -315,6 +315,8 @@ export const zhCNVaultMessages: Messages = { 'terminal.toolbar.terminalSettings': '终端设置', 'terminal.toolbar.searchTerminal': '搜索终端', 'terminal.toolbar.search': '搜索', + 'terminal.toolbar.startSessionLog': '开始会话日志', + 'terminal.toolbar.stopSessionLog': '停止会话日志', 'terminal.toolbar.broadcast': '广播', 'terminal.toolbar.broadcastEnable': '启用广播模式', 'terminal.toolbar.broadcastDisable': '关闭广播模式', diff --git a/application/state/useSessionLogBackend.ts b/application/state/useSessionLogBackend.ts new file mode 100644 index 000000000..5f112a273 --- /dev/null +++ b/application/state/useSessionLogBackend.ts @@ -0,0 +1,36 @@ +import { useCallback } from "react"; +import { netcattyBridge } from "../../infrastructure/services/netcattyBridge"; + +type ManualStartPayload = { + sessionId: string; + sessionName?: string; + preferredDirectory?: string; + initialLine?: string; +}; + +type ManualStopPayload = { + sessionId: string; +}; + +type ManualStatusPayload = { + sessionId: string; +}; + +export const useSessionLogBackend = () => { + const startManualSessionLog = useCallback(async (payload: ManualStartPayload) => { + const bridge = netcattyBridge.get(); + return bridge?.startManualSessionLog?.(payload) ?? { success: false, started: false, error: "Session log bridge unavailable" }; + }, []); + + const stopManualSessionLog = useCallback(async (payload: ManualStopPayload) => { + const bridge = netcattyBridge.get(); + return bridge?.stopManualSessionLog?.(payload) ?? { success: false, stopped: false, error: "Session log bridge unavailable" }; + }, []); + + const getManualSessionLogStatus = useCallback(async (payload: ManualStatusPayload) => { + const bridge = netcattyBridge.get(); + return bridge?.getManualSessionLogStatus?.(payload) ?? { success: false, isLogging: false, error: "Session log bridge unavailable" }; + }, []); + + return { startManualSessionLog, stopManualSessionLog, getManualSessionLogStatus }; +}; diff --git a/components/Terminal.tsx b/components/Terminal.tsx index ec9b4a022..18c5cf9c3 100644 --- a/components/Terminal.tsx +++ b/components/Terminal.tsx @@ -29,6 +29,7 @@ import { classifyDistroId, shouldProbeSessionCwd } from "../domain/host"; import { supportsZmodemTerminalDragDrop } from "../lib/zmodemDragDrop"; import { resolveHostAuth } from "../domain/sshAuth"; import { useTerminalBackend } from "../application/state/useTerminalBackend"; +import { useSessionLogBackend } from "../application/state/useSessionLogBackend"; import { useTerminalLayoutSuppressActive } from "../application/state/terminalLayoutSuppressStore"; // SFTPModal removed - SFTP is now handled by SftpSidePanel in TerminalLayer import { Button } from "./ui/button"; @@ -52,6 +53,7 @@ import { ZmodemProgressIndicator } from "./terminal/ZmodemProgressIndicator"; import { createReplaySafeTerminalLogSanitizer } from "./terminal/replaySafeTerminalLog"; import { createConnectionLogBuffer } from "./terminal/connectionLogBuffer"; import { createProgrammaticCommandLogRewriter, type ProgrammaticCommandLogRewrite } from "./terminal/programmaticCommandLog"; +import { getSessionLogInitialLine } from "./terminal/sessionLogInitialLine"; import { useZmodemTransfer } from "./terminal/hooks/useZmodemTransfer"; import { createTerminalSessionStarters, type PendingAuth } from "./terminal/runtime/createTerminalSessionStarters"; import { createXTermRuntime, type XTermRuntime } from "./terminal/runtime/createXTermRuntime"; @@ -347,6 +349,7 @@ const TerminalComponent: React.FC = ({ const sudoHintRef = useRef<((active: boolean) => boolean) | undefined>(undefined); const terminalBackend = useTerminalBackend(); + const { startManualSessionLog, stopManualSessionLog, getManualSessionLogStatus } = useSessionLogBackend(); const { resizeSession, receiveSerialYmodem, @@ -373,6 +376,7 @@ const TerminalComponent: React.FC = ({ const [timeLeft, setTimeLeft] = useState(CONNECTION_TIMEOUT / 1000); const [isCancelling, setIsCancelling] = useState(false); const [showSFTP, setShowSFTP] = useState(false); + const [isSessionLogging, setIsSessionLogging] = useState(false); const [progressValue, setProgressValue] = useState(15); const [hasSelection, setHasSelection] = useState(false); const [selectionOverlayPosition, setSelectionOverlayPosition] = useState<{ left: number; top: number } | null>(null); @@ -1550,6 +1554,70 @@ const TerminalComponent: React.FC = ({ containerRef, }); + const handleToggleSessionLog = useCallback(async () => { + const currentSessionId = sessionRef.current ?? sessionId; + if (!currentSessionId) { + toast.error("Session log bridge is unavailable"); + return; + } + + try { + const currentStatus = await getManualSessionLogStatus({ sessionId: currentSessionId }); + if (currentStatus?.isLogging) { + const stopResult = await stopManualSessionLog({ sessionId: currentSessionId }); + if (stopResult?.success) { + setIsSessionLogging(false); + } else { + toast.error(stopResult?.error || "Failed to stop session log"); + } + return; + } + + const startResult = await startManualSessionLog({ + sessionId: currentSessionId, + sessionName: host.label || host.hostname || currentSessionId, + preferredDirectory: sessionLog?.directory, + initialLine: termRef.current ? getSessionLogInitialLine(termRef.current) : "", + }); + if (startResult?.success) { + if (!startResult?.started && startResult?.canceled) return; + setIsSessionLogging(!!startResult?.started); + } else { + toast.error(startResult?.error || "Failed to start session log"); + } + } catch (err) { + logger.error("[Terminal] Failed to toggle manual session log:", err); + toast.error("Failed to toggle session log"); + } + }, [ + getManualSessionLogStatus, + host.hostname, + host.label, + sessionId, + sessionLog?.directory, + startManualSessionLog, + stopManualSessionLog, + ]); + + useEffect(() => { + const currentSessionId = sessionRef.current ?? sessionId; + if (!currentSessionId) { + setIsSessionLogging(false); + return; + } + + let cancelled = false; + void getManualSessionLogStatus({ sessionId: currentSessionId }).then((result) => { + if (!cancelled) setIsSessionLogging(!!result?.isLogging); + }).catch(() => { + if (!cancelled) setIsSessionLogging(false); + }); + + return () => { + cancelled = true; + }; + }, [getManualSessionLogStatus, sessionId, status]); + const renderControls = useCallback((opts?: { showClose?: boolean }) => ( = ({ onClose={() => onCloseSession?.(sessionId)} isSearchOpen={isSearchOpen} onToggleSearch={handleToggleSearch} + showLogButton + onToggleSessionLog={handleToggleSessionLog} + isSessionLogging={isSessionLogging} + isSessionLogDisabled={status !== "connected" && !isSessionLogging} isComposeBarOpen={inWorkspace ? isWorkspaceComposeBarOpen : isComposeBarOpen} onToggleComposeBar={inWorkspace ? onToggleComposeBar : () => setIsComposeBarOpen(prev => !prev)} terminalEncoding={terminalEncoding} @@ -1587,6 +1659,7 @@ const TerminalComponent: React.FC = ({ handleReceiveYmodem, handleSendYmodem, handleSetTerminalEncoding, + handleToggleSessionLog, handleToggleSearch, host, inWorkspace, @@ -1595,6 +1668,7 @@ const TerminalComponent: React.FC = ({ isSerialConnection, isComposeBarOpen, isSearchOpen, + isSessionLogging, isWorkspaceComposeBarOpen, onCloseSession, onOpenScripts, diff --git a/components/terminal/TerminalToolbar.test.ts b/components/terminal/TerminalToolbar.test.ts index 86b969463..564d44d9e 100644 --- a/components/terminal/TerminalToolbar.test.ts +++ b/components/terminal/TerminalToolbar.test.ts @@ -69,6 +69,33 @@ test("keeps Scripts visible before the terminal overflow menu", () => { assert.match(markup, /type="button"[^>]*aria-label="Scripts"/); }); +test("shows manual session log button when requested", () => { + const markup = renderToolbar(sshHost, "connected", { + showLogButton: true, + onToggleSessionLog: () => {}, + }); + + const logIndex = markup.indexOf('aria-label="Start session log"'); + const scriptsIndex = markup.indexOf('aria-label="Scripts"'); + + assert.notEqual(logIndex, -1); + assert.notEqual(scriptsIndex, -1); + assert.ok(logIndex < scriptsIndex); +}); + +test("marks manual session log button active while logging", () => { + const markup = renderToolbar(sshHost, "connected", { + showLogButton: true, + onToggleSessionLog: () => {}, + isSessionLogging: true, + }); + + assert.match( + markup, + /aria-label="Stop session log"[^>]*aria-pressed="true"[^>]*style="background-color:var\(--terminal-toolbar-btn-active\)"/, + ); +}); + test("hides SFTP for local terminal sessions", () => { const markup = renderToolbar({ ...sshHost, diff --git a/components/terminal/TerminalToolbar.tsx b/components/terminal/TerminalToolbar.tsx index 8897954d4..e9e82c9c7 100644 --- a/components/terminal/TerminalToolbar.tsx +++ b/components/terminal/TerminalToolbar.tsx @@ -2,7 +2,7 @@ * Terminal Toolbar * Displays high-frequency terminal actions and close button in the terminal status bar. */ -import { Check, ChevronRight, Download, FolderInput, FolderSync, History, Languages, MoreVertical, X, Zap, Palette, Search, TextCursorInput, Upload } from 'lucide-react'; +import { Check, ChevronRight, Download, FileText, FolderInput, FolderSync, History, Languages, MoreVertical, X, Zap, Palette, Search, TextCursorInput, Upload } from 'lucide-react'; import React, { useState } from 'react'; import { useI18n } from '../../application/i18n/I18nProvider'; import { Host, Snippet } from '../../types'; @@ -34,6 +34,11 @@ export interface TerminalToolbarProps { // Search functionality isSearchOpen?: boolean; onToggleSearch?: () => void; + // Manual session log + showLogButton?: boolean; + onToggleSessionLog?: () => void; + isSessionLogging?: boolean; + isSessionLogDisabled?: boolean; // Compose bar isComposeBarOpen?: boolean; onToggleComposeBar?: () => void; @@ -61,6 +66,10 @@ export const TerminalToolbar: React.FC = ({ onClose, isSearchOpen, onToggleSearch, + showLogButton = false, + onToggleSessionLog, + isSessionLogging = false, + isSessionLogDisabled = false, isComposeBarOpen, onToggleComposeBar, terminalEncoding, @@ -275,6 +284,29 @@ export const TerminalToolbar: React.FC = ({ {t("terminal.toolbar.searchTerminal")} + {showLogButton && ( + + + + + + {isSessionLogging ? t("terminal.toolbar.stopSessionLog") : t("terminal.toolbar.startSessionLog")} + + + )} +
{session.username}@{session.hostname} @@ -245,6 +249,7 @@ const TerminalFocusSidebarInner: React.FC = ({ resolvedPreviewTheme, sessionHostsMap, sessions, + dynamicTabTitleMode, t, }) => { const [focusSidebarSearch, setFocusSidebarSearch] = useState(''); @@ -546,6 +551,7 @@ const TerminalFocusSidebarInner: React.FC = ({ onDragOver={handleFocusSidebarDragOver} onDrop={handleFocusSidebarDrop} onDragEnd={handleFocusSidebarDragEnd} + dynamicTabTitleMode={dynamicTabTitleMode} t={t} /> ))} @@ -568,6 +574,7 @@ function terminalFocusSidebarPropsEqual( if (prev.resolvedPreviewTheme !== next.resolvedPreviewTheme) return false; if (prev.sessionHostsMap !== next.sessionHostsMap) return false; if (prev.sessions !== next.sessions) return false; + if (prev.dynamicTabTitleMode !== next.dynamicTabTitleMode) return false; if (prev.t !== next.t) return false; if (prev.onReorderWorkspaceSessions !== next.onReorderWorkspaceSessions) return false; if (prev.onRequestAddToWorkspace !== next.onRequestAddToWorkspace) return false; diff --git a/components/terminalLayer/TerminalLayerFocusSidebarSection.tsx b/components/terminalLayer/TerminalLayerFocusSidebarSection.tsx index 865f9a845..5a7c60352 100644 --- a/components/terminalLayer/TerminalLayerFocusSidebarSection.tsx +++ b/components/terminalLayer/TerminalLayerFocusSidebarSection.tsx @@ -25,6 +25,7 @@ function TerminalLayerFocusSidebarSectionInner({ ctx }: { ctx: FocusSidebarConte resolvedPreviewTheme={ctx.resolvedPreviewTheme} sessionHostsMap={ctx.sessionHostsMap} sessions={ctx.sessions} + dynamicTabTitleMode={ctx.terminalSettings?.dynamicTabTitleMode} t={ctx.t} /> ); diff --git a/components/terminalLayer/TerminalLayerSupport.tsx b/components/terminalLayer/TerminalLayerSupport.tsx index 97d65ebcb..30540203a 100644 --- a/components/terminalLayer/TerminalLayerSupport.tsx +++ b/components/terminalLayer/TerminalLayerSupport.tsx @@ -1010,7 +1010,7 @@ const TerminalPane: React.FC = memo(({ e.stopPropagation(); const startPoint = { clientX: e.clientX, clientY: e.clientY }; - const dragLabel = resolveSessionTabTitle(session, host); + const dragLabel = resolveSessionTabTitle(session, terminalSettings?.dynamicTabTitleMode); let dragStarted = false; let ghostEl: HTMLDivElement | null = null; let insertEl: HTMLDivElement | null = null; @@ -1162,13 +1162,13 @@ const TerminalPane: React.FC = memo(({ document.addEventListener('pointerup', handlePointerUp, true); document.addEventListener('pointercancel', handlePointerCancel, true); }, [ - host, inActiveWorkspace, onEndSessionDrag, onRemoveSessionFromWorkspace, onReorderTabs, onStartSessionDrag, session, + terminalSettings?.dynamicTabTitleMode, workspaceById, ]); const handleTerminalFontSizeChange = useCallback((nextFontSize: number) => { @@ -1255,7 +1255,7 @@ const TerminalPane: React.FC = memo(({ sessionLog={sessionLog} sshDebugLogEnabled={sshDebugLogEnabled} sudoAutofillPassword={sudoAutofillPassword} - sessionDisplayName={resolveSessionTabTitle(session, host)} + sessionDisplayName={resolveSessionTabTitle(session, terminalSettings?.dynamicTabTitleMode)} showSelectionAIAction={showSelectionAIAction} onAddSelectionToAI={onAddSelectionToAI} onRename={handleRename} diff --git a/components/terminalLayer/TerminalLayerTabBridge.test.ts b/components/terminalLayer/TerminalLayerTabBridge.test.ts index bcd215e24..435d50643 100644 --- a/components/terminalLayer/TerminalLayerTabBridge.test.ts +++ b/components/terminalLayer/TerminalLayerTabBridge.test.ts @@ -20,3 +20,8 @@ test('terminal panes can gate cwd restore per session host resolution', () => { assert.match(supportSource, /restoreTerminalCwd=\{restoreTerminalCwd && sessionHostResolved\}/); assert.match(layerSource, /session\.protocol === 'local'/); }); + +test('terminal layer bridge refreshes when terminal settings change', () => { + assert.match(source, /terminalSettings: s\.terminalSettings/); + assert.match(source, /\[\s*[\s\S]*s\.terminalSettings[\s\S]*\]\);/); +}); diff --git a/components/terminalLayer/TerminalLayerTabBridge.tsx b/components/terminalLayer/TerminalLayerTabBridge.tsx index 29826576e..6c890d371 100644 --- a/components/terminalLayer/TerminalLayerTabBridge.tsx +++ b/components/terminalLayer/TerminalLayerTabBridge.tsx @@ -526,6 +526,7 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef }) sessionHostsMap, s.resolvedSessionHostIds, sessions, + s.terminalSettings, showHostTreeSidebar, sftpActiveHost, s.sftpFollowTerminalCwd, diff --git a/components/terminalLayer/terminalLayerViewMemo.test.ts b/components/terminalLayer/terminalLayerViewMemo.test.ts index 87fc47458..50961be76 100644 --- a/components/terminalLayer/terminalLayerViewMemo.test.ts +++ b/components/terminalLayer/terminalLayerViewMemo.test.ts @@ -3,6 +3,7 @@ import assert from "node:assert/strict"; import type { Workspace } from "../../types"; import { + terminalLayerFocusSidebarPropsEqual, terminalLayerSidePanelCtxEqual, terminalLayerViewCtxEqual, terminalLayerWorkspaceCtxEqual, @@ -142,3 +143,30 @@ test("terminal layer side panel re-renders when follow terminal cwd setting chan false, ); }); + +test("terminal layer focus sidebar re-renders when dynamic tab title mode changes", () => { + const baseCtx = { + isFocusMode: true, + activeWorkspace: workspace(), + focusedSessionId: "session-1", + resolvedPreviewTheme: {}, + sessionHostsMap: new Map(), + sessions: [], + terminalSettings: { dynamicTabTitleMode: "agent" }, + }; + + assert.equal( + terminalLayerFocusSidebarPropsEqual( + baseCtx, + { ...baseCtx, terminalSettings: { dynamicTabTitleMode: "off" } }, + ), + false, + ); + assert.equal( + terminalLayerViewCtxEqual( + baseCtx, + { ...baseCtx, terminalSettings: { dynamicTabTitleMode: "off" } }, + ), + false, + ); +}); diff --git a/components/terminalLayer/terminalLayerViewMemo.ts b/components/terminalLayer/terminalLayerViewMemo.ts index 2769d4845..0727d1c26 100644 --- a/components/terminalLayer/terminalLayerViewMemo.ts +++ b/components/terminalLayer/terminalLayerViewMemo.ts @@ -354,6 +354,7 @@ export function terminalLayerFocusSidebarPropsEqual(prev: Ctx, next: Ctx): boole && eq(prev, next, 'resolvedPreviewTheme') && eq(prev, next, 'sessionHostsMap') && eq(prev, next, 'sessions') + && prev.terminalSettings?.dynamicTabTitleMode === next.terminalSettings?.dynamicTabTitleMode && eq(prev, next, 't') && eq(prev, next, 'onReorderWorkspaceSessions') && eq(prev, next, 'onRequestAddToWorkspace') diff --git a/components/top-tabs/TopTabItems.tsx b/components/top-tabs/TopTabItems.tsx index b04413b8f..ea74ae08f 100644 --- a/components/top-tabs/TopTabItems.tsx +++ b/components/top-tabs/TopTabItems.tsx @@ -10,6 +10,7 @@ import { resolveHostIconAppearance, resolveHostIconColorAppearance } from '../.. import { resolveSessionCodingCliProvider } from '../../domain/codingCliProviderMatch'; import { resolveCodingCliActivityPhase } from '../../domain/codingCliTitleParse'; import { resolveSessionTabTitle } from '../../domain/sessionTabTitle'; +import type { DynamicTabTitleMode } from '../../domain/models'; import { CodingCliProviderIcon } from '../icons/CodingCliProviderIcon'; import { cn } from '../../lib/utils'; import { Host, TerminalSession, Workspace } from '../../types'; @@ -503,6 +504,7 @@ interface SessionTopTabProps { onCopySession: (sessionId: string) => void; onCopySessionToNewWindow: (sessionId: string) => void; renderBulkCloseItems: RenderBulkCloseItems; + dynamicTabTitleMode?: DynamicTabTitleMode; t: TranslateFn; tabAnimationClass?: string; } @@ -526,6 +528,7 @@ export const SessionTopTab: React.FC = memo(({ onCopySession, onCopySessionToNewWindow, renderBulkCloseItems, + dynamicTabTitleMode, t, tabAnimationClass, }) => { @@ -592,7 +595,7 @@ export const SessionTopTab: React.FC = memo(({ )}
- {resolveSessionTabTitle(session, host)} + {resolveSessionTabTitle(session, dynamicTabTitleMode)}
{sessionStatusDot(session.status, hasActivity)}
-
+
+ ); }; diff --git a/components/port-forwarding/PortForwardHostKeyDialog.tsx b/components/port-forwarding/PortForwardHostKeyDialog.tsx new file mode 100644 index 000000000..d7e796ca8 --- /dev/null +++ b/components/port-forwarding/PortForwardHostKeyDialog.tsx @@ -0,0 +1,43 @@ +import React from "react"; +import type { KnownHost } from "../../domain/models"; +import { usePortForwardHostKeyVerification } from "../../application/state/usePortForwardHostKeyVerification"; +import { Dialog, DialogContent, DialogTitle } from "../ui/dialog"; +import { TerminalHostKeyVerification } from "../terminal/TerminalHostKeyVerification"; + +interface PortForwardHostKeyDialogProps { + onAddKnownHost?: (knownHost: KnownHost) => void; +} + +export const PortForwardHostKeyDialog: React.FC = ({ + onAddKnownHost, +}) => { + const { + hostKeyVerification, + rejectHostKeyVerification, + acceptHostKeyVerification, + acceptAndSaveHostKeyVerification, + } = usePortForwardHostKeyVerification(onAddKnownHost); + + return ( + { + if (!open) rejectHostKeyVerification(); + }} + > + + Confirm host key + {hostKeyVerification && ( + + )} + + + ); +}; diff --git a/components/port-forwarding/hostKeyVerification.test.ts b/components/port-forwarding/hostKeyVerification.test.ts new file mode 100644 index 000000000..0009c03e0 --- /dev/null +++ b/components/port-forwarding/hostKeyVerification.test.ts @@ -0,0 +1,38 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { + createKnownHostFromPortForwardHostKeyInfo, + isPortForwardHostKeySessionId, +} from "./hostKeyVerification.ts"; + +test("isPortForwardHostKeySessionId only accepts port-forward tunnel sessions", () => { + assert.equal(isPortForwardHostKeySessionId("pf-rule-1-123456"), true); + assert.equal(isPortForwardHostKeySessionId("session-1"), false); + assert.equal(isPortForwardHostKeySessionId(undefined), false); +}); + +test("createKnownHostFromPortForwardHostKeyInfo saves the verified host key", () => { + assert.deepEqual( + createKnownHostFromPortForwardHostKeyInfo( + { + hostname: "jump.internal", + port: 2200, + keyType: "ssh-ed25519", + fingerprint: "abc123", + publicKey: "ssh-ed25519 AAAA", + }, + 1000, + "fixed", + ), + { + id: "kh-1000-fixed", + hostname: "jump.internal", + port: 2200, + keyType: "ssh-ed25519", + publicKey: "ssh-ed25519 AAAA", + fingerprint: "abc123", + discoveredAt: 1000, + }, + ); +}); diff --git a/components/port-forwarding/hostKeyVerification.ts b/components/port-forwarding/hostKeyVerification.ts new file mode 100644 index 000000000..73c7c1af5 --- /dev/null +++ b/components/port-forwarding/hostKeyVerification.ts @@ -0,0 +1,20 @@ +import type { KnownHost } from "../../domain/models"; +import type { HostKeyInfo } from "../terminal/TerminalHostKeyVerification"; + +export const isPortForwardHostKeySessionId = (sessionId?: string): boolean => { + return typeof sessionId === "string" && sessionId.startsWith("pf-"); +}; + +export const createKnownHostFromPortForwardHostKeyInfo = ( + hostKeyInfo: HostKeyInfo, + now = Date.now(), + idSuffix = Math.random().toString(36).slice(2, 11), +): KnownHost => ({ + id: hostKeyInfo.knownHostId || `kh-${now}-${idSuffix}`, + hostname: hostKeyInfo.hostname, + port: hostKeyInfo.port || 22, + keyType: hostKeyInfo.keyType, + publicKey: hostKeyInfo.publicKey || `SHA256:${hostKeyInfo.fingerprint}`, + fingerprint: hostKeyInfo.fingerprint, + discoveredAt: now, +}); diff --git a/components/port-forwarding/index.ts b/components/port-forwarding/index.ts index c7adda081..4388b6a6a 100644 --- a/components/port-forwarding/index.ts +++ b/components/port-forwarding/index.ts @@ -15,3 +15,5 @@ export { WizardContent } from './WizardContent'; export { EditPanel } from './EditPanel'; export { NewFormPanel } from './NewFormPanel'; + +export { PortForwardHostKeyDialog } from './PortForwardHostKeyDialog'; From 156fcbebedf2cdb36d30a4d9af794294b4528922 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Thu, 25 Jun 2026 15:03:12 +0800 Subject: [PATCH 048/228] fix host hostname whitespace handling --- components/HostDetailsPanel.proxyProfile.test.tsx | 12 ++++++++++++ components/HostDetailsPanel.tsx | 11 +++++++---- domain/host.test.ts | 8 ++++++++ domain/host.ts | 2 +- 4 files changed, 28 insertions(+), 5 deletions(-) diff --git a/components/HostDetailsPanel.proxyProfile.test.tsx b/components/HostDetailsPanel.proxyProfile.test.tsx index 57f0163e4..32542da10 100644 --- a/components/HostDetailsPanel.proxyProfile.test.tsx +++ b/components/HostDetailsPanel.proxyProfile.test.tsx @@ -108,6 +108,18 @@ test("HostDetailsPanel keeps explicitly cleared telnet credentials empty", () => assert.doesNotMatch(markup, /placeholder="Telnet Password"[^>]*value="ssh-password"/); }); +test("HostDetailsPanel disables save when hostname is whitespace only", () => { + const markup = renderHostDetails({ + ...hostWithMissingProxyProfile, + hostname: " ", + proxyProfileId: undefined, + }); + + assert.match(markup, /]*disabled=""[^>]*aria-label="Save"/); + assert.match(markup, />Save<\/button>/); + assert.match(markup, /]*disabled=""[^>]*>Save<\/button>/); +}); + test("HostDetailsPanel gives the telnet port field the same roomy layout as SSH", () => { const markup = renderHostDetails({ ...hostWithMissingProxyProfile, diff --git a/components/HostDetailsPanel.tsx b/components/HostDetailsPanel.tsx index 5d8ff6e94..253f0eb5d 100644 --- a/components/HostDetailsPanel.tsx +++ b/components/HostDetailsPanel.tsx @@ -359,9 +359,11 @@ const HostDetailsPanel: React.FC = ({ return { ...prev, environmentVariables: filtered.length > 0 ? filtered : undefined }; }); }; + const hasHostname = form.hostname.trim().length > 0; const handleSubmit = () => { - if (!form.hostname) return; + const hostname = form.hostname.trim(); + if (!hostname) return; const normalizedProxyConfig = normalizeManualProxyConfig(form.proxyConfig); if (normalizedProxyConfig && !isCompleteProxyConfig(normalizedProxyConfig)) { toast.error( @@ -375,7 +377,7 @@ const HostDetailsPanel: React.FC = ({ setActiveSubPanel("proxy"); return; } - let finalLabel = form.label?.trim() || form.hostname; + let finalLabel = form.label?.trim() || hostname; const finalGroup = groupInputValue.trim() || form.group || ""; const targetManagedSource = managedSources @@ -407,6 +409,7 @@ const HostDetailsPanel: React.FC = ({ let cleaned: Host = { ...formWithoutProxyDraft, ...(normalizedProxyConfig && { proxyConfig: normalizedProxyConfig }), + hostname, label: finalLabel, group: finalGroup, tags: form.tags || [], @@ -711,7 +714,7 @@ const HostDetailsPanel: React.FC = ({ size="icon" className="h-8 w-8" onClick={handleSubmit} - disabled={!form.hostname} + disabled={!hasHostname} aria-label={t("hostDetails.saveAria")} > @@ -985,7 +988,7 @@ const HostDetailsPanel: React.FC = ({ diff --git a/domain/host.test.ts b/domain/host.test.ts index 6daa01a40..ee36520e6 100644 --- a/domain/host.test.ts +++ b/domain/host.test.ts @@ -173,6 +173,14 @@ test("sanitizeHost removes invalid custom host icon fields", () => { assert.equal(sanitized.iconColor, undefined); }); +test("sanitizeHost trims leading whitespace before extracting the hostname", () => { + const sanitized = sanitizeHost(makeHost({ + hostname: " 127.0.0.1", + })); + + assert.equal(sanitized.hostname, "127.0.0.1"); +}); + test("preserves a concurrent terminal timestamp toggle when host details did not edit it", () => { const openedHost = makeHost({ showLineTimestamps: false }); const latestHost = makeHost({ showLineTimestamps: true }); diff --git a/domain/host.ts b/domain/host.ts index ad9ee3a30..d6c1a50dd 100644 --- a/domain/host.ts +++ b/domain/host.ts @@ -333,7 +333,7 @@ export const resolveHostKeepalive = ( }; export const sanitizeHost = (host: Host): Host => { - const cleanHostname = (host.hostname || '').split(/\s+/)[0]; + const cleanHostname = (host.hostname || '').trim().split(/\s+/)[0]; const cleanDistro = normalizeDistroId(host.distro); const cleanManualDistro = normalizeDistroId(host.manualDistro); const cleanDistroMode = From 55ab3cc3f2a47500b70776c600e00355e6a0406c Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Thu, 25 Jun 2026 15:04:00 +0800 Subject: [PATCH 049/228] address port forward host key review --- .../usePortForwardHostKeyVerification.ts | 30 +++----- components/TrayPanel.tsx | 6 ++ .../PortForwardHostKeyDialog.test.ts | 20 +++++ .../PortForwardHostKeyDialog.tsx | 7 +- .../hostKeyVerification.test.ts | 77 +++++++++++++++++++ .../port-forwarding/hostKeyVerification.ts | 36 +++++++++ package.json | 2 +- 7 files changed, 157 insertions(+), 21 deletions(-) create mode 100644 components/port-forwarding/PortForwardHostKeyDialog.test.ts diff --git a/application/state/usePortForwardHostKeyVerification.ts b/application/state/usePortForwardHostKeyVerification.ts index 2b935a883..8e8aedaf0 100644 --- a/application/state/usePortForwardHostKeyVerification.ts +++ b/application/state/usePortForwardHostKeyVerification.ts @@ -2,22 +2,15 @@ import { useCallback, useEffect, useState } from "react"; import type { KnownHost } from "../../domain/models"; import { netcattyBridge } from "../../infrastructure/services/netcattyBridge"; import type { HostKeyInfo } from "../../components/terminal/TerminalHostKeyVerification"; -import { toHostKeyInfo, type HostKeyVerificationRequest } from "../../components/terminal/hostKeyVerification"; import { createKnownHostFromPortForwardHostKeyInfo, - isPortForwardHostKeySessionId, + enqueuePortForwardHostKeyVerification, + removePortForwardHostKeyVerification, + toPendingPortForwardHostKeyVerification, + type PendingPortForwardHostKeyVerification, + type PortForwardHostKeyRequest, } from "../../components/port-forwarding/hostKeyVerification"; -type PortForwardHostKeyRequest = HostKeyVerificationRequest & { - requestId: string; - sessionId?: string; -}; - -interface PendingHostKeyVerification { - requestId: string; - hostKeyInfo: HostKeyInfo; -} - export interface PortForwardHostKeyVerificationState { hostKeyInfo: HostKeyInfo; } @@ -25,15 +18,14 @@ export interface PortForwardHostKeyVerificationState { export const usePortForwardHostKeyVerification = ( onAddKnownHost?: (knownHost: KnownHost) => void, ) => { - const [pending, setPending] = useState(null); + const [pendingQueue, setPendingQueue] = useState([]); + const pending = pendingQueue[0] ?? null; useEffect(() => { const dispose = netcattyBridge.get()?.onHostKeyVerification?.((request: PortForwardHostKeyRequest) => { - if (!isPortForwardHostKeySessionId(request.sessionId)) return; - setPending({ - requestId: request.requestId, - hostKeyInfo: toHostKeyInfo(request), - }); + const next = toPendingPortForwardHostKeyVerification(request); + if (!next) return; + setPendingQueue((queue) => enqueuePortForwardHostKeyVerification(queue, next)); }); return () => { @@ -51,7 +43,7 @@ export const usePortForwardHostKeyVerification = ( accept, addToKnownHosts, ); - setPending(null); + setPendingQueue((queue) => removePortForwardHostKeyVerification(queue, pending.requestId)); }, [onAddKnownHost, pending]); return { diff --git a/components/TrayPanel.tsx b/components/TrayPanel.tsx index 3defcc00d..7b35503d9 100644 --- a/components/TrayPanel.tsx +++ b/components/TrayPanel.tsx @@ -200,6 +200,12 @@ const TrayPanelContent: React.FC = ({ terminalSettings }) if (target instanceof HTMLElement && target.closest("button,a,input,select,textarea,[role='button']")) { return; } + if ( + target instanceof HTMLElement && + target.closest("[data-port-forward-host-key-dialog='true'],.port-forward-host-key-dialog-layer") + ) { + return; + } // Clicking on background should close panel const root = document.getElementById("tray-panel-root"); if (root && !root.contains(target)) { diff --git a/components/port-forwarding/PortForwardHostKeyDialog.test.ts b/components/port-forwarding/PortForwardHostKeyDialog.test.ts new file mode 100644 index 000000000..23ed0e2f2 --- /dev/null +++ b/components/port-forwarding/PortForwardHostKeyDialog.test.ts @@ -0,0 +1,20 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; + +const dialogSource = readFileSync( + new URL("./PortForwardHostKeyDialog.tsx", import.meta.url), + "utf8", +); + +const trayPanelSource = readFileSync( + new URL("../TrayPanel.tsx", import.meta.url), + "utf8", +); + +test("port-forward host-key dialog is marked so tray outside-click handling ignores it", () => { + assert.match(dialogSource, /data-port-forward-host-key-dialog="true"/); + assert.match(dialogSource, /overlayClassName="port-forward-host-key-dialog-layer"/); + assert.match(trayPanelSource, /data-port-forward-host-key-dialog/); + assert.match(trayPanelSource, /port-forward-host-key-dialog-layer/); +}); diff --git a/components/port-forwarding/PortForwardHostKeyDialog.tsx b/components/port-forwarding/PortForwardHostKeyDialog.tsx index d7e796ca8..0066eef5f 100644 --- a/components/port-forwarding/PortForwardHostKeyDialog.tsx +++ b/components/port-forwarding/PortForwardHostKeyDialog.tsx @@ -25,7 +25,12 @@ export const PortForwardHostKeyDialog: React.FC = if (!open) rejectHostKeyVerification(); }} > - + Confirm host key {hostKeyVerification && ( { @@ -36,3 +39,77 @@ test("createKnownHostFromPortForwardHostKeyInfo saves the verified host key", () }, ); }); + +test("toPendingPortForwardHostKeyVerification ignores non-port-forward requests", () => { + assert.equal( + toPendingPortForwardHostKeyVerification({ + requestId: "req-terminal", + sessionId: "terminal-session", + hostname: "terminal.example.com", + port: 22, + keyType: "ssh-ed25519", + fingerprint: "terminal-fingerprint", + }), + null, + ); +}); + +test("toPendingPortForwardHostKeyVerification accepts port-forward requests", () => { + assert.deepEqual( + toPendingPortForwardHostKeyVerification({ + requestId: "req-port-forward", + sessionId: "pf-rule-1-123456", + hostname: "jump.internal", + port: 2200, + keyType: "ssh-ed25519", + fingerprint: "abc123", + publicKey: "ssh-ed25519 AAAA", + status: "unknown", + }), + { + requestId: "req-port-forward", + hostKeyInfo: { + hostname: "jump.internal", + port: 2200, + keyType: "ssh-ed25519", + fingerprint: "abc123", + publicKey: "ssh-ed25519 AAAA", + status: "unknown", + knownHostId: undefined, + knownFingerprint: undefined, + }, + }, + ); +}); + +test("port-forward host-key confirmations are queued instead of overwritten", () => { + const first = { + requestId: "req-1", + hostKeyInfo: { + hostname: "jump-1.internal", + port: 22, + keyType: "ssh-ed25519", + fingerprint: "first", + }, + }; + const second = { + requestId: "req-2", + hostKeyInfo: { + hostname: "jump-2.internal", + port: 22, + keyType: "ssh-ed25519", + fingerprint: "second", + }, + }; + + const queued = enqueuePortForwardHostKeyVerification( + enqueuePortForwardHostKeyVerification([], first), + second, + ); + + assert.deepEqual(queued.map((pending) => pending.requestId), ["req-1", "req-2"]); + assert.deepEqual( + removePortForwardHostKeyVerification(queued, "req-1").map((pending) => pending.requestId), + ["req-2"], + ); +}); diff --git a/components/port-forwarding/hostKeyVerification.ts b/components/port-forwarding/hostKeyVerification.ts index 73c7c1af5..bbae439ca 100644 --- a/components/port-forwarding/hostKeyVerification.ts +++ b/components/port-forwarding/hostKeyVerification.ts @@ -1,10 +1,46 @@ import type { KnownHost } from "../../domain/models"; +import { toHostKeyInfo, type HostKeyVerificationRequest } from "../terminal/hostKeyVerification"; import type { HostKeyInfo } from "../terminal/TerminalHostKeyVerification"; export const isPortForwardHostKeySessionId = (sessionId?: string): boolean => { return typeof sessionId === "string" && sessionId.startsWith("pf-"); }; +export type PortForwardHostKeyRequest = HostKeyVerificationRequest & { + requestId: string; + sessionId?: string; +}; + +export interface PendingPortForwardHostKeyVerification { + requestId: string; + hostKeyInfo: HostKeyInfo; +} + +export const toPendingPortForwardHostKeyVerification = ( + request: PortForwardHostKeyRequest, +): PendingPortForwardHostKeyVerification | null => { + if (!isPortForwardHostKeySessionId(request.sessionId)) return null; + return { + requestId: request.requestId, + hostKeyInfo: toHostKeyInfo(request), + }; +}; + +export const enqueuePortForwardHostKeyVerification = ( + queue: PendingPortForwardHostKeyVerification[], + pending: PendingPortForwardHostKeyVerification, +): PendingPortForwardHostKeyVerification[] => [...queue, pending]; + +export const removePortForwardHostKeyVerification = ( + queue: PendingPortForwardHostKeyVerification[], + requestId: string, +): PendingPortForwardHostKeyVerification[] => { + if (queue[0]?.requestId === requestId) { + return queue.slice(1); + } + return queue.filter((pending) => pending.requestId !== requestId); +}; + export const createKnownHostFromPortForwardHostKeyInfo = ( hostKeyInfo: HostKeyInfo, now = Date.now(), diff --git a/package.json b/package.json index bf068c578..8ed8b167a 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,7 @@ "tool:cli": "node electron/cli/netcatty-tool-cli.cjs", "lint": "eslint .", "lint:fix": "eslint . --fix", - "test": "node --test --import tsx electron/*.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/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/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/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/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", From 4881485fa67c5c91d8d77636b5be38e58dd2712c Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Thu, 25 Jun 2026 15:11:59 +0800 Subject: [PATCH 050/228] polish tray host key dialog sizing --- components/port-forwarding/PortForwardHostKeyDialog.test.ts | 2 ++ components/port-forwarding/PortForwardHostKeyDialog.tsx | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/components/port-forwarding/PortForwardHostKeyDialog.test.ts b/components/port-forwarding/PortForwardHostKeyDialog.test.ts index 23ed0e2f2..71bf00128 100644 --- a/components/port-forwarding/PortForwardHostKeyDialog.test.ts +++ b/components/port-forwarding/PortForwardHostKeyDialog.test.ts @@ -15,6 +15,8 @@ const trayPanelSource = readFileSync( test("port-forward host-key dialog is marked so tray outside-click handling ignores it", () => { assert.match(dialogSource, /data-port-forward-host-key-dialog="true"/); assert.match(dialogSource, /overlayClassName="port-forward-host-key-dialog-layer"/); + assert.match(dialogSource, /w-\[calc\(100vw-1\.5rem\)\]/); + assert.match(dialogSource, /rounded-lg/); assert.match(trayPanelSource, /data-port-forward-host-key-dialog/); assert.match(trayPanelSource, /port-forward-host-key-dialog-layer/); }); diff --git a/components/port-forwarding/PortForwardHostKeyDialog.tsx b/components/port-forwarding/PortForwardHostKeyDialog.tsx index 0066eef5f..45e5127d3 100644 --- a/components/port-forwarding/PortForwardHostKeyDialog.tsx +++ b/components/port-forwarding/PortForwardHostKeyDialog.tsx @@ -26,7 +26,7 @@ export const PortForwardHostKeyDialog: React.FC = }} > Date: Thu, 25 Jun 2026 15:25:23 +0800 Subject: [PATCH 051/228] fix focus sidebar dynamic title refresh Refresh focus sidebar rows when Dynamic tab title mode changes. Follow-up to Codex review on #1658. --- components/terminalLayer/TerminalFocusSidebar.test.ts | 9 +++++++++ components/terminalLayer/TerminalFocusSidebar.tsx | 1 + 2 files changed, 10 insertions(+) create mode 100644 components/terminalLayer/TerminalFocusSidebar.test.ts diff --git a/components/terminalLayer/TerminalFocusSidebar.test.ts b/components/terminalLayer/TerminalFocusSidebar.test.ts new file mode 100644 index 000000000..88ffbc46e --- /dev/null +++ b/components/terminalLayer/TerminalFocusSidebar.test.ts @@ -0,0 +1,9 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import test from 'node:test'; + +const source = readFileSync(new URL('./TerminalFocusSidebar.tsx', import.meta.url), 'utf8'); + +test('focus sidebar row memo refreshes when dynamic title mode changes', () => { + assert.match(source, /prev\.dynamicTabTitleMode === next\.dynamicTabTitleMode/); +}); diff --git a/components/terminalLayer/TerminalFocusSidebar.tsx b/components/terminalLayer/TerminalFocusSidebar.tsx index 9a10aa99a..81d50cb7c 100644 --- a/components/terminalLayer/TerminalFocusSidebar.tsx +++ b/components/terminalLayer/TerminalFocusSidebar.tsx @@ -230,6 +230,7 @@ const WorkspaceFocusSessionRow = memo(({ && prev.onDragOver === next.onDragOver && prev.onDrop === next.onDrop && prev.onDragEnd === next.onDragEnd + && prev.dynamicTabTitleMode === next.dynamicTabTitleMode && prev.t === next.t )); WorkspaceFocusSessionRow.displayName = 'WorkspaceFocusSessionRow'; From 7a62acb8286199ee3682353d0f81cfb3f9d52eab Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Thu, 25 Jun 2026 15:44:59 +0800 Subject: [PATCH 052/228] Add tray host key trust prompt --- application/i18n/locales/en/core.ts | 2 + application/i18n/locales/zh-CN/core.ts | 2 + application/state/sftp/types.ts | 2 +- .../state/sftp/useSftpHostCredentials.test.ts | 16 +++ .../state/sftp/useSftpHostCredentials.ts | 16 ++- components/TrayPanel.tsx | 8 +- .../PortForwardHostKeyDialog.test.ts | 14 +++ .../PortForwardHostKeyTrayPrompt.tsx | 119 ++++++++++++++++++ components/port-forwarding/index.ts | 1 + .../settings/tabs/SettingsTerminalTab.test.ts | 6 + .../settings/tabs/SettingsTerminalTab.tsx | 9 ++ .../createTerminalSessionStarters.test.ts | 9 +- .../runtime/createTerminalSessionStarters.ts | 16 ++- domain/models/terminal.ts | 2 + electron/bridges/hostKeyVerifier.cjs | 6 + electron/bridges/hostKeyVerifier.test.cjs | 23 ++++ electron/bridges/portForwardingBridge.cjs | 11 ++ .../bridges/sftpBridge/openConnection.cjs | 2 + electron/bridges/sshBridge.cjs | 1 + .../bridges/sshBridge/moshStatsConnection.cjs | 9 +- electron/bridges/sshBridge/startSession.cjs | 1 + electron/bridges/terminalBridge/etSession.cjs | 1 + .../bridges/terminalBridge/moshSession.cjs | 1 + global.d.ts | 3 + .../services/portForwardingService.ts | 18 ++- types/global/netcatty-bridge-session.d.ts | 2 + 26 files changed, 278 insertions(+), 22 deletions(-) create mode 100644 components/port-forwarding/PortForwardHostKeyTrayPrompt.tsx diff --git a/application/i18n/locales/en/core.ts b/application/i18n/locales/en/core.ts index d33a98928..c4dcb72c0 100644 --- a/application/i18n/locales/en/core.ts +++ b/application/i18n/locales/en/core.ts @@ -451,6 +451,8 @@ export const enCoreMessages: Messages = { 'settings.terminal.localShell.startDir.notFound': 'Directory not found', 'settings.terminal.localShell.startDir.isFile': 'Path is a file, not a directory', 'settings.terminal.section.connection': 'Connection', + 'settings.terminal.connection.verifyHostKeys': 'Verify SSH host keys', + 'settings.terminal.connection.verifyHostKeys.desc': 'Ask before connecting to a new or changed SSH host key. Turn this off only for trusted private networks.', 'settings.terminal.connection.keepaliveInterval': 'Keepalive Interval', 'settings.terminal.connection.keepaliveInterval.desc': 'How often (in seconds) to send SSH-level keepalive packets. Set to 0 to disable globally — note that individual hosts can override this in their own settings.', 'settings.terminal.connection.keepaliveCountMax': 'Max unanswered keepalives', diff --git a/application/i18n/locales/zh-CN/core.ts b/application/i18n/locales/zh-CN/core.ts index d9b4cce99..b8509ba2c 100644 --- a/application/i18n/locales/zh-CN/core.ts +++ b/application/i18n/locales/zh-CN/core.ts @@ -67,6 +67,8 @@ export const zhCNCoreMessages: Messages = { 'settings.tab.shortcuts': '快捷键', 'settings.tab.syncCloud': '同步与云', 'settings.tab.system': '系统', + 'settings.terminal.connection.verifyHostKeys': '校验 SSH 主机密钥', + 'settings.terminal.connection.verifyHostKeys.desc': '连接到新的或已变化的 SSH 主机密钥前先询问。只建议在可信内网中关闭。', // Settings > System 'settings.system.title': '系统', diff --git a/application/state/sftp/types.ts b/application/state/sftp/types.ts index e1744ad63..f090667be 100644 --- a/application/state/sftp/types.ts +++ b/application/state/sftp/types.ts @@ -85,7 +85,7 @@ export interface SftpStateOptions { * keepalive resolution so a host that has opted into its own override * is honored for SFTP browsing too (not just the terminal session). */ - terminalSettings?: { keepaliveInterval: number; keepaliveCountMax: number }; + terminalSettings?: { verifyHostKeys: boolean; keepaliveInterval: number; keepaliveCountMax: number }; knownHosts?: KnownHost[]; onAddKnownHost?: (knownHost: KnownHost) => void; } diff --git a/application/state/sftp/useSftpHostCredentials.test.ts b/application/state/sftp/useSftpHostCredentials.test.ts index e1cb02c42..3e0b068dc 100644 --- a/application/state/sftp/useSftpHostCredentials.test.ts +++ b/application/state/sftp/useSftpHostCredentials.test.ts @@ -124,6 +124,22 @@ test("buildSftpHostCredentials forwards known hosts for SFTP host-key checks", ( assert.equal(credentials.knownHosts, knownHosts); }); +test("buildSftpHostCredentials forwards the host-key verification setting", () => { + const credentials = buildSftpHostCredentials({ + host: host(), + hosts: [], + keys: [], + identities: [], + terminalSettings: { + verifyHostKeys: false, + keepaliveInterval: 30, + keepaliveCountMax: 10, + }, + }); + + assert.equal(credentials.verifyHostKeys, false); +}); + test("buildSftpHostCredentials passes jump host reference keys as identity file paths", () => { const key: SSHKey = { id: "jump-key", diff --git a/application/state/sftp/useSftpHostCredentials.ts b/application/state/sftp/useSftpHostCredentials.ts index 791ccb663..911b1dc0b 100644 --- a/application/state/sftp/useSftpHostCredentials.ts +++ b/application/state/sftp/useSftpHostCredentials.ts @@ -8,14 +8,18 @@ import { hasUsableProxyConfig } from "../../../domain/proxyProfiles"; // Fallback used when no global TerminalSettings are wired through (older // call sites or tests). Matches DEFAULT_TERMINAL_SETTINGS so behavior is // identical whether or not the caller passes settings. -const FALLBACK_KEEPALIVE = { keepaliveInterval: 30, keepaliveCountMax: 10 }; +const FALLBACK_TERMINAL_SETTINGS = { + verifyHostKeys: true, + keepaliveInterval: 30, + keepaliveCountMax: 10, +}; interface UseSftpHostCredentialsParams { hosts: Host[]; keys: SSHKey[]; identities: Identity[]; knownHosts?: KnownHost[]; - terminalSettings?: Pick; + terminalSettings?: Pick; } export const buildSftpHostCredentials = ({ @@ -26,7 +30,7 @@ export const buildSftpHostCredentials = ({ knownHosts, terminalSettings, }: UseSftpHostCredentialsParams & { host: Host }): NetcattySSHOptions => { - const globalKeepalive = terminalSettings ?? FALLBACK_KEEPALIVE; + const globalTerminalSettings = { ...FALLBACK_TERMINAL_SETTINGS, ...(terminalSettings ?? {}) }; if (host.proxyProfileId && !host.proxyConfig) { throw new Error(`Saved proxy for host "${host.label || host.hostname}" is missing. Open host settings and select a valid proxy.`); } @@ -92,7 +96,7 @@ export const buildSftpHostCredentials = ({ ) { throw new Error(`Saved credentials for jump host "${jumpHost.label || jumpHost.hostname}" cannot be decrypted on this device. Open host settings and re-enter them.`); } - const hopKeepalive = resolveHostKeepalive(jumpHost, globalKeepalive); + const hopKeepalive = resolveHostKeepalive(jumpHost, globalTerminalSettings); return { hostname: jumpHost.hostname, port: jumpHost.port || 22, @@ -118,6 +122,7 @@ export const buildSftpHostCredentials = ({ identityFilePaths: jumpKeyAuth.identityFilePaths, keepaliveInterval: hopKeepalive.interval, keepaliveCountMax: hopKeepalive.countMax, + verifyHostKeys: globalTerminalSettings.verifyHostKeys, legacyAlgorithms: jumpHost.legacyAlgorithms, skipEcdsaHostKey: jumpHost.skipEcdsaHostKey, algorithmOverrides: jumpHost.algorithms, @@ -149,7 +154,7 @@ export const buildSftpHostCredentials = ({ throw new Error("Saved credentials cannot be decrypted on this device. Open host settings and re-enter them."); } - const targetKeepalive = resolveHostKeepalive(host, globalKeepalive); + const targetKeepalive = resolveHostKeepalive(host, globalTerminalSettings); return { hostname: host.hostname, username: resolved.username, @@ -168,6 +173,7 @@ export const buildSftpHostCredentials = ({ keepaliveInterval: targetKeepalive.interval, keepaliveCountMax: targetKeepalive.countMax, knownHosts, + verifyHostKeys: globalTerminalSettings.verifyHostKeys, // Algorithm settings — must reach the SFTP bridge or hosts that need // legacy mode / the ECDSA skip / advanced overrides would still hit // the original negotiation failure when opening their SFTP pane, diff --git a/components/TrayPanel.tsx b/components/TrayPanel.tsx index 7b35503d9..a0735efa7 100644 --- a/components/TrayPanel.tsx +++ b/components/TrayPanel.tsx @@ -16,7 +16,7 @@ import { materializeHostProxyProfile } from "../domain/proxyProfiles"; import { upsertKnownHost } from "../domain/knownHosts"; import type { Host, KnownHost } from "../domain/models"; import { getEffectiveKnownHosts } from "../infrastructure/syncHelpers"; -import { PortForwardHostKeyDialog } from "./port-forwarding"; +import { PortForwardHostKeyTrayPrompt } from "./port-forwarding"; import { X, Maximize2, ChevronRight, ChevronDown, Power } from "lucide-react"; import { AppLogo } from "./AppLogo"; @@ -115,7 +115,7 @@ const WorkspaceGroup: React.FC<{ }; interface TrayPanelContentProps { - terminalSettings?: { keepaliveInterval: number; keepaliveCountMax: number }; + terminalSettings?: { verifyHostKeys: boolean; keepaliveInterval: number; keepaliveCountMax: number }; } const TrayPanelContent: React.FC = ({ terminalSettings }) => { @@ -202,7 +202,7 @@ const TrayPanelContent: React.FC = ({ terminalSettings }) } if ( target instanceof HTMLElement && - target.closest("[data-port-forward-host-key-dialog='true'],.port-forward-host-key-dialog-layer") + target.closest("[data-port-forward-host-key-dialog='true'],[data-port-forward-host-key-tray-prompt='true'],.port-forward-host-key-dialog-layer") ) { return; } @@ -233,7 +233,6 @@ const TrayPanelContent: React.FC = ({ terminalSettings }) return ( <> -
@@ -262,6 +261,7 @@ const TrayPanelContent: React.FC = ({ terminalSettings })
+ {jumpableSessions.length > 0 && (() => { // Group sessions by workspace diff --git a/components/port-forwarding/PortForwardHostKeyDialog.test.ts b/components/port-forwarding/PortForwardHostKeyDialog.test.ts index 71bf00128..1d8e94003 100644 --- a/components/port-forwarding/PortForwardHostKeyDialog.test.ts +++ b/components/port-forwarding/PortForwardHostKeyDialog.test.ts @@ -12,6 +12,11 @@ const trayPanelSource = readFileSync( "utf8", ); +const trayPromptSource = readFileSync( + new URL("./PortForwardHostKeyTrayPrompt.tsx", import.meta.url), + "utf8", +); + test("port-forward host-key dialog is marked so tray outside-click handling ignores it", () => { assert.match(dialogSource, /data-port-forward-host-key-dialog="true"/); assert.match(dialogSource, /overlayClassName="port-forward-host-key-dialog-layer"/); @@ -20,3 +25,12 @@ test("port-forward host-key dialog is marked so tray outside-click handling igno assert.match(trayPanelSource, /data-port-forward-host-key-dialog/); assert.match(trayPanelSource, /port-forward-host-key-dialog-layer/); }); + +test("tray uses the lightweight host-key prompt instead of the main dialog", () => { + assert.match(trayPromptSource, /data-port-forward-host-key-tray-prompt="true"/); + assert.match(trayPromptSource, /grid-cols-\[auto_auto_1fr\]/); + assert.match(trayPanelSource, //); + assert.doesNotMatch(trayPanelSource, / void; +} + +export const PortForwardHostKeyTrayPrompt: React.FC = ({ + onAddKnownHost, +}) => { + const { t } = useI18n(); + const { + hostKeyVerification, + rejectHostKeyVerification, + acceptHostKeyVerification, + acceptAndSaveHostKeyVerification, + } = usePortForwardHostKeyVerification(onAddKnownHost); + + if (!hostKeyVerification) return null; + + const { hostKeyInfo } = hostKeyVerification; + const isChanged = hostKeyInfo.status === "changed"; + const Icon = isChanged ? AlertTriangle : Fingerprint; + + return ( +
+
+
+ +
+
+
+ {isChanged + ? t("terminal.hostKey.changedTitle") + : t("terminal.hostKey.unknownTitle")} +
+
+ {hostKeyInfo.hostname}:{hostKeyInfo.port} +
+
+
+ +
+
+ {t("terminal.hostKey.fingerprintLabel", { keyType: hostKeyInfo.keyType })} +
+ + {hostKeyInfo.fingerprint} + +
+ + {isChanged && hostKeyInfo.knownFingerprint && ( +
+
+ {t("terminal.hostKey.savedFingerprintLabel")} +
+ + {hostKeyInfo.knownFingerprint} + +
+ )} + +
+ + + +
+
+ ); +}; diff --git a/components/port-forwarding/index.ts b/components/port-forwarding/index.ts index 4388b6a6a..e3eaf62d4 100644 --- a/components/port-forwarding/index.ts +++ b/components/port-forwarding/index.ts @@ -17,3 +17,4 @@ export { EditPanel } from './EditPanel'; export { NewFormPanel } from './NewFormPanel'; export { PortForwardHostKeyDialog } from './PortForwardHostKeyDialog'; +export { PortForwardHostKeyTrayPrompt } from './PortForwardHostKeyTrayPrompt'; diff --git a/components/settings/tabs/SettingsTerminalTab.test.ts b/components/settings/tabs/SettingsTerminalTab.test.ts index bcc305209..908ef0954 100644 --- a/components/settings/tabs/SettingsTerminalTab.test.ts +++ b/components/settings/tabs/SettingsTerminalTab.test.ts @@ -8,3 +8,9 @@ test("terminal settings keep the global theme picker visible while following app assert.doesNotMatch(source, /\{followAppTerminalTheme \? \(/); assert.match(source, /terminal\.themeModal\.globalTheme/); }); + +test("terminal settings expose host key verification toggle", () => { + assert.match(source, /settings\.terminal\.connection\.verifyHostKeys/); + assert.match(source, /checked=\{terminalSettings\.verifyHostKeys\}/); + assert.match(source, /updateTerminalSetting\("verifyHostKeys", v\)/); +}); diff --git a/components/settings/tabs/SettingsTerminalTab.tsx b/components/settings/tabs/SettingsTerminalTab.tsx index 74321d135..1f19fd538 100644 --- a/components/settings/tabs/SettingsTerminalTab.tsx +++ b/components/settings/tabs/SettingsTerminalTab.tsx @@ -791,6 +791,15 @@ function SettingsTerminalTab(props: {
+ + updateTerminalSetting("verifyHostKeys", v)} + /> + { knownHosts, resolvedChainHosts: [], sessionId: "session-1", - terminalSettings: {}, + terminalSettings: { + verifyHostKeys: false, + }, terminalBackend, sessionRef: { current: null }, hasConnectedRef: { current: false }, @@ -1665,6 +1669,7 @@ test("startSSH passes known host records to the SSH bridge", async () => { assert.ok(capturedOptions); assert.equal(capturedOptions.knownHosts, knownHosts); + assert.equal(capturedOptions.verifyHostKeys, false); }); test("startSSH omits jump host identity file paths when password auth is selected", async () => { diff --git a/components/terminal/runtime/createTerminalSessionStarters.ts b/components/terminal/runtime/createTerminalSessionStarters.ts index 74eb673dd..932561421 100644 --- a/components/terminal/runtime/createTerminalSessionStarters.ts +++ b/components/terminal/runtime/createTerminalSessionStarters.ts @@ -44,6 +44,13 @@ export const getMissingChainHostIds = ( }; export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContext) => { + const globalTerminalSettings = { + verifyHostKeys: true, + keepaliveInterval: 30, + keepaliveCountMax: 10, + ...(ctx.terminalSettings ?? {}), + }; + const tr = (key: string, fallback: string): string => { const translated = ctx.t?.(key); if (!translated || translated === key) return fallback; @@ -170,7 +177,6 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex ctx.updateStatus("disconnected"); return; } - const globalKeepalive = ctx.terminalSettings ?? { keepaliveInterval: 30, keepaliveCountMax: 10 }; const jumpHosts = ctx.resolvedChainHosts.map((jumpHost, index) => { const jumpAuth = resolveHostAuth({ host: jumpHost, @@ -216,7 +222,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex // Resolve keepalive for THIS hop. Each jump host carries its own // override toggle, so a bastion that is a router (interval=0) can // coexist with a cloud target host (interval=30) in the same chain. - const hopKeepalive = resolveHostKeepalive(jumpHost, globalKeepalive); + const hopKeepalive = resolveHostKeepalive(jumpHost, globalTerminalSettings); return { hostname: jumpHost.hostname, @@ -243,6 +249,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex identityFilePaths: jumpIdentityFilePaths, keepaliveInterval: hopKeepalive.interval, keepaliveCountMax: hopKeepalive.countMax, + verifyHostKeys: globalTerminalSettings.verifyHostKeys, legacyAlgorithms: jumpHost.legacyAlgorithms, skipEcdsaHostKey: jumpHost.skipEcdsaHostKey, algorithmOverrides: jumpHost.algorithms, @@ -381,7 +388,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex // inherits the cloud-friendly global setting. const keepalive = resolveHostKeepalive( ctx.host, - ctx.terminalSettings ?? { keepaliveInterval: 30, keepaliveCountMax: 10 }, + globalTerminalSettings, ); return ctx.terminalBackend.startSSHSession({ sessionId: ctx.sessionId, @@ -412,6 +419,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex jumpHosts: jumpHosts.length > 0 ? jumpHosts : undefined, keepaliveInterval: keepalive.interval, keepaliveCountMax: keepalive.countMax, + verifyHostKeys: globalTerminalSettings.verifyHostKeys, sessionLog: ctx.sessionLog?.enabled ? ctx.sessionLog : undefined, sshDebugLogEnabled: ctx.sshDebugLogEnabled, identityFilePaths: attempt.useIdentityFiles ? targetIdentityFilePaths : undefined, @@ -789,6 +797,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex // Lets the stats companion verify the host key before sending a saved // password (#1198), so it never discloses it to an unvetted host. knownHosts: ctx.knownHosts, + verifyHostKeys: globalTerminalSettings.verifyHostKeys, sudoAutofillPassword: resolveSavedSudoAutofillPassword(), cols: term.cols, rows: term.rows, @@ -1026,6 +1035,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex skipEcdsaHostKey: ctx.host.skipEcdsaHostKey, algorithmOverrides: ctx.host.algorithms, knownHosts: ctx.knownHosts, + verifyHostKeys: globalTerminalSettings.verifyHostKeys, jumpHosts: jumpHosts.length > 0 ? jumpHosts : undefined, agentForwarding: ctx.host.agentForwarding, sudoAutofillPassword: resolveSavedSudoAutofillPassword(), diff --git a/domain/models/terminal.ts b/domain/models/terminal.ts index c1ed3a984..5e563ec16 100644 --- a/domain/models/terminal.ts +++ b/domain/models/terminal.ts @@ -78,6 +78,7 @@ export interface TerminalSettings { localStartDir: string; // Starting directory for local terminal (empty = home directory) // SSH Connection + verifyHostKeys: boolean; // Verify SSH host keys before authenticating keepaliveInterval: number; // Seconds between SSH-level keepalive packets (0 = disabled) keepaliveCountMax: number; // Unanswered keepalives before declaring the connection dead x11Display: string; // Optional local X11 DISPLAY override (empty = use system DISPLAY/default) @@ -333,6 +334,7 @@ const DEFAULT_TERMINAL_SETTINGS: TerminalSettings = { // before declaring the session dead (~5 min). Hosts whose SSH stack doesn't // reply to keepalive@openssh.com (older routers/switches) should set their // own per-host keepaliveOverride and dial these values down. + verifyHostKeys: true, keepaliveInterval: 30, keepaliveCountMax: 10, x11Display: '', // Empty = use DISPLAY/default local X server diff --git a/electron/bridges/hostKeyVerifier.cjs b/electron/bridges/hostKeyVerifier.cjs index fed95e017..36e8c6520 100644 --- a/electron/bridges/hostKeyVerifier.cjs +++ b/electron/bridges/hostKeyVerifier.cjs @@ -207,7 +207,13 @@ const createHostVerifier = ({ hostname, port = 22, knownHosts = [], + verifyHostKeys = true, }) => (rawKey, callback) => { + if (verifyHostKeys === false) { + callback(true); + return; + } + const keyInfo = describeHostKey(rawKey); const decision = classifyHostKey({ knownHosts, diff --git a/electron/bridges/hostKeyVerifier.test.cjs b/electron/bridges/hostKeyVerifier.test.cjs index 88194d3be..f801ab22f 100644 --- a/electron/bridges/hostKeyVerifier.test.cjs +++ b/electron/bridges/hostKeyVerifier.test.cjs @@ -272,6 +272,29 @@ test("createHostVerifier accepts trusted host keys without prompting", async () assert.deepEqual(sent, []); }); +test("createHostVerifier skips prompts when host key verification is disabled", async () => { + const rawKey = Buffer.from("untrusted server key"); + const sent = []; + const sender = { + id: 1, + isDestroyed: () => false, + send: (channel, payload) => sent.push({ channel, payload }), + }; + const verifier = createHostVerifier({ + sender, + sessionId: "session-1", + hostname: "switch.local", + port: 22, + knownHosts: [], + verifyHostKeys: false, + }); + + const accepted = await new Promise((resolve) => verifier(rawKey, resolve)); + + assert.equal(accepted, true); + assert.deepEqual(sent, []); +}); + test("createHostVerifier accepts imported full known_hosts public keys without prompting", async () => { const rawKey = makeRawPublicKey("ssh-ed25519"); const sent = []; diff --git a/electron/bridges/portForwardingBridge.cjs b/electron/bridges/portForwardingBridge.cjs index bc16fef7a..a225b0021 100644 --- a/electron/bridges/portForwardingBridge.cjs +++ b/electron/bridges/portForwardingBridge.cjs @@ -8,6 +8,7 @@ const { Client: SSHClient } = require("ssh2"); const { NetcattyAgent } = require("./netcattyAgent.cjs"); const keyboardInteractiveHandler = require("./keyboardInteractiveHandler.cjs"); const { connectThroughChain, buildAlgorithms } = require("./sshBridge.cjs"); +const hostKeyVerifier = require("./hostKeyVerifier.cjs"); const { createProxySocket } = require("./proxyUtils.cjs"); const { buildAuthHandler, @@ -79,6 +80,7 @@ async function startPortForward(event, payload) { keyId, passphrase, knownHosts, + verifyHostKeys, proxy, jumpHosts = [], identityFilePaths, @@ -139,6 +141,14 @@ async function startPortForward(event, payload) { tryKeyboard: true, algorithms: buildAlgorithms(legacyAlgorithms, { skipEcdsaHostKey, algorithmOverrides }), }; + connectOpts.hostVerifier = hostKeyVerifier.createHostVerifier({ + sender, + sessionId: tunnelId, + hostname, + port, + knownHosts, + verifyHostKeys, + }); const hasCertificate = typeof certificate === "string" && certificate.trim().length > 0; sendStatus('connecting'); @@ -235,6 +245,7 @@ async function startPortForward(event, payload) { passphrase, proxy, knownHosts, + verifyHostKeys, jumpHosts, legacyAlgorithms, skipEcdsaHostKey, diff --git a/electron/bridges/sftpBridge/openConnection.cjs b/electron/bridges/sftpBridge/openConnection.cjs index 4ae8e9436..b28b86e95 100644 --- a/electron/bridges/sftpBridge/openConnection.cjs +++ b/electron/bridges/sftpBridge/openConnection.cjs @@ -87,6 +87,7 @@ function createOpenConnectionApi(ctx) { hostname: jump.hostname, port: jump.port || 22, knownHosts: options.knownHosts, + verifyHostKeys: jump.verifyHostKeys ?? options.verifyHostKeys, }); // Auth - support agent (certificate), key, and password fallback @@ -654,6 +655,7 @@ function createOpenConnectionApi(ctx) { hostname: options.hostname, port: options.port || 22, knownHosts: options.knownHosts, + verifyHostKeys: options.verifyHostKeys, }); // Use the tunneled socket if we have one diff --git a/electron/bridges/sshBridge.cjs b/electron/bridges/sshBridge.cjs index 6f79a8ce7..10e18d385 100644 --- a/electron/bridges/sshBridge.cjs +++ b/electron/bridges/sshBridge.cjs @@ -556,6 +556,7 @@ async function connectThroughChain(event, options, jumpHosts, targetHost, target hostname: jump.hostname, port: jump.port || 22, knownHosts: options.knownHosts, + verifyHostKeys: jump.verifyHostKeys ?? options.verifyHostKeys, }); attachSshDebugLogger(connOpts, sshDiagnosticLogger); logSshAlgorithms("Jump host", connOpts.algorithms, { diff --git a/electron/bridges/sshBridge/moshStatsConnection.cjs b/electron/bridges/sshBridge/moshStatsConnection.cjs index 8ac898ea4..5f2f57594 100644 --- a/electron/bridges/sshBridge/moshStatsConnection.cjs +++ b/electron/bridges/sshBridge/moshStatsConnection.cjs @@ -116,8 +116,14 @@ function createMoshStatsConnectionApi(ctx) { // keys. `trust.trusted` additionally gates the password method in the // authHandler (defense in depth); `trust.rejected` lets the caller treat an // untrusted host as a permanent failure so it stops reconnecting every poll. - function createTrustEnforcingHostVerifier({ hostname, port, knownHosts, trust, label }) { + function createTrustEnforcingHostVerifier({ hostname, port, knownHosts, verifyHostKeys = true, trust, label }) { return (rawKey, callback) => { + if (verifyHostKeys === false) { + trust.trusted = true; + callback(true); + return; + } + try { const keyInfo = hostKeyVerifier.describeHostKey(rawKey); const decision = hostKeyVerifier.classifyHostKey({ @@ -267,6 +273,7 @@ function createMoshStatsConnectionApi(ctx) { hostname: connectOpts.host, port: connectOpts.port, knownHosts: auth.knownHosts, + verifyHostKeys: auth.verifyHostKeys, trust, label, }); diff --git a/electron/bridges/sshBridge/startSession.cjs b/electron/bridges/sshBridge/startSession.cjs index fc334e68f..24cd507fe 100644 --- a/electron/bridges/sshBridge/startSession.cjs +++ b/electron/bridges/sshBridge/startSession.cjs @@ -504,6 +504,7 @@ function createStartSessionApi(ctx) { hostname: options.hostname, port: options.port || 22, knownHosts: options.knownHosts, + verifyHostKeys: options.verifyHostKeys, }); // Authentication for final target diff --git a/electron/bridges/terminalBridge/etSession.cjs b/electron/bridges/terminalBridge/etSession.cjs index 567aeb7c4..155edeeef 100644 --- a/electron/bridges/terminalBridge/etSession.cjs +++ b/electron/bridges/terminalBridge/etSession.cjs @@ -793,6 +793,7 @@ main(); skipEcdsaHostKey: options.skipEcdsaHostKey, algorithmOverrides: options.algorithmOverrides, knownHosts: options.knownHosts, + verifyHostKeys: options.verifyHostKeys, hasJumpHost: Array.isArray(options.jumpHosts) && options.jumpHosts.length > 0, }, systemManagerSudoPassword: typeof options.sudoAutofillPassword === "string" && options.sudoAutofillPassword.length > 0 diff --git a/electron/bridges/terminalBridge/moshSession.cjs b/electron/bridges/terminalBridge/moshSession.cjs index a1017f3a8..213319264 100644 --- a/electron/bridges/terminalBridge/moshSession.cjs +++ b/electron/bridges/terminalBridge/moshSession.cjs @@ -576,6 +576,7 @@ function createMoshSessionApi(ctx) { // password (see moshStatsConnection.cjs). Public-key / agent auth // does not depend on this. knownHosts: options.knownHosts, + verifyHostKeys: options.verifyHostKeys, }; session.systemManagerSudoPassword = typeof options.sudoAutofillPassword === "string" && options.sudoAutofillPassword.length > 0 ? options.sudoAutofillPassword diff --git a/global.d.ts b/global.d.ts index 2122fb37d..5c31a6067 100644 --- a/global.d.ts +++ b/global.d.ts @@ -59,6 +59,7 @@ declare global { // override / global fallback). interval in seconds, 0 = disabled. keepaliveInterval?: number; keepaliveCountMax?: number; + verifyHostKeys?: boolean; // Per-hop algorithm settings, mirroring the target-host fields. When // omitted the bridge falls back to the target host's settings so a // single setting on the leaf still covers the chain (matches the @@ -101,6 +102,7 @@ declare global { startupCommand?: string; passphrase?: string; knownHosts?: import("./domain/models").KnownHost[]; + verifyHostKeys?: boolean; // Environment variables to set in the remote shell env?: Record; // Proxy configuration @@ -170,6 +172,7 @@ declare global { keyId?: string; passphrase?: string; knownHosts?: import("./domain/models").KnownHost[]; + verifyHostKeys?: boolean; proxy?: NetcattyProxyConfig; jumpHosts?: NetcattyJumpHost[]; identityFilePaths?: string[]; diff --git a/infrastructure/services/portForwardingService.ts b/infrastructure/services/portForwardingService.ts index c563e3269..0a9af27ab 100644 --- a/infrastructure/services/portForwardingService.ts +++ b/infrastructure/services/portForwardingService.ts @@ -12,7 +12,11 @@ import { hasUsableProxyConfig } from '../../domain/proxyProfiles'; // Fallback matching DEFAULT_TERMINAL_SETTINGS so older call sites that don't // thread terminalSettings still get the cloud-friendly defaults. -const FALLBACK_KEEPALIVE = { keepaliveInterval: 30, keepaliveCountMax: 10 }; +const FALLBACK_TERMINAL_SETTINGS = { + verifyHostKeys: true, + keepaliveInterval: 30, + keepaliveCountMax: 10, +}; import { logger } from '../../lib/logger'; import { localStorageAdapter } from '../persistence/localStorageAdapter'; import { STORAGE_KEY_PF_RECONNECT_CANCEL } from '../config/storageKeys'; @@ -368,10 +372,10 @@ export const startPortForward = async ( identities: Identity[], onStatusChange: (status: PortForwardingRule['status'], error?: string) => void, enableReconnect = false, - terminalSettings?: Pick, + terminalSettings?: Pick, knownHosts?: KnownHost[], ): Promise<{ success: boolean; error?: string }> => { - const globalKeepalive = terminalSettings ?? FALLBACK_KEEPALIVE; + const globalTerminalSettings = { ...FALLBACK_TERMINAL_SETTINGS, ...(terminalSettings ?? {}) }; const bridge = netcattyBridge.get(); // Clear any existing reconnect timer @@ -450,7 +454,7 @@ export const startPortForward = async ( ) { throw new Error(`Saved credentials for jump host "${jumpHost.label || jumpHost.hostname}" cannot be decrypted on this device. Open host settings and re-enter them.`); } - const hopKeepalive = resolveHostKeepalive(jumpHost, globalKeepalive); + const hopKeepalive = resolveHostKeepalive(jumpHost, globalTerminalSettings); return { hostname: jumpHost.hostname, port: jumpHost.port || 22, @@ -476,6 +480,7 @@ export const startPortForward = async ( identityFilePaths: jumpKeyAuth.identityFilePaths, keepaliveInterval: hopKeepalive.interval, keepaliveCountMax: hopKeepalive.countMax, + verifyHostKeys: globalTerminalSettings.verifyHostKeys, legacyAlgorithms: jumpHost.legacyAlgorithms, skipEcdsaHostKey: jumpHost.skipEcdsaHostKey, algorithmOverrides: jumpHost.algorithms, @@ -556,14 +561,15 @@ export const startPortForward = async ( keyId: resolved.keyId, passphrase: keyAuth.passphrase, knownHosts, + verifyHostKeys: globalTerminalSettings.verifyHostKeys, proxy, jumpHosts: jumpHosts && jumpHosts.length > 0 ? jumpHosts : undefined, identityFilePaths: keyAuth.identityFilePaths, legacyAlgorithms: host.legacyAlgorithms, skipEcdsaHostKey: host.skipEcdsaHostKey, algorithmOverrides: host.algorithms, - keepaliveInterval: resolveHostKeepalive(host, globalKeepalive).interval, - keepaliveCountMax: resolveHostKeepalive(host, globalKeepalive).countMax, + keepaliveInterval: resolveHostKeepalive(host, globalTerminalSettings).interval, + keepaliveCountMax: resolveHostKeepalive(host, globalTerminalSettings).countMax, }); if (!result.success) { diff --git a/types/global/netcatty-bridge-session.d.ts b/types/global/netcatty-bridge-session.d.ts index 316295744..9dab80b9b 100644 --- a/types/global/netcatty-bridge-session.d.ts +++ b/types/global/netcatty-bridge-session.d.ts @@ -39,6 +39,7 @@ declare global { // Known hosts, used to verify the host key before the stats companion // connection (issue #1198) sends a saved password. knownHosts?: import("../../domain/models").KnownHost[]; + verifyHostKeys?: boolean; cols?: number; rows?: number; charset?: string; @@ -62,6 +63,7 @@ declare global { skipEcdsaHostKey?: boolean; algorithmOverrides?: import("../../domain/models").HostAlgorithmOverrides; knownHosts?: import("../../domain/models").KnownHost[]; + verifyHostKeys?: boolean; jumpHosts?: NetcattyJumpHost[]; agentForwarding?: boolean; sudoAutofillPassword?: string; From 8dc4dbf009dfc6a59934854bc7bc77eb4a1d2701 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Thu, 25 Jun 2026 16:36:02 +0800 Subject: [PATCH 053/228] Simplify tray host key prompt styling --- components/TrayPanel.tsx | 4 +- .../PortForwardHostKeyDialog.test.ts | 3 ++ .../PortForwardHostKeyTrayPrompt.tsx | 40 ++++++------------- 3 files changed, 18 insertions(+), 29 deletions(-) diff --git a/components/TrayPanel.tsx b/components/TrayPanel.tsx index a0735efa7..0f31864c8 100644 --- a/components/TrayPanel.tsx +++ b/components/TrayPanel.tsx @@ -260,9 +260,9 @@ const TrayPanelContent: React.FC = ({ terminalSettings })
-
- + +
{jumpableSessions.length > 0 && (() => { // Group sessions by workspace const workspaceGroups = new Map(); diff --git a/components/port-forwarding/PortForwardHostKeyDialog.test.ts b/components/port-forwarding/PortForwardHostKeyDialog.test.ts index 1d8e94003..d71fc3b3c 100644 --- a/components/port-forwarding/PortForwardHostKeyDialog.test.ts +++ b/components/port-forwarding/PortForwardHostKeyDialog.test.ts @@ -28,6 +28,9 @@ test("port-forward host-key dialog is marked so tray outside-click handling igno test("tray uses the lightweight host-key prompt instead of the main dialog", () => { assert.match(trayPromptSource, /data-port-forward-host-key-tray-prompt="true"/); + assert.match(trayPromptSource, /border-b px-3 py-2/); + assert.doesNotMatch(trayPromptSource, /rounded-md border p-2\.5 shadow-sm/); + assert.doesNotMatch(trayPromptSource, /lucide-react/); assert.match(trayPromptSource, /grid-cols-\[auto_auto_1fr\]/); assert.match(trayPanelSource, //); assert.doesNotMatch(trayPanelSource, / -
-
- -
+
{isChanged @@ -65,21 +53,19 @@ export const PortForwardHostKeyTrayPrompt: React.FC
-
-
- {t("terminal.hostKey.fingerprintLabel", { keyType: hostKeyInfo.keyType })} -
- +
+ {t("terminal.hostKey.fingerprintLabel", { keyType: hostKeyInfo.keyType })} + {hostKeyInfo.fingerprint}
{isChanged && hostKeyInfo.knownFingerprint && ( -
-
+
+ {t("terminal.hostKey.savedFingerprintLabel")} -
- + + {hostKeyInfo.knownFingerprint}
From 57da0ad4de4f3d1608f6cb3e2e5c584bd1291fc6 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Thu, 25 Jun 2026 16:39:33 +0800 Subject: [PATCH 054/228] Remove tray host key prompt divider --- components/port-forwarding/PortForwardHostKeyDialog.test.ts | 3 ++- components/port-forwarding/PortForwardHostKeyTrayPrompt.tsx | 6 ++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/components/port-forwarding/PortForwardHostKeyDialog.test.ts b/components/port-forwarding/PortForwardHostKeyDialog.test.ts index d71fc3b3c..7a6951ff0 100644 --- a/components/port-forwarding/PortForwardHostKeyDialog.test.ts +++ b/components/port-forwarding/PortForwardHostKeyDialog.test.ts @@ -28,7 +28,8 @@ test("port-forward host-key dialog is marked so tray outside-click handling igno test("tray uses the lightweight host-key prompt instead of the main dialog", () => { assert.match(trayPromptSource, /data-port-forward-host-key-tray-prompt="true"/); - assert.match(trayPromptSource, /border-b px-3 py-2/); + assert.match(trayPromptSource, /px-3 py-2/); + assert.doesNotMatch(trayPromptSource, /border-b/); assert.doesNotMatch(trayPromptSource, /rounded-md border p-2\.5 shadow-sm/); assert.doesNotMatch(trayPromptSource, /lucide-react/); assert.match(trayPromptSource, /grid-cols-\[auto_auto_1fr\]/); diff --git a/components/port-forwarding/PortForwardHostKeyTrayPrompt.tsx b/components/port-forwarding/PortForwardHostKeyTrayPrompt.tsx index 3b250ed09..58a98116b 100644 --- a/components/port-forwarding/PortForwardHostKeyTrayPrompt.tsx +++ b/components/port-forwarding/PortForwardHostKeyTrayPrompt.tsx @@ -29,10 +29,8 @@ export const PortForwardHostKeyTrayPrompt: React.FC
From 659c193769d8eb868e0783c541f6131e70086c23 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Thu, 25 Jun 2026 16:46:52 +0800 Subject: [PATCH 055/228] Tighten tray host key prompt buttons --- .../port-forwarding/PortForwardHostKeyDialog.test.ts | 3 ++- .../port-forwarding/PortForwardHostKeyTrayPrompt.tsx | 8 ++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/components/port-forwarding/PortForwardHostKeyDialog.test.ts b/components/port-forwarding/PortForwardHostKeyDialog.test.ts index 7a6951ff0..e17c858e2 100644 --- a/components/port-forwarding/PortForwardHostKeyDialog.test.ts +++ b/components/port-forwarding/PortForwardHostKeyDialog.test.ts @@ -29,10 +29,11 @@ test("port-forward host-key dialog is marked so tray outside-click handling igno test("tray uses the lightweight host-key prompt instead of the main dialog", () => { assert.match(trayPromptSource, /data-port-forward-host-key-tray-prompt="true"/); assert.match(trayPromptSource, /px-3 py-2/); + assert.match(trayPromptSource, /grid-cols-\[auto_auto_1fr\] gap-1/); + assert.match(trayPromptSource, /h-6 px-1\.5 text-\[10px\]/); assert.doesNotMatch(trayPromptSource, /border-b/); assert.doesNotMatch(trayPromptSource, /rounded-md border p-2\.5 shadow-sm/); assert.doesNotMatch(trayPromptSource, /lucide-react/); - assert.match(trayPromptSource, /grid-cols-\[auto_auto_1fr\]/); assert.match(trayPanelSource, //); assert.doesNotMatch(trayPanelSource, / )} -
+
+
diff --git a/components/ai/ChatInput.tsx b/components/ai/ChatInput.tsx index 5c479dea0..cc6a9e943 100644 --- a/components/ai/ChatInput.tsx +++ b/components/ai/ChatInput.tsx @@ -7,7 +7,7 @@ */ import { AtSign, Check, ChevronDown, ChevronRight, Cpu, Expand, Eye, FileText, ImageIcon, MessageSquare, Package, Plus, ShieldCheck, SquareTerminal, X, Zap } from 'lucide-react'; -import { filterQuickMessages, buildSlashCommandItems, filterUserSkillsForSlash, getSlashCommandItemKey, type AIQuickMessage, type SlashCommandItem, type UserSkillSlashOption } from '../../infrastructure/ai/quickMessages'; +import { filterQuickMessages, buildSlashCommandItems, filterUserSkillsForSlash, getSlashCommandItemKey, isSystemStopSlashCommand, type AIQuickMessage, type SlashCommandItem, type UserSkillSlashOption } from '../../infrastructure/ai/quickMessages'; import { SlashCommandPicker } from './SlashCommandPicker'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useI18n } from '../../application/i18n/I18nProvider'; @@ -460,9 +460,14 @@ const ChatInput: React.FC = ({ const handleSubmit = useCallback( (_text: string, _event: FormEvent) => { + if (isSystemStopSlashCommand(value)) { + onStop?.(); + onChange(''); + return; + } onSend(); }, - [onSend], + [onSend, onStop, onChange, value], ); const status: PromptInputStatus = isStreaming ? 'streaming' : 'idle'; diff --git a/components/ai/ChatMessageList.tsx b/components/ai/ChatMessageList.tsx index c952ae7d5..75a009fc4 100644 --- a/components/ai/ChatMessageList.tsx +++ b/components/ai/ChatMessageList.tsx @@ -20,6 +20,12 @@ import { Message, MessageContent, MessageResponse } from '../ai-elements/message import { ToolCall } from '../ai-elements/tool-call'; import ThinkingBlock from './ThinkingBlock'; import ToolCallGroup from './ToolCallGroup'; +import { + VaultArtifactNavigationProvider, +} from './toolArtifacts/VaultArtifactNavigationContext'; +import { parseVaultToolArtifact } from './toolArtifacts/vaultToolArtifact'; +import { VaultArtifactToolResult } from './toolArtifacts/VaultArtifactToolResult'; +import type { Host, VaultNote } from '../../types'; import { onApprovalRequest, onApprovalCleared, @@ -27,6 +33,10 @@ import { resolveApproval, type ApprovalRequest, } from '../../infrastructure/ai/shared/approvalGate'; +import { + buildGrantsFromApproval, + resolveCapabilityId, +} from '../../infrastructure/ai/harness/permissionGrants'; import { getAIPanelDiagnosticHiddenParts, getAIPanelProfilerProps, @@ -38,12 +48,26 @@ interface ChatMessageListProps { isStreaming?: boolean; /** Active chat session ID — used to filter standalone MCP approval blocks */ activeSessionId?: string | null; + notes?: VaultNote[]; + hosts?: Host[]; + onOpenVaultNote?: (noteId: string) => void; + onOpenVaultHost?: (hostId: string) => void; + onOpenVaultSection?: (section: 'notes' | 'hosts') => void; } const MESSAGE_RENDER_BATCH = 50; const MESSAGE_RENDER_STEP = 50; -const ChatMessageList: React.FC = ({ messages, isStreaming, activeSessionId }) => { +const ChatMessageList: React.FC = ({ + messages, + isStreaming, + activeSessionId, + notes = [], + hosts = [], + onOpenVaultNote, + onOpenVaultHost, + onOpenVaultSection, +}) => { // Track pending approvals from the approval gate const [pendingApprovals, setPendingApprovals] = useState>(new Map()); const [resolvedApprovals, setResolvedApprovals] = useState>(new Map()); @@ -70,12 +94,20 @@ const ChatMessageList: React.FC = ({ messages, isStreaming }); }, []); - const handleApprove = useCallback((toolCallId: string) => { + const handleApproveOnce = useCallback((toolCallId: string) => { resolveApproval(toolCallId, true); setPendingApprovals(prev => { const m = new Map(prev); m.delete(toolCallId); return m; }); setResolvedApprovals(prev => new Map(prev).set(toolCallId, true)); }, []); + const handleAlwaysAllow = useCallback((toolCallId: string, request: ApprovalRequest) => { + const capabilityId = request.capabilityId ?? resolveCapabilityId(request.toolName); + const persistGrants = buildGrantsFromApproval(capabilityId, request.args, request.chatSessionId); + resolveApproval(toolCallId, { approved: true, persistGrants }); + setPendingApprovals(prev => { const m = new Map(prev); m.delete(toolCallId); return m; }); + setResolvedApprovals(prev => new Map(prev).set(toolCallId, true)); + }, []); + const handleReject = useCallback((toolCallId: string) => { resolveApproval(toolCallId, false); setPendingApprovals(prev => { const m = new Map(prev); m.delete(toolCallId); return m; }); @@ -196,7 +228,7 @@ const ChatMessageList: React.FC = ({ messages, isStreaming const lastAssistantMessage = displayedMessages.findLast(m => m.role === 'assistant'); - return ( + const conversation = ( <> @@ -220,34 +252,64 @@ const ChatMessageList: React.FC = ({ messages, isStreaming let end = idx + 1; while (end < displayedMessages.length && displayedMessages[end].role === "tool") end++; const group = displayedMessages.slice(idx, end); - const groupTotal = group.reduce( - (sum, m) => sum + (m.toolResults?.length ?? 0), 0, + const toolResults = group.flatMap((toolMsg) => + (toolMsg.toolResults ?? []).map((tr) => ({ + toolCallId: tr.toolCallId, + name: toolCallNames.get(tr.toolCallId) || tr.toolCallId, + args: toolCallArgs.get(tr.toolCallId), + content: tr.content, + isError: tr.isError, + })), ); + const groupTotal = toolResults.length; // Expanded while the agent is still working (no assistant response follows) const hasAssistantAfter = end < displayedMessages.length && displayedMessages[end].role === "assistant"; + const renderToolResultItem = (item: typeof toolResults[number]) => { + const artifact = parseVaultToolArtifact(item.name, item.content); + if (artifact) { + return ( + + ); + } + return ( + +
+ +
+
+ ); + }; + + if (groupTotal === 1) { + return ( +
+ {renderToolResultItem(toolResults[0])} +
+ ); + } + return ( - {group.map((toolMsg) => - toolMsg.toolResults?.map((tr) => ( - -
- -
-
- )), - )} + {toolResults.map(renderToolResultItem)}
); } @@ -343,7 +405,13 @@ const ChatMessageList: React.FC = ({ messages, isStreaming args={tc.arguments} isInterrupted={!isPending} approvalStatus={approvalStatus} - onApprove={() => handleApprove(tc.id)} + onApproveOnce={() => handleApproveOnce(tc.id)} + onAlwaysAllow={() => handleAlwaysAllow(tc.id, pendingApprovals.get(tc.id) ?? { + toolCallId: tc.id, + toolName: tc.name, + args: tc.arguments ?? {}, + chatSessionId: activeSessionId ?? undefined, + })} onReject={() => handleReject(tc.id)} />
@@ -408,7 +476,13 @@ const ChatMessageList: React.FC = ({ messages, isStreaming args={tc.arguments} isLoading={isToolRunning && !isPending} approvalStatus={approvalStatus} - onApprove={() => handleApprove(tc.id)} + onApproveOnce={() => handleApproveOnce(tc.id)} + onAlwaysAllow={() => handleAlwaysAllow(tc.id, pendingApprovals.get(tc.id) ?? { + toolCallId: tc.id, + toolName: tc.name, + args: tc.arguments ?? {}, + chatSessionId: activeSessionId ?? undefined, + })} onReject={() => handleReject(tc.id)} />
@@ -431,7 +505,8 @@ const ChatMessageList: React.FC = ({ messages, isStreaming isLoading={false} isInterrupted={false} approvalStatus={'pending'} - onApprove={() => handleApprove(id)} + onApproveOnce={() => handleApproveOnce(id)} + onAlwaysAllow={() => handleAlwaysAllow(id, req)} onReject={() => handleReject(id)} />
@@ -527,11 +602,32 @@ const ChatMessageList: React.FC = ({ messages, isStreaming ); + + if (onOpenVaultNote && onOpenVaultHost && onOpenVaultSection) { + return ( + + {conversation} + + ); + } + + return conversation; }; function areMessagesEqual(prev: ChatMessageListProps, next: ChatMessageListProps): boolean { if (prev.isStreaming !== next.isStreaming) return false; if (prev.activeSessionId !== next.activeSessionId) return false; + if (prev.notes !== next.notes) return false; + if (prev.hosts !== next.hosts) return false; + if (prev.onOpenVaultNote !== next.onOpenVaultNote) return false; + if (prev.onOpenVaultHost !== next.onOpenVaultHost) return false; + if (prev.onOpenVaultSection !== next.onOpenVaultSection) return false; if (prev.messages.length !== next.messages.length) return false; if (prev.messages === next.messages) return true; diff --git a/components/ai/externalAgentHistory.ts b/components/ai/externalAgentHistory.ts index e322421ec..d750c185a 100644 --- a/components/ai/externalAgentHistory.ts +++ b/components/ai/externalAgentHistory.ts @@ -1,454 +1,18 @@ -import type { ChatMessage } from "../../infrastructure/ai/types.ts"; -import { buildHistoricalToolResultReplayText, buildHistoricalUserReplayContent } from "./cattyHistoryReplay.ts"; +import type { ChatMessage } from '../../infrastructure/ai/types'; +import { + buildExternalBridgeContextMessages, +} from '../../infrastructure/ai/harness/externalBridgeContext'; -type ExternalAgentHistoryMessage = { role: "user" | "assistant"; content: string }; -type RawHistoryMessage = ExternalAgentHistoryMessage & { sourceId: string }; -type DurableUserLine = { - line: string; - messageIndex: number; - priority: number; -}; - -const MAX_RECENT_RAW_MESSAGES = 6; -const MAX_MESSAGES_TO_SCAN = 20; -// Bound the scan by user turns, not raw message count: a tool-heavy external agent -// chat can produce 5+ messages per logical turn (user + assistant + -// several tool_results + follow-up assistant), so a plain -// message-count cap ages out early constraints much sooner than intended. -const MAX_DURABLE_SCAN_TURNS = 100; -const MAX_COMPACT_CONTEXT_CHARS = 3000; -const MAX_RAW_MESSAGE_CHARS = 2000; -const MAX_TOOL_SUMMARY_CHARS = 500; -const MAX_DURABLE_USER_CONTEXT_CHARS = 1400; -const MAX_DURABLE_ASSISTANT_CONTEXT_CHARS = 900; -const MAX_RECENT_SUMMARY_CONTEXT_CHARS = 1200; -const MAX_DURABLE_USER_MESSAGE_CHARS = 280; -const MAX_DURABLE_ASSISTANT_MESSAGE_CHARS = 360; -const MAX_TOOL_CALL_LABEL_CHARS = 200; - -type ToolCallInfo = { name: string; arguments: unknown }; - -const IMPORTANT_PATTERNS = [ - /不要|别|不能|不允许|必须|希望|只|最小|先|暂时|fallback|pwsh|powershell|cmd\.exe|windows|mcp|skills|cli|commit|\bpr\b|打包|内存|历史|压缩|慢/i, - /error|failed|failure|exit code|exception|cannot|unable|timeout|crash|fallback|commit|pull request|PR #\d+/i, -]; -const DURABLE_CONSTRAINT_PATTERNS = [ - /\bdo not\b|\bdon't\b|\bkeep\b|\bpreserve\b|\bavoid\b|\bonly\b|\bunchanged\b|\blocal only\b|\bwithout\b|\bleave\b/i, - /不要|别|保留|保持|维持|不改|别改|不要改|仅限本地/i, -]; -const TRIVIAL_USER_MESSAGE_PATTERNS = [ - /^(ok|okay|yes|no|thanks|thank you|continue|继续|好的|收到|行|嗯|好|继续处理|继续吧|开始吧)[.!? ]*$/i, -]; -const TRIVIAL_ASSISTANT_MESSAGE_PATTERNS = [ - /^(ok|okay|understood|got it|working|proceeding|ready|ack(?: \d+)?|收到|明白|继续处理|准备实现|开始处理|处理中)[.!? ]*$/i, -]; - -function truncateText(value: string, maxChars: number): string { - if (value.length <= maxChars) return value; - return `${value.slice(0, Math.max(0, maxChars - 24)).trimEnd()}\n[truncated]`; -} - -function normalizeWhitespace(value: string): string { - return value.replace(/\s+/g, " ").trim(); -} - -function isImportantText(value: string): boolean { - return IMPORTANT_PATTERNS.some((pattern) => pattern.test(value)); -} - -function isDurableConstraintText(value: string): boolean { - return DURABLE_CONSTRAINT_PATTERNS.some((pattern) => pattern.test(value)); -} - -function getUserHistoryContent(message: ChatMessage): string { - if (message.role !== "user") return message.content || ""; - return buildHistoricalUserReplayContent( - message.content || "", - message.attachments ?? [], - ); -} - -function isTrivialUserMessage(value: string): boolean { - const normalized = normalizeWhitespace(value); - if (isImportantText(normalized) || isDurableConstraintText(normalized)) return false; - // Don't blanket-drop short messages — short user turns are often - // load-bearing constraints ("Use ssh2", "中文输出", "no logs", "more - // verbose") that the IMPORTANT/DURABLE regexes can't realistically - // enumerate. The trivial-phrase regex already catches actual filler - // ("ok", "yes", "thanks", "继续"). - return TRIVIAL_USER_MESSAGE_PATTERNS.some((pattern) => pattern.test(normalized)); -} - -function getDurableUserPriority(value: string): number { - const normalized = normalizeWhitespace(value); - if (isImportantText(normalized) || isDurableConstraintText(normalized)) return 2; - return 1; -} - -function isSubstantiveAssistantMessage(value: string): boolean { - const normalized = normalizeWhitespace(value); - if (!normalized) return false; - // Mirror the user-side loosening: don't blanket-drop short assistant - // messages just because they're under 40 chars or don't match the small - // English keyword list. Short but load-bearing decisions ("Use ssh2", - // "rebase instead", "中文输出") aren't realistically enumerable and - // they're the exact things a later "do what you suggested" references. - // TRIVIAL_ASSISTANT_MESSAGE_PATTERNS still catches the actual filler - // ("ok", "ack", "got it", "明白"). - return !TRIVIAL_ASSISTANT_MESSAGE_PATTERNS.some((pattern) => pattern.test(normalized)); -} - -function getDurableAssistantPriority(value: string): number { - const normalized = normalizeWhitespace(value); - if (isImportantText(normalized)) return 2; - return 1; -} - -function appendUniqueLine( - target: string[], - seen: Set, - line: string, - maxSectionChars: number, - sectionCharsRef: { value: number }, -): void { - const normalized = normalizeWhitespace(line); - if (!normalized || seen.has(normalized)) return; - const nextChars = sectionCharsRef.value + normalized.length; - if (nextChars > maxSectionChars) return; - seen.add(normalized); - target.push(normalized); - sectionCharsRef.value = nextChars; -} - -function summarizeToolMessage( - message: ChatMessage, - toolCallIndex: Map, -): string[] { - if (!message.toolResults?.length) return []; - return message.toolResults.map((result) => { - const prefix = result.isError ? "Tool error" : "Tool result"; - // Same provenance problem as the raw-window path: once a tool result - // lands in the compact section (older than the 6-item raw window), - // its paired assistant tool_call is almost always gone. Without the - // call label, multiple older results collapse into indistinguishable - // "Tool result (callN): ..." lines and follow-ups like "use the - // resolv.conf output" can't be resolved. Inline the name+args here - // the same way toRawHistoryMessage does. - const callInfo = lookupToolCallInfo(toolCallIndex, message.id, result.toolCallId); - const callLabel = callInfo - ? ` [from ${callInfo.name}(${truncateText(JSON.stringify(callInfo.arguments ?? {}), MAX_TOOL_CALL_LABEL_CHARS)})]` - : ""; - const replayContent = buildHistoricalToolResultReplayText(result, callInfo - ? { id: result.toolCallId, name: callInfo.name, arguments: callInfo.arguments as Record } - : undefined); - return `${prefix}${callLabel} (${result.toolCallId}): ${truncateText(normalizeWhitespace(replayContent), MAX_TOOL_SUMMARY_CHARS)}`; - }); -} - -function summarizeMessage( - message: ChatMessage, - toolCallIndex: Map, -): string[] { - if (message.role === "system") return []; - if (message.role === "tool") return summarizeToolMessage(message, toolCallIndex); - - const lines: string[] = []; - const content = getUserHistoryContent(message); - if (content && isImportantText(content)) { - const label = message.role === "user" ? "User" : "Assistant"; - lines.push(`${label}: ${truncateText(normalizeWhitespace(content), MAX_TOOL_SUMMARY_CHARS)}`); - } - - if (message.role === "assistant" && message.toolCalls?.length) { - for (const toolCall of message.toolCalls) { - const args = JSON.stringify(toolCall.arguments ?? {}); - const summary = `Tool call: ${toolCall.name}(${truncateText(args, 220)})`; - if (isImportantText(summary)) lines.push(summary); - } - } - - return lines; -} - -function summarizeDurableUserMessage(message: ChatMessage): string | null { - if (message.role !== "user") return null; - const content = getUserHistoryContent(message); - if (!content) return null; - if (isTrivialUserMessage(content)) return null; - return `User request: ${truncateText(normalizeWhitespace(content), MAX_DURABLE_USER_MESSAGE_CHARS)}`; -} - -function summarizeDurableAssistantMessage(message: ChatMessage): string | null { - if (message.role !== "assistant" || !message.content) return null; - if (!isSubstantiveAssistantMessage(message.content)) return null; - return `Assistant context: ${truncateText(normalizeWhitespace(message.content), MAX_DURABLE_ASSISTANT_MESSAGE_CHARS)}`; -} - -/** - * Build a per-tool-result provenance index. Keys are - * `${toolResultMessageId}:${toolCallId}` rather than the bare toolCall.id - * so that provider-reused ids (e.g. "call1" across unrelated turns) don't - * cause later calls to overwrite older ones in the lookup — each - * tool_result resolves to the most recent assistant tool_call that - * preceded it with matching id, which preserves historical correctness - * when rebuilding older compact summaries. - */ -function buildToolCallIndex(messages: ChatMessage[]): Map { - const provenance = new Map(); - // Rolling map of the latest tool_call seen (by id) up to the current - // point in the message stream. - const latestByCallId = new Map(); - for (const message of messages) { - if (message.role === "assistant" && message.toolCalls?.length) { - for (const toolCall of message.toolCalls) { - if (!toolCall.id) continue; - latestByCallId.set(toolCall.id, { name: toolCall.name, arguments: toolCall.arguments }); - } - continue; - } - if (message.role === "tool" && message.toolResults?.length) { - for (const result of message.toolResults) { - const info = latestByCallId.get(result.toolCallId); - if (info) { - provenance.set(`${message.id}:${result.toolCallId}`, info); - } - } - } - } - return provenance; -} - -function lookupToolCallInfo( - index: Map, - toolMessageId: string, - toolCallId: string, -): ToolCallInfo | undefined { - return index.get(`${toolMessageId}:${toolCallId}`); -} - -function toRawHistoryMessage( - message: ChatMessage, - toolCallIndex: Map, -): RawHistoryMessage[] { - if (message.role === "user") { - const content = getUserHistoryContent(message); - return content - ? [{ sourceId: message.id, role: "user", content: truncateText(content, MAX_RAW_MESSAGE_CHARS) }] - : []; - } - - if (message.role === "assistant") { - const parts: string[] = []; - if (message.content) parts.push(message.content); - if (message.toolCalls?.length) { - parts.push(...message.toolCalls.map((tc) => `Tool call: ${tc.name}(${JSON.stringify(tc.arguments ?? {})})`)); - } - return parts.length - ? [{ sourceId: message.id, role: "assistant", content: truncateText(parts.join("\n\n"), MAX_RAW_MESSAGE_CHARS) }] - : []; - } - - if (message.role === "tool" && message.toolResults?.length) { - // Keep recent tool results self-describing while replacing terminal - // output with placeholders, so stale-session recovery doesn't replay - // bulky command output on every follow-up. External agent replay only - // supports user/assistant roles, so we flatten to "assistant" — the - // tool results were produced during the assistant's turn. - // - // Inline the originating tool_call's name+args. Tool calls and their - // results live in separate messages; if the last six raw items start - // in the middle of a tool interaction, the preceding assistant tool - // call can be outside the window. Without the call label the result - // is opaque bytes and "use that output" becomes ambiguous. - const parts = message.toolResults.map((result) => { - const prefix = result.isError ? "Tool error" : "Tool result"; - const callInfo = lookupToolCallInfo(toolCallIndex, message.id, result.toolCallId); - const callLabel = callInfo - ? ` [from ${callInfo.name}(${truncateText(JSON.stringify(callInfo.arguments ?? {}), MAX_TOOL_CALL_LABEL_CHARS)})]` - : ""; - const replayContent = buildHistoricalToolResultReplayText(result, callInfo - ? { id: result.toolCallId, name: callInfo.name, arguments: callInfo.arguments as Record } - : undefined); - return `${prefix}${callLabel} (${result.toolCallId}): ${replayContent}`; - }); - return [{ - sourceId: message.id, - role: "assistant", - content: truncateText(parts.join("\n\n"), MAX_RAW_MESSAGE_CHARS), - }]; - } - - return []; -} - -function buildCompactContext( - messages: ChatMessage[], - durableScanStart: number, - recentRawSourceIds: Set, - toolCallIndex: Map, -): ExternalAgentHistoryMessage[] { - const scanned = messages.slice(-MAX_MESSAGES_TO_SCAN); - const summaryLines: string[] = []; - const durableUserCandidates: DurableUserLine[] = []; - const selectedDurableUserLines: DurableUserLine[] = []; - const durableAssistantCandidates: DurableUserLine[] = []; - const selectedDurableAssistantLines: DurableUserLine[] = []; - const seen = new Set(); - const durableChars = { value: 0 }; - const durableAssistantChars = { value: 0 }; - const summaryChars = { value: 0 }; - - for (let messageIndex = durableScanStart; messageIndex < messages.length; messageIndex += 1) { - const message = messages[messageIndex]; - if (recentRawSourceIds.has(message.id)) continue; - const durableUserLine = summarizeDurableUserMessage(message); - if (durableUserLine) { - durableUserCandidates.push({ - line: durableUserLine, - messageIndex, - priority: getDurableUserPriority(getUserHistoryContent(message)), - }); - } - const durableAssistantLine = summarizeDurableAssistantMessage(message); - if (durableAssistantLine) { - durableAssistantCandidates.push({ - line: durableAssistantLine, - messageIndex, - priority: getDurableAssistantPriority(message.content || ""), - }); - } - } - - durableUserCandidates - .sort((left, right) => right.priority - left.priority || right.messageIndex - left.messageIndex) - .forEach((candidate) => { - const normalized = normalizeWhitespace(candidate.line); - if (!normalized || seen.has(normalized)) return; - const nextChars = durableChars.value + normalized.length; - if (nextChars > MAX_DURABLE_USER_CONTEXT_CHARS) return; - seen.add(normalized); - selectedDurableUserLines.push(candidate); - durableChars.value = nextChars; - }); - - durableAssistantCandidates - .sort((left, right) => right.priority - left.priority || right.messageIndex - left.messageIndex) - .forEach((candidate) => { - const normalized = normalizeWhitespace(candidate.line); - if (!normalized || seen.has(normalized)) return; - const nextChars = durableAssistantChars.value + normalized.length; - if (nextChars > MAX_DURABLE_ASSISTANT_CONTEXT_CHARS) return; - seen.add(normalized); - selectedDurableAssistantLines.push(candidate); - durableAssistantChars.value = nextChars; - }); - - const durableUserLines = selectedDurableUserLines - .sort((left, right) => left.messageIndex - right.messageIndex) - .map((candidate) => candidate.line); - const durableAssistantLines = selectedDurableAssistantLines - .sort((left, right) => left.messageIndex - right.messageIndex) - .map((candidate) => candidate.line); - - for (const line of [...durableUserLines, ...durableAssistantLines]) { - seen.add(normalizeWhitespace(line)); - } - - // Skip messages that are already appended verbatim in the raw window — - // otherwise the same last-6 turns get summarized here AND re-sent as - // raw, doubling the budget cost of important user turns / large tool - // output and crowding out older durable context the replay is meant - // to preserve. Matches the recentRawSourceIds skip in the durable pass. - for (const message of scanned) { - if (recentRawSourceIds.has(message.id)) continue; - for (const line of summarizeMessage(message, toolCallIndex)) { - appendUniqueLine(summaryLines, seen, line, MAX_RECENT_SUMMARY_CONTEXT_CHARS, summaryChars); - } - } - - if (!durableUserLines.length && !durableAssistantLines.length && !summaryLines.length) return []; - - const contentLines = [ - "[Compact prior Netcatty UI context]", - "The external SDK agent may already have its own persisted session context. Use this compact Netcatty UI context only as fallback/background, and prefer the current user request when there is any conflict.", - ]; - if (durableUserLines.length) { - contentLines.push("Earlier user requests that may still apply:"); - contentLines.push(...durableUserLines.map((line) => `- ${line}`)); - } - if (durableAssistantLines.length) { - contentLines.push("Earlier assistant context that may still matter:"); - contentLines.push(...durableAssistantLines.map((line) => `- ${line}`)); - } - if (summaryLines.length) { - contentLines.push("Recent noteworthy context:"); - contentLines.push(...summaryLines.map((line) => `- ${line}`)); - } - - return [{ - role: "user", - content: truncateText( - contentLines.join("\n"), - MAX_COMPACT_CONTEXT_CHARS, - ), - }]; -} - -/** - * Find the index of the first message to include in the scan window, - * bounded by MAX_DURABLE_SCAN_TURNS user turns (not raw message count). - * Walking backwards stops at the target turn count, so the cost is - * bounded even when the transcript is huge. - */ -function computeDurableScanStart(messages: ChatMessage[]): number { - let userTurns = 0; - for (let i = messages.length - 1; i >= 0; i -= 1) { - if (messages[i].role === "user") { - userTurns += 1; - if (userTurns >= MAX_DURABLE_SCAN_TURNS) return i; - } - } - return 0; -} +export type ExternalAgentHistoryMessage = { role: 'user' | 'assistant'; content: string }; export function buildExternalAgentHistoryMessages(messages: ChatMessage[]): ExternalAgentHistoryMessage[] { - // Compute the scan start once, then do all subsequent work over the - // already-sliced tail. This avoids O(N) walks over the whole transcript - // on every send — previously buildToolCallIndex + the flatMap-to-take- - // last-6 raw history both traversed every message in the chat. - const durableScanStart = computeDurableScanStart(messages); - const scannedTail = messages.slice(durableScanStart); - - // The tool-call provenance index only needs entries for tool_results - // that might appear in our output. Building from the scanned tail is - // correct for any tool_result whose paired assistant tool_call is - // also within the window, which covers >99% of realistic patterns - // (tool_calls and tool_results are always adjacent or near-adjacent). - // If an ancient tool_call's result stays within the window while the - // call itself is outside, that single result loses its [from X(Y)] - // label — an acceptable trade for eliminating the per-send O(N) walk. - const toolCallIndex = buildToolCallIndex(scannedTail); - - const rawHistory = scannedTail - .flatMap((message) => toRawHistoryMessage(message, toolCallIndex)) - .slice(-MAX_RECENT_RAW_MESSAGES); - const compactContext = buildCompactContext( - messages, - durableScanStart, - new Set(rawHistory.map((message) => message.sourceId)), - toolCallIndex, - ); - const recentRaw = rawHistory.map(({ role, content }) => ({ role, content })); - - return [...compactContext, ...recentRaw]; + return buildExternalBridgeContextMessages(messages); } export function buildExternalAgentHistoryMessagesForBridge( messages: ChatMessage[], _existingSessionId?: string | null, ): ExternalAgentHistoryMessage[] | undefined { - // The main process bridge only consumes this payload during stale-session - // fallback replay, so keep it available even when a session id exists. const historyMessages = buildExternalAgentHistoryMessages(messages); return historyMessages.length ? historyMessages : undefined; } diff --git a/components/ai/hooks/aiChatStreamingSupport.ts b/components/ai/hooks/aiChatStreamingSupport.ts index 7f508f63b..575916925 100644 --- a/components/ai/hooks/aiChatStreamingSupport.ts +++ b/components/ai/hooks/aiChatStreamingSupport.ts @@ -102,6 +102,9 @@ export interface PanelBridge extends NetcattyBridge { agentEnv?: Record, agentCommand?: string, ) => Promise<{ ok: boolean; models?: Array<{ id: string; name: string; description?: string; thinkingLevels?: string[] }>; currentModelId?: string | null; error?: string }>; + aiCattyCancelExec?(chatSessionId: string): Promise; + aiSetChatSessionCancelled?(chatSessionId: string, cancelled?: boolean): Promise<{ ok: boolean; error?: string }>; + aiMcpSyncPermissionGrants?(grants: Array>): Promise<{ ok: boolean; count?: number; error?: string }>; aiSdkAgentCancel?: (requestId: string, chatSessionId?: string) => Promise<{ ok: boolean; error?: string }>; aiSdkAgentCleanup?: (chatSessionId: string) => Promise<{ ok: boolean }>; aiUserSkillsGetStatus?: () => Promise<{ @@ -130,6 +133,14 @@ export interface TerminalSessionInfo { shellType?: string; deviceType?: string; connected: boolean; + hostChain?: Array<{ hostId: string; label?: string; hostname?: string }>; + activePortForwards?: Array<{ + ruleId: string; + label?: string; + type?: string; + localPort?: number; + status?: string; + }>; } export interface DefaultTargetSessionHint extends TerminalSessionInfo { diff --git a/components/ai/hooks/useAIChatStreaming.ts b/components/ai/hooks/useAIChatStreaming.ts index 8788cddba..ab7afea57 100644 --- a/components/ai/hooks/useAIChatStreaming.ts +++ b/components/ai/hooks/useAIChatStreaming.ts @@ -1,17 +1,11 @@ /** - * useAIChatStreaming — Encapsulates all streaming logic for the AI chat panel. + * useAIChatStreaming — React UI layer for AI chat streaming. * - * Handles: - * - Catty agent streaming via Vercel AI SDK `streamText` - * - External agent streaming through official SDK backends - * - Text-delta batching via requestAnimationFrame - * - Abort controller management - * - Stream state tracking (per-session) - * - Error reporting + * Turn orchestration lives in AgentRuntime + TurnDrivers; this hook only + * manages streaming state, abort controllers, and UI callbacks. */ import React, { useCallback, useEffect, useRef, useState } from 'react'; -import { generateText, pruneMessages, streamText, stepCountIs, type ModelMessage } from 'ai'; import type { AIPermissionMode, AIToolIntegrationMode, @@ -19,75 +13,18 @@ import type { ChatMessage, ChatMessageAttachment, ExternalAgentConfig, - ProviderAdvancedParams, ProviderConfig, - ToolResult, WebSearchConfig, } from '../../../infrastructure/ai/types'; -import { isWebSearchReady } from '../../../infrastructure/ai/types'; -import { buildSystemPrompt } from '../../../infrastructure/ai/cattyAgent/systemPrompt'; -import { - CONTEXT_COMPACTION_SYSTEM_PROMPT, - DEFAULT_CONTEXT_WINDOW_TOKENS, - DEFAULT_PROTECT_RECENT_MESSAGES, - formatMessagesForCompaction, - estimateUnknownTokens, - keepRecentContextMessages, - prepareContextCompaction, - resolveContextWindow, -} from '../../../infrastructure/ai/contextCompaction'; -import { - compressMessagesForRequestTooLargeRetry, -} from '../../../infrastructure/ai/requestPayloadCompression'; -import { - createCattyRequestTooLargeRetryError, - hadToolProgressBeforeRequestTooLarge, -} from '../../../infrastructure/ai/cattyRequestTooLargeRetry'; -import { createModelFromConfig } from '../../../infrastructure/ai/sdk/providers'; -import { createCattyTools } from '../../../infrastructure/ai/sdk/tools'; import type { ExecutorContext } from '../../../infrastructure/ai/cattyAgent/executor'; -import { getExternalAgentSdkBackend } from '../../../infrastructure/ai/managedAgents'; -import { runSdkAgentTurn } from '../../../infrastructure/ai/sdkAgentAdapter'; -import { classifyError, isRequestTooLargeError } from '../../../infrastructure/ai/errorClassifier'; -import { isSdkStreamStateError } from '../../../infrastructure/ai/shared/streamStateErrors'; -import { - buildPromptWithTerminalSelectionAttachments, - isTerminalSelectionAttachment, -} from '../../../application/state/terminalSelectionAttachment'; +import { getAgentRuntime } from '../../../infrastructure/ai/harness/globalAgentRuntime'; +import { classifyError } from '../../../infrastructure/ai/errorClassifier'; import { latestAISessionsSnapshot } from '../../../application/state/aiStateSnapshots'; import { - buildHistoricalToolReplayMaps, - buildHistoricalToolResultReplayText, - buildHistoricalUserReplayContent, -} from '../cattyHistoryReplay'; -import { - extractProviderContinuationFromRawChunk, - getOpenAIChatAssistantFieldsForHistoryMessage, - isProviderContinuationForSource, - mergeProviderContinuation, - normalizeProviderContinuationOptions, - withProviderContinuationSource, - type OpenAIChatAssistantFields, - type ProviderContinuation, -} from '../../../infrastructure/ai/providerContinuation'; - -import { - getNetcattyBridge, generateId, - isToolResultError, - resolveUserSkillsContext, - toAssistantModelContent, - type AssistantContentPart, - type CattyProviderContinuationContext, + getNetcattyBridge, type DefaultTargetSessionHint, - type ErrorChunk, - type RawChunk, - type ReasoningChunk, - type StreamChunk, type TerminalSessionInfo, - type TextDeltaChunk, - type ToolCallChunk, - type ToolResultChunk, } from './aiChatStreamingSupport'; export { getNetcattyBridge } from './aiChatStreamingSupport'; @@ -101,11 +38,6 @@ const streamingSubscribers = new Set<() => void>(); export function isAIChatSessionStreaming(sessionId: string | null | undefined): boolean { return !!sessionId && sharedStreamingSessionIds.has(sessionId); } -const OPENAI_CHAT_ASSISTANT_FIELDS = Symbol('netcatty.openAIChatAssistantFields'); - -type ModelMessageWithOpenAIChatFields = ModelMessage & { - [OPENAI_CHAT_ASSISTANT_FIELDS]?: OpenAIChatAssistantFields; -}; function emitStreamingStoreChange(): void { streamingSubscribers.forEach(listener => { @@ -117,49 +49,6 @@ function emitStreamingStoreChange(): void { }); } -function rememberOpenAIChatAssistantFields( - message: ModelMessage, - fields: OpenAIChatAssistantFields | undefined, - fieldsByMessage: Map, -): void { - fieldsByMessage.set(message, fields); - (message as ModelMessageWithOpenAIChatFields)[OPENAI_CHAT_ASSISTANT_FIELDS] = fields; -} - -function getRememberedOpenAIChatAssistantFields( - message: ModelMessage, - fieldsByMessage: Map, -): OpenAIChatAssistantFields | undefined { - if (fieldsByMessage.has(message)) return fieldsByMessage.get(message); - return (message as ModelMessageWithOpenAIChatFields)[OPENAI_CHAT_ASSISTANT_FIELDS]; -} - -function modelMessageHasToolCall(message: ModelMessage): boolean { - if (message.role !== 'assistant' || !Array.isArray(message.content)) return false; - return message.content.some((part) => part && typeof part === 'object' && (part as { type?: string }).type === 'tool-call'); -} - -function collectOpenAIChatAssistantFieldsForMessages( - messages: ModelMessage[], - fieldsByMessage: Map, -): Array { - const fields: Array = []; - let previousMessageWasTool = false; - for (const message of messages) { - const needsContinuationFields = message.role === 'assistant' - && (modelMessageHasToolCall(message) || previousMessageWasTool); - if (needsContinuationFields) { - fields.push(getRememberedOpenAIChatAssistantFields(message, fieldsByMessage)); - } - previousMessageWasTool = message.role === 'tool'; - } - return fields; -} - -// ------------------------------------------------------------------- -// Hook parameters -// ------------------------------------------------------------------- - export interface UseAIChatStreamingParams { maxIterations: number; addMessageToSession: (sessionId: string, message: ChatMessage) => void; @@ -167,30 +56,10 @@ export interface UseAIChatStreamingParams { updateMessageById: (sessionId: string, messageId: string, updater: (msg: ChatMessage) => ChatMessage) => void; } -// ------------------------------------------------------------------- -// Hook return type -// ------------------------------------------------------------------- - export interface UseAIChatStreamingReturn { - /** Set of session IDs currently streaming. */ streamingSessionIds: Set; - /** Set or unset streaming state for a session. */ setStreamingForScope: (key: string, val: boolean) => void; - /** Ref to per-session abort controllers. */ abortControllersRef: React.MutableRefObject>; - /** Process a Catty agent stream. */ - processCattyStream: ( - streamSessionId: string, - model: ReturnType, - systemPrompt: string, - tools: ReturnType, - sdkMessages: Array, - signal: AbortSignal, - currentAssistantMsgId: string, - advancedParams?: ProviderAdvancedParams, - continuationContext?: CattyProviderContinuationContext, - ) => Promise; - /** Send a message to the Catty agent (built-in). */ sendToCattyAgent: ( sessionId: string, sendScopeKey: string, @@ -201,7 +70,6 @@ export interface UseAIChatStreamingReturn { context: SendToCattyContext, attachments?: ChatMessageAttachment[], ) => Promise; - /** Send a message to an external SDK agent. */ sendToExternalAgent: ( sessionId: string, trimmed: string, @@ -210,11 +78,9 @@ export interface UseAIChatStreamingReturn { attachedImages: Array<{ base64Data: string; mediaType: string; filename?: string; filePath?: string }>, context: SendToExternalContext, ) => Promise; - /** Report a streaming error to the chat. */ reportStreamError: (sessionId: string, abortSignal: AbortSignal, err: unknown) => void; } -/** Context values needed by sendToCattyAgent that change frequently (avoids stale closures). */ export interface SendToCattyContext { activeProvider: ProviderConfig | undefined; activeModelId: string; @@ -229,9 +95,9 @@ export interface SendToCattyContext { autoTitleSession: (sessionId: string, text: string) => void; titleText?: string; selectedUserSkillSlugs?: string[]; + permissionMode?: AIPermissionMode; } -/** Context values needed by sendToExternalAgent that change frequently. */ export interface SendToExternalContext { existingSessionId?: string; updateExternalSessionId?: (sessionId: string, externalSessionId: string | undefined) => void; @@ -244,20 +110,16 @@ export interface SendToExternalContext { selectedUserSkillSlugs?: string[]; } -// ------------------------------------------------------------------- -// Hook implementation -// ------------------------------------------------------------------- - export function useAIChatStreaming({ maxIterations, addMessageToSession, updateLastMessage, updateMessageById, }: UseAIChatStreamingParams): UseAIChatStreamingReturn { - // Per-session streaming state (keyed by sessionId) const [streamingSessionIds, setStreamingSessions] = useState>( () => new Set(sharedStreamingSessionIds), ); + useEffect(() => { const syncFromStore = () => { setStreamingSessions(new Set(sharedStreamingSessionIds)); @@ -281,25 +143,15 @@ export function useAIChatStreaming({ } }, []); - // Per-scope abort controllers const abortControllersRef = useRef>(sharedAbortControllers); - // ------------------------------------------------------------------- - // reportStreamError - // ------------------------------------------------------------------- - const reportStreamError = useCallback(( sessionId: string, abortSignal: AbortSignal, err: unknown, ) => { if (abortSignal.aborted) return; - // Log the full unsanitized error for debugging console.error('[AIChatSidePanel] Stream error (full):', err); - // Pass the raw error to classifyError so it can inspect structured - // fields (statusCode, responseBody) from APICallError and friends; - // string-coercing here would strip the metadata we need to detect - // 413 / HTML-error-page / parse-failure scenarios. const errorInfo = classifyError(err); updateLastMessage(sessionId, msg => ({ ...msg, @@ -315,306 +167,14 @@ export function useAIChatStreaming({ }); }, [updateLastMessage, addMessageToSession]); - // ------------------------------------------------------------------- - // processCattyStream - // ------------------------------------------------------------------- - - const processCattyStream = useCallback(async ( - streamSessionId: string, - model: ReturnType, - systemPrompt: string, - tools: ReturnType, - sdkMessages: Array, - signal: AbortSignal, - currentAssistantMsgId: string, - advancedParams?: ProviderAdvancedParams, - continuationContext?: CattyProviderContinuationContext, - ): Promise => { - const result = streamText({ - model, - messages: sdkMessages, - system: systemPrompt, - tools, - stopWhen: stepCountIs(maxIterations), - abortSignal: signal, - includeRawChunks: true, - ...(advancedParams?.maxTokens != null && { maxOutputTokens: advancedParams.maxTokens }), - ...(advancedParams?.temperature != null && { temperature: advancedParams.temperature }), - ...(advancedParams?.topP != null && { topP: advancedParams.topP }), - ...(advancedParams?.frequencyPenalty != null && { frequencyPenalty: advancedParams.frequencyPenalty }), - ...(advancedParams?.presencePenalty != null && { presencePenalty: advancedParams.presencePenalty }), - }); - - // Track the current assistant message ID so updates target the correct message - let activeMsgId = currentAssistantMsgId; - let lastAddedRole: 'assistant' | 'tool' = 'assistant'; - let hadToolProgress = false; - const reader = result.fullStream.getReader(); - - // -- Text-delta batching: accumulate deltas and flush periodically -- - let pendingText = ''; - let rafId: number | null = null; - const ensureAssistantMessage = (): string => { - if (lastAddedRole !== 'tool') return activeMsgId; - - const newId = generateId(); - addMessageToSession(streamSessionId, { - id: newId, - role: 'assistant', - content: '', - timestamp: Date.now(), - }); - activeMsgId = newId; - lastAddedRole = 'assistant'; - return activeMsgId; - }; - - const updateAssistantContinuation = ( - messageId: string, - continuation: ProviderContinuation | undefined, - thinkingText = '', - ) => { - if (!continuation && !thinkingText) return; - const sourcedContinuation = withProviderContinuationSource(continuation, continuationContext?.source); - updateMessageById(streamSessionId, messageId, msg => { - const providerContinuation = mergeProviderContinuation(msg.providerContinuation, sourcedContinuation); - return { - ...msg, - ...(providerContinuation ? { providerContinuation } : {}), - ...(thinkingText ? { thinking: (msg.thinking || '') + thinkingText } : {}), - }; - }); - }; - - const getOpenAIReasoningText = (continuation: ProviderContinuation | undefined): string => { - const reasoningContent = continuation?.openAIChatAssistantFields?.reasoning_content; - return typeof reasoningContent === 'string' ? reasoningContent : ''; - }; - - const flushText = () => { - if (pendingText) { - const text = pendingText; - pendingText = ''; - if (lastAddedRole === 'tool') { - const newId = generateId(); - addMessageToSession(streamSessionId, { - id: newId, - role: 'assistant', - content: text, - timestamp: Date.now(), - }); - activeMsgId = newId; - lastAddedRole = 'assistant'; - } else { - updateMessageById(streamSessionId, activeMsgId, msg => ({ - ...msg, - content: msg.content + text, - })); - } - } - rafId = null; - }; - - const cancelPendingFlush = () => { - if (rafId !== null) { - cancelAnimationFrame(rafId); - rafId = null; - } - }; - - try { - while (true) { - let readResult: ReadableStreamReadResult; - try { - readResult = await reader.read(); - } catch (readErr) { - if (isRequestTooLargeError(readErr)) { - throw createCattyRequestTooLargeRetryError(readErr, hadToolProgress); - } - throw readErr; - } - const { done, value } = readResult; - if (done) break; - // Use the StreamChunk union for type narrowing instead of unsafe casts - const chunk = value as StreamChunk; - switch (chunk.type) { - case 'text': - case 'text-delta': { - const typedChunk = chunk as TextDeltaChunk; - const text = typedChunk.text ?? typedChunk.textDelta; - const providerOptions = normalizeProviderContinuationOptions(typedChunk.providerMetadata); - if (providerOptions) { - const messageId = ensureAssistantMessage(); - updateAssistantContinuation(messageId, { textProviderOptions: providerOptions }); - } - if (text) { - pendingText += text; - if (rafId === null) { - rafId = requestAnimationFrame(flushText); - } - } - break; - } - case 'reasoning': - case 'reasoning-start': - case 'reasoning-delta': { - cancelPendingFlush(); - flushText(); - const typedChunk = chunk as ReasoningChunk; - const rText = typedChunk.text ?? typedChunk.textDelta ?? typedChunk.delta ?? ''; - const providerOptions = normalizeProviderContinuationOptions(typedChunk.providerMetadata); - const continuation = rText || providerOptions - ? { - reasoningParts: [{ - text: rText, - ...(providerOptions ? { providerOptions } : {}), - }], - } satisfies ProviderContinuation - : undefined; - if (continuation || rText) { - const messageId = ensureAssistantMessage(); - updateAssistantContinuation(messageId, continuation, rText); - } - break; - } - case 'raw': { - const typedChunk = chunk as RawChunk; - const continuation = extractProviderContinuationFromRawChunk(typedChunk.rawValue); - if (continuation) { - cancelPendingFlush(); - flushText(); - const messageId = ensureAssistantMessage(); - updateAssistantContinuation(messageId, continuation, getOpenAIReasoningText(continuation)); - } - break; - } - case 'reasoning-end': - case 'text-start': - case 'text-end': - case 'start': - case 'finish': - case 'start-step': - case 'finish-step': - break; - case 'tool-call': { - cancelPendingFlush(); - flushText(); - const typedChunk = chunk as ToolCallChunk; - hadToolProgress = true; - const messageId = ensureAssistantMessage(); - const providerOptions = normalizeProviderContinuationOptions(typedChunk.providerMetadata); - updateMessageById(streamSessionId, messageId, msg => ({ - ...msg, - toolCalls: [...(msg.toolCalls || []), { - id: typedChunk.toolCallId, - name: typedChunk.toolName, - arguments: (typedChunk.input ?? typedChunk.args) as Record, - }], - executionStatus: 'running', - statusText: undefined, - })); - if (providerOptions) { - updateAssistantContinuation(messageId, { - toolCallProviderOptionsById: { - [typedChunk.toolCallId]: providerOptions, - }, - }); - } - break; - } - case 'tool-result': { - cancelPendingFlush(); - flushText(); - const typedChunk = chunk as ToolResultChunk; - hadToolProgress = true; - // Mark the assistant message's tool execution as completed - updateMessageById(streamSessionId, activeMsgId, msg => - msg.role === 'assistant' && msg.executionStatus === 'running' - ? { ...msg, executionStatus: 'completed', statusText: undefined } : msg, - ); - const toolOutput = typedChunk.output ?? typedChunk.result; - const toolError = isToolResultError(toolOutput); - addMessageToSession(streamSessionId, { - id: generateId(), - role: 'tool', - content: '', - toolResults: [{ - toolCallId: typedChunk.toolCallId, - content: typeof toolOutput === 'string' - ? toolOutput - : JSON.stringify(toolOutput), - isError: toolError, - }], - timestamp: Date.now(), - executionStatus: 'completed', - }); - lastAddedRole = 'tool'; - break; - } - // tool-approval-request is no longer handled here — approval is now - // inside the tool's execute function via the approvalGate module. - // The SDK may still emit this chunk type but we simply ignore it. - case 'error': { - const typedChunk = chunk as ErrorChunk; - // Internal SDK reasoning/text state-machine errors (e.g. a - // third-party Anthropic-compat backend like DeepSeek's - // `-v4-flash` streaming thinking deltas without first emitting - // the `reasoning-start` content-block signal) leak through - // fullStream once per orphan delta. They're not user-facing - // errors — and worse, surfacing one assistant message per - // event breaks tool_use/tool_result contiguity on the next - // turn, which the Anthropic backend then rejects as - // `messages.N: tool_use ids were found without tool_result - // blocks immediately after`. Filter them out at the chunk - // boundary: drop the placeholder assistant message and keep - // accepting subsequent chunks, so the rest of the stream - // (real text, tool calls, the genuine `finish`) lands intact. - if (isSdkStreamStateError(typedChunk.error)) { - console.warn('[Catty] suppressed SDK stream state error:', typedChunk.error); - break; - } - if (isRequestTooLargeError(typedChunk.error)) { - cancelPendingFlush(); - flushText(); - throw createCattyRequestTooLargeRetryError( - typedChunk.error, - hadToolProgress, - ); - } - cancelPendingFlush(); - flushText(); - updateMessageById(streamSessionId, activeMsgId, msg => ({ - ...msg, - statusText: '', - executionStatus: msg.executionStatus === 'running' ? 'failed' : msg.executionStatus, - })); - addMessageToSession(streamSessionId, { - id: generateId(), - role: 'assistant', - content: '', - // Pass the raw error so classifyError can detect 413 / HTML / - // schema-parse scenarios via structured fields (statusCode, - // responseBody) instead of lossy string conversion. - errorInfo: classifyError(typedChunk.error), - timestamp: Date.now(), - }); - break; - } - default: - break; - } - } - } finally { - cancelPendingFlush(); - flushText(); - reader.releaseLock(); - } - return; - }, [maxIterations, addMessageToSession, updateMessageById]); - - // ------------------------------------------------------------------- - // sendToExternalAgent - // ------------------------------------------------------------------- + const uiCallbacks = useCallback(() => ({ + addMessageToSession, + updateLastMessage, + updateMessageById, + reportStreamError, + setStreamingForScope, + getLatestSession: (sessionId: string) => latestAISessionsSnapshot?.find(s => s.id === sessionId), + }), [addMessageToSession, updateLastMessage, updateMessageById, reportStreamError, setStreamingForScope]); const sendToExternalAgent = useCallback(async ( sessionId: string, @@ -625,130 +185,18 @@ export function useAIChatStreaming({ context: SendToExternalContext, ) => { const bridge = getNetcattyBridge(); - const userSkillsContext = await resolveUserSkillsContext( + await getAgentRuntime().runTurn({ + backend: 'external-sdk', + chatSessionId: sessionId, + userText: trimmed, + signal: abortController.signal, + agentConfig, + attachedImages, + context, bridge, - trimmed, - context.selectedUserSkillSlugs, - ); - - const sdkBackend = getExternalAgentSdkBackend(agentConfig); - if (sdkBackend && bridge) { - const requestId = `sdk_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`; - - // Push terminal session metadata to MCP bridge - if (bridge?.aiMcpUpdateSessions) { - await bridge.aiMcpUpdateSessions(context.terminalSessions, sessionId); - } - - // Mutable flag: set after tool-result, cleared when new assistant msg is created - let needsNewAssistantMsg = false; - const maybeCreateAssistantMsg = () => { - if (needsNewAssistantMsg) { - needsNewAssistantMsg = false; - addMessageToSession(sessionId, { - id: generateId(), role: 'assistant', content: '', timestamp: Date.now(), - model: agentConfig.name || 'external', - }); - } - }; - - await runSdkAgentTurn( - bridge, - requestId, - sessionId, - agentConfig, - trimmed, - { - onTextDelta: (text: string) => { - maybeCreateAssistantMsg(); - updateLastMessage(sessionId, msg => ({ - ...msg, - content: msg.content + text, - statusText: undefined, - thinkingDurationMs: msg.thinking && !msg.thinkingDurationMs - ? Date.now() - msg.timestamp : msg.thinkingDurationMs, - })); - }, - onThinkingDelta: (text: string) => { - maybeCreateAssistantMsg(); - updateLastMessage(sessionId, msg => ({ - ...msg, thinking: (msg.thinking || '') + text, - })); - }, - onThinkingDone: () => { - updateLastMessage(sessionId, msg => ({ - ...msg, thinkingDurationMs: msg.thinkingDurationMs || (Date.now() - msg.timestamp), - })); - }, - onToolCall: (toolName: string, args: Record, toolCallId?: string) => { - maybeCreateAssistantMsg(); - updateLastMessage(sessionId, msg => ({ - ...msg, - toolCalls: [...(msg.toolCalls || []), { id: toolCallId || `tc_${Date.now()}`, name: toolName, arguments: args }], - executionStatus: 'running', - statusText: undefined, - })); - }, - onToolResult: (toolCallId: string, result: string, toolName?: string) => { - updateLastMessage(sessionId, msg => { - if (msg.role !== 'assistant' || msg.executionStatus !== 'running') return msg; - // Only patch tool call name if the existing name is missing/generic - // (don't overwrite a good name from onToolCall with a wrapper name from tool-result) - const updatedToolCalls = toolName && !toolName.includes('sdk_agent_dynamic_tool') && msg.toolCalls - ? msg.toolCalls.map(tc => tc.id === toolCallId && !tc.name ? { ...tc, name: toolName } : tc) - : msg.toolCalls; - return { ...msg, toolCalls: updatedToolCalls, executionStatus: 'completed', statusText: undefined }; - }); - const toolError = isToolResultError(result); - addMessageToSession(sessionId, { - id: generateId(), role: 'tool', content: '', - toolResults: [{ toolCallId, content: result, isError: toolError }], - timestamp: Date.now(), executionStatus: 'completed', - }); - needsNewAssistantMsg = true; - }, - onStatus: (message: string) => { - maybeCreateAssistantMsg(); - updateLastMessage(sessionId, msg => ({ ...msg, statusText: message })); - }, - onSessionId: (externalSessionId: string) => { - context.updateExternalSessionId?.(sessionId, externalSessionId); - }, - onError: (error: string) => { - reportStreamError(sessionId, abortController.signal, error); - setStreamingForScope(sessionId, false); - }, - onDone: () => {}, - }, - abortController.signal, - // Managed SDK agents (codex, claude) must resolve auth from their own - // CLI config/login state, so we deliberately pass no providerId here. - // See issue #705 for Codex; same reasoning for Claude. - undefined, - context.selectedAgentModel, - context.existingSessionId, - context.historyMessages, - attachedImages.length > 0 ? attachedImages : undefined, - context.toolIntegrationMode, - context.defaultTargetSession, - userSkillsContext, - ); - } else { - // Managed agents always route through the SDK path above. - reportStreamError( - sessionId, - abortController.signal, - 'This agent has no SDK backend configured. Re-discover it in Settings -> AI.', - ); - setStreamingForScope(sessionId, false); - } - }, [ - addMessageToSession, updateLastMessage, setStreamingForScope, reportStreamError, - ]); - - // ------------------------------------------------------------------- - // sendToCattyAgent - // ------------------------------------------------------------------- + ui: uiCallbacks(), + }); + }, [uiCallbacks]); const sendToCattyAgent = useCallback(async ( sessionId: string, @@ -761,450 +209,30 @@ export function useAIChatStreaming({ attachments?: ChatMessageAttachment[], ) => { const bridge = getNetcattyBridge(); - const userSkillsContext = await resolveUserSkillsContext( - bridge, - trimmed, - context.selectedUserSkillSlugs, - ); - const getExecutorContext = context.getExecutorContext ?? (() => ({ - sessions: context.terminalSessions, - workspaceId: context.scopeType === 'workspace' ? context.scopeTargetId : undefined, - workspaceName: context.scopeType === 'workspace' ? context.scopeLabel : undefined, - })); - const tools = createCattyTools( - bridge, - getExecutorContext, - context.commandBlocklist, - context.globalPermissionMode, - context.webSearchConfig ?? undefined, - sessionId, - ); - - const systemPrompt = buildSystemPrompt({ - scopeType: context.scopeType, scopeLabel: context.scopeLabel, - hosts: context.terminalSessions.map(s => ({ - sessionId: s.sessionId, hostname: s.hostname, label: s.label, - os: s.os, - username: s.username, - protocol: s.protocol, - shellType: s.shellType, - deviceType: s.deviceType, - connected: s.connected, - })), - permissionMode: context.globalPermissionMode, - webSearchEnabled: isWebSearchReady(context.webSearchConfig), - userSkillsContext, - }); - - // Guard: activeProvider must exist for Catty agent path - if (!context.activeProvider) { - reportStreamError(sessionId, abortController.signal, 'No AI provider configured. Please configure a provider in Settings → AI.'); - return; - } - - const activeModelId = context.activeModelId || context.activeProvider.defaultModel || ''; - const continuationContext: CattyProviderContinuationContext = { - source: { - providerConfigId: context.activeProvider.id, - providerType: context.activeProvider.providerId, - modelId: activeModelId, - }, - openAIChatAssistantFields: [], - }; - try { - let openAIChatAssistantFieldsByMessage = new Map(); - const buildSdkMessages = ( - allMessages: ChatMessage[], - includeCurrentUserMessage: boolean, - { - preserveTerminalToolResults = new Set(), - }: { - preserveTerminalToolResults?: ReadonlySet; - } = {}, - ): Array => { - const { resolvedToolCallsByAssistant, toolCallByToolResult } = buildHistoricalToolReplayMaps(allMessages); - const nextFieldsByMessage = new Map(); - const sdkMessages: Array = []; - let previousHistoryMessageWasToolResult = false; - - for (const m of allMessages) { - const currentMessageFollowsToolResult = previousHistoryMessageWasToolResult; - if (m.role === 'user') { - // Historical attachments are replayed as placeholders so screenshots, - // files, and terminal selections do not balloon every follow-up request. - const messageAttachments = m.attachments ?? m.images; - sdkMessages.push({ - role: 'user', - content: buildHistoricalUserReplayContent(m.content, messageAttachments ?? []), - }); - } else if (m.role === 'assistant') { - const activeContinuation = isProviderContinuationForSource( - m.providerContinuation, - continuationContext.source, - ) - ? m.providerContinuation - : undefined; - const openAIChatAssistantFields = getOpenAIChatAssistantFieldsForHistoryMessage( - m, - continuationContext.source, - ); - if (m.toolCalls?.length) { - // Only include tool calls that have matching results - const resolvedToolCalls = resolvedToolCallsByAssistant.get(m); - const resolvedCalls = resolvedToolCalls - ? m.toolCalls.filter(tc => resolvedToolCalls.has(tc)) - : []; - const contentParts: AssistantContentPart[] = []; - if (resolvedCalls.length > 0) { - for (const part of activeContinuation?.reasoningParts ?? []) { - if (!part.text && !part.providerOptions) continue; - contentParts.push({ - type: 'reasoning' as const, - text: part.text, - ...(part.providerOptions ? { providerOptions: part.providerOptions } : {}), - }); - } - } - if (m.content) { - contentParts.push({ - type: 'text' as const, - text: m.content, - ...(activeContinuation?.textProviderOptions ? { providerOptions: activeContinuation.textProviderOptions } : {}), - }); - } - for (const tc of resolvedCalls) { - const providerOptions = activeContinuation?.toolCallProviderOptionsById?.[tc.id]; - contentParts.push({ - type: 'tool-call' as const, - toolCallId: tc.id, - toolName: tc.name, - input: tc.arguments ?? {}, - ...(providerOptions ? { providerOptions } : {}), - }); - } - // If all tool calls were orphaned, just include the text content - if (contentParts.length > 0) { - const message: ModelMessage = { role: 'assistant', content: toAssistantModelContent(contentParts) }; - sdkMessages.push(message); - if (resolvedCalls.length > 0) { - rememberOpenAIChatAssistantFields(message, openAIChatAssistantFields, nextFieldsByMessage); - } - } - } else if (m.content) { - const contentParts: AssistantContentPart[] = []; - for (const part of activeContinuation?.reasoningParts ?? []) { - if (!part.text && !part.providerOptions) continue; - contentParts.push({ - type: 'reasoning' as const, - text: part.text, - ...(part.providerOptions ? { providerOptions: part.providerOptions } : {}), - }); - } - contentParts.push({ - type: 'text' as const, - text: m.content, - ...(activeContinuation?.textProviderOptions ? { providerOptions: activeContinuation.textProviderOptions } : {}), - }); - const message: ModelMessage = { - role: 'assistant', - content: toAssistantModelContent(contentParts), - }; - sdkMessages.push(message); - if (currentMessageFollowsToolResult) { - rememberOpenAIChatAssistantFields(message, openAIChatAssistantFields, nextFieldsByMessage); - } - } - } else if (m.role === 'tool' && m.toolResults?.length) { - sdkMessages.push({ - role: 'tool', - content: m.toolResults.map(tr => { - const toolCall = toolCallByToolResult.get(tr); - return { - type: 'tool-result' as const, - toolCallId: tr.toolCallId, - toolName: toolCall?.name ?? 'unknown', - output: { - type: 'text' as const, - value: buildHistoricalToolResultReplayText(tr, toolCall, { - preserveTerminalOutput: preserveTerminalToolResults.has(tr), - }), - }, - }; - }), - }); - } - previousHistoryMessageWasToolResult = m.role === 'tool' && !!m.toolResults?.length; - } - - if (includeCurrentUserMessage) { - // Build the current user message — include attachments as multimodal content - if (attachments?.length) { - const modelText = buildPromptWithTerminalSelectionAttachments(trimmed, attachments); - const modelAttachments = attachments.filter( - (attachment) => !isTerminalSelectionAttachment(attachment), - ); - if (!modelAttachments.length) { - sdkMessages.push({ role: 'user', content: modelText }); - } else { - const parts: Array<{ type: 'text'; text: string } | { type: 'image'; image: string; mediaType?: string } | { type: 'file'; data: string; mediaType: string; filename?: string }> = []; - parts.push({ type: 'text', text: modelText }); - for (const att of modelAttachments) { - if (att.mediaType.startsWith('image/')) { - parts.push({ type: 'image', image: att.base64Data, mediaType: att.mediaType }); - } else { - parts.push({ type: 'file', data: att.base64Data, mediaType: att.mediaType, filename: att.filename }); - } - } - sdkMessages.push({ role: 'user', content: parts }); - } - } else { - sdkMessages.push({ role: 'user', content: trimmed }); - } - } - - openAIChatAssistantFieldsByMessage = nextFieldsByMessage; - return sdkMessages; - }; - - const sdkMessages = buildSdkMessages(currentSession?.messages ?? [], true); - const collectToolResultsAfterMessage = ( - messages: ChatMessage[], - messageId: string, - ): Set => { - const results = new Set(); - let afterMessage = false; - for (const message of messages) { - if (message.id === messageId) { - afterMessage = true; - continue; - } - if (!afterMessage || message.role !== 'tool' || !message.toolResults?.length) continue; - for (const result of message.toolResults) { - results.add(result); - } - } - return results; - }; - - // Create model with placeholder API key — the main process injects the real - // decrypted key when the HTTP request is proxied through IPC, so plaintext - // keys never transit the renderer ↔ main IPC boundary. - let model; - try { - model = createModelFromConfig( - { - ...context.activeProvider, - defaultModel: activeModelId, - }, - { - getOpenAIChatAssistantFields: () => continuationContext.openAIChatAssistantFields, - }, - ); - } catch (e) { - console.error('[Catty] Model creation failed:', e); - reportStreamError(sessionId, abortController.signal, `Model creation failed: ${e instanceof Error ? e.message : String(e)}`); - return; - } - - const contextWindow = resolveContextWindow({ - provider: context.activeProvider, - modelId: activeModelId, - defaultContextWindow: DEFAULT_CONTEXT_WINDOW_TOKENS, + await getAgentRuntime().runTurn({ + backend: 'catty', + chatSessionId: sessionId, + sendScopeKey, + userText: trimmed, + signal: abortController.signal, + currentSession, + assistantMsgId, + context, + attachments, + maxIterations, + bridge, + ui: uiCallbacks(), }); - const outputReserveTokens = Math.min(4096, Math.ceil(contextWindow * 0.05)); - const getRequestReserveTokens = () => outputReserveTokens + estimateUnknownTokens({ - systemPrompt, - toolNames: Object.keys(tools), - openAIChatAssistantFields: Array.from(openAIChatAssistantFieldsByMessage.values()), - }); - - const summarizeForCompaction = async (messagesToSummarize: ModelMessage[]) => { - updateLastMessage(sessionId, msg => ({ ...msg, statusText: 'Compacting earlier context...' })); - const result = await generateText({ - model, - system: CONTEXT_COMPACTION_SYSTEM_PROMPT, - messages: [{ - role: 'user', - content: `Summarize this earlier conversation context for the next model turn:\n\n${formatMessagesForCompaction(messagesToSummarize)}`, - }], - abortSignal: abortController.signal, - maxOutputTokens: 1600, - temperature: 0, - }); - return result.text; - }; - const prepareMessagesForStream = (messages: ModelMessage[]): ModelMessage[] => { - const pruned = pruneMessages({ - messages, - reasoning: 'all', - emptyMessages: 'remove', - }); - continuationContext.openAIChatAssistantFields = collectOpenAIChatAssistantFieldsForMessages( - pruned, - openAIChatAssistantFieldsByMessage, - ); - return pruned; - }; - const compactMessages = async ( - messages: ModelMessage[], - { - force = false, - statusText, - fallbackLog, - compressForRequestTooLargeRetry = false, - compressionLog, - }: { - force?: boolean; - statusText?: string; - fallbackLog: string; - compressForRequestTooLargeRetry?: boolean; - compressionLog?: string; - }, - ): Promise => { - const compressRetryMessages = (candidateMessages: ModelMessage[], log?: string): ModelMessage[] => { - if (!compressForRequestTooLargeRetry) return candidateMessages; - const compressed = compressMessagesForRequestTooLargeRetry(candidateMessages); - if (compressed.didAdjust && log) { - console.warn(log); - } - return compressed.messages; - }; - - try { - if (statusText) { - updateLastMessage(sessionId, msg => ({ ...msg, statusText })); - } - const inputMessages = compressRetryMessages(messages, compressionLog); - const compacted = await prepareContextCompaction({ - messages: inputMessages, - contextWindow, - reservedTokens: getRequestReserveTokens(), - thresholdRatio: force ? 0 : undefined, - protectRecentMessages: DEFAULT_PROTECT_RECENT_MESSAGES, - summarize: summarizeForCompaction, - }); - let nextMessages = force && !compacted.didCompact - ? keepRecentContextMessages(inputMessages, DEFAULT_PROTECT_RECENT_MESSAGES) - : compacted.messages; - return compressRetryMessages(nextMessages); - } catch (err) { - if (abortController.signal.aborted) throw err; - console.warn(fallbackLog, err); - const fallbackMessages = keepRecentContextMessages(messages, DEFAULT_PROTECT_RECENT_MESSAGES); - if (!compressForRequestTooLargeRetry) { - return fallbackMessages; - } - const compressed = compressMessagesForRequestTooLargeRetry(fallbackMessages); - if (compressed.didAdjust) { - console.warn('[Catty] Request content compressed after compaction fallback.'); - } - return compressed.messages; - } - }; - let messagesForStream = sdkMessages; - messagesForStream = await compactMessages(messagesForStream, { - fallbackLog: '[Catty] Context compaction failed; falling back to recent messages only:', - }); - - messagesForStream = prepareMessagesForStream(messagesForStream); - - try { - await processCattyStream( - sessionId, - model, - systemPrompt, - tools, - messagesForStream, - abortController.signal, - assistantMsgId, - context.activeProvider?.advancedParams, - continuationContext, - ); - } catch (streamErr) { - if (abortController.signal.aborted || !isRequestTooLargeError(streamErr)) { - throw streamErr; - } - - console.warn('[Catty] Request hit HTTP 413; forcing context compaction and retrying once.', streamErr); - const statusText = 'Request was too large. Compacting context and retrying...'; - const hadToolProgress = hadToolProgressBeforeRequestTooLarge(streamErr); - let retryBaseMessages = messagesForStream; - let retryAssistantMsgId = assistantMsgId; - if (hadToolProgress) { - const latestSession = latestAISessionsSnapshot?.find(session => session.id === sessionId); - if (latestSession) { - retryBaseMessages = buildSdkMessages(latestSession.messages, false, { - preserveTerminalToolResults: collectToolResultsAfterMessage( - latestSession.messages, - assistantMsgId, - ), - }); - } - retryAssistantMsgId = generateId(); - addMessageToSession(sessionId, { - id: retryAssistantMsgId, - role: 'assistant', - content: '', - timestamp: Date.now(), - model: activeModelId || context.activeProvider?.defaultModel || '', - providerId: context.activeProvider?.providerId, - statusText, - }); - } else { - updateMessageById(sessionId, assistantMsgId, msg => ({ - ...msg, - content: '', - thinking: undefined, - thinkingDurationMs: undefined, - providerContinuation: undefined, - toolCalls: undefined, - errorInfo: undefined, - executionStatus: undefined, - pendingApproval: undefined, - statusText, - })); - } - const retryMessages = prepareMessagesForStream(await compactMessages(retryBaseMessages, { - force: true, - statusText, - fallbackLog: '[Catty] Forced context compaction after 413 failed; falling back to recent messages only:', - compressForRequestTooLargeRetry: true, - compressionLog: '[Catty] Request content compressed after forced context compaction.', - })); - - await processCattyStream( - sessionId, - model, - systemPrompt, - tools, - retryMessages, - abortController.signal, - retryAssistantMsgId, - context.activeProvider?.advancedParams, - continuationContext, - ); - } - } catch (err) { - console.error('[Catty] streamText error:', err); - reportStreamError(sessionId, abortController.signal, err); } finally { - // Clear any lingering statusText when the stream finishes - updateLastMessage(sessionId, msg => msg.statusText ? { ...msg, statusText: '' } : msg); - setStreamingForScope(sessionId, false); abortControllersRef.current.delete(sessionId); - context.autoTitleSession(sessionId, context.titleText ?? trimmed); } - }, [ - processCattyStream, reportStreamError, setStreamingForScope, - addMessageToSession, updateLastMessage, updateMessageById, - ]); + }, [maxIterations, uiCallbacks]); return { streamingSessionIds, setStreamingForScope, abortControllersRef, - processCattyStream, sendToCattyAgent, sendToExternalAgent, reportStreamError, diff --git a/components/ai/toolArtifacts/VaultArtifactCard.test.tsx b/components/ai/toolArtifacts/VaultArtifactCard.test.tsx new file mode 100644 index 000000000..880197392 --- /dev/null +++ b/components/ai/toolArtifacts/VaultArtifactCard.test.tsx @@ -0,0 +1,42 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import React from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; + +import { I18nProvider } from '../../../application/i18n/I18nProvider.tsx'; +import { VaultArtifactCard } from './VaultArtifactCard.tsx'; + +test('VaultArtifactCard renders note artifact title', () => { + const html = renderToStaticMarkup( + + + , + ); + + assert.match(html, /Runbook/); + assert.match(html, /ops\/prod/); +}); + +test('VaultArtifactCard renders host batch summary', () => { + const html = renderToStaticMarkup( + + + , + ); + + assert.match(html, /Added 2 hosts/); + assert.match(html, /Web/); +}); diff --git a/components/ai/toolArtifacts/VaultArtifactCard.tsx b/components/ai/toolArtifacts/VaultArtifactCard.tsx new file mode 100644 index 000000000..845ca5dc0 --- /dev/null +++ b/components/ai/toolArtifacts/VaultArtifactCard.tsx @@ -0,0 +1,130 @@ +import { ChevronRight } from 'lucide-react'; +import React from 'react'; +import { useI18n } from '../../../application/i18n/I18nProvider'; +import { cn } from '../../../lib/utils'; +import type { VaultToolArtifact } from './vaultToolArtifact'; +import { navigateVaultArtifact, useVaultArtifactNavigation } from './VaultArtifactNavigationContext'; +import { VaultArtifactIcon } from './vaultArtifactPresentation'; + +interface VaultArtifactCardProps { + artifact: VaultToolArtifact; + toolName?: string; + className?: string; +} + +function getArtifactPresentation( + artifact: VaultToolArtifact, + t: (key: string, values?: Record) => string, +): { + title: string; + subtitle?: string; + clickable: boolean; +} { + switch (artifact.kind) { + case 'vault.note': + return { + title: artifact.title, + subtitle: artifact.group ?? t('ai.chat.artifact.noteFallback'), + clickable: true, + }; + case 'vault.host': + return { + title: artifact.label, + subtitle: artifact.port + ? `${artifact.hostname}:${artifact.port}` + : artifact.hostname, + clickable: true, + }; + case 'vault.hosts.batch': { + const preview = artifact.preview + .slice(0, 2) + .map((host) => host.label || host.hostname) + .filter(Boolean) + .join(', '); + return { + title: artifact.dryRun + ? t('ai.chat.artifact.hostsPreview', { count: artifact.addedCount }) + : t('ai.chat.artifact.hostsAdded', { count: artifact.addedCount }), + subtitle: preview || t('ai.chat.artifact.openHosts'), + clickable: true, + }; + } + case 'vault.summary': + return { + title: artifact.section === 'notes' + ? t('ai.chat.artifact.notesSummary', { count: artifact.count }) + : t('ai.chat.artifact.hostsSummary', { count: artifact.count }), + subtitle: artifact.section === 'notes' + ? t('ai.chat.artifact.openNotes') + : t('ai.chat.artifact.openHosts'), + clickable: true, + }; + case 'error': + return { + title: t('ai.chat.artifact.failed'), + subtitle: artifact.message, + clickable: false, + }; + default: + return { + title: '', + clickable: false, + }; + } +} + +export const VaultArtifactCard: React.FC = ({ + artifact, + toolName, + className, +}) => { + const { t } = useI18n(); + const navigation = useVaultArtifactNavigation(); + const presentation = getArtifactPresentation(artifact, t); + + const handleClick = () => { + if (!presentation.clickable || !navigation) return; + navigateVaultArtifact(artifact, navigation); + }; + + const content = ( + <> + +
+
+ {presentation.title} +
+ {presentation.subtitle && ( +
+ {presentation.subtitle} +
+ )} +
+ {presentation.clickable && ( + + )} + + ); + + if (!presentation.clickable) { + return ( +
+ {content} +
+ ); + } + + return ( + + ); +}; diff --git a/components/ai/toolArtifacts/VaultArtifactNavigationContext.tsx b/components/ai/toolArtifacts/VaultArtifactNavigationContext.tsx new file mode 100644 index 000000000..07d8d7e14 --- /dev/null +++ b/components/ai/toolArtifacts/VaultArtifactNavigationContext.tsx @@ -0,0 +1,89 @@ +import React, { createContext, useCallback, useContext, useMemo } from 'react'; +import type { Host, VaultNote } from '../../../types'; +import { useI18n } from '../../../application/i18n/I18nProvider'; +import { toast } from '../../ui/toast'; +import type { VaultToolArtifact } from './vaultToolArtifact'; + +export interface VaultArtifactNavigationActions { + openVaultNote: (noteId: string) => void; + openVaultHost: (hostId: string) => void; + openVaultSection: (section: 'notes' | 'hosts') => void; +} + +interface VaultArtifactNavigationProviderProps { + notes: VaultNote[]; + hosts: Host[]; + onOpenVaultNote: (noteId: string) => void; + onOpenVaultHost: (hostId: string) => void; + onOpenVaultSection: (section: 'notes' | 'hosts') => void; + children: React.ReactNode; +} + +const VaultArtifactNavigationContext = createContext(null); + +export function VaultArtifactNavigationProvider({ + notes, + hosts, + onOpenVaultNote, + onOpenVaultHost, + onOpenVaultSection, + children, +}: VaultArtifactNavigationProviderProps) { + const { t } = useI18n(); + + const openVaultNote = useCallback((noteId: string) => { + const exists = notes.some((note) => note.id === noteId); + if (!exists) { + toast.warning(t('ai.chat.artifact.noteMissing'), t('ai.chat.artifact.unavailableTitle')); + return; + } + onOpenVaultNote(noteId); + }, [notes, onOpenVaultNote, t]); + + const openVaultHost = useCallback((hostId: string) => { + const exists = hosts.some((host) => host.id === hostId); + if (!exists) { + toast.warning(t('ai.chat.artifact.hostMissing'), t('ai.chat.artifact.unavailableTitle')); + return; + } + onOpenVaultHost(hostId); + }, [hosts, onOpenVaultHost, t]); + + const value = useMemo(() => ({ + openVaultNote, + openVaultHost, + openVaultSection: onOpenVaultSection, + }), [onOpenVaultHost, onOpenVaultNote, onOpenVaultSection, openVaultHost, openVaultNote]); + + return ( + + {children} + + ); +} + +export function useVaultArtifactNavigation(): VaultArtifactNavigationActions | null { + return useContext(VaultArtifactNavigationContext); +} + +export function navigateVaultArtifact( + artifact: VaultToolArtifact, + navigation: VaultArtifactNavigationActions, +): void { + switch (artifact.kind) { + case 'vault.note': + navigation.openVaultNote(artifact.noteId); + break; + case 'vault.host': + navigation.openVaultHost(artifact.hostId); + break; + case 'vault.hosts.batch': + navigation.openVaultSection('hosts'); + break; + case 'vault.summary': + navigation.openVaultSection(artifact.section); + break; + default: + break; + } +} diff --git a/components/ai/toolArtifacts/VaultArtifactToolResult.tsx b/components/ai/toolArtifacts/VaultArtifactToolResult.tsx new file mode 100644 index 000000000..edc9cc418 --- /dev/null +++ b/components/ai/toolArtifacts/VaultArtifactToolResult.tsx @@ -0,0 +1,38 @@ +import React from 'react'; +import { Tooltip, TooltipContent, TooltipTrigger } from '../../ui/tooltip'; +import { VaultArtifactCard } from './VaultArtifactCard'; +import { formatVaultToolTooltip } from './formatVaultToolTooltip'; +import type { VaultToolArtifact } from './vaultToolArtifact'; + +interface VaultArtifactToolResultProps { + artifact: VaultToolArtifact; + toolName: string; + args?: Record; + result?: unknown; + isError?: boolean; +} + +export const VaultArtifactToolResult: React.FC = ({ + artifact, + toolName, + args, + result, + isError, +}) => { + const tooltip = formatVaultToolTooltip(toolName, args, result, isError); + + return ( + + + + + + {tooltip} + + + ); +}; diff --git a/components/ai/toolArtifacts/formatVaultToolTooltip.test.ts b/components/ai/toolArtifacts/formatVaultToolTooltip.test.ts new file mode 100644 index 000000000..877016b81 --- /dev/null +++ b/components/ai/toolArtifacts/formatVaultToolTooltip.test.ts @@ -0,0 +1,18 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { formatVaultToolTooltip } from './formatVaultToolTooltip.ts'; + +test('formatVaultToolTooltip joins tool name, args, and result with line breaks', () => { + const text = formatVaultToolTooltip( + 'vault_notes_create', + { title: 'Runbook' }, + { ok: true, note: { id: 'n1', title: 'Runbook' } }, + ); + + assert.match(text, /^vault_notes_create/); + assert.match(text, /Arguments:/); + assert.match(text, /"title": "Runbook"/); + assert.match(text, /Result:/); + assert.match(text, /"ok": true/); +}); diff --git a/components/ai/toolArtifacts/formatVaultToolTooltip.ts b/components/ai/toolArtifacts/formatVaultToolTooltip.ts new file mode 100644 index 000000000..d00e4653c --- /dev/null +++ b/components/ai/toolArtifacts/formatVaultToolTooltip.ts @@ -0,0 +1,37 @@ +function stringifyToolPayload(value: unknown): string { + if (value == null) return ''; + if (typeof value === 'string') { + try { + const parsed = JSON.parse(value) as unknown; + if (parsed && typeof parsed === 'object') { + return JSON.stringify(parsed, null, 2); + } + } catch { + return value; + } + return value; + } + if (typeof value === 'object') { + return JSON.stringify(value, null, 2); + } + return String(value); +} + +export function formatVaultToolTooltip( + toolName: string, + args?: Record, + result?: unknown, + isError?: boolean, +): string { + const lines: string[] = [toolName]; + + if (args && Object.keys(args).length > 0) { + lines.push('', 'Arguments:', stringifyToolPayload(args)); + } + + if (result !== undefined) { + lines.push('', isError ? 'Error:' : 'Result:', stringifyToolPayload(result)); + } + + return lines.join('\n'); +} diff --git a/components/ai/toolArtifacts/vaultArtifactPresentation.test.ts b/components/ai/toolArtifacts/vaultArtifactPresentation.test.ts new file mode 100644 index 000000000..567e3defe --- /dev/null +++ b/components/ai/toolArtifacts/vaultArtifactPresentation.test.ts @@ -0,0 +1,45 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { resolveVaultArtifactVisualKind } from './vaultArtifactPresentation.tsx'; + +test('resolveVaultArtifactVisualKind distinguishes note vs host tools', () => { + assert.equal( + resolveVaultArtifactVisualKind( + { kind: 'vault.note', noteId: 'n1', title: 'Doc' }, + 'vault_notes_create', + ), + 'noteCreate', + ); + assert.equal( + resolveVaultArtifactVisualKind( + { kind: 'vault.host', hostId: 'h1', label: 'Web', hostname: '10.0.0.1' }, + 'host_get', + ), + 'host', + ); + assert.equal( + resolveVaultArtifactVisualKind( + { + kind: 'vault.hosts.batch', + sourceTool: 'vault_hosts_import', + addedCount: 2, + preview: [], + }, + 'vault_hosts_import', + ), + 'hostImport', + ); + assert.equal( + resolveVaultArtifactVisualKind( + { + kind: 'vault.hosts.batch', + sourceTool: 'vault_hosts_create', + addedCount: 2, + preview: [], + }, + 'vault_hosts_create', + ), + 'hostCreate', + ); +}); diff --git a/components/ai/toolArtifacts/vaultArtifactPresentation.tsx b/components/ai/toolArtifacts/vaultArtifactPresentation.tsx new file mode 100644 index 000000000..e1705bba0 --- /dev/null +++ b/components/ai/toolArtifacts/vaultArtifactPresentation.tsx @@ -0,0 +1,115 @@ +import { + AlertCircle, + FilePenLine, + FileText, + FolderInput, + LayoutGrid, + Library, + NotebookPen, + Server, + ServerCog, +} from 'lucide-react'; +import React from 'react'; +import { cn } from '../../../lib/utils'; +import type { VaultToolArtifact } from './vaultToolArtifact'; + +export type VaultArtifactVisualKind = + | 'noteCreate' + | 'noteUpdate' + | 'noteRead' + | 'noteList' + | 'host' + | 'hostCreate' + | 'hostImport' + | 'hostList' + | 'error'; + +const ARTIFACT_ICON_SIZE = 18; + +const VISUAL_STYLES: Record = { + noteCreate: { wrapper: 'bg-violet-500/12', icon: 'text-violet-400' }, + noteUpdate: { wrapper: 'bg-violet-500/10', icon: 'text-violet-300/90' }, + noteRead: { wrapper: 'bg-violet-500/10', icon: 'text-violet-300/80' }, + noteList: { wrapper: 'bg-muted/30', icon: 'text-muted-foreground/70' }, + host: { wrapper: 'bg-emerald-500/12', icon: 'text-emerald-400' }, + hostCreate: { wrapper: 'bg-sky-500/12', icon: 'text-sky-400' }, + hostImport: { wrapper: 'bg-amber-500/12', icon: 'text-amber-400' }, + hostList: { wrapper: 'bg-muted/30', icon: 'text-muted-foreground/70' }, + error: { wrapper: 'bg-destructive/10', icon: 'text-destructive/80' }, +}; + +export function resolveVaultArtifactVisualKind( + artifact: VaultToolArtifact, + toolName?: string, +): VaultArtifactVisualKind { + if (artifact.kind === 'error') return 'error'; + + if (artifact.kind === 'vault.note') { + if (toolName === 'vault_notes_create') return 'noteCreate'; + if (toolName === 'vault_notes_update') return 'noteUpdate'; + return 'noteRead'; + } + + if (artifact.kind === 'vault.host') return 'host'; + + if (artifact.kind === 'vault.hosts.batch') { + if (artifact.sourceTool === 'vault_hosts_import' || toolName === 'vault_hosts_import') { + return 'hostImport'; + } + return 'hostCreate'; + } + + if (artifact.kind === 'vault.summary') { + return artifact.section === 'notes' ? 'noteList' : 'hostList'; + } + + return 'host'; +} + +function renderVisualIcon(kind: VaultArtifactVisualKind): React.ReactNode { + const className = VISUAL_STYLES[kind].icon; + switch (kind) { + case 'noteCreate': + return ; + case 'noteUpdate': + return ; + case 'noteRead': + return ; + case 'noteList': + return ; + case 'host': + return ; + case 'hostCreate': + return ; + case 'hostImport': + return ; + case 'hostList': + return ; + case 'error': + return ; + default: + return ; + } +} + +export function VaultArtifactIcon({ + artifact, + toolName, +}: { + artifact: VaultToolArtifact; + toolName?: string; +}) { + const kind = resolveVaultArtifactVisualKind(artifact, toolName); + const styles = VISUAL_STYLES[kind]; + + return ( + + {renderVisualIcon(kind)} + + ); +} diff --git a/components/ai/toolArtifacts/vaultToolArtifact.test.ts b/components/ai/toolArtifacts/vaultToolArtifact.test.ts new file mode 100644 index 000000000..c6b9557f2 --- /dev/null +++ b/components/ai/toolArtifacts/vaultToolArtifact.test.ts @@ -0,0 +1,74 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { parseVaultToolArtifact } from './vaultToolArtifact.ts'; + +test('parseVaultToolArtifact maps note create results', () => { + const artifact = parseVaultToolArtifact('vault_notes_create', { + ok: true, + note: { id: 'note-1', title: 'Runbook', group: 'ops/prod' }, + }); + assert.deepEqual(artifact, { + kind: 'vault.note', + noteId: 'note-1', + title: 'Runbook', + group: 'ops/prod', + }); +}); + +test('parseVaultToolArtifact maps single host create to host artifact', () => { + const artifact = parseVaultToolArtifact('vault_hosts_create', { + ok: true, + addedCount: 1, + previewHosts: [ + { id: 'host-1', label: 'Dokploy', hostname: '10.2.0.209' }, + ], + }); + assert.deepEqual(artifact, { + kind: 'vault.host', + hostId: 'host-1', + label: 'Dokploy', + hostname: '10.2.0.209', + }); +}); + +test('parseVaultToolArtifact maps host batch import results', () => { + const artifact = parseVaultToolArtifact('vault_hosts_create', { + ok: true, + addedCount: 2, + previewHosts: [ + { id: 'host-1', label: 'Web', hostname: '10.0.0.1' }, + { id: 'host-2', hostname: 'db.internal' }, + ], + }); + assert.equal(artifact?.kind, 'vault.hosts.batch'); + if (artifact?.kind !== 'vault.hosts.batch') return; + assert.equal(artifact.addedCount, 2); + assert.equal(artifact.preview.length, 2); +}); + +test('parseVaultToolArtifact maps host get results', () => { + const artifact = parseVaultToolArtifact('host_get', { + ok: true, + host: { id: 'host-9', label: 'Prod', hostname: 'prod.example.com', port: 22 }, + }); + assert.deepEqual(artifact, { + kind: 'vault.host', + hostId: 'host-9', + label: 'Prod', + hostname: 'prod.example.com', + port: 22, + group: undefined, + }); +}); + +test('parseVaultToolArtifact maps errors', () => { + const artifact = parseVaultToolArtifact('vault_notes_get', { + ok: false, + error: 'Vault note "missing" was not found.', + }); + assert.deepEqual(artifact, { + kind: 'error', + message: 'Vault note "missing" was not found.', + }); +}); diff --git a/components/ai/toolArtifacts/vaultToolArtifact.ts b/components/ai/toolArtifacts/vaultToolArtifact.ts new file mode 100644 index 000000000..6b23517da --- /dev/null +++ b/components/ai/toolArtifacts/vaultToolArtifact.ts @@ -0,0 +1,183 @@ +export type VaultToolArtifact = + | { + kind: 'vault.note'; + noteId: string; + title: string; + group?: string; + } + | { + kind: 'vault.host'; + hostId: string; + label: string; + hostname: string; + port?: number; + group?: string; + } + | { + kind: 'vault.hosts.batch'; + sourceTool?: 'vault_hosts_create' | 'vault_hosts_import'; + addedCount: number; + dryRun?: boolean; + preview: Array<{ hostId?: string; label?: string; hostname?: string }>; + } + | { + kind: 'vault.summary'; + section: 'notes' | 'hosts'; + count: number; + } + | { + kind: 'error'; + message: string; + }; + +const VAULT_ARTIFACT_TOOL_NAMES = new Set([ + 'vault_notes_create', + 'vault_notes_update', + 'vault_notes_get', + 'vault_notes_list', + 'vault_hosts_create', + 'vault_hosts_import', + 'vault_hosts_list', + 'host_get', +]); + +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 parseNoteArtifact(note: unknown): VaultToolArtifact | null { + if (!note || typeof note !== 'object') return null; + const record = note as Record; + const noteId = readString(record.id); + const title = readString(record.title); + if (!noteId || !title) return null; + return { + kind: 'vault.note', + noteId, + title, + group: readString(record.group), + }; +} + +function parseHostArtifact(host: unknown): VaultToolArtifact | null { + if (!host || typeof host !== 'object') return null; + const record = host as Record; + const hostId = readString(record.id); + const hostname = readString(record.hostname); + if (!hostId || !hostname) return null; + return { + kind: 'vault.host', + hostId, + label: readString(record.label) ?? hostname, + hostname, + port: readNumber(record.port), + group: readString(record.group), + }; +} + +function parsePreviewHosts(value: unknown): Array<{ hostId?: string; label?: string; hostname?: string }> { + if (!Array.isArray(value)) return []; + return value + .map((entry) => { + if (!entry || typeof entry !== 'object') return null; + const record = entry as Record; + const hostname = readString(record.hostname); + if (!hostname) return null; + return { + hostId: readString(record.id), + label: readString(record.label), + hostname, + }; + }) + .filter((entry): entry is { hostId?: string; label?: string; hostname: string } => entry !== null); +} + +export function isVaultArtifactToolName(toolName: string): boolean { + return VAULT_ARTIFACT_TOOL_NAMES.has(toolName); +} + +export function parseVaultToolArtifact( + toolName: string, + result: unknown, +): VaultToolArtifact | null { + if (!isVaultArtifactToolName(toolName)) return null; + + const payload = parseResultPayload(result); + if (!payload) return null; + + if (payload.ok === false || payload.isError === true) { + const message = readString(payload.error) ?? 'Operation failed.'; + return { kind: 'error', message }; + } + + switch (toolName) { + case 'vault_notes_create': + case 'vault_notes_update': + case 'vault_notes_get': + return parseNoteArtifact(payload.note); + case 'vault_notes_list': { + const notes = Array.isArray(payload.notes) ? payload.notes : []; + return { kind: 'vault.summary', section: 'notes', count: notes.length }; + } + case 'vault_hosts_create': + case 'vault_hosts_import': { + const preview = parsePreviewHosts(payload.previewHosts); + const addedCount = readNumber(payload.addedCount) + ?? (payload.dryRun === true ? readNumber(payload.validCount) : undefined) + ?? preview.length; + if (addedCount <= 0 && preview.length === 0) return null; + + const dryRun = payload.dryRun === true; + if (!dryRun && addedCount === 1 && preview.length === 1 && preview[0].hostname) { + const single = preview[0]; + if (single.hostId) { + return { + kind: 'vault.host', + hostId: single.hostId, + label: single.label ?? single.hostname, + hostname: single.hostname, + }; + } + } + + return { + kind: 'vault.hosts.batch', + sourceTool: toolName === 'vault_hosts_import' ? 'vault_hosts_import' : 'vault_hosts_create', + addedCount, + dryRun, + preview, + }; + } + case 'vault_hosts_list': { + const hosts = Array.isArray(payload.hosts) ? payload.hosts : []; + return { kind: 'vault.summary', section: 'hosts', count: hosts.length }; + } + case 'host_get': + return parseHostArtifact(payload.host); + default: + return null; + } +} diff --git a/components/notes/NotesManager.tsx b/components/notes/NotesManager.tsx index 684150c67..4fe216cd9 100644 --- a/components/notes/NotesManager.tsx +++ b/components/notes/NotesManager.tsx @@ -115,6 +115,8 @@ export interface NotesManagerProps { onOpenHost?: (host: Host, source?: { noteId: string }) => void; displayMode?: "full" | "sidebar"; openNoteId?: string | null; + /** Called after a one-shot openNoteId focus request has been applied. */ + onOpenNoteIdHandled?: () => void; } type HoverActionMenuProps = { @@ -326,11 +328,12 @@ export const NotesManager: React.FC = ({ onOpenHost, displayMode = "full", openNoteId = null, + onOpenNoteIdHandled, }) => { const { t } = useI18n(); const { openExternal } = useApplicationBackend(); const isSidebarMode = displayMode === "sidebar"; - const initialOpenNoteId = isSidebarMode && openNoteId && notes.some((note) => note.id === openNoteId) + const initialOpenNoteId = openNoteId && notes.some((note) => note.id === openNoteId) ? openNoteId : null; const [query, setQuery] = useState(""); @@ -413,17 +416,18 @@ export const NotesManager: React.FC = ({ }, [selectedNote?.group]); useEffect(() => { - if (!isSidebarMode || !openNoteId) return; + if (!openNoteId) return; const note = sortedNotes.find((item) => item.id === openNoteId); if (!note) return; - const nextSelection = getNoteSelectionState(note, true); + const nextSelection = getNoteSelectionState(note, isSidebarMode); setSelectedNoteId(nextSelection.selectedNoteId); setSelectedGroup(nextSelection.selectedGroup); setOverlayNoteId(nextSelection.overlayNoteId); if (note.group) { setExpandedGroups((current) => new Set([...current, ...ancestorNoteGroupPaths(note.group || "")])); } - }, [isSidebarMode, openNoteId, sortedNotes]); + onOpenNoteIdHandled?.(); + }, [isSidebarMode, onOpenNoteIdHandled, openNoteId, sortedNotes]); useEffect(() => { if (expandedPanel !== "search") return; diff --git a/components/settings/tabs/SettingsAITab.tsx b/components/settings/tabs/SettingsAITab.tsx index 0f34a52dd..708ecc9ea 100644 --- a/components/settings/tabs/SettingsAITab.tsx +++ b/components/settings/tabs/SettingsAITab.tsx @@ -44,6 +44,8 @@ import { ClaudeCodeCard } from "./ai/ClaudeCodeCard"; import { CopilotCliCard } from "./ai/CopilotCliCard"; import { CodebuddyCard } from "./ai/CodebuddyCard"; import { SafetySettings } from "./ai/SafetySettings"; +import { PermissionGrantsSettings } from "./ai/PermissionGrantsSettings"; +import { useAIPermissionGrantsState } from "../../../application/state/useAIPermissionGrantsState"; import { WebSearchSettings } from "./ai/WebSearchSettings"; import { QuickMessagesSettings } from "./ai/QuickMessagesSettings"; import type { AIQuickMessage } from "../../../infrastructure/ai/quickMessages"; @@ -187,6 +189,14 @@ const SettingsAITab: React.FC = ({ showTerminalSelectionAIAction, setShowTerminalSelectionAIAction, }) => { + const { + permissionGrants, + addGrant, + updateGrant, + removeGrant, + importGrants, + exportGrants, + } = useAIPermissionGrantsState(); const { t } = useI18n(); const [editingProviderId, setEditingProviderId] = useState(null); const [codexIntegration, setCodexIntegration] = useState(null); @@ -1154,6 +1164,14 @@ const SettingsAITab: React.FC = ({ maxIterations={maxIterations} setMaxIterations={setMaxIterations} /> + diff --git a/components/settings/tabs/ai/PermissionGrantsSettings.tsx b/components/settings/tabs/ai/PermissionGrantsSettings.tsx new file mode 100644 index 000000000..cfa797843 --- /dev/null +++ b/components/settings/tabs/ai/PermissionGrantsSettings.tsx @@ -0,0 +1,255 @@ +import React, { useCallback, useMemo, useRef, useState } from 'react'; +import { Download, Plus, Trash2, Upload } from 'lucide-react'; +import { useI18n } from '../../../../application/i18n/I18nProvider'; +import { Button } from '../../../ui/button'; +import { SettingCard, SettingsSection } from '../../settings-ui'; +import { Tooltip, TooltipContent, TooltipTrigger } from '../../../ui/tooltip'; +import type { PermissionGrantRule } from '../../../../infrastructure/ai/harness/permissionGrants'; +import { + capabilitySupportsCommandPatternGrant, + createPermissionGrantId, + listGrantableCapabilityIds, +} from '../../../../infrastructure/ai/harness/permissionGrants'; + +const cellInputClass = + 'w-full min-w-0 max-w-full h-7 rounded border border-input bg-background px-2 text-xs font-mono focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring overflow-x-auto whitespace-nowrap scrollbar-thin'; + +const cellSelectClass = + `${cellInputClass} font-sans truncate pr-6`; + +const GrantCellInput: React.FC<{ + value: string; + placeholder?: string; + mono?: boolean; + onChange: (value: string) => void; +}> = ({ value, placeholder, mono = true, onChange }) => ( + onChange(e.target.value)} + className={mono ? cellInputClass : `${cellInputClass} font-sans whitespace-normal`} + title={value} + /> +); + +const GrantCapabilitySelect: React.FC<{ + value: string; + options: readonly string[]; + onChange: (value: string) => void; +}> = ({ value, options, onChange }) => { + const selectOptions = useMemo(() => { + if (options.includes(value)) return options; + return [value, ...options]; + }, [options, value]); + + return ( + + ); +}; + +export const PermissionGrantsSettings: React.FC<{ + grants: PermissionGrantRule[]; + addGrant: (rule: PermissionGrantRule) => void; + updateGrant: (id: string, updates: Partial>) => void; + removeGrant: (id: string) => void; + importGrants: (raw: unknown, mode?: 'merge' | 'replace') => void; + exportGrants: () => PermissionGrantRule[]; +}> = ({ + grants, + addGrant, + updateGrant, + removeGrant, + importGrants, + exportGrants, +}) => { + const { t } = useI18n(); + const fileInputRef = useRef(null); + const [importError, setImportError] = useState(null); + const grantableCapabilityIds = useMemo(() => listGrantableCapabilityIds(), []); + + const handleAdd = useCallback(() => { + addGrant({ + id: createPermissionGrantId(), + capabilityId: grantableCapabilityIds[0] ?? 'terminal.execute', + sessionPattern: '*', + createdAt: Date.now(), + }); + }, [addGrant, grantableCapabilityIds]); + + const handleExport = useCallback(() => { + const payload = exportGrants(); + const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + const anchor = document.createElement('a'); + anchor.href = url; + anchor.download = 'netcatty-permission-grants.json'; + anchor.click(); + URL.revokeObjectURL(url); + }, [exportGrants]); + + const handleImportFile = useCallback(async (file: File) => { + setImportError(null); + try { + const text = await file.text(); + const parsed = JSON.parse(text) as unknown; + importGrants(parsed, 'replace'); + } catch (error) { + setImportError(error instanceof Error ? error.message : String(error)); + } + }, [importGrants]); + + return ( + + +
+
+

{t('ai.safety.grants.heading')}

+

{t('ai.safety.grants.description')}

+
+
+ + + + { + const file = event.target.files?.[0]; + event.target.value = ''; + if (file) void handleImportFile(file); + }} + /> +
+
+ + {importError && ( +

{importError}

+ )} + + {grants.length === 0 ? ( +

+ {t('ai.safety.grants.empty')} +

+ ) : ( +
+ + + + + + + + + + + + + + + + {grants.map((grant) => { + const supportsCommandPattern = capabilitySupportsCommandPatternGrant(grant.capabilityId); + + return ( + + + + + + + ); + })} + +
+ {t('ai.safety.grants.capability')} + + {t('ai.safety.grants.commandPattern')} + + {t('ai.safety.grants.note')} + +
+ { + const updates: Partial> = { + capabilityId, + }; + if (!capabilitySupportsCommandPatternGrant(capabilityId)) { + updates.commandPattern = undefined; + } + updateGrant(grant.id, updates); + }} + /> + + {supportsCommandPattern ? ( + updateGrant(grant.id, { + commandPattern: commandPattern.trim() || undefined, + })} + /> + ) : ( + — + )} + + updateGrant(grant.id, { + note: note.trim() || undefined, + })} + /> + + + + + + {t('ai.safety.grants.remove')} + +
+
+ )} +
+
+ ); +}; diff --git a/components/settings/tabs/ai/managedAgentState.ts b/components/settings/tabs/ai/managedAgentState.ts index 2548a0ef3..b78e419ab 100644 --- a/components/settings/tabs/ai/managedAgentState.ts +++ b/components/settings/tabs/ai/managedAgentState.ts @@ -1,16 +1,13 @@ import type { ExternalAgentConfig } from "../../../../infrastructure/ai/types"; import { type ManagedAgentKey, + getExternalAgentSdkBackend, + isPathLikeCommand, } from "../../../../infrastructure/ai/managedAgents"; import type { AgentPathInfo } from "./types"; import { AGENT_DEFAULTS } from "./types"; import { buildCodebuddyEnv } from "./codebuddyConfigEnv"; -function isPathLikeCommand(command: string | undefined): boolean { - const normalized = String(command || "").trim(); - return normalized.includes("/") || normalized.includes("\\"); -} - function getAutoManagedAgentStoredPath( agents: ExternalAgentConfig[], agentKey: ManagedAgentKey, diff --git a/components/terminalLayer/TerminalLayerSidePanelSection.tsx b/components/terminalLayer/TerminalLayerSidePanelSection.tsx index b3a1414bd..5974b101e 100644 --- a/components/terminalLayer/TerminalLayerSidePanelSection.tsx +++ b/components/terminalLayer/TerminalLayerSidePanelSection.tsx @@ -143,6 +143,9 @@ function TerminalLayerSidePanelTabBody({ ctx }: { ctx: SidePanelContext }) { NotesManager, noteGroups, notes, + onOpenVaultHostFromChat, + onOpenVaultNoteFromChat, + onOpenVaultSectionFromChat, scriptsMountedTabIds, systemMountedTabIds, themeMountedTabIds, @@ -676,6 +679,11 @@ function TerminalLayerSidePanelTabBody({ ctx }: { ctx: SidePanelContext }) { resolveExecutorContext={resolveAIExecutorContext} pendingTerminalSelection={pendingTerminalSelectionForAI} onPendingTerminalSelectionConsumed={handlePendingTerminalSelectionConsumed} + notes={notes} + hosts={hosts} + onOpenVaultNoteFromChat={onOpenVaultNoteFromChat} + onOpenVaultHostFromChat={onOpenVaultHostFromChat} + onOpenVaultSectionFromChat={onOpenVaultSectionFromChat} /> )} diff --git a/components/terminalLayer/TerminalLayerSupport.tsx b/components/terminalLayer/TerminalLayerSupport.tsx index 30540203a..49b5164f6 100644 --- a/components/terminalLayer/TerminalLayerSupport.tsx +++ b/components/terminalLayer/TerminalLayerSupport.tsx @@ -268,8 +268,31 @@ export type AITerminalSessionInfo = { shellType?: string; deviceType?: string; connected: boolean; + hostChain?: Array<{ hostId: string; label?: string; hostname?: string }>; + activePortForwards?: Array<{ + ruleId: string; + label?: string; + type?: string; + localPort?: number; + status?: string; + }>; }; +function summarizeHostChain( + host: Host | undefined, + allHosts: Host[], +): AITerminalSessionInfo['hostChain'] | undefined { + if (!host?.hostChain?.hostIds?.length) return undefined; + return host.hostChain.hostIds.map((hostId) => { + const jumpHost = allHosts.find((entry) => entry.id === hostId); + return { + hostId, + label: jumpHost?.label, + hostname: jumpHost?.hostname, + }; + }); +} + export type AIPanelContext = { scopeType: 'terminal' | 'workspace'; scopeTargetId?: string; @@ -286,9 +309,26 @@ export const buildAITerminalSessionInfo = ( session: TerminalSession | undefined, host: Host | undefined, localOs: 'linux' | 'macos' | 'windows', + options?: { + allHosts?: Host[]; + portForwardingRules?: import('../../domain/models').PortForwardingRule[]; + }, ): AITerminalSessionInfo => { const protocol = session?.protocol || host?.protocol; const isLocalSession = protocol === 'local' || session?.hostId?.startsWith('local-'); + const allHosts = options?.allHosts ?? (host ? [host] : []); + const hostChain = summarizeHostChain(host, allHosts); + const activePortForwards = host?.id && options?.portForwardingRules + ? options.portForwardingRules + .filter((rule) => rule.hostId === host.id && (rule.status === 'active' || rule.status === 'connecting')) + .map((rule) => ({ + ruleId: rule.id, + label: rule.label, + type: rule.type, + localPort: rule.localPort, + status: rule.status, + })) + : undefined; return { sessionId: session?.id || '', hostId: session?.hostId || '', @@ -302,6 +342,8 @@ export const buildAITerminalSessionInfo = ( // PTY and cannot connect to vendor CLIs, so network device mode doesn't apply. deviceType: (session?.moshEnabled || host?.moshEnabled || session?.etEnabled || host?.etEnabled) ? undefined : host?.deviceType, connected: session?.status === 'connected', + ...(hostChain?.length ? { hostChain } : {}), + ...(activePortForwards?.length ? { activePortForwards } : {}), }; }; @@ -317,6 +359,11 @@ interface AIChatPanelsHostProps { }) => ExecutorContext; pendingTerminalSelection?: PendingTerminalSelectionForAI | null; onPendingTerminalSelectionConsumed?: (requestId: string) => void; + notes: VaultNote[]; + hosts: Host[]; + onOpenVaultNoteFromChat?: (noteId: string) => void; + onOpenVaultHostFromChat?: (hostId: string) => void; + onOpenVaultSectionFromChat?: (section: 'notes' | 'hosts') => void; } interface AIStateMaintenanceHostProps { @@ -384,6 +431,11 @@ function aiChatPanelsHostAreEqual( if (prev.pendingTerminalSelection !== next.pendingTerminalSelection) return false; if (prev.onPendingTerminalSelectionConsumed !== next.onPendingTerminalSelectionConsumed) return false; if (prev.resolveExecutorContext !== next.resolveExecutorContext) return false; + if (prev.notes !== next.notes) return false; + if (prev.hosts !== next.hosts) return false; + if (prev.onOpenVaultNoteFromChat !== next.onOpenVaultNoteFromChat) return false; + if (prev.onOpenVaultHostFromChat !== next.onOpenVaultHostFromChat) return false; + if (prev.onOpenVaultSectionFromChat !== next.onOpenVaultSectionFromChat) return false; if (prev.activeTabId === next.activeTabId) return true; for (let i = 0; i < prev.mountedTabIds.length; i += 1) { @@ -403,6 +455,11 @@ const AIChatPanelsHostInner: React.FC = ({ resolveExecutorContext, pendingTerminalSelection, onPendingTerminalSelectionConsumed, + notes, + hosts, + onOpenVaultNoteFromChat, + onOpenVaultHostFromChat, + onOpenVaultSectionFromChat, }) => { const aiState = useContext(AIStateContext); @@ -511,6 +568,11 @@ const AIChatPanelsHostInner: React.FC = ({ terminalSessions={context.terminalSessions} resolveExecutorContext={resolveExecutorContext} isVisible={isVisible} + notes={notes} + hosts={hosts} + onOpenVaultNote={onOpenVaultNoteFromChat} + onOpenVaultHost={onOpenVaultHostFromChat} + onOpenVaultSection={onOpenVaultSectionFromChat} /> @@ -526,6 +588,7 @@ AIChatPanelsHost.displayName = 'AIChatPanelsHost'; export interface TerminalLayerProps { hosts: Host[]; + portForwardingRules?: import('../../domain/models').PortForwardingRule[]; customGroups: string[]; groupConfigs: GroupConfig[]; proxyProfiles: ProxyProfile[]; @@ -536,6 +599,9 @@ export interface TerminalLayerProps { notes: VaultNote[]; noteGroups: string[]; openNoteRequest?: { tabId: string; noteId: string; requestId: number } | null; + onOpenVaultNoteFromChat?: (noteId: string) => void; + onOpenVaultHostFromChat?: (hostId: string) => void; + onOpenVaultSectionFromChat?: (section: 'notes' | 'hosts') => void; sessions: TerminalSession[]; workspaces: Workspace[]; knownHosts?: KnownHost[]; diff --git a/components/terminalLayer/TerminalLayerTabBridge.tsx b/components/terminalLayer/TerminalLayerTabBridge.tsx index 6c890d371..148fa842b 100644 --- a/components/terminalLayer/TerminalLayerTabBridge.tsx +++ b/components/terminalLayer/TerminalLayerTabBridge.tsx @@ -197,7 +197,10 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef }) }); const { aiContextsByTabId, resolveAIExecutorContext } = useTerminalAiContexts({ + hosts: s.hosts, hostsRef: s.hostsRef, + portForwardingRules: s.portForwardingRules, + portForwardingRulesRef: s.portForwardingRulesRef, mountedAiTabIds: s.mountedAiTabIds, sessionHostsMap, sessions, diff --git a/components/terminalLayer/terminalLayerStableSnapshot.ts b/components/terminalLayer/terminalLayerStableSnapshot.ts index 29d5e6bb0..29a086e58 100644 --- a/components/terminalLayer/terminalLayerStableSnapshot.ts +++ b/components/terminalLayer/terminalLayerStableSnapshot.ts @@ -52,6 +52,8 @@ export type TerminalLayerStableSnapshot = { sessionsRef: React.MutableRefObject; workspacesRef: React.MutableRefObject; hostsRef: React.MutableRefObject; + portForwardingRules: import('../../domain/models').PortForwardingRule[]; + portForwardingRulesRef: React.MutableRefObject; onSetWorkspaceFocusedSessionRef: React.MutableRefObject; sidePanelOpenTabs: Map; setSidePanelOpenTabs: React.Dispatch>>; diff --git a/components/terminalLayer/useTerminalAiContexts.ts b/components/terminalLayer/useTerminalAiContexts.ts index 8b00f2284..4f05f8a9c 100644 --- a/components/terminalLayer/useTerminalAiContexts.ts +++ b/components/terminalLayer/useTerminalAiContexts.ts @@ -3,11 +3,14 @@ import { useCallback, useMemo } from 'react'; import { collectSessionIds } from '../../domain/workspace'; import { detectLocalOs } from '../../lib/localShell'; -import type { Host, TerminalSession, Workspace } from '../../types'; +import type { Host, PortForwardingRule, TerminalSession, Workspace } from '../../types'; import { buildAITerminalSessionInfo, type AIPanelContext } from './TerminalLayerSupport'; interface UseTerminalAiContextsOptions { + hosts: Host[]; hostsRef: React.MutableRefObject; + portForwardingRules: PortForwardingRule[]; + portForwardingRulesRef: React.MutableRefObject; mountedAiTabIds: string[]; sessionHostsMap: Map; sessions: TerminalSession[]; @@ -17,7 +20,10 @@ interface UseTerminalAiContextsOptions { } export function useTerminalAiContexts({ + hosts, hostsRef, + portForwardingRules, + portForwardingRulesRef, mountedAiTabIds, sessionHostsMap, sessions, @@ -25,89 +31,93 @@ export function useTerminalAiContexts({ workspaces, workspacesRef, }: UseTerminalAiContextsOptions) { - // Build per-tab AI contexts so hidden panels can stay mounted without - // recomputing scope resolution from scratch on every tab switch. - const aiContextsByTabId = useMemo(() => { - 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 tabIds = new Set(mountedAiTabIds); - - const contexts = new Map(); - - for (const tabId of tabIds) { - const workspace = workspaceById.get(tabId); - if (workspace) { - const sessionIds = collectSessionIds(workspace.root); - contexts.set(tabId, { - scopeType: 'workspace', - scopeTargetId: workspace.id, - scopeHostIds: sessionIds - .map((sessionId) => sessionById.get(sessionId)?.hostId) - .filter((hostId): hostId is string => !!hostId), - scopeLabel: workspace.title, - terminalSessions: sessionIds.map((sessionId) => - buildAITerminalSessionInfo( - sessionById.get(sessionId), - sessionHostsMap.get(sessionId), - localOs, - ), - ), - }); - continue; - } - - const session = sessionById.get(tabId); - if (!session) continue; - + const aiContextsByTabId = useMemo(() => { + 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 tabIds = new Set(mountedAiTabIds); + + const contexts = new Map(); + + for (const tabId of tabIds) { + const workspace = workspaceById.get(tabId); + if (workspace) { + const sessionIds = collectSessionIds(workspace.root); contexts.set(tabId, { - scopeType: 'terminal', - scopeTargetId: session.id, - scopeHostIds: session.hostId ? [session.hostId] : [], - scopeLabel: session.hostLabel ?? '', - terminalSessions: [ + scopeType: 'workspace', + scopeTargetId: workspace.id, + scopeHostIds: sessionIds + .map((sessionId) => sessionById.get(sessionId)?.hostId) + .filter((hostId): hostId is string => !!hostId), + scopeLabel: workspace.title, + terminalSessions: sessionIds.map((sessionId) => buildAITerminalSessionInfo( - session, - sessionHostsMap.get(session.id), + sessionById.get(sessionId), + sessionHostsMap.get(sessionId), localOs, + { allHosts, portForwardingRules }, ), - ], + ), }); + continue; } - - return contexts; - }, [sessions, workspaces, mountedAiTabIds, sessionHostsMap]); - + + const session = sessionById.get(tabId); + if (!session) continue; + + contexts.set(tabId, { + scopeType: 'terminal', + scopeTargetId: session.id, + scopeHostIds: session.hostId ? [session.hostId] : [], + scopeLabel: session.hostLabel ?? '', + terminalSessions: [ + buildAITerminalSessionInfo( + session, + sessionHostsMap.get(session.id), + localOs, + { allHosts, portForwardingRules }, + ), + ], + }); + } + + return contexts; + }, [sessions, workspaces, mountedAiTabIds, sessionHostsMap, hosts, portForwardingRules]); + const resolveAIExecutorContext = useCallback((scope: { - type: 'terminal' | 'workspace'; - targetId?: string; - label?: string; - }) => { - const latestWorkspaces = workspacesRef.current; - const latestSessions = sessionsRef.current; - const latestHosts = hostsRef.current; - const localOs = detectLocalOs(navigator.userAgent || navigator.platform); - const sessionIds = scope.type === 'workspace' - ? (() => { - const workspace = scope.targetId ? latestWorkspaces.find((w) => w.id === scope.targetId) : undefined; - return workspace?.root ? collectSessionIds(workspace.root) : []; - })() - : scope.targetId ? [scope.targetId] : []; - - const workspaceName = scope.type === 'workspace' - ? latestWorkspaces.find((w) => w.id === scope.targetId)?.title ?? scope.label - : undefined; - - return { - sessions: sessionIds.map((sid) => { - const session = latestSessions.find((s) => s.id === sid); - const host = session?.hostId ? latestHosts.find((h) => h.id === session.hostId) : undefined; - return buildAITerminalSessionInfo(session, host, localOs); - }), - workspaceId: scope.type === 'workspace' ? scope.targetId : undefined, - workspaceName, - }; - }, [hostsRef, sessionsRef, workspacesRef]); + type: 'terminal' | 'workspace'; + targetId?: string; + label?: string; + }) => { + const latestWorkspaces = workspacesRef.current; + const latestSessions = sessionsRef.current; + const latestHosts = hostsRef.current; + const localOs = detectLocalOs(navigator.userAgent || navigator.platform); + const sessionIds = scope.type === 'workspace' + ? (() => { + const workspace = scope.targetId ? latestWorkspaces.find((w) => w.id === scope.targetId) : undefined; + return workspace?.root ? collectSessionIds(workspace.root) : []; + })() + : scope.targetId ? [scope.targetId] : []; + + const workspaceName = scope.type === 'workspace' + ? latestWorkspaces.find((w) => w.id === scope.targetId)?.title ?? scope.label + : undefined; + + return { + sessions: sessionIds.map((sid) => { + const session = latestSessions.find((s) => s.id === sid); + const host = session?.hostId ? latestHosts.find((h) => h.id === session.hostId) : undefined; + return buildAITerminalSessionInfo(session, host, localOs, { + allHosts: latestHosts, + portForwardingRules: portForwardingRulesRef.current, + }); + }), + workspaceId: scope.type === 'workspace' ? scope.targetId : undefined, + workspaceName, + }; + }, [hostsRef, portForwardingRulesRef, sessionsRef, workspacesRef]); return { aiContextsByTabId, diff --git a/components/terminalLayerMemo.ts b/components/terminalLayerMemo.ts index b91923b7e..dab4e08eb 100644 --- a/components/terminalLayerMemo.ts +++ b/components/terminalLayerMemo.ts @@ -12,6 +12,9 @@ export const terminalLayerAreEqual = ( prev.notes === next.notes && prev.noteGroups === next.noteGroups && prev.openNoteRequest === next.openNoteRequest && + prev.onOpenVaultNoteFromChat === next.onOpenVaultNoteFromChat && + prev.onOpenVaultHostFromChat === next.onOpenVaultHostFromChat && + prev.onOpenVaultSectionFromChat === next.onOpenVaultSectionFromChat && prev.sessions === next.sessions && prev.workspaces === next.workspaces && prev.knownHosts === next.knownHosts && diff --git a/components/vault/VaultViewLayout.tsx b/components/vault/VaultViewLayout.tsx index 3e862676c..2459d6265 100644 --- a/components/vault/VaultViewLayout.tsx +++ b/components/vault/VaultViewLayout.tsx @@ -18,7 +18,7 @@ const VaultSectionLoading = () => ( export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) { const { Activity, allGroupPaths, allTags, AppLogo, Array, Badge, BookMarked, Boolean, Button, cancelInlineGroupEdit, CheckSquare, ChevronDown, clearHostSelection, ClipboardCopy, Clock, cn, commitInlineGroupRename, connectionLogs, connectSelectedHosts, ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger, Copy, currentSection, customGroups, deleteGroupPath, deleteGroupWithHosts, deleteSelectedHosts, deleteTargetPath, Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, displayedGroups, displayedHosts, DistroAvatar, Download, Dropdown, DropdownContent, DropdownTrigger, Edit2, editingGroupPath, editingHost, editingHostGroupDefaults, FileCode, FileSymlink, FolderPlus, FolderTree, getDropTargetClasses, getEffectiveHostDistro, Globe, groupConfigs, GroupDetailsPanel, groupedDisplayHosts, handleConnectClick, handleCopyCredentials, handleDeleteTag, handleDuplicateHost, handleEditGroupConfig, handleEditHost, handleEditTag, handleExportHosts, handleHostConnect, handleImportFileSelected, handleNewHost, handleProtocolSelect, handleQuickConnect, handleQuickConnectSaveHost, handleSaveGroupConfig, handleSearchKeyDown, handleUnmanageGroup, handleSidebarWidthCommit, hasHostsSidePanel, HostDetailsPanel, hostListScrollRef, hosts, HostTreeView, hotkeyScheme, identities, ImportVaultDialog, Input, isDeleteGroupOpen, isGroupPanelOpen, isHostPanelOpen, isHostsSectionActive, isImportOpen, isMultiSelectMode, isNewFolderOpen, isQuickConnectOpen, isRenameGroupOpen, isSearchQuickConnect, isSerialModalOpen, Key, keyBindings, KeychainManager, keys, knownHostsManagerElement, Label, lastPinnedId, LayoutGrid, LazyConnectionLogsManager, LazyProtocolSelectDialog, List, managedGroupPaths, managedSources, moveGroup, moveHostToGroup, Network, newFolderName, newHostGroupPath, onClearUnsavedConnectionLogs, onConnectSerial, onCreateLocalTerminal, onDeleteConnectionLog, onDeleteHost, onImportOrReuseKey, onOpenLogView, onOpenSettings, onRunSnippet, onToggleConnectionLogSaved, onUpdateCustomGroups, onUpdateGroupConfigs, onUpdateHosts, onUpdateIdentities, onUpdateKeys, onUpdateProxyProfiles, onUpdateSnippetPackages, onUpdateSnippets, Pin, pinnedHosts, pinnedRecentIds, Plug, Plus, PortForwarding, protocolSelectHost, proxyProfiles, ProxyProfilesManager, quickConnectTarget, quickConnectWarnings, QuickConnectWizard, recentHosts, renameGroupError, renameGroupName, renameTargetPath, reorderGroup, reorderHost, RippleButton, rootRef, sanitizeHost, search, selectedGroupPath, selectedHostIds, selectedTags, SerialConnectModal, SerialHostDetailsPanel, sessionCount, Set, setCurrentSection, setDeleteGroupWithHosts, setDeleteTargetPath, setDragOverDropTarget, setEditingGroupPath, setEditingHost, setGroupDragOverDropTarget, setIsDeleteGroupOpen, setIsGroupPanelOpen, setIsHostPanelOpen, setIsImportOpen, setIsMultiSelectMode, setIsNewFolderOpen, setIsQuickConnectOpen, setIsRenameGroupOpen, setIsSerialModalOpen, setLastPinnedId, setNewFolderName, setNewHostGroupPath, setProtocolSelectHost, setQuickConnectTarget, setQuickConnectWarnings, setRenameGroupError, setRenameGroupName, setRenameTargetPath, setSearch, setSelectedGroupPath, setSelectedHostIds, setSelectedTags, setSidebarCollapsed, setSidebarWidth, setSortMode, setTargetParentPath, Settings, setViewMode, shellHistory, shouldHideEmptyRootHostsSection, showRecentHosts, sidebarCollapsed, sidebarWidth, snippetPackages, snippets, SnippetsManager, SortDropdown, sortMode, splitViewGridStyle, Square, Star, startInlineDeleteGroup, startInlineNewGroup, startInlineRenameGroup, submitNewFolder, submitRenameGroup, Suspense, t, TagFilterDropdown, targetParentPath, terminalFontSize, terminalSettings, TerminalSquare, terminalThemeId, toggleHostPinned, toggleHostSelection, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, Trash2, treeExpandedState, treeViewGroupTree, treeViewHosts, Upload, upsertHostById, Usb, viewMode, visibleDisplayedHosts, X, Zap } = ctx; - const { knownHosts, noteGroups, NotebookText, notes, NotesManager, onOpenHostFromNote, onUpdateNoteGroups, onUpdateNotes } = ctx; + const { knownHosts, noteGroups, NotebookText, notes, NotesManager, onOpenHostFromNote, onOpenNoteIdHandled, onUpdateNoteGroups, onUpdateNotes, openNoteId } = ctx; const [isSidebarResizing, setIsSidebarResizing] = React.useState(false); const sidebarMinWidth = 56; const sidebarMaxWidth = 320; @@ -604,6 +604,8 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) { hosts={hosts} onUpdateNotes={onUpdateNotes} onUpdateNoteGroups={onUpdateNoteGroups} + openNoteId={openNoteId ?? null} + onOpenNoteIdHandled={onOpenNoteIdHandled} onOpenHost={(host: any, source: any) => { if (source?.noteId && onOpenHostFromNote) { onOpenHostFromNote(host, source); diff --git a/components/vault/useVaultImportHandlers.ts b/components/vault/useVaultImportHandlers.ts index da1a92f4c..a5049daec 100644 --- a/components/vault/useVaultImportHandlers.ts +++ b/components/vault/useVaultImportHandlers.ts @@ -2,7 +2,7 @@ import { useCallback } from "react"; import { sanitizeHost } from "../../domain/host"; import { readTextFile } from "../../lib/readTextFile"; -import { importVaultHostsFromText, type VaultImportFormat } from "../../domain/vaultImport"; +import { applyVaultHostImport, importVaultHostsFromText, type VaultImportFormat } from "../../domain/vaultImport"; import type { Host, ManagedSource } from "../../types"; import type { ImportOptions } from "./ImportVaultDialog"; import { toast } from "../ui/toast"; @@ -153,16 +153,9 @@ export function useVaultImportHandlers({ ) as string[]; onUpdateCustomGroups(nextGroups); } else if (newHosts.length > 0) { - onUpdateHosts([...hosts, ...newHosts].map(sanitizeHost)); - - const nextGroups = Array.from( - new Set([ - ...customGroups, - ...result.groups, - ...newHosts.map((h) => h.group).filter(Boolean), - ]), - ) as string[]; - onUpdateCustomGroups(nextGroups); + const merged = applyVaultHostImport(hosts, customGroups, result, { skipDuplicates: true }); + onUpdateHosts(merged.hosts); + onUpdateCustomGroups(merged.customGroups); } // Count total hosts affected (new + converted to managed) diff --git a/domain/vaultHostCreate.test.ts b/domain/vaultHostCreate.test.ts new file mode 100644 index 000000000..a4d4e5ba3 --- /dev/null +++ b/domain/vaultHostCreate.test.ts @@ -0,0 +1,58 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import type { Host } from './models.ts'; +import { + applyVaultHostCreates, + buildVaultHostFromDraft, + buildVaultHostsFromDrafts, + parseVaultHostDraftsInput, +} from './vaultHostCreate.ts'; + +test('buildVaultHostFromDraft maps minimal unstructured fields to a vault host', () => { + const built = buildVaultHostFromDraft({ + hostname: '192.168.1.10', + username: 'ubuntu', + label: 'prod web', + group: 'infra/prod', + tags: 'web, nginx', + }); + + assert.equal(built.ok, true); + if (!built.ok) return; + assert.equal(built.host.hostname, '192.168.1.10'); + assert.equal(built.host.username, 'ubuntu'); + assert.equal(built.host.group, 'infra/prod'); + assert.deepEqual(built.host.tags, ['web', 'nginx']); +}); + +test('parseVaultHostDraftsInput accepts JSON array strings', () => { + const parsed = parseVaultHostDraftsInput(JSON.stringify([ + { hostname: '10.0.0.1', username: 'root' }, + { hostname: '10.0.0.2', username: 'deploy', port: 2222 }, + ])); + + assert.equal(parsed.ok, true); + if (!parsed.ok) return; + assert.equal(parsed.drafts.length, 2); +}); + +test('applyVaultHostCreates writes sanitized hosts into the vault list', () => { + const existing: Host = { + id: 'host-1', + label: 'db', + hostname: '10.0.0.99', + username: 'root', + port: 22, + tags: [], + os: 'linux', + }; + const { hosts: built } = buildVaultHostsFromDrafts([ + { hostname: '10.0.0.10', username: 'deploy', group: 'prod' }, + ]); + const merged = applyVaultHostCreates([existing], ['legacy'], built); + + assert.equal(merged.addedCount, 1); + assert.equal(merged.hosts.length, 2); + assert.ok(merged.customGroups.includes('prod')); +}); diff --git a/domain/vaultHostCreate.ts b/domain/vaultHostCreate.ts new file mode 100644 index 000000000..33c62c587 --- /dev/null +++ b/domain/vaultHostCreate.ts @@ -0,0 +1,190 @@ +import type { Host, HostProtocol } from './models'; +import { sanitizeHost } from './host'; + +const DEFAULT_SSH_PORT = 22; + +export type VaultHostDraftProtocol = Exclude; + +export interface VaultHostDraft { + label?: unknown; + hostname?: unknown; + port?: unknown; + username?: unknown; + password?: unknown; + group?: unknown; + tags?: unknown; + notes?: unknown; + protocol?: unknown; +} + +export interface VaultHostCreateIssue { + index: number; + error: string; +} + +const normalizeGroupPath = (raw: unknown): string | undefined => { + if (typeof raw !== 'string') return undefined; + const trimmed = raw.trim(); + if (!trimmed) return undefined; + const parts = trimmed.replace(/\\/g, '/').split('/').map((part) => part.trim()).filter(Boolean); + return parts.length ? parts.join('/') : undefined; +}; + +const normalizeProtocol = (raw: unknown): VaultHostDraftProtocol | undefined => { + if (typeof raw !== 'string') return undefined; + const value = raw.trim().toLowerCase(); + if (value === 'ssh' || value === 'ssh2') return 'ssh'; + if (value === 'telnet') return 'telnet'; + if (value === 'local') return 'local'; + return undefined; +}; + +const parsePort = (raw: unknown): number | undefined => { + if (typeof raw === 'number' && Number.isFinite(raw)) { + const port = Math.trunc(raw); + return port >= 1 && port <= 65535 ? port : undefined; + } + if (typeof raw !== 'string') return undefined; + const trimmed = raw.trim(); + if (!trimmed) return undefined; + const port = parseInt(trimmed, 10); + return Number.isFinite(port) && port >= 1 && port <= 65535 ? port : undefined; +}; + +const parseTags = (raw: unknown): string[] => { + if (Array.isArray(raw)) { + return Array.from( + new Set(raw.map((entry) => String(entry).trim()).filter(Boolean)), + ); + } + if (typeof raw !== 'string') return []; + return raw + .split(/[,;,]/g) + .map((entry) => entry.trim()) + .filter(Boolean); +}; + +export const buildVaultHostMergeKey = ( + host: Pick, +): string => + `${(host.protocol ?? 'ssh').toLowerCase()}|${host.hostname.toLowerCase()}|${host.port}|${(host.username ?? '').toLowerCase()}`; + +export function buildVaultHostFromDraft( + draft: VaultHostDraft, +): { ok: true; host: Host } | { ok: false; error: string } { + const hostname = typeof draft.hostname === 'string' ? draft.hostname.trim() : ''; + if (!hostname) { + return { ok: false, error: 'hostname is required.' }; + } + + const protocol = normalizeProtocol(draft.protocol) ?? 'ssh'; + const port = parsePort(draft.port) ?? (protocol === 'telnet' ? 23 : DEFAULT_SSH_PORT); + const label = typeof draft.label === 'string' && draft.label.trim() + ? draft.label.trim() + : hostname; + const username = typeof draft.username === 'string' ? draft.username.trim() : ''; + const password = typeof draft.password === 'string' && draft.password ? draft.password : undefined; + const notes = typeof draft.notes === 'string' && draft.notes.trim() ? draft.notes.trim() : undefined; + const now = Date.now(); + + return { + ok: true, + host: { + id: crypto.randomUUID(), + label, + hostname, + port, + username, + password, + group: normalizeGroupPath(draft.group), + tags: parseTags(draft.tags), + os: 'linux', + protocol, + createdAt: now, + ...(notes ? { notes } : {}), + }, + }; +} + +export function parseVaultHostDraftsInput( + value: unknown, +): { ok: true; drafts: VaultHostDraft[] } | { ok: false; error: string } { + let parsed: unknown = value; + if (typeof value === 'string') { + const trimmed = value.trim(); + if (!trimmed) return { ok: false, error: 'hosts is required.' }; + try { + parsed = JSON.parse(trimmed) as unknown; + } catch { + return { ok: false, error: 'hosts must be a JSON array string.' }; + } + } + + if (!Array.isArray(parsed)) { + return { ok: false, error: 'hosts must be a JSON array of host objects.' }; + } + if (parsed.length === 0) { + return { ok: false, error: 'hosts array is empty.' }; + } + + return { ok: true, drafts: parsed as VaultHostDraft[] }; +} + +export function buildVaultHostsFromDrafts( + drafts: VaultHostDraft[], +): { hosts: Host[]; issues: VaultHostCreateIssue[] } { + const hosts: Host[] = []; + const issues: VaultHostCreateIssue[] = []; + + drafts.forEach((draft, index) => { + const built = buildVaultHostFromDraft(draft); + if (!built.ok) { + issues.push({ index, error: built.error }); + return; + } + hosts.push(built.host); + }); + + return { hosts, issues }; +} + +export function applyVaultHostCreates( + existingHosts: Host[], + existingGroups: string[], + createdHosts: Host[], + options?: { skipDuplicates?: boolean }, +): { + hosts: Host[]; + customGroups: string[]; + addedCount: number; + skippedExistingCount: number; + addedHosts: Host[]; +} { + const skipDuplicates = options?.skipDuplicates !== false; + const existingKeys = new Set(existingHosts.map(buildVaultHostMergeKey)); + let newHosts = createdHosts; + let skippedExistingCount = 0; + + if (skipDuplicates) { + newHosts = createdHosts.filter((host) => { + const duplicate = existingKeys.has(buildVaultHostMergeKey(host)); + if (duplicate) skippedExistingCount++; + return !duplicate; + }); + } + + const customGroups = Array.from( + new Set([ + ...existingGroups, + ...newHosts.map((host) => host.group).filter(Boolean), + ]), + ) as string[]; + + return { + hosts: [...existingHosts, ...newHosts].map(sanitizeHost), + customGroups, + addedCount: newHosts.length, + skippedExistingCount, + addedHosts: newHosts, + }; +} diff --git a/domain/vaultImport.test.ts b/domain/vaultImport.test.ts index 26f1ec7f8..f196a8419 100644 --- a/domain/vaultImport.test.ts +++ b/domain/vaultImport.test.ts @@ -1,7 +1,8 @@ import test from "node:test"; import assert from "node:assert/strict"; -import { importVaultHostsFromText } from "./vaultImport.ts"; +import { importVaultHostsFromText, detectVaultImportFormat, applyVaultHostImport } from "./vaultImport.ts"; +import type { Host } from "./models.ts"; test("ssh_config import maps ForwardX11 yes to host X11 forwarding", () => { const result = importVaultHostsFromText("ssh_config", [ @@ -26,3 +27,34 @@ test("ssh_config import maps ForwardX11 no to disabled host X11 forwarding", () assert.equal(result.hosts.length, 1); assert.equal(result.hosts[0].x11Forwarding, false); }); + +test("detectVaultImportFormat recognizes csv and ssh_config exports", () => { + assert.equal( + detectVaultImportFormat("Label,Hostname,Port,Username\nweb,10.0.0.1,22,root"), + "csv", + ); + assert.equal( + detectVaultImportFormat(["Host prod", " HostName prod.example.com", " User deploy"].join("\n")), + "ssh_config", + ); +}); + +test("applyVaultHostImport skips duplicates by default", () => { + const existing: Host = { + id: "existing-1", + label: "web", + hostname: "10.0.0.10", + username: "deploy", + port: 22, + }; + const imported = importVaultHostsFromText("csv", [ + "Label,Hostname,Port,Username", + "web-1,10.0.0.10,22,deploy", + "db-1,10.0.0.20,22,root", + ].join("\n")); + + const merged = applyVaultHostImport([existing], [], imported); + assert.equal(merged.addedCount, 1); + assert.equal(merged.skippedExistingCount, 1); + assert.equal(merged.hosts.length, 2); +}); diff --git a/domain/vaultImport.ts b/domain/vaultImport.ts index 65a38dc83..8879e00ad 100644 --- a/domain/vaultImport.ts +++ b/domain/vaultImport.ts @@ -1,4 +1,12 @@ import { Host, HostChainConfig, HostProtocol } from "./models"; +import { sanitizeHost } from "./host"; +import { + buildVaultHostFromDraft, + buildVaultHostMergeKey, + type VaultHostDraftProtocol, +} from "./vaultHostCreate"; + +export { buildVaultHostMergeKey } from "./vaultHostCreate"; import { parseQuickConnectInput } from "./quickConnect"; import { findHeaderIndex, parseCsv } from "./vaultImport/csvUtils"; export { exportHostsToCsvWithStats, getVaultCsvTemplate } from "./vaultImport/csvExport"; @@ -85,21 +93,29 @@ export type VaultImportFormat = | "securecrt" | "ssh_config"; +export const VAULT_IMPORT_FORMATS: VaultImportFormat[] = [ + "csv", + "putty", + "mobaxterm", + "securecrt", + "ssh_config", +]; + type VaultImportIssueLevel = "warning" | "error"; -interface VaultImportIssue { +export interface VaultImportIssue { level: VaultImportIssueLevel; message: string; } -interface VaultImportStats { +export interface VaultImportStats { parsed: number; imported: number; skipped: number; duplicates: number; } -interface VaultImportResult { +export interface VaultImportResult { hosts: Host[]; groups: string[]; issues: VaultImportIssue[]; @@ -145,8 +161,7 @@ const splitTags = (raw: string | undefined): string[] => { .filter(Boolean); }; -const hostKey = (h: Pick) => - `${(h.protocol ?? "ssh").toLowerCase()}|${h.hostname.toLowerCase()}|${h.port}|${(h.username ?? "").toLowerCase()}`; +const hostKey = buildVaultHostMergeKey; const createHost = (input: { label?: string; @@ -154,27 +169,16 @@ const createHost = (input: { username?: string; password?: string; port?: number; - protocol?: Exclude; + protocol?: VaultHostDraftProtocol; group?: string; tags?: string[]; notes?: string; }): Host => { - const now = Date.now(); - const notes = input.notes?.trim() || undefined; - return { - id: crypto.randomUUID(), - label: input.label?.trim() || input.hostname, - hostname: input.hostname.trim(), - port: input.port ?? DEFAULT_SSH_PORT, - username: input.username?.trim() ?? "", - password: input.password || undefined, - group: normalizeGroupPath(input.group), - tags: (input.tags ?? []).filter(Boolean), - os: "linux", - protocol: input.protocol ?? "ssh", - createdAt: now, - ...(notes ? { notes } : {}), - }; + const built = buildVaultHostFromDraft(input); + if (!built.ok) { + throw new Error(built.error); + } + return built.host; }; const dedupeHosts = (hosts: Host[]): { hosts: Host[]; duplicates: number } => { @@ -933,3 +937,77 @@ export const importVaultHostsFromText = ( } } }; + +export function detectVaultImportFormat(text: string): VaultImportFormat | null { + const input = (text ?? "").trim(); + if (!input) return null; + + if ( + /Windows Registry Editor Version/i.test(input) + || /\\Software\\SimonTatham\\PuTTY\\Sessions/i.test(input) + ) { + return "putty"; + } + + if (/\[Bookmarks_\]/m.test(input) || /\[MobaXterm\]/i.test(input)) { + return "mobaxterm"; + } + + if (/^Host\s+/m.test(input) && (/^\s+HostName\s+/m.test(input) || /^\s+User\s+/m.test(input))) { + return "ssh_config"; + } + + if (/S:"Hostname"/m.test(input) && (/S:"Username"/m.test(input) || /D:"\[Sessions\]/i.test(input))) { + return "securecrt"; + } + + const firstLine = input.split(/\r?\n/, 1)[0] ?? ""; + if ( + /hostname|host(name)?|server/i.test(firstLine) + && (firstLine.includes(",") || firstLine.includes("\t")) + ) { + return "csv"; + } + + return null; +} + +export function applyVaultHostImport( + existingHosts: Host[], + existingGroups: string[], + importResult: VaultImportResult, + options?: { skipDuplicates?: boolean }, +): { + hosts: Host[]; + customGroups: string[]; + addedCount: number; + skippedExistingCount: number; +} { + const skipDuplicates = options?.skipDuplicates !== false; + const existingKeys = new Set(existingHosts.map(buildVaultHostMergeKey)); + let newHosts = importResult.hosts; + let skippedExistingCount = 0; + + if (skipDuplicates) { + newHosts = importResult.hosts.filter((host) => { + const duplicate = existingKeys.has(buildVaultHostMergeKey(host)); + if (duplicate) skippedExistingCount++; + return !duplicate; + }); + } + + const customGroups = Array.from( + new Set([ + ...existingGroups, + ...importResult.groups, + ...newHosts.map((host) => host.group).filter(Boolean), + ]), + ) as string[]; + + return { + hosts: [...existingHosts, ...newHosts].map(sanitizeHost), + customGroups, + addedCount: newHosts.length, + skippedExistingCount, + }; +} diff --git a/electron/bridges/aiBridge.cjs b/electron/bridges/aiBridge.cjs index c4b70bd99..ee72dd471 100644 --- a/electron/bridges/aiBridge.cjs +++ b/electron/bridges/aiBridge.cjs @@ -13,6 +13,7 @@ const { randomUUID } = require("node:crypto"); const { spawn, execFileSync } = require("node:child_process"); const fs = require("node:fs"); const { existsSync } = fs; +const { appendVaultAgentGuidance } = require("../shared/vaultAgentGuidance.cjs"); const mcpServerBridge = require("./mcpServerBridge.cjs"); const { getCliLauncherPath, TOOL_CLI_DISCOVERY_ENV_VAR } = require("../cli/discoveryPath.cjs"); @@ -22,6 +23,7 @@ const { toPublicUserSkillsStatus, } = require("./ai/userSkills.cjs"); const { registerProviderHandlers } = require("./aiBridge/providerHandlers.cjs"), { registerCattyExecHandlers } = require("./aiBridge/cattyExecHandlers.cjs"), { createAgentCliHelpers } = require("./aiBridge/agentCliHelpers.cjs"); +const { createVaultAgentBridge } = require("./aiBridge/vaultAgentBridge.cjs"); const { registerAgentDiscoveryHandlers } = require("./aiBridge/agentDiscoveryHandlers.cjs"), { registerAgentProcessHandlers } = require("./aiBridge/agentProcessHandlers.cjs"), { registerSdkStreamHandlers } = require("./aiBridge/sdk/sdkStreamHandlers.cjs"); const { probeClaudeAuth, probeCopilotAuth, probeCodexAuth, probeCodebuddyAuth } = require("./aiBridge/agentAuthProbes.cjs"); @@ -187,7 +189,7 @@ function buildExternalAgentSystemContext({ mode, chatSessionId, defaultTargetSes ); } - return ( + return appendVaultAgentGuidance( `${userSkillsPreamble}` + `[Context: You are inside Netcatty, a multi-session terminal manager. ` + `Use the "netcatty-remote-hosts" MCP tools to operate only on the terminal sessions exposed by Netcatty. ` + @@ -197,7 +199,7 @@ function buildExternalAgentSystemContext({ mode, chatSessionId, defaultTargetSes `Use terminal_execute only for commands likely to finish within about 60 seconds. ` + `For long-running commands such as builds, scans, follow/log streaming, watch commands, or anything likely to exceed 60 seconds on PTY-backed shell sessions, use terminal_start, then terminal_poll until completed is true. Reuse the returned nextOffset for the next poll. If terminal_poll reports outputTruncated=true, only the retained tail starting at outputBaseOffset is still available. Do not poll aggressively: wait at least about 30 seconds between polls, and increase the interval further when there is no new output, to avoid wasting tokens. As soon as completed is true, stop polling and analyze the result immediately. ` + `Use terminal_stop if you need to interrupt a started long-running command. Note: terminal_start requires a PTY-backed session; for sessions that only support exec-channel execution (no writable PTY), use terminal_execute instead. ` + - `For serial/raw sessions and network device sessions (deviceType: network), commands are sent as-is without shell wrapping and exit codes are unavailable. Use vendor CLI commands directly.]` + `For serial/raw sessions and network device sessions (deviceType: network), commands are sent as-is without shell wrapping and exit codes are unavailable. Use vendor CLI commands directly.]`, ); } @@ -219,6 +221,7 @@ let electronModule = null; let mainWebContentsId = null; let cliDiscoveryFilePath = null; let registeredContext = null; +let registeredVaultAgentBridge = null; // Active streaming requests (for cancellation) const activeStreams = new Map(); @@ -740,6 +743,23 @@ function registerHandlers(ipcMain) { Object.assign(context, createAgentCliHelpers(context)); registeredContext = context; + if (!registeredVaultAgentBridge) { + registeredVaultAgentBridge = createVaultAgentBridge({ + getMainWindowFn: () => { + try { + const windowManager = require("./windowManager.cjs"); + const mainWin = windowManager.getMainWindow?.(); + return (mainWin && !mainWin.isDestroyed()) ? mainWin : null; + } catch { + return null; + } + }, + validateSender, + }); + mcpServerBridge.setVaultAgentInvoker(registeredVaultAgentBridge.invokeVaultAgent); + } + registeredVaultAgentBridge.registerHandlers(ipcMain); + registerProviderHandlers(context); registerCattyExecHandlers(context); registerAgentDiscoveryHandlers(context); @@ -774,4 +794,10 @@ function cleanup() { mcpServerBridge.cleanup(); } -module.exports = { init, registerHandlers, cleanup }; +module.exports = { + init, + registerHandlers, + cleanup, + buildExternalAgentSystemContext, + buildExternalAgentContextualPrompt, +}; diff --git a/electron/bridges/aiBridge.externalContext.test.cjs b/electron/bridges/aiBridge.externalContext.test.cjs new file mode 100644 index 000000000..5925414a8 --- /dev/null +++ b/electron/bridges/aiBridge.externalContext.test.cjs @@ -0,0 +1,16 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { buildExternalAgentSystemContext } = require("./aiBridge.cjs"); + +test("buildExternalAgentSystemContext (MCP mode) includes vault host vs notes guidance", () => { + const context = buildExternalAgentSystemContext({ + mode: "mcp", + chatSessionId: "chat-1", + }); + assert.match(context, /vault_hosts_create/i); + assert.match(context, /NOT vault_notes_create/i); + assert.match(context, /do not silently create a Vault note/i); +}); diff --git a/electron/bridges/aiBridge.test.cjs b/electron/bridges/aiBridge.test.cjs index 06446d539..4d62550e9 100644 --- a/electron/bridges/aiBridge.test.cjs +++ b/electron/bridges/aiBridge.test.cjs @@ -21,6 +21,7 @@ function loadBridgeWithMocks(options = {}) { "./mcpServerBridge.cjs": { init() {}, setMainWindowGetter() {}, + setVaultAgentInvoker() {}, getOrCreateHost: async () => 4010, getScopedSessionIds: () => [], buildMcpServerConfig: () => ({ name: "netcatty-remote-hosts", type: "http", url: "http://127.0.0.1:4010" }), diff --git a/electron/bridges/aiBridge/agentProcessHandlers.cjs b/electron/bridges/aiBridge/agentProcessHandlers.cjs index 4ff47ec76..97feb98d4 100644 --- a/electron/bridges/aiBridge/agentProcessHandlers.cjs +++ b/electron/bridges/aiBridge/agentProcessHandlers.cjs @@ -69,6 +69,12 @@ function registerAgentProcessHandlers(ctx) { return { ok: true }; }); + ipcMain.handle("netcatty:ai:mcp:sync-permission-grants", async (event, { grants }) => { + if (!validateSenderOrSettings(event)) return { ok: false, error: "Unauthorized IPC sender" }; + mcpServerBridge.setPermissionGrants(grants); + return { ok: true, count: mcpServerBridge.getPermissionGrants().length }; + }); + // ── MCP Approval response (renderer → main) ── ipcMain.handle("netcatty:ai:mcp:approval-response", async (event, { approvalId, approved }) => { if (!validateSender(event)) return { ok: false, error: "Unauthorized IPC sender" }; diff --git a/electron/bridges/aiBridge/cattyExecHandlers.cjs b/electron/bridges/aiBridge/cattyExecHandlers.cjs index dc3ce2448..23d573e76 100644 --- a/electron/bridges/aiBridge/cattyExecHandlers.cjs +++ b/electron/bridges/aiBridge/cattyExecHandlers.cjs @@ -160,6 +160,33 @@ function registerCattyExecHandlers(ctx) { void mcpServerBridge.cancelSftpOpsForSession?.(chatSessionId); return { ok: true }; }); + + ipcMain.handle("netcatty:ai:chat-session:set-cancelled", async (event, { chatSessionId, cancelled }) => { + if (!validateSender(event)) { + return { ok: false, error: "Unauthorized IPC sender" }; + } + if (!chatSessionId || typeof chatSessionId !== "string") { + return { ok: false, error: "chatSessionId is required" }; + } + try { + return await mcpServerBridge.applyChatSessionCancelled(chatSessionId, cancelled !== false); + } catch (err) { + return { ok: false, error: err?.message || String(err) }; + } + }); + + ipcMain.handle("netcatty:ai:capability", async (event, { rpcMethod, params, chatSessionId }) => { + if (!validateSender(event)) { + return { ok: false, error: "Unauthorized IPC sender" }; + } + if (!rpcMethod || typeof rpcMethod !== "string") { + return { ok: false, error: "rpcMethod is required" }; + } + return mcpServerBridge.dispatchBuiltinRpc(rpcMethod, { + ...(params || {}), + chatSessionId, + }); + }); } } diff --git a/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs b/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs index 10633cd6d..c12f9bebf 100644 --- a/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs +++ b/electron/bridges/aiBridge/sdk/sdkStreamHandlers.cjs @@ -17,7 +17,18 @@ const VALID_BACKENDS = new Set(listBackends()); const MODEL_CACHE_TTL_MS = 5 * 60 * 1000; const MODEL_LIST_TIMEOUT_MS = 10000; const sdkModelCache = new Map(); -const SDK_SESSION_ID_PREFIX = "netcatty-sdk-session:"; +const { parseSdkSessionIdentity: parseSdkSessionIdentityPayload, SDK_SESSION_ID_PREFIX } = require("../../../shared/sdkSessionIdentity.cjs"); +const { isPathLikeCommand } = require("../../../shared/pathLikeCommand.cjs"); + +function parseSdkSessionIdentity(value) { + const parsed = parseSdkSessionIdentityPayload(value); + if (!parsed) return null; + return { + sessionId: parsed.id, + backendKey: parsed.backend, + binPath: parsed.binPath || "", + }; +} function buildSdkSessionKey(chatSessionId, backendKey, binPath) { return [ @@ -42,29 +53,6 @@ function normalizeSdkListModelsResult(raw) { return { currentModelId, models }; } -function isPathLikeCommand(command) { - const raw = String(command || "").trim(); - return Boolean(raw && (raw.includes("/") || raw.includes("\\") || /^[a-z]:/i.test(raw))); -} - -function parseSdkSessionIdentity(value) { - const raw = String(value || ""); - if (!raw.startsWith(SDK_SESSION_ID_PREFIX)) return null; - try { - const parsed = JSON.parse(decodeURIComponent(raw.slice(SDK_SESSION_ID_PREFIX.length))); - const sessionId = String(parsed?.id || "").trim(); - const backendKey = String(parsed?.backend || "").trim(); - if (!sessionId || !backendKey) return null; - return { - sessionId, - backendKey, - binPath: String(parsed?.binPath || ""), - }; - } catch { - return null; - } -} - function deleteSdkSessionKeysForChat(sdkSessionIds, chatSessionId) { const prefix = `${String(chatSessionId || "")}\u0000`; for (const key of sdkSessionIds.keys()) { diff --git a/electron/bridges/aiBridge/vaultAgentBridge.cjs b/electron/bridges/aiBridge/vaultAgentBridge.cjs new file mode 100644 index 000000000..90aedb64b --- /dev/null +++ b/electron/bridges/aiBridge/vaultAgentBridge.cjs @@ -0,0 +1,75 @@ +"use strict"; + +const crypto = require("node:crypto"); + +const VAULT_AGENT_TIMEOUT_MS = 15_000; +const pendingVaultRequests = new Map(); + +function createVaultAgentBridge({ getMainWindowFn, validateSender }) { + function registerHandlers(ipcMain) { + ipcMain.handle("netcatty:ai:vault-agent:response", (event, { requestId, result }) => { + if (!validateSender(event)) { + return { ok: false, error: "Unauthorized IPC sender" }; + } + if (!requestId || typeof requestId !== "string") { + return { ok: false, error: "requestId is required" }; + } + const entry = pendingVaultRequests.get(requestId); + if (!entry) { + return { ok: false, error: "Unknown or expired vault agent request." }; + } + clearTimeout(entry.timer); + pendingVaultRequests.delete(requestId); + entry.resolve(result); + return { ok: true }; + }); + } + + async function invokeVaultAgent(op, params = {}, options = {}) { + const mainWin = typeof getMainWindowFn === "function" ? getMainWindowFn() : null; + if (!mainWin || mainWin.isDestroyed()) { + return { + ok: false, + error: "No active Netcatty window is available for vault access.", + }; + } + + const requestId = crypto.randomUUID(); + return new Promise((resolve) => { + const timer = setTimeout(() => { + if (!pendingVaultRequests.has(requestId)) return; + pendingVaultRequests.delete(requestId); + resolve({ + ok: false, + error: "Vault agent bridge timed out waiting for renderer.", + }); + }, options.timeoutMs ?? VAULT_AGENT_TIMEOUT_MS); + + pendingVaultRequests.set(requestId, { resolve, timer }); + try { + mainWin.webContents.send("netcatty:ai:vault-agent:request", { + requestId, + op, + params, + }); + } catch (err) { + clearTimeout(timer); + pendingVaultRequests.delete(requestId); + resolve({ + ok: false, + error: err?.message || String(err), + }); + } + }); + } + + return { + registerHandlers, + invokeVaultAgent, + }; +} + +module.exports = { + createVaultAgentBridge, + VAULT_AGENT_TIMEOUT_MS, +}; diff --git a/electron/bridges/mcpServerBridge.cjs b/electron/bridges/mcpServerBridge.cjs index c9204b40b..2a66e94c3 100644 --- a/electron/bridges/mcpServerBridge.cjs +++ b/electron/bridges/mcpServerBridge.cjs @@ -13,10 +13,12 @@ const path = require("node:path"); const { existsSync } = require("node:fs"); const { toUnpackedAsarPath, getFreshIdlePrompt } = require("./ai/shellUtils.cjs"); +const { appendVaultAgentGuidance } = require("../shared/vaultAgentGuidance.cjs"); const { execViaPty, startPtyJob, execViaChannel, execViaRawPty } = require("./ai/ptyExec.cjs"); const { safeSend } = require("./ipcUtils.cjs"); const { getCliDiscoveryFilePath } = require("../cli/discoveryPath.cjs"); const sftpBridge = require("./sftpBridge.cjs"); +const portForwardingBridge = require("./portForwardingBridge.cjs"); const DEBUG_MCP = process.env.NETCATTY_MCP_DEBUG === "1"; @@ -55,6 +57,9 @@ let maxIterations = 20; // Permission mode: 'observer' | 'confirm' | 'autonomous' (synced from user settings) let permissionMode = "confirm"; +// Cached permission grants synced from renderer (confirm-mode memory table) +let permissionGrantsSnapshot = []; + // Track active PTY executions for cancellation const activePtyExecs = new Map(); // marker → { ptyStream, cleanup } const cancelledChatSessions = new Set(); @@ -89,7 +94,8 @@ function setMainWindowGetter(fn) { // after 120s"). Keep the Netcatty-side approval window below that with a small // buffer so a stale approval cannot still be accepted after the agent has // already timed out and abandoned the call. -const APPROVAL_TIMEOUT_MS = 110 * 1000; // 110 seconds +const { MCP_APPROVAL_TIMEOUT_MS } = require("../shared/approvalConstants.cjs"); +const APPROVAL_TIMEOUT_MS = MCP_APPROVAL_TIMEOUT_MS; function requestApprovalFromRenderer(toolName, args, chatSessionId) { return new Promise((resolve) => { @@ -424,6 +430,9 @@ function updateSessionMetadata(sessionList, chatSessionId) { shellType: s.shellType || "", deviceType: s.deviceType || "", connected: s.connected !== false, + hostId: s.hostId || "", + hostChain: Array.isArray(s.hostChain) ? s.hostChain : [], + activePortForwards: Array.isArray(s.activePortForwards) ? s.activePortForwards : [], }); } @@ -782,10 +791,41 @@ async function handleMessage(socket, line) { const { evaluateRpcPermission, + evaluatePermissionWithGrants, USER_DENIED_MESSAGE, } = require("../capabilities/policy.cjs"); const { CAPABILITY_SURFACES } = require("../capabilities/constants.cjs"); const { getCapabilityByRpcMethod } = require("../capabilities/registry.cjs"); +const { + createCapabilityRpcDispatcher, + UNROUTED, +} = require("./mcpServerBridge/capabilityRpcDispatch.cjs"); +const { buildBuiltinRpcHandlerRegistry } = require("./mcpServerBridge/builtinRpcHandlers.cjs"); + +let invokeVaultAgentFn = null; + +function setVaultAgentInvoker(fn) { + invokeVaultAgentFn = typeof fn === "function" ? fn : null; +} + +const dispatchCapabilityRpc = createCapabilityRpcDispatcher({ + invokeVaultAgent: (...args) => { + if (typeof invokeVaultAgentFn !== "function") { + return Promise.resolve({ ok: false, error: "Vault agent bridge is unavailable." }); + } + return invokeVaultAgentFn(...args); + }, + evaluatePermissionWithGrants, + get permissionMode() { + return permissionMode; + }, + get permissionGrantsSnapshot() { + return permissionGrantsSnapshot; + }, + isChatSessionCancelled, + requestApprovalFromRenderer, + USER_DENIED_MESSAGE, +}); /** * Validate that a sessionId is allowed in the current scope. @@ -813,15 +853,53 @@ function validateSessionScope(sessionId, chatSessionId, explicitScopedIds = null return null; } +let builtinRpcHandlerRegistry = null; + +function getBuiltinRpcHandlerRegistry() { + if (!builtinRpcHandlerRegistry) { + builtinRpcHandlerRegistry = buildBuiltinRpcHandlerRegistry({ + "session.environment": handleGetContext, + "meta.status": handleGetStatus, + "attachment.list": handleListAttachments, + "attachment.read": handleReadAttachment, + "terminal.execute": handleExec, + "sftp.list": handleSftpList, + "sftp.read": handleSftpRead, + "sftp.write": handleSftpWrite, + "sftp.download": handleSftpDownload, + "sftp.upload": handleSftpUpload, + "sftp.mkdir": handleSftpMkdir, + "sftp.delete": handleSftpDelete, + "sftp.rename": handleSftpRename, + "sftp.stat": handleSftpStat, + "sftp.chmod": handleSftpChmod, + "sftp.home": handleSftpHome, + "session.cancel": handleSetCancelled, + "terminal.start": handleJobStart, + "terminal.poll": handleJobPoll, + "terminal.stop": handleJobStop, + }); + } + return builtinRpcHandlerRegistry; +} + async function dispatch(method, params) { debugLog("dispatch", { method, params, permissionMode }); + + if (!method.startsWith("netcatty/")) { + const capabilityResult = await dispatchCapabilityRpc(method, params || {}); + if (capabilityResult !== UNROUTED) { + return capabilityResult; + } + } + const capability = getCapabilityByRpcMethod(method, CAPABILITY_SURFACES.BUILTIN); const sessionWriteLockId = (capability?.id === "terminal.execute" || capability?.id === "terminal.start") ? params?.sessionId : null; pruneCompletedBackgroundJobs(); - const permission = evaluateRpcPermission({ + const permission = evaluatePermissionWithGrants({ rpcMethod: method, surface: CAPABILITY_SURFACES.BUILTIN, permissionMode, @@ -829,7 +907,7 @@ async function dispatch(method, params) { context: { chatSessionCancelled: isChatSessionCancelled(params?.chatSessionId), }, - }); + }, permissionGrantsSnapshot); if (!permission.allowed) { return { ok: false, error: permission.error }; } @@ -870,50 +948,11 @@ async function dispatch(method, params) { return { ok: false, error: USER_DENIED_MESSAGE }; } } - switch (method) { - case "netcatty/getContext": - return handleGetContext(params); - case "netcatty/getStatus": - return handleGetStatus(); - case "netcatty/listAttachments": - return handleListAttachments(params); - case "netcatty/readAttachment": - return handleReadAttachment(params); - case "netcatty/exec": - return handleExec(params); - case "netcatty/sftp/list": - return handleSftpList(params); - case "netcatty/sftp/read": - return handleSftpRead(params); - case "netcatty/sftp/write": - return handleSftpWrite(params); - case "netcatty/sftp/download": - return handleSftpDownload(params); - case "netcatty/sftp/upload": - return handleSftpUpload(params); - case "netcatty/sftp/mkdir": - return handleSftpMkdir(params); - case "netcatty/sftp/delete": - return handleSftpDelete(params); - case "netcatty/sftp/rename": - return handleSftpRename(params); - case "netcatty/sftp/stat": - return handleSftpStat(params); - case "netcatty/sftp/chmod": - return handleSftpChmod(params); - case "netcatty/sftp/home": - return handleSftpHome(params); - case "netcatty/setCancelled": - return handleSetCancelled(params); - case "netcatty/jobStart": - return handleJobStart(params); - case "netcatty/jobPoll": - return handleJobPoll(params); - case "netcatty/jobStop": - return handleJobStop(params); - default: - throw new Error(`Unknown method: ${method}`); + const handler = getBuiltinRpcHandlerRegistry().get(method); + if (!handler) { + throw new Error(`Unknown method: ${method}`); } + return handler(params); } finally { if (sessionWriteLockId) { pendingSessionWriteApprovals.delete(sessionWriteLockId); @@ -923,7 +962,7 @@ async function dispatch(method, params) { // ── Handler: getContext ── -function handleGetContext(params) { +async function handleGetContext(params) { debugLog("handleGetContext:start", { params, sessionCount: sessions?.size || 0 }); if (!sessions) return { hosts: [], instructions: "No sessions available." }; @@ -971,19 +1010,33 @@ function handleGetContext(params) { shellType: meta.shellType || session.shellKind || "", deviceType: meta.deviceType || "", connected: meta.connected !== undefined ? meta.connected : !!(session.sshClient || session.conn || ptyStream || session.serialPort), + hostId: meta.hostId || "", + hostChain: meta.hostChain || [], + activePortForwards: meta.activePortForwards || [], }); } + let activePortForwardTunnels = []; + try { + activePortForwardTunnels = await portForwardingBridge.listPortForwards() || []; + } catch { + activePortForwardTunnels = []; + } + return { environment: "netcatty-terminal", - description: "You are operating inside Netcatty, a multi-session terminal manager. " + + description: appendVaultAgentGuidance( + "You are operating inside Netcatty, a multi-session terminal manager. " + "The available sessions may be remote hosts, local terminals, Mosh-backed shells, or serial port connections (network devices, embedded systems). " + "Use the provided tools to execute commands through the sessions exposed by Netcatty. " + "Serial sessions (protocol: serial, shellType: raw) do not run a standard shell — commands are sent as-is. " + "Network device sessions (deviceType: network) use vendor CLIs (Huawei VRP, Cisco IOS, etc.) — commands are sent as-is without shell wrapping, and exit codes are unavailable. " + + "Vault snippets, port forwarding rules/tunnels, and SFTP read/write tools are available when exposed in the tool list. " + "Always prefer these tools over suggesting the user to do things manually.", + ), hosts, hostCount: hosts.length, + activePortForwardTunnels, }; } @@ -1007,13 +1060,19 @@ function handleGetStatus() { }; } -async function handleSetCancelled(params) { - const chatSessionId = params?.chatSessionId; - const cancelled = params?.cancelled !== false; +function setPermissionGrants(grants) { + const { sanitizePermissionGrants } = require("../shared/permissionGrants.cjs"); + permissionGrantsSnapshot = sanitizePermissionGrants(grants); +} + +function getPermissionGrants() { + return permissionGrantsSnapshot; +} + +function applyChatSessionCancelled(chatSessionId, cancelled) { if (!chatSessionId || typeof chatSessionId !== "string") { throw new Error("chatSessionId is required"); } - if (cancelled) { setChatSessionCancelled(chatSessionId, true); cancelPtyExecsForSession(chatSessionId); @@ -1023,14 +1082,19 @@ async function handleSetCancelled(params) { } else { setChatSessionCancelled(chatSessionId, false); } - return { ok: true, chatSessionId, - cancelled, + cancelled: !!cancelled, }; } +async function handleSetCancelled(params) { + const chatSessionId = params?.chatSessionId; + const cancelled = params?.cancelled !== false; + return applyChatSessionCancelled(chatSessionId, cancelled); +} + const { createSftpHandlerApi } = require("./mcpServerBridge/sftpHandlers.cjs"); const sftpHandlerApi = createSftpHandlerApi({ get commandTimeoutMs() { return commandTimeoutMs; }, @@ -1096,7 +1160,10 @@ module.exports = { getMaxIterations, setPermissionMode, getPermissionMode, + setPermissionGrants, + getPermissionGrants, setChatSessionCancelled, + applyChatSessionCancelled, checkCommandSafety, updateSessionMetadata, updateAttachmentMetadata, @@ -1115,9 +1182,11 @@ module.exports = { cleanup, shutdownHost, setMainWindowGetter, + setVaultAgentInvoker, resolveApprovalFromRenderer, clearPendingApprovals, reserveSessionExecution, releaseSessionExecution, getSessionBusyError, + dispatchBuiltinRpc: dispatch, }; diff --git a/electron/bridges/mcpServerBridge/builtinRpcHandlers.cjs b/electron/bridges/mcpServerBridge/builtinRpcHandlers.cjs new file mode 100644 index 000000000..a3963862a --- /dev/null +++ b/electron/bridges/mcpServerBridge/builtinRpcHandlers.cjs @@ -0,0 +1,35 @@ +"use strict"; + +const { getCapabilityById } = require("../../capabilities/registry.cjs"); + +/** + * Build rpcMethod → handler map from capability-id-keyed handlers. + * Keeps dispatch aligned with catalog builtin RPC names. + * + * @param {Record Promise | unknown>} handlersByCapabilityId + * @returns {{ get: (rpcMethod: string) => ((params: object) => unknown) | null, has: (rpcMethod: string) => boolean }} + */ +function buildBuiltinRpcHandlerRegistry(handlersByCapabilityId) { + const byRpcMethod = new Map(); + + for (const [capabilityId, handler] of Object.entries(handlersByCapabilityId)) { + if (typeof handler !== "function") continue; + const capability = getCapabilityById(capabilityId); + const rpcMethod = capability?.surfaces?.builtin?.rpcMethod; + if (!rpcMethod) continue; + byRpcMethod.set(rpcMethod, handler); + } + + return { + get(rpcMethod) { + return byRpcMethod.get(rpcMethod) || null; + }, + has(rpcMethod) { + return byRpcMethod.has(rpcMethod); + }, + }; +} + +module.exports = { + buildBuiltinRpcHandlerRegistry, +}; diff --git a/electron/bridges/mcpServerBridge/builtinRpcHandlers.test.cjs b/electron/bridges/mcpServerBridge/builtinRpcHandlers.test.cjs new file mode 100644 index 000000000..2d0b5f944 --- /dev/null +++ b/electron/bridges/mcpServerBridge/builtinRpcHandlers.test.cjs @@ -0,0 +1,67 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { CAPABILITY_STATUS } = require("../../capabilities/constants.cjs"); +const { ALL_CAPABILITIES } = require("../../capabilities/catalog/index.cjs"); +const { buildBuiltinRpcHandlerRegistry } = require("./builtinRpcHandlers.cjs"); + +/** Capability ids wired in mcpServerBridge.getBuiltinRpcHandlerRegistry(). */ +const MCP_BRIDGE_BUILTIN_CAPABILITY_IDS = [ + "session.environment", + "meta.status", + "attachment.list", + "attachment.read", + "terminal.execute", + "sftp.list", + "sftp.read", + "sftp.write", + "sftp.download", + "sftp.upload", + "sftp.mkdir", + "sftp.delete", + "sftp.rename", + "sftp.stat", + "sftp.chmod", + "sftp.home", + "session.cancel", + "terminal.start", + "terminal.poll", + "terminal.stop", +]; + +test("buildBuiltinRpcHandlerRegistry maps catalog builtin rpcMethod to handlers", () => { + const handlersByCapabilityId = Object.fromEntries( + MCP_BRIDGE_BUILTIN_CAPABILITY_IDS.map((id) => [id, async () => ({ ok: true, id })]), + ); + const registry = buildBuiltinRpcHandlerRegistry(handlersByCapabilityId); + + for (const capabilityId of MCP_BRIDGE_BUILTIN_CAPABILITY_IDS) { + const capability = ALL_CAPABILITIES.find((entry) => entry.id === capabilityId); + assert.ok(capability, `missing catalog entry for ${capabilityId}`); + const rpcMethod = capability.surfaces?.builtin?.rpcMethod; + assert.ok(rpcMethod, `missing builtin rpcMethod for ${capabilityId}`); + assert.equal(typeof registry.get(rpcMethod), "function", rpcMethod); + } +}); + +test("every implemented netcatty/* builtin rpc has a bridge handler", () => { + const handlersByCapabilityId = Object.fromEntries( + MCP_BRIDGE_BUILTIN_CAPABILITY_IDS.map((id) => [id, async () => ({ ok: true })]), + ); + const registry = buildBuiltinRpcHandlerRegistry(handlersByCapabilityId); + + const implementedBuiltinRpcMethods = ALL_CAPABILITIES + .filter((capability) => capability.status === CAPABILITY_STATUS.IMPLEMENTED) + .map((capability) => capability.surfaces?.builtin?.rpcMethod) + .filter((rpcMethod) => typeof rpcMethod === "string" && rpcMethod.startsWith("netcatty/")); + + const uniqueRpcMethods = [...new Set(implementedBuiltinRpcMethods)]; + for (const rpcMethod of uniqueRpcMethods) { + assert.equal( + registry.has(rpcMethod), + true, + `no handler registered for ${rpcMethod}`, + ); + } +}); diff --git a/electron/bridges/mcpServerBridge/capabilityRpcDispatch.cjs b/electron/bridges/mcpServerBridge/capabilityRpcDispatch.cjs new file mode 100644 index 000000000..365be4ceb --- /dev/null +++ b/electron/bridges/mcpServerBridge/capabilityRpcDispatch.cjs @@ -0,0 +1,128 @@ +"use strict"; + +const { CAPABILITY_STATUS, CAPABILITY_SURFACES } = require("../../capabilities/constants.cjs"); +const { getCapabilityByRpcMethod } = require("../../capabilities/registry.cjs"); +const { getMcpToolNameForRpcMethod } = require("../../capabilities/adapters/mcpAdapter.cjs"); +const { createVaultService } = require("../../capabilities/services/vaultService.cjs"); +const { createPortForwardService } = require("../../capabilities/services/portforwardService.cjs"); + +const UNROUTED = Symbol("capability-rpc-unrouted"); + +const SERVICE_BINDINGS = Object.freeze({ + "vault.host.get": { domain: "vault", method: "getHost" }, + "vault.host.list": { domain: "vault", method: "listHosts" }, + "vault.hosts.create": { domain: "vault", method: "createHosts" }, + "vault.host.import": { domain: "vault", method: "importHosts" }, + "vault.host.notes.get": { domain: "vault", method: "getHostNotes" }, + "vault.host.notes.set": { domain: "vault", method: "setHostNotes" }, + "vault.note.list": { domain: "vault", method: "listNotes" }, + "vault.note.get": { domain: "vault", method: "getNote" }, + "vault.note.create": { domain: "vault", method: "createNote" }, + "vault.note.update": { domain: "vault", method: "updateNote" }, + "vault.snippets.list": { domain: "vault", method: "listSnippets" }, + "vault.snippets.get": { domain: "vault", method: "getSnippet" }, + "vault.snippets.run": { domain: "vault", method: "runSnippet" }, + "portforward.rules.list": { domain: "portforward", method: "listRules" }, + "portforward.tunnels.list": { domain: "portforward", method: "listTunnels" }, + "portforward.start": { domain: "portforward", method: "start" }, + "portforward.stop": { domain: "portforward", method: "stop" }, +}); + +function resolveCapabilitySurface(rpcMethod) { + for (const surface of [ + CAPABILITY_SURFACES.PUBLIC, + CAPABILITY_SURFACES.GLOBAL, + CAPABILITY_SURFACES.BUILTIN, + ]) { + if (rpcMethod.startsWith("netcatty/") && surface !== CAPABILITY_SURFACES.BUILTIN) { + continue; + } + const capability = getCapabilityByRpcMethod(rpcMethod, surface); + if (capability) { + return { capability, surface }; + } + } + return null; +} + +function createCapabilityRpcDispatcher(deps) { + const { + invokeVaultAgent, + evaluatePermissionWithGrants, + isChatSessionCancelled, + requestApprovalFromRenderer, + USER_DENIED_MESSAGE, + } = deps; + + const vaultService = createVaultService({ invokeVaultAgent }); + const portforwardService = createPortForwardService({ invokeVaultAgent }); + const services = { + vault: vaultService, + portforward: portforwardService, + }; + + return async function dispatchCapabilityRpc(rpcMethod, params = {}) { + if (typeof rpcMethod !== "string" || rpcMethod.startsWith("netcatty/")) { + return UNROUTED; + } + + const resolved = resolveCapabilitySurface(rpcMethod); + if (!resolved) { + return UNROUTED; + } + + const { capability, surface } = resolved; + if (capability.status !== CAPABILITY_STATUS.IMPLEMENTED) { + return { + ok: false, + code: "CAPABILITY_NOT_IMPLEMENTED", + error: `Capability "${capability.id}" is not implemented yet.`, + }; + } + + const binding = SERVICE_BINDINGS[capability.id]; + if (!binding) { + return UNROUTED; + } + + const permission = evaluatePermissionWithGrants({ + rpcMethod, + surface, + permissionMode: deps.permissionMode, + params, + context: { + chatSessionCancelled: isChatSessionCancelled(params?.chatSessionId), + }, + }, deps.permissionGrantsSnapshot); + + if (!permission.allowed) { + return { ok: false, error: permission.error }; + } + + if (permission.requiresApproval) { + const { chatSessionId, ...toolArgs } = params || {}; + const toolName = getMcpToolNameForRpcMethod(rpcMethod, surface) || capability.id; + const approved = await requestApprovalFromRenderer(toolName, toolArgs, chatSessionId); + if (!approved) { + return { ok: false, error: USER_DENIED_MESSAGE }; + } + } + + const service = services[binding.domain]; + const handler = service?.[binding.method]; + if (typeof handler !== "function") { + return { + ok: false, + error: `Capability handler "${capability.id}" is unavailable.`, + }; + } + + return handler(params); + }; +} + +module.exports = { + UNROUTED, + createCapabilityRpcDispatcher, + SERVICE_BINDINGS, +}; diff --git a/electron/bridges/mcpServerBridge/capabilityRpcDispatch.test.cjs b/electron/bridges/mcpServerBridge/capabilityRpcDispatch.test.cjs new file mode 100644 index 000000000..9d0e809ac --- /dev/null +++ b/electron/bridges/mcpServerBridge/capabilityRpcDispatch.test.cjs @@ -0,0 +1,188 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { createCapabilityRpcDispatcher, UNROUTED } = require("./capabilityRpcDispatch.cjs"); +const { CAPABILITY_SURFACES, PERMISSION_MODES } = require("../../capabilities/constants.cjs"); + +function createTestDispatcher(overrides = {}) { + const invokeVaultAgent = overrides.invokeVaultAgent || (async (op, params) => ({ + ok: true, + op, + params, + })); + const requestApprovalFromRenderer = overrides.requestApprovalFromRenderer + || (async () => true); + + return createCapabilityRpcDispatcher({ + invokeVaultAgent, + evaluatePermissionWithGrants: overrides.evaluatePermissionWithGrants || ((input, grants) => ({ + allowed: true, + requiresApproval: false, + grants, + ...input, + })), + permissionMode: overrides.permissionMode || PERMISSION_MODES.CONFIRM, + permissionGrantsSnapshot: [], + isChatSessionCancelled: () => false, + requestApprovalFromRenderer, + USER_DENIED_MESSAGE: "User denied the operation.", + ...overrides, + }); +} + +test("dispatchCapabilityRpc returns UNROUTED for netcatty builtin methods", async () => { + const dispatch = createTestDispatcher(); + const result = await dispatch("netcatty/exec", { chatSessionId: "chat-1" }); + assert.equal(result, UNROUTED); +}); + +test("dispatchCapabilityRpc routes vault host notes get to vault service", async () => { + let invokedOp = null; + const dispatch = createTestDispatcher({ + invokeVaultAgent: async (op, params) => { + invokedOp = op; + return { ok: true, hostId: params.hostId, notes: "notes" }; + }, + }); + + const result = await dispatch("vault/host/notes/get", { hostId: "host-1" }); + assert.equal(invokedOp, "host.notes.get"); + assert.equal(result.ok, true); + assert.equal(result.notes, "notes"); +}); + +test("dispatchCapabilityRpc routes public vault host notes set through approval", async () => { + const approvalCalls = []; + const dispatch = createTestDispatcher({ + evaluatePermissionWithGrants: () => ({ + allowed: true, + requiresApproval: true, + }), + requestApprovalFromRenderer: async (toolName, args, chatSessionId) => { + approvalCalls.push({ toolName, args, chatSessionId }); + return true; + }, + invokeVaultAgent: async (op, params) => ({ + ok: true, + op, + hostId: params.hostId, + notes: params.notes, + }), + }); + + const result = await dispatch("public/vault/hostNotes/set", { + chatSessionId: "chat-1", + hostId: "host-1", + notes: "updated", + }); + + assert.equal(approvalCalls.length, 1); + assert.equal(approvalCalls[0].toolName, "host_notes_set"); + assert.equal(result.ok, true); + assert.equal(result.notes, "updated"); +}); + +test("dispatchCapabilityRpc denies public vault host notes set when approval rejected", async () => { + const dispatch = createTestDispatcher({ + evaluatePermissionWithGrants: () => ({ + allowed: true, + requiresApproval: true, + }), + requestApprovalFromRenderer: async () => false, + }); + + const result = await dispatch("public/vault/hostNotes/set", { + chatSessionId: "chat-1", + hostId: "host-1", + notes: "updated", + }); + + assert.equal(result.ok, false); + assert.match(result.error, /denied/i); +}); + +test("dispatchCapabilityRpc routes vault hosts create to vault service", async () => { + let invokedOp = null; + const dispatch = createTestDispatcher({ + invokeVaultAgent: async (op, params) => { + invokedOp = op; + return { ok: true, addedCount: 1, previewHosts: [] , params }; + }, + }); + + const result = await dispatch("vault/hosts/create", { + hosts: JSON.stringify([{ hostname: "10.2.0.209", username: "root" }]), + dryRun: "true", + }); + assert.equal(invokedOp, "hosts.create"); + assert.equal(result.ok, true); +}); + +test("dispatchCapabilityRpc routes vault hosts import to vault service", async () => { + let invokedOp = null; + const dispatch = createTestDispatcher({ + invokeVaultAgent: async (op) => { + invokedOp = op; + return { ok: true, addedCount: 0 }; + }, + }); + + const result = await dispatch("vault/hosts/import", { + format: "csv", + text: "hostname,username\n10.0.0.1,root\n", + dryRun: "true", + }); + assert.equal(invokedOp, "host.import"); + assert.equal(result.ok, true); +}); + +test("dispatchCapabilityRpc routes portforward start to portforward service", async () => { + let invokedOp = null; + const dispatch = createTestDispatcher({ + invokeVaultAgent: async (op, params) => { + invokedOp = op; + return { ok: true, ruleId: params.ruleId, status: "active" }; + }, + }); + + const result = await dispatch("portforward/start", { + chatSessionId: "chat-1", + ruleId: "rule-1", + }); + assert.equal(invokedOp, "portforward.start"); + assert.equal(result.ok, true); + assert.equal(result.ruleId, "rule-1"); +}); + +test("dispatchCapabilityRpc reads permissionMode from deps on each call", async () => { + const seenModes = []; + const mutableDeps = { permissionMode: PERMISSION_MODES.CONFIRM }; + const liveDispatch = createCapabilityRpcDispatcher({ + invokeVaultAgent: async () => ({ ok: true }), + evaluatePermissionWithGrants: (input) => { + seenModes.push(input.permissionMode); + return { allowed: true, requiresApproval: false }; + }, + get permissionMode() { + return mutableDeps.permissionMode; + }, + permissionGrantsSnapshot: [], + isChatSessionCancelled: () => false, + requestApprovalFromRenderer: async () => true, + USER_DENIED_MESSAGE: "User denied the operation.", + }); + + await liveDispatch("vault/host/get", { hostId: "host-1" }); + mutableDeps.permissionMode = PERMISSION_MODES.AUTONOMOUS; + await liveDispatch("vault/host/get", { hostId: "host-2" }); + + assert.deepEqual(seenModes, [PERMISSION_MODES.CONFIRM, PERMISSION_MODES.AUTONOMOUS]); +}); + +test("implemented vault capabilities do not return CAPABILITY_NOT_IMPLEMENTED", async () => { + const dispatch = createTestDispatcher(); + const result = await dispatch("vault/host/get", { hostId: "host-1" }); + assert.notEqual(result.code, "CAPABILITY_NOT_IMPLEMENTED"); +}); diff --git a/electron/capabilities/adapters/cliAdapter.cjs b/electron/capabilities/adapters/cliAdapter.cjs index 31dba5f88..31a70c874 100644 --- a/electron/capabilities/adapters/cliAdapter.cjs +++ b/electron/capabilities/adapters/cliAdapter.cjs @@ -5,11 +5,39 @@ const { getCapabilityByCliCommand, listCapabilities, } = require("../registry.cjs"); +const { TOOL_INPUT_FIELDS } = require("../schemas/toolInputs.cjs"); + +/** Maps TOOL_INPUT_FIELDS keys to CLI flag names and opts property names. */ +const CLI_FIELD_BINDINGS = Object.freeze({ + hostId: { flag: "--host-id", optKey: "hostId" }, + snippetId: { flag: "--snippet-id", optKey: "snippetId" }, + ruleId: { flag: "--rule-id", optKey: "ruleId" }, + notes: { flag: "--notes", optKey: "notes" }, + sessionId: { flag: "--session", optKey: "sessionId" }, + variables: { flag: "--variables", optKey: "variables" }, + path: { flag: "--remote-path", optKey: "remotePath" }, + remotePath: { flag: "--remote-path", optKey: "remotePath" }, + localPath: { flag: "--local-path", optKey: "localPath" }, + oldPath: { flag: "--old-remote-path", optKey: "oldRemotePath" }, + newPath: { flag: "--new-remote-path", optKey: "newRemotePath" }, + content: { flag: "--content", optKey: "content" }, + mode: { flag: "--mode", optKey: "mode" }, + command: { flag: "--", optKey: "command" }, + jobId: { flag: "--job", optKey: "jobId" }, + offset: { flag: "--offset", optKey: "offset" }, +}); + +function resolveCliRpcMethod(capability) { + if (!capability) return null; + return capability.surfaces?.[CAPABILITY_SURFACES.BUILTIN]?.rpcMethod + || capability.surfaces?.[CAPABILITY_SURFACES.GLOBAL]?.rpcMethod + || capability.surfaces?.[CAPABILITY_SURFACES.PUBLIC]?.rpcMethod + || null; +} function getCliRpcMethod(commandParts) { const capability = getCapabilityByCliCommand(commandParts); - if (!capability) return null; - return capability.surfaces?.[CAPABILITY_SURFACES.BUILTIN]?.rpcMethod || null; + return resolveCliRpcMethod(capability); } function listCliCapabilities(options = {}) { @@ -25,7 +53,7 @@ function listCliCapabilities(options = {}) { status: capability.status, description: capability.description, command: capability.surfaces[surface].command, - rpcMethod: capability.surfaces?.[CAPABILITY_SURFACES.BUILTIN]?.rpcMethod || null, + rpcMethod: resolveCliRpcMethod(capability), policy: capability.policy, })); } @@ -37,8 +65,53 @@ function formatCliHelpLines(options = {}) { }); } +function buildCatalogCliParams(capabilityId, opts, createError) { + const fields = TOOL_INPUT_FIELDS[capabilityId]; + if (!fields) { + return {}; + } + + const params = {}; + for (const [fieldName, fieldDef] of Object.entries(fields)) { + const binding = CLI_FIELD_BINDINGS[fieldName]; + if (!binding) continue; + + let value = opts[binding.optKey]; + if (fieldName === "command" && Array.isArray(value)) { + value = value.length === 1 ? value[0] : null; + } + if (fieldName === "variables" && typeof value === "string" && value.trim()) { + try { + value = JSON.parse(value); + } catch { + throw createError("INVALID_ARGUMENT", `--variables must be valid JSON for ${capabilityId}.`); + } + } + if (fieldName === "offset" && value != null) { + value = Number(value); + } + + if (value == null || value === "") { + if (!fieldDef.optional) { + throw createError( + "INVALID_ARGUMENT", + `Missing required ${binding.flag} for ${capabilityId}.`, + ); + } + continue; + } + + params[fieldName] = value; + } + + return params; +} + module.exports = { + CLI_FIELD_BINDINGS, + buildCatalogCliParams, getCliRpcMethod, listCliCapabilities, formatCliHelpLines, + resolveCliRpcMethod, }; diff --git a/electron/capabilities/adapters/cliAdapter.test.cjs b/electron/capabilities/adapters/cliAdapter.test.cjs index a0ba57dfb..2afa27685 100644 --- a/electron/capabilities/adapters/cliAdapter.test.cjs +++ b/electron/capabilities/adapters/cliAdapter.test.cjs @@ -3,22 +3,59 @@ const test = require("node:test"); const assert = require("node:assert/strict"); -const { getCliRpcMethod, listCliCapabilities } = require("./cliAdapter.cjs"); +const { + getCliRpcMethod, + listCliCapabilities, + buildCatalogCliParams, +} = require("./cliAdapter.cjs"); const { CAPABILITY_STATUS } = require("../constants.cjs"); -test("getCliRpcMethod resolves implemented cli commands to builtin rpc methods", () => { +function fakeCreateError(code, message) { + const err = new Error(message); + err.code = code; + return err; +} + +test("getCliRpcMethod resolves implemented cli commands to rpc methods", () => { assert.equal(getCliRpcMethod(["exec"]), "netcatty/exec"); assert.equal(getCliRpcMethod(["sftp", "list"]), "netcatty/sftp/list"); + assert.equal(getCliRpcMethod(["vault", "host", "get"]), "vault/host/get"); + assert.equal(getCliRpcMethod(["portforward", "rules", "list"]), "portforward/rules/list"); assert.equal(getCliRpcMethod(["capabilities"]), null); }); test("listCliCapabilities returns implemented commands by default", () => { const entries = listCliCapabilities(); assert.ok(entries.some((entry) => entry.id === "terminal.execute")); + assert.ok(entries.some((entry) => entry.id === "vault.host.get")); assert.ok(entries.every((entry) => entry.status === CAPABILITY_STATUS.IMPLEMENTED)); + assert.ok(entries.every((entry) => entry.rpcMethod)); }); test("listCliCapabilities can include planned commands", () => { const entries = listCliCapabilities({ status: CAPABILITY_STATUS.PLANNED }); - assert.ok(entries.some((entry) => entry.id === "vault.host.notes.get")); + assert.ok(entries.length >= 0); +}); + +test("buildCatalogCliParams maps vault host get flags", () => { + const params = buildCatalogCliParams("vault.host.get", { hostId: "host-1" }, fakeCreateError); + assert.deepEqual(params, { hostId: "host-1" }); +}); + +test("buildCatalogCliParams parses snippet variables JSON", () => { + const params = buildCatalogCliParams("vault.snippets.run", { + snippetId: "snip-1", + sessionId: "sess-1", + variables: "{\"name\":\"prod\"}", + }, fakeCreateError); + assert.equal(params.snippetId, "snip-1"); + assert.equal(params.sessionId, "sess-1"); + assert.deepEqual(params.variables, { name: "prod" }); +}); + +test("buildCatalogCliParams throws for missing required fields", () => { + assert.throws( + () => buildCatalogCliParams("vault.host.get", {}, fakeCreateError), + /Missing required --host-id/, + ); }); diff --git a/electron/capabilities/catalog/harness.cjs b/electron/capabilities/catalog/harness.cjs new file mode 100644 index 000000000..a0dcb803d --- /dev/null +++ b/electron/capabilities/catalog/harness.cjs @@ -0,0 +1,100 @@ +"use strict"; + +const { CAPABILITY_STATUS } = require("../constants.cjs"); + +/** Catty-only harness tools (sidebar agent; renderer-local; not MCP/CLI). */ +/** @type {import("../types.cjs").CapabilityDefinition[]} */ +const HARNESS_CAPABILITIES = [ + { + id: "harness.tool_output.read", + domain: "harness", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Read stored tool output by handle id when a prior tool result was truncated.", + policy: { + write: false, + sensitiveRead: false, + longRunning: false, + requiresChatSession: true, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + catty: { toolName: "tool_output_read" }, + }, + }, + { + id: "harness.workspace.get_info", + domain: "harness", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Get information about the current workspace, including all terminal sessions and their connection status.", + policy: { + write: false, + sensitiveRead: false, + longRunning: false, + requiresChatSession: true, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + catty: { toolName: "workspace_get_info" }, + }, + }, + { + id: "harness.workspace.get_session_info", + domain: "harness", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Get detailed information about a specific terminal or SFTP session.", + policy: { + write: false, + sensitiveRead: false, + longRunning: false, + requiresChatSession: true, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + catty: { toolName: "workspace_get_session_info" }, + }, + }, + { + id: "harness.web.search", + domain: "harness", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Search the web for current information when configured in AI settings.", + policy: { + write: false, + sensitiveRead: false, + longRunning: false, + requiresChatSession: true, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + catty: { toolName: "web_search" }, + }, + }, + { + id: "harness.url.fetch", + domain: "harness", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Fetch and read the content of an HTTPS URL.", + policy: { + write: false, + sensitiveRead: false, + longRunning: false, + requiresChatSession: true, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + catty: { toolName: "url_fetch" }, + }, + }, +]; + +module.exports = { HARNESS_CAPABILITIES }; diff --git a/electron/capabilities/catalog/index.cjs b/electron/capabilities/catalog/index.cjs index c353c96ac..984649ca6 100644 --- a/electron/capabilities/catalog/index.cjs +++ b/electron/capabilities/catalog/index.cjs @@ -5,6 +5,7 @@ const { TERMINAL_CAPABILITIES } = require("./terminal.cjs"); const { SFTP_CAPABILITIES } = require("./sftp.cjs"); const { VAULT_CAPABILITIES } = require("./vault.cjs"); const { PORT_FORWARD_CAPABILITIES } = require("./portforward.cjs"); +const { HARNESS_CAPABILITIES } = require("./harness.cjs"); const ALL_CAPABILITIES = Object.freeze([ ...META_CAPABILITIES, @@ -12,6 +13,7 @@ const ALL_CAPABILITIES = Object.freeze([ ...SFTP_CAPABILITIES, ...VAULT_CAPABILITIES, ...PORT_FORWARD_CAPABILITIES, + ...HARNESS_CAPABILITIES, ]); module.exports = { @@ -20,5 +22,6 @@ module.exports = { SFTP_CAPABILITIES, VAULT_CAPABILITIES, PORT_FORWARD_CAPABILITIES, + HARNESS_CAPABILITIES, ALL_CAPABILITIES, }; diff --git a/electron/capabilities/catalog/integrity.test.cjs b/electron/capabilities/catalog/integrity.test.cjs index 8f7899412..ebfcde465 100644 --- a/electron/capabilities/catalog/integrity.test.cjs +++ b/electron/capabilities/catalog/integrity.test.cjs @@ -28,9 +28,19 @@ const IMPLEMENTED_CLI_COMMANDS = [ ["sftp", "home"], ["cancel"], ["resume"], + ["vault", "host", "get"], + ["vault", "host-notes", "get"], + ["vault", "host-notes", "set"], + ["snippets", "list"], + ["snippets", "get"], + ["snippets", "run"], + ["portforward", "rules", "list"], + ["portforward", "tunnels", "list"], + ["portforward", "start"], + ["portforward", "stop"], ]; -test("every implemented cli command maps to a builtin rpc method", () => { +test("every implemented cli command maps to an rpc method", () => { for (const command of IMPLEMENTED_CLI_COMMANDS) { const rpcMethod = getCliRpcMethod(command); assert.ok(rpcMethod, `missing rpc mapping for ${command.join(" ")}`); diff --git a/electron/capabilities/catalog/portforward.cjs b/electron/capabilities/catalog/portforward.cjs index a9375a3b3..502e20955 100644 --- a/electron/capabilities/catalog/portforward.cjs +++ b/electron/capabilities/catalog/portforward.cjs @@ -7,7 +7,7 @@ const PORT_FORWARD_CAPABILITIES = [ { id: "portforward.rules.list", domain: "portforward", - status: CAPABILITY_STATUS.PLANNED, + status: CAPABILITY_STATUS.IMPLEMENTED, description: "List persisted port forwarding rules.", policy: { write: false, @@ -27,7 +27,7 @@ const PORT_FORWARD_CAPABILITIES = [ { id: "portforward.tunnels.list", domain: "portforward", - status: CAPABILITY_STATUS.PLANNED, + status: CAPABILITY_STATUS.IMPLEMENTED, description: "List active port forwarding tunnels.", policy: { write: false, @@ -47,7 +47,7 @@ const PORT_FORWARD_CAPABILITIES = [ { id: "portforward.start", domain: "portforward", - status: CAPABILITY_STATUS.PLANNED, + status: CAPABILITY_STATUS.IMPLEMENTED, description: "Start a port forwarding tunnel for a rule.", policy: { write: true, @@ -67,7 +67,7 @@ const PORT_FORWARD_CAPABILITIES = [ { id: "portforward.stop", domain: "portforward", - status: CAPABILITY_STATUS.PLANNED, + status: CAPABILITY_STATUS.IMPLEMENTED, description: "Stop an active port forwarding tunnel.", policy: { write: true, diff --git a/electron/capabilities/catalog/sftp.cjs b/electron/capabilities/catalog/sftp.cjs index 200522c09..2faa2caae 100644 --- a/electron/capabilities/catalog/sftp.cjs +++ b/electron/capabilities/catalog/sftp.cjs @@ -60,6 +60,7 @@ const SFTP_CAPABILITIES = [ { write: true, bypassesApproval: false, bypassesChatCancel: false }, { builtin: { rpcMethod: "netcatty/sftp/download" }, + public: { rpcMethod: "public/sftp/download", mcpTool: "sftp_download" }, cli: { command: ["sftp", "download"] }, }, ), @@ -69,6 +70,7 @@ const SFTP_CAPABILITIES = [ { write: true, bypassesApproval: false, bypassesChatCancel: false }, { builtin: { rpcMethod: "netcatty/sftp/upload" }, + public: { rpcMethod: "public/sftp/upload", mcpTool: "sftp_upload" }, cli: { command: ["sftp", "upload"] }, }, ), diff --git a/electron/capabilities/catalog/vault.cjs b/electron/capabilities/catalog/vault.cjs index f030c9114..b17b261b5 100644 --- a/electron/capabilities/catalog/vault.cjs +++ b/electron/capabilities/catalog/vault.cjs @@ -7,7 +7,7 @@ const VAULT_CAPABILITIES = [ { id: "vault.host.get", domain: "vault", - status: CAPABILITY_STATUS.PLANNED, + status: CAPABILITY_STATUS.IMPLEMENTED, description: "Get host metadata from the vault.", policy: { write: false, @@ -21,13 +21,71 @@ const VAULT_CAPABILITIES = [ surfaces: { cli: { command: ["vault", "host", "get"] }, global: { rpcMethod: "vault/host/get" }, + public: { rpcMethod: "public/vault/host/get", mcpTool: "host_get" }, + }, + }, + { + id: "vault.host.list", + domain: "vault", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "List saved hosts in the vault (metadata only — no passwords or keys).", + policy: { + write: false, + sensitiveRead: true, + longRunning: false, + requiresChatSession: false, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + global: { rpcMethod: "vault/hosts/list" }, + public: { rpcMethod: "public/vault/hosts/list", mcpTool: "vault_hosts_list" }, + }, + }, + { + id: "vault.hosts.create", + domain: "vault", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Create vault hosts from structured host objects. Use when the user wants to add/create a host (Vault → Hosts). NOT for Vault → Notes sidebar documentation.", + policy: { + write: true, + sensitiveRead: false, + longRunning: false, + requiresChatSession: false, + bypassesObserverBlock: false, + bypassesApproval: false, + bypassesChatCancel: false, + }, + surfaces: { + global: { rpcMethod: "vault/hosts/create" }, + public: { rpcMethod: "public/vault/hosts/create", mcpTool: "vault_hosts_create" }, + }, + }, + { + id: "vault.host.import", + domain: "vault", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Parse known host export file formats (PuTTY, MobaXterm, CSV, SecureCRT, ssh_config) into vault hosts. For arbitrary unstructured text, map to host objects and use vault_hosts_create instead.", + policy: { + write: true, + sensitiveRead: false, + longRunning: false, + requiresChatSession: false, + bypassesObserverBlock: false, + bypassesApproval: false, + bypassesChatCancel: false, + }, + surfaces: { + global: { rpcMethod: "vault/hosts/import" }, + public: { rpcMethod: "public/vault/hosts/import", mcpTool: "vault_hosts_import" }, }, }, { id: "vault.host.notes.get", domain: "vault", - status: CAPABILITY_STATUS.PLANNED, - description: "Read host notes from the vault.", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Read host metadata notes attached to a saved host (Host Details panel — not Vault sidebar Notes).", policy: { write: false, sensitiveRead: true, @@ -46,8 +104,8 @@ const VAULT_CAPABILITIES = [ { id: "vault.host.notes.set", domain: "vault", - status: CAPABILITY_STATUS.PLANNED, - description: "Update host notes in the vault.", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Update host metadata notes on a saved host (Host Details panel — not Vault sidebar Notes).", policy: { write: true, sensitiveRead: false, @@ -60,12 +118,89 @@ const VAULT_CAPABILITIES = [ surfaces: { cli: { command: ["vault", "host-notes", "set"] }, global: { rpcMethod: "vault/host/notes/set" }, + public: { rpcMethod: "public/vault/hostNotes/set", mcpTool: "host_notes_set" }, + }, + }, + { + id: "vault.note.list", + domain: "vault", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "List notes in Vault → Notes (markdown notes visible in the vault sidebar).", + policy: { + write: false, + sensitiveRead: false, + longRunning: false, + requiresChatSession: false, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + global: { rpcMethod: "vault/notes/list" }, + public: { rpcMethod: "public/vault/notes/list", mcpTool: "vault_notes_list" }, + }, + }, + { + id: "vault.note.get", + domain: "vault", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Get a Vault → Notes entry by id (full markdown content).", + policy: { + write: false, + sensitiveRead: false, + longRunning: false, + requiresChatSession: false, + bypassesObserverBlock: false, + bypassesApproval: true, + bypassesChatCancel: true, + }, + surfaces: { + global: { rpcMethod: "vault/notes/get" }, + public: { rpcMethod: "public/vault/notes/get", mcpTool: "vault_notes_get" }, + }, + }, + { + id: "vault.note.create", + domain: "vault", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Create a note in Vault → Notes sidebar (markdown documentation). NOT for adding SSH hosts — use vault_hosts_create for that.", + policy: { + write: true, + sensitiveRead: false, + longRunning: false, + requiresChatSession: false, + bypassesObserverBlock: false, + bypassesApproval: false, + bypassesChatCancel: false, + }, + surfaces: { + global: { rpcMethod: "vault/notes/create" }, + public: { rpcMethod: "public/vault/notes/create", mcpTool: "vault_notes_create" }, + }, + }, + { + id: "vault.note.update", + domain: "vault", + status: CAPABILITY_STATUS.IMPLEMENTED, + description: "Update an existing Vault → Notes entry by id.", + policy: { + write: true, + sensitiveRead: false, + longRunning: false, + requiresChatSession: false, + bypassesObserverBlock: false, + bypassesApproval: false, + bypassesChatCancel: false, + }, + surfaces: { + global: { rpcMethod: "vault/notes/update" }, + public: { rpcMethod: "public/vault/notes/update", mcpTool: "vault_notes_update" }, }, }, { id: "vault.snippets.list", domain: "vault", - status: CAPABILITY_STATUS.PLANNED, + status: CAPABILITY_STATUS.IMPLEMENTED, description: "List code snippets stored in the vault.", policy: { write: false, @@ -85,7 +220,7 @@ const VAULT_CAPABILITIES = [ { id: "vault.snippets.get", domain: "vault", - status: CAPABILITY_STATUS.PLANNED, + status: CAPABILITY_STATUS.IMPLEMENTED, description: "Get a single code snippet from the vault.", policy: { write: false, @@ -105,7 +240,7 @@ const VAULT_CAPABILITIES = [ { id: "vault.snippets.run", domain: "vault", - status: CAPABILITY_STATUS.PLANNED, + status: CAPABILITY_STATUS.IMPLEMENTED, description: "Resolve snippet variables and execute a snippet in a terminal session.", policy: { write: true, diff --git a/electron/capabilities/codegen/mcpToolRegistry.cjs b/electron/capabilities/codegen/mcpToolRegistry.cjs new file mode 100644 index 000000000..4c3caad10 --- /dev/null +++ b/electron/capabilities/codegen/mcpToolRegistry.cjs @@ -0,0 +1,184 @@ +"use strict"; + +const { z } = require("zod"); +const { listMcpTools } = require("./toolSurfaces.cjs"); + +const TERMINAL_EXECUTE_TOOLS = new Set(["terminal_execute"]); +const TERMINAL_START_TOOLS = new Set(["terminal_start"]); +const TERMINAL_POLL_TOOLS = new Set(["terminal_poll"]); +const TERMINAL_STOP_TOOLS = new Set(["terminal_stop"]); +const CONTEXT_TOOLS = new Set(["get_environment"]); +const ATTACHMENT_LIST_TOOLS = new Set(["list_attachments"]); +const ATTACHMENT_READ_TOOLS = new Set(["read_attachment"]); +const SFTP_WRITE_TOOLS = new Set([ + "sftp_write_file", + "sftp_mkdir", + "sftp_delete", + "sftp_rename", + "sftp_chmod", +]); + +function buildZodField(field) { + let schema = field.type === "number" ? z.number() : z.string(); + if (field.type === "number") { + schema = schema.int().min(0); + } + if (field.description) { + schema = schema.describe(field.description); + } + if (field.optional) { + schema = schema.optional(); + } + return schema; +} + +function buildZodShapeObject(inputShape) { + const shape = {}; + for (const [key, field] of Object.entries(inputShape || {})) { + shape[key] = buildZodField(field); + } + return shape; +} + +function buildZodSchema(inputShape) { + return z.object(buildZodShapeObject(inputShape)); +} + +function formatRpcError(result) { + return `Error: ${result?.error || "Operation failed"}`; +} + +function formatTerminalExecuteResult(result) { + const parts = []; + if (result.stdout) parts.push(result.stdout); + if (result.stderr) parts.push(`[stderr] ${result.stderr}`); + if (result.exitCode != null) { + parts.push(`[exit code: ${result.exitCode}]`); + } + return parts.join("\n"); +} + +function createToolHandler(toolDef, deps) { + const { + rpcCall, + scopeParams, + guardWriteOperation, + catalogDescription, + } = deps; + const { mcpTool, rpcMethod, description, inputShape, policy } = toolDef; + + return async (args) => { + if (TERMINAL_EXECUTE_TOOLS.has(mcpTool) || TERMINAL_START_TOOLS.has(mcpTool)) { + const { sessionId, command } = args; + const guardErr = guardWriteOperation(command, { skipBlocklist: true }); + if (guardErr) { + return { content: [{ type: "text", text: `Error: ${guardErr}` }], isError: true }; + } + const result = await rpcCall(rpcMethod, { ...scopeParams, sessionId, command }); + if (!result.ok) { + return { content: [{ type: "text", text: formatRpcError(result) }], isError: true }; + } + if (TERMINAL_START_TOOLS.has(mcpTool)) { + return { + content: [{ + type: "text", + text: JSON.stringify({ + jobId: result.jobId, + sessionId: result.sessionId, + status: result.status, + startedAt: result.startedAt, + outputMode: result.outputMode, + recommendedPollIntervalMs: result.recommendedPollIntervalMs, + }, null, 2), + }], + }; + } + return { content: [{ type: "text", text: formatTerminalExecuteResult(result) }] }; + } + + if (TERMINAL_POLL_TOOLS.has(mcpTool) || TERMINAL_STOP_TOOLS.has(mcpTool)) { + const params = TERMINAL_POLL_TOOLS.has(mcpTool) + ? { ...scopeParams, jobId: args.jobId, offset: args.offset || 0 } + : { ...scopeParams, jobId: args.jobId }; + const result = await rpcCall(rpcMethod, params); + if (!result.ok) { + return { content: [{ type: "text", text: formatRpcError(result) }], isError: true }; + } + return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] }; + } + + if (CONTEXT_TOOLS.has(mcpTool)) { + const ctx = await rpcCall(rpcMethod, scopeParams); + return { content: [{ type: "text", text: JSON.stringify(ctx, null, 2) }] }; + } + + if (ATTACHMENT_LIST_TOOLS.has(mcpTool)) { + const result = await rpcCall(rpcMethod, scopeParams); + if (!result.ok) { + return { + content: [{ type: "text", text: formatRpcError(result) }], + isError: true, + }; + } + return { + content: [{ type: "text", text: JSON.stringify(result.attachments || [], null, 2) }], + }; + } + + if (ATTACHMENT_READ_TOOLS.has(mcpTool)) { + const { filePath, filename } = args; + const result = await rpcCall(rpcMethod, { ...scopeParams, filePath, filename }); + if (!result.ok) { + return { + content: [{ type: "text", text: formatRpcError(result) }], + isError: true, + }; + } + const payload = { + filename: result.filename, + mediaType: result.mediaType, + filePath: result.filePath, + sizeBytes: result.sizeBytes, + ...(result.text != null ? { text: result.text } : { base64Data: result.base64Data }), + }; + return { content: [{ type: "text", text: JSON.stringify(payload, null, 2) }] }; + } + + if (policy?.write) { + const guardErr = guardWriteOperation("", { skipBlocklist: true }); + if (guardErr) { + return { content: [{ type: "text", text: `Error: ${guardErr}` }], isError: true }; + } + } + + const result = await rpcCall(rpcMethod, { ...scopeParams, ...args }); + if (result && typeof result === "object" && result.ok === false) { + return { + content: [{ type: "text", text: formatRpcError(result) }], + isError: true, + }; + } + return { + content: [{ type: "text", text: JSON.stringify(result, null, 2) }], + }; + }; +} + +function registerMcpTools(server, deps) { + const tools = listMcpTools(); + for (const toolDef of tools) { + if (!toolDef.mcpTool || !toolDef.rpcMethod) continue; + const schemaShape = buildZodShapeObject(toolDef.inputShape); + const handler = createToolHandler(toolDef, deps); + const toolDescription = deps.catalogDescription(toolDef.mcpTool, toolDef.description); + server.tool(toolDef.mcpTool, toolDescription, schemaShape, handler); + } + return tools.length; +} + +module.exports = { + buildZodSchema, + buildZodShapeObject, + registerMcpTools, + SFTP_WRITE_TOOLS, +}; diff --git a/electron/capabilities/codegen/toolSurfaces.cjs b/electron/capabilities/codegen/toolSurfaces.cjs new file mode 100644 index 000000000..2a858fc7e --- /dev/null +++ b/electron/capabilities/codegen/toolSurfaces.cjs @@ -0,0 +1,204 @@ +"use strict"; + +const { AGENT_KINDS, CAPABILITY_STATUS, CAPABILITY_SURFACES } = require("../constants.cjs"); +const { ALL_CAPABILITIES } = require("../catalog/index.cjs"); +const { TOOL_INPUT_FIELDS, MODEL_DESCRIPTION_HINTS } = require("../schemas/toolInputs.cjs"); + +function buildZodShape(fields) { + const shape = {}; + for (const [key, field] of Object.entries(fields || {})) { + shape[key] = { + type: field.type, + optional: Boolean(field.optional), + description: field.description || "", + }; + } + return shape; +} + +function getMcpToolName(capability) { + return capability.surfaces?.public?.mcpTool + || capability.surfaces?.builtin?.mcpTool + || null; +} + +function getCattyToolName(capability) { + return capability.surfaces?.[CAPABILITY_SURFACES.CATTY]?.toolName + || getMcpToolName(capability) + || capability.id.replace(/\./g, "_"); +} + +function getCattyRpcMethod(capability) { + return capability.surfaces?.builtin?.rpcMethod + || capability.surfaces?.global?.rpcMethod + || capability.surfaces?.public?.rpcMethod + || null; +} + +function getAgentToolName(capability, agentKind) { + if (agentKind === AGENT_KINDS.GLOBAL) { + return capability.surfaces?.[CAPABILITY_SURFACES.GLOBAL_AGENT]?.toolName + || getMcpToolName(capability) + || capability.id.replace(/\./g, "_"); + } + return getCattyToolName(capability); +} + +function getAgentRpcMethod(capability) { + return getCattyRpcMethod(capability); +} + +function buildToolDescription(capability) { + const hint = MODEL_DESCRIPTION_HINTS[capability.id]; + if (!hint) return capability.description; + return `${capability.description} ${hint}`; +} + +function listToolSurfaces(options = {}) { + const { + surface = CAPABILITY_SURFACES.PUBLIC, + status = CAPABILITY_STATUS.IMPLEMENTED, + includeCatty = true, + } = options; + + const tools = []; + + for (const capability of ALL_CAPABILITIES) { + if (capability.status !== status) continue; + const binding = capability.surfaces?.[surface] || capability.surfaces?.public || capability.surfaces?.builtin; + if (!binding) continue; + + const mcpTool = getMcpToolName(capability); + const cattyToolName = getCattyToolName(capability); + if (!includeCatty && !mcpTool) continue; + + const builtinRpc = capability.surfaces?.builtin?.rpcMethod || binding.rpcMethod || null; + + tools.push({ + capabilityId: capability.id, + domain: capability.domain, + toolName: cattyToolName, + mcpTool, + rpcMethod: builtinRpc, + publicRpcMethod: capability.surfaces?.public?.rpcMethod || null, + description: buildToolDescription(capability), + policy: capability.policy, + inputShape: buildZodShape(TOOL_INPUT_FIELDS[capability.id]), + cattyEnabled: includeCatty && Boolean(TOOL_INPUT_FIELDS[capability.id] != null || mcpTool), + }); + } + + return tools; +} + +function listMcpTools() { + return listToolSurfaces({ surface: CAPABILITY_SURFACES.PUBLIC, includeCatty: false }) + .filter((tool) => tool.mcpTool); +} + +/** Capabilities excluded from Catty even when implemented (CLI-only / meta). */ +const CATTY_CAPABILITY_DENYLIST = new Set([ + "meta.status", + "session.cancel", + "session.resume", + "session.get", +]); + +function isCattyOnlyCapability(capability) { + return isAgentLocalOnlyCapability(capability, AGENT_KINDS.SIDEBAR); +} + +function isAgentLocalOnlyCapability(capability, agentKind) { + if (agentKind === AGENT_KINDS.GLOBAL) { + return Boolean(capability.surfaces?.[CAPABILITY_SURFACES.GLOBAL_AGENT]?.toolName) + && !getAgentRpcMethod(capability) + && !getMcpToolName(capability); + } + return Boolean(capability.surfaces?.[CAPABILITY_SURFACES.CATTY]?.toolName) + && !getAgentRpcMethod(capability) + && !getMcpToolName(capability); +} + +/** + * Resolve which agents may use a capability when agentKinds is not set explicitly. + * - surfaces.globalAgent only → global agent + * - surfaces.catty only (harness) → sidebar agent + * - RPC/MCP-backed tools → both agents (shared infrastructure) + */ +function resolveAgentKinds(capability) { + if (Array.isArray(capability.agentKinds) && capability.agentKinds.length > 0) { + return capability.agentKinds; + } + if (capability.surfaces?.[CAPABILITY_SURFACES.GLOBAL_AGENT]) { + return [AGENT_KINDS.GLOBAL]; + } + if (isAgentLocalOnlyCapability(capability, AGENT_KINDS.SIDEBAR)) { + return [AGENT_KINDS.SIDEBAR]; + } + if (isAgentEligibleForKind(capability, AGENT_KINDS.SIDEBAR, { skipAgentKindCheck: true })) { + return [AGENT_KINDS.SIDEBAR, AGENT_KINDS.GLOBAL]; + } + return []; +} + +function isAgentEligibleForKind(capability, agentKind, options = {}) { + if (capability.status !== CAPABILITY_STATUS.IMPLEMENTED) return false; + if (CATTY_CAPABILITY_DENYLIST.has(capability.id)) return false; + if (!options.skipAgentKindCheck && !resolveAgentKinds(capability).includes(agentKind)) { + return false; + } + const hasInputFields = Object.prototype.hasOwnProperty.call(TOOL_INPUT_FIELDS, capability.id); + if (!hasInputFields) return false; + if (isAgentLocalOnlyCapability(capability, agentKind)) return true; + const hasBuiltinRpc = Boolean(capability.surfaces?.builtin?.rpcMethod); + const hasGlobalRpc = Boolean(capability.surfaces?.global?.rpcMethod); + return hasBuiltinRpc || hasGlobalRpc || Boolean(getMcpToolName(capability)); +} + +function isCattyEligible(capability) { + return isAgentEligibleForKind(capability, AGENT_KINDS.SIDEBAR); +} + +function listAgentToolSpecs(agentKind = AGENT_KINDS.SIDEBAR) { + return ALL_CAPABILITIES + .filter((capability) => isAgentEligibleForKind(capability, agentKind)) + .map((capability) => { + const spec = { + capabilityId: capability.id, + toolName: getAgentToolName(capability, agentKind), + rpcMethod: getAgentRpcMethod(capability), + localExecution: isAgentLocalOnlyCapability(capability, agentKind), + description: buildToolDescription(capability), + inputShape: buildZodShape(TOOL_INPUT_FIELDS[capability.id]), + policy: capability.policy, + }; + if (agentKind !== AGENT_KINDS.SIDEBAR) { + spec.agentKind = agentKind; + } + return spec; + }); +} + +function listCattyToolSpecs() { + return listAgentToolSpecs(AGENT_KINDS.SIDEBAR); +} + +module.exports = { + AGENT_KINDS, + buildZodShape, + buildToolDescription, + CATTY_CAPABILITY_DENYLIST, + getAgentRpcMethod, + getAgentToolName, + getCattyToolName, + getCattyRpcMethod, + isAgentEligibleForKind, + isAgentLocalOnlyCapability, + isCattyEligible, + isCattyOnlyCapability, + listAgentToolSpecs, + listToolSurfaces, + listMcpTools, + listCattyToolSpecs, + resolveAgentKinds, +}; diff --git a/electron/capabilities/codegen/toolSurfaces.test.cjs b/electron/capabilities/codegen/toolSurfaces.test.cjs new file mode 100644 index 000000000..9e7b49388 --- /dev/null +++ b/electron/capabilities/codegen/toolSurfaces.test.cjs @@ -0,0 +1,162 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { CAPABILITY_STATUS } = require("../constants.cjs"); +const { ALL_CAPABILITIES } = require("../catalog/index.cjs"); +const { TOOL_INPUT_FIELDS } = require("../schemas/toolInputs.cjs"); +const { + listMcpTools, + listCattyToolSpecs, + CATTY_CAPABILITY_DENYLIST, + isCattyEligible, +} = require("./toolSurfaces.cjs"); +const { registerMcpTools, buildZodShapeObject } = require("./mcpToolRegistry.cjs"); + +test("listCattyToolSpecs includes terminal long-running tools", () => { + const specs = listCattyToolSpecs(); + const names = specs.map((spec) => spec.toolName); + assert.ok(names.includes("terminal_execute")); + assert.ok(names.includes("terminal_start")); + assert.ok(names.includes("terminal_poll")); + assert.ok(names.includes("terminal_stop")); +}); + +test("listCattyToolSpecs includes SFTP write tools and attachments", () => { + const capabilityIds = listCattyToolSpecs().map((spec) => spec.capabilityId); + assert.ok(capabilityIds.includes("attachment.list")); + assert.ok(capabilityIds.includes("attachment.read")); + assert.ok(capabilityIds.includes("sftp.write")); + assert.ok(capabilityIds.includes("sftp.mkdir")); + assert.ok(capabilityIds.includes("sftp.delete")); + assert.ok(capabilityIds.includes("sftp.rename")); + assert.ok(capabilityIds.includes("sftp.chmod")); + assert.ok(!capabilityIds.includes("meta.status")); + assert.ok(!capabilityIds.includes("session.cancel")); +}); + +test("listCattyToolSpecs includes vault host tools and SFTP transfer", () => { + const capabilityIds = listCattyToolSpecs().map((spec) => spec.capabilityId); + assert.ok(capabilityIds.includes("vault.host.get")); + assert.ok(capabilityIds.includes("vault.host.list")); + assert.ok(capabilityIds.includes("vault.hosts.create")); + assert.ok(capabilityIds.includes("vault.host.import")); + assert.ok(capabilityIds.includes("vault.note.create")); + assert.ok(capabilityIds.includes("vault.note.list")); + assert.ok(capabilityIds.includes("sftp.download")); + assert.ok(capabilityIds.includes("sftp.upload")); +}); + +test("listCattyToolSpecs binds vault note tools to global RPC methods", () => { + const specs = listCattyToolSpecs(); + const noteCreate = specs.find((spec) => spec.capabilityId === "vault.note.create"); + assert.equal(noteCreate?.rpcMethod, "vault/notes/create"); + const noteList = specs.find((spec) => spec.capabilityId === "vault.note.list"); + assert.equal(noteList?.rpcMethod, "vault/notes/list"); +}); + +test("listCattyToolSpecs binds vault and portforward tools to global RPC methods", () => { + const specs = listCattyToolSpecs(); + const hostNotesSet = specs.find((spec) => spec.capabilityId === "vault.host.notes.set"); + assert.equal(hostNotesSet?.rpcMethod, "vault/host/notes/set"); + const portforwardStart = specs.find((spec) => spec.capabilityId === "portforward.start"); + assert.equal(portforwardStart?.rpcMethod, "portforward/start"); +}); + +test("listAgentToolSpecs splits sidebar harness tools from shared RPC tools", () => { + const { AGENT_KINDS, listAgentToolSpecs } = require("./toolSurfaces.cjs"); + const sidebarIds = listAgentToolSpecs(AGENT_KINDS.SIDEBAR).map((spec) => spec.capabilityId); + const globalIds = listAgentToolSpecs(AGENT_KINDS.GLOBAL).map((spec) => spec.capabilityId); + + assert.ok(sidebarIds.includes("harness.workspace.get_info")); + assert.ok(!globalIds.includes("harness.workspace.get_info")); + + assert.ok(sidebarIds.includes("terminal.execute")); + assert.ok(globalIds.includes("terminal.execute")); + assert.ok(globalIds.includes("vault.note.create")); + + assert.ok(globalIds.every((id) => sidebarIds.includes(id) || id.startsWith("harness.") === false)); +}); + +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); + for (const spec of harness) { + assert.equal(spec.localExecution, true); + assert.equal(spec.rpcMethod, null); + } + const harnessIds = harness.map((spec) => spec.capabilityId); + assert.ok(harnessIds.includes("harness.tool_output.read")); + assert.ok(harnessIds.includes("harness.workspace.get_info")); +}); + +test("harness capabilities are not exposed on MCP", () => { + const mcpCapabilityIds = listMcpTools().map((tool) => tool.capabilityId); + for (const capabilityId of mcpCapabilityIds) { + assert.ok(!capabilityId.startsWith("harness.")); + } + assert.equal(listMcpTools().length, 35); +}); + +test("listMcpTools descriptions stay aligned with catalog capability ids", () => { + const mcpTools = listMcpTools(); + assert.ok(mcpTools.length >= 35); + for (const tool of mcpTools) { + assert.ok(tool.capabilityId); + assert.ok(tool.mcpTool); + assert.ok(tool.description.length > 0); + assert.ok(tool.rpcMethod); + } +}); + +test("catty and mcp terminal tools share capability ids", () => { + const catty = listCattyToolSpecs().find((spec) => spec.toolName === "terminal_execute"); + const mcp = listMcpTools().find((tool) => tool.mcpTool === "terminal_execute"); + assert.equal(catty?.capabilityId, "terminal.execute"); + assert.equal(mcp?.capabilityId, "terminal.execute"); +}); + +test("implemented catalog tools with inputs are catty-eligible unless denylisted", () => { + const implemented = ALL_CAPABILITIES.filter((cap) => cap.status === CAPABILITY_STATUS.IMPLEMENTED); + for (const capability of implemented) { + const hasInputs = Object.prototype.hasOwnProperty.call(TOOL_INPUT_FIELDS, capability.id); + if (!hasInputs) continue; + if (CATTY_CAPABILITY_DENYLIST.has(capability.id)) { + assert.equal(isCattyEligible(capability), false); + continue; + } + const hasRpc = Boolean( + capability.surfaces?.builtin?.rpcMethod + || capability.surfaces?.public?.mcpTool, + ); + if (hasRpc) { + assert.equal(isCattyEligible(capability), true); + } + } +}); + +test("mcp registry builds zod shapes for every MCP tool", () => { + for (const tool of listMcpTools()) { + const shape = buildZodShapeObject(tool.inputShape); + assert.equal(typeof shape, "object"); + } +}); + +test("registerMcpTools registers one handler per catalog MCP tool", () => { + const registered = []; + const fakeServer = { + tool(name, _description, _shape, handler) { + registered.push({ name, handler: typeof handler }); + }, + }; + const count = registerMcpTools(fakeServer, { + rpcCall: async () => ({ ok: true }), + scopeParams: {}, + guardWriteOperation: () => null, + catalogDescription: (_name, fallback) => fallback, + }); + assert.equal(count, listMcpTools().length); + assert.equal(registered.length, listMcpTools().length); +}); diff --git a/electron/capabilities/constants.cjs b/electron/capabilities/constants.cjs index ee96c70bd..48d5bc0d0 100644 --- a/electron/capabilities/constants.cjs +++ b/electron/capabilities/constants.cjs @@ -1,14 +1,27 @@ "use strict"; -/** @typedef {'builtin' | 'public' | 'cli' | 'global'} CapabilitySurface */ +/** @typedef {'builtin' | 'public' | 'cli' | 'global' | 'catty' | 'globalAgent'} CapabilitySurface */ /** @typedef {'implemented' | 'planned'} CapabilityStatus */ /** @typedef {'observer' | 'confirm' | 'autonomous'} PermissionMode */ +/** @typedef {'sidebar' | 'global'} AgentKind */ const CAPABILITY_SURFACES = Object.freeze({ BUILTIN: "builtin", PUBLIC: "public", CLI: "cli", GLOBAL: "global", + /** Renderer-local sidebar (Catty) harness tools (no MCP/CLI exposure). */ + CATTY: "catty", + /** Renderer-local global agent tools (no MCP/CLI exposure). */ + GLOBAL_AGENT: "globalAgent", +}); + +/** Where in the app an agent runs — orthogonal to RPC/MCP/CLI capability surfaces. */ +const AGENT_KINDS = Object.freeze({ + /** Chat side panel (Catty). */ + SIDEBAR: "sidebar", + /** Future app-wide agent (cross-window / proactive). */ + GLOBAL: "global", }); const CAPABILITY_STATUS = Object.freeze({ @@ -30,6 +43,7 @@ const RPC_TIMEOUT_DEFAULTS = Object.freeze({ }); module.exports = { + AGENT_KINDS, CAPABILITY_SURFACES, CAPABILITY_STATUS, PERMISSION_MODES, diff --git a/electron/capabilities/dispatch.test.cjs b/electron/capabilities/dispatch.test.cjs index df0559fbd..b56d2d17d 100644 --- a/electron/capabilities/dispatch.test.cjs +++ b/electron/capabilities/dispatch.test.cjs @@ -22,7 +22,7 @@ test("createRegistryDispatcher routes implemented capabilities to handlers", asy assert.equal(calls.length, 0); }); -test("createRegistryDispatcher returns not-implemented for planned capabilities", async () => { +test("createRegistryDispatcher falls back for implemented capabilities without handlers", async () => { const dispatch = createRegistryDispatcher({ surface: CAPABILITY_SURFACES.GLOBAL, handlers: {}, @@ -31,7 +31,7 @@ test("createRegistryDispatcher returns not-implemented for planned capabilities" const result = await dispatch("vault/host/notes/get", { hostId: "host-1" }); assert.equal(result.ok, false); - assert.equal(result.code, "CAPABILITY_NOT_IMPLEMENTED"); + assert.equal(result.error, "unknown:vault/host/notes/get"); }); test("createRegistryDispatcher falls back for unknown rpc methods", async () => { diff --git a/electron/capabilities/policy.cjs b/electron/capabilities/policy.cjs index 1198c2c67..927cde9eb 100644 --- a/electron/capabilities/policy.cjs +++ b/electron/capabilities/policy.cjs @@ -84,6 +84,32 @@ function evaluateRpcPermission({ }; } +function evaluatePermissionWithGrants(ctx, grants = []) { + const base = evaluateRpcPermission(ctx); + if (!base.allowed || !base.requiresApproval || !base.capability) { + return base; + } + + const { matchPermissionGrant } = require("../shared/permissionGrants.cjs"); + const params = ctx?.params && typeof ctx.params === "object" ? ctx.params : {}; + const matched = matchPermissionGrant(grants, { + capabilityId: base.capability.id, + chatSessionId: params.chatSessionId, + sessionId: params.sessionId, + args: params, + }); + + if (matched) { + return { + ...base, + requiresApproval: false, + matchedGrantId: matched.id, + }; + } + + return base; +} + function buildRpcMethodSet(surface, predicate) { const { getRpcMethodsForSurface } = require("./registry.cjs"); const methods = new Set(); @@ -132,6 +158,7 @@ module.exports = { requiresApprovalInConfirmMode, isBlockedInObserverMode, evaluateRpcPermission, + evaluatePermissionWithGrants, BUILTIN_WRITE_RPC_METHODS, BUILTIN_APPROVAL_RPC_METHODS, PUBLIC_WRITE_RPC_METHODS, diff --git a/electron/capabilities/policy.test.cjs b/electron/capabilities/policy.test.cjs index dd692db6f..ec6230c17 100644 --- a/electron/capabilities/policy.test.cjs +++ b/electron/capabilities/policy.test.cjs @@ -8,6 +8,7 @@ const { BUILTIN_APPROVAL_RPC_METHODS, PUBLIC_CONFIRM_RPC_METHODS, evaluateRpcPermission, + evaluatePermissionWithGrants, OBSERVER_DENY_MESSAGE, } = require("./policy.cjs"); const { CAPABILITY_SURFACES, PERMISSION_MODES } = require("./constants.cjs"); @@ -146,3 +147,51 @@ test("unknown rpc methods pass through policy checks", () => { assert.equal(decision.requiresApproval, false); assert.equal(decision.capability, null); }); + +test("confirm mode requires approval for portforward start and host notes set", () => { + const portforwardDecision = evaluateRpcPermission({ + rpcMethod: "public/portforward/start", + surface: CAPABILITY_SURFACES.PUBLIC, + permissionMode: PERMISSION_MODES.CONFIRM, + params: { chatSessionId: "chat-1", ruleId: "rule-1" }, + }); + assert.equal(portforwardDecision.requiresApproval, true); + + const notesDecision = evaluateRpcPermission({ + rpcMethod: "vault/host/notes/set", + surface: CAPABILITY_SURFACES.GLOBAL, + permissionMode: PERMISSION_MODES.CONFIRM, + params: { chatSessionId: "chat-1", hostId: "host-1" }, + }); + assert.equal(notesDecision.requiresApproval, true); + + const publicNotesDecision = evaluateRpcPermission({ + rpcMethod: "public/vault/hostNotes/set", + surface: CAPABILITY_SURFACES.PUBLIC, + permissionMode: PERMISSION_MODES.CONFIRM, + params: { chatSessionId: "chat-1", hostId: "host-1" }, + }); + assert.equal(publicNotesDecision.requiresApproval, true); +}); + +test("evaluatePermissionWithGrants skips approval when a grant matches", () => { + const decision = evaluatePermissionWithGrants({ + rpcMethod: "netcatty/exec", + permissionMode: PERMISSION_MODES.CONFIRM, + params: { + chatSessionId: "chat-1", + sessionId: "session-a", + command: "ls -la", + }, + context: { chatSessionCancelled: false }, + }, [{ + id: "grant-1", + capabilityId: "terminal.execute", + sessionPattern: "session-a", + commandPattern: "ls *", + createdAt: Date.now(), + }]); + + assert.equal(decision.allowed, true); + assert.equal(decision.requiresApproval, false); +}); diff --git a/electron/capabilities/registry.cjs b/electron/capabilities/registry.cjs index 0179343f1..77b1a45a5 100644 --- a/electron/capabilities/registry.cjs +++ b/electron/capabilities/registry.cjs @@ -9,6 +9,7 @@ function buildRegistryIndex(capabilities) { const byMcpTool = new Map(); const byCliCommand = new Map(); const byDomain = new Map(); + const byCattyTool = new Map(); for (const capability of capabilities) { byId.set(capability.id, capability); @@ -27,6 +28,9 @@ function buildRegistryIndex(capabilities) { if (Array.isArray(binding?.command) && binding.command.length > 0) { byCliCommand.set(binding.command.join(" "), capability); } + if (binding?.toolName) { + byCattyTool.set(binding.toolName, capability); + } } } @@ -36,6 +40,7 @@ function buildRegistryIndex(capabilities) { byRpcMethod, byMcpTool, byCliCommand, + byCattyTool, byDomain, }; } @@ -69,6 +74,10 @@ function getCapabilityByCliCommand(commandParts) { return registryIndex.byCliCommand.get(key) || null; } +function getCapabilityByCattyToolName(toolName) { + return registryIndex.byCattyTool.get(toolName) || null; +} + function getRpcMethodsForSurface(surface, filter = {}) { const methods = new Set(); for (const capability of registryIndex.capabilities) { @@ -95,6 +104,7 @@ module.exports = { getCapabilityByRpcMethod, getCapabilityByMcpTool, getCapabilityByCliCommand, + getCapabilityByCattyToolName, getRpcMethodsForSurface, getImplementedRpcMethodsForSurface, buildRegistryIndex, diff --git a/electron/capabilities/registry.test.cjs b/electron/capabilities/registry.test.cjs index bf56bd5ed..c3ea1e32b 100644 --- a/electron/capabilities/registry.test.cjs +++ b/electron/capabilities/registry.test.cjs @@ -13,12 +13,10 @@ const { } = require("./registry.cjs"); const { CAPABILITY_STATUS, CAPABILITY_SURFACES } = require("./constants.cjs"); -test("registry contains implemented and planned capabilities", () => { +test("registry contains implemented capabilities", () => { assert.ok(ALL_CAPABILITIES.length >= 20); const implemented = listCapabilities({ status: CAPABILITY_STATUS.IMPLEMENTED }); - const planned = listCapabilities({ status: CAPABILITY_STATUS.PLANNED }); - assert.ok(implemented.length > 0); - assert.ok(planned.length > 0); + assert.ok(implemented.length >= 20); }); test("registry resolves builtin rpc methods and mcp tools", () => { @@ -41,7 +39,7 @@ test("registry resolves cli commands", () => { assert.equal(sftpList?.id, "sftp.list"); }); -test("planned vault and portforward capabilities are registered", () => { - assert.equal(getCapabilityById("vault.host.notes.get")?.status, CAPABILITY_STATUS.PLANNED); - assert.equal(getCapabilityById("portforward.start")?.status, CAPABILITY_STATUS.PLANNED); +test("vault and portforward capabilities are implemented", () => { + assert.equal(getCapabilityById("vault.host.notes.get")?.status, CAPABILITY_STATUS.IMPLEMENTED); + assert.equal(getCapabilityById("portforward.start")?.status, CAPABILITY_STATUS.IMPLEMENTED); }); diff --git a/electron/capabilities/schemas/toolInputs.cjs b/electron/capabilities/schemas/toolInputs.cjs new file mode 100644 index 000000000..1d2c9de69 --- /dev/null +++ b/electron/capabilities/schemas/toolInputs.cjs @@ -0,0 +1,207 @@ +"use strict"; + +/** + * Input field definitions keyed by capability id. + * Single source for MCP, Catty, and CLI tool schemas. + */ +const TOOL_INPUT_FIELDS = Object.freeze({ + "terminal.execute": { + sessionId: { type: "string", description: "The terminal session ID to execute on." }, + command: { type: "string", description: "The shell command to execute in the target session." }, + }, + "terminal.start": { + sessionId: { type: "string", description: "The terminal session ID to start a long-running command on." }, + command: { type: "string", description: "The command to start in the target session." }, + }, + "terminal.poll": { + jobId: { type: "string", description: "The background job ID returned by terminal_start." }, + offset: { type: "number", optional: true, description: "Character offset from a previous poll (default 0)." }, + }, + "terminal.stop": { + jobId: { type: "string", description: "The background job ID returned by terminal_start." }, + }, + "session.environment": {}, + "attachment.list": {}, + "attachment.read": { + filePath: { type: "string", optional: true, description: "Exact local attachment path." }, + filename: { type: "string", optional: true, description: "Attachment filename from list_attachments." }, + }, + "sftp.list": { + sessionId: { type: "string", description: "SFTP session ID." }, + path: { type: "string", description: "Remote directory path." }, + }, + "sftp.read": { + sessionId: { type: "string", description: "SFTP session ID." }, + path: { type: "string", description: "Remote file path to read." }, + }, + "sftp.stat": { + sessionId: { type: "string", description: "SFTP session ID." }, + path: { type: "string", description: "Remote path to stat." }, + }, + "sftp.home": { + sessionId: { type: "string", description: "SFTP session ID." }, + }, + "sftp.write": { + sessionId: { type: "string", description: "SFTP session ID." }, + path: { type: "string", description: "Remote file path to write." }, + content: { type: "string", description: "File content to write." }, + }, + "sftp.download": { + sessionId: { type: "string", description: "SFTP session ID." }, + remotePath: { type: "string", description: "Remote file path to download." }, + localPath: { type: "string", description: "Local destination path." }, + }, + "sftp.upload": { + sessionId: { type: "string", description: "SFTP session ID." }, + localPath: { type: "string", description: "Local file path to upload." }, + remotePath: { type: "string", description: "Remote destination path." }, + }, + "sftp.mkdir": { + sessionId: { type: "string", description: "SFTP session ID." }, + path: { type: "string", description: "Remote directory path to create." }, + }, + "sftp.delete": { + sessionId: { type: "string", description: "SFTP session ID." }, + path: { type: "string", description: "Remote file or directory path to delete." }, + }, + "sftp.rename": { + sessionId: { type: "string", description: "SFTP session ID." }, + oldPath: { type: "string", description: "Current remote path." }, + newPath: { type: "string", description: "New remote path." }, + }, + "sftp.chmod": { + sessionId: { type: "string", description: "SFTP session ID." }, + path: { type: "string", description: "Remote file path." }, + mode: { type: "string", description: "Octal permission mode (e.g. 755)." }, + }, + "vault.host.get": { + hostId: { type: "string", description: "Vault host ID." }, + }, + "vault.host.list": {}, + "vault.hosts.create": { + hosts: { + type: "string", + description: + "JSON array of host objects you extracted from the user's text. Each object: hostname (required), label, port, username, password, group, tags (array or comma-separated string), notes (Host Details remarks — NOT Vault sidebar Notes), protocol (ssh|telnet|local).", + }, + dryRun: { + type: "string", + optional: true, + description: "Set to true to validate and preview without writing to the vault.", + }, + skipDuplicates: { + type: "string", + optional: true, + description: "Set to false to create even when a matching host already exists (default true).", + }, + }, + "vault.host.import": { + format: { + type: "string", + description: "Import format: csv, putty, mobaxterm, securecrt, ssh_config, or auto to detect from text.", + }, + text: { type: "string", description: "Exported host data text to import." }, + dryRun: { + type: "string", + optional: true, + description: "Set to true to parse and preview without writing to the vault.", + }, + skipDuplicates: { + type: "string", + optional: true, + description: "Set to false to import even when a matching host already exists (default true).", + }, + fileName: { + type: "string", + optional: true, + description: "Optional source file name (helps SecureCRT .ini parsing).", + }, + }, + "vault.host.notes.get": { + hostId: { type: "string", description: "Vault host ID." }, + }, + "vault.host.notes.set": { + hostId: { type: "string", description: "Vault host ID." }, + notes: { type: "string", description: "Host metadata notes (Host Details — not Vault sidebar Notes)." }, + }, + "vault.note.list": {}, + "vault.note.get": { + noteId: { type: "string", description: "Vault note ID from vault_notes_list." }, + }, + "vault.note.create": { + title: { type: "string", description: "Note title shown in Vault → Notes." }, + content: { type: "string", description: "Markdown note body." }, + group: { type: "string", optional: true, description: "Optional folder path (e.g. infra/prod)." }, + linkedHostIds: { type: "string", optional: true, description: "Optional JSON array of vault host IDs to link." }, + tags: { type: "string", optional: true, description: "Optional JSON array of tag strings." }, + }, + "vault.note.update": { + noteId: { type: "string", description: "Vault note ID to update." }, + title: { type: "string", optional: true, description: "New title." }, + content: { type: "string", optional: true, description: "New markdown body." }, + group: { type: "string", optional: true, description: "New folder path." }, + linkedHostIds: { type: "string", optional: true, description: "Optional JSON array of vault host IDs to link." }, + tags: { type: "string", optional: true, description: "Optional JSON array of tag strings." }, + }, + "vault.snippets.list": {}, + "vault.snippets.get": { + snippetId: { type: "string", description: "Snippet ID." }, + }, + "vault.snippets.run": { + snippetId: { type: "string", description: "Snippet ID to run." }, + sessionId: { type: "string", description: "Terminal session ID to execute on." }, + variables: { type: "string", optional: true, description: "JSON object of snippet variable values." }, + }, + "portforward.rules.list": {}, + "portforward.tunnels.list": {}, + "portforward.start": { + ruleId: { type: "string", description: "Port forwarding rule ID." }, + }, + "portforward.stop": { + ruleId: { type: "string", description: "Port forwarding rule ID." }, + }, + "harness.tool_output.read": { + handleId: { type: "string", description: "Tool output handle id from a prior truncated result." }, + mode: { type: "string", optional: true, description: "Which portion to read: head, tail, or full." }, + maxChars: { type: "number", optional: true, description: "Maximum characters to return." }, + }, + "harness.workspace.get_info": {}, + "harness.workspace.get_session_info": { + sessionId: { type: "string", description: "The session ID to get information about." }, + }, + "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." }, + }, + "harness.url.fetch": { + url: { type: "string", description: "The HTTPS URL to fetch." }, + maxLength: { type: "number", optional: true, description: "Maximum characters to return (default 50000)." }, + }, +}); + +/** Long-form model guidance appended to terminal tool descriptions from catalog. */ +const MODEL_DESCRIPTION_HINTS = Object.freeze({ + "terminal.execute": + "Use only for commands expected to finish within about 60 seconds. For long-running commands use terminal_start and terminal_poll.", + "terminal.start": + "Prefer for builds, scans, log-following, or anything likely to exceed about 2 minutes.", + "terminal.poll": + "Wait at least about 30 seconds between polls unless output justifies checking sooner.", + "vault.host.notes.get": + "Host metadata notes on a saved host — not Vault → Notes sidebar entries.", + "vault.host.notes.set": + "Host metadata notes on a saved host — not Vault → Notes sidebar entries. Prefer vault_notes_create/update when the user wants vault notes they can open in the Notes sidebar.", + "vault.host.import": + "Only for text in known export formats (PuTTY reg, MobaXterm ini, CSV template, SecureCRT, ssh_config). For arbitrary unstructured host lists from the user, extract fields yourself and call vault_hosts_create.", + "vault.hosts.create": + "Use when the user wants to add/create a host in Vault → Hosts (创建主机、SSH 连接凭据). NOT for Vault → Notes sidebar docs. Put SSH password in password field; long remarks/admin tables in host notes field. Never fall back to vault_notes_create if this fails.", + "vault.note.create": + "Use ONLY when the user wants markdown documentation in Vault → Notes sidebar (保险箱笔记). Do NOT use when the user asked to create/add a host — use vault_hosts_create instead.", + "vault.note.update": + "Update an existing Vault → Notes entry (visible in the vault notes sidebar).", +}); + +module.exports = { + TOOL_INPUT_FIELDS, + MODEL_DESCRIPTION_HINTS, +}; diff --git a/electron/capabilities/services/portforwardService.cjs b/electron/capabilities/services/portforwardService.cjs index b3bba4b25..124236fbd 100644 --- a/electron/capabilities/services/portforwardService.cjs +++ b/electron/capabilities/services/portforwardService.cjs @@ -1,17 +1,42 @@ "use strict"; -const { createNotImplementedHandler } = require("./notImplemented.cjs"); +const portForwardingBridge = require("../../bridges/portForwardingBridge.cjs"); /** - * Port forwarding domain service skeleton. Implementation will delegate to - * portForwardingBridge once rules are accessible from the main process. + * Port forwarding domain service. Tunnels live in main; rules live in renderer vault. */ -function createPortForwardService(_ctx = {}) { +function createPortForwardService(ctx = {}) { + const { invokeVaultAgent } = ctx; + return { - listRules: createNotImplementedHandler("portforward.rules.list"), - listTunnels: createNotImplementedHandler("portforward.tunnels.list"), - start: createNotImplementedHandler("portforward.start"), - stop: createNotImplementedHandler("portforward.stop"), + listRules: async () => { + if (typeof invokeVaultAgent !== "function") { + return { ok: false, error: "Vault agent bridge is unavailable." }; + } + return invokeVaultAgent("portforward.rules.list", {}); + }, + listTunnels: async () => { + const tunnels = await portForwardingBridge.listPortForwards(); + return { ok: true, tunnels }; + }, + start: async (params = {}) => { + if (typeof invokeVaultAgent !== "function") { + return { ok: false, error: "Vault agent bridge is unavailable." }; + } + return invokeVaultAgent("portforward.start", { + ruleId: params.ruleId, + chatSessionId: params.chatSessionId, + }); + }, + stop: async (params = {}) => { + if (typeof invokeVaultAgent !== "function") { + return { ok: false, error: "Vault agent bridge is unavailable." }; + } + return invokeVaultAgent("portforward.stop", { + ruleId: params.ruleId, + chatSessionId: params.chatSessionId, + }); + }, }; } diff --git a/electron/capabilities/services/portforwardService.test.cjs b/electron/capabilities/services/portforwardService.test.cjs new file mode 100644 index 000000000..aa7cfeb4f --- /dev/null +++ b/electron/capabilities/services/portforwardService.test.cjs @@ -0,0 +1,28 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { createPortForwardService } = require("./portforwardService.cjs"); + +test("portforward service lists active tunnels from main bridge", async () => { + const service = createPortForwardService({ + invokeVaultAgent: async () => ({ ok: true, rules: [] }), + }); + const result = await service.listTunnels(); + assert.equal(result.ok, true); + assert.ok(Array.isArray(result.tunnels)); +}); + +test("portforward start delegates to vault agent bridge after approval path", async () => { + let invokedOp = null; + const service = createPortForwardService({ + invokeVaultAgent: async (op, params) => { + invokedOp = op; + return { ok: true, ruleId: params.ruleId }; + }, + }); + const result = await service.start({ ruleId: "rule-1", chatSessionId: "chat-1" }); + assert.equal(invokedOp, "portforward.start"); + assert.equal(result.ok, true); +}); diff --git a/electron/capabilities/services/vaultService.cjs b/electron/capabilities/services/vaultService.cjs index 5f2ca1255..7af5b766a 100644 --- a/electron/capabilities/services/vaultService.cjs +++ b/electron/capabilities/services/vaultService.cjs @@ -1,19 +1,93 @@ "use strict"; -const { createNotImplementedHandler } = require("./notImplemented.cjs"); - /** - * Vault domain service skeleton. Handlers will be wired to a VaultFacade bridge - * in a follow-up PR; registry entries already describe the public contract. + * Vault domain service. Read-only metadata and notes/snippets are served from + * renderer vault state via VaultAgentBridge; credentials never cross the bridge. */ -function createVaultService(_ctx = {}) { +function createVaultService(ctx = {}) { + const { invokeVaultAgent } = ctx; + + function requireBridge() { + if (typeof invokeVaultAgent !== "function") { + return { ok: false, error: "Vault agent bridge is unavailable." }; + } + return null; + } + return { - getHost: createNotImplementedHandler("vault.host.get"), - getHostNotes: createNotImplementedHandler("vault.host.notes.get"), - setHostNotes: createNotImplementedHandler("vault.host.notes.set"), - listSnippets: createNotImplementedHandler("vault.snippets.list"), - getSnippet: createNotImplementedHandler("vault.snippets.get"), - runSnippet: createNotImplementedHandler("vault.snippets.run"), + getHost: async (params = {}) => { + const bridgeErr = requireBridge(); + if (bridgeErr) return bridgeErr; + return invokeVaultAgent("host.get", { hostId: params.hostId }); + }, + listHosts: async () => { + const bridgeErr = requireBridge(); + if (bridgeErr) return bridgeErr; + return invokeVaultAgent("host.list", {}); + }, + createHosts: async (params = {}) => { + const bridgeErr = requireBridge(); + if (bridgeErr) return bridgeErr; + return invokeVaultAgent("hosts.create", params); + }, + importHosts: async (params = {}) => { + const bridgeErr = requireBridge(); + if (bridgeErr) return bridgeErr; + return invokeVaultAgent("host.import", params); + }, + getHostNotes: async (params = {}) => { + const bridgeErr = requireBridge(); + if (bridgeErr) return bridgeErr; + return invokeVaultAgent("host.notes.get", { hostId: params.hostId }); + }, + setHostNotes: async (params = {}) => { + const bridgeErr = requireBridge(); + if (bridgeErr) return bridgeErr; + return invokeVaultAgent("host.notes.set", { + hostId: params.hostId, + notes: params.notes, + }); + }, + listNotes: async () => { + const bridgeErr = requireBridge(); + if (bridgeErr) return bridgeErr; + return invokeVaultAgent("note.list", {}); + }, + getNote: async (params = {}) => { + const bridgeErr = requireBridge(); + if (bridgeErr) return bridgeErr; + return invokeVaultAgent("note.get", { noteId: params.noteId }); + }, + createNote: async (params = {}) => { + const bridgeErr = requireBridge(); + if (bridgeErr) return bridgeErr; + return invokeVaultAgent("note.create", params); + }, + updateNote: async (params = {}) => { + const bridgeErr = requireBridge(); + if (bridgeErr) return bridgeErr; + return invokeVaultAgent("note.update", params); + }, + listSnippets: async () => { + const bridgeErr = requireBridge(); + if (bridgeErr) return bridgeErr; + return invokeVaultAgent("snippets.list", {}); + }, + getSnippet: async (params = {}) => { + const bridgeErr = requireBridge(); + if (bridgeErr) return bridgeErr; + return invokeVaultAgent("snippets.get", { snippetId: params.snippetId }); + }, + runSnippet: async (params = {}) => { + const bridgeErr = requireBridge(); + if (bridgeErr) return bridgeErr; + return invokeVaultAgent("snippets.run", { + snippetId: params.snippetId, + sessionId: params.sessionId, + variables: params.variables, + chatSessionId: params.chatSessionId, + }); + }, }; } diff --git a/electron/capabilities/services/vaultService.test.cjs b/electron/capabilities/services/vaultService.test.cjs index a174fc30c..1f1c021ca 100644 --- a/electron/capabilities/services/vaultService.test.cjs +++ b/electron/capabilities/services/vaultService.test.cjs @@ -5,9 +5,23 @@ const assert = require("node:assert/strict"); const { createVaultService } = require("./vaultService.cjs"); -test("vault service skeleton returns not-implemented for all handlers", async () => { - const service = createVaultService(); +test("vault service delegates host notes read to vault agent bridge", async () => { + let invokedOp = null; + const service = createVaultService({ + invokeVaultAgent: async (op, params) => { + invokedOp = op; + return { ok: true, hostId: params.hostId, notes: "hello" }; + }, + }); const result = await service.getHostNotes({ hostId: "host-1" }); + assert.equal(invokedOp, "host.notes.get"); + assert.equal(result.ok, true); + assert.equal(result.notes, "hello"); +}); + +test("vault service returns bridge unavailable when renderer bridge missing", async () => { + const service = createVaultService({}); + const result = await service.listSnippets(); assert.equal(result.ok, false); - assert.equal(result.code, "CAPABILITY_NOT_IMPLEMENTED"); + assert.match(result.error, /unavailable/i); }); diff --git a/electron/capabilities/types.cjs b/electron/capabilities/types.cjs index 28689262e..0a4e5a866 100644 --- a/electron/capabilities/types.cjs +++ b/electron/capabilities/types.cjs @@ -6,10 +6,12 @@ * @typedef {import('./constants.cjs').CapabilitySurface} CapabilitySurface * @typedef {import('./constants.cjs').CapabilityStatus} CapabilityStatus * @typedef {import('./constants.cjs').PermissionMode} PermissionMode + * @typedef {import('./constants.cjs').AgentKind} AgentKind * * @typedef {Object} CapabilitySurfaceBinding * @property {string} [rpcMethod] * @property {string} [mcpTool] + * @property {string} [toolName] * @property {string[]} [command] * @property {boolean} [confirmInConfirmMode] * @@ -29,6 +31,7 @@ * @property {string} description * @property {CapabilityPolicy} policy * @property {Partial>} surfaces + * @property {AgentKind[]} [agentKinds] Explicit agent placement; inferred when omitted (see resolveAgentKinds). * * @typedef {Object} RpcPermissionContext * @property {boolean} [chatSessionCancelled] diff --git a/electron/cli/netcatty-tool-cli.capabilities.test.cjs b/electron/cli/netcatty-tool-cli.capabilities.test.cjs index 6ee6402cd..2463aa55d 100644 --- a/electron/cli/netcatty-tool-cli.capabilities.test.cjs +++ b/electron/cli/netcatty-tool-cli.capabilities.test.cjs @@ -14,4 +14,6 @@ test("netcatty-tool-cli capabilities lists implemented commands without app conn const payload = JSON.parse(result.stdout); assert.equal(payload.ok, true); assert.ok(payload.capabilities.some((entry) => entry.id === "terminal.execute")); + assert.ok(payload.capabilities.some((entry) => entry.id === "vault.host.get")); + assert.ok(payload.capabilities.some((entry) => entry.id === "portforward.rules.list")); }); diff --git a/electron/cli/netcatty-tool-cli.cjs b/electron/cli/netcatty-tool-cli.cjs index 90b8ee483..67508d24a 100644 --- a/electron/cli/netcatty-tool-cli.cjs +++ b/electron/cli/netcatty-tool-cli.cjs @@ -4,44 +4,29 @@ const path = require("node:path"); const { connectClient, createError } = require("./netcattyRpcClient.cjs"); -const { listCliCapabilities } = require("../capabilities/adapters/cliAdapter.cjs"); +const { + buildCatalogCliParams, + formatCliHelpLines, + getCliRpcMethod, + listCliCapabilities, +} = require("../capabilities/adapters/cliAdapter.cjs"); +const { getCapabilityByCliCommand } = require("../capabilities/registry.cjs"); const { CAPABILITY_STATUS } = require("../capabilities/constants.cjs"); function printHelp() { + const catalogLines = formatCliHelpLines().join("\n"); process.stdout.write( "Netcatty Tool CLI\n\n" + "Usage:\n" + - " netcatty-tool-cli status [--json]\n" + - " netcatty-tool-cli env --chat-session [--json] [--scope-session ...]\n" + - " netcatty-tool-cli session --session --chat-session [--json] [--scope-session ...]\n" + - " netcatty-tool-cli exec --session --chat-session [--json] [--] \n" + - " netcatty-tool-cli job-start --session --chat-session [--json] [--] \n" + - " netcatty-tool-cli job-poll --job --chat-session [--offset ] [--json]\n" + - " netcatty-tool-cli job-stop --job --chat-session [--json]\n" + - " netcatty-tool-cli sftp list --session --remote-path --chat-session [--encoding ] [--json] [--scope-session ...]\n" + - " netcatty-tool-cli sftp read --session --remote-path --chat-session [--encoding ] [--json] [--scope-session ...]\n" + - " netcatty-tool-cli sftp write --session --remote-path --content --chat-session [--encoding ] [--json] [--scope-session ...]\n" + - " netcatty-tool-cli sftp download --session --remote-path --local-path --chat-session [--encoding ] [--json] [--scope-session ...]\n" + - " netcatty-tool-cli sftp upload --session --local-path --remote-path --chat-session [--encoding ] [--json] [--scope-session ...]\n" + - " netcatty-tool-cli sftp mkdir --session --remote-path --chat-session [--encoding ] [--json] [--scope-session ...]\n" + - " netcatty-tool-cli sftp delete --session --remote-path --chat-session [--encoding ] [--json] [--scope-session ...]\n" + - " netcatty-tool-cli sftp rename --session --old-remote-path --new-remote-path --chat-session [--encoding ] [--json] [--scope-session ...]\n" + - " netcatty-tool-cli sftp stat --session --remote-path --chat-session [--encoding ] [--json] [--scope-session ...]\n" + - " netcatty-tool-cli sftp chmod --session --remote-path --mode --chat-session [--encoding ] [--json] [--scope-session ...]\n" + - " netcatty-tool-cli sftp home --session --chat-session [--json] [--scope-session ...]\n" + - " netcatty-tool-cli cancel --chat-session [--json]\n" + - " netcatty-tool-cli resume --chat-session [--json]\n" + - " netcatty-tool-cli capabilities [--json] [--status implemented|planned|all]\n" + - " netcatty-tool-cli help\n\n" + + catalogLines + "\n\n" + "Examples:\n" + " netcatty-tool-cli status --json\n" + " netcatty-tool-cli env --chat-session ai_123 --json\n" + " netcatty-tool-cli session --session sess_123 --json --chat-session ai_123\n" + " netcatty-tool-cli exec --session sess_123 --chat-session ai_123 --json -- \"pwd\"\n" + - " netcatty-tool-cli job-start --session sess_123 --chat-session ai_123 --json -- \"npm run dev\"\n" + - " netcatty-tool-cli job-poll --job job_123 --chat-session ai_123 --offset 0 --json\n" + - " netcatty-tool-cli sftp list --session sess_123 --remote-path /etc --chat-session ai_123 --json\n" + - " netcatty-tool-cli sftp download --session sess_123 --remote-path /etc/hosts --local-path ./hosts.txt --chat-session ai_123 --json\n\n" + + " netcatty-tool-cli vault host get --host-id host_123 --json\n" + + " netcatty-tool-cli snippets run --snippet-id snip_1 --session sess_123 --chat-session ai_123 --json\n" + + " netcatty-tool-cli portforward rules list --json\n\n" + "Notes:\n" + " - Start the Netcatty desktop app before using this CLI.\n" + " - This CLI is intended as an internal Skills + CLI transport, not a general customer-facing shell tool.\n" + @@ -50,6 +35,7 @@ function printHelp() { " - `job-start` always requires both --session and --chat-session .\n" + " - `job-poll` and `job-stop` always require both --job and --chat-session .\n" + " - Every `sftp ` always requires both --session and --chat-session , and only works on connected SSH-backed sessions.\n" + + " - Vault/portforward/snippet commands use catalog-driven dispatch; see `capabilities --json` for the full list.\n" + " - After `--`, pass exactly one shell-ready command string. Preserve quoting inside that one argument.\n" + " - `cancel` stops in-flight execs, session-backed SFTP transfers, and running jobs for that chat session, then blocks further execs until `resume`.\n", ); @@ -85,6 +71,11 @@ function parseArgs(argv) { content: null, mode: null, encoding: null, + hostId: null, + snippetId: null, + ruleId: null, + notes: null, + variables: null, command: [], }; @@ -161,6 +152,31 @@ function parseArgs(argv) { i += 1; continue; } + if (arg === "--host-id") { + opts.hostId = readFlagValue(args, i + 1); + i += 1; + continue; + } + if (arg === "--snippet-id") { + opts.snippetId = readFlagValue(args, i + 1); + i += 1; + continue; + } + if (arg === "--rule-id") { + opts.ruleId = readFlagValue(args, i + 1); + i += 1; + continue; + } + if (arg === "--notes") { + opts.notes = readFlagValue(args, i + 1); + i += 1; + continue; + } + if (arg === "--variables") { + opts.variables = readFlagValue(args, i + 1); + i += 1; + continue; + } positionals.push(arg); } @@ -694,6 +710,31 @@ async function run() { return; } + const catalogCapability = getCapabilityByCliCommand(positionals); + if (catalogCapability) { + const rpcMethod = getCliRpcMethod(positionals); + if (!rpcMethod) { + throw createError("INVALID_ARGUMENT", `No RPC mapping for command: ${positionals.join(" ")}`); + } + if (catalogCapability.policy?.requiresChatSession && !opts.chatSessionId) { + throw createError( + "INVALID_ARGUMENT", + `Missing required --chat-session for ${positionals.join(" ")}.`, + ); + } + const params = buildCatalogCliParams(catalogCapability.id, opts, createError); + const result = ensureBridgeCallOk( + await client.call(rpcMethod, { ...params, ...buildScopeParams(opts) }), + "CAPABILITY_RPC_FAILED", + `Failed to execute ${catalogCapability.id}`, + ); + const payload = { ok: true, ...result }; + process.stdout.write(opts.json + ? `${JSON.stringify(payload, null, 2)}\n` + : `${JSON.stringify(result, null, 2)}\n`); + return; + } + throw createError("INVALID_ARGUMENT", `Unknown command: ${positionals.join(" ")}`); } catch (err) { const payload = toErrorPayload(err); diff --git a/electron/mcp/catalogToolMetadata.cjs b/electron/mcp/catalogToolMetadata.cjs new file mode 100644 index 000000000..a38a8e677 --- /dev/null +++ b/electron/mcp/catalogToolMetadata.cjs @@ -0,0 +1,20 @@ +"use strict"; + +const { listMcpTools } = require("../capabilities/codegen/toolSurfaces.cjs"); + +const mcpToolDescriptions = new Map( + listMcpTools().map((tool) => [tool.mcpTool, tool.description]), +); + +function getCatalogToolDescription(toolName) { + return mcpToolDescriptions.get(toolName) || null; +} + +function listCatalogMcpToolNames() { + return [...mcpToolDescriptions.keys()]; +} + +module.exports = { + getCatalogToolDescription, + listCatalogMcpToolNames, +}; diff --git a/electron/mcp/netcatty-mcp-server.cjs b/electron/mcp/netcatty-mcp-server.cjs index 4b2fcf2eb..be72fec20 100644 --- a/electron/mcp/netcatty-mcp-server.cjs +++ b/electron/mcp/netcatty-mcp-server.cjs @@ -10,7 +10,12 @@ const net = require("node:net"); const { McpServer } = require("@modelcontextprotocol/sdk/server/mcp.js"); const { StdioServerTransport } = require("@modelcontextprotocol/sdk/server/stdio.js"); -const { z } = require("zod"); +const { getCatalogToolDescription } = require("./catalogToolMetadata.cjs"); +const { registerMcpTools } = require("../capabilities/codegen/mcpToolRegistry.cjs"); + +function catalogDescription(toolName, fallback) { + return getCatalogToolDescription(toolName) || fallback; +} const DEBUG_MCP = process.env.NETCATTY_MCP_DEBUG === "1"; @@ -205,171 +210,13 @@ server.resource( }, ); -// Tool: get_environment -server.tool( - "get_environment", - "Get information about the current Netcatty scope: all terminal sessions exposed by Netcatty, their session IDs, OS, shell hints, and connection status. Sessions may be remote hosts, a local terminal, Mosh-backed shells, or serial port connections (network devices, embedded systems). Serial sessions have protocol 'serial' and shellType 'raw'. SSH sessions with deviceType 'network' are network equipment (Huawei VRP, Cisco IOS, etc.) using vendor CLIs instead of a standard shell. Call this first before executing commands.", - {}, - async () => { - process.stderr.write(`[netcatty-mcp] get_environment called, SCOPED_SESSION_IDS: ${JSON.stringify(SCOPED_SESSION_IDS)}, CHAT_SESSION_ID: ${CHAT_SESSION_ID}\n`); - const ctx = await rpcCall("netcatty/getContext", scopeParams); - process.stderr.write(`[netcatty-mcp] get_environment result: hostCount=${ctx.hostCount}, hosts=${JSON.stringify(ctx.hosts?.map(h => h.sessionId))}\n`); - debugLog("get_environment payload", { - hostCount: ctx?.hostCount, - hosts: Array.isArray(ctx?.hosts) ? ctx.hosts.map(h => ({ - sessionId: h.sessionId, - hostname: h.hostname, - connected: h.connected, - protocol: h.protocol, - deviceType: h.deviceType, - })) : [], - }); - return { - content: [{ - type: "text", - text: JSON.stringify(ctx, null, 2), - }], - }; - }, -); - -server.tool( - "list_attachments", - "List local files explicitly attached by the user in this Netcatty AI chat. Use this before read_attachment when the user asks about a pasted, dropped, or uploaded local file.", - {}, - async () => { - const result = await rpcCall("netcatty/listAttachments", scopeParams); - if (!result.ok) { - return { content: [{ type: "text", text: `Error: ${result.error || "Failed to list attachments"}` }], isError: true }; - } - return { content: [{ type: "text", text: JSON.stringify(result.attachments || [], null, 2) }] }; - }, -); - -server.tool( - "read_attachment", - "Read a local file explicitly attached by the user in this Netcatty AI chat. This tool only accepts file paths or filenames that were registered from user attachments; it cannot read arbitrary local files.", - { - filePath: z.string().optional().describe("Exact local attachment path shown in the prompt or returned by list_attachments."), - filename: z.string().optional().describe("Attachment filename returned by list_attachments. Use filePath when available."), - }, - async ({ filePath, filename }) => { - const result = await rpcCall("netcatty/readAttachment", { ...scopeParams, filePath, filename }); - if (!result.ok) { - return { content: [{ type: "text", text: `Error: ${result.error || "Failed to read attachment"}` }], isError: true }; - } - const payload = { - filename: result.filename, - mediaType: result.mediaType, - filePath: result.filePath, - sizeBytes: result.sizeBytes, - ...(result.text != null ? { text: result.text } : { base64Data: result.base64Data }), - }; - return { content: [{ type: "text", text: JSON.stringify(payload, null, 2) }] }; - }, -); - -// Tool: terminal_execute -server.tool( - "terminal_execute", - "Execute a short command on a Netcatty terminal session and wait for the full result. Use this only for commands expected to finish within about 60 seconds. For long-running commands such as builds, scans, log-following, or anything likely to exceed that budget, use terminal_start and then terminal_poll instead.", - { - sessionId: z.string().describe("The terminal session ID (from get_environment) to execute on."), - command: z.string().describe("The command to execute in the target session."), - }, - async ({ sessionId, command }) => { - debugLog("terminal_execute called", { sessionId, command }); - // skipBlocklist: bridge layer does session-aware blocklist (serial sessions skip shell patterns) - const guardErr = guardWriteOperation(command, { skipBlocklist: true }); - if (guardErr) { - debugLog("terminal_execute blocked locally", { sessionId, guardErr }); - return { content: [{ type: "text", text: `Error: ${guardErr}` }], isError: true }; - } - const result = await rpcCall("netcatty/exec", { ...scopeParams, sessionId, command }); - debugLog("terminal_execute result", { - sessionId, - ok: result?.ok, - error: result?.error, - exitCode: result?.exitCode, - stdoutLength: result?.stdout?.length || 0, - stderrLength: result?.stderr?.length || 0, - }); - if (!result.ok) { - return { content: [{ type: "text", text: `Error: ${result.error || "Command failed"}` }], isError: true }; - } - const parts = []; - if (result.stdout) parts.push(result.stdout); - if (result.stderr) parts.push(`[stderr] ${result.stderr}`); - // Serial/raw and network device sessions return null exitCode (vendor CLIs have no exit codes) - if (result.exitCode != null) { - parts.push(`[exit code: ${result.exitCode}]`); - } - return { content: [{ type: "text", text: parts.join("\n") }] }; - }, -); - -server.tool( - "terminal_start", - "Start a long-running command on a Netcatty terminal session without waiting for final completion. The command still runs in the visible terminal/PTTY so the user can watch live output. Prefer this whenever the command may exceed about 2 minutes, or when it streams output for an extended period, such as builds, scans, watch commands, and log-follow commands. After starting, wait at least about 30 seconds before the first terminal_poll unless you have a strong reason to check sooner.", - { - sessionId: z.string().describe("The terminal session ID (from get_environment) to execute on."), - command: z.string().describe("The command to start in the target session."), - }, - async ({ sessionId, command }) => { - const guardErr = guardWriteOperation(command, { skipBlocklist: true }); - if (guardErr) { - return { content: [{ type: "text", text: `Error: ${guardErr}` }], isError: true }; - } - const result = await rpcCall("netcatty/jobStart", { ...scopeParams, sessionId, command }); - if (!result.ok) { - return { content: [{ type: "text", text: `Error: ${result.error || "Failed to start background command"}` }], isError: true }; - } - return { - content: [{ - type: "text", - text: JSON.stringify({ - jobId: result.jobId, - sessionId: result.sessionId, - status: result.status, - startedAt: result.startedAt, - outputMode: result.outputMode, - recommendedPollIntervalMs: result.recommendedPollIntervalMs, - }, null, 2), - }], - }; - }, -); - -server.tool( - "terminal_poll", - "Poll a long-running Netcatty command that was started with terminal_start. Returns incremental output since the given offset and the current status. Use the returned nextOffset for the next poll. If outputTruncated is true, only the retained tail starting at outputBaseOffset is still available. Do not poll aggressively: wait at least about 30 seconds between polls unless the tool output explicitly justifies checking sooner. As soon as completed is true, stop polling and analyze the final result immediately.", - { - jobId: z.string().describe("The background job ID returned by terminal_start."), - offset: z.number().int().min(0).optional().describe("Character offset previously returned as nextOffset. Omit or use 0 on the first poll."), - }, - async ({ jobId, offset }) => { - const result = await rpcCall("netcatty/jobPoll", { ...scopeParams, jobId, offset: offset || 0 }); - if (!result.ok) { - return { content: [{ type: "text", text: `Error: ${result.error || "Failed to poll background command"}` }], isError: true }; - } - return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] }; - }, -); - -server.tool( - "terminal_stop", - "Stop a long-running Netcatty command that was started with terminal_start. This sends Ctrl+C to the running terminal job and returns its latest state.", - { - jobId: z.string().describe("The background job ID returned by terminal_start."), - }, - async ({ jobId }) => { - const result = await rpcCall("netcatty/jobStop", { ...scopeParams, jobId }); - if (!result.ok) { - return { content: [{ type: "text", text: `Error: ${result.error || "Failed to stop background command"}` }], isError: true }; - } - return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] }; - }, -); +// Register catalog-driven MCP tools (terminal, SFTP, attachments, vault, portforward). +registerMcpTools(server, { + rpcCall, + scopeParams, + guardWriteOperation, + catalogDescription, +}); // ── Start ── diff --git a/electron/preload/api.cjs b/electron/preload/api.cjs index feb957f7f..a5174cc21 100644 --- a/electron/preload/api.cjs +++ b/electron/preload/api.cjs @@ -934,6 +934,12 @@ function createPreloadApi(ctx) { aiCattyCancelExec: async (chatSessionId) => { return ipcRenderer.invoke("netcatty:ai:catty:cancel", { chatSessionId }); }, + aiSetChatSessionCancelled: async (chatSessionId, cancelled = true) => { + return ipcRenderer.invoke("netcatty:ai:chat-session:set-cancelled", { chatSessionId, cancelled }); + }, + aiCapability: async (rpcMethod, params, chatSessionId) => { + return ipcRenderer.invoke("netcatty:ai:capability", { rpcMethod, params, chatSessionId }); + }, aiDiscoverAgents: async (options) => { return ipcRenderer.invoke("netcatty:ai:agents:discover", options); }, @@ -977,6 +983,9 @@ function createPreloadApi(ctx) { aiMcpSetToolIntegrationMode: async (mode) => { return ipcRenderer.invoke("netcatty:ai:mcp:set-tool-integration-mode", { mode }); }, + aiMcpSyncPermissionGrants: async (grants) => { + return ipcRenderer.invoke("netcatty:ai:mcp:sync-permission-grants", { grants }); + }, aiUserSkillsGetStatus: async () => { return ipcRenderer.invoke("netcatty:ai:user-skills:status"); }, @@ -1001,6 +1010,14 @@ function createPreloadApi(ctx) { ipcRenderer.on("netcatty:ai:mcp:approval-cleared", handler); return () => ipcRenderer.removeListener("netcatty:ai:mcp:approval-cleared", handler); }, + onVaultAgentRequest: (cb) => { + const handler = (_event, payload) => cb(payload); + ipcRenderer.on("netcatty:ai:vault-agent:request", handler); + return () => ipcRenderer.removeListener("netcatty:ai:vault-agent:request", handler); + }, + respondVaultAgent: async (requestId, result) => { + return ipcRenderer.invoke("netcatty:ai:vault-agent:response", { requestId, result }); + }, // SDK external agent streaming aiSdkAgentStream: async (requestId, chatSessionId, sdkBackend, prompt, cwd, providerId, model, existingSessionId, historyMessages, images, toolIntegrationMode, defaultTargetSession, userSkillsContext, agentEnv, agentCommand) => { return ipcRenderer.invoke("netcatty:ai:sdk-agent:stream", { requestId, chatSessionId, sdkBackend, prompt, cwd, providerId, model, existingSessionId, historyMessages, images, toolIntegrationMode, defaultTargetSession, userSkillsContext, agentEnv, agentCommand }); diff --git a/electron/shared/approvalConstants.cjs b/electron/shared/approvalConstants.cjs new file mode 100644 index 000000000..3c6bb4cdb --- /dev/null +++ b/electron/shared/approvalConstants.cjs @@ -0,0 +1,10 @@ +"use strict"; + +/** Shared approval timeout constants for main-process bridges. */ +const CATTY_APPROVAL_TIMEOUT_MS = 5 * 60 * 1000; +const MCP_APPROVAL_TIMEOUT_MS = 110 * 1000; + +module.exports = { + CATTY_APPROVAL_TIMEOUT_MS, + MCP_APPROVAL_TIMEOUT_MS, +}; diff --git a/electron/shared/pathLikeCommand.cjs b/electron/shared/pathLikeCommand.cjs new file mode 100644 index 000000000..144d3e5ae --- /dev/null +++ b/electron/shared/pathLikeCommand.cjs @@ -0,0 +1,18 @@ +"use strict"; + +function isPathLikeCommand(command) { + const normalized = String(command || "").trim(); + return normalized.includes("/") || normalized.includes("\\") || /^[a-z]:/i.test(normalized); +} + +function getCommandBasename(command) { + const normalized = String(command || "").trim(); + if (!normalized) return ""; + const parts = normalized.split(/[\\/]/); + return (parts.pop() || "").toLowerCase(); +} + +module.exports = { + isPathLikeCommand, + getCommandBasename, +}; diff --git a/electron/shared/permissionGrants.cjs b/electron/shared/permissionGrants.cjs new file mode 100644 index 000000000..829add637 --- /dev/null +++ b/electron/shared/permissionGrants.cjs @@ -0,0 +1,133 @@ +"use strict"; + +/** + * Permission grant pattern matching — shared between main (MCP) and renderer. + */ + +function patternMatches(pattern, value) { + if (typeof pattern !== "string" || pattern.length === 0) return false; + if (pattern === "*") return true; + if (typeof value !== "string") return false; + + if (pattern.startsWith("host:")) { + const hostPattern = pattern.slice("host:".length); + return globOrRegexMatch(hostPattern, value); + } + + return globOrRegexMatch(pattern, value); +} + +function globOrRegexMatch(pattern, value) { + if (pattern.startsWith("/") && pattern.lastIndexOf("/") > 0) { + const lastSlash = pattern.lastIndexOf("/"); + const body = pattern.slice(1, lastSlash); + const flags = pattern.slice(lastSlash + 1); + try { + return new RegExp(body, flags).test(value); + } catch { + return false; + } + } + + if (!pattern.includes("*") && !pattern.includes("?")) { + return value === pattern; + } + + // OpenCode Wildcard.match semantics (trailing " *" allows optional args). + let escaped = pattern + .replace(/[.+^${}()|[\]\\]/g, "\\$&") + .replace(/\*/g, ".*") + .replace(/\?/g, "."); + if (escaped.endsWith(" .*")) { + escaped = `${escaped.slice(0, -3)}( .*)?`; + } + + return new RegExp(`^${escaped}$`, "s").test(value); +} + +function argsPatternMatches(argsPattern, args) { + if (!argsPattern || typeof argsPattern !== "object") return true; + if (!args || typeof args !== "object") return false; + + for (const [key, pattern] of Object.entries(argsPattern)) { + const argValue = args[key]; + if (typeof argValue === "undefined") return false; + if (!patternMatches(String(pattern), String(argValue))) return false; + } + return true; +} + +function matchPermissionGrant(rules, ctx) { + if (!Array.isArray(rules) || rules.length === 0) return null; + + const args = ctx?.args && typeof ctx.args === "object" ? ctx.args : {}; + + for (const rule of rules) { + if (!rule || typeof rule.capabilityId !== "string") continue; + + if (rule.capabilityId !== ctx?.capabilityId) continue; + + if (rule.commandPattern) { + const command = typeof args.command === "string" ? args.command : ""; + if (!patternMatches(rule.commandPattern, command)) continue; + } + + if (!argsPatternMatches(rule.argsPattern, args)) continue; + + return rule; + } + + return null; +} + +function sanitizePermissionGrants(raw) { + if (!Array.isArray(raw)) return []; + + const result = []; + for (const entry of raw) { + if (!entry || typeof entry !== "object") continue; + const capabilityId = typeof entry.capabilityId === "string" ? entry.capabilityId.trim() : ""; + if (!capabilityId) continue; + + const rule = { + id: typeof entry.id === "string" && entry.id.trim() + ? entry.id.trim().slice(0, 64) + : `grant_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`, + capabilityId, + sessionPattern: typeof entry.sessionPattern === "string" && entry.sessionPattern.trim() + ? entry.sessionPattern.trim() + : "*", + createdAt: typeof entry.createdAt === "number" && Number.isFinite(entry.createdAt) + ? entry.createdAt + : Date.now(), + }; + + if (typeof entry.commandPattern === "string" && entry.commandPattern.trim()) { + rule.commandPattern = entry.commandPattern.trim(); + } + if (entry.argsPattern && typeof entry.argsPattern === "object" && !Array.isArray(entry.argsPattern)) { + const argsPattern = {}; + for (const [key, value] of Object.entries(entry.argsPattern)) { + if (typeof value === "string" && value.trim()) { + argsPattern[key] = value.trim(); + } + } + if (Object.keys(argsPattern).length > 0) { + rule.argsPattern = argsPattern; + } + } + if (typeof entry.note === "string" && entry.note.trim()) { + rule.note = entry.note.trim().slice(0, 240); + } + + result.push(rule); + } + + return result; +} + +module.exports = { + patternMatches, + matchPermissionGrant, + sanitizePermissionGrants, +}; diff --git a/electron/shared/sdkSessionIdentity.cjs b/electron/shared/sdkSessionIdentity.cjs new file mode 100644 index 000000000..3d859fb61 --- /dev/null +++ b/electron/shared/sdkSessionIdentity.cjs @@ -0,0 +1,32 @@ +"use strict"; + +const SDK_SESSION_ID_PREFIX = "netcatty-sdk-session:"; + +function encodeSdkSessionIdentity(sessionId, sdkBackend, binPath) { + if (!sessionId || !sdkBackend) return sessionId; + const payload = { + v: 1, + id: sessionId, + backend: sdkBackend, + binPath: binPath || "", + }; + return `${SDK_SESSION_ID_PREFIX}${encodeURIComponent(JSON.stringify(payload))}`; +} + +function parseSdkSessionIdentity(value) { + const raw = String(value || "").trim(); + if (!raw.startsWith(SDK_SESSION_ID_PREFIX)) return null; + try { + const parsed = JSON.parse(decodeURIComponent(raw.slice(SDK_SESSION_ID_PREFIX.length))); + if (!parsed || parsed.v !== 1 || !parsed.id || !parsed.backend) return null; + return parsed; + } catch { + return null; + } +} + +module.exports = { + SDK_SESSION_ID_PREFIX, + encodeSdkSessionIdentity, + parseSdkSessionIdentity, +}; diff --git a/electron/shared/vaultAgentGuidance.cjs b/electron/shared/vaultAgentGuidance.cjs new file mode 100644 index 000000000..97fd77a33 --- /dev/null +++ b/electron/shared/vaultAgentGuidance.cjs @@ -0,0 +1,27 @@ +"use strict"; + +/** + * Shared Vault tool-selection guidance for MCP external agents and get_environment. + * Keep in sync with infrastructure/ai/cattyAgent/systemPrompt.ts (Catty sidebar). + */ +const VAULT_HOSTS_VS_NOTES_GUIDANCE = + "Vault → Hosts vs Vault → Notes: When the user asks to add/create/import a host " + + "(创建主机、添加主机、保存 SSH 连接凭据), use vault_hosts_create with dryRun=true first, " + + "or vault_hosts_import for known export formats (PuTTY, MobaXterm, CSV, SecureCRT, ssh_config) — " + + "NOT vault_notes_create. Extract hostname, username, password, port, group, tags, and label from the user's text; " + + "put long admin tables or remarks in the host notes field (host_notes_set / Host Details metadata), " + + "not Vault sidebar Notes. Use vault_notes_create or vault_notes_update ONLY when the user explicitly wants " + + "markdown documentation in Vault → Notes (保险箱笔记 sidebar). " + + "If vault_hosts_create or vault_hosts_import fails, report the error — do not silently create a Vault note instead."; + +function appendVaultAgentGuidance(description) { + const base = typeof description === "string" ? description.trim() : ""; + if (!base) return VAULT_HOSTS_VS_NOTES_GUIDANCE; + if (base.includes("Vault → Hosts vs Vault → Notes")) return base; + return `${base} ${VAULT_HOSTS_VS_NOTES_GUIDANCE}`; +} + +module.exports = { + VAULT_HOSTS_VS_NOTES_GUIDANCE, + appendVaultAgentGuidance, +}; diff --git a/electron/shared/vaultAgentGuidance.test.cjs b/electron/shared/vaultAgentGuidance.test.cjs new file mode 100644 index 000000000..3bd6416de --- /dev/null +++ b/electron/shared/vaultAgentGuidance.test.cjs @@ -0,0 +1,24 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { + VAULT_HOSTS_VS_NOTES_GUIDANCE, + appendVaultAgentGuidance, +} = require("./vaultAgentGuidance.cjs"); + +test("VAULT_HOSTS_VS_NOTES_GUIDANCE forbids note fallback for host creation", () => { + assert.match(VAULT_HOSTS_VS_NOTES_GUIDANCE, /vault_hosts_create/i); + assert.match(VAULT_HOSTS_VS_NOTES_GUIDANCE, /NOT vault_notes_create/i); + assert.match(VAULT_HOSTS_VS_NOTES_GUIDANCE, /do not silently create a Vault note/i); +}); + +test("appendVaultAgentGuidance appends guidance once", () => { + const once = appendVaultAgentGuidance("Netcatty terminal manager."); + assert.match(once, /Netcatty terminal manager/); + assert.match(once, /Vault → Hosts vs Vault → Notes/); + + const twice = appendVaultAgentGuidance(once); + assert.equal(twice, once); +}); diff --git a/infrastructure/ai/agentKinds.ts b/infrastructure/ai/agentKinds.ts new file mode 100644 index 000000000..9f2e0f4a1 --- /dev/null +++ b/infrastructure/ai/agentKinds.ts @@ -0,0 +1,12 @@ +/** Where an in-app agent runs — distinct from RPC/MCP/CLI capability surfaces. */ +export const AGENT_KINDS = { + /** Chat side panel (Catty). */ + SIDEBAR: 'sidebar', + /** Future app-wide agent (cross-window / proactive). */ + GLOBAL: 'global', +} as const; + +export type AgentKind = (typeof AGENT_KINDS)[keyof typeof AGENT_KINDS]; + +export const SIDEBAR_AGENT_KIND: AgentKind = AGENT_KINDS.SIDEBAR; +export const GLOBAL_AGENT_KIND: AgentKind = AGENT_KINDS.GLOBAL; diff --git a/infrastructure/ai/cattyAgent/executor.ts b/infrastructure/ai/cattyAgent/executor.ts index df01f8c02..f60616c92 100644 --- a/infrastructure/ai/cattyAgent/executor.ts +++ b/infrastructure/ai/cattyAgent/executor.ts @@ -33,6 +33,12 @@ export interface NetcattyBridge { * `aiExec` but before the main process has registered it. */ aiCattyCancelExec?(chatSessionId: string): Promise; + aiSetChatSessionCancelled?(chatSessionId: string, cancelled?: boolean): Promise<{ ok: boolean; error?: string }>; + aiCapability?( + rpcMethod: string, + params: Record, + chatSessionId?: string, + ): Promise; } // Workspace context provided to the executor diff --git a/infrastructure/ai/cattyAgent/systemPrompt.ts b/infrastructure/ai/cattyAgent/systemPrompt.ts index 6ff79f2d1..4841c7911 100644 --- a/infrastructure/ai/cattyAgent/systemPrompt.ts +++ b/infrastructure/ai/cattyAgent/systemPrompt.ts @@ -3,6 +3,7 @@ export interface SystemPromptContext { scopeLabel?: string; hosts: Array<{ sessionId: string; + hostId?: string; hostname: string; label: string; os?: string; @@ -11,6 +12,14 @@ export interface SystemPromptContext { shellType?: string; deviceType?: string; connected: boolean; + hostChain?: Array<{ hostId: string; label?: string; hostname?: string }>; + activePortForwards?: Array<{ + ruleId: string; + label?: string; + type?: string; + localPort?: number; + status?: string; + }>; }>; permissionMode: 'observer' | 'confirm' | 'autonomous'; webSearchEnabled?: boolean; @@ -42,7 +51,15 @@ ${permissionRules} 1. **Plan before acting.** When a task involves multiple steps, present a brief numbered plan to the user before executing. -2. **Use the right tool.** For normal shell commands, use \`terminal_execute\` so you receive the command output. When operating on multiple sessions, call \`terminal_execute\` for each target session. +2. **Use the right tool.** For normal shell commands, use \`terminal_execute\`. SFTP read/write, vault snippets, port forwarding, vault notes, and vault host tools are available when listed in your tool set — prefer them over manual shell workarounds. + + **Vault → Hosts (SSH connections):** When the user asks to **add/create/import a host** (创建主机、添加主机、保存服务器连接凭据), use \`vault_hosts_create\` — NOT \`vault_notes_create\`. Extract \`hostname\`, \`username\`, \`password\`, \`port\`, \`group\`, \`tags\`, and \`label\` from the user's text; put long admin tables or remarks in the host's \`notes\` field (Host Details metadata). Call with \`dryRun: true\` first to preview, then write. Only use \`vault_hosts_import\` for known export formats (PuTTY, MobaXterm, CSV, SecureCRT, ssh_config). Use \`vault_hosts_list\` to check existing hosts. + + **Vault → Notes (sidebar markdown docs):** When the user explicitly wants documentation saved to **Vault → Notes** (the notes sidebar / 保险箱笔记), use \`vault_notes_create\` or \`vault_notes_update\` — **not** \`host_notes_set\` (Host Details only) and **not** as a substitute for creating a host. + + **Never fallback:** If \`vault_hosts_create\` or \`vault_hosts_import\` fails, report the error to the user. Do **not** silently create a Vault note instead of the requested host. + + When the user pastes unstructured text with host/server info, **you** extract fields and call \`vault_hosts_create\`. When operating on multiple sessions, call \`terminal_execute\` for each target session. 3. **Never execute dangerous commands.** Commands matching the blocklist (e.g. \`rm -rf /\`, \`mkfs\`, \`dd\` to disk devices, \`shutdown\`, fork bombs, recursive chmod 777 on root) are strictly forbidden and will be automatically denied. Do not attempt to bypass these restrictions. @@ -78,6 +95,29 @@ function buildScopeDescription( } } +function formatHostChain( + hostChain: SystemPromptContext['hosts'][number]['hostChain'], +): string | null { + if (!hostChain?.length) return null; + return hostChain + .map((hop) => hop.label || hop.hostname || hop.hostId) + .join(' → '); +} + +function formatActivePortForwards( + activePortForwards: SystemPromptContext['hosts'][number]['activePortForwards'], +): string | null { + if (!activePortForwards?.length) return null; + return activePortForwards + .map((rule) => { + const label = rule.label || rule.ruleId; + const port = rule.localPort != null ? `:${rule.localPort}` : ''; + const status = rule.status ? ` (${rule.status})` : ''; + return `${label}${port}${status}`; + }) + .join(', '); +} + function buildHostList( hosts: SystemPromptContext['hosts'], ): string { @@ -87,6 +127,8 @@ function buildHostList( const lines = hosts.map(host => { const status = host.connected ? 'connected' : 'disconnected'; + const hostChain = formatHostChain(host.hostChain); + const portForwards = formatActivePortForwards(host.activePortForwards); const details = [ `hostname: ${host.hostname}`, `label: ${host.label}`, @@ -95,6 +137,8 @@ function buildHostList( host.username ? `user: ${host.username}` : null, host.shellType ? `shell: ${host.shellType}` : null, host.deviceType ? `deviceType: ${host.deviceType}` : null, + hostChain ? `hostChain: ${hostChain}` : null, + portForwards ? `portForwards: ${portForwards}` : null, `status: ${status}`, ] .filter(Boolean) diff --git a/infrastructure/ai/contextCompaction.ts b/infrastructure/ai/contextCompaction.ts index 7ef9a1f24..6efc0359d 100644 --- a/infrastructure/ai/contextCompaction.ts +++ b/infrastructure/ai/contextCompaction.ts @@ -1,5 +1,6 @@ import type { ModelMessage } from "ai"; import type { ProviderConfig } from "./types"; +import { estimateModelMessagesTokensWithKind } from "./harness/tokenEstimator"; const DEFAULT_COMPACTION_RATIO = 0.85; const TOKEN_CHARS = 4; @@ -76,10 +77,7 @@ export function sanitizeContextWindow(value: unknown): number | undefined { } export function estimateModelMessagesTokens(messages: ModelMessage[]): number { - const chars = messages.reduce((total, message) => { - return total + estimateUnknownChars(message.role) + estimateUnknownChars(message.content); - }, 0); - return Math.ceil(chars / TOKEN_CHARS); + return estimateModelMessagesTokensWithKind({ messages }).tokens; } export function estimateUnknownTokens(value: unknown): number { diff --git a/infrastructure/ai/harness/agentEventAdapter.ts b/infrastructure/ai/harness/agentEventAdapter.ts new file mode 100644 index 000000000..16dbea152 --- /dev/null +++ b/infrastructure/ai/harness/agentEventAdapter.ts @@ -0,0 +1,171 @@ +import type { AgentEvent, AgentEventListener } from './types'; + +let eventCounter = 0; + +function nextEventId(prefix: string): string { + eventCounter += 1; + return `${prefix}-${Date.now()}-${eventCounter}`; +} + +export interface StreamEventContext { + sessionId: string; + chatSessionId?: string; + turnId?: string; +} + +export interface CattyStreamChunk { + type: string; + text?: string; + textDelta?: string; + delta?: string; + toolCallId?: string; + toolName?: string; + input?: unknown; + args?: unknown; + output?: unknown; + result?: unknown; + error?: unknown; +} + +function isToolResultError(output: unknown): boolean { + if (output == null) return false; + if (typeof output === 'object') { + const obj = output as Record; + if ('error' in obj && typeof obj.error === 'string') return true; + if ('ok' in obj && obj.ok === false) return true; + } + if (typeof output === 'string') { + try { + const parsed = JSON.parse(output) as Record; + if ('error' in parsed && typeof parsed.error === 'string') return true; + if ('ok' in parsed && parsed.ok === false) return true; + } catch { + return false; + } + } + return false; +} + +export function mapSdkStreamEventToAgentEvents( + event: Record, + ctx: StreamEventContext, +): AgentEvent[] { + const base = { + sessionId: ctx.sessionId, + chatSessionId: ctx.chatSessionId, + backend: 'external-sdk' as const, + timestamp: Date.now(), + turnId: ctx.turnId, + }; + + switch (event.type) { + case 'text-delta': + return [{ + ...base, + id: nextEventId('model-delta'), + type: 'model_delta', + text: String(event.text ?? event.textDelta ?? event.delta ?? ''), + }]; + case 'thinking-delta': + case 'reasoning-delta': + return [{ + ...base, + id: nextEventId('reasoning-delta'), + type: 'reasoning_delta', + text: String(event.text ?? event.textDelta ?? event.delta ?? ''), + }]; + case 'tool-call': + return [{ + ...base, + id: nextEventId('tool-call'), + type: 'tool_call', + toolCallId: String(event.toolCallId ?? event.id ?? ''), + toolName: String(event.toolName ?? event.name ?? 'unknown'), + args: (event.args ?? event.input ?? {}) as Record, + }]; + case 'tool-result': + return [{ + ...base, + id: nextEventId('tool-result'), + type: 'tool_result', + toolCallId: String(event.toolCallId ?? ''), + toolName: typeof event.toolName === 'string' ? event.toolName : undefined, + result: String(event.result ?? event.output ?? ''), + isError: Boolean(event.isError), + }]; + case 'error': + return [{ + ...base, + id: nextEventId('error'), + type: 'error', + message: String(event.error ?? event.message ?? 'Unknown SDK error'), + recoverable: false, + }]; + default: + return []; + } +} + +export function mapCattyStreamChunkToAgentEvents( + chunk: CattyStreamChunk, + ctx: StreamEventContext, +): AgentEvent[] { + const base = { + sessionId: ctx.sessionId, + chatSessionId: ctx.chatSessionId, + backend: 'catty' as const, + timestamp: Date.now(), + turnId: ctx.turnId, + }; + + if (chunk.type === 'text' || chunk.type === 'text-delta') { + const text = chunk.text ?? chunk.textDelta ?? ''; + if (!text) return []; + return [{ ...base, id: nextEventId('model-delta'), type: 'model_delta', text }]; + } + + if (chunk.type === 'reasoning' || chunk.type === 'reasoning-start' || chunk.type === 'reasoning-delta') { + const text = chunk.text ?? chunk.textDelta ?? chunk.delta ?? ''; + if (!text) return []; + return [{ ...base, id: nextEventId('reasoning-delta'), type: 'reasoning_delta', text }]; + } + + if (chunk.type === 'tool-call' && chunk.toolCallId && chunk.toolName) { + return [{ + ...base, + id: nextEventId('tool-call'), + type: 'tool_call', + toolCallId: chunk.toolCallId, + toolName: chunk.toolName, + args: (chunk.input ?? chunk.args ?? {}) as Record, + }]; + } + + if (chunk.type === 'tool-result' && chunk.toolCallId) { + const output = chunk.output ?? chunk.result; + const resultText = typeof output === 'string' ? output : JSON.stringify(output ?? ''); + return [{ + ...base, + id: nextEventId('tool-result'), + type: 'tool_result', + toolCallId: chunk.toolCallId, + result: resultText, + isError: isToolResultError(output), + }]; + } + + if (chunk.type === 'error') { + const message = chunk.error instanceof Error + ? chunk.error.message + : String(chunk.error ?? 'Unknown stream error'); + return [{ ...base, id: nextEventId('error'), type: 'error', message }]; + } + + return []; +} + +export function createHarnessEventSink( + listener: AgentEventListener, +): AgentEventListener { + return (event) => listener(event); +} diff --git a/infrastructure/ai/harness/agentRuntime.test.ts b/infrastructure/ai/harness/agentRuntime.test.ts new file mode 100644 index 000000000..ed956472d --- /dev/null +++ b/infrastructure/ai/harness/agentRuntime.test.ts @@ -0,0 +1,68 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { AgentRuntime } from './agentRuntime'; +import { TraceStore } from './traceStore'; +import type { TurnDriver, TurnDriverContext, TurnInput } from './turnDrivers/types'; + +class MockTurnDriver implements TurnDriver { + readonly backend = 'catty' as const; + readonly runs: TurnInput[] = []; + + async run(input: TurnInput, ctx: TurnDriverContext): Promise { + this.runs.push(input); + ctx.emit({ + id: 'model-delta-1', + type: 'model_delta', + text: 'hello', + } as import('./types').AgentEvent); + if (input.signal.aborted) return; + } + + abort(): void {} +} + +test('AgentRuntime runTurn emits turn lifecycle and records trace', async () => { + const traceStore = new TraceStore(); + const driver = new MockTurnDriver(); + const runtime = new AgentRuntime({ drivers: [driver], traceStore }); + const events: string[] = []; + runtime.subscribe(event => events.push(event.type)); + + const controller = new AbortController(); + const result = await runtime.runTurn({ + backend: 'catty', + chatSessionId: 'chat-1', + sendScopeKey: 'chat-1', + userText: 'hi', + signal: controller.signal, + currentSession: undefined, + assistantMsgId: 'assistant-1', + context: { + activeProvider: undefined, + activeModelId: '', + scopeType: 'terminal', + globalPermissionMode: 'confirm', + terminalSessions: [], + autoTitleSession: () => {}, + }, + maxIterations: 5, + ui: { + addMessageToSession: () => {}, + updateLastMessage: () => {}, + updateMessageById: () => {}, + reportStreamError: () => {}, + setStreamingForScope: () => {}, + }, + }); + + assert.equal(result.reason, 'completed'); + assert.equal(driver.runs.length, 1); + assert.deepEqual(events, ['turn_start', 'model_delta', 'turn_end']); + assert.equal(traceStore.getEvents('chat-1').length, 3); +}); + +test('AgentRuntime stopTurn delegates to active driver', async () => { + const driver = new MockTurnDriver(); + const runtime = new AgentRuntime({ drivers: [driver] }); + await runtime.stopTurn('chat-2'); +}); diff --git a/infrastructure/ai/harness/agentRuntime.ts b/infrastructure/ai/harness/agentRuntime.ts new file mode 100644 index 000000000..585a77740 --- /dev/null +++ b/infrastructure/ai/harness/agentRuntime.ts @@ -0,0 +1,177 @@ +import { globalTraceStore } from './traceStore'; +import { stopAgentTurn } from './agentStop'; +import type { AgentBackend, AgentEvent, AgentEventListener } from './types'; +import { ToolOutputStore } from './toolOutputStore'; +import { ToolResultDedup } from './toolResultDedup'; +import type { TurnDriver, TurnInput, TurnResult } from './turnDrivers/types'; + +let turnCounter = 0; + +function nextTurnId(): string { + turnCounter += 1; + return `turn-${Date.now()}-${turnCounter}`; +} + +interface ActiveTurn { + turnId: string; + backend: AgentBackend; + driver: TurnDriver; +} + +export interface AgentRuntimeOptions { + drivers: TurnDriver[]; + traceStore?: typeof globalTraceStore; +} + +export class AgentRuntime { + private readonly drivers = new Map(); + private readonly listeners = new Set(); + private readonly activeTurns = new Map(); + private readonly activeTurnPromises = new Map>(); + private readonly toolOutputStores = new Map(); + private readonly traceStore: typeof globalTraceStore; + + constructor(options: AgentRuntimeOptions) { + for (const driver of options.drivers) { + this.drivers.set(driver.backend, driver); + } + this.traceStore = options.traceStore ?? globalTraceStore; + } + + getToolOutputStore(chatSessionId: string): ToolOutputStore { + let store = this.toolOutputStores.get(chatSessionId); + if (!store) { + store = new ToolOutputStore(); + this.toolOutputStores.set(chatSessionId, store); + } + return store; + } + + clearChatSession(chatSessionId: string): void { + this.toolOutputStores.get(chatSessionId)?.prune(chatSessionId); + this.toolOutputStores.delete(chatSessionId); + } + + async waitForActiveTurn(chatSessionId: string): Promise { + await this.activeTurnPromises.get(chatSessionId)?.catch(() => {}); + } + + subscribe(listener: AgentEventListener): () => void { + this.listeners.add(listener); + return () => { + this.listeners.delete(listener); + }; + } + + async runTurn(input: TurnInput): Promise { + const driver = this.drivers.get(input.backend); + if (!driver) { + throw new Error(`No TurnDriver registered for backend "${input.backend}"`); + } + + const chatSessionId = input.chatSessionId; + const priorTurn = this.activeTurnPromises.get(chatSessionId); + if (priorTurn) { + await priorTurn.catch(() => {}); + } + + const turnPromise = this.runTurnInternal(input, driver); + this.activeTurnPromises.set(chatSessionId, turnPromise); + try { + return await turnPromise; + } finally { + if (this.activeTurnPromises.get(chatSessionId) === turnPromise) { + this.activeTurnPromises.delete(chatSessionId); + } + } + } + + private async runTurnInternal(input: TurnInput, driver: TurnDriver): Promise { + const turnId = nextTurnId(); + const chatSessionId = input.chatSessionId; + const toolOutputStore = this.getToolOutputStore(chatSessionId); + const toolResultDedup = new ToolResultDedup(); + toolResultDedup.beginTurn(); + + this.activeTurns.set(chatSessionId, { + turnId, + backend: input.backend, + driver, + }); + + const emit = ( + partial: Omit + & Partial>, + ) => { + const event = { + id: partial.id, + type: partial.type, + sessionId: partial.sessionId ?? chatSessionId, + chatSessionId: partial.chatSessionId ?? chatSessionId, + backend: partial.backend ?? input.backend, + timestamp: partial.timestamp ?? Date.now(), + turnId: partial.turnId ?? turnId, + ...partial, + } as AgentEvent; + this.traceStore.append(event); + for (const listener of this.listeners) { + listener(event); + } + }; + + emit({ + id: `turn-start-${turnId}`, + type: 'turn_start', + backendLabel: input.backend === 'external-sdk' + ? ('agentConfig' in input ? input.agentConfig.name : undefined) + : 'catty', + } as AgentEvent); + + let reason: TurnResult['reason'] = 'completed'; + + try { + await driver.run(input, { + turnId, + chatSessionId, + sessionId: chatSessionId, + backend: input.backend, + signal: input.signal, + emit, + toolOutputStore, + toolResultDedup, + }); + if (input.signal.aborted) { + reason = 'aborted'; + } + } catch (err) { + reason = 'error'; + emit({ + id: `turn-error-${turnId}`, + type: 'error', + message: err instanceof Error ? err.message : String(err), + recoverable: false, + } as AgentEvent); + throw err; + } finally { + emit({ + id: `turn-end-${turnId}`, + type: 'turn_end', + reason, + } as AgentEvent); + this.activeTurns.delete(chatSessionId); + } + + return { turnId, reason }; + } + + async stopTurn(chatSessionId: string, reason: 'user' | 'slash' = 'user'): Promise { + const active = this.activeTurns.get(chatSessionId); + active?.driver.abort?.(chatSessionId); + await stopAgentTurn({ + chatSessionId, + reason, + backend: active?.backend ?? 'catty', + }); + await this.waitForActiveTurn(chatSessionId); + } +} diff --git a/infrastructure/ai/harness/agentStop.test.ts b/infrastructure/ai/harness/agentStop.test.ts new file mode 100644 index 000000000..3a5dbfea7 --- /dev/null +++ b/infrastructure/ai/harness/agentStop.test.ts @@ -0,0 +1,40 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { stopAgentTurn } from './agentStop'; +import { globalTraceStore } from './traceStore'; + +describe('stopAgentTurn', () => { + it('aborts, cancels bridge surfaces, and emits turn_end', async () => { + const calls: string[] = []; + const controller = new AbortController(); + const sessionId = 'chat-stop-test'; + + globalTraceStore.clear(sessionId); + + await stopAgentTurn({ + chatSessionId: sessionId, + abortController: controller, + bridge: { + aiCattyCancelExec: async (id) => { calls.push(`catty:${id}`); }, + aiSdkAgentCancel: async (_req, id) => { calls.push(`sdk:${id}`); return { ok: true }; }, + aiSetChatSessionCancelled: async (id, cancelled) => { + calls.push(`cancelled:${id}:${cancelled}`); + return { ok: true }; + }, + }, + reason: 'slash', + backend: 'catty', + }); + + assert.equal(controller.signal.aborted, true); + assert.deepEqual(calls, [ + `catty:${sessionId}`, + `sdk:${sessionId}`, + `cancelled:${sessionId}:true`, + ]); + + const events = globalTraceStore.getEvents(sessionId); + assert.equal(events.at(-1)?.type, 'turn_end'); + assert.equal((events.at(-1) as { reason?: string }).reason, 'aborted'); + }); +}); diff --git a/infrastructure/ai/harness/agentStop.ts b/infrastructure/ai/harness/agentStop.ts new file mode 100644 index 000000000..55e66f99f --- /dev/null +++ b/infrastructure/ai/harness/agentStop.ts @@ -0,0 +1,73 @@ +import { clearAllPendingApprovals } from '../shared/approvalGate'; +import { globalTraceStore } from './traceStore'; +import type { AgentBackend } from './types'; + +export type StopAgentTurnReason = 'user' | 'slash'; + +export interface AgentStopBridge { + aiCattyCancelExec?(chatSessionId: string): Promise; + aiSdkAgentCancel?(requestId: string, chatSessionId?: string): Promise<{ ok: boolean; error?: string }>; + aiSetChatSessionCancelled?(chatSessionId: string, cancelled?: boolean): Promise<{ ok: boolean; error?: string }>; +} + +export interface StopAgentTurnParams { + chatSessionId: string; + abortController?: AbortController | null; + bridge?: AgentStopBridge | null; + reason?: StopAgentTurnReason; + backend?: AgentBackend; +} + +let stopEventCounter = 0; + +function nextStopEventId(): string { + stopEventCounter += 1; + return `turn-end-${Date.now()}-${stopEventCounter}`; +} + +/** + * Unified stop entry for Catty, external SDK, and MCP tool surfaces. + */ +export async function stopAgentTurn({ + chatSessionId, + abortController, + bridge, + reason = 'user', + backend = 'catty', +}: StopAgentTurnParams): Promise { + abortController?.abort(); + clearAllPendingApprovals(chatSessionId); + + const tasks: Array> = []; + if (bridge?.aiCattyCancelExec) { + tasks.push(bridge.aiCattyCancelExec(chatSessionId).catch(() => {})); + } + if (bridge?.aiSdkAgentCancel) { + tasks.push(bridge.aiSdkAgentCancel('', chatSessionId).catch(() => {})); + } + if (bridge?.aiSetChatSessionCancelled) { + tasks.push(bridge.aiSetChatSessionCancelled(chatSessionId, true).catch(() => {})); + } + await Promise.all(tasks); + + globalTraceStore.append({ + id: nextStopEventId(), + type: 'turn_end', + sessionId: chatSessionId, + chatSessionId, + backend, + timestamp: Date.now(), + reason: 'aborted', + ...(reason === 'slash' ? { backendLabel: 'slash-stop' } : {}), + }); +} + +/** + * Clear the main-process cancelled flag when a new agent turn begins. + */ +export async function clearChatSessionCancelled( + chatSessionId: string, + bridge?: AgentStopBridge | null, +): Promise { + await bridge?.aiSetChatSessionCancelled?.(chatSessionId, false).catch(() => {}); +} diff --git a/infrastructure/ai/harness/capabilityTools.test.ts b/infrastructure/ai/harness/capabilityTools.test.ts new file mode 100644 index 000000000..4bd1dae8a --- /dev/null +++ b/infrastructure/ai/harness/capabilityTools.test.ts @@ -0,0 +1,31 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { resolveSessionQueueKeyForTests } from './capabilityTools'; + +describe('capabilityTools session queue keys', () => { + it('does not queue read-only harness tools behind terminal session writes', () => { + const key = resolveSessionQueueKeyForTests( + { + capabilityId: 'harness.workspace.get_session_info', + toolName: 'workspace_get_session_info', + policy: { write: false, bypassesApproval: true }, + }, + { sessionId: 'session-a' }, + 'chat-1', + ); + assert.equal(key, null); + }); + + it('still serializes terminal.execute on the same session', () => { + const key = resolveSessionQueueKeyForTests( + { + capabilityId: 'terminal.execute', + toolName: 'terminal_execute', + policy: { write: true, bypassesApproval: false }, + }, + { sessionId: 'session-a', command: 'ls' }, + 'chat-1', + ); + assert.equal(key, 'chat-1:session-a'); + }); +}); diff --git a/infrastructure/ai/harness/capabilityTools.ts b/infrastructure/ai/harness/capabilityTools.ts new file mode 100644 index 000000000..98c7d0f6c --- /dev/null +++ b/infrastructure/ai/harness/capabilityTools.ts @@ -0,0 +1,419 @@ +import { tool } from 'ai'; +import { z } from 'zod'; +import type { NetcattyBridge } from '../cattyAgent/executor'; +import type { AIPermissionMode } from '../types'; +import type { WebSearchConfig } from '../types'; +import { isWebSearchReady } from '../types'; +import { + executeTerminalExecute, + executeWorkspaceGetInfo, + executeWorkspaceGetSessionInfo, + executeWebSearch, + executeUrlFetch, + type ToolDeps, + type ToolExecResult, +} from '../shared/toolExecutors'; +import { requestApproval } from '../shared/approvalGate'; +import { reserveSessionSlot } from '../shared/sessionExecutionQueue'; +import { fitTerminalExecuteResultForModel } from './terminalCompression'; +import type { ToolOutputStore } from './toolOutputStore'; +import { + hashScopeKey, + previewToolResult, + type ToolResultDedup, +} from './toolResultDedup'; +import cattyToolSpecs from './generated/cattyToolSpecs.json'; + +type FieldShape = { + type: string; + optional?: boolean; + description?: string; +}; + +type CattyToolSpec = { + capabilityId: string; + toolName: string; + rpcMethod: string | null; + localExecution?: boolean; + description: string; + inputShape: Record; + policy: { + write: boolean; + bypassesApproval: boolean; + }; +}; + +function buildZodObject(shape: Record): z.ZodObject> { + const entries: Record = {}; + for (const [key, field] of Object.entries(shape)) { + let schema: z.ZodTypeAny = field.type === 'number' ? z.number() : z.string(); + if (field.description) { + schema = schema.describe(field.description); + } + entries[key] = field.optional ? schema.optional() : schema; + } + return z.object(entries); +} + +function unwrap(r: ToolExecResult): T | { error: string } { + if (r.ok === false) return { error: r.error }; + return r.data; +} + +async function invokeCapabilityRpc( + bridge: NetcattyBridge, + rpcMethod: string, + params: Record, + chatSessionId?: string, +): Promise { + if (!bridge.aiCapability) { + return { error: 'Capability bridge is unavailable in this environment.' }; + } + const result = await bridge.aiCapability(rpcMethod, params, chatSessionId); + if (result && typeof result === 'object' && 'ok' in result && (result as { ok: boolean }).ok === false) { + return { error: (result as { error?: string }).error || 'Capability call failed.' }; + } + return result; +} + +async function tryFetchHostEnvironment( + bridge: NetcattyBridge, + chatSessionId?: string, +): Promise | null> { + if (!bridge.aiCapability || !chatSessionId) return null; + try { + const environment = await invokeCapabilityRpc( + bridge, + 'netcatty/getContext', + {}, + chatSessionId, + ); + if (environment && typeof environment === 'object' && !('error' in environment)) { + return environment as Record; + } + } catch { + // IPC failures must not block read-only harness tools. + } + return null; +} + +function applyToolDedup( + toolName: string, + fingerprint: string, + result: unknown, + dedup?: ToolResultDedup, +): unknown { + if (!dedup) return result; + const cached = dedup.check(fingerprint); + if (cached) { + return dedup.buildCachedNotice(cached); + } + dedup.remember(toolName, fingerprint, previewToolResult(result)); + return result; +} + +interface LocalExecutionContext { + deps: ToolDeps; + spec: CattyToolSpec; + args: Record; + toolOutputStore?: ToolOutputStore; + toolResultDedup?: ToolResultDedup; + chatSessionId?: string; +} + +async function executeLocalCattyCapability(ctx: LocalExecutionContext): Promise { + const { deps, spec, args, toolOutputStore, toolResultDedup, chatSessionId } = ctx; + const resolveContext = () => (typeof deps.context === 'function' ? deps.context() : deps.context); + + switch (spec.capabilityId) { + case 'harness.tool_output.read': { + const { handleId, mode, maxChars } = args as { + handleId: string; + mode?: 'head' | 'tail' | 'full'; + maxChars?: number; + }; + if (!toolOutputStore || !chatSessionId) { + return { error: 'Tool output store is unavailable.' }; + } + const content = toolOutputStore.read({ handleId, mode, maxChars }, chatSessionId); + if (content == null) { + return { error: `Handle "${handleId}" was not found for this chat session.` }; + } + return { handleId, mode: mode ?? 'head', content }; + } + case 'harness.workspace.get_info': { + const scopeCtx = resolveContext(); + const fingerprint = toolResultDedup?.fingerprintFor( + spec.toolName, + hashScopeKey([chatSessionId, scopeCtx.workspaceId, String(scopeCtx.sessions?.length ?? 0)]), + ); + const local = executeWorkspaceGetInfo(deps); + if (local.ok === false) { + return unwrap(local); + } + let merged: unknown = local.data; + const environment = await tryFetchHostEnvironment(deps.bridge, chatSessionId); + if (environment) { + const hosts = Array.isArray(environment.hosts) + ? (environment.hosts as Array>) + : []; + const hostBySessionId = new Map(hosts.map((host) => [String(host.sessionId), host])); + merged = { + ...local.data, + sessions: local.data.sessions.map((session) => ({ + ...session, + ...(hostBySessionId.get(session.sessionId) ?? {}), + })), + activePortForwardTunnels: environment.activePortForwardTunnels, + }; + } + if (fingerprint) { + return applyToolDedup(spec.toolName, fingerprint, merged, toolResultDedup); + } + return merged; + } + case 'harness.workspace.get_session_info': { + const { sessionId } = args as { sessionId: string }; + const local = executeWorkspaceGetSessionInfo(deps, { sessionId }); + if (local.ok === false) { + return unwrap(local); + } + const environment = await tryFetchHostEnvironment(deps.bridge, chatSessionId); + if (environment) { + const hosts = Array.isArray(environment.hosts) + ? (environment.hosts as Array>) + : []; + const match = hosts.find((host) => String(host.sessionId) === sessionId); + if (match) { + return { ...local.data, ...match }; + } + } + return local.data; + } + case 'harness.web.search': { + const { query, maxResults } = args as { query: string; maxResults?: number }; + return unwrap(await executeWebSearch(deps, { query, maxResults })); + } + case 'harness.url.fetch': { + const { url, maxLength } = args as { url: string; maxLength?: number }; + const fingerprint = toolResultDedup?.fingerprintFor(spec.toolName, url); + const raw = unwrap(await executeUrlFetch(deps, { url, maxLength })); + if (fingerprint) { + return applyToolDedup(spec.toolName, fingerprint, raw, toolResultDedup); + } + return raw; + } + default: + return { error: `No local executor registered for "${spec.capabilityId}".` }; + } +} + +function resolveSessionQueueKey( + spec: CattyToolSpec, + args: Record, + chatSessionId?: string, +): string | null { + // Read-only harness tools only inspect renderer context (plus optional host + // metadata). They must not queue behind terminal.execute on the same sessionId. + if (spec.capabilityId.startsWith('harness.') && !spec.policy.write) { + return null; + } + + const sessionId = typeof args.sessionId === 'string' ? args.sessionId : undefined; + if (sessionId) { + return `${chatSessionId ?? 'global'}:${sessionId}`; + } + return `${chatSessionId ?? 'global'}:${spec.toolName}`; +} + +export function resolveSessionQueueKeyForTests( + spec: Pick, + args: Record, + chatSessionId?: string, +): string | null { + return resolveSessionQueueKey(spec as CattyToolSpec, args, chatSessionId); +} + +function createCatalogTool( + spec: CattyToolSpec, + deps: ToolDeps, + permissionMode: AIPermissionMode, + toolOutputStore?: ToolOutputStore, + toolResultDedup?: ToolResultDedup, +) { + const inputSchema = buildZodObject(spec.inputShape); + + return tool({ + description: spec.description, + inputSchema, + execute: async (args, { toolCallId, abortSignal }) => { + const queueKey = resolveSessionQueueKey( + spec, + args as Record, + deps.chatSessionId, + ); + const slot = queueKey ? reserveSessionSlot(queueKey) : null; + + try { + if ( + permissionMode === 'confirm' + && spec.policy.write + && !spec.policy.bypassesApproval + ) { + const approved = await requestApproval( + toolCallId, + spec.toolName, + args as Record, + deps.chatSessionId, + undefined, + spec.capabilityId, + ); + if (!approved) { + return { error: 'User denied tool execution.' }; + } + } + + if (abortSignal?.aborted) { + return { error: 'Tool call cancelled before it could start.' }; + } + + await slot?.ready; + + if (spec.capabilityId === 'terminal.execute') { + const { sessionId: sid, command } = args as { sessionId: string; command: string }; + const cancelOnAbort = () => { + if (deps.chatSessionId) { + void deps.bridge.aiCattyCancelExec?.(deps.chatSessionId); + } + }; + abortSignal?.addEventListener('abort', cancelOnAbort, { once: true }); + try { + const result = await executeTerminalExecute(deps, { sessionId: sid, command }); + if (result.ok === false) return unwrap(result); + return fitTerminalExecuteResultForModel({ + ...result.data, + command, + sessionId: sid, + }, { + chatSessionId: deps.chatSessionId, + toolOutputStore, + }); + } finally { + abortSignal?.removeEventListener('abort', cancelOnAbort); + } + } + + if (spec.localExecution || spec.capabilityId.startsWith('harness.')) { + return executeLocalCattyCapability({ + deps, + spec, + args: args as Record, + toolOutputStore, + toolResultDedup, + chatSessionId: deps.chatSessionId, + }); + } + + if (!spec.rpcMethod) { + return { error: `Capability "${spec.capabilityId}" has no RPC binding.` }; + } + + const raw = await invokeCapabilityRpc( + deps.bridge, + spec.rpcMethod, + args as Record, + deps.chatSessionId, + ); + + if (spec.toolName === 'get_environment' || spec.capabilityId === 'session.environment') { + const ctx = typeof deps.context === 'function' ? deps.context() : deps.context; + const fingerprint = toolResultDedup?.fingerprintFor( + spec.toolName, + hashScopeKey([deps.chatSessionId, ctx.workspaceId, String(ctx.sessions?.length ?? 0)]), + ); + if (fingerprint) { + return applyToolDedup(spec.toolName, fingerprint, raw, toolResultDedup); + } + } + + if (spec.capabilityId.includes('sftp') && spec.capabilityId.includes('read')) { + const { sessionId: sid, path } = args as { sessionId?: string; path?: string }; + const fingerprint = toolResultDedup?.fingerprintFor( + spec.toolName, + hashScopeKey([sid, path]), + ); + if (fingerprint) { + return applyToolDedup(spec.toolName, fingerprint, raw, toolResultDedup); + } + + if ( + raw + && typeof raw === 'object' + && 'content' in raw + && toolOutputStore + && deps.chatSessionId + ) { + const content = String((raw as { content?: string }).content ?? ''); + const MAX_LIVE_SFTP_READ_CHARS = 24_000; + if (content.length > MAX_LIVE_SFTP_READ_CHARS) { + const handle = toolOutputStore.store({ + chatSessionId: deps.chatSessionId, + capabilityId: spec.capabilityId, + content, + sessionId: sid, + }); + return { + ok: true, + path: (raw as { path?: string }).path ?? path, + preview: handle.preview, + totalChars: handle.totalChars, + handleId: handle.id, + note: 'Full file content stored. Use tool_output_read with this handleId to read more.', + }; + } + } + } + + return raw; + } finally { + slot?.release(); + } + }, + }); +} + +export function createCattyToolsFromCatalog( + bridge: NetcattyBridge, + context: ToolDeps['context'], + commandBlocklist?: string[], + permissionMode: AIPermissionMode = 'confirm', + webSearchConfig?: WebSearchConfig, + chatSessionId?: string, + toolOutputStore?: ToolOutputStore, + toolResultDedup?: ToolResultDedup, +) { + const deps: ToolDeps = { + bridge, + context, + commandBlocklist, + permissionMode, + webSearchConfig, + chatSessionId, + }; + + const catalogTools: Record> = {}; + for (const rawSpec of cattyToolSpecs as CattyToolSpec[]) { + if (rawSpec.capabilityId === 'harness.web.search' && !isWebSearchReady(webSearchConfig)) { + continue; + } + catalogTools[rawSpec.toolName] = createCatalogTool( + rawSpec, + deps, + permissionMode, + toolOutputStore, + toolResultDedup, + ); + } + + return catalogTools; +} diff --git a/infrastructure/ai/harness/cattyRuntime.ts b/infrastructure/ai/harness/cattyRuntime.ts new file mode 100644 index 000000000..2e3f0059d --- /dev/null +++ b/infrastructure/ai/harness/cattyRuntime.ts @@ -0,0 +1,124 @@ +import type { ModelMessage } from 'ai'; +import { generateText, pruneMessages } from 'ai'; +import { + CONTEXT_COMPACTION_SYSTEM_PROMPT, + DEFAULT_PROTECT_RECENT_MESSAGES, + formatMessagesForCompaction, + resolveContextWindow, +} from '../contextCompaction'; +import type { ProviderConfig } from '../types'; +import { + extractLatestUserGoal, + prepareTurnContext, +} from './contextManager'; +import type { AgentEventListener, CompactionTrace } from './types'; + +export interface CompactCattyMessagesInput { + messages: ModelMessage[]; + sessionId: string; + chatSessionId?: string; + provider?: Pick | null; + modelId?: string | null; + reservedTokens?: () => number; + model: Parameters[0]['model']; + abortSignal: AbortSignal; + trigger?: 'pre-turn' | '413-retry' | 'force'; + force?: boolean; + compressForRequestTooLargeRetry?: boolean; + onStatusText?: (text: string) => void; + onCompaction?: (trace: CompactionTrace) => void; + reinjection?: { + permissionMode?: import('../types').AIPermissionMode; + sessionScopeSummary?: string; + }; +} + +export interface CompactCattyMessagesResult { + messages: ModelMessage[]; + trace?: CompactionTrace; +} + +function createEventListener( + input: CompactCattyMessagesInput, +): AgentEventListener | undefined { + if (!input.onCompaction) return undefined; + return (event) => { + if (event.type === 'compaction') { + input.onCompaction?.(event.trace); + } + }; +} + +export async function compactCattyMessages( + input: CompactCattyMessagesInput, +): Promise { + const contextWindow = resolveContextWindow({ + provider: input.provider, + modelId: input.modelId, + }); + + const summarize = async (messagesToSummarize: ModelMessage[]) => { + input.onStatusText?.('Compacting earlier context...'); + const result = await generateText({ + model: input.model, + system: CONTEXT_COMPACTION_SYSTEM_PROMPT, + messages: [{ + role: 'user', + content: `Summarize this earlier conversation context for the next model turn:\n\n${formatMessagesForCompaction(messagesToSummarize)}`, + }], + abortSignal: input.abortSignal, + maxOutputTokens: 1600, + temperature: 0, + }); + return result.text; + }; + + const trigger = input.trigger ?? (input.force ? 'force' : 'pre-turn'); + + try { + const prepared = await prepareTurnContext({ + messages: input.messages, + backend: 'catty', + contextWindow, + reservedTokens: input.reservedTokens?.() ?? 0, + trigger, + force: input.force, + compressForRequestTooLargeRetry: input.compressForRequestTooLargeRetry, + protectRecentMessages: DEFAULT_PROTECT_RECENT_MESSAGES, + summarize, + sessionId: input.sessionId, + chatSessionId: input.chatSessionId, + onEvent: createEventListener(input), + reinjection: { + ...input.reinjection, + userGoal: extractLatestUserGoal(input.messages), + }, + providerId: input.provider?.providerId, + }); + return { messages: prepared.messages, trace: prepared.trace }; + } catch (err) { + if (input.abortSignal.aborted) throw err; + console.warn('[Harness] Context compaction failed; falling back to recent messages only:', err); + const fallback = await prepareTurnContext({ + messages: input.messages, + backend: 'catty', + contextWindow, + trigger: 'force', + force: true, + compressForRequestTooLargeRetry: input.compressForRequestTooLargeRetry, + protectRecentMessages: DEFAULT_PROTECT_RECENT_MESSAGES, + sessionId: input.sessionId, + chatSessionId: input.chatSessionId, + onEvent: createEventListener(input), + }); + return { messages: fallback.messages, trace: fallback.trace }; + } +} + +export function prepareCattyMessagesForStream(messages: ModelMessage[]): ModelMessage[] { + return pruneMessages({ + messages, + reasoning: 'all', + emptyMessages: 'remove', + }); +} diff --git a/infrastructure/ai/harness/contextManager.test.ts b/infrastructure/ai/harness/contextManager.test.ts new file mode 100644 index 000000000..69b4ea42f --- /dev/null +++ b/infrastructure/ai/harness/contextManager.test.ts @@ -0,0 +1,102 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import type { ModelMessage } from 'ai'; +import { prepareTurnContext } from './contextManager.ts'; +import { TraceStore } from './traceStore.ts'; + +test('prepareTurnContext applies typed compression before LLM summarize threshold', async () => { + const longOutput = 'line\n'.repeat(20_000); + const messages: ModelMessage[] = [ + { + role: 'user', + content: 'Check nginx error logs on prod-web-01 and summarize failures.', + }, + { + role: 'assistant', + content: [{ + type: 'tool-call', + toolCallId: 'call-1', + toolName: 'terminal_execute', + input: { sessionId: 'sess-1', command: 'tail -n 500 /var/log/nginx/error.log' }, + }], + }, + { + role: 'tool', + content: [{ + type: 'tool-result', + toolCallId: 'call-1', + toolName: 'terminal_execute', + output: { type: 'text', value: longOutput }, + }], + }, + { + role: 'assistant', + content: 'Found repeated upstream timeout errors.', + }, + { + role: 'user', + content: 'Fix only the upstream timeout issue, do not restart nginx yet.', + }, + ]; + + const traces: string[] = []; + const prepared = await prepareTurnContext({ + messages, + backend: 'catty', + contextWindow: 128_000, + trigger: 'pre-turn', + sessionId: 'chat-1', + onEvent: (event) => { + if (event.type === 'compaction') traces.push(event.trace.trigger); + }, + reinjection: { + permissionMode: 'confirm', + userGoal: 'Fix upstream timeout without restarting nginx.', + }, + }); + + assert.ok(prepared.messages.length >= messages.length); + const serialized = JSON.stringify(prepared.messages); + assert.match(serialized, /Fix only the upstream timeout issue/); + assert.match(serialized, /Permission mode: confirm/); + assert.ok(serialized.length < JSON.stringify(messages).length); +}); + +test('prepareTurnContext force trigger retains recent user goal in replay', async () => { + const messages: ModelMessage[] = Array.from({ length: 40 }, (_, index) => ({ + role: index % 2 === 0 ? 'user' : 'assistant', + content: index === 38 + ? 'SSH into db-01 and inspect /var/log/postgresql/postgresql.log for crash signatures.' + : `filler message ${index}`, + })) as ModelMessage[]; + + const prepared = await prepareTurnContext({ + messages, + backend: 'catty', + contextWindow: 128_000, + trigger: 'force', + force: true, + sessionId: 'chat-2', + }); + + const serialized = JSON.stringify(prepared.messages); + assert.match(serialized, /SSH into db-01/); + assert.match(serialized, /postgresql\.log/); +}); + +test('TraceStore records compaction events for export', async () => { + const store = new TraceStore(); + await prepareTurnContext({ + messages: [{ role: 'user', content: 'x'.repeat(500_000) }], + backend: 'catty', + contextWindow: 1000, + trigger: 'force', + force: true, + sessionId: 'chat-3', + onEvent: (event) => store.append(event), + }); + + const exported = store.exportTrace('chat-3'); + assert.ok(exported.compactions.length >= 1); + assert.equal(exported.compactions[0]?.trigger, 'force'); +}); diff --git a/infrastructure/ai/harness/contextManager.ts b/infrastructure/ai/harness/contextManager.ts new file mode 100644 index 000000000..138477711 --- /dev/null +++ b/infrastructure/ai/harness/contextManager.ts @@ -0,0 +1,251 @@ +import type { ModelMessage } from 'ai'; +import type { ChatMessage, AIPermissionMode } from '../types'; +import { + DEFAULT_CONTEXT_WINDOW_TOKENS, + DEFAULT_PROTECT_RECENT_MESSAGES, + keepRecentContextMessages, + prepareContextCompaction, +} from '../contextCompaction'; +import { compressMessagesForRequestTooLargeRetry } from '../requestPayloadCompression'; +import { estimateModelMessagesTokensWithKind } from './tokenEstimator'; +import type { PrepareStepContextInput } from './turnDrivers/types'; +import type { + AgentEventListener, + CompactionTrace, + ContextPrepareResult, + ContextPrepareTrigger, + ExternalBridgeHistoryMessage, +} from './types'; +import { buildExternalBridgeContextMessages } from './externalBridgeContext'; + +export interface PrepareTurnContextInput { + messages: ModelMessage[]; + backend: 'catty' | 'external-bridge'; + contextWindow?: number; + reservedTokens?: number; + trigger: ContextPrepareTrigger; + protectRecentMessages?: number; + force?: boolean; + compressForRequestTooLargeRetry?: boolean; + summarize?: (messagesToSummarize: ModelMessage[]) => Promise; + onEvent?: AgentEventListener; + sessionId?: string; + chatSessionId?: string; + providerId?: string | null; + reinjection?: PostCompactReinjection; +} + +export interface PostCompactReinjection { + permissionMode?: AIPermissionMode; + sessionScopeSummary?: string; + userGoal?: string; + pendingToolHandleIds?: string[]; +} + +function emitCompactionEvent( + onEvent: AgentEventListener | undefined, + input: PrepareTurnContextInput, + trace: CompactionTrace, +): void { + if (!onEvent || !input.sessionId) return; + onEvent({ + id: `compaction-${Date.now()}`, + type: 'compaction', + sessionId: input.sessionId, + chatSessionId: input.chatSessionId, + backend: input.backend === 'catty' ? 'catty' : 'external-sdk', + timestamp: Date.now(), + trace, + }); +} + +function applyTypedMessageCompression(messages: ModelMessage[]): { + messages: ModelMessage[]; + didAdjust: boolean; +} { + const compressed = compressMessagesForRequestTooLargeRetry(messages); + return { messages: compressed.messages, didAdjust: compressed.didAdjust }; +} + +function buildReinjectionMessages(reinjection?: PostCompactReinjection): ModelMessage[] { + if (!reinjection) return []; + const lines: string[] = ['[Netcatty session context — preserved after compaction]']; + if (reinjection.permissionMode) { + lines.push(`Permission mode: ${reinjection.permissionMode}`); + } + if (reinjection.sessionScopeSummary) { + lines.push(reinjection.sessionScopeSummary); + } + if (reinjection.userGoal) { + lines.push(`Current user goal: ${reinjection.userGoal}`); + } + if (reinjection.pendingToolHandleIds?.length) { + lines.push(`Unresolved tool output handles: ${reinjection.pendingToolHandleIds.join(', ')}`); + } + if (lines.length <= 1) return []; + return [{ + role: 'user', + content: lines.join('\n'), + }]; +} + +export async function prepareTurnContext( + input: PrepareTurnContextInput, +): Promise { + const contextWindow = input.contextWindow ?? DEFAULT_CONTEXT_WINDOW_TOKENS; + const protectRecent = input.protectRecentMessages ?? DEFAULT_PROTECT_RECENT_MESSAGES; + const tokensBeforeResult = estimateModelMessagesTokensWithKind({ + messages: input.messages, + providerId: input.providerId, + }); + const tokensBefore = tokensBeforeResult.tokens; + const estimatorKind = tokensBeforeResult.estimatorKind; + + let working = input.messages; + let didAdjust = false; + let didTypedCompression = false; + let didLlmSummarize = false; + let did413Fallback = false; + let summaryLength: number | undefined; + let compressedMessageCount = 0; + let retainedTailCount = working.length; + + if (input.compressForRequestTooLargeRetry || input.trigger === '413-retry') { + const typed = applyTypedMessageCompression(working); + working = typed.messages; + didTypedCompression = typed.didAdjust; + did413Fallback = typed.didAdjust; + didAdjust = didAdjust || typed.didAdjust; + } else { + const typed = applyTypedMessageCompression(working); + if (typed.didAdjust) { + working = typed.messages; + didTypedCompression = true; + didAdjust = true; + } + } + + if (input.summarize) { + const compacted = await prepareContextCompaction({ + messages: working, + contextWindow, + reservedTokens: input.reservedTokens ?? 0, + thresholdRatio: input.force || input.trigger === 'force' ? 0 : undefined, + protectRecentMessages: protectRecent, + summarize: input.summarize, + }); + + if (compacted.didCompact) { + working = compacted.messages; + didLlmSummarize = true; + didAdjust = true; + summaryLength = compacted.summary?.length; + compressedMessageCount = Math.max(0, input.messages.length - protectRecent); + retainedTailCount = protectRecent; + } else if (input.force || input.trigger === '413-retry' || input.trigger === 'force') { + working = keepRecentContextMessages(working, protectRecent); + didAdjust = true; + retainedTailCount = working.length; + } + } else if (input.force || input.trigger === '413-retry' || input.trigger === 'force') { + working = keepRecentContextMessages(working, protectRecent); + didAdjust = true; + retainedTailCount = working.length; + } + + const reinjection = buildReinjectionMessages(input.reinjection); + if (reinjection.length > 0) { + working = [...reinjection, ...working]; + didAdjust = true; + } + + const tokensAfter = estimateModelMessagesTokensWithKind({ + messages: working, + providerId: input.providerId, + }).tokens; + + if (didAdjust) { + const trace: CompactionTrace = { + trigger: input.trigger, + estimatedTokensBefore: tokensBefore, + estimatedTokensAfter: tokensAfter, + messagesBefore: input.messages.length, + messagesAfter: working.length, + compressedMessageCount, + retainedTailCount, + summaryLength, + didTypedCompression, + didLlmSummarize, + did413Fallback, + estimatorKind, + }; + emitCompactionEvent(input.onEvent, input, trace); + return { messages: working, didAdjust: true, trace }; + } + + return { messages: working, didAdjust: false }; +} + +export function buildExternalBridgeContext( + messages: ChatMessage[], +): ExternalBridgeHistoryMessage[] { + return buildExternalBridgeContextMessages(messages); +} + +export function extractLatestUserGoal(messages: ModelMessage[] | ChatMessage[]): string | undefined { + for (let i = messages.length - 1; i >= 0; i -= 1) { + const message = messages[i]; + if (message.role !== 'user') continue; + const content = typeof message.content === 'string' + ? message.content.trim() + : ''; + if (content) return content.slice(0, 500); + } + return undefined; +} + +/** Step-level typed pruning — no LLM summarize (reserved for pre-turn / 413). */ +export async function prepareStepContext( + input: PrepareStepContextInput, +): Promise { + const typed = compressMessagesForRequestTooLargeRetry(input.messages); + let working = typed.messages; + let didAdjust = typed.didAdjust; + + const pendingHandles = input.toolOutputStore?.listPendingHandles(input.chatSessionId ?? input.sessionId) ?? []; + if (pendingHandles.length > 0 && input.stepNumber > 0) { + const notice: ModelMessage = { + role: 'user', + content: `[step ${input.stepNumber}] Tool output handles available: ${pendingHandles.map(h => h.id).join(', ')}`, + }; + working = [notice, ...working]; + didAdjust = true; + } + + const before = estimateModelMessagesTokensWithKind({ + messages: input.messages, + providerId: input.providerId, + }); + const after = estimateModelMessagesTokensWithKind({ + messages: working, + providerId: input.providerId, + }); + + return { + messages: working, + didAdjust, + trace: didAdjust ? { + trigger: 'pre-turn', + estimatedTokensBefore: before.tokens, + estimatedTokensAfter: after.tokens, + messagesBefore: input.messages.length, + messagesAfter: working.length, + compressedMessageCount: 0, + retainedTailCount: working.length, + didTypedCompression: typed.didAdjust, + didLlmSummarize: false, + did413Fallback: false, + estimatorKind: before.estimatorKind, + } : undefined, + }; +} diff --git a/infrastructure/ai/harness/contextReplay.test.ts b/infrastructure/ai/harness/contextReplay.test.ts new file mode 100644 index 000000000..cbfa974e4 --- /dev/null +++ b/infrastructure/ai/harness/contextReplay.test.ts @@ -0,0 +1,37 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import type { ModelMessage } from 'ai'; +import { prepareTurnContext, extractLatestUserGoal } from './contextManager'; + +const fixtureMessages: ModelMessage[] = [ + { role: 'user', content: 'Deploy nginx on prod-web-01 and verify port 443.' }, + { role: 'assistant', content: 'I will check the server first.' }, + { role: 'user', content: 'Command failed: systemctl restart nginx returned exit code 1.' }, + { role: 'assistant', content: 'The error log shows missing ssl_certificate path.' }, +]; + +test('context replay compaction retains user goal and recent tail', async () => { + const goal = extractLatestUserGoal(fixtureMessages); + assert.ok(goal?.includes('Command failed')); + + const prepared = await prepareTurnContext({ + messages: [...fixtureMessages], + backend: 'catty', + contextWindow: 500, + reservedTokens: 100, + trigger: 'force', + force: true, + protectRecentMessages: 2, + providerId: 'anthropic', + reinjection: { + userGoal: goal, + permissionMode: 'confirm', + }, + }); + + assert.equal(prepared.didAdjust, true); + assert.ok(prepared.messages.length <= fixtureMessages.length + 1); + const joined = JSON.stringify(prepared.messages); + assert.match(joined, /Deploy nginx|Command failed|ssl_certificate/); + assert.ok(prepared.trace?.estimatorKind); +}); diff --git a/infrastructure/ai/harness/externalBridgeContext.ts b/infrastructure/ai/harness/externalBridgeContext.ts new file mode 100644 index 000000000..51555ef70 --- /dev/null +++ b/infrastructure/ai/harness/externalBridgeContext.ts @@ -0,0 +1,445 @@ +import type { ChatMessage } from '../types'; +import type { ExternalBridgeHistoryMessage } from './types'; +import { buildHistoricalToolResultReplayText, buildHistoricalUserReplayContent } from '../../../components/ai/cattyHistoryReplay'; + +type ExternalAgentHistoryMessage = ExternalBridgeHistoryMessage; +type RawHistoryMessage = ExternalAgentHistoryMessage & { sourceId: string }; +type DurableUserLine = { + line: string; + messageIndex: number; + priority: number; +}; + +const MAX_RECENT_RAW_MESSAGES = 6; +const MAX_MESSAGES_TO_SCAN = 20; +// Bound the scan by user turns, not raw message count: a tool-heavy external agent +// chat can produce 5+ messages per logical turn (user + assistant + +// several tool_results + follow-up assistant), so a plain +// message-count cap ages out early constraints much sooner than intended. +const MAX_DURABLE_SCAN_TURNS = 100; +const MAX_COMPACT_CONTEXT_CHARS = 3000; +const MAX_RAW_MESSAGE_CHARS = 2000; +const MAX_TOOL_SUMMARY_CHARS = 500; +const MAX_DURABLE_USER_CONTEXT_CHARS = 1400; +const MAX_DURABLE_ASSISTANT_CONTEXT_CHARS = 900; +const MAX_RECENT_SUMMARY_CONTEXT_CHARS = 1200; +const MAX_DURABLE_USER_MESSAGE_CHARS = 280; +const MAX_DURABLE_ASSISTANT_MESSAGE_CHARS = 360; +const MAX_TOOL_CALL_LABEL_CHARS = 200; + +type ToolCallInfo = { name: string; arguments: unknown }; + +const IMPORTANT_PATTERNS = [ + /不要|别|不能|不允许|必须|希望|只|最小|先|暂时|fallback|pwsh|powershell|cmd\.exe|windows|mcp|skills|cli|commit|\bpr\b|打包|内存|历史|压缩|慢/i, + /error|failed|failure|exit code|exception|cannot|unable|timeout|crash|fallback|commit|pull request|PR #\d+/i, +]; +const DURABLE_CONSTRAINT_PATTERNS = [ + /\bdo not\b|\bdon't\b|\bkeep\b|\bpreserve\b|\bavoid\b|\bonly\b|\bunchanged\b|\blocal only\b|\bwithout\b|\bleave\b/i, + /不要|别|保留|保持|维持|不改|别改|不要改|仅限本地/i, +]; +const TRIVIAL_USER_MESSAGE_PATTERNS = [ + /^(ok|okay|yes|no|thanks|thank you|continue|继续|好的|收到|行|嗯|好|继续处理|继续吧|开始吧)[.!? ]*$/i, +]; +const TRIVIAL_ASSISTANT_MESSAGE_PATTERNS = [ + /^(ok|okay|understood|got it|working|proceeding|ready|ack(?: \d+)?|收到|明白|继续处理|准备实现|开始处理|处理中)[.!? ]*$/i, +]; + +function truncateText(value: string, maxChars: number): string { + if (value.length <= maxChars) return value; + return `${value.slice(0, Math.max(0, maxChars - 24)).trimEnd()}\n[truncated]`; +} + +function normalizeWhitespace(value: string): string { + return value.replace(/\s+/g, " ").trim(); +} + +function isImportantText(value: string): boolean { + return IMPORTANT_PATTERNS.some((pattern) => pattern.test(value)); +} + +function isDurableConstraintText(value: string): boolean { + return DURABLE_CONSTRAINT_PATTERNS.some((pattern) => pattern.test(value)); +} + +function getUserHistoryContent(message: ChatMessage): string { + if (message.role !== "user") return message.content || ""; + return buildHistoricalUserReplayContent( + message.content || "", + message.attachments ?? [], + ); +} + +function isTrivialUserMessage(value: string): boolean { + const normalized = normalizeWhitespace(value); + if (isImportantText(normalized) || isDurableConstraintText(normalized)) return false; + // Don't blanket-drop short messages — short user turns are often + // load-bearing constraints ("Use ssh2", "中文输出", "no logs", "more + // verbose") that the IMPORTANT/DURABLE regexes can't realistically + // enumerate. The trivial-phrase regex already catches actual filler + // ("ok", "yes", "thanks", "继续"). + return TRIVIAL_USER_MESSAGE_PATTERNS.some((pattern) => pattern.test(normalized)); +} + +function getDurableUserPriority(value: string): number { + const normalized = normalizeWhitespace(value); + if (isImportantText(normalized) || isDurableConstraintText(normalized)) return 2; + return 1; +} + +function isSubstantiveAssistantMessage(value: string): boolean { + const normalized = normalizeWhitespace(value); + if (!normalized) return false; + // Mirror the user-side loosening: don't blanket-drop short assistant + // messages just because they're under 40 chars or don't match the small + // English keyword list. Short but load-bearing decisions ("Use ssh2", + // "rebase instead", "中文输出") aren't realistically enumerable and + // they're the exact things a later "do what you suggested" references. + // TRIVIAL_ASSISTANT_MESSAGE_PATTERNS still catches the actual filler + // ("ok", "ack", "got it", "明白"). + return !TRIVIAL_ASSISTANT_MESSAGE_PATTERNS.some((pattern) => pattern.test(normalized)); +} + +function getDurableAssistantPriority(value: string): number { + const normalized = normalizeWhitespace(value); + if (isImportantText(normalized)) return 2; + return 1; +} + +function appendUniqueLine( + target: string[], + seen: Set, + line: string, + maxSectionChars: number, + sectionCharsRef: { value: number }, +): void { + const normalized = normalizeWhitespace(line); + if (!normalized || seen.has(normalized)) return; + const nextChars = sectionCharsRef.value + normalized.length; + if (nextChars > maxSectionChars) return; + seen.add(normalized); + target.push(normalized); + sectionCharsRef.value = nextChars; +} + +function summarizeToolMessage( + message: ChatMessage, + toolCallIndex: Map, +): string[] { + if (!message.toolResults?.length) return []; + return message.toolResults.map((result) => { + const prefix = result.isError ? "Tool error" : "Tool result"; + // Same provenance problem as the raw-window path: once a tool result + // lands in the compact section (older than the 6-item raw window), + // its paired assistant tool_call is almost always gone. Without the + // call label, multiple older results collapse into indistinguishable + // "Tool result (callN): ..." lines and follow-ups like "use the + // resolv.conf output" can't be resolved. Inline the name+args here + // the same way toRawHistoryMessage does. + const callInfo = lookupToolCallInfo(toolCallIndex, message.id, result.toolCallId); + const callLabel = callInfo + ? ` [from ${callInfo.name}(${truncateText(JSON.stringify(callInfo.arguments ?? {}), MAX_TOOL_CALL_LABEL_CHARS)})]` + : ""; + const replayContent = buildHistoricalToolResultReplayText(result, callInfo + ? { id: result.toolCallId, name: callInfo.name, arguments: callInfo.arguments as Record } + : undefined); + return `${prefix}${callLabel} (${result.toolCallId}): ${truncateText(normalizeWhitespace(replayContent), MAX_TOOL_SUMMARY_CHARS)}`; + }); +} + +function summarizeMessage( + message: ChatMessage, + toolCallIndex: Map, +): string[] { + if (message.role === "system") return []; + if (message.role === "tool") return summarizeToolMessage(message, toolCallIndex); + + const lines: string[] = []; + const content = getUserHistoryContent(message); + if (content && isImportantText(content)) { + const label = message.role === "user" ? "User" : "Assistant"; + lines.push(`${label}: ${truncateText(normalizeWhitespace(content), MAX_TOOL_SUMMARY_CHARS)}`); + } + + if (message.role === "assistant" && message.toolCalls?.length) { + for (const toolCall of message.toolCalls) { + const args = JSON.stringify(toolCall.arguments ?? {}); + const summary = `Tool call: ${toolCall.name}(${truncateText(args, 220)})`; + if (isImportantText(summary)) lines.push(summary); + } + } + + return lines; +} + +function summarizeDurableUserMessage(message: ChatMessage): string | null { + if (message.role !== "user") return null; + const content = getUserHistoryContent(message); + if (!content) return null; + if (isTrivialUserMessage(content)) return null; + return `User request: ${truncateText(normalizeWhitespace(content), MAX_DURABLE_USER_MESSAGE_CHARS)}`; +} + +function summarizeDurableAssistantMessage(message: ChatMessage): string | null { + if (message.role !== "assistant" || !message.content) return null; + if (!isSubstantiveAssistantMessage(message.content)) return null; + return `Assistant context: ${truncateText(normalizeWhitespace(message.content), MAX_DURABLE_ASSISTANT_MESSAGE_CHARS)}`; +} + +/** + * Build a per-tool-result provenance index. Keys are + * `${toolResultMessageId}:${toolCallId}` rather than the bare toolCall.id + * so that provider-reused ids (e.g. "call1" across unrelated turns) don't + * cause later calls to overwrite older ones in the lookup — each + * tool_result resolves to the most recent assistant tool_call that + * preceded it with matching id, which preserves historical correctness + * when rebuilding older compact summaries. + */ +function buildToolCallIndex(messages: ChatMessage[]): Map { + const provenance = new Map(); + // Rolling map of the latest tool_call seen (by id) up to the current + // point in the message stream. + const latestByCallId = new Map(); + for (const message of messages) { + if (message.role === "assistant" && message.toolCalls?.length) { + for (const toolCall of message.toolCalls) { + if (!toolCall.id) continue; + latestByCallId.set(toolCall.id, { name: toolCall.name, arguments: toolCall.arguments }); + } + continue; + } + if (message.role === "tool" && message.toolResults?.length) { + for (const result of message.toolResults) { + const info = latestByCallId.get(result.toolCallId); + if (info) { + provenance.set(`${message.id}:${result.toolCallId}`, info); + } + } + } + } + return provenance; +} + +function lookupToolCallInfo( + index: Map, + toolMessageId: string, + toolCallId: string, +): ToolCallInfo | undefined { + return index.get(`${toolMessageId}:${toolCallId}`); +} + +function toRawHistoryMessage( + message: ChatMessage, + toolCallIndex: Map, +): RawHistoryMessage[] { + if (message.role === "user") { + const content = getUserHistoryContent(message); + return content + ? [{ sourceId: message.id, role: "user", content: truncateText(content, MAX_RAW_MESSAGE_CHARS) }] + : []; + } + + if (message.role === "assistant") { + const parts: string[] = []; + if (message.content) parts.push(message.content); + if (message.toolCalls?.length) { + parts.push(...message.toolCalls.map((tc) => `Tool call: ${tc.name}(${JSON.stringify(tc.arguments ?? {})})`)); + } + return parts.length + ? [{ sourceId: message.id, role: "assistant", content: truncateText(parts.join("\n\n"), MAX_RAW_MESSAGE_CHARS) }] + : []; + } + + if (message.role === "tool" && message.toolResults?.length) { + // Keep recent tool results self-describing while replacing terminal + // output with placeholders, so stale-session recovery doesn't replay + // bulky command output on every follow-up. External agent replay only + // supports user/assistant roles, so we flatten to "assistant" — the + // tool results were produced during the assistant's turn. + // + // Inline the originating tool_call's name+args. Tool calls and their + // results live in separate messages; if the last six raw items start + // in the middle of a tool interaction, the preceding assistant tool + // call can be outside the window. Without the call label the result + // is opaque bytes and "use that output" becomes ambiguous. + const parts = message.toolResults.map((result) => { + const prefix = result.isError ? "Tool error" : "Tool result"; + const callInfo = lookupToolCallInfo(toolCallIndex, message.id, result.toolCallId); + const callLabel = callInfo + ? ` [from ${callInfo.name}(${truncateText(JSON.stringify(callInfo.arguments ?? {}), MAX_TOOL_CALL_LABEL_CHARS)})]` + : ""; + const replayContent = buildHistoricalToolResultReplayText(result, callInfo + ? { id: result.toolCallId, name: callInfo.name, arguments: callInfo.arguments as Record } + : undefined); + return `${prefix}${callLabel} (${result.toolCallId}): ${replayContent}`; + }); + return [{ + sourceId: message.id, + role: "assistant", + content: truncateText(parts.join("\n\n"), MAX_RAW_MESSAGE_CHARS), + }]; + } + + return []; +} + +function buildCompactContext( + messages: ChatMessage[], + durableScanStart: number, + recentRawSourceIds: Set, + toolCallIndex: Map, +): ExternalAgentHistoryMessage[] { + const scanned = messages.slice(-MAX_MESSAGES_TO_SCAN); + const summaryLines: string[] = []; + const durableUserCandidates: DurableUserLine[] = []; + const selectedDurableUserLines: DurableUserLine[] = []; + const durableAssistantCandidates: DurableUserLine[] = []; + const selectedDurableAssistantLines: DurableUserLine[] = []; + const seen = new Set(); + const durableChars = { value: 0 }; + const durableAssistantChars = { value: 0 }; + const summaryChars = { value: 0 }; + + for (let messageIndex = durableScanStart; messageIndex < messages.length; messageIndex += 1) { + const message = messages[messageIndex]; + if (recentRawSourceIds.has(message.id)) continue; + const durableUserLine = summarizeDurableUserMessage(message); + if (durableUserLine) { + durableUserCandidates.push({ + line: durableUserLine, + messageIndex, + priority: getDurableUserPriority(getUserHistoryContent(message)), + }); + } + const durableAssistantLine = summarizeDurableAssistantMessage(message); + if (durableAssistantLine) { + durableAssistantCandidates.push({ + line: durableAssistantLine, + messageIndex, + priority: getDurableAssistantPriority(message.content || ""), + }); + } + } + + durableUserCandidates + .sort((left, right) => right.priority - left.priority || right.messageIndex - left.messageIndex) + .forEach((candidate) => { + const normalized = normalizeWhitespace(candidate.line); + if (!normalized || seen.has(normalized)) return; + const nextChars = durableChars.value + normalized.length; + if (nextChars > MAX_DURABLE_USER_CONTEXT_CHARS) return; + seen.add(normalized); + selectedDurableUserLines.push(candidate); + durableChars.value = nextChars; + }); + + durableAssistantCandidates + .sort((left, right) => right.priority - left.priority || right.messageIndex - left.messageIndex) + .forEach((candidate) => { + const normalized = normalizeWhitespace(candidate.line); + if (!normalized || seen.has(normalized)) return; + const nextChars = durableAssistantChars.value + normalized.length; + if (nextChars > MAX_DURABLE_ASSISTANT_CONTEXT_CHARS) return; + seen.add(normalized); + selectedDurableAssistantLines.push(candidate); + durableAssistantChars.value = nextChars; + }); + + const durableUserLines = selectedDurableUserLines + .sort((left, right) => left.messageIndex - right.messageIndex) + .map((candidate) => candidate.line); + const durableAssistantLines = selectedDurableAssistantLines + .sort((left, right) => left.messageIndex - right.messageIndex) + .map((candidate) => candidate.line); + + for (const line of [...durableUserLines, ...durableAssistantLines]) { + seen.add(normalizeWhitespace(line)); + } + + // Skip messages that are already appended verbatim in the raw window — + // otherwise the same last-6 turns get summarized here AND re-sent as + // raw, doubling the budget cost of important user turns / large tool + // output and crowding out older durable context the replay is meant + // to preserve. Matches the recentRawSourceIds skip in the durable pass. + for (const message of scanned) { + if (recentRawSourceIds.has(message.id)) continue; + for (const line of summarizeMessage(message, toolCallIndex)) { + appendUniqueLine(summaryLines, seen, line, MAX_RECENT_SUMMARY_CONTEXT_CHARS, summaryChars); + } + } + + if (!durableUserLines.length && !durableAssistantLines.length && !summaryLines.length) return []; + + const contentLines = [ + "[Compact prior Netcatty UI context]", + "The external SDK agent may already have its own persisted session context. Use this compact Netcatty UI context only as fallback/background, and prefer the current user request when there is any conflict.", + ]; + if (durableUserLines.length) { + contentLines.push("Earlier user requests that may still apply:"); + contentLines.push(...durableUserLines.map((line) => `- ${line}`)); + } + if (durableAssistantLines.length) { + contentLines.push("Earlier assistant context that may still matter:"); + contentLines.push(...durableAssistantLines.map((line) => `- ${line}`)); + } + if (summaryLines.length) { + contentLines.push("Recent noteworthy context:"); + contentLines.push(...summaryLines.map((line) => `- ${line}`)); + } + + return [{ + role: "user", + content: truncateText( + contentLines.join("\n"), + MAX_COMPACT_CONTEXT_CHARS, + ), + }]; +} + +/** + * Find the index of the first message to include in the scan window, + * bounded by MAX_DURABLE_SCAN_TURNS user turns (not raw message count). + * Walking backwards stops at the target turn count, so the cost is + * bounded even when the transcript is huge. + */ +function computeDurableScanStart(messages: ChatMessage[]): number { + let userTurns = 0; + for (let i = messages.length - 1; i >= 0; i -= 1) { + if (messages[i].role === "user") { + userTurns += 1; + if (userTurns >= MAX_DURABLE_SCAN_TURNS) return i; + } + } + return 0; +} + +export function buildExternalBridgeContextMessages(messages: ChatMessage[]): ExternalBridgeHistoryMessage[] { + // Compute the scan start once, then do all subsequent work over the + // already-sliced tail. This avoids O(N) walks over the whole transcript + // on every send — previously buildToolCallIndex + the flatMap-to-take- + // last-6 raw history both traversed every message in the chat. + const durableScanStart = computeDurableScanStart(messages); + const scannedTail = messages.slice(durableScanStart); + + // The tool-call provenance index only needs entries for tool_results + // that might appear in our output. Building from the scanned tail is + // correct for any tool_result whose paired assistant tool_call is + // also within the window, which covers >99% of realistic patterns + // (tool_calls and tool_results are always adjacent or near-adjacent). + // If an ancient tool_call's result stays within the window while the + // call itself is outside, that single result loses its [from X(Y)] + // label — an acceptable trade for eliminating the per-send O(N) walk. + const toolCallIndex = buildToolCallIndex(scannedTail); + + const rawHistory = scannedTail + .flatMap((message) => toRawHistoryMessage(message, toolCallIndex)) + .slice(-MAX_RECENT_RAW_MESSAGES); + const compactContext = buildCompactContext( + messages, + durableScanStart, + new Set(rawHistory.map((message) => message.sourceId)), + toolCallIndex, + ); + const recentRaw = rawHistory.map(({ role, content }) => ({ role, content })); + + return [...compactContext, ...recentRaw]; +} \ No newline at end of file diff --git a/infrastructure/ai/harness/generated/cattyToolSpecs.json b/infrastructure/ai/harness/generated/cattyToolSpecs.json new file mode 100644 index 000000000..18d13e643 --- /dev/null +++ b/infrastructure/ai/harness/generated/cattyToolSpecs.json @@ -0,0 +1,1079 @@ +[ + { + "capabilityId": "session.environment", + "toolName": "get_environment", + "rpcMethod": "netcatty/getContext", + "localExecution": false, + "description": "List scoped terminal sessions available to the agent.", + "inputShape": {}, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "attachment.list", + "toolName": "list_attachments", + "rpcMethod": "netcatty/listAttachments", + "localExecution": false, + "description": "List user-attached files in the current AI chat scope.", + "inputShape": {}, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "attachment.read", + "toolName": "read_attachment", + "rpcMethod": "netcatty/readAttachment", + "localExecution": false, + "description": "Read a user-attached file from the current AI chat scope.", + "inputShape": { + "filePath": { + "type": "string", + "optional": true, + "description": "Exact local attachment path." + }, + "filename": { + "type": "string", + "optional": true, + "description": "Attachment filename from list_attachments." + } + }, + "policy": { + "write": false, + "sensitiveRead": true, + "longRunning": false, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "terminal.execute", + "toolName": "terminal_execute", + "rpcMethod": "netcatty/exec", + "localExecution": false, + "description": "Execute a short command in a terminal session and wait for completion. Use only for commands expected to finish within about 60 seconds. For long-running commands use terminal_start and terminal_poll.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "The terminal session ID to execute on." + }, + "command": { + "type": "string", + "optional": false, + "description": "The shell command to execute in the target session." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + } + }, + { + "capabilityId": "terminal.start", + "toolName": "terminal_start", + "rpcMethod": "netcatty/jobStart", + "localExecution": false, + "description": "Start a long-running command in a terminal session. Prefer for builds, scans, log-following, or anything likely to exceed about 2 minutes.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "The terminal session ID to start a long-running command on." + }, + "command": { + "type": "string", + "optional": false, + "description": "The command to start in the target session." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + } + }, + { + "capabilityId": "terminal.poll", + "toolName": "terminal_poll", + "rpcMethod": "netcatty/jobPoll", + "localExecution": false, + "description": "Poll incremental output from a long-running terminal job. Wait at least about 30 seconds between polls unless output justifies checking sooner.", + "inputShape": { + "jobId": { + "type": "string", + "optional": false, + "description": "The background job ID returned by terminal_start." + }, + "offset": { + "type": "number", + "optional": true, + "description": "Character offset from a previous poll (default 0)." + } + }, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "terminal.stop", + "toolName": "terminal_stop", + "rpcMethod": "netcatty/jobStop", + "localExecution": false, + "description": "Stop a long-running terminal job.", + "inputShape": { + "jobId": { + "type": "string", + "optional": false, + "description": "The background job ID returned by terminal_start." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": true, + "bypassesObserverBlock": true, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "sftp.list", + "toolName": "sftp_list", + "rpcMethod": "netcatty/sftp/list", + "localExecution": false, + "description": "List a remote directory over SFTP.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + }, + "path": { + "type": "string", + "optional": false, + "description": "Remote directory path." + } + }, + "policy": { + "write": false, + "sensitiveRead": true, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "sftp.read", + "toolName": "sftp_read_file", + "rpcMethod": "netcatty/sftp/read", + "localExecution": false, + "description": "Read a remote file over SFTP.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + }, + "path": { + "type": "string", + "optional": false, + "description": "Remote file path to read." + } + }, + "policy": { + "write": false, + "sensitiveRead": true, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "sftp.write", + "toolName": "sftp_write_file", + "rpcMethod": "netcatty/sftp/write", + "localExecution": false, + "description": "Write a remote file over SFTP.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + }, + "path": { + "type": "string", + "optional": false, + "description": "Remote file path to write." + }, + "content": { + "type": "string", + "optional": false, + "description": "File content to write." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + } + }, + { + "capabilityId": "sftp.download", + "toolName": "sftp_download", + "rpcMethod": "netcatty/sftp/download", + "localExecution": false, + "description": "Download a remote file to a local path.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + }, + "remotePath": { + "type": "string", + "optional": false, + "description": "Remote file path to download." + }, + "localPath": { + "type": "string", + "optional": false, + "description": "Local destination path." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + } + }, + { + "capabilityId": "sftp.upload", + "toolName": "sftp_upload", + "rpcMethod": "netcatty/sftp/upload", + "localExecution": false, + "description": "Upload a local file to a remote path.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + }, + "localPath": { + "type": "string", + "optional": false, + "description": "Local file path to upload." + }, + "remotePath": { + "type": "string", + "optional": false, + "description": "Remote destination path." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + } + }, + { + "capabilityId": "sftp.stat", + "toolName": "sftp_stat", + "rpcMethod": "netcatty/sftp/stat", + "localExecution": false, + "description": "Get remote file metadata over SFTP.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + }, + "path": { + "type": "string", + "optional": false, + "description": "Remote path to stat." + } + }, + "policy": { + "write": false, + "sensitiveRead": true, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "sftp.home", + "toolName": "sftp_home", + "rpcMethod": "netcatty/sftp/home", + "localExecution": false, + "description": "Get the remote home directory for a session.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + } + }, + "policy": { + "write": false, + "sensitiveRead": true, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "sftp.mkdir", + "toolName": "sftp_mkdir", + "rpcMethod": "netcatty/sftp/mkdir", + "localExecution": false, + "description": "Create a remote directory over SFTP.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + }, + "path": { + "type": "string", + "optional": false, + "description": "Remote directory path to create." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + } + }, + { + "capabilityId": "sftp.delete", + "toolName": "sftp_delete", + "rpcMethod": "netcatty/sftp/delete", + "localExecution": false, + "description": "Delete a remote file or directory over SFTP.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + }, + "path": { + "type": "string", + "optional": false, + "description": "Remote file or directory path to delete." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + } + }, + { + "capabilityId": "sftp.rename", + "toolName": "sftp_rename", + "rpcMethod": "netcatty/sftp/rename", + "localExecution": false, + "description": "Rename a remote file or directory over SFTP.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + }, + "oldPath": { + "type": "string", + "optional": false, + "description": "Current remote path." + }, + "newPath": { + "type": "string", + "optional": false, + "description": "New remote path." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + } + }, + { + "capabilityId": "sftp.chmod", + "toolName": "sftp_chmod", + "rpcMethod": "netcatty/sftp/chmod", + "localExecution": false, + "description": "Change remote file permissions over SFTP.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + }, + "path": { + "type": "string", + "optional": false, + "description": "Remote file path." + }, + "mode": { + "type": "string", + "optional": false, + "description": "Octal permission mode (e.g. 755)." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + } + }, + { + "capabilityId": "vault.host.get", + "toolName": "host_get", + "rpcMethod": "vault/host/get", + "localExecution": false, + "description": "Get host metadata from the vault.", + "inputShape": { + "hostId": { + "type": "string", + "optional": false, + "description": "Vault host ID." + } + }, + "policy": { + "write": false, + "sensitiveRead": true, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "vault.host.list", + "toolName": "vault_hosts_list", + "rpcMethod": "vault/hosts/list", + "localExecution": false, + "description": "List saved hosts in the vault (metadata only — no passwords or keys).", + "inputShape": {}, + "policy": { + "write": false, + "sensitiveRead": true, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "vault.hosts.create", + "toolName": "vault_hosts_create", + "rpcMethod": "vault/hosts/create", + "localExecution": false, + "description": "Create vault hosts from structured host objects. Use when the user wants to add/create a host (Vault → Hosts). NOT for Vault → Notes sidebar documentation. Use when the user wants to add/create a host in Vault → Hosts (创建主机、SSH 连接凭据). NOT for Vault → Notes sidebar docs. Put SSH password in password field; long remarks/admin tables in host notes field. Never fall back to vault_notes_create if this fails.", + "inputShape": { + "hosts": { + "type": "string", + "optional": false, + "description": "JSON array of host objects you extracted from the user's text. Each object: hostname (required), label, port, username, password, group, tags (array or comma-separated string), notes (Host Details remarks — NOT Vault sidebar Notes), protocol (ssh|telnet|local)." + }, + "dryRun": { + "type": "string", + "optional": true, + "description": "Set to true to validate and preview without writing to the vault." + }, + "skipDuplicates": { + "type": "string", + "optional": true, + "description": "Set to false to create even when a matching host already exists (default true)." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + } + }, + { + "capabilityId": "vault.host.import", + "toolName": "vault_hosts_import", + "rpcMethod": "vault/hosts/import", + "localExecution": false, + "description": "Parse known host export file formats (PuTTY, MobaXterm, CSV, SecureCRT, ssh_config) into vault hosts. For arbitrary unstructured text, map to host objects and use vault_hosts_create instead. Only for text in known export formats (PuTTY reg, MobaXterm ini, CSV template, SecureCRT, ssh_config). For arbitrary unstructured host lists from the user, extract fields yourself and call vault_hosts_create.", + "inputShape": { + "format": { + "type": "string", + "optional": false, + "description": "Import format: csv, putty, mobaxterm, securecrt, ssh_config, or auto to detect from text." + }, + "text": { + "type": "string", + "optional": false, + "description": "Exported host data text to import." + }, + "dryRun": { + "type": "string", + "optional": true, + "description": "Set to true to parse and preview without writing to the vault." + }, + "skipDuplicates": { + "type": "string", + "optional": true, + "description": "Set to false to import even when a matching host already exists (default true)." + }, + "fileName": { + "type": "string", + "optional": true, + "description": "Optional source file name (helps SecureCRT .ini parsing)." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + } + }, + { + "capabilityId": "vault.host.notes.get", + "toolName": "host_notes_get", + "rpcMethod": "vault/host/notes/get", + "localExecution": false, + "description": "Read host metadata notes attached to a saved host (Host Details panel — not Vault sidebar Notes). Host metadata notes on a saved host — not Vault → Notes sidebar entries.", + "inputShape": { + "hostId": { + "type": "string", + "optional": false, + "description": "Vault host ID." + } + }, + "policy": { + "write": false, + "sensitiveRead": true, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "vault.host.notes.set", + "toolName": "host_notes_set", + "rpcMethod": "vault/host/notes/set", + "localExecution": false, + "description": "Update host metadata notes on a saved host (Host Details panel — not Vault sidebar Notes). Host metadata notes on a saved host — not Vault → Notes sidebar entries. Prefer vault_notes_create/update when the user wants vault notes they can open in the Notes sidebar.", + "inputShape": { + "hostId": { + "type": "string", + "optional": false, + "description": "Vault host ID." + }, + "notes": { + "type": "string", + "optional": false, + "description": "Host metadata notes (Host Details — not Vault sidebar Notes)." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + } + }, + { + "capabilityId": "vault.note.list", + "toolName": "vault_notes_list", + "rpcMethod": "vault/notes/list", + "localExecution": false, + "description": "List notes in Vault → Notes (markdown notes visible in the vault sidebar).", + "inputShape": {}, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "vault.note.get", + "toolName": "vault_notes_get", + "rpcMethod": "vault/notes/get", + "localExecution": false, + "description": "Get a Vault → Notes entry by id (full markdown content).", + "inputShape": { + "noteId": { + "type": "string", + "optional": false, + "description": "Vault note ID from vault_notes_list." + } + }, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "vault.note.create", + "toolName": "vault_notes_create", + "rpcMethod": "vault/notes/create", + "localExecution": false, + "description": "Create a note in Vault → Notes sidebar (markdown documentation). NOT for adding SSH hosts — use vault_hosts_create for that. Use ONLY when the user wants markdown documentation in Vault → Notes sidebar (保险箱笔记). Do NOT use when the user asked to create/add a host — use vault_hosts_create instead.", + "inputShape": { + "title": { + "type": "string", + "optional": false, + "description": "Note title shown in Vault → Notes." + }, + "content": { + "type": "string", + "optional": false, + "description": "Markdown note body." + }, + "group": { + "type": "string", + "optional": true, + "description": "Optional folder path (e.g. infra/prod)." + }, + "linkedHostIds": { + "type": "string", + "optional": true, + "description": "Optional JSON array of vault host IDs to link." + }, + "tags": { + "type": "string", + "optional": true, + "description": "Optional JSON array of tag strings." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + } + }, + { + "capabilityId": "vault.note.update", + "toolName": "vault_notes_update", + "rpcMethod": "vault/notes/update", + "localExecution": false, + "description": "Update an existing Vault → Notes entry by id. Update an existing Vault → Notes entry (visible in the vault notes sidebar).", + "inputShape": { + "noteId": { + "type": "string", + "optional": false, + "description": "Vault note ID to update." + }, + "title": { + "type": "string", + "optional": true, + "description": "New title." + }, + "content": { + "type": "string", + "optional": true, + "description": "New markdown body." + }, + "group": { + "type": "string", + "optional": true, + "description": "New folder path." + }, + "linkedHostIds": { + "type": "string", + "optional": true, + "description": "Optional JSON array of vault host IDs to link." + }, + "tags": { + "type": "string", + "optional": true, + "description": "Optional JSON array of tag strings." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + } + }, + { + "capabilityId": "vault.snippets.list", + "toolName": "snippets_list", + "rpcMethod": "vault/snippets/list", + "localExecution": false, + "description": "List code snippets stored in the vault.", + "inputShape": {}, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "vault.snippets.get", + "toolName": "snippets_get", + "rpcMethod": "vault/snippets/get", + "localExecution": false, + "description": "Get a single code snippet from the vault.", + "inputShape": { + "snippetId": { + "type": "string", + "optional": false, + "description": "Snippet ID." + } + }, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "vault.snippets.run", + "toolName": "snippets_run", + "rpcMethod": "vault/snippets/run", + "localExecution": false, + "description": "Resolve snippet variables and execute a snippet in a terminal session.", + "inputShape": { + "snippetId": { + "type": "string", + "optional": false, + "description": "Snippet ID to run." + }, + "sessionId": { + "type": "string", + "optional": false, + "description": "Terminal session ID to execute on." + }, + "variables": { + "type": "string", + "optional": true, + "description": "JSON object of snippet variable values." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + } + }, + { + "capabilityId": "portforward.rules.list", + "toolName": "portforward_rules_list", + "rpcMethod": "portforward/rules/list", + "localExecution": false, + "description": "List persisted port forwarding rules.", + "inputShape": {}, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "portforward.tunnels.list", + "toolName": "portforward_tunnels_list", + "rpcMethod": "portforward/tunnels/list", + "localExecution": false, + "description": "List active port forwarding tunnels.", + "inputShape": {}, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "portforward.start", + "toolName": "portforward_start", + "rpcMethod": "portforward/start", + "localExecution": false, + "description": "Start a port forwarding tunnel for a rule.", + "inputShape": { + "ruleId": { + "type": "string", + "optional": false, + "description": "Port forwarding rule ID." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + } + }, + { + "capabilityId": "portforward.stop", + "toolName": "portforward_stop", + "rpcMethod": "portforward/stop", + "localExecution": false, + "description": "Stop an active port forwarding tunnel.", + "inputShape": { + "ruleId": { + "type": "string", + "optional": false, + "description": "Port forwarding rule ID." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + } + }, + { + "capabilityId": "harness.tool_output.read", + "toolName": "tool_output_read", + "rpcMethod": null, + "localExecution": true, + "description": "Read stored tool output by handle id when a prior tool result was truncated.", + "inputShape": { + "handleId": { + "type": "string", + "optional": false, + "description": "Tool output handle id from a prior truncated result." + }, + "mode": { + "type": "string", + "optional": true, + "description": "Which portion to read: head, tail, or full." + }, + "maxChars": { + "type": "number", + "optional": true, + "description": "Maximum characters to return." + } + }, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "harness.workspace.get_info", + "toolName": "workspace_get_info", + "rpcMethod": null, + "localExecution": true, + "description": "Get information about the current workspace, including all terminal sessions and their connection status.", + "inputShape": {}, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "harness.workspace.get_session_info", + "toolName": "workspace_get_session_info", + "rpcMethod": null, + "localExecution": true, + "description": "Get detailed information about a specific terminal or SFTP session.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "The session ID to get information about." + } + }, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "harness.web.search", + "toolName": "web_search", + "rpcMethod": null, + "localExecution": true, + "description": "Search the web for current information when configured in AI settings.", + "inputShape": { + "query": { + "type": "string", + "optional": false, + "description": "The search query to look up on the web." + }, + "maxResults": { + "type": "number", + "optional": true, + "description": "Maximum number of search results to return." + } + }, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + }, + { + "capabilityId": "harness.url.fetch", + "toolName": "url_fetch", + "rpcMethod": null, + "localExecution": true, + "description": "Fetch and read the content of an HTTPS URL.", + "inputShape": { + "url": { + "type": "string", + "optional": false, + "description": "The HTTPS URL to fetch." + }, + "maxLength": { + "type": "number", + "optional": true, + "description": "Maximum characters to return (default 50000)." + } + }, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + } + } +] diff --git a/infrastructure/ai/harness/generated/globalAgentToolSpecs.json b/infrastructure/ai/harness/generated/globalAgentToolSpecs.json new file mode 100644 index 000000000..a296b38bf --- /dev/null +++ b/infrastructure/ai/harness/generated/globalAgentToolSpecs.json @@ -0,0 +1,985 @@ +[ + { + "capabilityId": "session.environment", + "toolName": "get_environment", + "rpcMethod": "netcatty/getContext", + "localExecution": false, + "description": "List scoped terminal sessions available to the agent.", + "inputShape": {}, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + }, + "agentKind": "global" + }, + { + "capabilityId": "attachment.list", + "toolName": "list_attachments", + "rpcMethod": "netcatty/listAttachments", + "localExecution": false, + "description": "List user-attached files in the current AI chat scope.", + "inputShape": {}, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + }, + "agentKind": "global" + }, + { + "capabilityId": "attachment.read", + "toolName": "read_attachment", + "rpcMethod": "netcatty/readAttachment", + "localExecution": false, + "description": "Read a user-attached file from the current AI chat scope.", + "inputShape": { + "filePath": { + "type": "string", + "optional": true, + "description": "Exact local attachment path." + }, + "filename": { + "type": "string", + "optional": true, + "description": "Attachment filename from list_attachments." + } + }, + "policy": { + "write": false, + "sensitiveRead": true, + "longRunning": false, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + }, + "agentKind": "global" + }, + { + "capabilityId": "terminal.execute", + "toolName": "terminal_execute", + "rpcMethod": "netcatty/exec", + "localExecution": false, + "description": "Execute a short command in a terminal session and wait for completion. Use only for commands expected to finish within about 60 seconds. For long-running commands use terminal_start and terminal_poll.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "The terminal session ID to execute on." + }, + "command": { + "type": "string", + "optional": false, + "description": "The shell command to execute in the target session." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + }, + "agentKind": "global" + }, + { + "capabilityId": "terminal.start", + "toolName": "terminal_start", + "rpcMethod": "netcatty/jobStart", + "localExecution": false, + "description": "Start a long-running command in a terminal session. Prefer for builds, scans, log-following, or anything likely to exceed about 2 minutes.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "The terminal session ID to start a long-running command on." + }, + "command": { + "type": "string", + "optional": false, + "description": "The command to start in the target session." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + }, + "agentKind": "global" + }, + { + "capabilityId": "terminal.poll", + "toolName": "terminal_poll", + "rpcMethod": "netcatty/jobPoll", + "localExecution": false, + "description": "Poll incremental output from a long-running terminal job. Wait at least about 30 seconds between polls unless output justifies checking sooner.", + "inputShape": { + "jobId": { + "type": "string", + "optional": false, + "description": "The background job ID returned by terminal_start." + }, + "offset": { + "type": "number", + "optional": true, + "description": "Character offset from a previous poll (default 0)." + } + }, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + }, + "agentKind": "global" + }, + { + "capabilityId": "terminal.stop", + "toolName": "terminal_stop", + "rpcMethod": "netcatty/jobStop", + "localExecution": false, + "description": "Stop a long-running terminal job.", + "inputShape": { + "jobId": { + "type": "string", + "optional": false, + "description": "The background job ID returned by terminal_start." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": true, + "bypassesObserverBlock": true, + "bypassesApproval": true, + "bypassesChatCancel": true + }, + "agentKind": "global" + }, + { + "capabilityId": "sftp.list", + "toolName": "sftp_list", + "rpcMethod": "netcatty/sftp/list", + "localExecution": false, + "description": "List a remote directory over SFTP.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + }, + "path": { + "type": "string", + "optional": false, + "description": "Remote directory path." + } + }, + "policy": { + "write": false, + "sensitiveRead": true, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + }, + "agentKind": "global" + }, + { + "capabilityId": "sftp.read", + "toolName": "sftp_read_file", + "rpcMethod": "netcatty/sftp/read", + "localExecution": false, + "description": "Read a remote file over SFTP.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + }, + "path": { + "type": "string", + "optional": false, + "description": "Remote file path to read." + } + }, + "policy": { + "write": false, + "sensitiveRead": true, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + }, + "agentKind": "global" + }, + { + "capabilityId": "sftp.write", + "toolName": "sftp_write_file", + "rpcMethod": "netcatty/sftp/write", + "localExecution": false, + "description": "Write a remote file over SFTP.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + }, + "path": { + "type": "string", + "optional": false, + "description": "Remote file path to write." + }, + "content": { + "type": "string", + "optional": false, + "description": "File content to write." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + }, + "agentKind": "global" + }, + { + "capabilityId": "sftp.download", + "toolName": "sftp_download", + "rpcMethod": "netcatty/sftp/download", + "localExecution": false, + "description": "Download a remote file to a local path.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + }, + "remotePath": { + "type": "string", + "optional": false, + "description": "Remote file path to download." + }, + "localPath": { + "type": "string", + "optional": false, + "description": "Local destination path." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + }, + "agentKind": "global" + }, + { + "capabilityId": "sftp.upload", + "toolName": "sftp_upload", + "rpcMethod": "netcatty/sftp/upload", + "localExecution": false, + "description": "Upload a local file to a remote path.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + }, + "localPath": { + "type": "string", + "optional": false, + "description": "Local file path to upload." + }, + "remotePath": { + "type": "string", + "optional": false, + "description": "Remote destination path." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + }, + "agentKind": "global" + }, + { + "capabilityId": "sftp.stat", + "toolName": "sftp_stat", + "rpcMethod": "netcatty/sftp/stat", + "localExecution": false, + "description": "Get remote file metadata over SFTP.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + }, + "path": { + "type": "string", + "optional": false, + "description": "Remote path to stat." + } + }, + "policy": { + "write": false, + "sensitiveRead": true, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + }, + "agentKind": "global" + }, + { + "capabilityId": "sftp.home", + "toolName": "sftp_home", + "rpcMethod": "netcatty/sftp/home", + "localExecution": false, + "description": "Get the remote home directory for a session.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + } + }, + "policy": { + "write": false, + "sensitiveRead": true, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + }, + "agentKind": "global" + }, + { + "capabilityId": "sftp.mkdir", + "toolName": "sftp_mkdir", + "rpcMethod": "netcatty/sftp/mkdir", + "localExecution": false, + "description": "Create a remote directory over SFTP.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + }, + "path": { + "type": "string", + "optional": false, + "description": "Remote directory path to create." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + }, + "agentKind": "global" + }, + { + "capabilityId": "sftp.delete", + "toolName": "sftp_delete", + "rpcMethod": "netcatty/sftp/delete", + "localExecution": false, + "description": "Delete a remote file or directory over SFTP.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + }, + "path": { + "type": "string", + "optional": false, + "description": "Remote file or directory path to delete." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + }, + "agentKind": "global" + }, + { + "capabilityId": "sftp.rename", + "toolName": "sftp_rename", + "rpcMethod": "netcatty/sftp/rename", + "localExecution": false, + "description": "Rename a remote file or directory over SFTP.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + }, + "oldPath": { + "type": "string", + "optional": false, + "description": "Current remote path." + }, + "newPath": { + "type": "string", + "optional": false, + "description": "New remote path." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + }, + "agentKind": "global" + }, + { + "capabilityId": "sftp.chmod", + "toolName": "sftp_chmod", + "rpcMethod": "netcatty/sftp/chmod", + "localExecution": false, + "description": "Change remote file permissions over SFTP.", + "inputShape": { + "sessionId": { + "type": "string", + "optional": false, + "description": "SFTP session ID." + }, + "path": { + "type": "string", + "optional": false, + "description": "Remote file path." + }, + "mode": { + "type": "string", + "optional": false, + "description": "Octal permission mode (e.g. 755)." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + }, + "agentKind": "global" + }, + { + "capabilityId": "vault.host.get", + "toolName": "host_get", + "rpcMethod": "vault/host/get", + "localExecution": false, + "description": "Get host metadata from the vault.", + "inputShape": { + "hostId": { + "type": "string", + "optional": false, + "description": "Vault host ID." + } + }, + "policy": { + "write": false, + "sensitiveRead": true, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + }, + "agentKind": "global" + }, + { + "capabilityId": "vault.host.list", + "toolName": "vault_hosts_list", + "rpcMethod": "vault/hosts/list", + "localExecution": false, + "description": "List saved hosts in the vault (metadata only — no passwords or keys).", + "inputShape": {}, + "policy": { + "write": false, + "sensitiveRead": true, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + }, + "agentKind": "global" + }, + { + "capabilityId": "vault.hosts.create", + "toolName": "vault_hosts_create", + "rpcMethod": "vault/hosts/create", + "localExecution": false, + "description": "Create vault hosts from structured host objects. Use when the user wants to add/create a host (Vault → Hosts). NOT for Vault → Notes sidebar documentation. Use when the user wants to add/create a host in Vault → Hosts (创建主机、SSH 连接凭据). NOT for Vault → Notes sidebar docs. Put SSH password in password field; long remarks/admin tables in host notes field. Never fall back to vault_notes_create if this fails.", + "inputShape": { + "hosts": { + "type": "string", + "optional": false, + "description": "JSON array of host objects you extracted from the user's text. Each object: hostname (required), label, port, username, password, group, tags (array or comma-separated string), notes (Host Details remarks — NOT Vault sidebar Notes), protocol (ssh|telnet|local)." + }, + "dryRun": { + "type": "string", + "optional": true, + "description": "Set to true to validate and preview without writing to the vault." + }, + "skipDuplicates": { + "type": "string", + "optional": true, + "description": "Set to false to create even when a matching host already exists (default true)." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + }, + "agentKind": "global" + }, + { + "capabilityId": "vault.host.import", + "toolName": "vault_hosts_import", + "rpcMethod": "vault/hosts/import", + "localExecution": false, + "description": "Parse known host export file formats (PuTTY, MobaXterm, CSV, SecureCRT, ssh_config) into vault hosts. For arbitrary unstructured text, map to host objects and use vault_hosts_create instead. Only for text in known export formats (PuTTY reg, MobaXterm ini, CSV template, SecureCRT, ssh_config). For arbitrary unstructured host lists from the user, extract fields yourself and call vault_hosts_create.", + "inputShape": { + "format": { + "type": "string", + "optional": false, + "description": "Import format: csv, putty, mobaxterm, securecrt, ssh_config, or auto to detect from text." + }, + "text": { + "type": "string", + "optional": false, + "description": "Exported host data text to import." + }, + "dryRun": { + "type": "string", + "optional": true, + "description": "Set to true to parse and preview without writing to the vault." + }, + "skipDuplicates": { + "type": "string", + "optional": true, + "description": "Set to false to import even when a matching host already exists (default true)." + }, + "fileName": { + "type": "string", + "optional": true, + "description": "Optional source file name (helps SecureCRT .ini parsing)." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + }, + "agentKind": "global" + }, + { + "capabilityId": "vault.host.notes.get", + "toolName": "host_notes_get", + "rpcMethod": "vault/host/notes/get", + "localExecution": false, + "description": "Read host metadata notes attached to a saved host (Host Details panel — not Vault sidebar Notes). Host metadata notes on a saved host — not Vault → Notes sidebar entries.", + "inputShape": { + "hostId": { + "type": "string", + "optional": false, + "description": "Vault host ID." + } + }, + "policy": { + "write": false, + "sensitiveRead": true, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + }, + "agentKind": "global" + }, + { + "capabilityId": "vault.host.notes.set", + "toolName": "host_notes_set", + "rpcMethod": "vault/host/notes/set", + "localExecution": false, + "description": "Update host metadata notes on a saved host (Host Details panel — not Vault sidebar Notes). Host metadata notes on a saved host — not Vault → Notes sidebar entries. Prefer vault_notes_create/update when the user wants vault notes they can open in the Notes sidebar.", + "inputShape": { + "hostId": { + "type": "string", + "optional": false, + "description": "Vault host ID." + }, + "notes": { + "type": "string", + "optional": false, + "description": "Host metadata notes (Host Details — not Vault sidebar Notes)." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + }, + "agentKind": "global" + }, + { + "capabilityId": "vault.note.list", + "toolName": "vault_notes_list", + "rpcMethod": "vault/notes/list", + "localExecution": false, + "description": "List notes in Vault → Notes (markdown notes visible in the vault sidebar).", + "inputShape": {}, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + }, + "agentKind": "global" + }, + { + "capabilityId": "vault.note.get", + "toolName": "vault_notes_get", + "rpcMethod": "vault/notes/get", + "localExecution": false, + "description": "Get a Vault → Notes entry by id (full markdown content).", + "inputShape": { + "noteId": { + "type": "string", + "optional": false, + "description": "Vault note ID from vault_notes_list." + } + }, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + }, + "agentKind": "global" + }, + { + "capabilityId": "vault.note.create", + "toolName": "vault_notes_create", + "rpcMethod": "vault/notes/create", + "localExecution": false, + "description": "Create a note in Vault → Notes sidebar (markdown documentation). NOT for adding SSH hosts — use vault_hosts_create for that. Use ONLY when the user wants markdown documentation in Vault → Notes sidebar (保险箱笔记). Do NOT use when the user asked to create/add a host — use vault_hosts_create instead.", + "inputShape": { + "title": { + "type": "string", + "optional": false, + "description": "Note title shown in Vault → Notes." + }, + "content": { + "type": "string", + "optional": false, + "description": "Markdown note body." + }, + "group": { + "type": "string", + "optional": true, + "description": "Optional folder path (e.g. infra/prod)." + }, + "linkedHostIds": { + "type": "string", + "optional": true, + "description": "Optional JSON array of vault host IDs to link." + }, + "tags": { + "type": "string", + "optional": true, + "description": "Optional JSON array of tag strings." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + }, + "agentKind": "global" + }, + { + "capabilityId": "vault.note.update", + "toolName": "vault_notes_update", + "rpcMethod": "vault/notes/update", + "localExecution": false, + "description": "Update an existing Vault → Notes entry by id. Update an existing Vault → Notes entry (visible in the vault notes sidebar).", + "inputShape": { + "noteId": { + "type": "string", + "optional": false, + "description": "Vault note ID to update." + }, + "title": { + "type": "string", + "optional": true, + "description": "New title." + }, + "content": { + "type": "string", + "optional": true, + "description": "New markdown body." + }, + "group": { + "type": "string", + "optional": true, + "description": "New folder path." + }, + "linkedHostIds": { + "type": "string", + "optional": true, + "description": "Optional JSON array of vault host IDs to link." + }, + "tags": { + "type": "string", + "optional": true, + "description": "Optional JSON array of tag strings." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + }, + "agentKind": "global" + }, + { + "capabilityId": "vault.snippets.list", + "toolName": "snippets_list", + "rpcMethod": "vault/snippets/list", + "localExecution": false, + "description": "List code snippets stored in the vault.", + "inputShape": {}, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + }, + "agentKind": "global" + }, + { + "capabilityId": "vault.snippets.get", + "toolName": "snippets_get", + "rpcMethod": "vault/snippets/get", + "localExecution": false, + "description": "Get a single code snippet from the vault.", + "inputShape": { + "snippetId": { + "type": "string", + "optional": false, + "description": "Snippet ID." + } + }, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + }, + "agentKind": "global" + }, + { + "capabilityId": "vault.snippets.run", + "toolName": "snippets_run", + "rpcMethod": "vault/snippets/run", + "localExecution": false, + "description": "Resolve snippet variables and execute a snippet in a terminal session.", + "inputShape": { + "snippetId": { + "type": "string", + "optional": false, + "description": "Snippet ID to run." + }, + "sessionId": { + "type": "string", + "optional": false, + "description": "Terminal session ID to execute on." + }, + "variables": { + "type": "string", + "optional": true, + "description": "JSON object of snippet variable values." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": true, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + }, + "agentKind": "global" + }, + { + "capabilityId": "portforward.rules.list", + "toolName": "portforward_rules_list", + "rpcMethod": "portforward/rules/list", + "localExecution": false, + "description": "List persisted port forwarding rules.", + "inputShape": {}, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + }, + "agentKind": "global" + }, + { + "capabilityId": "portforward.tunnels.list", + "toolName": "portforward_tunnels_list", + "rpcMethod": "portforward/tunnels/list", + "localExecution": false, + "description": "List active port forwarding tunnels.", + "inputShape": {}, + "policy": { + "write": false, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": true, + "bypassesChatCancel": true + }, + "agentKind": "global" + }, + { + "capabilityId": "portforward.start", + "toolName": "portforward_start", + "rpcMethod": "portforward/start", + "localExecution": false, + "description": "Start a port forwarding tunnel for a rule.", + "inputShape": { + "ruleId": { + "type": "string", + "optional": false, + "description": "Port forwarding rule ID." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": true, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + }, + "agentKind": "global" + }, + { + "capabilityId": "portforward.stop", + "toolName": "portforward_stop", + "rpcMethod": "portforward/stop", + "localExecution": false, + "description": "Stop an active port forwarding tunnel.", + "inputShape": { + "ruleId": { + "type": "string", + "optional": false, + "description": "Port forwarding rule ID." + } + }, + "policy": { + "write": true, + "sensitiveRead": false, + "longRunning": false, + "requiresChatSession": false, + "bypassesObserverBlock": false, + "bypassesApproval": false, + "bypassesChatCancel": false + }, + "agentKind": "global" + } +] diff --git a/infrastructure/ai/harness/globalAgentRuntime.ts b/infrastructure/ai/harness/globalAgentRuntime.ts new file mode 100644 index 000000000..88551f187 --- /dev/null +++ b/infrastructure/ai/harness/globalAgentRuntime.ts @@ -0,0 +1,11 @@ +import { AgentRuntime } from './agentRuntime'; +import { cattyTurnDriver } from './turnDrivers/cattyTurnDriver'; +import { externalSdkTurnDriver } from './turnDrivers/externalSdkTurnDriver'; + +export const globalAgentRuntime = new AgentRuntime({ + drivers: [cattyTurnDriver, externalSdkTurnDriver], +}); + +export function getAgentRuntime(): AgentRuntime { + return globalAgentRuntime; +} diff --git a/infrastructure/ai/harness/index.ts b/infrastructure/ai/harness/index.ts new file mode 100644 index 000000000..72247bd94 --- /dev/null +++ b/infrastructure/ai/harness/index.ts @@ -0,0 +1,99 @@ +export type { + AgentBackend, + AgentEvent, + AgentEventListener, + AgentEventType, + ApprovalOutcome, + CompactionEvent, + CompactionTrace, + ContextPrepareResult, + ContextPrepareTrigger, + ExternalBridgeHistoryMessage, + TokenEstimatorKind, + UsageEvent, +} from './types'; + +export { TraceStore, globalTraceStore } from './traceStore'; +export type { TraceExport } from './traceStore'; + +export { stopAgentTurn, clearChatSessionCancelled } from './agentStop'; +export type { AgentStopBridge, StopAgentTurnParams, StopAgentTurnReason } from './agentStop'; + +export { AgentRuntime } from './agentRuntime'; +export { globalAgentRuntime, getAgentRuntime } from './globalAgentRuntime'; + +export { + estimateModelMessagesTokens, + estimateModelMessagesTokensWithKind, +} from './tokenEstimator'; +export type { EstimateModelMessagesTokensInput, EstimateModelMessagesTokensResult } from './tokenEstimator'; + +export { ToolOutputStore, globalToolOutputStore } from './toolOutputStore'; +export type { ToolOutputHandle, StoreToolOutputInput, ReadToolOutputInput } from './toolOutputStore'; + +export { ToolResultDedup, hashScopeKey, previewToolResult } from './toolResultDedup'; +export type { ToolResultDedupEntry } from './toolResultDedup'; + +export { cattyTurnDriver } from './turnDrivers/cattyTurnDriver'; +export { externalSdkTurnDriver } from './turnDrivers/externalSdkTurnDriver'; +export type { + TurnInput, + TurnResult, + TurnDriver, + TurnDriverContext, + TurnUiCallbacks, + CattyTurnInput, + ExternalTurnInput, +} from './turnDrivers/types'; + +export { + prepareTurnContext, + prepareStepContext, + buildExternalBridgeContext, + extractLatestUserGoal, +} from './contextManager'; +export type { PrepareTurnContextInput, PostCompactReinjection } from './contextManager'; + +export { buildExternalBridgeContextMessages } from './externalBridgeContext'; + +export { + fitTerminalExecuteResultForModel, + MAX_LIVE_TERMINAL_STDOUT_CHARS, + MAX_LIVE_TERMINAL_STDERR_CHARS, +} from './terminalCompression'; +export type { TerminalExecuteResult, TerminalOutputHandle } from './terminalCompression'; + +export { + encodeSdkSessionIdentity, + parseSdkSessionIdentity, + SDK_SESSION_ID_PREFIX, +} from './sdkSessionIdentity'; +export type { SdkSessionIdentityPayload } from './sdkSessionIdentity'; + +export { + mapCattyStreamChunkToAgentEvents, + mapSdkStreamEventToAgentEvents, + createHarnessEventSink, +} from './agentEventAdapter'; +export type { StreamEventContext } from './agentEventAdapter'; + +export { + compactCattyMessages, + prepareCattyMessagesForStream, +} from './cattyRuntime'; +export type { CompactCattyMessagesInput, CompactCattyMessagesResult } from './cattyRuntime'; + +export { createCattyToolsFromCatalog } from './capabilityTools'; + +export { + PermissionGrantStore, + buildGrantFromApproval, + createPermissionGrantId, + getActivePermissionGrants, + matchPermissionGrant, + patternMatches, + resolveCapabilityId, + sanitizePermissionGrants, + setActivePermissionGrants, +} from './permissionGrants'; +export type { PermissionGrantMatchContext, PermissionGrantRule } from './permissionGrants'; diff --git a/infrastructure/ai/harness/permissionGrants.test.ts b/infrastructure/ai/harness/permissionGrants.test.ts new file mode 100644 index 000000000..0bb56716f --- /dev/null +++ b/infrastructure/ai/harness/permissionGrants.test.ts @@ -0,0 +1,87 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { + buildGrantFromApproval, + buildGrantsFromApproval, + listGrantableCapabilityIds, + matchPermissionGrant, + patternMatches, + type PermissionGrantRule, +} from './permissionGrants'; + +const baseRule = (overrides: Partial): PermissionGrantRule => ({ + id: 'grant-1', + capabilityId: 'terminal.execute', + sessionPattern: 'session-a', + createdAt: Date.now(), + ...overrides, +}); + +describe('permissionGrants', () => { + it('matches wildcard session and command patterns', () => { + const rules = [baseRule({ sessionPattern: '*', commandPattern: 'ls *' })]; + const matched = matchPermissionGrant(rules, { + capabilityId: 'terminal.execute', + sessionId: 'any-session', + args: { command: 'ls -la /tmp' }, + }); + assert.ok(matched); + }); + + it('ignores sessionPattern and matches globally by capability and command', () => { + const rules = [baseRule({ sessionPattern: 'old-session-uuid', commandPattern: 'ls *' })]; + const matched = matchPermissionGrant(rules, { + capabilityId: 'terminal.execute', + sessionId: 'different-session', + args: { command: 'ls -la /tmp' }, + }); + assert.ok(matched); + }); + + it('does not match a different capability', () => { + const rules = [baseRule({ sessionPattern: '*' })]; + const matched = matchPermissionGrant(rules, { + capabilityId: 'terminal.start', + sessionId: 'session-a', + args: { command: 'make' }, + }); + assert.equal(matched, null); + }); + + it('buildGrantFromApproval uses global scope and OpenCode-style command prefix patterns', () => { + const grant = buildGrantFromApproval('terminal.execute', { + sessionId: 'ssh-1', + command: 'systemctl status nginx', + }, 'chat-1'); + assert.equal(grant.sessionPattern, '*'); + assert.equal(grant.commandPattern, 'systemctl status *'); + }); + + it('buildGrantsFromApproval emits one rule per chained command segment', () => { + const grants = buildGrantsFromApproval('terminal.execute', { + sessionId: 'ssh-1', + command: 'cd /tmp && lscpu', + }, 'chat-1'); + assert.equal(grants.length, 1); + assert.equal(grants[0]?.commandPattern, 'lscpu *'); + }); + + it('OpenCode wildcard allows optional args after prefix', () => { + assert.equal(patternMatches('lscpu *', 'lscpu'), true); + assert.equal(patternMatches('lscpu *', 'lscpu -e'), true); + assert.equal(patternMatches('git checkout *', 'git checkout main'), true); + assert.equal(patternMatches('git checkout *', 'git commit'), false); + }); + + it('lists grantable capability ids from catalog policy', () => { + const ids = listGrantableCapabilityIds(); + assert.ok(ids.includes('terminal.execute')); + assert.ok(ids.includes('sftp.write')); + assert.ok(!ids.includes('terminal.poll')); + }); + + it('patternMatches supports regex literals', () => { + assert.equal(patternMatches('/^ls\\b/', 'ls -la'), true); + assert.equal(patternMatches('/^ls\\b/', 'cat file'), false); + }); +}); diff --git a/infrastructure/ai/harness/permissionGrants.ts b/infrastructure/ai/harness/permissionGrants.ts new file mode 100644 index 000000000..e7d623db8 --- /dev/null +++ b/infrastructure/ai/harness/permissionGrants.ts @@ -0,0 +1,286 @@ +import cattyToolSpecs from './generated/cattyToolSpecs.json'; +import { buildAlwaysAllowCommandPatterns } from '../shared/shellCommandGrant'; + +export interface PermissionGrantRule { + id: string; + capabilityId: string; + sessionPattern: string; + commandPattern?: string; + argsPattern?: Record; + createdAt: number; + note?: string; +} + +export interface PermissionGrantMatchContext { + capabilityId: string; + sessionId?: string; + chatSessionId?: string; + hostname?: string; + args?: Record; +} + +type CattyToolSpecRef = { + capabilityId: string; + toolName: string; + rpcMethod: string | null; + policy?: { + write?: boolean; + bypassesApproval?: boolean; + }; +}; + +const TOOL_NAME_TO_CAPABILITY = new Map(); +const RPC_METHOD_TO_CAPABILITY = new Map(); + +for (const spec of cattyToolSpecs as CattyToolSpecRef[]) { + TOOL_NAME_TO_CAPABILITY.set(spec.toolName, spec.capabilityId); + if (spec.rpcMethod) { + RPC_METHOD_TO_CAPABILITY.set(spec.rpcMethod, spec.capabilityId); + } +} + +export function resolveCapabilityId(toolOrRpcName: string): string { + return TOOL_NAME_TO_CAPABILITY.get(toolOrRpcName) + ?? RPC_METHOD_TO_CAPABILITY.get(toolOrRpcName) + ?? toolOrRpcName; +} + +export function patternMatches(pattern: string, value: string): boolean { + if (!pattern) return false; + if (pattern === '*') return true; + + if (pattern.startsWith('host:')) { + return globOrRegexMatch(pattern.slice('host:'.length), value); + } + + return globOrRegexMatch(pattern, value); +} + +function globOrRegexMatch(pattern: string, value: string): boolean { + if (pattern.startsWith('/') && pattern.lastIndexOf('/') > 0) { + const lastSlash = pattern.lastIndexOf('/'); + const body = pattern.slice(1, lastSlash); + const flags = pattern.slice(lastSlash + 1); + try { + return new RegExp(body, flags).test(value); + } catch { + return false; + } + } + + if (!pattern.includes('*') && !pattern.includes('?')) { + return value === pattern; + } + + // OpenCode Wildcard.match semantics (trailing " *" allows optional args). + let escaped = pattern + .replace(/[.+^${}()|[\]\\]/g, '\\$&') + .replace(/\*/g, '.*') + .replace(/\?/g, '.'); + if (escaped.endsWith(' .*')) { + escaped = `${escaped.slice(0, -3)}( .*)?`; + } + + return new RegExp(`^${escaped}$`, 's').test(value); +} + +function argsPatternMatches( + argsPattern: Record | undefined, + args: Record | undefined, +): boolean { + if (!argsPattern) return true; + if (!args) return false; + + for (const [key, pattern] of Object.entries(argsPattern)) { + const argValue = args[key]; + if (typeof argValue === 'undefined') return false; + if (!patternMatches(pattern, String(argValue))) return false; + } + return true; +} + +export function matchPermissionGrant( + rules: readonly PermissionGrantRule[], + ctx: PermissionGrantMatchContext, +): PermissionGrantRule | null { + if (rules.length === 0) return null; + + const args = ctx.args ?? {}; + + for (const rule of rules) { + if (rule.capabilityId !== ctx.capabilityId) continue; + + if (rule.commandPattern) { + const command = typeof args.command === 'string' ? args.command : ''; + if (!patternMatches(rule.commandPattern, command)) continue; + } + + if (!argsPatternMatches(rule.argsPattern, args)) continue; + + return rule; + } + + return null; +} + +export function sanitizePermissionGrants(raw: unknown): PermissionGrantRule[] { + if (!Array.isArray(raw)) return []; + + const result: PermissionGrantRule[] = []; + for (const entry of raw) { + if (!entry || typeof entry !== 'object') continue; + const record = entry as Record; + const capabilityId = typeof record.capabilityId === 'string' ? record.capabilityId.trim() : ''; + if (!capabilityId) continue; + + const rule: PermissionGrantRule = { + id: typeof record.id === 'string' && record.id.trim() + ? record.id.trim().slice(0, 64) + : createPermissionGrantId(), + capabilityId, + sessionPattern: typeof record.sessionPattern === 'string' && record.sessionPattern.trim() + ? record.sessionPattern.trim() + : '*', + createdAt: typeof record.createdAt === 'number' && Number.isFinite(record.createdAt) + ? record.createdAt + : Date.now(), + }; + + if (typeof record.commandPattern === 'string' && record.commandPattern.trim()) { + rule.commandPattern = record.commandPattern.trim(); + } + if (record.argsPattern && typeof record.argsPattern === 'object' && !Array.isArray(record.argsPattern)) { + const argsPattern: Record = {}; + for (const [key, value] of Object.entries(record.argsPattern as Record)) { + if (typeof value === 'string' && value.trim()) { + argsPattern[key] = value.trim(); + } + } + if (Object.keys(argsPattern).length > 0) { + rule.argsPattern = argsPattern; + } + } + if (typeof record.note === 'string' && record.note.trim()) { + rule.note = record.note.trim().slice(0, 240); + } + + result.push(rule); + } + + return result; +} + +export function createPermissionGrantId(): string { + return `grant_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; +} + +const COMMAND_GRANT_CAPABILITIES = new Set([ + 'terminal.execute', + 'terminal.start', +]); + +const GRANTABLE_CAPABILITY_IDS: readonly string[] = Object.freeze( + [...new Set( + (cattyToolSpecs as CattyToolSpecRef[]) + .filter((spec) => spec.policy?.write && !spec.policy?.bypassesApproval) + .map((spec) => spec.capabilityId), + )].sort(), +); + +export function listGrantableCapabilityIds(): readonly string[] { + return GRANTABLE_CAPABILITY_IDS; +} + +export function capabilitySupportsCommandPatternGrant(capabilityId: string): boolean { + return COMMAND_GRANT_CAPABILITIES.has(capabilityId); +} + +function resolveCommandGrantPatterns( + capabilityId: string, + args: Record, +): string[] | undefined { + if (!COMMAND_GRANT_CAPABILITIES.has(capabilityId)) return undefined; + const command = typeof args.command === 'string' ? args.command.trim() : ''; + if (!command) return undefined; + return buildAlwaysAllowCommandPatterns(command); +} + +export function buildGrantsFromApproval( + capabilityId: string, + args: Record, + _chatSessionId?: string, +): PermissionGrantRule[] { + // OpenCode-style always-allow: global scope (not bound to a terminal session UUID). + const sessionPattern = '*'; + const commandPatterns = resolveCommandGrantPatterns(capabilityId, args); + const createdAt = Date.now(); + + if (!commandPatterns || commandPatterns.length === 0) { + return [{ + id: createPermissionGrantId(), + capabilityId, + sessionPattern, + createdAt, + }]; + } + + return commandPatterns.map((commandPattern) => ({ + id: createPermissionGrantId(), + capabilityId, + sessionPattern, + commandPattern, + createdAt, + })); +} + +export function buildGrantFromApproval( + capabilityId: string, + args: Record, + chatSessionId?: string, +): PermissionGrantRule { + return buildGrantsFromApproval(capabilityId, args, chatSessionId)[0]; +} + +let activeRules: PermissionGrantRule[] = []; + +export function setActivePermissionGrants(rules: PermissionGrantRule[]): void { + activeRules = [...rules]; +} + +export function getActivePermissionGrants(): readonly PermissionGrantRule[] { + return activeRules; +} + +export class PermissionGrantStore { + private rules: PermissionGrantRule[]; + + constructor(rules: PermissionGrantRule[] = []) { + this.rules = [...rules]; + } + + getRules(): readonly PermissionGrantRule[] { + return this.rules; + } + + setRules(rules: PermissionGrantRule[]): void { + this.rules = [...rules]; + } + + addRule(rule: PermissionGrantRule): void { + this.rules = [...this.rules, rule]; + } + + updateRule(id: string, updates: Partial>): void { + this.rules = this.rules.map((rule) => ( + rule.id === id ? { ...rule, ...updates } : rule + )); + } + + removeRule(id: string): void { + this.rules = this.rules.filter((rule) => rule.id !== id); + } + + match(ctx: PermissionGrantMatchContext): PermissionGrantRule | null { + return matchPermissionGrant(this.rules, ctx); + } +} diff --git a/infrastructure/ai/harness/sdkSessionIdentity.ts b/infrastructure/ai/harness/sdkSessionIdentity.ts new file mode 100644 index 000000000..bb2ddf437 --- /dev/null +++ b/infrastructure/ai/harness/sdkSessionIdentity.ts @@ -0,0 +1,35 @@ +export const SDK_SESSION_ID_PREFIX = 'netcatty-sdk-session:'; + +export interface SdkSessionIdentityPayload { + v: 1; + id: string; + backend: string; + binPath: string; +} + +export function encodeSdkSessionIdentity( + sessionId: string, + sdkBackend?: string, + binPath?: string, +): string { + if (!sessionId || !sdkBackend) return sessionId; + const payload: SdkSessionIdentityPayload = { + v: 1, + id: sessionId, + backend: sdkBackend, + binPath: binPath || '', + }; + return `${SDK_SESSION_ID_PREFIX}${encodeURIComponent(JSON.stringify(payload))}`; +} + +export function parseSdkSessionIdentity(value: string | undefined | null): SdkSessionIdentityPayload | null { + const raw = String(value || '').trim(); + if (!raw.startsWith(SDK_SESSION_ID_PREFIX)) return null; + try { + const parsed = JSON.parse(decodeURIComponent(raw.slice(SDK_SESSION_ID_PREFIX.length))) as SdkSessionIdentityPayload; + if (parsed?.v !== 1 || !parsed.id || !parsed.backend) return null; + return parsed; + } catch { + return null; + } +} diff --git a/infrastructure/ai/harness/terminalCompression.ts b/infrastructure/ai/harness/terminalCompression.ts new file mode 100644 index 000000000..c53f265d0 --- /dev/null +++ b/infrastructure/ai/harness/terminalCompression.ts @@ -0,0 +1,93 @@ +import { compressVerboseText, truncateTextWithHeadAndTail } from '../requestPayloadCompression'; +import type { ToolOutputStore } from './toolOutputStore'; + +export const MAX_LIVE_TERMINAL_STDOUT_CHARS = 24_000; +export const MAX_LIVE_TERMINAL_STDERR_CHARS = 12_000; + +export interface TerminalExecuteResult { + stdout: string; + stderr: string; + exitCode: number | null; + command?: string; + sessionId?: string; +} + +export interface TerminalOutputHandle { + kind: 'terminal-output'; + sessionId: string; + command?: string; + totalStdoutChars: number; + totalStderrChars: number; + handleId?: string; +} + +export interface FitTerminalExecuteResultOptions { + chatSessionId?: string; + toolOutputStore?: ToolOutputStore; +} + +export function fitTerminalExecuteResultForModel( + result: TerminalExecuteResult, + options?: FitTerminalExecuteResultOptions, +): TerminalExecuteResult { + const stdout = truncateTextWithHeadAndTail( + compressVerboseText(result.stdout), + MAX_LIVE_TERMINAL_STDOUT_CHARS, + ); + const stderr = truncateTextWithHeadAndTail( + compressVerboseText(result.stderr), + MAX_LIVE_TERMINAL_STDERR_CHARS, + ); + + const fitted: TerminalExecuteResult = { + ...result, + stdout, + stderr, + }; + + if ( + stdout.length < result.stdout.length + || stderr.length < result.stderr.length + ) { + const fullContent = [ + result.command ? `command: ${result.command}` : '', + result.stdout ? `stdout:\n${result.stdout}` : '', + result.stderr ? `stderr:\n${result.stderr}` : '', + ].filter(Boolean).join('\n\n'); + + let handleId: string | undefined; + if (options?.toolOutputStore && options.chatSessionId && fullContent) { + handleId = options.toolOutputStore.store({ + chatSessionId: options.chatSessionId, + capabilityId: 'terminal.execute', + sessionId: result.sessionId, + content: fullContent, + }).id; + } + + const handle: TerminalOutputHandle = { + kind: 'terminal-output', + sessionId: result.sessionId ?? 'unknown', + command: result.command, + totalStdoutChars: result.stdout.length, + totalStderrChars: result.stderr.length, + handleId, + }; + fitted.stdout = appendOutputHandleNotice(stdout, handle, 'stdout'); + if (result.stderr) { + fitted.stderr = appendOutputHandleNotice(stderr, handle, 'stderr'); + } + } + + return fitted; +} + +function appendOutputHandleNotice( + truncated: string, + handle: TerminalOutputHandle, + stream: 'stdout' | 'stderr', +): string { + const totalChars = stream === 'stdout' ? handle.totalStdoutChars : handle.totalStderrChars; + const handleSuffix = handle.handleId ? ` handleId=${handle.handleId}` : ''; + return `${truncated}\n\n[output handle: session=${handle.sessionId}${handle.command ? ` command=${handle.command}` : ''} ${stream}=${totalChars} chars truncated for model context${handleSuffix}]`; +} diff --git a/infrastructure/ai/harness/tokenEstimator.ts b/infrastructure/ai/harness/tokenEstimator.ts new file mode 100644 index 000000000..624baa488 --- /dev/null +++ b/infrastructure/ai/harness/tokenEstimator.ts @@ -0,0 +1,71 @@ +import type { ModelMessage } from 'ai'; +import type { TokenEstimatorKind } from './types'; + +const CHARS_PER_TOKEN_FALLBACK = 4; + +function estimateChars(value: unknown): number { + if (value == null) return 0; + if (typeof value === 'string') return value.length; + if (Array.isArray(value)) { + return value.reduce((sum, item) => sum + estimateChars(item), 0); + } + if (typeof value === 'object') { + try { + return JSON.stringify(value).length; + } catch { + return String(value).length; + } + } + return String(value).length; +} + +function resolveEstimatorKind(providerId?: string | null): TokenEstimatorKind { + const id = (providerId ?? '').toLowerCase(); + if (id.includes('openai') || id.includes('gpt')) return 'openai-heuristic'; + if (id.includes('anthropic') || id.includes('claude')) return 'anthropic-heuristic'; + if (id.includes('google') || id.includes('gemini')) return 'google-heuristic'; + return 'chars-div-4'; +} + +function applyHeuristicMultiplier(chars: number, kind: TokenEstimatorKind): number { + switch (kind) { + case 'openai-heuristic': + return Math.ceil(chars / 3.5); + case 'anthropic-heuristic': + return Math.ceil(chars / 3.2); + case 'google-heuristic': + return Math.ceil(chars / 3.8); + default: + return Math.ceil(chars / CHARS_PER_TOKEN_FALLBACK); + } +} + +export interface EstimateModelMessagesTokensInput { + messages: ModelMessage[]; + providerId?: string | null; +} + +export interface EstimateModelMessagesTokensResult { + tokens: number; + estimatorKind: TokenEstimatorKind; +} + +export function estimateModelMessagesTokensWithKind( + input: EstimateModelMessagesTokensInput, +): EstimateModelMessagesTokensResult { + const estimatorKind = resolveEstimatorKind(input.providerId); + const chars = input.messages.reduce((total, message) => { + return total + estimateChars(message.role) + estimateChars(message.content); + }, 0); + return { + tokens: applyHeuristicMultiplier(chars, estimatorKind), + estimatorKind, + }; +} + +export function estimateModelMessagesTokens( + messages: ModelMessage[], + providerId?: string | null, +): number { + return estimateModelMessagesTokensWithKind({ messages, providerId }).tokens; +} diff --git a/infrastructure/ai/harness/toolOutputStore.test.ts b/infrastructure/ai/harness/toolOutputStore.test.ts new file mode 100644 index 000000000..535c76e79 --- /dev/null +++ b/infrastructure/ai/harness/toolOutputStore.test.ts @@ -0,0 +1,26 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { ToolOutputStore } from './toolOutputStore'; + +test('ToolOutputStore stores and reads truncated output by handle', () => { + const store = new ToolOutputStore(); + const handle = store.store({ + chatSessionId: 'chat-1', + capabilityId: 'terminal.execute', + sessionId: 'sess-1', + content: 'A'.repeat(50_000), + }); + + assert.ok(handle.id.startsWith('tool-output-')); + assert.equal(handle.totalChars, 50_000); + + const head = store.read({ handleId: handle.id, mode: 'head', maxChars: 100 }, 'chat-1'); + assert.equal(head?.length, 100); + + const tail = store.read({ handleId: handle.id, mode: 'tail', maxChars: 50 }, 'chat-1'); + assert.equal(tail?.length, 50); + assert.equal(tail, 'A'.repeat(50)); + + store.prune('chat-1'); + assert.equal(store.read({ handleId: handle.id }, 'chat-1'), null); +}); diff --git a/infrastructure/ai/harness/toolOutputStore.ts b/infrastructure/ai/harness/toolOutputStore.ts new file mode 100644 index 000000000..38824ac50 --- /dev/null +++ b/infrastructure/ai/harness/toolOutputStore.ts @@ -0,0 +1,87 @@ +export interface ToolOutputHandle { + id: string; + capabilityId: string; + sessionId?: string; + totalChars: number; + preview: string; + storedAt: number; + fullContent: string; +} + +export interface StoreToolOutputInput { + chatSessionId: string; + capabilityId: string; + content: string; + sessionId?: string; + previewChars?: number; +} + +export interface ReadToolOutputInput { + handleId: string; + mode?: 'head' | 'tail' | 'full'; + maxChars?: number; +} + +let handleCounter = 0; + +function nextHandleId(): string { + handleCounter += 1; + return `tool-output-${Date.now()}-${handleCounter}`; +} + +export class ToolOutputStore { + private readonly bySession = new Map>(); + + store(input: StoreToolOutputInput): ToolOutputHandle { + const previewChars = input.previewChars ?? 240; + const handle: ToolOutputHandle = { + id: nextHandleId(), + capabilityId: input.capabilityId, + sessionId: input.sessionId, + totalChars: input.content.length, + preview: input.content.slice(0, previewChars), + storedAt: Date.now(), + fullContent: input.content, + }; + const sessionMap = this.bySession.get(input.chatSessionId) ?? new Map(); + sessionMap.set(handle.id, handle); + this.bySession.set(input.chatSessionId, sessionMap); + return handle; + } + + get(handleId: string, chatSessionId?: string): ToolOutputHandle | undefined { + if (chatSessionId) { + return this.bySession.get(chatSessionId)?.get(handleId); + } + for (const sessionMap of this.bySession.values()) { + const handle = sessionMap.get(handleId); + if (handle) return handle; + } + return undefined; + } + + listPendingHandles(chatSessionId: string): ToolOutputHandle[] { + return [...(this.bySession.get(chatSessionId)?.values() ?? [])]; + } + + read(input: ReadToolOutputInput, chatSessionId?: string): string | null { + const handle = this.get(input.handleId, chatSessionId); + if (!handle) return null; + const maxChars = input.maxChars ?? 12_000; + const mode = input.mode ?? 'head'; + const content = handle.fullContent; + if (mode === 'full') { + return content.length <= maxChars ? content : content.slice(0, maxChars); + } + if (mode === 'tail') { + return content.length <= maxChars ? content : content.slice(-maxChars); + } + return content.slice(0, maxChars); + } + + prune(chatSessionId: string): void { + this.bySession.delete(chatSessionId); + } +} + +export const globalToolOutputStore = new ToolOutputStore(); diff --git a/infrastructure/ai/harness/toolResultDedup.ts b/infrastructure/ai/harness/toolResultDedup.ts new file mode 100644 index 000000000..dd5d071d3 --- /dev/null +++ b/infrastructure/ai/harness/toolResultDedup.ts @@ -0,0 +1,54 @@ +export interface ToolResultDedupEntry { + fingerprint: string; + toolName: string; + turnNumber: number; + preview: string; +} + +export class ToolResultDedup { + private turnNumber = 0; + private readonly cache = new Map(); + + beginTurn(): void { + this.turnNumber += 1; + } + + reset(): void { + this.cache.clear(); + this.turnNumber = 0; + } + + fingerprintFor(toolName: string, key: string): string { + return `${toolName}:${key}`; + } + + check(fingerprint: string): ToolResultDedupEntry | undefined { + return this.cache.get(fingerprint); + } + + remember(toolName: string, fingerprint: string, preview: string): void { + this.cache.set(fingerprint, { + fingerprint, + toolName, + turnNumber: this.turnNumber, + preview: preview.slice(0, 160), + }); + } + + buildCachedNotice(entry: ToolResultDedupEntry): string { + return `[cached] same as turn ${entry.turnNumber} for ${entry.toolName}`; + } +} + +export function hashScopeKey(parts: Array): string { + return parts.filter(Boolean).join('|'); +} + +export function previewToolResult(result: unknown): string { + if (typeof result === 'string') return result.slice(0, 160); + try { + return JSON.stringify(result).slice(0, 160); + } catch { + return String(result).slice(0, 160); + } +} diff --git a/infrastructure/ai/harness/traceStore.ts b/infrastructure/ai/harness/traceStore.ts new file mode 100644 index 000000000..0c9d85f57 --- /dev/null +++ b/infrastructure/ai/harness/traceStore.ts @@ -0,0 +1,60 @@ +import type { AgentEvent, CompactionTrace } from './types'; + +const DEFAULT_MAX_EVENTS = 2_000; + +export interface TraceExport { + sessionId: string; + events: AgentEvent[]; + compactions: CompactionTrace[]; + exportedAt: number; +} + +export class TraceStore { + private readonly events = new Map(); + private readonly compactions = new Map(); + private readonly maxEvents: number; + + constructor(maxEvents = DEFAULT_MAX_EVENTS) { + this.maxEvents = maxEvents; + } + + append(event: AgentEvent): void { + const list = this.events.get(event.sessionId) ?? []; + list.push(event); + if (list.length > this.maxEvents) { + list.splice(0, list.length - this.maxEvents); + } + this.events.set(event.sessionId, list); + + if (event.type === 'compaction') { + const traces = this.compactions.get(event.sessionId) ?? []; + traces.push(event.trace); + this.compactions.set(event.sessionId, traces); + } + } + + getEvents(sessionId: string): readonly AgentEvent[] { + return this.events.get(sessionId) ?? []; + } + + getCompactions(sessionId: string): readonly CompactionTrace[] { + return this.compactions.get(sessionId) ?? []; + } + + exportTrace(sessionId: string): TraceExport { + return { + sessionId, + events: [...(this.events.get(sessionId) ?? [])], + compactions: [...(this.compactions.get(sessionId) ?? [])], + exportedAt: Date.now(), + }; + } + + clear(sessionId: string): void { + this.events.delete(sessionId); + this.compactions.delete(sessionId); + } +} + +/** Process-wide trace store for harness debugging. */ +export const globalTraceStore = new TraceStore(); diff --git a/infrastructure/ai/harness/turnDrivers/cattyMessageBuilder.ts b/infrastructure/ai/harness/turnDrivers/cattyMessageBuilder.ts new file mode 100644 index 000000000..9917401de --- /dev/null +++ b/infrastructure/ai/harness/turnDrivers/cattyMessageBuilder.ts @@ -0,0 +1,266 @@ +import type { ModelMessage } from 'ai'; +import type { ChatMessage, ChatMessageAttachment, ToolResult } from '../../types'; +import { + buildHistoricalToolReplayMaps, + buildHistoricalToolResultReplayText, + buildHistoricalUserReplayContent, +} from '../../../../components/ai/cattyHistoryReplay'; +import { + buildPromptWithTerminalSelectionAttachments, + isTerminalSelectionAttachment, +} from '../../../../application/state/terminalSelectionAttachment'; +import { + getOpenAIChatAssistantFieldsForHistoryMessage, + isProviderContinuationForSource, + type OpenAIChatAssistantFields, + type ProviderContinuation, +} from '../../providerContinuation'; +import { + toAssistantModelContent, + type AssistantContentPart, + type CattyProviderContinuationContext, +} from '../../../../components/ai/hooks/aiChatStreamingSupport'; + +const OPENAI_CHAT_ASSISTANT_FIELDS = Symbol('netcatty.openAIChatAssistantFields'); + +type ModelMessageWithOpenAIChatFields = ModelMessage & { + [OPENAI_CHAT_ASSISTANT_FIELDS]?: OpenAIChatAssistantFields; +}; + +function rememberOpenAIChatAssistantFields( + message: ModelMessage, + fields: OpenAIChatAssistantFields | undefined, + fieldsByMessage: Map, +): void { + fieldsByMessage.set(message, fields); + (message as ModelMessageWithOpenAIChatFields)[OPENAI_CHAT_ASSISTANT_FIELDS] = fields; +} + +function getRememberedOpenAIChatAssistantFields( + message: ModelMessage, + fieldsByMessage: Map, +): OpenAIChatAssistantFields | undefined { + if (fieldsByMessage.has(message)) return fieldsByMessage.get(message); + return (message as ModelMessageWithOpenAIChatFields)[OPENAI_CHAT_ASSISTANT_FIELDS]; +} + +function modelMessageHasToolCall(message: ModelMessage): boolean { + if (message.role !== 'assistant' || !Array.isArray(message.content)) return false; + return message.content.some((part) => part && typeof part === 'object' && (part as { type?: string }).type === 'tool-call'); +} + +export function collectOpenAIChatAssistantFieldsForMessages( + messages: ModelMessage[], + fieldsByMessage: Map, +): Array { + const fields: Array = []; + let previousMessageWasTool = false; + for (const message of messages) { + const needsContinuationFields = message.role === 'assistant' + && (modelMessageHasToolCall(message) || previousMessageWasTool); + if (needsContinuationFields) { + fields.push(getRememberedOpenAIChatAssistantFields(message, fieldsByMessage)); + } + previousMessageWasTool = message.role === 'tool'; + } + return fields; +} + +export interface BuildCattySdkMessagesInput { + allMessages: ChatMessage[]; + includeCurrentUserMessage: boolean; + trimmed: string; + attachments?: ChatMessageAttachment[]; + continuationContext: CattyProviderContinuationContext; + preserveTerminalToolResults?: ReadonlySet; + fieldsByMessage: Map; +} + +export function buildCattySdkMessages(input: BuildCattySdkMessagesInput): ModelMessage[] { + const { + allMessages, + includeCurrentUserMessage, + trimmed, + attachments, + continuationContext, + preserveTerminalToolResults = new Set(), + fieldsByMessage, + } = input; + + const { resolvedToolCallsByAssistant, toolCallByToolResult } = buildHistoricalToolReplayMaps(allMessages); + const nextFieldsByMessage = new Map(); + const sdkMessages: ModelMessage[] = []; + let previousHistoryMessageWasToolResult = false; + + for (const m of allMessages) { + const currentMessageFollowsToolResult = previousHistoryMessageWasToolResult; + if (m.role === 'user') { + const messageAttachments = m.attachments ?? m.images; + sdkMessages.push({ + role: 'user', + content: buildHistoricalUserReplayContent(m.content, messageAttachments ?? []), + }); + } else if (m.role === 'assistant') { + const activeContinuation = isProviderContinuationForSource( + m.providerContinuation, + continuationContext.source, + ) + ? m.providerContinuation + : undefined; + const openAIChatAssistantFields = getOpenAIChatAssistantFieldsForHistoryMessage( + m, + continuationContext.source, + ); + if (m.toolCalls?.length) { + const resolvedToolCalls = resolvedToolCallsByAssistant.get(m); + const resolvedCalls = resolvedToolCalls + ? m.toolCalls.filter(tc => resolvedToolCalls.has(tc)) + : []; + const contentParts: AssistantContentPart[] = []; + if (resolvedCalls.length > 0) { + for (const part of activeContinuation?.reasoningParts ?? []) { + if (!part.text && !part.providerOptions) continue; + contentParts.push({ + type: 'reasoning' as const, + text: part.text, + ...(part.providerOptions ? { providerOptions: part.providerOptions } : {}), + }); + } + } + if (m.content) { + contentParts.push({ + type: 'text' as const, + text: m.content, + ...(activeContinuation?.textProviderOptions ? { providerOptions: activeContinuation.textProviderOptions } : {}), + }); + } + for (const tc of resolvedCalls) { + const providerOptions = activeContinuation?.toolCallProviderOptionsById?.[tc.id]; + contentParts.push({ + type: 'tool-call' as const, + toolCallId: tc.id, + toolName: tc.name, + input: tc.arguments ?? {}, + ...(providerOptions ? { providerOptions } : {}), + }); + } + if (contentParts.length > 0) { + const message: ModelMessage = { role: 'assistant', content: toAssistantModelContent(contentParts) }; + sdkMessages.push(message); + if (resolvedCalls.length > 0) { + rememberOpenAIChatAssistantFields(message, openAIChatAssistantFields, nextFieldsByMessage); + } + } + } else if (m.content) { + const contentParts: AssistantContentPart[] = []; + for (const part of activeContinuation?.reasoningParts ?? []) { + if (!part.text && !part.providerOptions) continue; + contentParts.push({ + type: 'reasoning' as const, + text: part.text, + ...(part.providerOptions ? { providerOptions: part.providerOptions } : {}), + }); + } + contentParts.push({ + type: 'text' as const, + text: m.content, + ...(activeContinuation?.textProviderOptions ? { providerOptions: activeContinuation.textProviderOptions } : {}), + }); + const message: ModelMessage = { + role: 'assistant', + content: toAssistantModelContent(contentParts), + }; + sdkMessages.push(message); + if (currentMessageFollowsToolResult) { + rememberOpenAIChatAssistantFields(message, openAIChatAssistantFields, nextFieldsByMessage); + } + } + } else if (m.role === 'tool' && m.toolResults?.length) { + sdkMessages.push({ + role: 'tool', + content: m.toolResults.map(tr => { + const toolCall = toolCallByToolResult.get(tr); + return { + type: 'tool-result' as const, + toolCallId: tr.toolCallId, + toolName: toolCall?.name ?? 'unknown', + output: { + type: 'text' as const, + value: buildHistoricalToolResultReplayText(tr, toolCall, { + preserveTerminalOutput: preserveTerminalToolResults.has(tr), + }), + }, + }; + }), + }); + } + previousHistoryMessageWasToolResult = m.role === 'tool' && !!m.toolResults?.length; + } + + if (includeCurrentUserMessage) { + if (attachments?.length) { + const modelText = buildPromptWithTerminalSelectionAttachments(trimmed, attachments); + const modelAttachments = attachments.filter( + (attachment) => !isTerminalSelectionAttachment(attachment), + ); + if (!modelAttachments.length) { + sdkMessages.push({ role: 'user', content: modelText }); + } else { + const parts: Array<{ type: 'text'; text: string } | { type: 'image'; image: string; mediaType?: string } | { type: 'file'; data: string; mediaType: string; filename?: string }> = []; + parts.push({ type: 'text', text: modelText }); + for (const att of modelAttachments) { + if (att.mediaType.startsWith('image/')) { + parts.push({ type: 'image', image: att.base64Data, mediaType: att.mediaType }); + } else { + parts.push({ type: 'file', data: att.base64Data, mediaType: att.mediaType, filename: att.filename }); + } + } + sdkMessages.push({ role: 'user', content: parts }); + } + } else { + sdkMessages.push({ role: 'user', content: trimmed }); + } + } + + for (const [message, fields] of nextFieldsByMessage.entries()) { + fieldsByMessage.set(message, fields); + } + + return sdkMessages; +} + +export function collectToolResultsAfterMessage( + messages: ChatMessage[], + messageId: string, +): Set { + const results = new Set(); + let afterMessage = false; + for (const message of messages) { + if (message.id === messageId) { + afterMessage = true; + continue; + } + if (!afterMessage || message.role !== 'tool' || !message.toolResults?.length) continue; + for (const result of message.toolResults) { + results.add(result); + } + } + return results; +} + +export function createContinuationContext( + providerConfigId: string, + providerType: string, + modelId: string, +): CattyProviderContinuationContext { + return { + source: { + providerConfigId, + providerType, + modelId, + }, + openAIChatAssistantFields: [], + }; +} + +export type { CattyProviderContinuationContext, ProviderContinuation }; diff --git a/infrastructure/ai/harness/turnDrivers/cattyStreamProcessor.ts b/infrastructure/ai/harness/turnDrivers/cattyStreamProcessor.ts new file mode 100644 index 000000000..b4032c941 --- /dev/null +++ b/infrastructure/ai/harness/turnDrivers/cattyStreamProcessor.ts @@ -0,0 +1,358 @@ +import { streamText, stepCountIs, type ModelMessage } from 'ai'; +import { classifyError } from '../../errorClassifier'; +import { isRequestTooLargeError } from '../../errorClassifier'; +import { isSdkStreamStateError } from '../../shared/streamStateErrors'; +import { + createCattyRequestTooLargeRetryError, + hadToolProgressBeforeRequestTooLarge, +} from '../../cattyRequestTooLargeRetry'; +import { mapCattyStreamChunkToAgentEvents } from '../agentEventAdapter'; +import type { AgentEvent } from '../types'; +import type { ProviderAdvancedParams } from '../../types'; +import { createModelFromConfig } from '../../sdk/providers'; +import { createCattyToolsFromCatalog } from '../capabilityTools'; +import { + extractProviderContinuationFromRawChunk, + mergeProviderContinuation, + normalizeProviderContinuationOptions, + withProviderContinuationSource, + type ProviderContinuation, +} from '../../providerContinuation'; +import { + generateId, + isToolResultError, + type CattyProviderContinuationContext, + type ErrorChunk, + type RawChunk, + type ReasoningChunk, + type StreamChunk, + type TextDeltaChunk, + type ToolCallChunk, + type ToolResultChunk, +} from '../../../../components/ai/hooks/aiChatStreamingSupport'; +import type { ChatMessage } from '../../types'; + +export type CattyModel = ReturnType; +export type CattyTools = ReturnType; + +export interface CattyStreamUiSink { + addMessageToSession: (sessionId: string, message: ChatMessage) => void; + updateMessageById: (sessionId: string, messageId: string, updater: (msg: ChatMessage) => ChatMessage) => void; +} + +export interface ProcessCattyStreamInput { + streamSessionId: string; + model: CattyModel; + systemPrompt: string; + tools: CattyTools; + sdkMessages: ModelMessage[]; + signal: AbortSignal; + currentAssistantMsgId: string; + maxIterations: number; + advancedParams?: ProviderAdvancedParams; + continuationContext?: CattyProviderContinuationContext; + turnId?: string; + onAgentEvent?: (event: AgentEvent) => void; + prepareStep?: (args: { stepNumber: number; messages: ModelMessage[] }) => Promise<{ messages: ModelMessage[] } | undefined>; + ui: CattyStreamUiSink; +} + +export async function processCattyStream(input: ProcessCattyStreamInput): Promise<{ usage?: { promptTokens?: number; completionTokens?: number; totalTokens?: number } }> { + const { + streamSessionId, + model, + systemPrompt, + tools, + sdkMessages, + signal, + currentAssistantMsgId, + maxIterations, + advancedParams, + continuationContext, + turnId, + onAgentEvent, + prepareStep, + ui, + } = input; + + const result = streamText({ + model, + messages: sdkMessages, + system: systemPrompt, + tools, + stopWhen: stepCountIs(maxIterations), + abortSignal: signal, + includeRawChunks: true, + ...(prepareStep ? { + prepareStep: async ({ stepNumber, messages }) => { + const prepared = await prepareStep({ stepNumber, messages }); + return prepared ?? { messages }; + }, + } : {}), + ...(advancedParams?.maxTokens != null && { maxOutputTokens: advancedParams.maxTokens }), + ...(advancedParams?.temperature != null && { temperature: advancedParams.temperature }), + ...(advancedParams?.topP != null && { topP: advancedParams.topP }), + ...(advancedParams?.frequencyPenalty != null && { frequencyPenalty: advancedParams.frequencyPenalty }), + ...(advancedParams?.presencePenalty != null && { presencePenalty: advancedParams.presencePenalty }), + }); + + let activeMsgId = currentAssistantMsgId; + let lastAddedRole: 'assistant' | 'tool' = 'assistant'; + let hadToolProgress = false; + const reader = result.fullStream.getReader(); + + let pendingText = ''; + let rafId: number | null = null; + + const ensureAssistantMessage = (): string => { + if (lastAddedRole !== 'tool') return activeMsgId; + const newId = generateId(); + ui.addMessageToSession(streamSessionId, { + id: newId, + role: 'assistant', + content: '', + timestamp: Date.now(), + }); + activeMsgId = newId; + lastAddedRole = 'assistant'; + return activeMsgId; + }; + + const updateAssistantContinuation = ( + messageId: string, + continuation: ProviderContinuation | undefined, + thinkingText = '', + ) => { + if (!continuation && !thinkingText) return; + const sourcedContinuation = withProviderContinuationSource(continuation, continuationContext?.source); + ui.updateMessageById(streamSessionId, messageId, msg => { + const providerContinuation = mergeProviderContinuation(msg.providerContinuation, sourcedContinuation); + return { + ...msg, + ...(providerContinuation ? { providerContinuation } : {}), + ...(thinkingText ? { thinking: (msg.thinking || '') + thinkingText } : {}), + }; + }); + }; + + const getOpenAIReasoningText = (continuation: ProviderContinuation | undefined): string => { + const reasoningContent = continuation?.openAIChatAssistantFields?.reasoning_content; + return typeof reasoningContent === 'string' ? reasoningContent : ''; + }; + + const flushText = () => { + if (pendingText) { + const text = pendingText; + pendingText = ''; + if (lastAddedRole === 'tool') { + const newId = generateId(); + ui.addMessageToSession(streamSessionId, { + id: newId, + role: 'assistant', + content: text, + timestamp: Date.now(), + }); + activeMsgId = newId; + lastAddedRole = 'assistant'; + } else { + ui.updateMessageById(streamSessionId, activeMsgId, msg => ({ + ...msg, + content: msg.content + text, + })); + } + } + rafId = null; + }; + + const cancelPendingFlush = () => { + if (rafId !== null) { + cancelAnimationFrame(rafId); + rafId = null; + } + }; + + try { + while (true) { + let readResult: ReadableStreamReadResult; + try { + readResult = await reader.read(); + } catch (readErr) { + if (isRequestTooLargeError(readErr)) { + throw createCattyRequestTooLargeRetryError(readErr, hadToolProgress); + } + throw readErr; + } + const { done, value } = readResult; + if (done) break; + const chunk = value as StreamChunk; + for (const agentEvent of mapCattyStreamChunkToAgentEvents(chunk, { + sessionId: streamSessionId, + chatSessionId: streamSessionId, + turnId, + })) { + onAgentEvent?.(agentEvent); + } + switch (chunk.type) { + case 'text': + case 'text-delta': { + const typedChunk = chunk as TextDeltaChunk; + const text = typedChunk.text ?? typedChunk.textDelta; + const providerOptions = normalizeProviderContinuationOptions(typedChunk.providerMetadata); + if (providerOptions) { + const messageId = ensureAssistantMessage(); + updateAssistantContinuation(messageId, { textProviderOptions: providerOptions }); + } + if (text) { + pendingText += text; + if (rafId === null) { + rafId = requestAnimationFrame(flushText); + } + } + break; + } + case 'reasoning': + case 'reasoning-start': + case 'reasoning-delta': { + cancelPendingFlush(); + flushText(); + const typedChunk = chunk as ReasoningChunk; + const rText = typedChunk.text ?? typedChunk.textDelta ?? typedChunk.delta ?? ''; + const providerOptions = normalizeProviderContinuationOptions(typedChunk.providerMetadata); + const continuation = rText || providerOptions + ? { + reasoningParts: [{ + text: rText, + ...(providerOptions ? { providerOptions } : {}), + }], + } satisfies ProviderContinuation + : undefined; + if (continuation || rText) { + const messageId = ensureAssistantMessage(); + updateAssistantContinuation(messageId, continuation, rText); + } + break; + } + case 'raw': { + const typedChunk = chunk as RawChunk; + const continuation = extractProviderContinuationFromRawChunk(typedChunk.rawValue); + if (continuation) { + cancelPendingFlush(); + flushText(); + const messageId = ensureAssistantMessage(); + updateAssistantContinuation(messageId, continuation, getOpenAIReasoningText(continuation)); + } + break; + } + case 'reasoning-end': + case 'text-start': + case 'text-end': + case 'start': + case 'finish': + case 'start-step': + case 'finish-step': + break; + case 'tool-call': { + cancelPendingFlush(); + flushText(); + const typedChunk = chunk as ToolCallChunk; + hadToolProgress = true; + const messageId = ensureAssistantMessage(); + const providerOptions = normalizeProviderContinuationOptions(typedChunk.providerMetadata); + ui.updateMessageById(streamSessionId, messageId, msg => ({ + ...msg, + toolCalls: [...(msg.toolCalls || []), { + id: typedChunk.toolCallId, + name: typedChunk.toolName, + arguments: (typedChunk.input ?? typedChunk.args) as Record, + }], + executionStatus: 'running', + statusText: undefined, + })); + if (providerOptions) { + updateAssistantContinuation(messageId, { + toolCallProviderOptionsById: { + [typedChunk.toolCallId]: providerOptions, + }, + }); + } + break; + } + case 'tool-result': { + cancelPendingFlush(); + flushText(); + const typedChunk = chunk as ToolResultChunk; + hadToolProgress = true; + ui.updateMessageById(streamSessionId, activeMsgId, msg => + msg.role === 'assistant' && msg.executionStatus === 'running' + ? { ...msg, executionStatus: 'completed', statusText: undefined } : msg, + ); + const toolOutput = typedChunk.output ?? typedChunk.result; + const toolError = isToolResultError(toolOutput); + ui.addMessageToSession(streamSessionId, { + id: generateId(), + role: 'tool', + content: '', + toolResults: [{ + toolCallId: typedChunk.toolCallId, + content: typeof toolOutput === 'string' + ? toolOutput + : JSON.stringify(toolOutput), + isError: toolError, + }], + timestamp: Date.now(), + executionStatus: 'completed', + }); + lastAddedRole = 'tool'; + break; + } + case 'error': { + const typedChunk = chunk as ErrorChunk; + if (isSdkStreamStateError(typedChunk.error)) { + console.warn('[Catty] suppressed SDK stream state error:', typedChunk.error); + break; + } + if (isRequestTooLargeError(typedChunk.error)) { + cancelPendingFlush(); + flushText(); + throw createCattyRequestTooLargeRetryError( + typedChunk.error, + hadToolProgress, + ); + } + cancelPendingFlush(); + flushText(); + ui.updateMessageById(streamSessionId, activeMsgId, msg => ({ + ...msg, + statusText: '', + executionStatus: msg.executionStatus === 'running' ? 'failed' : msg.executionStatus, + })); + ui.addMessageToSession(streamSessionId, { + id: generateId(), + role: 'assistant', + content: '', + errorInfo: classifyError(typedChunk.error), + timestamp: Date.now(), + }); + break; + } + default: + break; + } + } + } finally { + cancelPendingFlush(); + flushText(); + reader.releaseLock(); + } + + const usage = await result.usage; + return { + usage: usage ? { + promptTokens: usage.inputTokens, + completionTokens: usage.outputTokens, + totalTokens: (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0), + } : undefined, + }; +} + +export { hadToolProgressBeforeRequestTooLarge }; diff --git a/infrastructure/ai/harness/turnDrivers/cattyTurnDriver.ts b/infrastructure/ai/harness/turnDrivers/cattyTurnDriver.ts new file mode 100644 index 000000000..549b6f349 --- /dev/null +++ b/infrastructure/ai/harness/turnDrivers/cattyTurnDriver.ts @@ -0,0 +1,318 @@ +import type { ModelMessage } from 'ai'; +import type { OpenAIChatAssistantFields } from '../../providerContinuation'; +import { + DEFAULT_CONTEXT_WINDOW_TOKENS, + estimateUnknownTokens, + resolveContextWindow, +} from '../../contextCompaction'; +import { buildSystemPrompt } from '../../cattyAgent/systemPrompt'; +import { isWebSearchReady } from '../../types'; +import { createModelFromConfig } from '../../sdk/providers'; +import { createCattyToolsFromCatalog } from '../capabilityTools'; +import { + compactCattyMessages, + prepareCattyMessagesForStream, +} from '../cattyRuntime'; +import { clearChatSessionCancelled } from '../agentStop'; +import { prepareStepContext } from '../contextManager'; +import { isRequestTooLargeError } from '../../errorClassifier'; +import { getNetcattyBridge, generateId, resolveUserSkillsContext } from '../../../../components/ai/hooks/aiChatStreamingSupport'; +import { + buildCattySdkMessages, + collectOpenAIChatAssistantFieldsForMessages, + collectToolResultsAfterMessage, + createContinuationContext, +} from './cattyMessageBuilder'; +import { hadToolProgressBeforeRequestTooLarge, processCattyStream } from './cattyStreamProcessor'; +import type { CattyTurnInput, TurnDriver, TurnDriverContext } from './types'; + +export class CattyTurnDriver implements TurnDriver { + readonly backend = 'catty' as const; + + async run(input: import('./types').TurnInput, ctx: TurnDriverContext): Promise { + if (input.backend !== 'catty') { + throw new Error('CattyTurnDriver received non-catty input'); + } + await runCattyTurn(input, ctx); + } + + abort(): void { + // Abort is handled via AbortSignal on the turn input. + } +} + +async function runCattyTurn(input: CattyTurnInput, ctx: TurnDriverContext): Promise { + const { + chatSessionId: sessionId, + sendScopeKey, + userText: trimmed, + signal, + currentSession, + assistantMsgId, + context, + attachments, + maxIterations, + bridge, + ui, + } = input; + + const netcattyBridge = bridge ?? getNetcattyBridge(); + await clearChatSessionCancelled(sessionId, netcattyBridge); + if (netcattyBridge.aiMcpUpdateSessions) { + await netcattyBridge.aiMcpUpdateSessions(context.terminalSessions, sessionId); + } + const userSkillsContext = await resolveUserSkillsContext( + netcattyBridge, + trimmed, + context.selectedUserSkillSlugs, + ); + const getExecutorContext = context.getExecutorContext ?? (() => ({ + sessions: context.terminalSessions, + workspaceId: context.scopeType === 'workspace' ? context.scopeTargetId : undefined, + workspaceName: context.scopeType === 'workspace' ? context.scopeLabel : undefined, + })); + const tools = createCattyToolsFromCatalog( + netcattyBridge, + getExecutorContext, + context.commandBlocklist, + context.globalPermissionMode, + context.webSearchConfig ?? undefined, + sessionId, + ctx.toolOutputStore, + ctx.toolResultDedup, + ); + + const systemPrompt = buildSystemPrompt({ + scopeType: context.scopeType, + scopeLabel: context.scopeLabel, + hosts: context.terminalSessions, + permissionMode: context.globalPermissionMode, + webSearchEnabled: isWebSearchReady(context.webSearchConfig), + userSkillsContext, + }); + + if (!context.activeProvider) { + ui.reportStreamError(sessionId, signal, 'No AI provider configured. Please configure a provider in Settings → AI.'); + return; + } + + const activeModelId = context.activeModelId || context.activeProvider.defaultModel || ''; + const continuationContext = createContinuationContext( + context.activeProvider.id, + context.activeProvider.providerId, + activeModelId, + ); + + ui.setStreamingForScope(sessionId, true); + + try { + const openAIChatAssistantFieldsByMessage = new Map(); + + const buildSdkMessages = ( + allMessages: import('../../types').ChatMessage[], + includeCurrentUserMessage: boolean, + options: { preserveTerminalToolResults?: ReadonlySet } = {}, + ) => buildCattySdkMessages({ + allMessages, + includeCurrentUserMessage, + trimmed, + attachments: includeCurrentUserMessage ? attachments : undefined, + continuationContext, + preserveTerminalToolResults: options.preserveTerminalToolResults, + fieldsByMessage: openAIChatAssistantFieldsByMessage, + }); + + let model; + try { + model = createModelFromConfig( + { + ...context.activeProvider, + defaultModel: activeModelId, + }, + { + getOpenAIChatAssistantFields: () => continuationContext.openAIChatAssistantFields, + }, + ); + } catch (e) { + console.error('[Catty] Model creation failed:', e); + ui.reportStreamError(sessionId, signal, `Model creation failed: ${e instanceof Error ? e.message : String(e)}`); + return; + } + + const contextWindow = resolveContextWindow({ + provider: context.activeProvider, + modelId: activeModelId, + defaultContextWindow: DEFAULT_CONTEXT_WINDOW_TOKENS, + }); + const outputReserveTokens = Math.min(4096, Math.ceil(contextWindow * 0.05)); + const getRequestReserveTokens = () => outputReserveTokens + estimateUnknownTokens({ + systemPrompt, + toolNames: Object.keys(tools), + openAIChatAssistantFields: Array.from(openAIChatAssistantFieldsByMessage.values()), + }); + + const prepareMessagesForStream = (messages: ModelMessage[]): ModelMessage[] => { + const pruned = prepareCattyMessagesForStream(messages); + continuationContext.openAIChatAssistantFields = collectOpenAIChatAssistantFieldsForMessages( + pruned, + openAIChatAssistantFieldsByMessage, + ); + return pruned; + }; + + const compactMessages = async ( + messages: ModelMessage[], + options: { + force?: boolean; + statusText?: string; + compressForRequestTooLargeRetry?: boolean; + }, + ): Promise => { + const pendingHandles = ctx.toolOutputStore.listPendingHandles(sessionId); + const result = await compactCattyMessages({ + messages, + sessionId, + chatSessionId: sessionId, + provider: context.activeProvider, + modelId: activeModelId || context.activeProvider?.defaultModel, + reservedTokens: getRequestReserveTokens, + model, + abortSignal: signal, + trigger: options.force ? 'force' : options.compressForRequestTooLargeRetry ? '413-retry' : 'pre-turn', + force: options.force, + compressForRequestTooLargeRetry: options.compressForRequestTooLargeRetry, + onStatusText: (text) => { + ui.updateLastMessage(sessionId, msg => ({ ...msg, statusText: options.statusText || text })); + }, + onCompaction: (trace) => { + ctx.emit({ + id: `compaction-${Date.now()}`, + type: 'compaction', + trace, + } as import('../types').AgentEvent); + if (options.compressForRequestTooLargeRetry && trace.did413Fallback) { + console.warn('[Catty] Request content compressed after forced context compaction.'); + } + }, + reinjection: { + permissionMode: context.permissionMode ?? context.globalPermissionMode, + sessionScopeSummary: pendingHandles.length + ? `Pending tool output handles: ${pendingHandles.map(h => h.id).join(', ')}` + : undefined, + }, + }); + return result.messages; + }; + + let messagesForStream = buildSdkMessages(currentSession?.messages ?? [], true); + messagesForStream = await compactMessages(messagesForStream, {}); + messagesForStream = prepareMessagesForStream(messagesForStream); + + const runStream = async (streamMessages: ModelMessage[], streamAssistantMsgId: string) => { + const { usage } = await processCattyStream({ + streamSessionId: sessionId, + model, + systemPrompt, + tools, + sdkMessages: streamMessages, + signal, + currentAssistantMsgId: streamAssistantMsgId, + maxIterations, + advancedParams: context.activeProvider?.advancedParams, + continuationContext, + turnId: ctx.turnId, + onAgentEvent: (event) => ctx.emit(event), + prepareStep: async ({ stepNumber, messages }) => { + const prepared = await prepareStepContext({ + messages, + stepNumber, + sessionId, + chatSessionId: sessionId, + providerId: context.activeProvider?.providerId, + modelId: activeModelId, + toolOutputStore: ctx.toolOutputStore, + }); + return { messages: prepared.messages }; + }, + ui: { + addMessageToSession: ui.addMessageToSession, + updateMessageById: ui.updateMessageById, + }, + }); + + if (usage?.totalTokens) { + ctx.emit({ + id: `usage-${ctx.turnId}`, + type: 'usage', + promptTokens: usage.promptTokens ?? 0, + completionTokens: usage.completionTokens ?? 0, + totalTokens: usage.totalTokens, + estimated: false, + } as import('../types').AgentEvent); + } + }; + + try { + await runStream(messagesForStream, assistantMsgId); + } catch (streamErr) { + if (signal.aborted || !isRequestTooLargeError(streamErr)) { + throw streamErr; + } + + console.warn('[Catty] Request hit HTTP 413; forcing context compaction and retrying once.', streamErr); + const statusText = 'Request was too large. Compacting context and retrying...'; + const hadToolProgress = hadToolProgressBeforeRequestTooLarge(streamErr); + let retryBaseMessages = messagesForStream; + let retryAssistantMsgId = assistantMsgId; + if (hadToolProgress) { + const latestSession = ui.getLatestSession?.(sessionId); + if (latestSession) { + retryBaseMessages = buildSdkMessages(latestSession.messages, false, { + preserveTerminalToolResults: collectToolResultsAfterMessage( + latestSession.messages, + assistantMsgId, + ), + }); + } + retryAssistantMsgId = generateId(); + ui.addMessageToSession(sessionId, { + id: retryAssistantMsgId, + role: 'assistant', + content: '', + timestamp: Date.now(), + model: activeModelId || context.activeProvider?.defaultModel || '', + providerId: context.activeProvider?.providerId, + statusText, + }); + } else { + ui.updateMessageById(sessionId, assistantMsgId, msg => ({ + ...msg, + content: '', + thinking: undefined, + thinkingDurationMs: undefined, + providerContinuation: undefined, + toolCalls: undefined, + errorInfo: undefined, + executionStatus: undefined, + pendingApproval: undefined, + statusText, + })); + } + const retryMessages = prepareMessagesForStream(await compactMessages(retryBaseMessages, { + force: true, + statusText, + compressForRequestTooLargeRetry: true, + })); + await runStream(retryMessages, retryAssistantMsgId); + } + } catch (err) { + console.error('[Catty] streamText error:', err); + ui.reportStreamError(sessionId, signal, err); + } finally { + ui.updateLastMessage(sessionId, msg => msg.statusText ? { ...msg, statusText: '' } : msg); + ui.setStreamingForScope(sessionId, false); + context.autoTitleSession(sessionId, context.titleText ?? trimmed); + } +} + +export const cattyTurnDriver = new CattyTurnDriver(); diff --git a/infrastructure/ai/harness/turnDrivers/externalSdkTurnDriver.ts b/infrastructure/ai/harness/turnDrivers/externalSdkTurnDriver.ts new file mode 100644 index 000000000..66ac0a799 --- /dev/null +++ b/infrastructure/ai/harness/turnDrivers/externalSdkTurnDriver.ts @@ -0,0 +1,174 @@ +import { getExternalAgentSdkBackend } from '../../managedAgents'; +import { runSdkAgentTurn, type SdkAgentCallbacks } from '../../sdkAgentAdapter'; +import { getNetcattyBridge, generateId, resolveUserSkillsContext, isToolResultError } from '../../../../components/ai/hooks/aiChatStreamingSupport'; +import type { ExternalTurnInput, TurnDriver, TurnDriverContext } from './types'; + +export class ExternalSdkTurnDriver implements TurnDriver { + readonly backend = 'external-sdk' as const; + + async run(input: import('./types').TurnInput, ctx: TurnDriverContext): Promise { + if (input.backend !== 'external-sdk') { + throw new Error('ExternalSdkTurnDriver received non-external input'); + } + await runExternalTurn(input, ctx); + } + + abort(): void { + // Abort is handled via AbortSignal on the turn input. + } +} + +async function runExternalTurn(input: ExternalTurnInput, ctx: TurnDriverContext): Promise { + const { + chatSessionId: sessionId, + userText: trimmed, + signal, + agentConfig, + attachedImages, + context, + bridge, + ui, + } = input; + + const netcattyBridge = bridge ?? getNetcattyBridge(); + const sdkBackend = getExternalAgentSdkBackend(agentConfig); + + if (!sdkBackend || !netcattyBridge) { + ui.reportStreamError( + sessionId, + signal, + 'This agent has no SDK backend configured. Re-discover it in Settings -> AI.', + ); + ui.setStreamingForScope(sessionId, false); + return; + } + + const userSkillsContext = await resolveUserSkillsContext( + netcattyBridge, + trimmed, + context.selectedUserSkillSlugs, + ); + + const requestId = ctx.turnId; + ui.setStreamingForScope(sessionId, true); + + if (netcattyBridge.aiMcpUpdateSessions) { + await netcattyBridge.aiMcpUpdateSessions(context.terminalSessions, sessionId); + } + + let needsNewAssistantMsg = false; + const maybeCreateAssistantMsg = () => { + if (needsNewAssistantMsg) { + needsNewAssistantMsg = false; + ui.addMessageToSession(sessionId, { + id: generateId(), + role: 'assistant', + content: '', + timestamp: Date.now(), + model: agentConfig.name || 'external', + }); + } + }; + + const callbacks: SdkAgentCallbacks = { + onTextDelta: (text: string) => { + maybeCreateAssistantMsg(); + ui.updateLastMessage(sessionId, msg => ({ + ...msg, + content: msg.content + text, + statusText: undefined, + thinkingDurationMs: msg.thinking && !msg.thinkingDurationMs + ? Date.now() - msg.timestamp : msg.thinkingDurationMs, + })); + }, + onThinkingDelta: (text: string) => { + maybeCreateAssistantMsg(); + ui.updateLastMessage(sessionId, msg => ({ + ...msg, + thinking: (msg.thinking || '') + text, + })); + }, + onThinkingDone: () => { + ui.updateLastMessage(sessionId, msg => ({ + ...msg, + thinkingDurationMs: msg.thinkingDurationMs || (Date.now() - msg.timestamp), + })); + }, + onToolCall: (toolName: string, args: Record, toolCallId?: string) => { + maybeCreateAssistantMsg(); + ui.updateLastMessage(sessionId, msg => ({ + ...msg, + toolCalls: [...(msg.toolCalls || []), { id: toolCallId || `tc_${Date.now()}`, name: toolName, arguments: args }], + executionStatus: 'running', + statusText: undefined, + })); + }, + onToolResult: (toolCallId: string, result: string, toolName?: string) => { + ui.updateLastMessage(sessionId, msg => { + if (msg.role !== 'assistant' || msg.executionStatus !== 'running') return msg; + const updatedToolCalls = toolName && !toolName.includes('sdk_agent_dynamic_tool') && msg.toolCalls + ? msg.toolCalls.map(tc => tc.id === toolCallId && !tc.name ? { ...tc, name: toolName } : tc) + : msg.toolCalls; + return { ...msg, toolCalls: updatedToolCalls, executionStatus: 'completed', statusText: undefined }; + }); + ui.addMessageToSession(sessionId, { + id: generateId(), + role: 'tool', + content: '', + toolResults: [{ toolCallId, content: result, isError: isToolResultError(result) }], + timestamp: Date.now(), + executionStatus: 'completed', + }); + needsNewAssistantMsg = true; + }, + onStatus: (message: string) => { + maybeCreateAssistantMsg(); + ui.updateLastMessage(sessionId, msg => ({ ...msg, statusText: message })); + }, + onSessionId: (externalSessionId: string) => { + context.updateExternalSessionId?.(sessionId, externalSessionId); + }, + onError: (error: string) => { + ui.reportStreamError(sessionId, signal, error); + ui.setStreamingForScope(sessionId, false); + }, + onDone: () => {}, + }; + + try { + await runSdkAgentTurn( + netcattyBridge, + requestId, + sessionId, + agentConfig, + trimmed, + callbacks, + signal, + undefined, + context.selectedAgentModel, + context.existingSessionId, + context.historyMessages, + attachedImages.length > 0 ? attachedImages : undefined, + context.toolIntegrationMode, + context.defaultTargetSession, + userSkillsContext, + { + traceSink: (event) => ctx.emit(event), + skipHarnessTrace: true, + }, + ); + + ctx.emit({ + id: `usage-${ctx.turnId}`, + type: 'usage', + promptTokens: 0, + completionTokens: 0, + totalTokens: Math.ceil(trimmed.length / 4), + estimated: true, + } as import('../types').AgentEvent); + } finally { + ui.setStreamingForScope(sessionId, false); + } +} + +export const externalSdkTurnDriver = new ExternalSdkTurnDriver(); diff --git a/infrastructure/ai/harness/turnDrivers/types.ts b/infrastructure/ai/harness/turnDrivers/types.ts new file mode 100644 index 000000000..ba160c9b3 --- /dev/null +++ b/infrastructure/ai/harness/turnDrivers/types.ts @@ -0,0 +1,139 @@ +import type { ModelMessage } from 'ai'; +import type { + AIPermissionMode, + AIToolIntegrationMode, + AISession, + ChatMessage, + ChatMessageAttachment, + ExternalAgentConfig, + ProviderAdvancedParams, + ProviderConfig, + WebSearchConfig, +} from '../../types'; +import type { ExecutorContext } from '../../cattyAgent/executor'; +import type { AgentBackend, AgentEvent, AgentEventListener } from '../types'; +import type { ToolOutputStore } from '../toolOutputStore'; +import type { ToolResultDedup } from '../toolResultDedup'; +import type { DefaultTargetSessionHint } from '../../sdkAgentAdapter'; +import type { AgentStopBridge } from '../agentStop'; + +export interface TerminalSessionInfo { + sessionId: string; + hostId?: string; + hostname: string; + label: string; + os?: string; + username?: string; + protocol?: string; + shellType?: string; + deviceType?: string; + connected: boolean; + hostChain?: Array<{ hostId: string; label?: string; hostname?: string }>; + activePortForwards?: Array<{ + ruleId: string; + label?: string; + type?: string; + localPort?: number; + status?: string; + }>; +} + +export interface TurnUiCallbacks { + addMessageToSession: (sessionId: string, message: ChatMessage) => void; + updateLastMessage: (sessionId: string, updater: (msg: ChatMessage) => ChatMessage) => void; + updateMessageById: (sessionId: string, messageId: string, updater: (msg: ChatMessage) => ChatMessage) => void; + reportStreamError: (sessionId: string, abortSignal: AbortSignal, err: unknown) => void; + setStreamingForScope: (key: string, val: boolean) => void; + getLatestSession?: (sessionId: string) => AISession | undefined; +} + +export interface CattyTurnContext { + activeProvider: ProviderConfig | undefined; + activeModelId: string; + scopeType: 'terminal' | 'workspace'; + scopeTargetId?: string; + scopeLabel?: string; + globalPermissionMode: AIPermissionMode; + permissionMode?: AIPermissionMode; + commandBlocklist?: string[]; + terminalSessions: TerminalSessionInfo[]; + webSearchConfig?: WebSearchConfig | null; + getExecutorContext?: () => ExecutorContext; + autoTitleSession: (sessionId: string, text: string) => void; + titleText?: string; + selectedUserSkillSlugs?: string[]; +} + +export interface ExternalTurnContext { + existingSessionId?: string; + updateExternalSessionId?: (sessionId: string, externalSessionId: string | undefined) => void; + historyMessages?: Array<{ role: 'user' | 'assistant'; content: string }>; + terminalSessions: TerminalSessionInfo[]; + defaultTargetSession?: DefaultTargetSessionHint; + providers: ProviderConfig[]; + selectedAgentModel?: string; + toolIntegrationMode: AIToolIntegrationMode; + selectedUserSkillSlugs?: string[]; +} + +export interface CattyTurnInput { + backend: 'catty'; + chatSessionId: string; + sendScopeKey: string; + userText: string; + signal: AbortSignal; + currentSession: AISession | undefined; + assistantMsgId: string; + context: CattyTurnContext; + attachments?: ChatMessageAttachment[]; + maxIterations: number; + bridge?: AgentStopBridge | null; + ui: TurnUiCallbacks; +} + +export interface ExternalTurnInput { + backend: 'external-sdk'; + chatSessionId: string; + userText: string; + signal: AbortSignal; + agentConfig: ExternalAgentConfig; + attachedImages: Array<{ base64Data: string; mediaType: string; filename?: string; filePath?: string }>; + context: ExternalTurnContext; + bridge?: Record unknown> | null; + ui: TurnUiCallbacks; +} + +export type TurnInput = CattyTurnInput | ExternalTurnInput; + +export interface TurnResult { + turnId: string; + reason: 'completed' | 'aborted' | 'error'; +} + +export interface TurnDriverContext { + turnId: string; + chatSessionId: string; + sessionId: string; + backend: AgentBackend; + signal: AbortSignal; + emit: (event: Omit & Partial>) => void; + toolOutputStore: ToolOutputStore; + toolResultDedup: ToolResultDedup; + onEvent?: AgentEventListener; +} + +export interface TurnDriver { + readonly backend: AgentBackend; + run(input: TurnInput, ctx: TurnDriverContext): Promise; + abort?(chatSessionId: string): void; +} + +export interface PrepareStepContextInput { + messages: ModelMessage[]; + stepNumber: number; + sessionId: string; + chatSessionId?: string; + providerId?: string | null; + modelId?: string | null; + toolOutputStore?: ToolOutputStore; +} diff --git a/infrastructure/ai/harness/types.ts b/infrastructure/ai/harness/types.ts new file mode 100644 index 000000000..abedfad36 --- /dev/null +++ b/infrastructure/ai/harness/types.ts @@ -0,0 +1,145 @@ +/** + * Unified agent harness event protocol. + * Catty (Vercel AI SDK) and external SDK drivers emit the same shapes. + */ + +export type AgentEventType = + | 'turn_start' + | 'model_delta' + | 'reasoning_delta' + | 'tool_call' + | 'tool_result' + | 'approval_requested' + | 'approval_resolved' + | 'compaction' + | 'usage' + | 'error' + | 'turn_end'; + +export type AgentBackend = 'catty' | 'external-sdk'; + +export type ApprovalOutcome = 'approved' | 'denied' | 'timeout'; + +export type ContextPrepareTrigger = 'pre-turn' | '413-retry' | 'force'; + +export interface AgentEventBase { + id: string; + sessionId: string; + chatSessionId?: string; + backend: AgentBackend; + timestamp: number; + turnId?: string; +} + +export interface TurnStartEvent extends AgentEventBase { + type: 'turn_start'; + backendLabel?: string; +} + +export interface ModelDeltaEvent extends AgentEventBase { + type: 'model_delta'; + text: string; +} + +export interface ReasoningDeltaEvent extends AgentEventBase { + type: 'reasoning_delta'; + text: string; +} + +export interface ToolCallEvent extends AgentEventBase { + type: 'tool_call'; + toolCallId: string; + toolName: string; + args: Record; +} + +export interface ToolResultEvent extends AgentEventBase { + type: 'tool_result'; + toolCallId: string; + toolName?: string; + result: string; + isError?: boolean; +} + +export interface ApprovalRequestedEvent extends AgentEventBase { + type: 'approval_requested'; + toolCallId: string; + toolName: string; + args: Record; +} + +export interface ApprovalResolvedEvent extends AgentEventBase { + type: 'approval_resolved'; + toolCallId: string; + toolName: string; + outcome: ApprovalOutcome; + persistedGrantId?: string; +} + +export type TokenEstimatorKind = 'chars-div-4' | 'openai-heuristic' | 'anthropic-heuristic' | 'google-heuristic'; + +export interface CompactionTrace { + trigger: ContextPrepareTrigger; + estimatedTokensBefore: number; + estimatedTokensAfter: number; + messagesBefore: number; + messagesAfter: number; + compressedMessageCount: number; + retainedTailCount: number; + summaryLength?: number; + didTypedCompression: boolean; + didLlmSummarize: boolean; + did413Fallback: boolean; + estimatorKind?: TokenEstimatorKind; +} + +export interface CompactionEvent extends AgentEventBase { + type: 'compaction'; + trace: CompactionTrace; +} + +export interface ErrorEvent extends AgentEventBase { + type: 'error'; + message: string; + code?: string; + recoverable?: boolean; +} + +export interface UsageEvent extends AgentEventBase { + type: 'usage'; + promptTokens: number; + completionTokens: number; + totalTokens: number; + estimated?: boolean; +} + +export interface TurnEndEvent extends AgentEventBase { + type: 'turn_end'; + reason?: 'completed' | 'aborted' | 'error'; +} + +export type AgentEvent = + | TurnStartEvent + | ModelDeltaEvent + | ReasoningDeltaEvent + | ToolCallEvent + | ToolResultEvent + | ApprovalRequestedEvent + | ApprovalResolvedEvent + | CompactionEvent + | UsageEvent + | ErrorEvent + | TurnEndEvent; + +export type AgentEventListener = (event: AgentEvent) => void; + +export interface ContextPrepareResult { + messages: import('ai').ModelMessage[]; + didAdjust: boolean; + trace?: CompactionTrace; +} + +export interface ExternalBridgeHistoryMessage { + role: 'user' | 'assistant'; + content: string; +} diff --git a/infrastructure/ai/managedAgents.ts b/infrastructure/ai/managedAgents.ts index b0f78ad93..0dda10e84 100644 --- a/infrastructure/ai/managedAgents.ts +++ b/infrastructure/ai/managedAgents.ts @@ -1,4 +1,7 @@ import type { DiscoveredAgent, ExternalAgentConfig } from './types'; +import { getCommandBasename, isPathLikeCommand } from './shared/pathLikeCommand'; + +export { isPathLikeCommand, getCommandBasename }; export type ManagedAgentKey = 'codex' | 'claude' | 'copilot' | 'cursor' | 'codebuddy' | 'opencode'; @@ -11,18 +14,6 @@ const MANAGED_AGENT_META: Record | null | undefined, +): string | undefined { + const command = String(config?.command || '').trim(); + return config?.commandSource === 'manual' && command ? command : undefined; +} diff --git a/infrastructure/ai/quickMessages.ts b/infrastructure/ai/quickMessages.ts index 1c6153da0..10a6ba286 100644 --- a/infrastructure/ai/quickMessages.ts +++ b/infrastructure/ai/quickMessages.ts @@ -150,3 +150,16 @@ export function getSlashCommandItemId(item: SlashCommandItem): string { export function createQuickMessageId(): string { return `qm_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; } + +/** Built-in slash commands — not stored in user quick messages. */ +export const SYSTEM_BUILTIN_SLASH_COMMANDS = { + stop: { + slug: 'stop', + descriptionKey: 'ai.chat.slashStopDesc', + }, +} as const; + +export function isSystemStopSlashCommand(input: string): boolean { + const trimmed = input.trim(); + return /^\/stop(?:\s|$)/i.test(trimmed) || trimmed.toLowerCase() === '/stop'; +} diff --git a/infrastructure/ai/sdk/tools.ts b/infrastructure/ai/sdk/tools.ts index 36d34c2cc..7e1172a2a 100644 --- a/infrastructure/ai/sdk/tools.ts +++ b/infrastructure/ai/sdk/tools.ts @@ -1,194 +1,6 @@ -import { tool } from 'ai'; -import { z } from 'zod'; -import type { NetcattyBridge } from '../cattyAgent/executor'; -import type { AIPermissionMode } from '../types'; -import type { WebSearchConfig } from '../types'; -import { isWebSearchReady } from '../types'; -import { - executeTerminalExecute, - executeWorkspaceGetInfo, - executeWorkspaceGetSessionInfo, - executeWebSearch, - executeUrlFetch, - type ToolDeps, - type ToolExecResult, -} from '../shared/toolExecutors'; -import { requestApproval } from '../shared/approvalGate'; -import { reserveSessionSlot } from '../shared/sessionExecutionQueue'; -import { truncateTextWithHeadAndTail } from '../requestPayloadCompression'; +import { createCattyToolsFromCatalog, fitTerminalExecuteResultForModel } from '../harness'; -const MAX_LIVE_TERMINAL_STDOUT_CHARS = 24_000; -const MAX_LIVE_TERMINAL_STDERR_CHARS = 12_000; +export { fitTerminalExecuteResultForModel }; -/** Unwrap a shared ToolExecResult into the shape expected by Vercel AI SDK tool results. */ -function unwrap(r: ToolExecResult): T | { error: string } { - if (r.ok === false) return { error: r.error }; - return r.data; -} - -export function fitTerminalExecuteResultForModel(result: { - stdout: string; - stderr: string; - exitCode: number | null; -}): { stdout: string; stderr: string; exitCode: number | null } { - return { - ...result, - stdout: truncateTextWithHeadAndTail(result.stdout, MAX_LIVE_TERMINAL_STDOUT_CHARS), - stderr: truncateTextWithHeadAndTail(result.stderr, MAX_LIVE_TERMINAL_STDERR_CHARS), - }; -} - -/** - * Create Catty Agent tools using the Vercel AI SDK `tool()` helper with zod schemas. - * - * @param bridge - The Electron IPC bridge for executing operations - * @param context - Workspace/session context available to the agent - * @param commandBlocklist - Optional command blocklist patterns for safety checks - * @param permissionMode - Permission mode for tool execution gating - */ -export function createCattyTools( - bridge: NetcattyBridge, - context: ToolDeps['context'], - commandBlocklist?: string[], - permissionMode: AIPermissionMode = 'confirm', - webSearchConfig?: WebSearchConfig, - chatSessionId?: string, -) { - const deps: ToolDeps = { bridge, context, commandBlocklist, permissionMode, webSearchConfig, chatSessionId }; - - return { - terminal_execute: tool({ - description: - 'Execute a shell command on the specified terminal session. ' + - "The command runs in the session's shell and output is returned when complete.", - inputSchema: z.object({ - sessionId: z.string().describe('The terminal session ID to execute the command on.'), - command: z.string().describe('The shell command to execute in the target session.'), - }), - // No needsApproval — approval is handled inside execute via the approval gate. - execute: async ({ sessionId, command }, { toolCallId, abortSignal }) => { - // Snap our place in the per-session execution queue *first*, - // synchronously, so the eventual command-run order matches the - // LLM's tool_use emission order regardless of how long each - // call's approval prompt takes to settle. Vercel AI SDK - // dispatches every tool_use block in a turn through - // `Promise.all(...)`, so the three executes for "A then B then - // C" all start at the same instant; if we deferred slot - // reservation until after approval, B's approval could land - // first and run B before A. Reserving up front fixes that. - // - // The bridge-side mutex (mcpServerBridge.reserveSessionExecution) - // stays as defense-in-depth for non-LLM IPC paths - // (terminal_start, MCP, etc.) — this queue just keeps the - // renderer-side LLM path from racing into it. - const queueKey = `${chatSessionId ?? 'global'}:${sessionId}`; - const slot = reserveSessionSlot(queueKey); - try { - // In confirm mode, await user approval. Approvals run *while* - // the slot is held but before the serialized work, so multiple - // parallel tool_use blocks each surface their own approval - // card immediately and the user can approve/deny in any - // order — the queue still drains in reservation order. - if (permissionMode === 'confirm') { - const approved = await requestApproval(toolCallId, 'terminal_execute', { sessionId, command }, chatSessionId); - if (!approved) { - return { error: 'User denied command execution.' }; - } - } - if (abortSignal?.aborted) { - return { error: 'Command cancelled before it could start.' }; - } - await slot.ready; - if (abortSignal?.aborted) { - return { error: 'Command cancelled before it could start.' }; - } - // There's a tiny race between this check and the main-process - // `mcpServerBridge.reserveSessionExecution` registering the new - // exec into the cancellation tracker: `handleStop` issues a - // cancel IPC and the user's abort signal fires, but if our - // `aiExec` IPC was already in transit, the cancel may run - // before the exec has registered — and find nothing to - // cancel. Re-issue the cancel from the abort listener so a - // duplicate `aiCattyCancelExec` lands once the registration - // is complete. The cancel is idempotent (it only acts on - // entries it finds in `activePtyExecs`), so issuing twice is - // harmless. - const cancelOnAbort = () => { - if (chatSessionId) { - void bridge.aiCattyCancelExec?.(chatSessionId); - } - }; - abortSignal?.addEventListener('abort', cancelOnAbort, { once: true }); - try { - const result = await executeTerminalExecute(deps, { sessionId, command }); - if (result.ok === false) return unwrap(result); - return fitTerminalExecuteResultForModel(result.data); - } finally { - abortSignal?.removeEventListener('abort', cancelOnAbort); - } - } finally { - slot.release(); - } - }, - }), - - workspace_get_info: tool({ - description: - 'Get information about the current workspace, including all terminal sessions ' + - 'and their connection status. No parameters required.', - inputSchema: z.object({}), - execute: async () => { - return unwrap(executeWorkspaceGetInfo(deps)); - }, - }), - - workspace_get_session_info: tool({ - description: - 'Get detailed information about a specific terminal or SFTP session, including ' + - 'its connection status, protocol, shell hints, and session metadata.', - inputSchema: z.object({ - sessionId: z.string().describe('The session ID to get information about.'), - }), - execute: async ({ sessionId }) => { - return unwrap(executeWorkspaceGetSessionInfo(deps, { sessionId })); - }, - }), - - // -- Web Search (conditional on fully configured webSearchConfig) -- - ...(isWebSearchReady(webSearchConfig) ? { - web_search: tool({ - description: - 'Search the web for current information. Use this when the user asks about recent events, ' + - 'news, or facts you are unsure about. Returns a list of search results with titles, URLs, and content snippets.', - inputSchema: z.object({ - query: z.string().describe('The search query to look up on the web.'), - maxResults: z - .number() - .optional() - .describe('Maximum number of search results to return. If omitted, uses the configured default.'), - }), - execute: async ({ query, maxResults }) => { - return unwrap(await executeWebSearch(deps, { query, maxResults })); - }, - }), - } : {}), - - // -- URL Fetch (always available, read-only like sftp_read_file) -- - url_fetch: tool({ - description: - 'Fetch and read the content of a web URL. Use this when the user provides a URL and wants ' + - 'you to read or summarize its content. Returns the page content as text.', - inputSchema: z.object({ - url: z.string().describe('The HTTPS URL to fetch. Must start with https://.'), - maxLength: z - .number() - .optional() - .default(50000) - .describe('Maximum number of characters to return. Defaults to 50000.'), - }), - execute: async ({ url, maxLength }) => { - return unwrap(await executeUrlFetch(deps, { url, maxLength })); - }, - }), - }; -} +/** @deprecated Use createCattyToolsFromCatalog from harness directly. */ +export const createCattyTools = createCattyToolsFromCatalog; diff --git a/infrastructure/ai/sdkAgentAdapter.ts b/infrastructure/ai/sdkAgentAdapter.ts index eaf93c20e..98c61f46f 100644 --- a/infrastructure/ai/sdkAgentAdapter.ts +++ b/infrastructure/ai/sdkAgentAdapter.ts @@ -6,7 +6,9 @@ */ import type { AIToolIntegrationMode, ExternalAgentConfig } from './types'; -import { getExternalAgentSdkBackend } from './managedAgents'; +import { getExternalAgentSdkBackend, getManualAgentCommand } from './managedAgents'; +import { encodeSdkSessionIdentity } from './harness/sdkSessionIdentity'; +import { globalTraceStore, mapSdkStreamEventToAgentEvents } from './harness'; import { decryptField } from '../persistence/secureFieldAdapter'; export interface DefaultTargetSessionHint { @@ -63,32 +65,6 @@ interface StreamEvent { [key: string]: unknown; } -const SDK_SESSION_ID_PREFIX = 'netcatty-sdk-session:'; - -function getManualAgentCommand(config: ExternalAgentConfig): string | undefined { - const command = String(config.command || '').trim(); - return config.commandSource === 'manual' && command ? command : undefined; -} - -function encodeSdkSessionIdentity( - sessionId: string, - sdkBackend?: string, - binPath?: string, -): string { - if (!sessionId || !sdkBackend) return sessionId; - return `${SDK_SESSION_ID_PREFIX}${encodeURIComponent(JSON.stringify({ - v: 1, - id: sessionId, - backend: sdkBackend, - binPath: binPath || '', - }))}`; -} - -/** - * Run one managed SDK agent turn. - * Sends the prompt to the main process and listens for streamed events. - * Stream events are forwarded back via IPC. - */ export interface FileAttachment { base64Data: string; mediaType: string; @@ -182,6 +158,10 @@ export async function runSdkAgentTurn( toolIntegrationMode?: AIToolIntegrationMode, defaultTargetSession?: DefaultTargetSessionHint, userSkillsContext?: string, + harnessOptions?: { + traceSink?: (event: import('./harness/types').AgentEvent) => void; + skipHarnessTrace?: boolean; + }, ): Promise { const sdkBridge = bridge as unknown as SdkAgentBridge; const sdkBackend = getExternalAgentSdkBackend(config); @@ -209,7 +189,36 @@ export async function runSdkAgentTurn( const agentCommand = getManualAgentCommand(config); // Set up event listeners before starting stream + if (!harnessOptions?.skipHarnessTrace) { + globalTraceStore.append({ + id: `turn-start-${requestId}`, + type: 'turn_start', + sessionId: chatSessionId, + chatSessionId, + backend: 'external-sdk', + timestamp: Date.now(), + backendLabel: sdkBackend, + }); + } + + const appendHarnessEvent = (event: import('./harness/types').AgentEvent) => { + if (harnessOptions?.traceSink) { + harnessOptions.traceSink(event); + return; + } + if (!harnessOptions?.skipHarnessTrace) { + globalTraceStore.append(event); + } + }; + const unsubEvent = sdkBridge.onAiSdkAgentEvent(requestId, (event: StreamEvent) => { + for (const agentEvent of mapSdkStreamEventToAgentEvents(event, { + sessionId: chatSessionId, + chatSessionId, + turnId: requestId, + })) { + appendHarnessEvent(agentEvent); + } const streamFailed = handleStreamEvent(event, callbacks); if (streamFailed) { settle(); diff --git a/infrastructure/ai/shared/approvalConstants.ts b/infrastructure/ai/shared/approvalConstants.ts new file mode 100644 index 000000000..769feb569 --- /dev/null +++ b/infrastructure/ai/shared/approvalConstants.ts @@ -0,0 +1,8 @@ +/** Renderer-side Catty tool approval timeout (5 minutes). */ +export const CATTY_APPROVAL_TIMEOUT_MS = 5 * 60 * 1000; + +/** + * MCP / external SDK approval timeout aligned with Codex MCP limits (~110s). + * Kept separate from Catty because external agents block on main-process IPC. + */ +export const MCP_APPROVAL_TIMEOUT_MS = 110 * 1000; diff --git a/infrastructure/ai/shared/approvalGate.ts b/infrastructure/ai/shared/approvalGate.ts index eb39b5fa7..ae54d3b5d 100644 --- a/infrastructure/ai/shared/approvalGate.ts +++ b/infrastructure/ai/shared/approvalGate.ts @@ -15,8 +15,18 @@ * interference when stopping or cancelling sessions. */ -/** Default timeout for unanswered approval prompts (5 minutes). */ -const APPROVAL_TIMEOUT_MS = 5 * 60 * 1000; +import { CATTY_APPROVAL_TIMEOUT_MS } from './approvalConstants'; +import { localStorageAdapter } from '../../persistence/localStorageAdapter'; +import { STORAGE_KEY_AI_PERMISSION_GRANTS } from '../../config/storageKeys'; +import { globalTraceStore } from '../harness/traceStore'; +import { + getActivePermissionGrants, + matchPermissionGrant, + resolveCapabilityId, + sanitizePermissionGrants, + setActivePermissionGrants, + type PermissionGrantRule, +} from '../harness/permissionGrants'; export interface ApprovalRequest { toolCallId: string; @@ -24,6 +34,53 @@ export interface ApprovalRequest { args: Record; /** Optional chat session scope — used to clear only relevant approvals on stop */ chatSessionId?: string; + capabilityId?: string; +} + +export interface ResolveApprovalOptions { + approved: boolean; + persistGrant?: PermissionGrantRule; + persistGrants?: PermissionGrantRule[]; +} + +export type GrantPersister = (rule: PermissionGrantRule) => void; + +let grantPersister: GrantPersister | null = null; +const grantPersisterStack: GrantPersister[] = []; +let grantsHydrated = false; + +function refreshPermissionGrantsFromStorage(): void { + if (typeof window === 'undefined') return; + setActivePermissionGrants( + sanitizePermissionGrants(localStorageAdapter.read(STORAGE_KEY_AI_PERMISSION_GRANTS)), + ); + grantsHydrated = true; +} + +function ensureGrantsHydrated(): void { + if (grantsHydrated) return; + refreshPermissionGrantsFromStorage(); +} + +export function setGrantPersister(persister: GrantPersister | null): void { + grantPersisterStack.length = 0; + if (persister) { + grantPersisterStack.push(persister); + } + grantPersister = persister; +} + +/** Register a grant persister; supports multiple mounted AI panels via a stack. */ +export function registerGrantPersister(persister: GrantPersister): () => void { + grantPersisterStack.push(persister); + grantPersister = persister; + return () => { + const idx = grantPersisterStack.lastIndexOf(persister); + if (idx >= 0) { + grantPersisterStack.splice(idx, 1); + } + grantPersister = grantPersisterStack[grantPersisterStack.length - 1] ?? null; + }; } // Pending approval entries keyed by toolCallId. @@ -42,6 +99,59 @@ const listeners = new Set(); type ApprovalClearedListener = (toolCallIds: string[]) => void; const clearedListeners = new Set(); +let approvalEventCounter = 0; + +function nextApprovalEventId(prefix: string): string { + approvalEventCounter += 1; + return `${prefix}-${Date.now()}-${approvalEventCounter}`; +} + +function emitApprovalEvent( + type: 'approval_requested' | 'approval_resolved', + request: ApprovalRequest, + extra?: { outcome?: 'approved' | 'denied' | 'timeout'; persistedGrantId?: string }, +): void { + const sessionId = request.chatSessionId ?? 'global'; + const capabilityId = request.capabilityId ?? resolveCapabilityId(request.toolName); + const base = { + sessionId, + chatSessionId: request.chatSessionId, + backend: 'catty' as const, + timestamp: Date.now(), + toolCallId: request.toolCallId, + toolName: request.toolName, + }; + + if (type === 'approval_requested') { + globalTraceStore.append({ + ...base, + id: nextApprovalEventId('approval-requested'), + type: 'approval_requested', + args: request.args, + }); + return; + } + + globalTraceStore.append({ + ...base, + id: nextApprovalEventId('approval-resolved'), + type: 'approval_resolved', + outcome: extra?.outcome ?? 'denied', + persistedGrantId: extra?.persistedGrantId, + }); +} + +function isGrantedByRules(request: ApprovalRequest): boolean { + refreshPermissionGrantsFromStorage(); + const capabilityId = request.capabilityId ?? resolveCapabilityId(request.toolName); + return matchPermissionGrant(getActivePermissionGrants(), { + capabilityId, + chatSessionId: request.chatSessionId, + sessionId: typeof request.args.sessionId === 'string' ? request.args.sessionId : undefined, + args: request.args, + }) !== null; +} + /** * Called from a tool's `execute` function when it needs user approval. * Returns a Promise that resolves to `true` (approved) or `false` (denied). @@ -55,9 +165,22 @@ export function requestApproval( toolName: string, args: Record, chatSessionId?: string, - timeoutMs: number = APPROVAL_TIMEOUT_MS, + timeoutMs: number = CATTY_APPROVAL_TIMEOUT_MS, + capabilityId?: string, ): Promise { - const request: ApprovalRequest = { toolCallId, toolName, args, chatSessionId }; + const request: ApprovalRequest = { + toolCallId, + toolName, + args, + chatSessionId, + capabilityId: capabilityId ?? resolveCapabilityId(toolName), + }; + + if (isGrantedByRules(request)) { + return Promise.resolve(true); + } + + emitApprovalEvent('approval_requested', request); return new Promise((resolve) => { let timerId: ReturnType | null = null; @@ -74,6 +197,7 @@ export function requestApproval( if (pendingApprovals.has(toolCallId)) { pendingApprovals.delete(toolCallId); wrappedResolve(false); + emitApprovalEvent('approval_resolved', request, { outcome: 'timeout' }); // Notify UI to remove the stale card for (const cl of clearedListeners) { try { cl([toolCallId]); } catch { /* ignore */ } @@ -92,14 +216,38 @@ export function requestApproval( * Called from the UI when the user approves or rejects a tool execution. * Handles both SDK tool calls (local Promise) and MCP tool calls (IPC to main process). */ -export function resolveApproval(toolCallId: string, approved: boolean): void { +export function resolveApproval( + toolCallId: string, + decision: boolean | ResolveApprovalOptions, +): void { + const approved = typeof decision === 'boolean' ? decision : decision.approved; + const persistGrant = typeof decision === 'boolean' ? undefined : decision.persistGrant; + const persistGrants = typeof decision === 'boolean' + ? undefined + : (decision.persistGrants ?? (persistGrant ? [persistGrant] : undefined)); + const entry = pendingApprovals.get(toolCallId); + const request = entry?.request; + if (entry) { pendingApprovals.delete(toolCallId); - // SDK tool calls have a real resolve; MCP tool calls have a no-op resolve entry.resolve(approved); } + if (request) { + let persistedGrantId: string | undefined; + if (approved && persistGrants?.length) { + for (const grant of persistGrants) { + grantPersister?.(grant); + persistedGrantId = grant.id; + } + } + emitApprovalEvent('approval_resolved', request, { + outcome: approved ? 'approved' : 'denied', + persistedGrantId, + }); + } + // MCP tool call: also forward response to main process via IPC if (toolCallId.startsWith('mcp_approval_')) { const bridge = (window as unknown as { netcatty?: { respondMcpApproval?: (id: string, approved: boolean) => Promise } }).netcatty; @@ -218,6 +366,7 @@ export function setupMcpApprovalBridge(): () => void { toolName: payload.toolName, args: payload.args, chatSessionId: payload.chatSessionId, + capabilityId: resolveCapabilityId(payload.toolName), }; // Store in pendingApprovals so it survives unmount/remount diff --git a/infrastructure/ai/shared/bashArity.test.ts b/infrastructure/ai/shared/bashArity.test.ts new file mode 100644 index 000000000..2a85fb242 --- /dev/null +++ b/infrastructure/ai/shared/bashArity.test.ts @@ -0,0 +1,29 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { bashArityPrefix } from './bashArity'; + +describe('bashArity (OpenCode parity)', () => { + it('unknown commands default to first token', () => { + assert.deepEqual(bashArityPrefix(['unknown', 'command', 'subcommand']), ['unknown']); + assert.deepEqual(bashArityPrefix(['touch', 'foo.txt']), ['touch']); + }); + + it('two token commands', () => { + assert.deepEqual(bashArityPrefix(['git', 'checkout', 'main']), ['git', 'checkout']); + assert.deepEqual(bashArityPrefix(['docker', 'run', 'nginx']), ['docker', 'run']); + }); + + it('three token commands', () => { + assert.deepEqual(bashArityPrefix(['aws', 's3', 'ls', 'my-bucket']), ['aws', 's3', 'ls']); + assert.deepEqual(bashArityPrefix(['npm', 'run', 'dev', 'script']), ['npm', 'run', 'dev']); + }); + + it('longest match wins', () => { + assert.deepEqual(bashArityPrefix(['docker', 'compose', 'up', 'service']), ['docker', 'compose', 'up']); + assert.deepEqual(bashArityPrefix(['consul', 'kv', 'get', 'config']), ['consul', 'kv', 'get']); + }); + + it('lscpu uses first token only', () => { + assert.deepEqual(bashArityPrefix(['lscpu']), ['lscpu']); + }); +}); diff --git a/infrastructure/ai/shared/bashArity.ts b/infrastructure/ai/shared/bashArity.ts new file mode 100644 index 000000000..bb336c702 --- /dev/null +++ b/infrastructure/ai/shared/bashArity.ts @@ -0,0 +1,163 @@ +export function prefix(tokens: string[]) { + for (let len = tokens.length; len > 0; len--) { + const prefix = tokens.slice(0, len).join(" ") + const arity = ARITY[prefix] + if (arity !== undefined) return tokens.slice(0, arity) + } + if (tokens.length === 0) return [] + return tokens.slice(0, 1) +} + +/* Generated with following prompt: +You are generating a dictionary of command-prefix arities for bash-style commands. +This dictionary is used to identify the "human-understandable command" from an input shell command.### **RULES (follow strictly)**1. Each entry maps a **command prefix string → number**, representing how many **tokens** define the command. +2. **Flags NEVER count as tokens**. Only subcommands count. +3. **Longest matching prefix wins**. +4. **Only include a longer prefix if its arity is different from what the shorter prefix already implies**. * Example: If `git` is 2, then do **not** include `git checkout`, `git commit`, etc. unless they require *different* arity. +5. The output must be a **single JSON object**. Each entry should have a comment with an example real world matching command. DO NOT MAKE ANY OTHER COMMENTS. Should be alphabetical +6. Include the **most commonly used commands** across many stacks and languages. More is better.### **Semantics examples*** `touch foo.txt` → `touch` (arity 1, explicitly listed) +* `git checkout main` → `git checkout` (because `git` has arity 2) +* `npm install` → `npm install` (because `npm` has arity 2) +* `npm run dev` → `npm run dev` (because `npm run` has arity 3) +* `python script.py` → `python script.py` (default: whole input, not in dictionary)### **Now generate the dictionary.** +*/ +const ARITY: Record = { + cat: 1, // cat file.txt + cd: 1, // cd /path/to/dir + chmod: 1, // chmod 755 script.sh + chown: 1, // chown user:group file.txt + cp: 1, // cp source.txt dest.txt + echo: 1, // echo "hello world" + env: 1, // env + export: 1, // export PATH=/usr/bin + grep: 1, // grep pattern file.txt + kill: 1, // kill 1234 + killall: 1, // killall process + ln: 1, // ln -s source target + ls: 1, // ls -la + mkdir: 1, // mkdir new-dir + mv: 1, // mv old.txt new.txt + ps: 1, // ps aux + pwd: 1, // pwd + rm: 1, // rm file.txt + rmdir: 1, // rmdir empty-dir + sleep: 1, // sleep 5 + source: 1, // source ~/.bashrc + tail: 1, // tail -f log.txt + touch: 1, // touch file.txt + unset: 1, // unset VAR + which: 1, // which node + aws: 3, // aws s3 ls + az: 3, // az storage blob list + bazel: 2, // bazel build + brew: 2, // brew install node + bun: 2, // bun install + "bun run": 3, // bun run dev + "bun x": 3, // bun x vite + cargo: 2, // cargo build + "cargo add": 3, // cargo add tokio + "cargo run": 3, // cargo run main + cdk: 2, // cdk deploy + cf: 2, // cf push app + cmake: 2, // cmake build + composer: 2, // composer require laravel + consul: 2, // consul members + "consul kv": 3, // consul kv get config/app + crictl: 2, // crictl ps + deno: 2, // deno run server.ts + "deno task": 3, // deno task dev + doctl: 3, // doctl kubernetes cluster list + docker: 2, // docker run nginx + "docker builder": 3, // docker builder prune + "docker compose": 3, // docker compose up + "docker container": 3, // docker container ls + "docker image": 3, // docker image prune + "docker network": 3, // docker network inspect + "docker volume": 3, // docker volume ls + eksctl: 2, // eksctl get clusters + "eksctl create": 3, // eksctl create cluster + firebase: 2, // firebase deploy + flyctl: 2, // flyctl deploy + gcloud: 3, // gcloud compute instances list + gh: 3, // gh pr list + git: 2, // git checkout main + "git config": 3, // git config user.name + "git remote": 3, // git remote add origin + "git stash": 3, // git stash pop + go: 2, // go build + gradle: 2, // gradle build + helm: 2, // helm install mychart + heroku: 2, // heroku logs + hugo: 2, // hugo new site blog + ip: 2, // ip link show + "ip addr": 3, // ip addr show + "ip link": 3, // ip link set eth0 up + "ip netns": 3, // ip netns exec foo bash + "ip route": 3, // ip route add default via 1.1.1.1 + kind: 2, // kind delete cluster + "kind create": 3, // kind create cluster + kubectl: 2, // kubectl get pods + "kubectl kustomize": 3, // kubectl kustomize overlays/dev + "kubectl rollout": 3, // kubectl rollout restart deploy/api + kustomize: 2, // kustomize build . + make: 2, // make build + mc: 2, // mc ls myminio + "mc admin": 3, // mc admin info myminio + minikube: 2, // minikube start + mongosh: 2, // mongosh test + mysql: 2, // mysql -u root + mvn: 2, // mvn compile + ng: 2, // ng generate component home + npm: 2, // npm install + "npm exec": 3, // npm exec vite + "npm init": 3, // npm init vue + "npm run": 3, // npm run dev + "npm view": 3, // npm view react version + nvm: 2, // nvm use 18 + nx: 2, // nx build + openssl: 2, // openssl genrsa 2048 + "openssl req": 3, // openssl req -new -key key.pem + "openssl x509": 3, // openssl x509 -in cert.pem + pip: 2, // pip install numpy + pipenv: 2, // pipenv install flask + pnpm: 2, // pnpm install + "pnpm dlx": 3, // pnpm dlx create-next-app + "pnpm exec": 3, // pnpm exec vite + "pnpm run": 3, // pnpm run dev + poetry: 2, // poetry add requests + podman: 2, // podman run alpine + "podman container": 3, // podman container ls + "podman image": 3, // podman image prune + psql: 2, // psql -d mydb + pulumi: 2, // pulumi up + "pulumi stack": 3, // pulumi stack output + pyenv: 2, // pyenv install 3.11 + python: 2, // python -m venv env + rake: 2, // rake db:migrate + rbenv: 2, // rbenv install 3.2.0 + "redis-cli": 2, // redis-cli ping + rustup: 2, // rustup update + serverless: 2, // serverless invoke + sfdx: 3, // sfdx force:org:list + skaffold: 2, // skaffold dev + sls: 2, // sls deploy + sst: 2, // sst deploy + swift: 2, // swift build + systemctl: 2, // systemctl restart nginx + terraform: 2, // terraform apply + "terraform workspace": 3, // terraform workspace select prod + tmux: 2, // tmux new -s dev + turbo: 2, // turbo run build + ufw: 2, // ufw allow 22 + vault: 2, // vault login + "vault auth": 3, // vault auth list + "vault kv": 3, // vault kv get secret/api + vercel: 2, // vercel deploy + volta: 2, // volta install node + wp: 2, // wp plugin install + yarn: 2, // yarn add react + "yarn dlx": 3, // yarn dlx create-react-app + "yarn run": 3, // yarn run dev +} + +export function bashArityPrefix(tokens: string[]): string[] { return prefix(tokens); } diff --git a/infrastructure/ai/shared/pathLikeCommand.ts b/infrastructure/ai/shared/pathLikeCommand.ts new file mode 100644 index 000000000..48420d394 --- /dev/null +++ b/infrastructure/ai/shared/pathLikeCommand.ts @@ -0,0 +1,12 @@ +/** True when the configured agent command looks like an explicit filesystem path. */ +export function isPathLikeCommand(command: string | undefined): boolean { + const normalized = String(command || '').trim(); + return normalized.includes('/') || normalized.includes('\\') || /^[a-z]:/i.test(normalized); +} + +export function getCommandBasename(command: string | undefined): string { + const normalized = String(command || '').trim(); + if (!normalized) return ''; + const parts = normalized.split(/[\\/]/); + return (parts.pop() || '').toLowerCase(); +} diff --git a/infrastructure/ai/shared/shellCommandGrant.test.ts b/infrastructure/ai/shared/shellCommandGrant.test.ts new file mode 100644 index 000000000..dfe657064 --- /dev/null +++ b/infrastructure/ai/shared/shellCommandGrant.test.ts @@ -0,0 +1,23 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { buildAlwaysAllowCommandPatterns } from './shellCommandGrant'; + +describe('shellCommandGrant (OpenCode always patterns)', () => { + it('builds prefix wildcard for simple commands', () => { + assert.deepEqual(buildAlwaysAllowCommandPatterns('lscpu'), ['lscpu *']); + assert.deepEqual(buildAlwaysAllowCommandPatterns('touch foo.txt'), ['touch *']); + }); + + it('builds subcommand-aware prefixes', () => { + assert.deepEqual(buildAlwaysAllowCommandPatterns('git checkout main'), ['git checkout *']); + assert.deepEqual(buildAlwaysAllowCommandPatterns('systemctl status nginx'), ['systemctl status *']); + assert.deepEqual(buildAlwaysAllowCommandPatterns('npm run dev'), ['npm run dev *']); + }); + + it('skips cd segments in chains but keeps others', () => { + assert.deepEqual( + buildAlwaysAllowCommandPatterns('cd /tmp && ls -la'), + ['ls *'], + ); + }); +}); diff --git a/infrastructure/ai/shared/shellCommandGrant.ts b/infrastructure/ai/shared/shellCommandGrant.ts new file mode 100644 index 000000000..2f7ecc41c --- /dev/null +++ b/infrastructure/ai/shared/shellCommandGrant.ts @@ -0,0 +1,65 @@ +import { bashArityPrefix } from './bashArity'; + +/** Commands whose always-allow patterns are skipped (OpenCode shell.ts CWD set). */ +const CWD_COMMANDS = new Set([ + 'cd', + 'chdir', + 'popd', + 'pushd', + 'push-location', + 'set-location', +]); + +export function unquoteShellToken(token: string): string { + if (token.length >= 2) { + const first = token[0]; + const last = token[token.length - 1]; + if ((first === '"' || first === "'") && first === last) { + return token.slice(1, -1); + } + } + return token; +} + +export function tokenizeShellCommand(command: string): string[] { + const matches = command.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g) ?? []; + return matches.map(unquoteShellToken); +} + +export function splitShellCommandSegments(command: string): string[] { + return command + .split(/\s*(?:&&|\|\||;)\s*/) + .map((segment) => segment.trim()) + .filter(Boolean); +} + +/** + * OpenCode always-allow patterns: BashArity.prefix(tokens) + " *" + * @see packages/opencode/src/tool/shell.ts collect() + */ +export function buildAlwaysAllowCommandPatterns(command: string): string[] { + const trimmed = command.trim(); + if (!trimmed) return []; + + const patterns = new Set(); + const segments = splitShellCommandSegments(trimmed); + + for (const segment of segments) { + const tokens = tokenizeShellCommand(segment); + if (tokens.length === 0) continue; + const cmd = tokens[0]?.toLowerCase(); + if (cmd && CWD_COMMANDS.has(cmd)) continue; + const prefix = bashArityPrefix(tokens); + if (prefix.length === 0) continue; + patterns.add(`${prefix.join(' ')} *`); + } + + if (patterns.size === 0) { + const tokens = tokenizeShellCommand(trimmed); + if (tokens.length > 0) { + patterns.add(`${bashArityPrefix(tokens).join(' ')} *`); + } + } + + return [...patterns]; +} diff --git a/infrastructure/ai/vaultAgentBridgeClient.test.ts b/infrastructure/ai/vaultAgentBridgeClient.test.ts new file mode 100644 index 000000000..3f975890d --- /dev/null +++ b/infrastructure/ai/vaultAgentBridgeClient.test.ts @@ -0,0 +1,310 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import type { Host, VaultNote } from '../../domain/models'; +import { handleVaultAgentOp, runSerializedVaultAgentRequest, type VaultAgentApiDeps } from './vaultAgentBridgeClient'; + +type DepsSeed = { + hosts?: Host[]; + notes?: VaultNote[]; + customGroups?: string[]; +}; + +function createDeps( + overrides: Partial & DepsSeed = {}, +): VaultAgentApiDeps { + let hosts = overrides.hosts ?? []; + let notes = overrides.notes ?? []; + let customGroups = overrides.customGroups ?? []; + + const base: VaultAgentApiDeps = { + getHosts: () => hosts, + getNotes: () => notes, + getCustomGroups: () => customGroups, + snippets: [], + portForwardingRules: [], + keys: [], + identities: [], + resolveEffectiveHost: (host) => host, + updateHostNotes: () => {}, + updateCustomGroups: (groups) => { + customGroups = groups; + }, + updateHosts: (nextHosts) => { + hosts = nextHosts; + }, + updateNotes: (nextNotes) => { + notes = nextNotes; + }, + startTunnel: async () => ({ success: true }), + stopTunnel: async () => ({ success: true }), + }; + + return { + ...base, + ...overrides, + getHosts: overrides.getHosts ?? base.getHosts, + getNotes: overrides.getNotes ?? base.getNotes, + getCustomGroups: overrides.getCustomGroups ?? base.getCustomGroups, + updateHosts: (nextHosts) => { + base.updateHosts(nextHosts); + overrides.updateHosts?.(nextHosts); + }, + updateNotes: (nextNotes) => { + base.updateNotes(nextNotes); + overrides.updateNotes?.(nextNotes); + }, + updateCustomGroups: (groups) => { + base.updateCustomGroups(groups); + overrides.updateCustomGroups?.(groups); + }, + }; +} + +describe('handleVaultAgentOp vault notes', () => { + it('note.create persists to updateNotes and returns the new note', async () => { + const updated: VaultNote[][] = []; + const deps = createDeps({ + notes: [], + updateNotes: (nextNotes) => { + updated.push(nextNotes); + }, + }); + + const result = await handleVaultAgentOp( + 'note.create', + { title: 'Deploy runbook', content: '# Steps\n1. Connect' }, + deps, + ); + + assert.equal(result.ok, true); + assert.equal(updated.length, 1); + assert.equal(updated[0]?.length, 1); + assert.equal(updated[0]?.[0]?.title, 'Deploy runbook'); + assert.equal(updated[0]?.[0]?.content, '# Steps\n1. Connect'); + assert.equal((result as { note?: VaultNote }).note?.id, updated[0]?.[0]?.id); + }); + + it('note.list returns summaries without full content', async () => { + const note: VaultNote = { + id: 'note-1', + title: 'Existing', + content: 'secret body', + createdAt: 1, + updatedAt: 2, + }; + const result = await handleVaultAgentOp('note.list', {}, createDeps({ notes: [note] })); + + assert.equal(result.ok, true); + const listed = (result as { notes?: Array<{ id: string; contentLength: number; title: string }> }).notes; + assert.equal(listed?.length, 1); + assert.equal(listed?.[0]?.title, 'Existing'); + assert.equal(listed?.[0]?.contentLength, 'secret body'.length); + assert.equal('content' in (listed?.[0] ?? {}), false); + }); + + it('note.update replaces content and bumps updatedAt', async () => { + const existing: VaultNote = { + id: 'note-1', + title: 'Old title', + content: 'old', + createdAt: 100, + updatedAt: 100, + }; + const updated: VaultNote[][] = []; + const deps = createDeps({ + notes: [existing], + updateNotes: (nextNotes) => { + updated.push(nextNotes); + }, + }); + + const result = await handleVaultAgentOp( + 'note.update', + { noteId: 'note-1', title: 'New title', content: 'new body' }, + deps, + ); + + assert.equal(result.ok, true); + assert.equal(updated[0]?.[0]?.title, 'New title'); + assert.equal(updated[0]?.[0]?.content, 'new body'); + assert.ok((updated[0]?.[0]?.updatedAt ?? 0) >= 100); + }); + + it('sequential note.create calls accumulate instead of overwriting prior notes', async () => { + const deps = createDeps({ notes: [] }); + + const first = await handleVaultAgentOp( + 'note.create', + { title: 'First', content: 'one' }, + deps, + ); + const second = await handleVaultAgentOp( + 'note.create', + { title: 'Second', content: 'two' }, + deps, + ); + + assert.equal(first.ok, true); + assert.equal(second.ok, true); + assert.equal(deps.getNotes().length, 2); + assert.deepEqual(deps.getNotes().map((note) => note.title), ['First', 'Second']); + }); + + it('host.notes.set still updates host metadata separately from vault notes', async () => { + const host: Host = { + id: 'host-1', + label: 'prod', + hostname: '10.0.0.1', + username: 'root', + notes: '', + }; + let hostNotes = ''; + const deps = createDeps({ + hosts: [host], + updateHostNotes: (hostId, notes) => { + assert.equal(hostId, 'host-1'); + hostNotes = notes; + }, + }); + + const result = await handleVaultAgentOp( + 'host.notes.set', + { hostId: 'host-1', notes: 'host detail memo' }, + deps, + ); + + assert.equal(result.ok, true); + assert.equal(hostNotes, 'host detail memo'); + }); +}); + +describe('handleVaultAgentOp vault hosts', () => { + const csvText = [ + 'Label,Hostname,Port,Username,Groups', + 'web-1,10.0.0.10,22,deploy,prod/web', + 'db-1,10.0.0.20,22,root,prod/db', + ].join('\n'); + + it('host.list returns metadata without passwords', async () => { + const host: Host = { + id: 'host-1', + label: 'prod', + hostname: '10.0.0.1', + username: 'root', + password: 'secret', + port: 22, + }; + const result = await handleVaultAgentOp('host.list', {}, createDeps({ hosts: [host] })); + assert.equal(result.ok, true); + const hosts = (result as { hosts?: Array> }).hosts; + assert.equal(hosts?.length, 1); + assert.equal(hosts?.[0]?.hostname, '10.0.0.1'); + assert.equal('password' in (hosts?.[0] ?? {}), false); + }); + + it('hosts.create maps structured JSON from arbitrary text into vault hosts', async () => { + const updatedHosts: Host[][] = []; + const unstructuredMapped = JSON.stringify([ + { label: 'Prod API', hostname: 'api.example.com', username: 'deploy', port: 22, group: 'prod/api' }, + { label: 'Staging DB', hostname: '10.20.0.5', username: 'postgres', tags: ['db', 'staging'] }, + ]); + + const result = await handleVaultAgentOp( + 'hosts.create', + { hosts: unstructuredMapped }, + createDeps({ + updateHosts: (hosts) => { + updatedHosts.push(hosts); + }, + updateCustomGroups: () => {}, + }), + ); + + assert.equal(result.ok, true); + assert.equal(updatedHosts[0]?.length, 2); + assert.equal((result as { addedCount?: number }).addedCount, 2); + }); + + it('sequential hosts.create calls accumulate instead of dropping prior hosts', async () => { + const deps = createDeps({ hosts: [], customGroups: [] }); + + const first = await handleVaultAgentOp( + 'hosts.create', + { hosts: JSON.stringify([{ hostname: '10.0.0.1', username: 'root', label: 'first' }]) }, + deps, + ); + const second = await handleVaultAgentOp( + 'hosts.create', + { hosts: JSON.stringify([{ hostname: '10.0.0.2', username: 'root', label: 'second' }]) }, + deps, + ); + + assert.equal(first.ok, true); + assert.equal(second.ok, true); + assert.equal(deps.getHosts().length, 2); + assert.deepEqual(deps.getHosts().map((host) => host.hostname), ['10.0.0.1', '10.0.0.2']); + }); + + it('host.import dryRun previews parsed hosts without writing', async () => { + const updatedHosts: Host[][] = []; + const result = await handleVaultAgentOp( + 'host.import', + { format: 'csv', text: csvText, dryRun: 'true' }, + createDeps({ + updateHosts: (hosts) => { + updatedHosts.push(hosts); + }, + }), + ); + + assert.equal(result.ok, true); + assert.equal((result as { dryRun?: boolean }).dryRun, true); + assert.equal(updatedHosts.length, 0); + assert.equal((result as { previewHosts?: unknown[] }).previewHosts?.length, 2); + }); + + it('host.import applies hosts to the vault', async () => { + const updatedHosts: Host[][] = []; + const updatedGroups: string[][] = []; + const result = await handleVaultAgentOp( + 'host.import', + { format: 'auto', text: csvText }, + createDeps({ + updateHosts: (hosts) => { + updatedHosts.push(hosts); + }, + updateCustomGroups: (groups) => { + updatedGroups.push(groups); + }, + }), + ); + + assert.equal(result.ok, true); + assert.equal(updatedHosts[0]?.length, 2); + assert.ok(updatedGroups[0]?.includes('prod/web')); + assert.equal((result as { addedCount?: number }).addedCount, 2); + }); +}); + +describe('runSerializedVaultAgentRequest', () => { + it('runs concurrent tasks sequentially without losing updates', async () => { + let value = 0; + const results = await Promise.all([ + runSerializedVaultAgentRequest(async () => { + const snapshot = value; + await new Promise((resolve) => setTimeout(resolve, 5)); + value = snapshot + 1; + return value; + }), + runSerializedVaultAgentRequest(async () => { + const snapshot = value; + await new Promise((resolve) => setTimeout(resolve, 1)); + value = snapshot + 1; + return value; + }), + ]); + + assert.deepEqual(results, [1, 2]); + assert.equal(value, 2); + }); +}); diff --git a/infrastructure/ai/vaultAgentBridgeClient.ts b/infrastructure/ai/vaultAgentBridgeClient.ts new file mode 100644 index 000000000..8eb34e177 --- /dev/null +++ b/infrastructure/ai/vaultAgentBridgeClient.ts @@ -0,0 +1,582 @@ +import type { Host, Identity, PortForwardingRule, Snippet, SSHKey, TerminalSettings, VaultNote } from '../../domain/models'; +import { + normalizeVaultNotes, + sanitizeNoteTitle, + sanitizeVaultNote, +} from '../../domain/notes'; +import { getNextVaultOrder } from '../../domain/vaultOrder'; +import { + applyVaultHostCreates, + buildVaultHostsFromDrafts, + parseVaultHostDraftsInput, +} from '../../domain/vaultHostCreate'; +import { + applyVaultHostImport, + detectVaultImportFormat, + importVaultHostsFromText, + VAULT_IMPORT_FORMATS, + type VaultImportFormat, +} from '../../domain/vaultImport'; +import { resolveHostAuth } from '../../domain/sshAuth'; +import { netcattyBridge } from '../services/netcattyBridge'; + +const SENSITIVE_HOST_KEYS = new Set([ + 'password', + 'telnetPassword', + 'privateKey', + 'passphrase', +]); + +export function sanitizeHostForAgent(host: Host): Record { + const sanitized: Record = {}; + for (const [key, value] of Object.entries(host)) { + if (SENSITIVE_HOST_KEYS.has(key)) continue; + sanitized[key] = value; + } + return sanitized; +} + +function summarizeHostForList(host: Host) { + return { + id: host.id, + label: host.label, + hostname: host.hostname, + port: host.port, + username: host.username, + protocol: host.protocol, + group: host.group, + tags: host.tags, + os: host.os, + createdAt: host.createdAt, + }; +} + +function parseOptionalBoolean(value: unknown): boolean | undefined { + if (value === undefined || value === null) return undefined; + if (typeof value === 'boolean') return value; + if (typeof value !== 'string') return undefined; + const normalized = value.trim().toLowerCase(); + if (normalized === 'true' || normalized === '1' || normalized === 'yes') return true; + if (normalized === 'false' || normalized === '0' || normalized === 'no') return false; + return undefined; +} + +function resolveVaultImportFormat(raw: unknown): VaultImportFormat | 'auto' | { error: string } { + const format = typeof raw === 'string' ? raw.trim().toLowerCase() : ''; + if (!format) return { error: 'format is required.' }; + if (format === 'auto') return 'auto'; + if ((VAULT_IMPORT_FORMATS as readonly string[]).includes(format)) { + return format as VaultImportFormat; + } + return { + error: `Unsupported format "${format}". Use csv, putty, mobaxterm, securecrt, ssh_config, or auto.`, + }; +} + +export function sanitizePortForwardRuleForAgent(rule: PortForwardingRule): Record { + return { + id: rule.id, + label: rule.label, + type: rule.type, + localPort: rule.localPort, + bindAddress: rule.bindAddress, + remoteHost: rule.remoteHost, + remotePort: rule.remotePort, + hostId: rule.hostId, + autoStart: rule.autoStart, + status: rule.status, + error: rule.error, + createdAt: rule.createdAt, + lastUsedAt: rule.lastUsedAt, + }; +} + +function summarizeVaultNoteForList(note: VaultNote) { + return { + id: note.id, + title: note.title, + group: note.group, + tags: note.tags, + linkedHostIds: note.linkedHostIds, + updatedAt: note.updatedAt, + contentLength: note.content.length, + }; +} + +function serializeVaultNoteForAgent(note: VaultNote) { + return { + id: note.id, + title: note.title, + content: note.content, + group: note.group, + tags: note.tags, + linkedHostIds: note.linkedHostIds, + createdAt: note.createdAt, + updatedAt: note.updatedAt, + }; +} + +function parseSnippetVariableValues( + raw: unknown, +): Record | { error: string } { + if (raw === undefined || raw === null) return {}; + if (typeof raw === 'object' && !Array.isArray(raw)) { + return Object.fromEntries( + Object.entries(raw as Record).map(([key, value]) => [key, String(value ?? '')]), + ); + } + if (typeof raw !== 'string' || !raw.trim()) return {}; + try { + const parsed = JSON.parse(raw) as unknown; + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + return Object.fromEntries( + Object.entries(parsed as Record).map(([key, value]) => [key, String(value ?? '')]), + ); + } + return { error: 'variables must be a JSON object string.' }; + } catch { + return { error: 'variables must be a JSON object string.' }; + } +} + +function parseOptionalStringArray( + value: unknown, + fieldName: string, +): string[] | undefined | { error: string } { + if (value === undefined || value === null) return undefined; + if (Array.isArray(value)) { + return value.map((entry) => String(entry).trim()).filter(Boolean); + } + if (typeof value !== 'string') { + return { error: `${fieldName} must be a string or array.` }; + } + const trimmed = value.trim(); + if (!trimmed) return undefined; + if (trimmed.startsWith('[')) { + try { + const parsed = JSON.parse(trimmed) as unknown; + if (!Array.isArray(parsed)) { + return { error: `${fieldName} must be a JSON array.` }; + } + return parsed.map((entry) => String(entry).trim()).filter(Boolean); + } catch { + return { error: `${fieldName} must be valid JSON array.` }; + } + } + return trimmed.split(',').map((entry) => entry.trim()).filter(Boolean); +} + +export interface VaultAgentApiDeps { + getHosts: () => Host[]; + getNotes: () => VaultNote[]; + getCustomGroups: () => string[]; + snippets: Snippet[]; + portForwardingRules: PortForwardingRule[]; + keys: SSHKey[]; + identities: Identity[]; + terminalSettings?: Pick; + resolveEffectiveHost: (host: Host) => Host; + updateHostNotes: (hostId: string, notes: string) => void; + updateCustomGroups: (groups: string[]) => void; + updateHosts: (hosts: Host[]) => void; + updateNotes: (notes: VaultNote[]) => void; + startTunnel: ( + rule: PortForwardingRule, + host: Host, + hosts: Host[], + keys: SSHKey[], + identities: Identity[], + onStatusChange?: (status: PortForwardingRule['status'], error?: string) => void, + enableReconnect?: boolean, + terminalSettings?: Pick, + ) => Promise<{ success: boolean; error?: string }>; + stopTunnel: ( + ruleId: string, + onStatusChange?: (status: PortForwardingRule['status']) => void, + ) => Promise<{ success: boolean; error?: string }>; +} + +export async function handleVaultAgentOp( + op: string, + params: Record, + deps: VaultAgentApiDeps, +): Promise> { + switch (op) { + case 'host.get': { + const hostId = String(params.hostId || ''); + const host = deps.getHosts().find((entry) => entry.id === hostId); + if (!host) return { ok: false, error: `Host "${hostId}" was not found.` }; + return { ok: true, host: sanitizeHostForAgent(deps.resolveEffectiveHost(host)) }; + } + case 'host.list': { + return { + ok: true, + hosts: deps.getHosts().map((host) => summarizeHostForList(deps.resolveEffectiveHost(host))), + }; + } + case 'hosts.create': { + const parsedDrafts = parseVaultHostDraftsInput(params.hosts); + if (!parsedDrafts.ok) return { ok: false, error: parsedDrafts.error }; + + const dryRun = parseOptionalBoolean(params.dryRun) ?? false; + const skipDuplicates = parseOptionalBoolean(params.skipDuplicates) ?? true; + const { hosts: builtHosts, issues: buildIssues } = buildVaultHostsFromDrafts(parsedDrafts.drafts); + + if (builtHosts.length === 0) { + return { + ok: false, + error: buildIssues[0]?.error || 'No valid hosts to create.', + issues: buildIssues, + }; + } + + const previewHosts = builtHosts.map((host) => sanitizeHostForAgent(host)); + + if (dryRun) { + return { + ok: true, + dryRun: true, + parsedCount: parsedDrafts.drafts.length, + validCount: builtHosts.length, + issues: buildIssues, + previewHosts, + }; + } + + const merged = applyVaultHostCreates( + deps.getHosts(), + deps.getCustomGroups(), + builtHosts, + { skipDuplicates }, + ); + + if (merged.addedCount === 0) { + return { + ok: false, + error: 'No new hosts were added (all duplicates or invalid).', + issues: buildIssues, + skippedExistingCount: merged.skippedExistingCount, + previewHosts, + }; + } + + deps.updateHosts(merged.hosts); + deps.updateCustomGroups(merged.customGroups); + + return { + ok: true, + dryRun: false, + parsedCount: parsedDrafts.drafts.length, + validCount: builtHosts.length, + addedCount: merged.addedCount, + skippedExistingCount: merged.skippedExistingCount, + issues: buildIssues, + previewHosts: merged.addedHosts.map((host) => sanitizeHostForAgent(host)), + }; + } + case 'host.import': { + const text = typeof params.text === 'string' ? params.text : ''; + if (!text.trim()) return { ok: false, error: 'text is required.' }; + + const formatParam = resolveVaultImportFormat(params.format); + if (typeof formatParam === 'object' && 'error' in formatParam) { + return { ok: false, error: formatParam.error }; + } + + let resolvedFormat: VaultImportFormat; + if (formatParam === 'auto') { + const detected = detectVaultImportFormat(text); + if (!detected) { + return { + ok: false, + error: 'Could not detect import format. Specify csv, putty, mobaxterm, securecrt, or ssh_config.', + }; + } + resolvedFormat = detected; + } else { + resolvedFormat = formatParam; + } + + const dryRun = parseOptionalBoolean(params.dryRun) ?? false; + const skipDuplicates = parseOptionalBoolean(params.skipDuplicates) ?? true; + const fileName = typeof params.fileName === 'string' && params.fileName.trim() + ? params.fileName.trim() + : undefined; + + const importResult = importVaultHostsFromText(resolvedFormat, text, { fileName }); + const previewHosts = importResult.hosts.map((host) => sanitizeHostForAgent(host)); + + if (dryRun) { + return { + ok: true, + dryRun: true, + format: resolvedFormat, + stats: importResult.stats, + issues: importResult.issues, + groups: importResult.groups, + previewHosts, + }; + } + + const merged = applyVaultHostImport( + deps.getHosts(), + deps.getCustomGroups(), + importResult, + { skipDuplicates }, + ); + + if (merged.addedCount === 0 && importResult.stats.parsed === 0) { + return { + ok: false, + error: importResult.issues[0]?.message || 'No hosts were imported.', + format: resolvedFormat, + stats: importResult.stats, + issues: importResult.issues, + }; + } + + deps.updateHosts(merged.hosts); + deps.updateCustomGroups(merged.customGroups); + + return { + ok: true, + dryRun: false, + format: resolvedFormat, + stats: importResult.stats, + issues: importResult.issues, + addedCount: merged.addedCount, + skippedExistingCount: merged.skippedExistingCount, + previewHosts: previewHosts.slice(0, 20), + }; + } + case 'host.notes.get': { + const hostId = String(params.hostId || ''); + const host = deps.getHosts().find((entry) => entry.id === hostId); + if (!host) return { ok: false, error: `Host "${hostId}" was not found.` }; + return { ok: true, hostId, notes: host.notes || '' }; + } + case 'host.notes.set': { + const hostId = String(params.hostId || ''); + const notes = typeof params.notes === 'string' ? params.notes : ''; + const host = deps.getHosts().find((entry) => entry.id === hostId); + if (!host) return { ok: false, error: `Host "${hostId}" was not found.` }; + deps.updateHostNotes(hostId, notes); + return { ok: true, hostId }; + } + case 'note.list': { + return { + ok: true, + notes: deps.getNotes().map(summarizeVaultNoteForList), + }; + } + case 'note.get': { + const noteId = String(params.noteId || ''); + const note = deps.getNotes().find((entry) => entry.id === noteId); + if (!note) return { ok: false, error: `Vault note "${noteId}" was not found.` }; + return { ok: true, note: serializeVaultNoteForAgent(note) }; + } + case 'note.create': { + const title = sanitizeNoteTitle(params.title); + if (!title) return { ok: false, error: 'title is required.' }; + const content = typeof params.content === 'string' ? params.content : ''; + const linkedHostIds = parseOptionalStringArray(params.linkedHostIds, 'linkedHostIds'); + if (linkedHostIds && 'error' in linkedHostIds) return { ok: false, error: linkedHostIds.error }; + const tags = parseOptionalStringArray(params.tags, 'tags'); + if (tags && 'error' in tags) return { ok: false, error: tags.error }; + const note = sanitizeVaultNote({ + title, + content, + group: typeof params.group === 'string' && params.group.trim() ? params.group.trim() : undefined, + linkedHostIds, + tags, + order: getNextVaultOrder(deps.getNotes()), + }); + const nextNotes = normalizeVaultNotes([...deps.getNotes(), note]); + deps.updateNotes(nextNotes); + return { ok: true, note: serializeVaultNoteForAgent(note) }; + } + case 'note.update': { + const noteId = String(params.noteId || ''); + const existing = deps.getNotes().find((entry) => entry.id === noteId); + if (!existing) return { ok: false, error: `Vault note "${noteId}" was not found.` }; + const linkedHostIds = parseOptionalStringArray(params.linkedHostIds, 'linkedHostIds'); + if (linkedHostIds && 'error' in linkedHostIds) return { ok: false, error: linkedHostIds.error }; + const tags = parseOptionalStringArray(params.tags, 'tags'); + if (tags && 'error' in tags) return { ok: false, error: tags.error }; + const note = sanitizeVaultNote({ + ...existing, + title: params.title !== undefined ? sanitizeNoteTitle(params.title) : existing.title, + content: typeof params.content === 'string' ? params.content : existing.content, + group: params.group !== undefined + ? (typeof params.group === 'string' && params.group.trim() ? params.group.trim() : undefined) + : existing.group, + linkedHostIds: linkedHostIds ?? existing.linkedHostIds, + tags: tags ?? existing.tags, + updatedAt: Date.now(), + }); + if (!note.title) return { ok: false, error: 'title cannot be empty.' }; + const nextNotes = normalizeVaultNotes( + deps.getNotes().map((entry) => (entry.id === noteId ? note : entry)), + ); + deps.updateNotes(nextNotes); + return { ok: true, note: serializeVaultNoteForAgent(note) }; + } + case 'snippets.list': { + return { + ok: true, + snippets: deps.snippets.map((snippet) => ({ + id: snippet.id, + label: snippet.label, + tags: snippet.tags || [], + targets: snippet.targets || [], + package: snippet.package, + })), + }; + } + case 'snippets.get': { + const snippetId = String(params.snippetId || ''); + const snippet = deps.snippets.find((entry) => entry.id === snippetId); + if (!snippet) return { ok: false, error: `Snippet "${snippetId}" was not found.` }; + return { + ok: true, + snippet: { + id: snippet.id, + label: snippet.label, + command: snippet.command, + tags: snippet.tags || [], + targets: snippet.targets || [], + noAutoRun: snippet.noAutoRun, + }, + }; + } + case 'snippets.run': { + const snippetId = String(params.snippetId || ''); + const sessionId = String(params.sessionId || ''); + const snippet = deps.snippets.find((entry) => entry.id === snippetId); + if (!snippet) return { ok: false, error: `Snippet "${snippetId}" was not found.` }; + if (!sessionId) return { ok: false, error: 'sessionId is required.' }; + + let variableValues: Record = {}; + const parsedVariables = parseSnippetVariableValues(params.variables); + if ('error' in parsedVariables) { + return { ok: false, error: parsedVariables.error }; + } + variableValues = parsedVariables; + + const defs = parseSnippetVariables(snippet.command); + for (const def of defs) { + if (variableValues[def.name] === undefined && def.defaultValue !== undefined) { + variableValues[def.name] = def.defaultValue; + } + } + for (const def of defs) { + if ((variableValues[def.name] ?? '').trim() === '' && def.defaultValue === undefined) { + return { ok: false, error: `Missing snippet variable "${def.name}".` }; + } + } + + const command = applySnippetVariables(snippet.command, variableValues); + const bridge = netcattyBridge.get(); + if (!bridge?.aiExec) { + return { ok: false, error: 'Terminal execution bridge is unavailable.' }; + } + const chatSessionId = typeof params.chatSessionId === 'string' ? params.chatSessionId : undefined; + const result = await bridge.aiExec(sessionId, command, chatSessionId); + if (result && typeof result === 'object' && 'ok' in result && result.ok === false) { + return { ok: false, error: (result as { error?: string }).error || 'Snippet execution failed.' }; + } + return { ok: true, sessionId, snippetId, command, result }; + } + case 'portforward.rules.list': { + return { + ok: true, + rules: deps.portForwardingRules.map(sanitizePortForwardRuleForAgent), + }; + } + case 'portforward.start': { + const ruleId = String(params.ruleId || ''); + const rule = deps.portForwardingRules.find((entry) => entry.id === ruleId); + if (!rule) return { ok: false, error: `Port forwarding rule "${ruleId}" was not found.` }; + if (!rule.hostId) return { ok: false, error: 'Rule has no associated host.' }; + const rawHost = deps.getHosts().find((entry) => entry.id === rule.hostId); + if (!rawHost) return { ok: false, error: `Host "${rule.hostId}" was not found.` }; + const host = deps.resolveEffectiveHost(rawHost); + try { + resolveHostAuth({ host, keys: deps.keys, identities: deps.identities }); + } catch (err) { + return { ok: false, error: err instanceof Error ? err.message : String(err) }; + } + const effectiveHosts = deps.getHosts().map((entry) => deps.resolveEffectiveHost(entry)); + const result = await deps.startTunnel( + rule, + host, + effectiveHosts, + deps.keys, + deps.identities, + undefined, + false, + deps.terminalSettings, + ); + if (!result.success) { + return { ok: false, error: result.error || 'Failed to start port forwarding tunnel.' }; + } + return { ok: true, ruleId }; + } + case 'portforward.stop': { + const ruleId = String(params.ruleId || ''); + const result = await deps.stopTunnel(ruleId); + if (!result.success) { + return { ok: false, error: result.error || 'Failed to stop port forwarding tunnel.' }; + } + return { ok: true, ruleId }; + } + default: + return { ok: false, error: `Unknown vault agent operation "${op}".` }; + } +} + +export type VaultAgentHandler = (op: string, params: Record) => Promise>; + +let activeHandler: VaultAgentHandler | null = null; +let vaultAgentMutationChain: Promise = Promise.resolve(); + +/** Serialize vault agent IPC handlers so read-modify-write mutations cannot clobber each other. */ +export async function runSerializedVaultAgentRequest(task: () => Promise): Promise { + const run = () => task(); + const next = vaultAgentMutationChain.then(run, run); + vaultAgentMutationChain = next.then( + () => undefined, + () => undefined, + ); + return next; +} + +export function registerVaultAgentHandler(handler: VaultAgentHandler | null): void { + activeHandler = handler; +} + +export function setupVaultAgentBridge(): () => void { + const bridge = netcattyBridge.get(); + if (!bridge?.onVaultAgentRequest || !bridge.respondVaultAgent) { + return () => {}; + } + + const unsubscribe = bridge.onVaultAgentRequest(async (payload) => { + const { requestId, op, params } = payload; + await runSerializedVaultAgentRequest(async () => { + try { + const result = activeHandler + ? await activeHandler(op, params || {}) + : { ok: false, error: 'Vault agent bridge is not ready.' }; + await bridge.respondVaultAgent?.(requestId, result); + } catch (err) { + await bridge.respondVaultAgent?.(requestId, { + ok: false, + error: err instanceof Error ? err.message : String(err), + }); + } + }); + }); + + return unsubscribe; +} diff --git a/infrastructure/config/storageKeys.ts b/infrastructure/config/storageKeys.ts index 3b6a474e0..18097c490 100644 --- a/infrastructure/config/storageKeys.ts +++ b/infrastructure/config/storageKeys.ts @@ -156,6 +156,8 @@ export const STORAGE_KEY_AI_AGENT_MODEL_MAP = 'netcatty_ai_agent_model_map_v1'; export const STORAGE_KEY_AI_AGENT_PROVIDER_MAP = 'netcatty_ai_agent_provider_map_v1'; export const STORAGE_KEY_AI_WEB_SEARCH = 'netcatty_ai_web_search_v1'; export const STORAGE_KEY_AI_QUICK_MESSAGES = 'netcatty_ai_quick_messages_v1'; +/** Confirm-mode permission grant memory (capability + session/command patterns). */ +export const STORAGE_KEY_AI_PERMISSION_GRANTS = 'netcatty_ai_permission_grants_v1'; export const STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION = 'netcatty_ai_show_terminal_selection_action_v1'; // SFTP Transfer Concurrency diff --git a/package-lock.json b/package-lock.json index 378bdd3f3..a7f777ccb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -326,29 +326,6 @@ "win32" ] }, - "node_modules/@anthropic-ai/sdk": { - "version": "0.105.0", - "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.105.0.tgz", - "integrity": "sha512-sDyu+aM9cE6uZE+HgRjjHRb+qqb87GHZOx+8bE0YlWetdL1YcVLxn8h9ltxGOflyChTe6PMEo50kMQV4cw0hfg==", - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "json-schema-to-ts": "^3.1.1", - "standardwebhooks": "^1.0.0" - }, - "bin": { - "anthropic-ai-sdk": "bin/cli" - }, - "peerDependencies": { - "zod": "^3.25.0 || ^4.0.0" - }, - "peerDependenciesMeta": { - "zod": { - "optional": true - } - } - }, "node_modules/@aws-crypto/crc32": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/@aws-crypto/crc32/-/crc32-5.2.0.tgz", @@ -1278,6 +1255,7 @@ "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", @@ -1558,14 +1536,6 @@ "node": ">=6.9.0" } }, - "node_modules/@bufbuild/protobuf": { - "version": "1.10.1", - "resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-1.10.1.tgz", - "integrity": "sha512-wJ8ReQbHxsAfXhrf9ixl0aYbZorRuOWpBNzm8pL8ftmSxQx/wnJD5Eg861NwJU/czy2VXFIebCeZnZrI9rktIQ==", - "license": "(Apache-2.0 AND BSD-3-Clause)", - "optional": true, - "peer": true - }, "node_modules/@buttercup/fetch": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/@buttercup/fetch/-/fetch-0.2.1.tgz", @@ -1884,6 +1854,7 @@ "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.3.tgz", "integrity": "sha512-QwCZW6Tt1siP37Jet9Tb02Zs81TQt6qQrZR2H+eGMcFsL1zMrk2/b9CLC7/9ieP1fjIUMgviLWMmgiHoJrj+ZA==", "license": "MIT", + "peer": true, "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.23.0", @@ -1973,6 +1944,7 @@ "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.6.0.tgz", "integrity": "sha512-4nbvra5R5EtiCzr9BTHiTLc+MLXK2QGiAVYMyi8PkQd3SR+6ixar/Q/01Fa21TBIDOZXgeWV4WppsQolSreAPQ==", "license": "MIT", + "peer": true, "dependencies": { "@marijn/find-cluster-break": "^1.0.0" } @@ -1982,6 +1954,7 @@ "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.1.tgz", "integrity": "sha512-+BIjw/AG3tDQ4pJgTLPYdAW25eDE66YsvM4LKyVPgGzVgZ4a9Wj1SRX8kPVKgBDdPt8oHtZ15F0qx7p0oOHdHw==", "license": "MIT", + "peer": true, "dependencies": { "@codemirror/state": "^6.6.0", "crelt": "^1.0.6", @@ -1989,16 +1962,6 @@ "w3c-keyname": "^2.2.4" } }, - "node_modules/@connectrpc/connect": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/@connectrpc/connect/-/connect-1.7.0.tgz", - "integrity": "sha512-iNKdJRi69YP3mq6AePRT8F/HrxWCewrhxnLMNm0vpqXAR8biwzRtO6Hjx80C6UvtKJ5sFmffQT7I4Baecz389w==", - "license": "Apache-2.0", - "optional": true, - "peerDependencies": { - "@bufbuild/protobuf": "^1.10.0" - } - }, "node_modules/@connectrpc/connect-node": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/@connectrpc/connect-node/-/connect-node-1.7.0.tgz", @@ -2446,7 +2409,6 @@ "dev": true, "license": "BSD-2-Clause", "optional": true, - "peer": true, "dependencies": { "cross-dirname": "^0.1.0", "debug": "^4.3.4", @@ -2468,7 +2430,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", @@ -3878,6 +3839,7 @@ "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz", "integrity": "sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==", "license": "MIT", + "peer": true, "dependencies": { "@lezer/common": "^1.3.0" } @@ -4160,6 +4122,7 @@ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz", "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==", "license": "MIT", + "peer": true, "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", @@ -7582,8 +7545,7 @@ "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz", "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==", "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/@standard-schema/spec": { "version": "1.1.0", @@ -8193,6 +8155,7 @@ "integrity": "sha512-hAAP5io/7csFStuOmR782YmTthKBJ9ND3WVL60hcOjvtGFb+HJxH4O5huAcmcZ9v9G8P+JETiZ/G1B8MALnWZQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.54.0", @@ -8222,6 +8185,7 @@ "integrity": "sha512-BtE0k6cjwjLZoZixN0t5AKP0kSzlGu7FctRXYuPAm//aaiZhmfq1JwdYpYr1brzEspYyFeF+8XF5j2VK6oalrA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.54.0", "@typescript-eslint/types": "8.54.0", @@ -8575,6 +8539,7 @@ "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.1.0-beta.220.tgz", "integrity": "sha512-rwEKE75wfwfNWeGnjl0iQRA1W50HigKoGcGMeF3o5CqDSdI9IjmwzpV9xHXqLH6CYj6s9N1g6bbKFVDou9dJ/A==", "license": "MIT", + "peer": true, "workspaces": [ "addons/*" ] @@ -8639,6 +8604,7 @@ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "license": "MIT", + "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -9340,6 +9306,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", @@ -10165,8 +10132,7 @@ "integrity": "sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q==", "dev": true, "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/cross-env": { "version": "10.1.0", @@ -10463,6 +10429,7 @@ "integrity": "sha512-fMkjRqKyPtsz4Kzu/qGP0BGjqzMCIgp+/7kw/u6YH6lvn/8hvL3c0TXhoFayBoYdpPCnEinnCHztd4bW7/jetA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "app-builder-lib": "26.15.2", "builder-util": "26.15.0", @@ -10744,7 +10711,6 @@ "dev": true, "hasInstallScript": true, "license": "MIT", - "peer": true, "dependencies": { "@electron/asar": "^3.2.1", "debug": "^4.1.1", @@ -10765,7 +10731,6 @@ "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "graceful-fs": "^4.1.2", "jsonfile": "^4.0.0", @@ -10781,7 +10746,6 @@ "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", "dev": true, "license": "MIT", - "peer": true, "optionalDependencies": { "graceful-fs": "^4.1.6" } @@ -10792,7 +10756,6 @@ "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">= 4.0.0" } @@ -11017,6 +10980,7 @@ "integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.1", @@ -11470,8 +11434,7 @@ "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz", "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==", "license": "Unlicense", - "optional": true, - "peer": true + "optional": true }, "node_modules/fast-uri": { "version": "3.1.0", @@ -12408,6 +12371,7 @@ "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.14.tgz", "integrity": "sha512-am5zfg3yu6sqn5yjKBNqhnTX7Cv+m00ox+7jbaKkrLMRJ4rAdldd1xPd/JzbBWspqaQv6RSTrgFN95EsfhC+7w==", "license": "MIT", + "peer": true, "engines": { "node": ">=16.9.0" } @@ -12864,7 +12828,6 @@ "resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz", "integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==", "license": "MIT", - "peer": true, "funding": { "type": "GitHub Sponsors ❤", "url": "https://github.com/sponsors/dmonad" @@ -12986,7 +12949,6 @@ "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", "license": "MIT", "optional": true, - "peer": true, "dependencies": { "@babel/runtime": "^7.18.3", "ts-algebra": "^2.0.0" @@ -13144,7 +13106,6 @@ "resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.117.tgz", "integrity": "sha512-DeXj9X5xDCjgKLU/7RR+/HQEVzuuEUiwldwOGsHK/sfAfELGWEyTcf0x+uOvCvK3O2zPmZePXWL85vtia6GyZw==", "license": "MIT", - "peer": true, "dependencies": { "isomorphic.js": "^0.2.4" }, @@ -14090,6 +14051,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", @@ -15210,7 +15172,6 @@ "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "minimist": "^1.2.6" }, @@ -15230,6 +15191,7 @@ "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.55.1.tgz", "integrity": "sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A==", "license": "MIT", + "peer": true, "dependencies": { "dompurify": "3.2.7", "marked": "14.0.0" @@ -15980,7 +15942,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "commander": "^9.4.0" }, @@ -15998,7 +15959,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": "^12.20.0 || >=14" } @@ -16303,6 +16263,7 @@ "resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz", "integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==", "license": "MIT", + "peer": true, "engines": { "node": ">=0.10.0" } @@ -16312,6 +16273,7 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz", "integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==", "license": "MIT", + "peer": true, "dependencies": { "scheduler": "^0.27.0" }, @@ -17649,7 +17611,6 @@ "integrity": "sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==", "license": "MIT", "optional": true, - "peer": true, "dependencies": { "@stablelib/base64": "^1.0.0", "fast-sha256": "^1.3.0" @@ -17955,7 +17916,6 @@ "integrity": "sha512-yYrrsWnrXMcdsnu/7YMYAofM1ktpL5By7vZhf15CrXijWWrEYZks5AXBudalfSWJLlnen/QUJUB5aoB0kqZUGA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "mkdirp": "^0.5.1", "rimraf": "~2.6.2" @@ -17982,7 +17942,6 @@ "deprecated": "Rimraf versions prior to v4 are no longer supported", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "glob": "^7.1.3" }, @@ -18057,6 +18016,7 @@ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -18151,8 +18111,7 @@ "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/ts-api-utils": { "version": "2.4.0", @@ -18179,6 +18138,7 @@ "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "esbuild": "~0.27.0", "get-tsconfig": "^4.7.5" @@ -18290,6 +18250,7 @@ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -18330,6 +18291,7 @@ "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz", "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==", "license": "MIT", + "peer": true, "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", @@ -18705,6 +18667,7 @@ "integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", @@ -18798,6 +18761,7 @@ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -19085,6 +19049,7 @@ "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", "license": "MIT", + "peer": true, "funding": { "url": "https://github.com/sponsors/colinhacks" } diff --git a/package.json b/package.json index 8ed8b167a..cab4c4062 100644 --- a/package.json +++ b/package.json @@ -33,9 +33,10 @@ "postinstall": "electron-builder install-app-deps && patch-package && node scripts/patch-xterm-webgl-atlas.cjs", "rebuild": "electron-builder install-app-deps", "tool:cli": "node electron/cli/netcatty-tool-cli.cjs", + "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/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/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-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", diff --git a/scripts/generate-capability-tools.cjs b/scripts/generate-capability-tools.cjs new file mode 100644 index 000000000..5a3aa9ec5 --- /dev/null +++ b/scripts/generate-capability-tools.cjs @@ -0,0 +1,27 @@ +#!/usr/bin/env node +"use strict"; + +const fs = require("node:fs"); +const path = require("node:path"); +const { AGENT_KINDS, listAgentToolSpecs, listCattyToolSpecs } = require("../electron/capabilities/codegen/toolSurfaces.cjs"); + +const generatedDir = path.join( + __dirname, + "../infrastructure/ai/harness/generated", +); + +function writeSpecs(filename, specs) { + const outputPath = path.join(generatedDir, filename); + fs.mkdirSync(path.dirname(outputPath), { recursive: true }); + fs.writeFileSync(outputPath, `${JSON.stringify(specs, null, 2)}\n`, "utf8"); + return { outputPath, count: specs.length }; +} + +const sidebar = writeSpecs("cattyToolSpecs.json", listCattyToolSpecs()); +const globalAgent = writeSpecs( + "globalAgentToolSpecs.json", + listAgentToolSpecs(AGENT_KINDS.GLOBAL), +); + +process.stdout.write(`Wrote ${sidebar.count} sidebar tool specs to ${sidebar.outputPath}\n`); +process.stdout.write(`Wrote ${globalAgent.count} global agent tool specs to ${globalAgent.outputPath}\n`); diff --git a/scripts/generate-capability-tools.test.cjs b/scripts/generate-capability-tools.test.cjs new file mode 100644 index 000000000..cb4e19a6b --- /dev/null +++ b/scripts/generate-capability-tools.test.cjs @@ -0,0 +1,33 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); + +const { AGENT_KINDS, listAgentToolSpecs, listCattyToolSpecs } = require("../electron/capabilities/codegen/toolSurfaces.cjs"); + +const GENERATED_DIR = path.join( + __dirname, + "..", + "infrastructure", + "ai", + "harness", + "generated", +); + +test("committed cattyToolSpecs.json matches listCattyToolSpecs()", () => { + const committed = JSON.parse( + fs.readFileSync(path.join(GENERATED_DIR, "cattyToolSpecs.json"), "utf8"), + ); + const fresh = listCattyToolSpecs(); + assert.deepEqual(committed, fresh); +}); + +test("committed globalAgentToolSpecs.json matches listAgentToolSpecs(global)", () => { + const committed = JSON.parse( + fs.readFileSync(path.join(GENERATED_DIR, "globalAgentToolSpecs.json"), "utf8"), + ); + const fresh = listAgentToolSpecs(AGENT_KINDS.GLOBAL); + assert.deepEqual(committed, fresh); +}); diff --git a/types/global/netcatty-bridge-ai.d.ts b/types/global/netcatty-bridge-ai.d.ts index dff132ef7..942285bc7 100644 --- a/types/global/netcatty-bridge-ai.d.ts +++ b/types/global/netcatty-bridge-ai.d.ts @@ -94,6 +94,7 @@ declare global { }>; aiMcpUpdateSessions?(sessions: Array<{ sessionId: string; + hostId?: string; hostname: string; label: string; os?: string; @@ -102,7 +103,11 @@ declare global { shellType?: string; deviceType?: string; connected: boolean; + hostChain?: Array<{ hostId: string; label?: string; hostname?: string }>; + activePortForwards?: Array<{ ruleId: string; label?: string; type?: string; localPort?: number; status?: string }>; }>, chatSessionId?: string): Promise<{ ok: boolean }>; + onVaultAgentRequest?(cb: (payload: { requestId: string; op: string; params: Record }) => void): () => void; + respondVaultAgent?(requestId: string, result: Record): Promise<{ ok: boolean; error?: string }>; aiMcpSetToolIntegrationMode?(mode: 'mcp' | 'skills'): Promise<{ ok: boolean; error?: string }>; aiUserSkillsGetStatus?(): Promise<{ ok: boolean; @@ -149,6 +154,9 @@ declare global { }>; aiSdkAgentStream?(requestId: string, chatSessionId: string, sdkBackend: string, prompt: string, cwd?: string, providerId?: string, model?: string, existingSessionId?: string, historyMessages?: Array<{ role: 'user' | 'assistant'; content: string }>, images?: Array<{ base64Data: string; mediaType: string; filename?: string; filePath?: string }>, toolIntegrationMode?: 'mcp' | 'skills', defaultTargetSession?: { sessionId: string; hostname: string; label: string; os?: string; username?: string; protocol?: string; shellType?: string; deviceType?: string; connected: boolean; source: 'scope-target' | 'only-connected-in-scope' }, userSkillsContext?: string, agentEnv?: Record, agentCommand?: string): Promise<{ ok: boolean; error?: string }>; aiSdkAgentListModels?(sdkBackend: string, cwd?: string, providerId?: string, chatSessionId?: string, agentEnv?: Record, agentCommand?: string): Promise<{ ok: boolean; models?: Array<{ id: string; name: string; description?: string; thinkingLevels?: string[] }>; currentModelId?: string | null; error?: string }>; + aiCattyCancelExec?(chatSessionId: string): Promise; + aiSetChatSessionCancelled?(chatSessionId: string, cancelled?: boolean): Promise<{ ok: boolean; error?: string }>; + aiMcpSyncPermissionGrants?(grants: Array>): Promise<{ ok: boolean; count?: number; error?: string }>; aiSdkAgentCancel?(requestId: string, chatSessionId?: string): Promise<{ ok: boolean; error?: string }>; aiSdkAgentCleanup?(chatSessionId: string): Promise<{ ok: boolean }>; onAiSdkAgentEvent?(requestId: string, cb: (event: Record) => void): () => void; From 0c8370477cd6aff381afde9c54400c68121d1226 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 00:26:30 +0800 Subject: [PATCH 059/228] Unify AI permission auto mode (#1688) --- application/i18n/locales/en/ai.ts | 2 +- application/i18n/locales/ru/ai.ts | 2 +- application/i18n/locales/zh-CN/ai.ts | 4 +- application/state/useAISettingsState.ts | 2 +- application/state/useAIState.ts | 6 +-- application/syncPayload.test.ts | 4 +- application/syncPayload.ts | 2 +- .../AIChatSidePanel.mountRetention.test.ts | 38 ++++++++++++++++++- components/ai/ChatInput.tsx | 8 ++-- .../settings/tabs/ai/SafetySettings.tsx | 2 +- domain/sync.ts | 2 +- .../bridges/aiBridge/agentProcessHandlers.cjs | 2 +- electron/bridges/mcpServerBridge.cjs | 4 +- .../capabilityRpcDispatch.test.cjs | 4 +- electron/capabilities/constants.cjs | 4 +- electron/capabilities/policy.cjs | 2 +- electron/capabilities/policy.test.cjs | 8 ++-- electron/mcp/netcatty-mcp-server.cjs | 4 +- infrastructure/ai/cattyAgent/systemPrompt.ts | 12 +++--- infrastructure/ai/types.ts | 2 +- 20 files changed, 75 insertions(+), 39 deletions(-) diff --git a/application/i18n/locales/en/ai.ts b/application/i18n/locales/en/ai.ts index 293eab56f..0f2e76f24 100644 --- a/application/i18n/locales/en/ai.ts +++ b/application/i18n/locales/en/ai.ts @@ -315,7 +315,7 @@ export const enAiMessages: Messages = { 'ai.safety.permissionMode.description': 'Controls how the AI interacts with your Netcatty terminal sessions. Observer mode blocks write operations that go through Netcatty. External agent CLIs may still have their own local tools and approval flow.', 'ai.safety.permissionMode.observer': 'Observer - Read only, no actions', 'ai.safety.permissionMode.confirm': 'Confirm - Ask before actions', - 'ai.safety.permissionMode.autonomous': 'Autonomous - Execute freely', + 'ai.safety.permissionMode.auto': 'Auto - Execute freely', 'ai.safety.commandTimeout': 'Command Timeout', 'ai.safety.commandTimeout.description': 'Maximum seconds a command can run before being terminated through Netcatty execution.', 'ai.safety.commandTimeout.unit': 'sec', diff --git a/application/i18n/locales/ru/ai.ts b/application/i18n/locales/ru/ai.ts index 26fb1d07f..bf2c3ec7e 100644 --- a/application/i18n/locales/ru/ai.ts +++ b/application/i18n/locales/ru/ai.ts @@ -303,7 +303,7 @@ export const ruAiMessages: Messages = { 'ai.safety.permissionMode.description': 'Управляет тем, как AI взаимодействует с вашими терминалами. Режим наблюдателя блокирует все операции записи через Netcatty и применяется как к встроенным, так и к внешним агентам. Режим подтверждения носит рекомендательный характер для внешних агентов (они управляют собственным потоком одобрения инструментов).', 'ai.safety.permissionMode.observer': 'Наблюдатель — только чтение, без действий', 'ai.safety.permissionMode.confirm': 'Подтверждение — спрашивать перед действиями', - 'ai.safety.permissionMode.autonomous': 'Автономный — выполнять свободно', + 'ai.safety.permissionMode.auto': 'Авто — выполнять свободно', 'ai.safety.commandTimeout': 'Тайм-аут команды', 'ai.safety.commandTimeout.description': 'Максимальное число секунд, которое команда может выполняться до принудительного завершения. Применяется как к встроенным, так и к внешним агентам.', 'ai.safety.commandTimeout.unit': 'с', diff --git a/application/i18n/locales/zh-CN/ai.ts b/application/i18n/locales/zh-CN/ai.ts index 4650c9d33..9b46d8882 100644 --- a/application/i18n/locales/zh-CN/ai.ts +++ b/application/i18n/locales/zh-CN/ai.ts @@ -247,7 +247,7 @@ export const zhCNAiMessages: Messages = { 'ai.chat.rescan': '重新扫描', 'ai.chat.permObserver': '观察', 'ai.chat.permConfirm': '确认', - 'ai.chat.permAuto': '自主', + 'ai.chat.permAuto': '自动', 'ai.chat.permObserverDesc': '只读模式', 'ai.chat.permConfirmDesc': '操作前询问', 'ai.chat.permAutoDesc': '自由执行', @@ -315,7 +315,7 @@ export const zhCNAiMessages: Messages = { 'ai.safety.permissionMode.description': '控制 AI 通过 Netcatty 访问终端会话的方式。观察者模式会阻止经由 Netcatty 的写操作;外部 Agent CLI 可能仍有自己的本机工具和审批流程。', 'ai.safety.permissionMode.observer': '观察者 - 只读,禁止操作', 'ai.safety.permissionMode.confirm': '确认 - 操作前询问', - 'ai.safety.permissionMode.autonomous': '自主 - 自由执行', + 'ai.safety.permissionMode.auto': '自动 - 自由执行', 'ai.safety.commandTimeout': '命令超时', 'ai.safety.commandTimeout.description': '通过 Netcatty 执行命令时允许运行的最长秒数,超时将被终止。', 'ai.safety.commandTimeout.unit': '秒', diff --git a/application/state/useAISettingsState.ts b/application/state/useAISettingsState.ts index 601977c20..828557c0d 100644 --- a/application/state/useAISettingsState.ts +++ b/application/state/useAISettingsState.ts @@ -34,7 +34,7 @@ import { useStoredBoolean } from './useStoredBoolean'; function readPermissionMode(): AIPermissionMode { const stored = localStorageAdapter.readString(STORAGE_KEY_AI_PERMISSION_MODE); - if (stored === 'observer' || stored === 'confirm' || stored === 'autonomous') return stored; + if (stored === 'observer' || stored === 'confirm' || stored === 'auto') return stored; return 'confirm'; } diff --git a/application/state/useAIState.ts b/application/state/useAIState.ts index 7c8c24719..536568bad 100644 --- a/application/state/useAIState.ts +++ b/application/state/useAIState.ts @@ -83,7 +83,7 @@ export function useAIState() { // ── Permission Model ── const [globalPermissionMode, setGlobalPermissionModeRaw] = useState(() => { const stored = localStorageAdapter.readString(STORAGE_KEY_AI_PERMISSION_MODE); - if (stored === 'observer' || stored === 'confirm' || stored === 'autonomous') return stored; + if (stored === 'observer' || stored === 'confirm' || stored === 'auto') return stored; return 'confirm'; }); const [toolIntegrationMode, setToolIntegrationModeRaw] = useState(() => { @@ -399,7 +399,7 @@ export function useAIState() { break; case STORAGE_KEY_AI_PERMISSION_MODE: { const mode = localStorageAdapter.readString(STORAGE_KEY_AI_PERMISSION_MODE); - if (mode === 'observer' || mode === 'confirm' || mode === 'autonomous') { + if (mode === 'observer' || mode === 'confirm' || mode === 'auto') { setGlobalPermissionModeRaw(mode); getAIBridge()?.aiMcpSetPermissionMode?.(mode); } @@ -545,7 +545,7 @@ export function useAIState() { bridge?.aiMcpSetMaxIterations?.(initialMaxIter); const storedPermMode = localStorageAdapter.readString(STORAGE_KEY_AI_PERMISSION_MODE); const initialPermMode: AIPermissionMode = - storedPermMode === 'observer' || storedPermMode === 'confirm' || storedPermMode === 'autonomous' + storedPermMode === 'observer' || storedPermMode === 'confirm' || storedPermMode === 'auto' ? storedPermMode : 'confirm'; bridge?.aiMcpSetPermissionMode?.(initialPermMode); diff --git a/application/syncPayload.test.ts b/application/syncPayload.test.ts index df7b9dc6d..59fc87106 100644 --- a/application/syncPayload.test.ts +++ b/application/syncPayload.test.ts @@ -143,7 +143,7 @@ test("buildSyncPayload includes AI configuration settings", () => { localStorage.setItem(storageKeys.STORAGE_KEY_AI_PROVIDERS, JSON.stringify(providers)); localStorage.setItem(storageKeys.STORAGE_KEY_AI_ACTIVE_PROVIDER, "openai-main"); localStorage.setItem(storageKeys.STORAGE_KEY_AI_ACTIVE_MODEL, "gpt-test"); - localStorage.setItem(storageKeys.STORAGE_KEY_AI_PERMISSION_MODE, "autonomous"); + localStorage.setItem(storageKeys.STORAGE_KEY_AI_PERMISSION_MODE, "auto"); localStorage.setItem(storageKeys.STORAGE_KEY_AI_TOOL_INTEGRATION_MODE, "skills"); localStorage.setItem(storageKeys.STORAGE_KEY_AI_DEFAULT_AGENT, "codex"); localStorage.setItem(storageKeys.STORAGE_KEY_AI_COMMAND_BLOCKLIST, JSON.stringify(["rm -rf"])); @@ -160,7 +160,7 @@ test("buildSyncPayload includes AI configuration settings", () => { providers, activeProviderId: "openai-main", activeModelId: "gpt-test", - globalPermissionMode: "autonomous", + globalPermissionMode: "auto", toolIntegrationMode: "skills", defaultAgentId: "codex", commandBlocklist: ["rm -rf"], diff --git a/application/syncPayload.ts b/application/syncPayload.ts index b90e17125..cf49305fd 100644 --- a/application/syncPayload.ts +++ b/application/syncPayload.ts @@ -466,7 +466,7 @@ export function collectSyncableSettings(): SyncPayload['settings'] { const activeModelId = localStorageAdapter.readString(STORAGE_KEY_AI_ACTIVE_MODEL); if (activeModelId != null) ai.activeModelId = activeModelId; const permissionMode = localStorageAdapter.readString(STORAGE_KEY_AI_PERMISSION_MODE); - if (permissionMode === 'observer' || permissionMode === 'confirm' || permissionMode === 'autonomous') { + if (permissionMode === 'observer' || permissionMode === 'confirm' || permissionMode === 'auto') { ai.globalPermissionMode = permissionMode; } const toolIntegrationMode = localStorageAdapter.readString(STORAGE_KEY_AI_TOOL_INTEGRATION_MODE); diff --git a/components/AIChatSidePanel.mountRetention.test.ts b/components/AIChatSidePanel.mountRetention.test.ts index 116755b8c..fd3bdc64b 100644 --- a/components/AIChatSidePanel.mountRetention.test.ts +++ b/components/AIChatSidePanel.mountRetention.test.ts @@ -14,6 +14,42 @@ import { } from './AIChatSidePanel.tsx'; import type { AIChatSidePanelProps } from './AIChatSidePanel.types.ts'; +type LocalStorageMock = { + clear(): void; + getItem(key: string): string | null; + setItem(key: string, value: string): void; + removeItem(key: string): void; +}; + +function installLocalStorage(): LocalStorageMock { + const store = new Map(); + const localStorage: LocalStorageMock = { + clear() { + store.clear(); + }, + getItem(key: string) { + return store.has(key) ? store.get(key)! : null; + }, + setItem(key: string, value: string) { + store.set(key, String(value)); + }, + removeItem(key: string) { + store.delete(key); + }, + }; + Object.defineProperty(globalThis, 'localStorage', { + value: localStorage, + configurable: true, + }); + return localStorage; +} + +const localStorage = installLocalStorage(); + +test.beforeEach(() => { + localStorage.clear(); +}); + const draft = (overrides: Partial = {}): AIDraft => ({ text: '', agentId: 'catty', @@ -64,7 +100,7 @@ const baseProps = (overrides: Partial = {}): AIChatSidePan setAgentModel: () => undefined, agentProviderMap: {}, setAgentProvider: () => undefined, - globalPermissionMode: 'autonomous', + globalPermissionMode: 'auto', scopeType: 'terminal', scopeTargetId: 'terminal-1', isVisible: false, diff --git a/components/ai/ChatInput.tsx b/components/ai/ChatInput.tsx index cc6a9e943..efbf01f40 100644 --- a/components/ai/ChatInput.tsx +++ b/components/ai/ChatInput.tsx @@ -472,7 +472,7 @@ const ChatInput: React.FC = ({ const status: PromptInputStatus = isStreaming ? 'streaming' : 'idle'; - // Permission mode chip removed — agents run in autonomous mode + // Permission mode chip removed — agents run in auto mode // selectedModelId may be "/" for codex ChatGPT models // (e.g. "gpt-5.4/high"). Note: custom config.toml / OpenRouter model ids @@ -1009,11 +1009,11 @@ const ChatInput: React.FC = ({ > {permissionMode === 'observer' && } {permissionMode === 'confirm' && } - {permissionMode === 'autonomous' && } + {permissionMode === 'auto' && } {permissionMode === 'observer' && t('ai.chat.permObserver')} {permissionMode === 'confirm' && t('ai.chat.permConfirm')} - {permissionMode === 'autonomous' && t('ai.chat.permAuto')} + {permissionMode === 'auto' && t('ai.chat.permAuto')} @@ -1031,7 +1031,7 @@ const ChatInput: React.FC = ({ style={{ left: menuPos.left, bottom: menuPos.bottom }} > {([ - { mode: 'autonomous' as const, icon: Zap, color: 'text-green-400/70', label: t('ai.chat.permAuto'), desc: t('ai.chat.permAutoDesc') }, + { mode: 'auto' as const, icon: Zap, color: 'text-green-400/70', label: t('ai.chat.permAuto'), desc: t('ai.chat.permAutoDesc') }, { mode: 'confirm' as const, icon: ShieldCheck, color: 'text-yellow-400/70', label: t('ai.chat.permConfirm'), desc: t('ai.chat.permConfirmDesc') }, { mode: 'observer' as const, icon: Eye, color: 'text-blue-400/70', label: t('ai.chat.permObserver'), desc: t('ai.chat.permObserverDesc') }, ]).map(({ mode, icon: Icon, color, label, desc }) => ( diff --git a/components/settings/tabs/ai/SafetySettings.tsx b/components/settings/tabs/ai/SafetySettings.tsx index f82ac9571..d370c8fbf 100644 --- a/components/settings/tabs/ai/SafetySettings.tsx +++ b/components/settings/tabs/ai/SafetySettings.tsx @@ -64,7 +64,7 @@ export const SafetySettings: React.FC<{ const permissionModeOptions = [ { value: "observer", label: t('ai.safety.permissionMode.observer') }, { value: "confirm", label: t('ai.safety.permissionMode.confirm') }, - { value: "autonomous", label: t('ai.safety.permissionMode.autonomous') }, + { value: "auto", label: t('ai.safety.permissionMode.auto') }, ]; return ( diff --git a/domain/sync.ts b/domain/sync.ts index c6c82e4bd..e0bf0194d 100644 --- a/domain/sync.ts +++ b/domain/sync.ts @@ -264,7 +264,7 @@ export interface SyncPayload { providers?: Array>; activeProviderId?: string; activeModelId?: string; - globalPermissionMode?: 'observer' | 'confirm' | 'autonomous'; + globalPermissionMode?: 'observer' | 'confirm' | 'auto'; toolIntegrationMode?: 'mcp' | 'skills'; hostPermissions?: Array>; // externalAgents intentionally omitted: command/args/env are device-local diff --git a/electron/bridges/aiBridge/agentProcessHandlers.cjs b/electron/bridges/aiBridge/agentProcessHandlers.cjs index 97feb98d4..0d217f328 100644 --- a/electron/bridges/aiBridge/agentProcessHandlers.cjs +++ b/electron/bridges/aiBridge/agentProcessHandlers.cjs @@ -51,7 +51,7 @@ function registerAgentProcessHandlers(ctx) { ipcMain.handle("netcatty:ai:mcp:set-permission-mode", async (event, { mode }) => { if (!validateSenderOrSettings(event)) return { ok: false, error: "Unauthorized IPC sender" }; - const validModes = ["observer", "confirm", "autonomous"]; + const validModes = ["observer", "confirm", "auto"]; if (!validModes.includes(mode)) { return { ok: false, error: `mode must be one of: ${validModes.join(", ")}` }; } diff --git a/electron/bridges/mcpServerBridge.cjs b/electron/bridges/mcpServerBridge.cjs index 2a66e94c3..f721fefbf 100644 --- a/electron/bridges/mcpServerBridge.cjs +++ b/electron/bridges/mcpServerBridge.cjs @@ -54,7 +54,7 @@ let commandTimeoutMs = 60000; // Max iterations for AI agent loops (default 20, synced from user settings) let maxIterations = 20; -// Permission mode: 'observer' | 'confirm' | 'autonomous' (synced from user settings) +// Permission mode: 'observer' | 'confirm' | 'auto' (synced from user settings) let permissionMode = "confirm"; // Cached permission grants synced from renderer (confirm-mode memory table) @@ -349,7 +349,7 @@ function getMaxIterations() { } function setPermissionMode(mode) { - if (mode === "observer" || mode === "confirm" || mode === "autonomous") { + if (mode === "observer" || mode === "confirm" || mode === "auto") { permissionMode = mode; writeCliDiscoveryFile(); } diff --git a/electron/bridges/mcpServerBridge/capabilityRpcDispatch.test.cjs b/electron/bridges/mcpServerBridge/capabilityRpcDispatch.test.cjs index 9d0e809ac..2080a022d 100644 --- a/electron/bridges/mcpServerBridge/capabilityRpcDispatch.test.cjs +++ b/electron/bridges/mcpServerBridge/capabilityRpcDispatch.test.cjs @@ -175,10 +175,10 @@ test("dispatchCapabilityRpc reads permissionMode from deps on each call", async }); await liveDispatch("vault/host/get", { hostId: "host-1" }); - mutableDeps.permissionMode = PERMISSION_MODES.AUTONOMOUS; + mutableDeps.permissionMode = PERMISSION_MODES.AUTO; await liveDispatch("vault/host/get", { hostId: "host-2" }); - assert.deepEqual(seenModes, [PERMISSION_MODES.CONFIRM, PERMISSION_MODES.AUTONOMOUS]); + assert.deepEqual(seenModes, [PERMISSION_MODES.CONFIRM, PERMISSION_MODES.AUTO]); }); test("implemented vault capabilities do not return CAPABILITY_NOT_IMPLEMENTED", async () => { diff --git a/electron/capabilities/constants.cjs b/electron/capabilities/constants.cjs index 48d5bc0d0..df20bb76e 100644 --- a/electron/capabilities/constants.cjs +++ b/electron/capabilities/constants.cjs @@ -2,7 +2,7 @@ /** @typedef {'builtin' | 'public' | 'cli' | 'global' | 'catty' | 'globalAgent'} CapabilitySurface */ /** @typedef {'implemented' | 'planned'} CapabilityStatus */ -/** @typedef {'observer' | 'confirm' | 'autonomous'} PermissionMode */ +/** @typedef {'observer' | 'confirm' | 'auto'} PermissionMode */ /** @typedef {'sidebar' | 'global'} AgentKind */ const CAPABILITY_SURFACES = Object.freeze({ @@ -32,7 +32,7 @@ const CAPABILITY_STATUS = Object.freeze({ const PERMISSION_MODES = Object.freeze({ OBSERVER: "observer", CONFIRM: "confirm", - AUTONOMOUS: "autonomous", + AUTO: "auto", }); const RPC_TIMEOUT_DEFAULTS = Object.freeze({ diff --git a/electron/capabilities/policy.cjs b/electron/capabilities/policy.cjs index 927cde9eb..3449cb7ce 100644 --- a/electron/capabilities/policy.cjs +++ b/electron/capabilities/policy.cjs @@ -3,7 +3,7 @@ const { CAPABILITY_SURFACES, PERMISSION_MODES } = require("./constants.cjs"); const { getCapabilityByRpcMethod } = require("./registry.cjs"); -const OBSERVER_DENY_MESSAGE = 'Operation denied: permission mode is "observer" (read-only). Change to "confirm" or "autonomous" in Settings → AI → Safety to allow this action.'; +const OBSERVER_DENY_MESSAGE = 'Operation denied: permission mode is "observer" (read-only). Change to "confirm" or "auto" in Settings → AI → Safety to allow this action.'; const CHAT_SESSION_REQUIRED_MESSAGE = "chatSessionId is required for write operations."; const CHAT_SESSION_CANCELLED_MESSAGE = "Operation cancelled: the SDK agent session was stopped."; const USER_DENIED_MESSAGE = "Operation denied by user."; diff --git a/electron/capabilities/policy.test.cjs b/electron/capabilities/policy.test.cjs index ec6230c17..268e9ba9a 100644 --- a/electron/capabilities/policy.test.cjs +++ b/electron/capabilities/policy.test.cjs @@ -87,7 +87,7 @@ test("public surface treats sensitive reads as confirm-gated", () => { test("write operations require chatSessionId on builtin surface", () => { const decision = evaluateRpcPermission({ rpcMethod: "netcatty/exec", - permissionMode: PERMISSION_MODES.AUTONOMOUS, + permissionMode: PERMISSION_MODES.AUTO, params: {}, }); assert.equal(decision.allowed, false); @@ -97,7 +97,7 @@ test("write operations require chatSessionId on builtin surface", () => { test("cancelled chat sessions block terminal writes", () => { const decision = evaluateRpcPermission({ rpcMethod: "netcatty/exec", - permissionMode: PERMISSION_MODES.AUTONOMOUS, + permissionMode: PERMISSION_MODES.AUTO, params: { chatSessionId: "chat-1" }, context: { chatSessionCancelled: true }, }); @@ -108,7 +108,7 @@ test("cancelled chat sessions block terminal writes", () => { test("cancelled chat sessions block sftp writes", () => { const decision = evaluateRpcPermission({ rpcMethod: "netcatty/sftp/write", - permissionMode: PERMISSION_MODES.AUTONOMOUS, + permissionMode: PERMISSION_MODES.AUTO, params: { chatSessionId: "chat-1" }, context: { chatSessionCancelled: true }, }); @@ -119,7 +119,7 @@ test("cancelled chat sessions block sftp writes", () => { test("cancelled chat sessions still allow sftp reads", () => { const decision = evaluateRpcPermission({ rpcMethod: "netcatty/sftp/list", - permissionMode: PERMISSION_MODES.AUTONOMOUS, + permissionMode: PERMISSION_MODES.AUTO, params: { chatSessionId: "chat-1" }, context: { chatSessionCancelled: true }, }); diff --git a/electron/mcp/netcatty-mcp-server.cjs b/electron/mcp/netcatty-mcp-server.cjs index be72fec20..debf1f140 100644 --- a/electron/mcp/netcatty-mcp-server.cjs +++ b/electron/mcp/netcatty-mcp-server.cjs @@ -56,7 +56,7 @@ const SCOPED_SESSION_IDS = process.env.NETCATTY_MCP_SESSION_IDS != null // Chat session ID for per-scope metadata isolation const CHAT_SESSION_ID = process.env.NETCATTY_MCP_CHAT_SESSION_ID || null; -// Permission mode: 'observer' | 'confirm' | 'autonomous' (defense-in-depth, TCP bridge also checks) +// Permission mode: 'observer' | 'confirm' | 'auto' (defense-in-depth, TCP bridge also checks) const PERMISSION_MODE = process.env.NETCATTY_MCP_PERMISSION_MODE || "confirm"; // Default command blocklist (defense-in-depth, TCP bridge also checks) @@ -84,7 +84,7 @@ function checkCommandSafety(command) { /** Guard for write tools: blocks in observer mode, optionally checks command safety. */ function guardWriteOperation(command, { skipBlocklist = false } = {}) { if (PERMISSION_MODE === "observer") { - return 'Operation denied: permission mode is "observer" (read-only). Change to "confirm" or "autonomous" in Settings → AI → Safety to allow this action.'; + return 'Operation denied: permission mode is "observer" (read-only). Change to "confirm" or "auto" in Settings → AI → Safety to allow this action.'; } // When skipBlocklist is true, the caller relies on the TCP bridge layer for // session-aware blocklist checks (e.g. serial and network device sessions skip shell patterns). diff --git a/infrastructure/ai/cattyAgent/systemPrompt.ts b/infrastructure/ai/cattyAgent/systemPrompt.ts index 4841c7911..0ceba989f 100644 --- a/infrastructure/ai/cattyAgent/systemPrompt.ts +++ b/infrastructure/ai/cattyAgent/systemPrompt.ts @@ -21,7 +21,7 @@ export interface SystemPromptContext { status?: string; }>; }>; - permissionMode: 'observer' | 'confirm' | 'autonomous'; + permissionMode: 'observer' | 'confirm' | 'auto'; webSearchEnabled?: boolean; userSkillsContext?: string; } @@ -151,7 +151,7 @@ function buildHostList( } function buildPermissionRules( - permissionMode: 'observer' | 'confirm' | 'autonomous', + permissionMode: 'observer' | 'confirm' | 'auto', ): string { switch (permissionMode) { case 'observer': @@ -161,7 +161,7 @@ function buildPermissionRules( '- Fetching URLs (`url_fetch`)', '- Searching the web (`web_search`)', '', - 'All write and execute operations are denied. If the user asks you to run a command or modify a file, explain that observer mode does not allow it and suggest switching to confirm or autonomous mode.', + 'All write and execute operations are denied. If the user asks you to run a command or modify a file, explain that observer mode does not allow it and suggest switching to confirm or auto mode.', ].join('\n'); case 'confirm': @@ -172,11 +172,11 @@ function buildPermissionRules( 'You do NOT need to ask the user for confirmation in your text responses. Just call the tool directly — the approval system handles it. Read-only operations are allowed without any approval.', ].join('\n'); - case 'autonomous': + case 'auto': return [ - 'You are in **autonomous** mode. You may execute commands and write files without explicit per-action approval, as long as they are not on the blocklist.', + 'You are in **auto** mode. You may execute commands and write files without explicit per-action approval, as long as they are not on the blocklist.', '', - 'Even in autonomous mode:', + 'Even in auto mode:', '- Always present a plan for multi-step tasks before starting.', '- Blocked commands are still denied regardless of mode.', '- Exercise caution with destructive or irreversible operations.', diff --git a/infrastructure/ai/types.ts b/infrastructure/ai/types.ts index b41786f00..fa25355b1 100644 --- a/infrastructure/ai/types.ts +++ b/infrastructure/ai/types.ts @@ -198,7 +198,7 @@ export interface AISessionScope { } // Permission model -export type AIPermissionMode = 'observer' | 'confirm' | 'autonomous'; +export type AIPermissionMode = 'observer' | 'confirm' | 'auto'; export type AIToolIntegrationMode = 'mcp' | 'skills'; export interface HostAIPermission { From 46d2a6e50a64a9c70931fb3f5d50d0fe803d3d1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 00:44:58 +0800 Subject: [PATCH 060/228] Fit large AI tool outputs before model replay (#1689) * Add generic AI tool output fitting * Preserve explicit tool output readbacks --- .../ai/harness/capabilityTools.test.ts | 65 +++++++++- infrastructure/ai/harness/capabilityTools.ts | 38 +++++- .../ai/harness/toolResultFitting.test.ts | 59 +++++++++ .../ai/harness/toolResultFitting.ts | 121 ++++++++++++++++++ 4 files changed, 278 insertions(+), 5 deletions(-) create mode 100644 infrastructure/ai/harness/toolResultFitting.test.ts create mode 100644 infrastructure/ai/harness/toolResultFitting.ts diff --git a/infrastructure/ai/harness/capabilityTools.test.ts b/infrastructure/ai/harness/capabilityTools.test.ts index 4bd1dae8a..80f0ab97f 100644 --- a/infrastructure/ai/harness/capabilityTools.test.ts +++ b/infrastructure/ai/harness/capabilityTools.test.ts @@ -1,6 +1,7 @@ import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; -import { resolveSessionQueueKeyForTests } from './capabilityTools'; +import { createCattyToolsFromCatalog, resolveSessionQueueKeyForTests } from './capabilityTools'; +import { ToolOutputStore } from './toolOutputStore'; describe('capabilityTools session queue keys', () => { it('does not queue read-only harness tools behind terminal session writes', () => { @@ -29,3 +30,65 @@ describe('capabilityTools session queue keys', () => { assert.equal(key, 'chat-1:session-a'); }); }); + +describe('capabilityTools result fitting', () => { + it('truncates large vault note content and stores the full note body behind a handle', async () => { + const store = new ToolOutputStore(); + const body = `${'note line\n'.repeat(1000)}important ending`; + const tools = createCattyToolsFromCatalog( + { + aiCapability: async () => ({ + ok: true, + note: { + id: 'note-1', + title: 'Long note', + content: body, + }, + }), + }, + { sessions: [] }, + [], + 'auto', + undefined, + 'chat-1', + store, + ); + + const result = await tools.vault_notes_get.execute( + { noteId: 'note-1' }, + { toolCallId: 'call-1', messages: [] }, + ) as { note: { content: string } }; + + assert.notEqual(result.note.content, body); + assert.match(result.note.content, /tool output handle/); + const handleId = result.note.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('does not refit explicit tool output read-back content', async () => { + const store = new ToolOutputStore(); + const body = `${'full note line\n'.repeat(1000)}important ending`; + const handle = store.store({ + chatSessionId: 'chat-1', + capabilityId: 'vault.notes.get', + content: body, + }); + const tools = createCattyToolsFromCatalog( + {}, + { sessions: [] }, + [], + 'auto', + undefined, + 'chat-1', + store, + ); + + const result = await tools.tool_output_read.execute( + { handleId: handle.id, mode: 'full', maxChars: body.length + 100 }, + { toolCallId: 'call-1', messages: [] }, + ) as { content: string }; + + assert.equal(result.content, body); + }); +}); diff --git a/infrastructure/ai/harness/capabilityTools.ts b/infrastructure/ai/harness/capabilityTools.ts index 98c7d0f6c..c48538af6 100644 --- a/infrastructure/ai/harness/capabilityTools.ts +++ b/infrastructure/ai/harness/capabilityTools.ts @@ -16,6 +16,7 @@ import { import { requestApproval } from '../shared/approvalGate'; import { reserveSessionSlot } from '../shared/sessionExecutionQueue'; import { fitTerminalExecuteResultForModel } from './terminalCompression'; +import { fitLargeToolResultForModel } from './toolResultFitting'; import type { ToolOutputStore } from './toolOutputStore'; import { hashScopeKey, @@ -112,6 +113,24 @@ function applyToolDedup( return result; } +function fitCapabilityResultForModel( + result: unknown, + spec: CattyToolSpec, + chatSessionId?: string, + toolOutputStore?: ToolOutputStore, +): unknown { + if (spec.capabilityId === 'harness.tool_output.read') { + return result; + } + + return fitLargeToolResultForModel({ + result, + capabilityId: spec.capabilityId, + chatSessionId, + toolOutputStore, + }); +} + interface LocalExecutionContext { deps: ToolDeps; spec: CattyToolSpec; @@ -304,7 +323,7 @@ function createCatalogTool( } if (spec.localExecution || spec.capabilityId.startsWith('harness.')) { - return executeLocalCattyCapability({ + const result = await executeLocalCattyCapability({ deps, spec, args: args as Record, @@ -312,6 +331,7 @@ function createCatalogTool( toolResultDedup, chatSessionId: deps.chatSessionId, }); + return fitCapabilityResultForModel(result, spec, deps.chatSessionId, toolOutputStore); } if (!spec.rpcMethod) { @@ -332,7 +352,12 @@ function createCatalogTool( hashScopeKey([deps.chatSessionId, ctx.workspaceId, String(ctx.sessions?.length ?? 0)]), ); if (fingerprint) { - return applyToolDedup(spec.toolName, fingerprint, raw, toolResultDedup); + return fitCapabilityResultForModel( + applyToolDedup(spec.toolName, fingerprint, raw, toolResultDedup), + spec, + deps.chatSessionId, + toolOutputStore, + ); } } @@ -343,7 +368,12 @@ function createCatalogTool( hashScopeKey([sid, path]), ); if (fingerprint) { - return applyToolDedup(spec.toolName, fingerprint, raw, toolResultDedup); + return fitCapabilityResultForModel( + applyToolDedup(spec.toolName, fingerprint, raw, toolResultDedup), + spec, + deps.chatSessionId, + toolOutputStore, + ); } if ( @@ -374,7 +404,7 @@ function createCatalogTool( } } - return raw; + return fitCapabilityResultForModel(raw, spec, deps.chatSessionId, toolOutputStore); } finally { slot?.release(); } diff --git a/infrastructure/ai/harness/toolResultFitting.test.ts b/infrastructure/ai/harness/toolResultFitting.test.ts new file mode 100644 index 000000000..11675ebd2 --- /dev/null +++ b/infrastructure/ai/harness/toolResultFitting.test.ts @@ -0,0 +1,59 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; + +import { fitLargeToolResultForModel } from './toolResultFitting'; +import { ToolOutputStore } from './toolOutputStore'; + +describe('fitLargeToolResultForModel', () => { + it('truncates large nested string fields and stores the full content behind a handle', () => { + const store = new ToolOutputStore(); + const body = `${'alpha\n'.repeat(1000)}important-tail`; + + const fitted = fitLargeToolResultForModel({ + result: { + ok: true, + note: { + id: 'note-1', + title: 'Runbook', + content: body, + }, + }, + capabilityId: 'vault.note.get', + chatSessionId: 'chat-1', + toolOutputStore: store, + maxStringChars: 500, + }) as { + note: { content: string }; + }; + + assert.notEqual(fitted.note.content, body); + assert.match(fitted.note.content, /tool output handle/); + assert.match(fitted.note.content, /capability=vault\.note\.get/); + assert.match(fitted.note.content, /field=note\.content/); + assert.match(fitted.note.content, /handleId=tool-output-/); + + const handleId = fitted.note.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('leaves small results unchanged', () => { + const result = { + ok: true, + note: { + id: 'note-1', + content: 'short note', + }, + }; + + const fitted = fitLargeToolResultForModel({ + result, + capabilityId: 'vault.note.get', + chatSessionId: 'chat-1', + toolOutputStore: new ToolOutputStore(), + maxStringChars: 500, + }); + + assert.equal(fitted, result); + }); +}); diff --git a/infrastructure/ai/harness/toolResultFitting.ts b/infrastructure/ai/harness/toolResultFitting.ts new file mode 100644 index 000000000..8e34d5936 --- /dev/null +++ b/infrastructure/ai/harness/toolResultFitting.ts @@ -0,0 +1,121 @@ +import { compressVerboseText, truncateTextWithHeadAndTail } from '../requestPayloadCompression'; +import type { ToolOutputStore } from './toolOutputStore'; + +export const MAX_LIVE_TOOL_STRING_CHARS = 8_000; + +export interface FitLargeToolResultForModelInput { + result: unknown; + capabilityId: string; + chatSessionId?: string; + toolOutputStore?: ToolOutputStore; + maxStringChars?: number; +} + +export function fitLargeToolResultForModel({ + result, + capabilityId, + chatSessionId, + toolOutputStore, + maxStringChars = MAX_LIVE_TOOL_STRING_CHARS, +}: FitLargeToolResultForModelInput): unknown { + return fitValue(result, { + capabilityId, + chatSessionId, + toolOutputStore, + maxStringChars, + path: [], + }); +} + +interface FitValueContext { + capabilityId: string; + chatSessionId?: string; + toolOutputStore?: ToolOutputStore; + maxStringChars: number; + path: string[]; +} + +function fitValue(value: unknown, ctx: FitValueContext): unknown { + if (typeof value === 'string') { + return fitString(value, ctx); + } + + if (Array.isArray(value)) { + let changed = false; + const next = value.map((entry, index) => { + const fitted = fitValue(entry, { + ...ctx, + path: [...ctx.path, `[${index}]`], + }); + if (fitted !== entry) changed = true; + return fitted; + }); + return changed ? next : value; + } + + if (!value || typeof value !== 'object') { + return value; + } + + let changed = false; + const next: Record = {}; + for (const [key, entry] of Object.entries(value as Record)) { + const fitted = fitValue(entry, { + ...ctx, + path: [...ctx.path, key], + }); + if (fitted !== entry) changed = true; + next[key] = fitted; + } + + return changed ? next : value; +} + +function fitString(value: string, ctx: FitValueContext): string { + if (value.length <= ctx.maxStringChars) return value; + + const fitted = truncateTextWithHeadAndTail( + compressVerboseText(value), + ctx.maxStringChars, + ); + if (fitted === value) return value; + + let handleId: string | undefined; + if (ctx.toolOutputStore && ctx.chatSessionId) { + handleId = ctx.toolOutputStore.store({ + chatSessionId: ctx.chatSessionId, + capabilityId: ctx.capabilityId, + content: value, + }).id; + } + + return appendToolOutputHandleNotice(fitted, { + capabilityId: ctx.capabilityId, + fieldPath: formatFieldPath(ctx.path), + totalChars: value.length, + handleId, + }); +} + +function formatFieldPath(path: string[]): string { + if (path.length === 0) return '$'; + return path + .map((part, index) => { + if (part.startsWith('[')) return part; + return index === 0 ? part : `.${part}`; + }) + .join(''); +} + +function appendToolOutputHandleNotice( + fitted: string, + details: { + capabilityId: string; + fieldPath: string; + totalChars: number; + handleId?: string; + }, +): string { + const handleSuffix = details.handleId ? ` handleId=${details.handleId}` : ''; + return `${fitted}\n\n[tool output handle: capability=${details.capabilityId} field=${details.fieldPath} chars=${details.totalChars} truncated for model context${handleSuffix}]`; +} From 6979a6b16539712c8fb8b18a15f781a4c36fc5ef Mon Sep 17 00:00:00 2001 From: Pgooone Date: Fri, 26 Jun 2026 02:16:58 +0900 Subject: [PATCH 061/228] =?UTF-8?q?fix(terminal):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E6=92=B0=E5=86=99=E6=A0=8F=E5=A4=9A=E8=A1=8C=E8=BE=93=E5=85=A5?= =?UTF-8?q?=E5=8F=AA=E5=8F=91=E9=80=81=E7=AC=AC=E4=B8=80=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 撰写栏(及自动执行的多行 snippet)采用"逐行延迟发送":第一行立即写入, 其余行通过 setTimeout 排入待发队列。writeToSession 在收到任何"非自动写入" 时清空该队列,本意是让用户中途输入(如 Ctrl+C)中断整批发送。但终端的自动 回写会被误判为用户输入,导致第 2 行及之后被丢弃,表现为"只发出第一行"。 ## 根因 writeToSession 开头 `if (!payload.automated) clearPendingAutomatedWrites(session)` 把"终端自动回写"也当成"用户开始输入"。终端的光标位置报告(ESC[…R)、设备 属性、焦点进出(ESC[I/O)走同一条 netcatty:write 路径且不带 automated 标志, 常在第一行执行后立即触发,于是清空了待发队列。又因 shouldDelayAutoRunSnippetInput 只检测 \n,多行中英文一视同仁——与中文/编码无关。 ## 修复 新增 isTerminalReportSequence(),将光标位置报告 / 设备属性 / 焦点进出等终端 自动回写序列从"清队列"判定中排除:真正的用户输入仍能中断整批发送,无害的 终端自动回写不再误清待发行。 ## 测试 新增 terminalBridge.composeMultiline.test.cjs: - [REPRO] 行间的终端自动回写不应取消待发行(修复前失败、修复后通过) - [GUARD] 行间的 Ctrl+C 仍应取消待发行(保留既有行为) 回归:terminalBridge.ctrlCInterrupt.test.cjs 仍 8/8 通过。 Co-Authored-By: Claude --- electron/bridges/terminalBridge.cjs | 21 ++++- .../terminalBridge.composeMultiline.test.cjs | 87 +++++++++++++++++++ 2 files changed, 107 insertions(+), 1 deletion(-) create mode 100644 electron/bridges/terminalBridge.composeMultiline.test.cjs diff --git a/electron/bridges/terminalBridge.cjs b/electron/bridges/terminalBridge.cjs index 320e154ef..92b0fc595 100644 --- a/electron/bridges/terminalBridge.cjs +++ b/electron/bridges/terminalBridge.cjs @@ -708,6 +708,23 @@ function clearPendingAutomatedWrites(session) { session.pendingAutomatedWriteTimers = []; } +// Terminal-originated automatic replies (cursor position reports, device +// attributes, focus in/out, etc.) travel through the same write path as user +// keystrokes but must NOT be treated as "the user started typing". A terminal +// routinely emits such a reply right after the first line runs; counting it as +// manual input would clear the pending automated line-by-line writes and only +// the first line would ever be sent (multi-line compose-bar input bug). +function isTerminalReportSequence(data) { + if (typeof data !== "string" || data.length === 0) return false; + // Focus in/out reports: ESC [ I / ESC [ O + if (data === "\x1b[I" || data === "\x1b[O") return true; + // CPR / DECXCPR / DA1 / DA2 / DSR: ESC [ (?|>)? digits/semicolons (R|c|n) + if (/^\x1b\[[?>]?[0-9;]*[Rcn]$/.test(data)) return true; + // DCS replies (XTGETTCAP / DECRQSS, etc.): ESC P ... ESC \ + if (/^\x1bP[\s\S]*\x1b\\$/.test(data)) return true; + return false; +} + function splitTerminalInputIntoLineWrites(data) { if (typeof data !== "string") return [data]; const chunks = []; @@ -810,7 +827,9 @@ function writeToSession(event, payload) { const session = sessions.get(payload.sessionId); if (!session) return; - if (!payload.automated) clearPendingAutomatedWrites(session); + if (!payload.automated && !isTerminalReportSequence(payload.data)) { + clearPendingAutomatedWrites(session); + } if (shouldBlockSessionInput(session, payload.data)) { return; } diff --git a/electron/bridges/terminalBridge.composeMultiline.test.cjs b/electron/bridges/terminalBridge.composeMultiline.test.cjs new file mode 100644 index 000000000..5d4b1196d --- /dev/null +++ b/electron/bridges/terminalBridge.composeMultiline.test.cjs @@ -0,0 +1,87 @@ +/** + * 复现:撰写栏(Compose Bar)发送多行内容时只发出第一行。 + * + * 链路:撰写栏 textarea → executeSnippetCommand(text, false) → 多行+autoRun + * 触发 lineDelayMs=250 → 后端 writeToSession 走"逐行延迟发送":第一行立即发, + * 行2+ 用 setTimeout 排进 session.pendingAutomatedWriteTimers。 + * + * 根因:writeToSession 开头 + * if (!payload.automated) clearPendingAutomatedWrites(session); + * 会被【任何】非自动写入触发——包括 xterm 对第一行命令输出的自动回写 + * (光标位置查询 DSR 响应、焦点上报、bracketed-paste 响应等),它们同样走 + * netcatty:write 且不带 automated 标志 → 清空行2+ 的待发队列 → 只发第一行。 + * 与中文无关:shouldDelayAutoRunSnippetInput 只检测 \n,多行英文同样中招。 + */ +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const terminalBridge = require("./terminalBridge.cjs"); + +function initBridge(sessions) { + terminalBridge.init({ + sessions, + electronModule: { + webContents: { fromId: () => ({ send() {} }) }, + }, + }); +} + +function delay(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +// 断言【期望的正确行为】:无害的终端自动回写不应取消后续行。 +// 因此在修复前,这个测试会失败(实际只发出 "echo one\r" + 那次自动回写)。 +test("[REPRO] terminal auto-reply between automated lines must NOT cancel pending lines", async () => { + const calls = []; + const sessions = new Map(); + sessions.set("ssh-1", { + stream: { signal() {}, write(data) { calls.push(data); } }, + }); + initBridge(sessions); + + // 撰写栏多行(autoRun → 逐行延迟发送) + terminalBridge.writeToSession( + { sender: {} }, + { + sessionId: "ssh-1", + data: "echo one\necho two\necho three\r", + automated: true, + lineDelayMs: 20, + }, + ); + assert.deepEqual(calls, ["echo one\r"], "第一行应立即发出"); + + // 模拟 xterm 对第一行命令输出的自动回写(光标位置查询 DSR 响应),非 automated + terminalBridge.writeToSession({ sender: {} }, { sessionId: "ssh-1", data: "\x1b[2;1R" }); + + await delay(80); + + assert.deepEqual( + calls, + ["echo one\r", "\x1b[2;1R", "echo two\r", "echo three\r"], + "终端自动回写不应清空逐行队列;行2/行3 应照常发出", + ); +}); + +// 对照(护栏):真正的用户中断(Ctrl+C)应当取消剩余自动逐行发送。 +// 这是既有的有意行为,修复 REPRO 时不能破坏。当前应通过。 +test("[GUARD] Ctrl+C between automated lines SHOULD cancel pending lines", async () => { + const calls = []; + const sessions = new Map(); + sessions.set("ssh-1", { + stream: { signal() {}, write(data) { calls.push(data); } }, + }); + initBridge(sessions); + + terminalBridge.writeToSession( + { sender: {} }, + { sessionId: "ssh-1", data: "echo one\necho two\r", automated: true, lineDelayMs: 20 }, + ); + assert.deepEqual(calls, ["echo one\r"]); + + terminalBridge.writeToSession({ sender: {} }, { sessionId: "ssh-1", data: "\x03" }); // Ctrl+C + await delay(60); + + assert.deepEqual(calls, ["echo one\r", "\x03"], "Ctrl+C 应取消行2(既有设计,修复后须保留)"); +}); From 59502d629a8a6c69dc12c4e80747245cc81afea6 Mon Sep 17 00:00:00 2001 From: mam15mon Date: Fri, 26 Jun 2026 01:17:31 +0800 Subject: [PATCH 062/228] Include Ctrl+Tab in pinned tab shortcut skip (#1680) --- application/AppHandlers.globalHotkeys.test.ts | 98 +++++++++++++++++++ application/app/AppHandlers.ts | 37 +++---- application/app/tabShortcutTargets.ts | 2 +- application/i18n/locales/en/core.ts | 4 +- application/i18n/locales/ru/core.ts | 4 +- application/i18n/locales/zh-CN/terminal.ts | 4 +- domain/sync.ts | 2 +- infrastructure/config/storageKeys.ts | 2 +- 8 files changed, 122 insertions(+), 31 deletions(-) diff --git a/application/AppHandlers.globalHotkeys.test.ts b/application/AppHandlers.globalHotkeys.test.ts index 03da276ed..ef7de8717 100644 --- a/application/AppHandlers.globalHotkeys.test.ts +++ b/application/AppHandlers.globalHotkeys.test.ts @@ -170,6 +170,104 @@ test('quick switch hotkey toggles the quick switcher open state', () => { assert.equal(isQuickSwitcherOpen, false); }); +test('next tab includes pinned tabs when shell-only shortcut mode is disabled', () => { + let activeTabId = ''; + const noop = () => {}; + + executeHotkeyActionImpl( + () => ({ + IS_DEV: false, + MOVE_FOCUS_DEBOUNCE_MS: 0, + activeTabStore: { getActiveTabId: () => 'vault' }, + addConnectionLogRef: { current: noop }, + closeSession: noop, + closeTabInFlightRef: { current: false }, + closeWorkspace: noop, + collectSessionIds: () => [], + confirmIfBusyLocalTerminal: async () => true, + createLocalTerminalWithCurrentShell: noop, + editorTabs: [{ id: 'editor-1' }], + fromEditorTabId: () => null, + handleOpenSettingsRef: { current: noop }, + handleRequestCloseEditorTabRef: { current: noop }, + isEditorTabId: () => false, + isQuickSwitcherOpen: false, + lastMoveFocusTimeRef: { current: 0 }, + moveFocusInWorkspace: noop, + orderedTabs: ['session-1'], + resolveCloseIntent: () => ({ kind: 'noop' }), + resolveSnippetsShortcutIntent: () => ({ kind: 'noop' }), + sessions: [], + setActiveTabId: (id: string) => { activeTabId = id; }, + setAddToWorkspaceDialog: noop, + setIsQuickSwitcherOpen: noop, + setNavigateToSection: noop, + settings: { showSftpTab: true, shellOnlyTabNumberShortcuts: false }, + splitSessionWithCurrentShell: noop, + systemInfoRef: { current: { username: 'user', hostname: 'host' } }, + toEditorTabId: (id: string) => `editor:${id}`, + toggleBroadcast: noop, + toggleScriptsSidePanelRef: { current: noop }, + toggleSidePanelRef: { current: noop }, + toggleWorkspaceViewMode: noop, + workspaces: [], + }), + 'nextTab', + { key: 'Tab', ctrlKey: true } as KeyboardEvent, + ); + + assert.equal(activeTabId, 'sftp'); +}); + +test('next tab skips pinned tabs when shell-only shortcut mode is enabled', () => { + let activeTabId = ''; + const noop = () => {}; + + executeHotkeyActionImpl( + () => ({ + IS_DEV: false, + MOVE_FOCUS_DEBOUNCE_MS: 0, + activeTabStore: { getActiveTabId: () => 'vault' }, + addConnectionLogRef: { current: noop }, + closeSession: noop, + closeTabInFlightRef: { current: false }, + closeWorkspace: noop, + collectSessionIds: () => [], + confirmIfBusyLocalTerminal: async () => true, + createLocalTerminalWithCurrentShell: noop, + editorTabs: [{ id: 'editor-1' }], + fromEditorTabId: () => null, + handleOpenSettingsRef: { current: noop }, + handleRequestCloseEditorTabRef: { current: noop }, + isEditorTabId: () => false, + isQuickSwitcherOpen: false, + lastMoveFocusTimeRef: { current: 0 }, + moveFocusInWorkspace: noop, + orderedTabs: ['session-1'], + resolveCloseIntent: () => ({ kind: 'noop' }), + resolveSnippetsShortcutIntent: () => ({ kind: 'noop' }), + sessions: [], + setActiveTabId: (id: string) => { activeTabId = id; }, + setAddToWorkspaceDialog: noop, + setIsQuickSwitcherOpen: noop, + setNavigateToSection: noop, + settings: { showSftpTab: true, shellOnlyTabNumberShortcuts: true }, + splitSessionWithCurrentShell: noop, + systemInfoRef: { current: { username: 'user', hostname: 'host' } }, + toEditorTabId: (id: string) => `editor:${id}`, + toggleBroadcast: noop, + toggleScriptsSidePanelRef: { current: noop }, + toggleSidePanelRef: { current: noop }, + toggleWorkspaceViewMode: noop, + workspaces: [], + }), + 'nextTab', + { key: 'Tab', ctrlKey: true } as KeyboardEvent, + ); + + assert.equal(activeTabId, 'session-1'); +}); + test('connection log host snapshot includes custom host icon fields', () => { assert.deepEqual( getLogHostVisualSnapshot({ diff --git a/application/app/AppHandlers.ts b/application/app/AppHandlers.ts index 5d4be0775..30c083653 100644 --- a/application/app/AppHandlers.ts +++ b/application/app/AppHandlers.ts @@ -452,14 +452,7 @@ export async function closeTabsBatchImpl(getCtx: AppContextGetter, targetIds: st export function executeHotkeyActionImpl(getCtx: AppContextGetter, action: string, e: KeyboardEvent) { const { IS_DEV, MOVE_FOCUS_DEBOUNCE_MS, activeTabStore, addConnectionLogRef, closeSession, closeTabInFlightRef, closeWorkspace, collectSessionIds, confirmIfBusyLocalTerminal, createLocalTerminalWithCurrentShell, editorTabs, fromEditorTabId, handleOpenSettingsRef, handleRequestCloseEditorTabRef, isEditorTabId, isQuickSwitcherOpen, lastMoveFocusTimeRef, moveFocusInWorkspace, orderedTabs, resolveCloseIntent, resolveSnippetsShortcutIntent, sessions, setActiveTabId, setAddToWorkspaceDialog, setIsQuickSwitcherOpen, setNavigateToSection, settings, splitSessionWithCurrentShell, systemInfoRef, toEditorTabId, toggleBroadcast, toggleScriptsSidePanelRef, toggleSidePanelRef, toggleWorkspaceViewMode, workspaces } = getCtx(); { - // Build complete tab list: vault + (sftp when visible) + sessions/workspaces + editor tabs. - // Hiding the SFTP tab must also remove it from keyboard cycling so nextTab - // doesn't land on a hidden tab (which would get redirected back) and so - // number shortcuts don't shift. - const allTabs = settings.showSftpTab - ? ['vault', 'sftp', ...orderedTabs, ...editorTabs.map((t) => toEditorTabId(t.id))] - : ['vault', ...orderedTabs, ...editorTabs.map((t) => toEditorTabId(t.id))]; - const numberShortcutTabs = buildNumberShortcutTabTargets({ + const shortcutTabs = buildNumberShortcutTabTargets({ showSftpTab: settings.showSftpTab ?? true, shellOnlyTabNumberShortcuts: settings.shellOnlyTabNumberShortcuts ?? false, orderedTabs, @@ -470,31 +463,31 @@ export function executeHotkeyActionImpl(getCtx: AppContextGetter, action: string // Get the number key pressed (1-9) const num = parseInt(e.key, 10); if (num >= 1 && num <= 9) { - if (num <= numberShortcutTabs.length) { - setActiveTabId(numberShortcutTabs[num - 1]); + if (num <= shortcutTabs.length) { + setActiveTabId(shortcutTabs[num - 1]); } } break; } case 'nextTab': { const currentId = activeTabStore.getActiveTabId(); - const currentIdx = allTabs.indexOf(currentId); - if (currentIdx !== -1 && allTabs.length > 0) { - const nextIdx = (currentIdx + 1) % allTabs.length; - setActiveTabId(allTabs[nextIdx]); - } else if (allTabs.length > 0) { - setActiveTabId(allTabs[0]); + const currentIdx = shortcutTabs.indexOf(currentId); + if (currentIdx !== -1 && shortcutTabs.length > 0) { + const nextIdx = (currentIdx + 1) % shortcutTabs.length; + setActiveTabId(shortcutTabs[nextIdx]); + } else if (shortcutTabs.length > 0) { + setActiveTabId(shortcutTabs[0]); } break; } case 'prevTab': { const currentId = activeTabStore.getActiveTabId(); - const currentIdx = allTabs.indexOf(currentId); - if (currentIdx !== -1 && allTabs.length > 0) { - const prevIdx = (currentIdx - 1 + allTabs.length) % allTabs.length; - setActiveTabId(allTabs[prevIdx]); - } else if (allTabs.length > 0) { - setActiveTabId(allTabs[allTabs.length - 1]); + const currentIdx = shortcutTabs.indexOf(currentId); + if (currentIdx !== -1 && shortcutTabs.length > 0) { + const prevIdx = (currentIdx - 1 + shortcutTabs.length) % shortcutTabs.length; + setActiveTabId(shortcutTabs[prevIdx]); + } else if (shortcutTabs.length > 0) { + setActiveTabId(shortcutTabs[shortcutTabs.length - 1]); } break; } diff --git a/application/app/tabShortcutTargets.ts b/application/app/tabShortcutTargets.ts index 6cb675e90..104f0606a 100644 --- a/application/app/tabShortcutTargets.ts +++ b/application/app/tabShortcutTargets.ts @@ -1,4 +1,4 @@ -/** Tab ids targeted by Cmd/Ctrl+[1...9] number shortcuts. */ +/** Tab ids targeted by keyboard tab navigation shortcuts. */ export function buildNumberShortcutTabTargets(params: { showSftpTab: boolean; shellOnlyTabNumberShortcuts: boolean; diff --git a/application/i18n/locales/en/core.ts b/application/i18n/locales/en/core.ts index 1896dd7a6..a207e412e 100644 --- a/application/i18n/locales/en/core.ts +++ b/application/i18n/locales/en/core.ts @@ -525,8 +525,8 @@ export const enCoreMessages: Messages = { 'settings.shortcuts.scheme.pc': 'PC (Ctrl)', 'settings.shortcuts.disableTerminalFontZoom.label': 'Disable terminal zoom', 'settings.shortcuts.disableTerminalFontZoom.desc': 'Turn off terminal font zoom shortcuts, including Cmd/Ctrl + mouse wheel.', - 'settings.shortcuts.shellOnlyTabNumberShortcuts.label': 'Number keys skip pinned tabs', - 'settings.shortcuts.shellOnlyTabNumberShortcuts.desc': 'When enabled, Cmd/Ctrl+[1...9] switches only work tabs (terminals, workspaces, editors), not the pinned Vault or SFTP tabs.', + 'settings.shortcuts.shellOnlyTabNumberShortcuts.label': 'Tab shortcuts skip pinned tabs', + 'settings.shortcuts.shellOnlyTabNumberShortcuts.desc': 'When enabled, Cmd/Ctrl+[1...9] and Ctrl+Tab switch only work tabs (terminals, workspaces, editors), not the pinned Vault or SFTP tabs.', 'settings.shortcuts.section.custom': 'Custom Shortcuts', 'settings.shortcuts.resetAll': 'Reset All', 'settings.shortcuts.recording': 'Press keys...', diff --git a/application/i18n/locales/ru/core.ts b/application/i18n/locales/ru/core.ts index 7481980b5..4804a74a3 100644 --- a/application/i18n/locales/ru/core.ts +++ b/application/i18n/locales/ru/core.ts @@ -500,8 +500,8 @@ export const ruCoreMessages: Messages = { 'settings.shortcuts.scheme.pc': 'PC (Ctrl)', 'settings.shortcuts.disableTerminalFontZoom.label': 'Отключить масштаб терминала', 'settings.shortcuts.disableTerminalFontZoom.desc': 'Отключает быстрый масштаб текста в терминале, включая Cmd/Ctrl + колесо мыши.', - 'settings.shortcuts.shellOnlyTabNumberShortcuts.label': 'Цифры без закреплённых вкладок', - 'settings.shortcuts.shellOnlyTabNumberShortcuts.desc': 'Если включено, Cmd/Ctrl+[1...9] переключает только рабочие вкладки (терминалы, рабочие области, редакторы), а не закреплённые Vault и SFTP.', + 'settings.shortcuts.shellOnlyTabNumberShortcuts.label': 'Сочетания без закреплённых вкладок', + 'settings.shortcuts.shellOnlyTabNumberShortcuts.desc': 'Если включено, Cmd/Ctrl+[1...9] и Ctrl+Tab переключают только рабочие вкладки (терминалы, рабочие области, редакторы), а не закреплённые Vault и SFTP.', 'settings.shortcuts.section.custom': 'Пользовательские сочетания', 'settings.shortcuts.resetAll': 'Сбросить все', 'settings.shortcuts.recording': 'Нажмите клавиши...', diff --git a/application/i18n/locales/zh-CN/terminal.ts b/application/i18n/locales/zh-CN/terminal.ts index 943413f2f..ef15853f5 100644 --- a/application/i18n/locales/zh-CN/terminal.ts +++ b/application/i18n/locales/zh-CN/terminal.ts @@ -395,8 +395,8 @@ export const zhCNTerminalMessages: Messages = { 'settings.shortcuts.scheme.pc': 'PC (Ctrl)', 'settings.shortcuts.disableTerminalFontZoom.label': '禁用终端缩放', 'settings.shortcuts.disableTerminalFontZoom.desc': '关闭终端文字缩放快捷操作,包括 Cmd/Ctrl 加滚轮。', - 'settings.shortcuts.shellOnlyTabNumberShortcuts.label': '数字键跳过固定标签', - 'settings.shortcuts.shellOnlyTabNumberShortcuts.desc': '开启后,Cmd/Ctrl+[1...9] 仅在终端、工作区、编辑器等可关闭标签页之间切换,不包括固定的 Vault 和 SFTP 标签页。', + 'settings.shortcuts.shellOnlyTabNumberShortcuts.label': '标签快捷键跳过固定标签', + 'settings.shortcuts.shellOnlyTabNumberShortcuts.desc': '开启后,Cmd/Ctrl+[1...9] 和 Ctrl+Tab 仅在终端、工作区、编辑器等可关闭标签页之间切换,不包括固定的 Vault 和 SFTP 标签页。', 'settings.shortcuts.section.custom': '自定义快捷键', 'settings.shortcuts.resetAll': '全部重置', 'settings.shortcuts.recording': '请按键...', diff --git a/domain/sync.ts b/domain/sync.ts index e0bf0194d..172880bc3 100644 --- a/domain/sync.ts +++ b/domain/sync.ts @@ -251,7 +251,7 @@ export interface SyncPayload { showOnlyUngroupedHostsInRoot?: boolean; // Top tabs: show standalone SFTP view tab showSftpTab?: boolean; - // Shortcuts: Cmd/Ctrl+[1...9] skip pinned Vault/SFTP tabs + // Shortcuts: Cmd/Ctrl+[1...9] and Ctrl+Tab skip pinned Vault/SFTP tabs shellOnlyTabNumberShortcuts?: boolean; // Shortcuts: disable terminal font zoom shortcuts disableTerminalFontZoom?: boolean; diff --git a/infrastructure/config/storageKeys.ts b/infrastructure/config/storageKeys.ts index 18097c490..3ca1a37d5 100644 --- a/infrastructure/config/storageKeys.ts +++ b/infrastructure/config/storageKeys.ts @@ -174,7 +174,7 @@ export const STORAGE_KEY_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT = 'netcatty_show_only export const STORAGE_KEY_SHOW_SFTP_TAB = 'netcatty_show_sftp_tab_v1'; export const STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR = 'netcatty_show_host_tree_sidebar_v1'; -// Shortcuts: Cmd/Ctrl+[1...9] skip pinned Vault/SFTP tabs +// Shortcuts: Cmd/Ctrl+[1...9] and Ctrl+Tab skip pinned Vault/SFTP tabs export const STORAGE_KEY_SHELL_ONLY_TAB_NUMBER_SHORTCUTS = 'netcatty_shell_only_tab_number_shortcuts_v1'; // Shortcuts: disable terminal font zoom shortcuts From a3052ae429a35af3dbd0cea6ff03e0b5ccfe2cd4 Mon Sep 17 00:00:00 2001 From: StartHex <149861313+StartHex@users.noreply.github.com> Date: Fri, 26 Jun 2026 01:17:59 +0800 Subject: [PATCH 063/228] Add latency to terminal network stats (#1670) --- application/i18n/locales/en/terminal.ts | 1 + application/i18n/locales/zh-CN/vault.ts | 1 + components/terminal/TerminalServerStats.tsx | 17 ++++++++++++++++- components/terminal/hooks/useServerStats.ts | 4 ++++ electron/bridges/sshBridge/sessionOps.cjs | 11 +++++++++-- .../sshBridge/sessionOps.serverStats.test.cjs | 1 + types/global/netcatty-bridge-session.d.ts | 1 + 7 files changed, 33 insertions(+), 3 deletions(-) diff --git a/application/i18n/locales/en/terminal.ts b/application/i18n/locales/en/terminal.ts index df76d5a3d..6cb226d52 100644 --- a/application/i18n/locales/en/terminal.ts +++ b/application/i18n/locales/en/terminal.ts @@ -88,6 +88,7 @@ export const enTerminalMessages: Messages = { 'terminal.serverStats.disk': 'Disk Usage (Root)', 'terminal.serverStats.diskDetails': 'Mounted Disks', 'terminal.serverStats.network': 'Network Speed', + 'terminal.serverStats.latency': 'Latency', 'terminal.serverStats.networkDetails': 'Network Interfaces', 'terminal.serverStats.noData': 'No data available', 'terminal.dragDrop.localTitle': 'Drop to Insert Paths', diff --git a/application/i18n/locales/zh-CN/vault.ts b/application/i18n/locales/zh-CN/vault.ts index 2ed388e53..a2c6a239e 100644 --- a/application/i18n/locales/zh-CN/vault.ts +++ b/application/i18n/locales/zh-CN/vault.ts @@ -367,6 +367,7 @@ export const zhCNVaultMessages: Messages = { 'terminal.serverStats.disk': '磁盘使用(根分区)', 'terminal.serverStats.diskDetails': '已挂载磁盘', 'terminal.serverStats.network': '网络速度', + 'terminal.serverStats.latency': '延迟', 'terminal.serverStats.networkDetails': '网络接口', 'terminal.serverStats.noData': '暂无数据', 'terminal.dragDrop.localTitle': '拖放以插入路径', diff --git a/components/terminal/TerminalServerStats.tsx b/components/terminal/TerminalServerStats.tsx index 146fd1a36..3f4666e44 100644 --- a/components/terminal/TerminalServerStats.tsx +++ b/components/terminal/TerminalServerStats.tsx @@ -1,5 +1,5 @@ import React from 'react'; -import { ArrowDownToLine, ArrowUpFromLine, Cpu, HardDrive, MemoryStick } from 'lucide-react'; +import { Activity, ArrowDownToLine, ArrowUpFromLine, Cpu, HardDrive, MemoryStick } from 'lucide-react'; import { useI18n } from '../../application/i18n/I18nProvider'; import { cn } from '../../lib/utils'; @@ -17,6 +17,10 @@ interface TerminalServerStatsProps { isConnected: boolean; } +const formatLatency = (latencyMs: number | null): string => ( + typeof latencyMs === 'number' && Number.isFinite(latencyMs) ? `${latencyMs}ms` : '--ms' +); + /** * Self-contained server-stats (CPU / Memory / Disk / Network) indicator. * @@ -323,6 +327,8 @@ export const TerminalServerStats: React.FC = ({ {formatNetSpeed(serverStats.netRxSpeed)} {formatNetSpeed(serverStats.netTxSpeed)} + + {formatLatency(serverStats.latencyMs)} = ({ >
{t("terminal.serverStats.networkDetails")}
+
+ + {t("terminal.serverStats.latency")} + + + + {formatLatency(serverStats.latencyMs)} + +
{serverStats.netInterfaces.map((iface, index) => (
diff --git a/components/terminal/hooks/useServerStats.ts b/components/terminal/hooks/useServerStats.ts index 2e961c364..980a4a4e5 100644 --- a/components/terminal/hooks/useServerStats.ts +++ b/components/terminal/hooks/useServerStats.ts @@ -40,6 +40,7 @@ export interface ServerStats { disks: DiskInfo[]; // All mounted disks netRxSpeed: number; // Total network receive speed (bytes/sec) netTxSpeed: number; // Total network transmit speed (bytes/sec) + latencyMs: number | null; // Approximate SSH stats round-trip latency netInterfaces: NetInterfaceInfo[]; // Per-interface network stats lastUpdated: number | null; // Timestamp of last successful update } @@ -79,6 +80,7 @@ export function useServerStats({ disks: [], netRxSpeed: 0, netTxSpeed: 0, + latencyMs: null, netInterfaces: [], lastUpdated: null, }); @@ -167,6 +169,7 @@ export function useServerStats({ disks: result.stats.disks || [], netRxSpeed: result.stats.netRxSpeed || 0, netTxSpeed: result.stats.netTxSpeed || 0, + latencyMs: Number.isFinite(result.stats.latencyMs) ? result.stats.latencyMs : null, netInterfaces: result.stats.netInterfaces || [], lastUpdated: Date.now(), }); @@ -236,6 +239,7 @@ export function useServerStats({ disks: [], netRxSpeed: 0, netTxSpeed: 0, + latencyMs: null, netInterfaces: [], lastUpdated: null, }); diff --git a/electron/bridges/sshBridge/sessionOps.cjs b/electron/bridges/sshBridge/sessionOps.cjs index e59e567b7..ca70738e2 100644 --- a/electron/bridges/sshBridge/sessionOps.cjs +++ b/electron/bridges/sshBridge/sessionOps.cjs @@ -784,11 +784,13 @@ function createSessionOpsApi(ctx) { ].join('; '); // Auto-detect OS via uname — only Linux and macOS are supported - const statsCommand = `ostype=$(uname -s 2>/dev/null || echo "Unknown"); if [ "$ostype" = "Darwin" ]; then ${macosStatsCommand}; elif [ "$ostype" = "Linux" ]; then ${linuxStatsCommand}; else echo "UNSUPPORTED_OS:$ostype"; fi`; + const latencyMarker = "NC_LATENCY_MARK"; + const statsCommand = `printf "${latencyMarker}|"; ostype=$(uname -s 2>/dev/null || echo "Unknown"); if [ "$ostype" = "Darwin" ]; then ${macosStatsCommand}; elif [ "$ostype" = "Linux" ]; then ${linuxStatsCommand}; else echo "UNSUPPORTED_OS:$ostype"; fi`; return new Promise((resolve) => { const timeout = setTimeout(() => { resolve({ success: false, error: 'Timeout getting server stats' }); }, 5000); + const latencyStartedAt = Date.now(); conn.exec(statsCommand, (err, stream) => { if (err) { @@ -799,8 +801,12 @@ function createSessionOpsApi(ctx) { let stdout = ''; let stderr = ''; + let latencyMs = null; stream.on('data', (data) => { + if (latencyMs === null) { + latencyMs = Math.max(0, Date.now() - latencyStartedAt); + } stdout += data.toString(); }); @@ -812,7 +818,7 @@ function createSessionOpsApi(ctx) { clearTimeout(timeout); // Parse the output - const output = stdout.trim(); + const output = stdout.trim().replace(new RegExp(`^${latencyMarker}\\|?`), ''); // Unsupported OS — stop polling this session if (output.startsWith('UNSUPPORTED_OS:')) { @@ -1086,6 +1092,7 @@ function createSessionOpsApi(ctx) { disks, // Array of all mounted disks netRxSpeed, // Total network receive speed (bytes/sec) netTxSpeed, // Total network transmit speed (bytes/sec) + latencyMs, // Approximate SSH stats round-trip latency (ms) netInterfaces, // Per-interface network stats }, }); diff --git a/electron/bridges/sshBridge/sessionOps.serverStats.test.cjs b/electron/bridges/sshBridge/sessionOps.serverStats.test.cjs index 3ca16b422..2603f6657 100644 --- a/electron/bridges/sshBridge/sessionOps.serverStats.test.cjs +++ b/electron/bridges/sshBridge/sessionOps.serverStats.test.cjs @@ -75,6 +75,7 @@ test("getServerStats opens a Mosh stats companion connection when session.conn i assert.equal(result.success, true); assert.equal(result.stats.memTotal, 8000); assert.equal(result.stats.cpuCores, 4); + assert.equal(typeof result.stats.latencyMs, "number"); }); test("getServerStats fails gracefully when the companion connection cannot be established", async () => { diff --git a/types/global/netcatty-bridge-session.d.ts b/types/global/netcatty-bridge-session.d.ts index 8a8ace1d7..467bb25f2 100644 --- a/types/global/netcatty-bridge-session.d.ts +++ b/types/global/netcatty-bridge-session.d.ts @@ -218,6 +218,7 @@ declare global { }>; netRxSpeed: number; // Total network receive speed (bytes/sec) netTxSpeed: number; // Total network transmit speed (bytes/sec) + latencyMs: number | null; // Approximate SSH stats round-trip latency netInterfaces: Array<{ // Per-interface network stats name: string; // Interface name (e.g., eth0, ens33) rxBytes: number; // Total received bytes From cb4a84b439354f2e7c3a1f6d94ed45c9f155cc63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 01:30:33 +0800 Subject: [PATCH 064/228] Handle empty DeepSeek tool call fields (#1690) --- .../capabilities/catalog/integrity.test.cjs | 5 +- .../ai/providersBridgeFetch.test.ts | 225 ++++++++++++++++++ infrastructure/ai/sdk/providers.ts | 48 +++- package-lock.json | 93 +++++--- 4 files changed, 336 insertions(+), 35 deletions(-) diff --git a/electron/capabilities/catalog/integrity.test.cjs b/electron/capabilities/catalog/integrity.test.cjs index ebfcde465..fbd7a8fbb 100644 --- a/electron/capabilities/catalog/integrity.test.cjs +++ b/electron/capabilities/catalog/integrity.test.cjs @@ -54,9 +54,10 @@ 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 hasCatty = Boolean(capability.surfaces[CAPABILITY_SURFACES.CATTY]?.toolName); assert.ok( - hasRpc || hasCli || capability.surfaces[CAPABILITY_SURFACES.BUILTIN]?.mcpTool, - `${capability.id} has no rpc/cli/mcp binding`, + hasRpc || hasCli || hasCatty || capability.surfaces[CAPABILITY_SURFACES.BUILTIN]?.mcpTool, + `${capability.id} has no rpc/cli/catty/mcp binding`, ); } }); diff --git a/infrastructure/ai/providersBridgeFetch.test.ts b/infrastructure/ai/providersBridgeFetch.test.ts index 1215e4321..0a0212278 100644 --- a/infrastructure/ai/providersBridgeFetch.test.ts +++ b/infrastructure/ai/providersBridgeFetch.test.ts @@ -597,6 +597,231 @@ test('continues OpenAI-compatible streams when provider chunks omit the top-leve assert.equal(toolMessage.tool_call_id, assistantMessage.tool_calls?.[0]?.id); }); +test('continues DeepSeek-compatible tool streams when empty id, type, and name precede the real tool name', async (t) => { + const originalWindow = (globalThis as typeof globalThis & { window?: unknown }).window; + t.after(() => { + (globalThis as typeof globalThis & { window?: unknown }).window = originalWindow; + }); + + const dataHandlers = new Map void>(); + const endHandlers = new Map void>(); + const sentBodies: Array> = []; + const emitChatChunk = (emit: (data: string) => void, delta: Record, finishReason?: string) => { + emit(JSON.stringify({ + id: 'chatcmpl-one-api-test', + object: 'chat.completion.chunk', + created: 1777600000, + model: 'deepseek-chat', + choices: [{ index: 0, delta, finish_reason: finishReason ?? null }], + })); + }; + + (globalThis as typeof globalThis & { window?: unknown }).window = { + netcatty: { + aiFetch: async () => ({ ok: true, status: 200, data: '{}' }), + aiChatCancel: async () => true, + onAiStreamData: (requestId: string, cb: (data: string) => void) => { + dataHandlers.set(requestId, cb); + return () => dataHandlers.delete(requestId); + }, + onAiStreamEnd: (requestId: string, cb: () => void) => { + endHandlers.set(requestId, cb); + return () => endHandlers.delete(requestId); + }, + onAiStreamError: () => () => undefined, + aiChatStream: async ( + requestId: string, + _url: string, + _headers: Record, + body: string, + ) => { + sentBodies.push(JSON.parse(body)); + const requestNumber = sentBodies.length; + setTimeout(() => { + const emit = dataHandlers.get(requestId); + assert.ok(emit, 'stream data handler should be registered before aiChatStream starts'); + if (requestNumber === 1) { + emitChatChunk(emit, { + tool_calls: [{ + index: 0, + id: '', + type: '', + function: { name: '', arguments: '' }, + }], + }); + emitChatChunk(emit, { + tool_calls: [{ + index: 0, + function: { name: 'terminal_exec', arguments: '{"command":"pwd"}' }, + }], + }); + emitChatChunk(emit, {}, 'tool_calls'); + } else { + emitChatChunk(emit, { content: 'tool completed' }); + emitChatChunk(emit, {}, 'stop'); + } + endHandlers.get(requestId)?.(); + }, 0); + return { ok: true, statusCode: 200, statusText: 'OK' }; + }, + }, + }; + + const executedCommands: string[] = []; + const model = createModelFromConfig({ + id: 'deepseek-one-api', + providerId: 'custom', + name: 'DeepSeek One API', + apiKey: 'test-key', + baseURL: 'https://one-api.example/v1', + defaultModel: 'deepseek-chat', + enabled: true, + }); + + const result = streamText({ + model, + messages: [{ role: 'user', content: 'inspect cwd' }], + tools: { + terminal_exec: tool({ + inputSchema: z.object({ command: z.string() }), + execute: async ({ command }) => { + executedCommands.push(command); + return { ok: true }; + }, + }), + }, + stopWhen: stepCountIs(2), + }); + + let text = ''; + for await (const chunk of result.fullStream) { + if (chunk.type === 'text-delta') { + text += chunk.text; + } + } + + assert.deepEqual(executedCommands, ['pwd']); + assert.equal(text, 'tool completed'); + const followUpMessages = sentBodies[1].messages as Array>; + const assistantMessage = followUpMessages[1] as { + tool_calls?: Array<{ id?: string; type?: string; function?: { name?: string; arguments?: string } }>; + }; + const toolMessage = followUpMessages[2] as { tool_call_id?: string }; + assert.ok(assistantMessage.tool_calls?.[0]?.id?.startsWith('call_netcatty_')); + assert.equal(assistantMessage.tool_calls?.[0]?.type, 'function'); + assert.equal(assistantMessage.tool_calls?.[0]?.function?.name, 'terminal_exec'); + assert.equal(toolMessage.tool_call_id, assistantMessage.tool_calls?.[0]?.id); +}); + +test('continues DeepSeek-compatible tool streams when later argument chunks keep empty id and type', async (t) => { + const originalWindow = (globalThis as typeof globalThis & { window?: unknown }).window; + t.after(() => { + (globalThis as typeof globalThis & { window?: unknown }).window = originalWindow; + }); + + const dataHandlers = new Map void>(); + const endHandlers = new Map void>(); + const sentBodies: Array> = []; + const emitChatChunk = (emit: (data: string) => void, delta: Record, finishReason?: string) => { + emit(JSON.stringify({ + id: 'chatcmpl-one-api-later-empty-test', + object: 'chat.completion.chunk', + created: 1777600000, + model: 'deepseek-chat', + choices: [{ index: 0, delta, finish_reason: finishReason ?? null }], + })); + }; + + (globalThis as typeof globalThis & { window?: unknown }).window = { + netcatty: { + aiFetch: async () => ({ ok: true, status: 200, data: '{}' }), + aiChatCancel: async () => true, + onAiStreamData: (requestId: string, cb: (data: string) => void) => { + dataHandlers.set(requestId, cb); + return () => dataHandlers.delete(requestId); + }, + onAiStreamEnd: (requestId: string, cb: () => void) => { + endHandlers.set(requestId, cb); + return () => endHandlers.delete(requestId); + }, + onAiStreamError: () => () => undefined, + aiChatStream: async ( + requestId: string, + _url: string, + _headers: Record, + body: string, + ) => { + sentBodies.push(JSON.parse(body)); + const requestNumber = sentBodies.length; + setTimeout(() => { + const emit = dataHandlers.get(requestId); + assert.ok(emit, 'stream data handler should be registered before aiChatStream starts'); + if (requestNumber === 1) { + emitChatChunk(emit, { + tool_calls: [{ + index: 0, + id: '', + type: '', + function: { name: 'terminal_exec', arguments: '{"command":' }, + }], + }); + emitChatChunk(emit, { + tool_calls: [{ + index: 0, + id: '', + type: '', + function: { name: '', arguments: '"pwd"}' }, + }], + }); + emitChatChunk(emit, {}, 'tool_calls'); + } else { + emitChatChunk(emit, { content: 'tool completed' }); + emitChatChunk(emit, {}, 'stop'); + } + endHandlers.get(requestId)?.(); + }, 0); + return { ok: true, statusCode: 200, statusText: 'OK' }; + }, + }, + }; + + const executedCommands: string[] = []; + const model = createModelFromConfig({ + id: 'deepseek-one-api', + providerId: 'custom', + name: 'DeepSeek One API', + apiKey: 'test-key', + baseURL: 'https://one-api.example/v1', + defaultModel: 'deepseek-chat', + enabled: true, + }); + + const result = streamText({ + model, + messages: [{ role: 'user', content: 'inspect cwd' }], + tools: { + terminal_exec: tool({ + inputSchema: z.object({ command: z.string() }), + execute: async ({ command }) => { + executedCommands.push(command); + return { ok: true }; + }, + }), + }, + stopWhen: stepCountIs(2), + }); + + let text = ''; + for await (const chunk of result.fullStream) { + if (chunk.type === 'text-delta') { + text += chunk.text; + } + } + + assert.deepEqual(executedCommands, ['pwd']); + assert.equal(text, 'tool completed'); +}); + test('continues OpenAI-compatible tool streams when arguments arrive before the tool id and name', async (t) => { const originalWindow = (globalThis as typeof globalThis & { window?: unknown }).window; t.after(() => { diff --git a/infrastructure/ai/sdk/providers.ts b/infrastructure/ai/sdk/providers.ts index aa5ae63a3..67c1c7b4a 100644 --- a/infrastructure/ai/sdk/providers.ts +++ b/infrastructure/ai/sdk/providers.ts @@ -164,7 +164,18 @@ function createOpenAIChatToolCallNormalizer(requestId: string): (data: string) = : toolCallRecord; if (existingId) { - normalizedToolCalls.push(toolCall); + const normalizedToolCall = normalizeOpenAIChatToolCall(toolCallRecord, existingId); + if ( + normalizedToolCall.id === toolCallRecord.id && + normalizedToolCall.type === toolCallRecord.type && + normalizedToolCall.function === toolCallRecord.function + ) { + normalizedToolCalls.push(toolCall); + } else { + changed = true; + deltaChanged = true; + normalizedToolCalls.push(normalizedToolCall); + } continue; } @@ -180,15 +191,20 @@ function createOpenAIChatToolCallNormalizer(requestId: string): (data: string) = : `call_netcatty_${requestIdToken}_${choiceIndex}_${toolCallIndex}`; toolCallIdsByChoiceAndIndex.set(key, toolCallId); pendingToolCallsByChoiceAndIndex.delete(key); + const normalizedToolCall = normalizeOpenAIChatToolCall(candidateToolCall, toolCallId); - if (candidateToolCall === toolCallRecord && toolCallId === toolCallRecord.id) { + if ( + candidateToolCall === toolCallRecord && + toolCallId === toolCallRecord.id && + normalizedToolCall.type === toolCallRecord.type + ) { normalizedToolCalls.push(toolCall); continue; } changed = true; deltaChanged = true; - normalizedToolCalls.push({ ...candidateToolCall, id: toolCallId }); + normalizedToolCalls.push(normalizedToolCall); } if (!deltaChanged) return choice; @@ -221,10 +237,17 @@ function mergeOpenAIChatToolCallDeltas( const incomingFunction = incomingFn && typeof incomingFn === 'object' ? incomingFn as Record : undefined; - const mergedFunction = { + const mergedFunction: Record = { ...(currentFunction ?? {}), ...(incomingFunction ?? {}), }; + if ( + typeof currentFunction?.name === 'string' && + currentFunction.name && + incomingFunction?.name === '' + ) { + mergedFunction.name = currentFunction.name; + } const currentArgs = currentFunction?.arguments; const incomingArgs = incomingFunction?.arguments; if (typeof currentArgs === 'string' && typeof incomingArgs === 'string') { @@ -238,6 +261,23 @@ function mergeOpenAIChatToolCallDeltas( }; } +function normalizeOpenAIChatToolCall( + toolCall: Record, + toolCallId: string, +): Record { + const normalized = { ...toolCall, id: toolCallId }; + if (normalized.type === '') { + normalized.type = 'function'; + } + const fn = normalized.function; + if (fn && typeof fn === 'object' && (fn as Record).name === '') { + const normalizedFunction = { ...(fn as Record) }; + delete normalizedFunction.name; + normalized.function = normalizedFunction; + } + return normalized; +} + function hasFunctionName(toolCall: Record): boolean { const fn = toolCall.function; return Boolean( diff --git a/package-lock.json b/package-lock.json index a7f777ccb..3e7c9fd2c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -326,6 +326,29 @@ "win32" ] }, + "node_modules/@anthropic-ai/sdk": { + "version": "0.106.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.106.0.tgz", + "integrity": "sha512-ufwVvYNDBj2dzOGupBCTaNzBLxqcTnGOzI4z8Wouxlt+mT3J3HuOmatgCy1VmwCHOUueqZ41ERhm0O99OUcbWA==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "json-schema-to-ts": "^3.1.1", + "standardwebhooks": "^1.0.0" + }, + "bin": { + "anthropic-ai-sdk": "bin/cli" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } + } + }, "node_modules/@aws-crypto/crc32": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/@aws-crypto/crc32/-/crc32-5.2.0.tgz", @@ -1255,7 +1278,6 @@ "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", @@ -1536,6 +1558,14 @@ "node": ">=6.9.0" } }, + "node_modules/@bufbuild/protobuf": { + "version": "1.10.1", + "resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-1.10.1.tgz", + "integrity": "sha512-wJ8ReQbHxsAfXhrf9ixl0aYbZorRuOWpBNzm8pL8ftmSxQx/wnJD5Eg861NwJU/czy2VXFIebCeZnZrI9rktIQ==", + "license": "(Apache-2.0 AND BSD-3-Clause)", + "optional": true, + "peer": true + }, "node_modules/@buttercup/fetch": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/@buttercup/fetch/-/fetch-0.2.1.tgz", @@ -1854,7 +1884,6 @@ "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.3.tgz", "integrity": "sha512-QwCZW6Tt1siP37Jet9Tb02Zs81TQt6qQrZR2H+eGMcFsL1zMrk2/b9CLC7/9ieP1fjIUMgviLWMmgiHoJrj+ZA==", "license": "MIT", - "peer": true, "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.23.0", @@ -1944,7 +1973,6 @@ "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.6.0.tgz", "integrity": "sha512-4nbvra5R5EtiCzr9BTHiTLc+MLXK2QGiAVYMyi8PkQd3SR+6ixar/Q/01Fa21TBIDOZXgeWV4WppsQolSreAPQ==", "license": "MIT", - "peer": true, "dependencies": { "@marijn/find-cluster-break": "^1.0.0" } @@ -1954,7 +1982,6 @@ "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.1.tgz", "integrity": "sha512-+BIjw/AG3tDQ4pJgTLPYdAW25eDE66YsvM4LKyVPgGzVgZ4a9Wj1SRX8kPVKgBDdPt8oHtZ15F0qx7p0oOHdHw==", "license": "MIT", - "peer": true, "dependencies": { "@codemirror/state": "^6.6.0", "crelt": "^1.0.6", @@ -1962,6 +1989,16 @@ "w3c-keyname": "^2.2.4" } }, + "node_modules/@connectrpc/connect": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@connectrpc/connect/-/connect-1.7.0.tgz", + "integrity": "sha512-iNKdJRi69YP3mq6AePRT8F/HrxWCewrhxnLMNm0vpqXAR8biwzRtO6Hjx80C6UvtKJ5sFmffQT7I4Baecz389w==", + "license": "Apache-2.0", + "optional": true, + "peerDependencies": { + "@bufbuild/protobuf": "^1.10.0" + } + }, "node_modules/@connectrpc/connect-node": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/@connectrpc/connect-node/-/connect-node-1.7.0.tgz", @@ -2409,6 +2446,7 @@ "dev": true, "license": "BSD-2-Clause", "optional": true, + "peer": true, "dependencies": { "cross-dirname": "^0.1.0", "debug": "^4.3.4", @@ -2430,6 +2468,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", @@ -3839,7 +3878,6 @@ "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz", "integrity": "sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==", "license": "MIT", - "peer": true, "dependencies": { "@lezer/common": "^1.3.0" } @@ -4122,7 +4160,6 @@ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz", "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==", "license": "MIT", - "peer": true, "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", @@ -7545,7 +7582,8 @@ "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz", "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==", "license": "MIT", - "optional": true + "optional": true, + "peer": true }, "node_modules/@standard-schema/spec": { "version": "1.1.0", @@ -8155,7 +8193,6 @@ "integrity": "sha512-hAAP5io/7csFStuOmR782YmTthKBJ9ND3WVL60hcOjvtGFb+HJxH4O5huAcmcZ9v9G8P+JETiZ/G1B8MALnWZQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.54.0", @@ -8185,7 +8222,6 @@ "integrity": "sha512-BtE0k6cjwjLZoZixN0t5AKP0kSzlGu7FctRXYuPAm//aaiZhmfq1JwdYpYr1brzEspYyFeF+8XF5j2VK6oalrA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.54.0", "@typescript-eslint/types": "8.54.0", @@ -8539,7 +8575,6 @@ "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.1.0-beta.220.tgz", "integrity": "sha512-rwEKE75wfwfNWeGnjl0iQRA1W50HigKoGcGMeF3o5CqDSdI9IjmwzpV9xHXqLH6CYj6s9N1g6bbKFVDou9dJ/A==", "license": "MIT", - "peer": true, "workspaces": [ "addons/*" ] @@ -8604,7 +8639,6 @@ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -9306,7 +9340,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", @@ -10132,7 +10165,8 @@ "integrity": "sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q==", "dev": true, "license": "MIT", - "optional": true + "optional": true, + "peer": true }, "node_modules/cross-env": { "version": "10.1.0", @@ -10429,7 +10463,6 @@ "integrity": "sha512-fMkjRqKyPtsz4Kzu/qGP0BGjqzMCIgp+/7kw/u6YH6lvn/8hvL3c0TXhoFayBoYdpPCnEinnCHztd4bW7/jetA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "app-builder-lib": "26.15.2", "builder-util": "26.15.0", @@ -10711,6 +10744,7 @@ "dev": true, "hasInstallScript": true, "license": "MIT", + "peer": true, "dependencies": { "@electron/asar": "^3.2.1", "debug": "^4.1.1", @@ -10731,6 +10765,7 @@ "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "graceful-fs": "^4.1.2", "jsonfile": "^4.0.0", @@ -10746,6 +10781,7 @@ "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", "dev": true, "license": "MIT", + "peer": true, "optionalDependencies": { "graceful-fs": "^4.1.6" } @@ -10756,6 +10792,7 @@ "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">= 4.0.0" } @@ -10980,7 +11017,6 @@ "integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.1", @@ -11434,7 +11470,8 @@ "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz", "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==", "license": "Unlicense", - "optional": true + "optional": true, + "peer": true }, "node_modules/fast-uri": { "version": "3.1.0", @@ -12371,7 +12408,6 @@ "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.14.tgz", "integrity": "sha512-am5zfg3yu6sqn5yjKBNqhnTX7Cv+m00ox+7jbaKkrLMRJ4rAdldd1xPd/JzbBWspqaQv6RSTrgFN95EsfhC+7w==", "license": "MIT", - "peer": true, "engines": { "node": ">=16.9.0" } @@ -12828,6 +12864,7 @@ "resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz", "integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==", "license": "MIT", + "peer": true, "funding": { "type": "GitHub Sponsors ❤", "url": "https://github.com/sponsors/dmonad" @@ -12949,6 +12986,7 @@ "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", "license": "MIT", "optional": true, + "peer": true, "dependencies": { "@babel/runtime": "^7.18.3", "ts-algebra": "^2.0.0" @@ -13106,6 +13144,7 @@ "resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.117.tgz", "integrity": "sha512-DeXj9X5xDCjgKLU/7RR+/HQEVzuuEUiwldwOGsHK/sfAfELGWEyTcf0x+uOvCvK3O2zPmZePXWL85vtia6GyZw==", "license": "MIT", + "peer": true, "dependencies": { "isomorphic.js": "^0.2.4" }, @@ -14051,7 +14090,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", @@ -15172,6 +15210,7 @@ "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "minimist": "^1.2.6" }, @@ -15191,7 +15230,6 @@ "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.55.1.tgz", "integrity": "sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A==", "license": "MIT", - "peer": true, "dependencies": { "dompurify": "3.2.7", "marked": "14.0.0" @@ -15942,6 +15980,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "commander": "^9.4.0" }, @@ -15959,6 +15998,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": "^12.20.0 || >=14" } @@ -16263,7 +16303,6 @@ "resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz", "integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==", "license": "MIT", - "peer": true, "engines": { "node": ">=0.10.0" } @@ -16273,7 +16312,6 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz", "integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==", "license": "MIT", - "peer": true, "dependencies": { "scheduler": "^0.27.0" }, @@ -17611,6 +17649,7 @@ "integrity": "sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==", "license": "MIT", "optional": true, + "peer": true, "dependencies": { "@stablelib/base64": "^1.0.0", "fast-sha256": "^1.3.0" @@ -17916,6 +17955,7 @@ "integrity": "sha512-yYrrsWnrXMcdsnu/7YMYAofM1ktpL5By7vZhf15CrXijWWrEYZks5AXBudalfSWJLlnen/QUJUB5aoB0kqZUGA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "mkdirp": "^0.5.1", "rimraf": "~2.6.2" @@ -17942,6 +17982,7 @@ "deprecated": "Rimraf versions prior to v4 are no longer supported", "dev": true, "license": "ISC", + "peer": true, "dependencies": { "glob": "^7.1.3" }, @@ -18016,7 +18057,6 @@ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -18111,7 +18151,8 @@ "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", "license": "MIT", - "optional": true + "optional": true, + "peer": true }, "node_modules/ts-api-utils": { "version": "2.4.0", @@ -18138,7 +18179,6 @@ "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "esbuild": "~0.27.0", "get-tsconfig": "^4.7.5" @@ -18250,7 +18290,6 @@ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -18291,7 +18330,6 @@ "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz", "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==", "license": "MIT", - "peer": true, "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", @@ -18667,7 +18705,6 @@ "integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", @@ -18761,7 +18798,6 @@ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -19049,7 +19085,6 @@ "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", "license": "MIT", - "peer": true, "funding": { "url": "https://github.com/sponsors/colinhacks" } From d010065da16c19c4fcfc42863ae746c2d61d23fc Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 01:00:31 +0800 Subject: [PATCH 065/228] Add terminal context read tool for AI --- components/Terminal.tsx | 108 +++++++++ components/ai/ChatMessageList.tsx | 15 ++ .../TerminalArtifactCard.test.tsx | 45 ++++ .../ai/toolArtifacts/TerminalArtifactCard.tsx | 73 ++++++ .../TerminalArtifactToolResult.tsx | 38 ++++ .../formatTerminalToolTooltip.ts | 25 ++ .../terminalToolArtifact.test.ts | 48 ++++ .../ai/toolArtifacts/terminalToolArtifact.ts | 96 ++++++++ .../terminal/terminalContextBuffer.test.ts | 59 +++++ components/terminal/terminalContextBuffer.ts | 42 ++++ components/terminal/terminalHelpers.ts | 2 + .../terminal/terminalHibernateRuntime.test.ts | 41 +++- .../terminal/terminalHibernateRuntime.ts | 23 ++ components/terminal/terminalMemo.test.ts | 10 + components/terminal/terminalMemo.ts | 1 + .../terminal/useTerminalHibernateEffect.ts | 12 + .../terminalLayer/TerminalLayerSupport.tsx | 7 + .../terminalLayer/TerminalLayerTabBridge.tsx | 16 ++ .../TerminalLayerWorkspaceSection.tsx | 2 + .../terminalLayer/terminalLayerViewMemo.ts | 1 + .../terminalLayer/useTerminalAiContexts.ts | 17 +- domain/terminalContextRead.test.ts | 98 ++++++++ domain/terminalContextRead.ts | 214 ++++++++++++++++++ electron/capabilities/catalog/harness.cjs | 18 ++ .../capabilities/catalog/integrity.test.cjs | 3 +- .../codegen/toolSurfaces.test.cjs | 3 +- electron/capabilities/schemas/toolInputs.cjs | 6 + infrastructure/ai/cattyAgent/executor.ts | 4 + .../ai/harness/capabilityTools.test.ts | 114 ++++++++++ infrastructure/ai/harness/capabilityTools.ts | 39 ++++ .../ai/harness/generated/cattyToolSpecs.json | 38 ++++ package.json | 2 +- 32 files changed, 1209 insertions(+), 11 deletions(-) create mode 100644 components/ai/toolArtifacts/TerminalArtifactCard.test.tsx create mode 100644 components/ai/toolArtifacts/TerminalArtifactCard.tsx create mode 100644 components/ai/toolArtifacts/TerminalArtifactToolResult.tsx create mode 100644 components/ai/toolArtifacts/formatTerminalToolTooltip.ts create mode 100644 components/ai/toolArtifacts/terminalToolArtifact.test.ts create mode 100644 components/ai/toolArtifacts/terminalToolArtifact.ts create mode 100644 components/terminal/terminalContextBuffer.test.ts create mode 100644 components/terminal/terminalContextBuffer.ts create mode 100644 domain/terminalContextRead.test.ts create mode 100644 domain/terminalContextRead.ts 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", From 2c485e9806df6f0c2e4495bce5084acfcde065db Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 01:49:34 +0800 Subject: [PATCH 066/228] Address compose multiline review feedback --- electron/bridges/terminalBridge.cjs | 2 + .../terminalBridge.composeMultiline.test.cjs | 62 +++++++++++++------ 2 files changed, 45 insertions(+), 19 deletions(-) diff --git a/electron/bridges/terminalBridge.cjs b/electron/bridges/terminalBridge.cjs index 92b0fc595..24c426265 100644 --- a/electron/bridges/terminalBridge.cjs +++ b/electron/bridges/terminalBridge.cjs @@ -720,6 +720,8 @@ function isTerminalReportSequence(data) { if (data === "\x1b[I" || data === "\x1b[O") return true; // CPR / DECXCPR / DA1 / DA2 / DSR: ESC [ (?|>)? digits/semicolons (R|c|n) if (/^\x1b\[[?>]?[0-9;]*[Rcn]$/.test(data)) return true; + // Kitty keyboard mode query reply: ESC [ ? digits u + if (/^\x1b\[\?[0-9]+u$/.test(data)) return true; // DCS replies (XTGETTCAP / DECRQSS, etc.): ESC P ... ESC \ if (/^\x1bP[\s\S]*\x1b\\$/.test(data)) return true; return false; diff --git a/electron/bridges/terminalBridge.composeMultiline.test.cjs b/electron/bridges/terminalBridge.composeMultiline.test.cjs index 5d4b1196d..17025666f 100644 --- a/electron/bridges/terminalBridge.composeMultiline.test.cjs +++ b/electron/bridges/terminalBridge.composeMultiline.test.cjs @@ -1,16 +1,14 @@ /** - * 复现:撰写栏(Compose Bar)发送多行内容时只发出第一行。 + * Repro: multi-line compose bar input only sent the first line. * - * 链路:撰写栏 textarea → executeSnippetCommand(text, false) → 多行+autoRun - * 触发 lineDelayMs=250 → 后端 writeToSession 走"逐行延迟发送":第一行立即发, - * 行2+ 用 setTimeout 排进 session.pendingAutomatedWriteTimers。 + * Path: compose bar textarea -> executeSnippetCommand(text, false) -> + * multi-line autoRun -> lineDelayMs=250 -> backend writeToSession sends the + * first line immediately and queues the remaining lines in + * session.pendingAutomatedWriteTimers. * - * 根因:writeToSession 开头 - * if (!payload.automated) clearPendingAutomatedWrites(session); - * 会被【任何】非自动写入触发——包括 xterm 对第一行命令输出的自动回写 - * (光标位置查询 DSR 响应、焦点上报、bracketed-paste 响应等),它们同样走 - * netcatty:write 且不带 automated 标志 → 清空行2+ 的待发队列 → 只发第一行。 - * 与中文无关:shouldDelayAutoRunSnippetInput 只检测 \n,多行英文同样中招。 + * Root cause: terminal-originated automatic replies used the same netcatty:write + * path without the automated flag. Treating those replies as user input cleared + * queued lines, so only the first line was sent. */ const test = require("node:test"); const assert = require("node:assert/strict"); @@ -30,8 +28,7 @@ function delay(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } -// 断言【期望的正确行为】:无害的终端自动回写不应取消后续行。 -// 因此在修复前,这个测试会失败(实际只发出 "echo one\r" + 那次自动回写)。 +// Expected behavior: harmless terminal auto-replies must not cancel queued lines. test("[REPRO] terminal auto-reply between automated lines must NOT cancel pending lines", async () => { const calls = []; const sessions = new Map(); @@ -40,7 +37,6 @@ test("[REPRO] terminal auto-reply between automated lines must NOT cancel pendin }); initBridge(sessions); - // 撰写栏多行(autoRun → 逐行延迟发送) terminalBridge.writeToSession( { sender: {} }, { @@ -50,9 +46,8 @@ test("[REPRO] terminal auto-reply between automated lines must NOT cancel pendin lineDelayMs: 20, }, ); - assert.deepEqual(calls, ["echo one\r"], "第一行应立即发出"); + assert.deepEqual(calls, ["echo one\r"], "the first line is sent immediately"); - // 模拟 xterm 对第一行命令输出的自动回写(光标位置查询 DSR 响应),非 automated terminalBridge.writeToSession({ sender: {} }, { sessionId: "ssh-1", data: "\x1b[2;1R" }); await delay(80); @@ -60,12 +55,41 @@ test("[REPRO] terminal auto-reply between automated lines must NOT cancel pendin assert.deepEqual( calls, ["echo one\r", "\x1b[2;1R", "echo two\r", "echo three\r"], - "终端自动回写不应清空逐行队列;行2/行3 应照常发出", + "terminal auto-replies should not clear queued line writes", ); }); -// 对照(护栏):真正的用户中断(Ctrl+C)应当取消剩余自动逐行发送。 -// 这是既有的有意行为,修复 REPRO 时不能破坏。当前应通过。 +test("[REPRO] Kitty keyboard query reply must NOT cancel pending lines", async () => { + const calls = []; + const sessions = new Map(); + sessions.set("ssh-1", { + stream: { signal() {}, write(data) { calls.push(data); } }, + }); + initBridge(sessions); + + terminalBridge.writeToSession( + { sender: {} }, + { + sessionId: "ssh-1", + data: "echo one\necho two\necho three\r", + automated: true, + lineDelayMs: 20, + }, + ); + assert.deepEqual(calls, ["echo one\r"], "the first line is sent immediately"); + + terminalBridge.writeToSession({ sender: {} }, { sessionId: "ssh-1", data: "\x1b[?0u" }); + + await delay(80); + + assert.deepEqual( + calls, + ["echo one\r", "\x1b[?0u", "echo two\r", "echo three\r"], + "Kitty query replies should not clear queued line writes", + ); +}); + +// Guardrail: real user interruption must still cancel queued automated writes. test("[GUARD] Ctrl+C between automated lines SHOULD cancel pending lines", async () => { const calls = []; const sessions = new Map(); @@ -83,5 +107,5 @@ test("[GUARD] Ctrl+C between automated lines SHOULD cancel pending lines", async terminalBridge.writeToSession({ sender: {} }, { sessionId: "ssh-1", data: "\x03" }); // Ctrl+C await delay(60); - assert.deepEqual(calls, ["echo one\r", "\x03"], "Ctrl+C 应取消行2(既有设计,修复后须保留)"); + assert.deepEqual(calls, ["echo one\r", "\x03"], "Ctrl+C should cancel queued line writes"); }); From 22ff5d2e16a20613830f5937bad534e2578403ab Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 01:52:55 +0800 Subject: [PATCH 067/228] Fix external tool artifact cards --- components/ai/ChatMessageList.test.tsx | 96 ++++++++++++++++++- components/ai/ChatMessageList.tsx | 37 ++++--- .../ai/toolArtifacts/terminalToolArtifact.ts | 5 +- .../toolArtifacts/toolArtifactNames.test.ts | 27 ++++++ .../ai/toolArtifacts/toolArtifactNames.ts | 70 ++++++++++++++ .../ai/toolArtifacts/vaultToolArtifact.ts | 12 ++- .../turnDrivers/externalSdkTurnDriver.ts | 7 +- infrastructure/ai/types.ts | 2 + 8 files changed, 238 insertions(+), 18 deletions(-) create mode 100644 components/ai/toolArtifacts/toolArtifactNames.test.ts create mode 100644 components/ai/toolArtifacts/toolArtifactNames.ts diff --git a/components/ai/ChatMessageList.test.tsx b/components/ai/ChatMessageList.test.tsx index 57cfc4542..c95aa92dd 100644 --- a/components/ai/ChatMessageList.test.tsx +++ b/components/ai/ChatMessageList.test.tsx @@ -6,6 +6,7 @@ import { renderToStaticMarkup } from "react-dom/server"; import { I18nProvider } from "../../application/i18n/I18nProvider.tsx"; import type { ChatMessage } from "../../infrastructure/ai/types.ts"; import ChatMessageList from "./ChatMessageList.tsx"; +import { TooltipProvider } from "../ui/tooltip.tsx"; const makeMessage = (index: number): ChatMessage => ({ id: `msg-${index}`, @@ -21,7 +22,11 @@ test("ChatMessageList only renders the recent message batch by default", () => { React.createElement( I18nProvider, { locale: "en" }, - React.createElement(ChatMessageList, { messages }), + React.createElement( + TooltipProvider, + null, + React.createElement(ChatMessageList, { messages }), + ), ), ); @@ -30,3 +35,92 @@ test("ChatMessageList only renders the recent message batch by default", () => { assert.match(markup, /message-10/); assert.match(markup, /message-59/); }); + +test("ChatMessageList renders external MCP vault tool results as artifact cards", () => { + const messages: ChatMessage[] = [ + { + id: "tool-1", + role: "tool", + content: "", + timestamp: 1, + toolResults: [ + { + toolCallId: "external-call-1", + toolName: "mcp__netcatty__vault_notes_create", + content: JSON.stringify({ + ok: true, + note: { id: "note-1", title: "Deploy Runbook", group: "ops" }, + }), + }, + ], + }, + ]; + + const markup = renderToStaticMarkup( + React.createElement( + I18nProvider, + { locale: "en" }, + React.createElement( + TooltipProvider, + null, + React.createElement(ChatMessageList, { messages }), + ), + ), + ); + + assert.match(markup, /Deploy Runbook/); + assert.match(markup, /ops/); + assert.doesNotMatch(markup, /external-call-1/); +}); + +test("ChatMessageList renders Netcatty CLI vault results as artifact cards", () => { + const messages: ChatMessage[] = [ + { + id: "assistant-1", + role: "assistant", + content: "", + timestamp: 1, + toolCalls: [ + { + id: "cli-call-1", + name: "shell", + arguments: { + command: `/bin/zsh -lc '"/Applications/Netcatty.app/netcatty-tool-cli" vault host get --host-id host_1 --json'`, + }, + }, + ], + executionStatus: "completed", + }, + { + id: "tool-1", + role: "tool", + content: "", + timestamp: 2, + toolResults: [ + { + toolCallId: "cli-call-1", + content: JSON.stringify({ + ok: true, + host: { id: "host_1", label: "Prod", hostname: "prod.example.com", port: 22 }, + }), + }, + ], + }, + ]; + + const markup = renderToStaticMarkup( + React.createElement( + I18nProvider, + { locale: "en" }, + React.createElement( + TooltipProvider, + null, + React.createElement(ChatMessageList, { messages }), + ), + ), + ); + + assert.match(markup, /Prod/); + assert.match(markup, /prod\.example\.com:22/); + assert.doesNotMatch(markup, /cli-call-1/); +}); diff --git a/components/ai/ChatMessageList.tsx b/components/ai/ChatMessageList.tsx index 25cf5b0c8..07123558f 100644 --- a/components/ai/ChatMessageList.tsx +++ b/components/ai/ChatMessageList.tsx @@ -25,6 +25,10 @@ import { } from './toolArtifacts/VaultArtifactNavigationContext'; import { parseTerminalToolArtifact } from './toolArtifacts/terminalToolArtifact'; import { TerminalArtifactToolResult } from './toolArtifacts/TerminalArtifactToolResult'; +import { + inferArtifactToolNameFromCliArgs, + normalizeArtifactToolName, +} from './toolArtifacts/toolArtifactNames'; import { parseVaultToolArtifact } from './toolArtifacts/vaultToolArtifact'; import { VaultArtifactToolResult } from './toolArtifacts/VaultArtifactToolResult'; import type { Host, VaultNote } from '../../types'; @@ -255,13 +259,23 @@ const ChatMessageList: React.FC = ({ while (end < displayedMessages.length && displayedMessages[end].role === "tool") end++; const group = displayedMessages.slice(idx, end); const toolResults = group.flatMap((toolMsg) => - (toolMsg.toolResults ?? []).map((tr) => ({ - toolCallId: tr.toolCallId, - name: toolCallNames.get(tr.toolCallId) || tr.toolCallId, - args: toolCallArgs.get(tr.toolCallId), - content: tr.content, - isError: tr.isError, - })), + (toolMsg.toolResults ?? []).map((tr) => { + const args = toolCallArgs.get(tr.toolCallId); + const resultToolName = typeof tr.toolName === 'string' ? tr.toolName : undefined; + const pairedToolName = toolCallNames.get(tr.toolCallId); + const artifactToolName = + normalizeArtifactToolName(resultToolName) + ?? inferArtifactToolNameFromCliArgs(args) + ?? normalizeArtifactToolName(pairedToolName); + return { + toolCallId: tr.toolCallId, + name: pairedToolName || resultToolName || tr.toolCallId, + artifactToolName, + args, + content: tr.content, + isError: tr.isError, + }; + }), ); const groupTotal = toolResults.length; @@ -270,26 +284,27 @@ const ChatMessageList: React.FC = ({ && displayedMessages[end].role === "assistant"; const renderToolResultItem = (item: typeof toolResults[number]) => { - const terminalArtifact = parseTerminalToolArtifact(item.name, item.content); + const artifactToolName = item.artifactToolName ?? item.name; + const terminalArtifact = parseTerminalToolArtifact(artifactToolName, item.content); if (terminalArtifact) { return ( ); } - const artifact = parseVaultToolArtifact(item.name, item.content); + const artifact = parseVaultToolArtifact(artifactToolName, item.content); if (artifact) { return ( { + assert.equal( + normalizeArtifactToolName('mcp__netcatty__vault_notes_create'), + 'vault_notes_create', + ); + assert.equal( + normalizeArtifactToolName('mcp__netcatty-remote-hosts__terminal_read_context'), + 'terminal_read_context', + ); +}); + +test('inferArtifactToolNameFromCliArgs maps Netcatty CLI artifact commands', () => { + assert.equal( + inferArtifactToolNameFromCliArgs({ + command: `/bin/zsh -lc '"/Applications/Netcatty.app/netcatty-tool-cli" vault host get --host-id host_1 --json'`, + }), + 'host_get', + ); +}); diff --git a/components/ai/toolArtifacts/toolArtifactNames.ts b/components/ai/toolArtifacts/toolArtifactNames.ts new file mode 100644 index 000000000..88c38235a --- /dev/null +++ b/components/ai/toolArtifacts/toolArtifactNames.ts @@ -0,0 +1,70 @@ +const MCP_TOOL_NAME_PREFIX = 'mcp__'; + +const CLI_ARTIFACT_TOOL_NAMES = new Map([ + ['vault host get', 'host_get'], +]); + +function readCommandString(args: Record | undefined): string | null { + if (!args) return null; + const raw = args.command; + if (typeof raw === 'string') return raw || null; + if (!Array.isArray(raw) || raw.length === 0) return null; + + const isShellWrap = + raw.length >= 3 && + /(?:^|\/)(sh|bash|zsh|fish|ash|dash)$/.test(String(raw[0] ?? '')) && + /^-l?c$/.test(String(raw[1] ?? '')); + + return isShellWrap + ? String(raw[raw.length - 1] ?? '') || null + : raw.map((part) => String(part)).join(' '); +} + +function unwrapShellCommand(command: string): string { + const strWrap = command.match( + /^(?:\S*\/)?(?:sh|bash|zsh|fish|ash|dash)\s+-l?c\s+(['"])([\s\S]*)\1\s*$/, + ); + return strWrap ? strWrap[2] : command; +} + +function stripWrappingQuote(value: string): string { + const trimmed = value.trim(); + if (trimmed.length < 2) return trimmed; + const first = trimmed[0]; + const last = trimmed[trimmed.length - 1]; + return (first === last && (first === '"' || first === "'")) + ? trimmed.slice(1, -1) + : trimmed; +} + +export function normalizeArtifactToolName(toolName: string | undefined): string | undefined { + const trimmed = toolName?.trim(); + if (!trimmed) return undefined; + + if (trimmed.startsWith(MCP_TOOL_NAME_PREFIX)) { + const segments = trimmed.split('__').filter(Boolean); + return segments[segments.length - 1] || trimmed; + } + + return trimmed; +} + +export function inferArtifactToolNameFromCliArgs( + args: Record | undefined, +): string | undefined { + const command = readCommandString(args); + if (!command) return undefined; + + const unwrapped = unwrapShellCommand(command); + const cliMatch = unwrapped.match(/(?:^|\s|["'])(?:\S*\/)?netcatty-tool-cli(?:\.(?:cjs|cmd))?(?=["'\s]|$)([\s\S]*)$/); + if (!cliMatch) return undefined; + + const afterCli = stripWrappingQuote(cliMatch[1] ?? '').replace(/^["']?\s*/, ''); + const commandKey = afterCli + .split(/\s+/) + .filter((part) => part && !part.startsWith('-')) + .slice(0, 3) + .join(' '); + + return CLI_ARTIFACT_TOOL_NAMES.get(commandKey); +} diff --git a/components/ai/toolArtifacts/vaultToolArtifact.ts b/components/ai/toolArtifacts/vaultToolArtifact.ts index 6b23517da..7e57dfc92 100644 --- a/components/ai/toolArtifacts/vaultToolArtifact.ts +++ b/components/ai/toolArtifacts/vaultToolArtifact.ts @@ -1,3 +1,5 @@ +import { normalizeArtifactToolName } from './toolArtifactNames'; + export type VaultToolArtifact = | { kind: 'vault.note'; @@ -116,14 +118,16 @@ function parsePreviewHosts(value: unknown): Array<{ hostId?: string; label?: str } export function isVaultArtifactToolName(toolName: string): boolean { - return VAULT_ARTIFACT_TOOL_NAMES.has(toolName); + const normalized = normalizeArtifactToolName(toolName); + return normalized ? VAULT_ARTIFACT_TOOL_NAMES.has(normalized) : false; } export function parseVaultToolArtifact( toolName: string, result: unknown, ): VaultToolArtifact | null { - if (!isVaultArtifactToolName(toolName)) return null; + const normalizedToolName = normalizeArtifactToolName(toolName); + if (!normalizedToolName || !VAULT_ARTIFACT_TOOL_NAMES.has(normalizedToolName)) return null; const payload = parseResultPayload(result); if (!payload) return null; @@ -133,7 +137,7 @@ export function parseVaultToolArtifact( return { kind: 'error', message }; } - switch (toolName) { + switch (normalizedToolName) { case 'vault_notes_create': case 'vault_notes_update': case 'vault_notes_get': @@ -165,7 +169,7 @@ export function parseVaultToolArtifact( return { kind: 'vault.hosts.batch', - sourceTool: toolName === 'vault_hosts_import' ? 'vault_hosts_import' : 'vault_hosts_create', + sourceTool: normalizedToolName === 'vault_hosts_import' ? 'vault_hosts_import' : 'vault_hosts_create', addedCount, dryRun, preview, diff --git a/infrastructure/ai/harness/turnDrivers/externalSdkTurnDriver.ts b/infrastructure/ai/harness/turnDrivers/externalSdkTurnDriver.ts index 66ac0a799..88732a913 100644 --- a/infrastructure/ai/harness/turnDrivers/externalSdkTurnDriver.ts +++ b/infrastructure/ai/harness/turnDrivers/externalSdkTurnDriver.ts @@ -115,7 +115,12 @@ async function runExternalTurn(input: ExternalTurnInput, ctx: TurnDriverContext) id: generateId(), role: 'tool', content: '', - toolResults: [{ toolCallId, content: result, isError: isToolResultError(result) }], + toolResults: [{ + toolCallId, + toolName, + content: result, + isError: isToolResultError(result), + }], timestamp: Date.now(), executionStatus: 'completed', }); diff --git a/infrastructure/ai/types.ts b/infrastructure/ai/types.ts index fa25355b1..71725c669 100644 --- a/infrastructure/ai/types.ts +++ b/infrastructure/ai/types.ts @@ -152,6 +152,8 @@ export interface ToolCall { export interface ToolResult { toolCallId: string; + /** Optional tool name carried by external SDK/MCP result streams. */ + toolName?: string; content: string; isError?: boolean; } From 09268f9b97d0799f9e4a3ae19f2f715c33825845 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 01:56:40 +0800 Subject: [PATCH 068/228] Open AI note artifacts in side panel --- components/TerminalLayer.tsx | 23 +++++- .../VaultArtifactNavigationContext.test.ts | 58 +++++++++++++++ .../VaultArtifactNavigationContext.tsx | 74 +++++++++++++------ .../aiNoteArtifactPanelIntent.test.ts | 34 +++++++++ .../aiNoteArtifactPanelIntent.ts | 34 +++++++++ 5 files changed, 200 insertions(+), 23 deletions(-) create mode 100644 components/ai/toolArtifacts/VaultArtifactNavigationContext.test.ts create mode 100644 components/terminalLayer/aiNoteArtifactPanelIntent.test.ts create mode 100644 components/terminalLayer/aiNoteArtifactPanelIntent.ts diff --git a/components/TerminalLayer.tsx b/components/TerminalLayer.tsx index 2635c893e..a00bdfebb 100644 --- a/components/TerminalLayer.tsx +++ b/components/TerminalLayer.tsx @@ -59,6 +59,7 @@ import { resolveSidePanelToggleIntent } from '../application/state/resolveSidePa import { resolveAiSidePanelToggleIntent } from '../application/state/resolveAiSidePanelToggleIntent'; import { terminalLayerAreEqual } from './terminalLayerMemo'; import { TerminalLayerTabBridge } from './terminalLayer/TerminalLayerTabBridge'; +import { resolveAiNoteArtifactPanelIntent } from './terminalLayer/aiNoteArtifactPanelIntent'; import { canUseDirectSessionWriteFallback, } from './terminalLayer/terminalLayerSessionRouting'; @@ -1128,6 +1129,26 @@ const TerminalLayerInner: React.FC = ({ openNotesPanelForSourceNote(openNoteRequest.tabId, openNoteRequest.noteId); }, [openNoteRequest, openNotesPanelForSourceNote]); + const handleOpenVaultNoteFromAiPanel = useCallback((noteId: string) => { + const intent = resolveAiNoteArtifactPanelIntent({ + activeTabId: activeTabIdRef.current, + currentPanel: activeTabIdRef.current + ? sidePanelOpenTabsRef.current.get(activeTabIdRef.current) ?? null + : null, + noteId, + }); + + if (intent.kind === 'fallback') { + onOpenVaultNoteFromChat?.(intent.noteId); + return; + } + + if (intent.returnPanel) { + notesReturnTabRef.current.set(intent.tabId, intent.returnPanel); + } + openNotesPanelForSourceNote(intent.tabId, intent.noteId); + }, [onOpenVaultNoteFromChat, openNotesPanelForSourceNote]); + const handleAddSelectionToAI = useCallback((sourceSessionId: string, selection: string) => { const text = selection.trim(); if (!text) return; @@ -1456,7 +1477,7 @@ const TerminalLayerInner: React.FC = ({ noteGroups, notes, onOpenVaultHostFromChat, - onOpenVaultNoteFromChat, + onOpenVaultNoteFromChat: handleOpenVaultNoteFromAiPanel, onOpenVaultSectionFromChat, splitHorizontalHandlersRef, splitVerticalHandlersRef, diff --git a/components/ai/toolArtifacts/VaultArtifactNavigationContext.test.ts b/components/ai/toolArtifacts/VaultArtifactNavigationContext.test.ts new file mode 100644 index 000000000..93a199797 --- /dev/null +++ b/components/ai/toolArtifacts/VaultArtifactNavigationContext.test.ts @@ -0,0 +1,58 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { + createVaultArtifactNavigationActions, + navigateVaultArtifact, +} from './VaultArtifactNavigationContext.tsx'; + +const t = (key: string) => key; + +test('clicking an existing note artifact opens that note', () => { + const openedNotes: string[] = []; + const unavailable: Array<{ title: string; message: string }> = []; + const navigation = createVaultArtifactNavigationActions({ + notes: [{ id: 'note-1', title: 'Runbook', content: '', createdAt: 1, updatedAt: 1 }], + hosts: [], + t, + onOpenVaultNote: (noteId) => openedNotes.push(noteId), + onOpenVaultHost: () => {}, + onOpenVaultSection: () => {}, + onUnavailable: (message, title) => unavailable.push({ title, message }), + }); + + navigateVaultArtifact({ + kind: 'vault.note', + noteId: 'note-1', + title: 'Runbook', + }, navigation); + + assert.deepEqual(openedNotes, ['note-1']); + assert.deepEqual(unavailable, []); +}); + +test('clicking a missing note artifact shows an unavailable message instead of opening', () => { + const openedNotes: string[] = []; + const unavailable: Array<{ title: string; message: string }> = []; + const navigation = createVaultArtifactNavigationActions({ + notes: [], + hosts: [], + t, + onOpenVaultNote: (noteId) => openedNotes.push(noteId), + onOpenVaultHost: () => {}, + onOpenVaultSection: () => {}, + onUnavailable: (message, title) => unavailable.push({ title, message }), + }); + + navigateVaultArtifact({ + kind: 'vault.note', + noteId: 'deleted-note', + title: 'Deleted note', + }, navigation); + + assert.deepEqual(openedNotes, []); + assert.deepEqual(unavailable, [{ + title: 'ai.chat.artifact.unavailableTitle', + message: 'ai.chat.artifact.noteMissing', + }]); +}); diff --git a/components/ai/toolArtifacts/VaultArtifactNavigationContext.tsx b/components/ai/toolArtifacts/VaultArtifactNavigationContext.tsx index 07d8d7e14..5b3c98a6d 100644 --- a/components/ai/toolArtifacts/VaultArtifactNavigationContext.tsx +++ b/components/ai/toolArtifacts/VaultArtifactNavigationContext.tsx @@ -10,6 +10,16 @@ export interface VaultArtifactNavigationActions { openVaultSection: (section: 'notes' | 'hosts') => void; } +interface CreateVaultArtifactNavigationActionsOptions { + notes: VaultNote[]; + hosts: Host[]; + t: (key: string) => string; + onOpenVaultNote: (noteId: string) => void; + onOpenVaultHost: (hostId: string) => void; + onOpenVaultSection: (section: 'notes' | 'hosts') => void; + onUnavailable: (message: string, title: string) => void; +} + interface VaultArtifactNavigationProviderProps { notes: VaultNote[]; hosts: Host[]; @@ -21,6 +31,36 @@ interface VaultArtifactNavigationProviderProps { const VaultArtifactNavigationContext = createContext(null); +export function createVaultArtifactNavigationActions({ + notes, + hosts, + t, + onOpenVaultNote, + onOpenVaultHost, + onOpenVaultSection, + onUnavailable, +}: CreateVaultArtifactNavigationActionsOptions): VaultArtifactNavigationActions { + return { + openVaultNote: (noteId: string) => { + const exists = notes.some((note) => note.id === noteId); + if (!exists) { + onUnavailable(t('ai.chat.artifact.noteMissing'), t('ai.chat.artifact.unavailableTitle')); + return; + } + onOpenVaultNote(noteId); + }, + openVaultHost: (hostId: string) => { + const exists = hosts.some((host) => host.id === hostId); + if (!exists) { + onUnavailable(t('ai.chat.artifact.hostMissing'), t('ai.chat.artifact.unavailableTitle')); + return; + } + onOpenVaultHost(hostId); + }, + openVaultSection: onOpenVaultSection, + }; +} + export function VaultArtifactNavigationProvider({ notes, hosts, @@ -31,29 +71,19 @@ export function VaultArtifactNavigationProvider({ }: VaultArtifactNavigationProviderProps) { const { t } = useI18n(); - const openVaultNote = useCallback((noteId: string) => { - const exists = notes.some((note) => note.id === noteId); - if (!exists) { - toast.warning(t('ai.chat.artifact.noteMissing'), t('ai.chat.artifact.unavailableTitle')); - return; - } - onOpenVaultNote(noteId); - }, [notes, onOpenVaultNote, t]); + const onUnavailable = useCallback((message: string, title: string) => { + toast.warning(message, title); + }, []); - const openVaultHost = useCallback((hostId: string) => { - const exists = hosts.some((host) => host.id === hostId); - if (!exists) { - toast.warning(t('ai.chat.artifact.hostMissing'), t('ai.chat.artifact.unavailableTitle')); - return; - } - onOpenVaultHost(hostId); - }, [hosts, onOpenVaultHost, t]); - - const value = useMemo(() => ({ - openVaultNote, - openVaultHost, - openVaultSection: onOpenVaultSection, - }), [onOpenVaultHost, onOpenVaultNote, onOpenVaultSection, openVaultHost, openVaultNote]); + const value = useMemo(() => createVaultArtifactNavigationActions({ + notes, + hosts, + t, + onOpenVaultNote, + onOpenVaultHost, + onOpenVaultSection, + onUnavailable, + }), [hosts, notes, onOpenVaultHost, onOpenVaultNote, onOpenVaultSection, onUnavailable, t]); return ( diff --git a/components/terminalLayer/aiNoteArtifactPanelIntent.test.ts b/components/terminalLayer/aiNoteArtifactPanelIntent.test.ts new file mode 100644 index 000000000..7d7ed654c --- /dev/null +++ b/components/terminalLayer/aiNoteArtifactPanelIntent.test.ts @@ -0,0 +1,34 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { resolveAiNoteArtifactPanelIntent } from './aiNoteArtifactPanelIntent.ts'; + +test('AI note artifact opens the notes side panel for the active tab and returns to AI', () => { + assert.deepEqual( + resolveAiNoteArtifactPanelIntent({ + activeTabId: 'session-1', + currentPanel: 'ai', + noteId: 'note-1', + }), + { + kind: 'openNotesSidePanel', + tabId: 'session-1', + noteId: 'note-1', + returnPanel: 'ai', + }, + ); +}); + +test('AI note artifact falls back when there is no active side-panel tab', () => { + assert.deepEqual( + resolveAiNoteArtifactPanelIntent({ + activeTabId: '', + currentPanel: null, + noteId: 'note-1', + }), + { + kind: 'fallback', + noteId: 'note-1', + }, + ); +}); diff --git a/components/terminalLayer/aiNoteArtifactPanelIntent.ts b/components/terminalLayer/aiNoteArtifactPanelIntent.ts new file mode 100644 index 000000000..caeae9ded --- /dev/null +++ b/components/terminalLayer/aiNoteArtifactPanelIntent.ts @@ -0,0 +1,34 @@ +import type { SidePanelTab } from './TerminalLayerSupport'; + +export type AiNoteArtifactPanelIntent = + | { + kind: 'openNotesSidePanel'; + tabId: string; + noteId: string; + returnPanel: SidePanelTab | null; + } + | { + kind: 'fallback'; + noteId: string; + }; + +export function resolveAiNoteArtifactPanelIntent({ + activeTabId, + currentPanel, + noteId, +}: { + activeTabId: string | null | undefined; + currentPanel: SidePanelTab | null; + noteId: string; +}): AiNoteArtifactPanelIntent { + if (!activeTabId) { + return { kind: 'fallback', noteId }; + } + + return { + kind: 'openNotesSidePanel', + tabId: activeTabId, + noteId, + returnPanel: currentPanel && currentPanel !== 'notes' ? currentPanel : null, + }; +} From 92da1893600fbc6a9ab5733ed35de2b4aa40a64f Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 01:50:58 +0800 Subject: [PATCH 069/228] Fix Catty attachment visibility --- components/ai/hooks/aiChatStreamingSupport.ts | 4 + electron/bridges/aiBridge.test.cjs | 39 ++++++++ .../bridges/aiBridge/agentProcessHandlers.cjs | 6 ++ .../codegen/toolSurfaces.test.cjs | 9 ++ electron/capabilities/schemas/toolInputs.cjs | 2 +- electron/preload/api.cjs | 3 + electron/shared/vaultAgentGuidance.cjs | 4 +- electron/shared/vaultAgentGuidance.test.cjs | 7 ++ .../ai/cattyAgent/systemPrompt.test.ts | 18 ++++ infrastructure/ai/cattyAgent/systemPrompt.ts | 2 + .../cattyTurnDriver.attachments.test.ts | 98 +++++++++++++++++++ .../ai/harness/generated/cattyToolSpecs.json | 2 +- .../generated/globalAgentToolSpecs.json | 2 +- .../ai/harness/turnDrivers/cattyTurnDriver.ts | 4 +- 14 files changed, 195 insertions(+), 5 deletions(-) create mode 100644 infrastructure/ai/cattyAgent/systemPrompt.test.ts create mode 100644 infrastructure/ai/harness/cattyTurnDriver.attachments.test.ts diff --git a/components/ai/hooks/aiChatStreamingSupport.ts b/components/ai/hooks/aiChatStreamingSupport.ts index 575916925..5b5806a26 100644 --- a/components/ai/hooks/aiChatStreamingSupport.ts +++ b/components/ai/hooks/aiChatStreamingSupport.ts @@ -94,6 +94,10 @@ export interface PanelBridge extends NetcattyBridge { aiSyncProviders?: (providers: Array<{ id: string; providerId: string; apiKey?: string; baseURL?: string; enabled: boolean }>) => Promise<{ ok: boolean }>; aiSyncWebSearch?: (apiHost: string | null, apiKey: string | null) => Promise<{ ok: boolean }>; aiMcpUpdateSessions?: (sessions: TerminalSessionInfo[], chatSessionId?: string) => Promise; + aiMcpUpdateAttachments?: ( + attachments: Array<{ base64Data?: string; mediaType?: string; filename?: string; filePath?: string }>, + chatSessionId?: string, + ) => Promise; aiSdkAgentListModels?: ( sdkBackend: string, cwd?: string, diff --git a/electron/bridges/aiBridge.test.cjs b/electron/bridges/aiBridge.test.cjs index 4d62550e9..5affda194 100644 --- a/electron/bridges/aiBridge.test.cjs +++ b/electron/bridges/aiBridge.test.cjs @@ -30,6 +30,9 @@ function loadBridgeWithMocks(options = {}) { ? options.getPermissionMode() : "default", getMaxIterations: () => 20, + updateAttachmentMetadata: (...args) => { + if (typeof options.updateAttachmentMetadata === "function") options.updateAttachmentMetadata(...args); + }, setChatSessionCancelled() {}, cancelPtyExecsForSession() {}, clearPendingApprovals() {}, @@ -175,6 +178,42 @@ function loadBridgeWithMocks(options = {}) { } } +test("mcp attachment update handler forwards current chat attachments", async () => { + const calls = []; + const { bridge, restore } = loadBridgeWithMocks({ + updateAttachmentMetadata: (attachments, chatSessionId) => calls.push({ attachments, chatSessionId }), + }); + const ipcMain = createIpcMainStub(); + + bridge.init({ + sessions: new Map(), + sftpClients: new Map(), + electronModule: { app: { getPath: () => process.cwd() } }, + }); + bridge.registerHandlers(ipcMain); + + try { + const updateAttachments = ipcMain.handlers.get("netcatty:ai:mcp:update-attachments"); + assert.equal(typeof updateAttachments, "function"); + const attachments = [{ + filename: "hosts_export_2026-06-25.csv", + mediaType: "text/csv", + base64Data: Buffer.from("label,hostname\nprod,prod.example.com\n").toString("base64"), + filePath: "/tmp/hosts_export_2026-06-25.csv", + }]; + + const result = await updateAttachments({ sender: { id: 1 } }, { + attachments, + chatSessionId: "chat-1", + }); + + assert.deepEqual(result, { ok: true }); + assert.deepEqual(calls, [{ attachments, chatSessionId: "chat-1" }]); + } finally { + restore(); + } +}); + test("discover returns the 3-layer contract for an installed, authenticated agent", async (t) => { const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-discover-contract-")); t.after(() => fs.rmSync(tempDir, { recursive: true, force: true })); diff --git a/electron/bridges/aiBridge/agentProcessHandlers.cjs b/electron/bridges/aiBridge/agentProcessHandlers.cjs index 0d217f328..bc120a0fd 100644 --- a/electron/bridges/aiBridge/agentProcessHandlers.cjs +++ b/electron/bridges/aiBridge/agentProcessHandlers.cjs @@ -9,6 +9,12 @@ function registerAgentProcessHandlers(ctx) { return { ok: true }; }); + ipcMain.handle("netcatty:ai:mcp:update-attachments", async (event, { attachments, chatSessionId }) => { + if (!validateSenderOrSettings(event)) return { ok: false, error: "Unauthorized IPC sender" }; + mcpServerBridge.updateAttachmentMetadata(attachments || [], chatSessionId); + return { ok: true }; + }); + ipcMain.handle("netcatty:ai:mcp:set-command-blocklist", async (event, { blocklist }) => { if (!validateSenderOrSettings(event)) return { ok: false, error: "Unauthorized IPC sender" }; // Validate: must be an array of strings, each a valid regex pattern diff --git a/electron/capabilities/codegen/toolSurfaces.test.cjs b/electron/capabilities/codegen/toolSurfaces.test.cjs index 938fdd54a..9109bcbe3 100644 --- a/electron/capabilities/codegen/toolSurfaces.test.cjs +++ b/electron/capabilities/codegen/toolSurfaces.test.cjs @@ -47,6 +47,15 @@ test("listCattyToolSpecs includes vault host tools and SFTP transfer", () => { assert.ok(capabilityIds.includes("sftp.upload")); }); +test("vault host import tool description routes unknown attached host text to host creation", () => { + const importSpec = listCattyToolSpecs().find((spec) => spec.capabilityId === "vault.host.import"); + assert.ok(importSpec); + assert.match(importSpec.description, /known export formats/i); + assert.match(importSpec.description, /unknown/i); + assert.match(importSpec.description, /read_attachment/i); + assert.match(importSpec.description, /vault_hosts_create/i); +}); + test("listCattyToolSpecs binds vault note tools to global RPC methods", () => { const specs = listCattyToolSpecs(); const noteCreate = specs.find((spec) => spec.capabilityId === "vault.note.create"); diff --git a/electron/capabilities/schemas/toolInputs.cjs b/electron/capabilities/schemas/toolInputs.cjs index 4a59eb09b..63d8d6b93 100644 --- a/electron/capabilities/schemas/toolInputs.cjs +++ b/electron/capabilities/schemas/toolInputs.cjs @@ -198,7 +198,7 @@ const MODEL_DESCRIPTION_HINTS = Object.freeze({ "vault.host.notes.set": "Host metadata notes on a saved host — not Vault → Notes sidebar entries. Prefer vault_notes_create/update when the user wants vault notes they can open in the Notes sidebar.", "vault.host.import": - "Only for text in known export formats (PuTTY reg, MobaXterm ini, CSV template, SecureCRT, ssh_config). For arbitrary unstructured host lists from the user, extract fields yourself and call vault_hosts_create.", + "Only for text in known export formats (PuTTY reg, MobaXterm ini, CSV template, SecureCRT, ssh_config). If attached host text is unknown or auto-detection fails, use read_attachment content, extract fields yourself, and call vault_hosts_create.", "vault.hosts.create": "Use when the user wants to add/create a host in Vault → Hosts (创建主机、SSH 连接凭据). NOT for Vault → Notes sidebar docs. Put SSH password in password field; long remarks/admin tables in host notes field. Never fall back to vault_notes_create if this fails.", "vault.note.create": diff --git a/electron/preload/api.cjs b/electron/preload/api.cjs index a5174cc21..c42448a5a 100644 --- a/electron/preload/api.cjs +++ b/electron/preload/api.cjs @@ -968,6 +968,9 @@ function createPreloadApi(ctx) { aiMcpUpdateSessions: async (sessions, chatSessionId) => { return ipcRenderer.invoke("netcatty:ai:mcp:update-sessions", { sessions, chatSessionId }); }, + aiMcpUpdateAttachments: async (attachments, chatSessionId) => { + return ipcRenderer.invoke("netcatty:ai:mcp:update-attachments", { attachments, chatSessionId }); + }, aiMcpSetCommandBlocklist: async (blocklist) => { return ipcRenderer.invoke("netcatty:ai:mcp:set-command-blocklist", { blocklist }); }, diff --git a/electron/shared/vaultAgentGuidance.cjs b/electron/shared/vaultAgentGuidance.cjs index 97fd77a33..a1947d1b3 100644 --- a/electron/shared/vaultAgentGuidance.cjs +++ b/electron/shared/vaultAgentGuidance.cjs @@ -8,7 +8,9 @@ const VAULT_HOSTS_VS_NOTES_GUIDANCE = "Vault → Hosts vs Vault → Notes: When the user asks to add/create/import a host " + "(创建主机、添加主机、保存 SSH 连接凭据), use vault_hosts_create with dryRun=true first, " + "or vault_hosts_import for known export formats (PuTTY, MobaXterm, CSV, SecureCRT, ssh_config) — " - + "NOT vault_notes_create. Extract hostname, username, password, port, group, tags, and label from the user's text; " + + "NOT vault_notes_create. For attached host files, use vault_hosts_import only when the attachment is a known export format; " + + "for unknown attached host/server text, read the attachment content, extract hostname, username, password, port, group, tags, and label yourself, " + + "then call vault_hosts_create with dryRun=true first. Extract hostname, username, password, port, group, tags, and label from the user's text; " + "put long admin tables or remarks in the host notes field (host_notes_set / Host Details metadata), " + "not Vault sidebar Notes. Use vault_notes_create or vault_notes_update ONLY when the user explicitly wants " + "markdown documentation in Vault → Notes (保险箱笔记 sidebar). " diff --git a/electron/shared/vaultAgentGuidance.test.cjs b/electron/shared/vaultAgentGuidance.test.cjs index 3bd6416de..236c36180 100644 --- a/electron/shared/vaultAgentGuidance.test.cjs +++ b/electron/shared/vaultAgentGuidance.test.cjs @@ -14,6 +14,13 @@ test("VAULT_HOSTS_VS_NOTES_GUIDANCE forbids note fallback for host creation", () assert.match(VAULT_HOSTS_VS_NOTES_GUIDANCE, /do not silently create a Vault note/i); }); +test("VAULT_HOSTS_VS_NOTES_GUIDANCE routes unknown attached host files through AI extraction", () => { + assert.match(VAULT_HOSTS_VS_NOTES_GUIDANCE, /attached/i); + assert.match(VAULT_HOSTS_VS_NOTES_GUIDANCE, /unknown/i); + assert.match(VAULT_HOSTS_VS_NOTES_GUIDANCE, /extract/i); + assert.match(VAULT_HOSTS_VS_NOTES_GUIDANCE, /vault_hosts_create/i); +}); + test("appendVaultAgentGuidance appends guidance once", () => { const once = appendVaultAgentGuidance("Netcatty terminal manager."); assert.match(once, /Netcatty terminal manager/); diff --git a/infrastructure/ai/cattyAgent/systemPrompt.test.ts b/infrastructure/ai/cattyAgent/systemPrompt.test.ts new file mode 100644 index 000000000..51257fed1 --- /dev/null +++ b/infrastructure/ai/cattyAgent/systemPrompt.test.ts @@ -0,0 +1,18 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { buildSystemPrompt } from './systemPrompt'; + +test('system prompt tells Catty how to import unknown attached host lists safely', () => { + const prompt = buildSystemPrompt({ + scopeType: 'terminal', + hosts: [], + permissionMode: 'confirm', + }); + + assert.match(prompt, /list_attachments/i); + assert.match(prompt, /read_attachment/i); + assert.match(prompt, /unknown/i); + assert.match(prompt, /vault_hosts_create/i); + assert.match(prompt, /tool_output_read/i); + assert.match(prompt, /compressed|truncated/i); +}); diff --git a/infrastructure/ai/cattyAgent/systemPrompt.ts b/infrastructure/ai/cattyAgent/systemPrompt.ts index 0ceba989f..6fc90db5d 100644 --- a/infrastructure/ai/cattyAgent/systemPrompt.ts +++ b/infrastructure/ai/cattyAgent/systemPrompt.ts @@ -55,6 +55,8 @@ ${permissionRules} **Vault → Hosts (SSH connections):** When the user asks to **add/create/import a host** (创建主机、添加主机、保存服务器连接凭据), use \`vault_hosts_create\` — NOT \`vault_notes_create\`. Extract \`hostname\`, \`username\`, \`password\`, \`port\`, \`group\`, \`tags\`, and \`label\` from the user's text; put long admin tables or remarks in the host's \`notes\` field (Host Details metadata). Call with \`dryRun: true\` first to preview, then write. Only use \`vault_hosts_import\` for known export formats (PuTTY, MobaXterm, CSV, SecureCRT, ssh_config). Use \`vault_hosts_list\` to check existing hosts. + **Attached host files:** When the user asks to import attached host/server data, call \`list_attachments\` then \`read_attachment\`. If the attachment is a known export format, pass the exact text to \`vault_hosts_import\`. If the format is unknown or \`vault_hosts_import\` cannot detect it, do not search a terminal or remote filesystem; read the attached text, extract host fields yourself, and call \`vault_hosts_create\` with \`dryRun: true\` first. If a tool result is truncated or compressed and includes a \`tool_output_read\` handle, use \`tool_output_read\` to recover the needed original text before extracting fields. + **Vault → Notes (sidebar markdown docs):** When the user explicitly wants documentation saved to **Vault → Notes** (the notes sidebar / 保险箱笔记), use \`vault_notes_create\` or \`vault_notes_update\` — **not** \`host_notes_set\` (Host Details only) and **not** as a substitute for creating a host. **Never fallback:** If \`vault_hosts_create\` or \`vault_hosts_import\` fails, report the error to the user. Do **not** silently create a Vault note instead of the requested host. diff --git a/infrastructure/ai/harness/cattyTurnDriver.attachments.test.ts b/infrastructure/ai/harness/cattyTurnDriver.attachments.test.ts new file mode 100644 index 000000000..3bdeeb0d2 --- /dev/null +++ b/infrastructure/ai/harness/cattyTurnDriver.attachments.test.ts @@ -0,0 +1,98 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { CattyTurnDriver } from './turnDrivers/cattyTurnDriver'; +import type { TurnDriverContext, TurnInput } from './turnDrivers/types'; + +const mcpServerBridge = await import('../../../electron/bridges/mcpServerBridge.cjs'); + +function createTurnContext(): TurnDriverContext { + return { + turnId: 'turn-1', + chatSessionId: 'chat-1', + sessionId: 'chat-1', + backend: 'catty', + signal: new AbortController().signal, + emit: () => {}, + toolOutputStore: { + store: () => ({ id: 'handle-1', contentLength: 0 }), + read: () => null, + clearSession: () => {}, + }, + toolResultDedup: { + fingerprintFor: () => 'fingerprint', + check: () => null, + remember: () => {}, + buildCachedNotice: () => ({}), + clearTurn: () => {}, + }, + } as TurnDriverContext; +} + +test('Catty turn registers current message file attachments for attachment tools', async (t) => { + mcpServerBridge.cleanup(); + const csvText = 'label,hostname,username\nprod,prod.example.com,root\n'; + const bridge = { + aiSetChatSessionCancelled: async () => ({ ok: true }), + aiMcpUpdateSessions: async () => undefined, + aiMcpUpdateAttachments: async ( + attachments: Array<{ base64Data?: string; mediaType?: string; filename?: string; filePath?: string }>, + chatSessionId?: string, + ) => { + mcpServerBridge.updateAttachmentMetadata(attachments, chatSessionId); + return { ok: true }; + }, + }; + t.after(() => mcpServerBridge.cleanup()); + + const controller = new AbortController(); + const input: TurnInput = { + backend: 'catty', + chatSessionId: 'chat-1', + sendScopeKey: 'chat-1', + userText: '把这些主机都导入到 vault', + signal: controller.signal, + currentSession: undefined, + assistantMsgId: 'assistant-1', + context: { + activeProvider: undefined, + activeModelId: '', + scopeType: 'terminal', + globalPermissionMode: 'confirm', + terminalSessions: [], + autoTitleSession: () => {}, + }, + attachments: [{ + filename: 'hosts_export_2026-06-25.csv', + mediaType: 'text/csv', + base64Data: Buffer.from(csvText).toString('base64'), + filePath: '/tmp/hosts_export_2026-06-25.csv', + }], + maxIterations: 5, + bridge, + ui: { + addMessageToSession: () => {}, + updateLastMessage: () => {}, + updateMessageById: () => {}, + reportStreamError: () => {}, + setStreamingForScope: () => {}, + }, + }; + + await new CattyTurnDriver().run(input, createTurnContext()); + + const listed = mcpServerBridge.handleListAttachments({ chatSessionId: 'chat-1' }); + assert.equal(listed.ok, true); + assert.deepEqual(listed.attachments, [{ + filename: 'hosts_export_2026-06-25.csv', + mediaType: 'text/csv', + filePath: '/tmp/hosts_export_2026-06-25.csv', + sizeBytes: Buffer.byteLength(csvText), + }]); + + const read = mcpServerBridge.handleReadAttachment({ + chatSessionId: 'chat-1', + filename: 'hosts_export_2026-06-25.csv', + }); + assert.equal(read.ok, true); + assert.equal(read.text, csvText); +}); diff --git a/infrastructure/ai/harness/generated/cattyToolSpecs.json b/infrastructure/ai/harness/generated/cattyToolSpecs.json index 4d681e4c5..45a1298ed 100644 --- a/infrastructure/ai/harness/generated/cattyToolSpecs.json +++ b/infrastructure/ai/harness/generated/cattyToolSpecs.json @@ -574,7 +574,7 @@ "toolName": "vault_hosts_import", "rpcMethod": "vault/hosts/import", "localExecution": false, - "description": "Parse known host export file formats (PuTTY, MobaXterm, CSV, SecureCRT, ssh_config) into vault hosts. For arbitrary unstructured text, map to host objects and use vault_hosts_create instead. Only for text in known export formats (PuTTY reg, MobaXterm ini, CSV template, SecureCRT, ssh_config). For arbitrary unstructured host lists from the user, extract fields yourself and call vault_hosts_create.", + "description": "Parse known host export file formats (PuTTY, MobaXterm, CSV, SecureCRT, ssh_config) into vault hosts. For arbitrary unstructured text, map to host objects and use vault_hosts_create instead. Only for text in known export formats (PuTTY reg, MobaXterm ini, CSV template, SecureCRT, ssh_config). If attached host text is unknown or auto-detection fails, use read_attachment content, extract fields yourself, and call vault_hosts_create.", "inputShape": { "format": { "type": "string", diff --git a/infrastructure/ai/harness/generated/globalAgentToolSpecs.json b/infrastructure/ai/harness/generated/globalAgentToolSpecs.json index a296b38bf..3d2d9242a 100644 --- a/infrastructure/ai/harness/generated/globalAgentToolSpecs.json +++ b/infrastructure/ai/harness/generated/globalAgentToolSpecs.json @@ -595,7 +595,7 @@ "toolName": "vault_hosts_import", "rpcMethod": "vault/hosts/import", "localExecution": false, - "description": "Parse known host export file formats (PuTTY, MobaXterm, CSV, SecureCRT, ssh_config) into vault hosts. For arbitrary unstructured text, map to host objects and use vault_hosts_create instead. Only for text in known export formats (PuTTY reg, MobaXterm ini, CSV template, SecureCRT, ssh_config). For arbitrary unstructured host lists from the user, extract fields yourself and call vault_hosts_create.", + "description": "Parse known host export file formats (PuTTY, MobaXterm, CSV, SecureCRT, ssh_config) into vault hosts. For arbitrary unstructured text, map to host objects and use vault_hosts_create instead. Only for text in known export formats (PuTTY reg, MobaXterm ini, CSV template, SecureCRT, ssh_config). If attached host text is unknown or auto-detection fails, use read_attachment content, extract fields yourself, and call vault_hosts_create.", "inputShape": { "format": { "type": "string", diff --git a/infrastructure/ai/harness/turnDrivers/cattyTurnDriver.ts b/infrastructure/ai/harness/turnDrivers/cattyTurnDriver.ts index 549b6f349..31c6404a3 100644 --- a/infrastructure/ai/harness/turnDrivers/cattyTurnDriver.ts +++ b/infrastructure/ai/harness/turnDrivers/cattyTurnDriver.ts @@ -44,7 +44,6 @@ export class CattyTurnDriver implements TurnDriver { async function runCattyTurn(input: CattyTurnInput, ctx: TurnDriverContext): Promise { const { chatSessionId: sessionId, - sendScopeKey, userText: trimmed, signal, currentSession, @@ -61,6 +60,9 @@ async function runCattyTurn(input: CattyTurnInput, ctx: TurnDriverContext): Prom if (netcattyBridge.aiMcpUpdateSessions) { await netcattyBridge.aiMcpUpdateSessions(context.terminalSessions, sessionId); } + if (attachments?.length && netcattyBridge.aiMcpUpdateAttachments) { + await netcattyBridge.aiMcpUpdateAttachments(attachments, sessionId); + } const userSkillsContext = await resolveUserSkillsContext( netcattyBridge, trimmed, From b73c9a90ae88b4b260628fe69bf24803cfe502a7 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 02:17:15 +0800 Subject: [PATCH 070/228] Fix repeated AI note artifact opens --- components/TerminalLayer.tsx | 7 +- components/ai/ChatMessageList.test.tsx | 12 +++- components/ai/ChatMessageList.tsx | 16 ++++- .../toolArtifacts/VaultArtifactCard.test.tsx | 16 +++++ .../ai/toolArtifacts/VaultArtifactCard.tsx | 23 +++++-- .../VaultArtifactNavigationContext.tsx | 68 +++++++++++++------ components/notes/NotesManager.test.tsx | 7 ++ components/notes/NotesManager.tsx | 4 +- .../TerminalLayerSidePanelSection.test.ts | 10 +++ .../TerminalLayerSidePanelSection.tsx | 4 +- .../TerminalLayerTabBridge.test.ts | 6 ++ .../terminalLayer/TerminalLayerTabBridge.tsx | 3 + .../terminalLayerStableSnapshot.ts | 4 +- .../terminalLayerViewMemo.test.ts | 15 ++++ .../terminalLayer/terminalLayerViewMemo.ts | 3 + 15 files changed, 165 insertions(+), 33 deletions(-) diff --git a/components/TerminalLayer.tsx b/components/TerminalLayer.tsx index a00bdfebb..2aa03c63b 100644 --- a/components/TerminalLayer.tsx +++ b/components/TerminalLayer.tsx @@ -510,7 +510,8 @@ const TerminalLayerInner: React.FC = ({ >(new Map()); const [pendingTerminalSelectionForAI, setPendingTerminalSelectionForAI] = useState(null); - const [notesOpenNoteByTab, setNotesOpenNoteByTab] = useState>(new Map()); + const [notesOpenNoteByTab, setNotesOpenNoteByTab] = useState>(new Map()); + const notesOpenRequestIdRef = useRef(0); const sftpHostForTabRef = useRef(sftpHostForTab); sftpHostForTabRef.current = sftpHostForTab; @@ -1084,9 +1085,11 @@ const TerminalLayerInner: React.FC = ({ }, [handleSwitchSidePanelTab, resolveSftpHostForTab]); const openNotesPanelForSourceNote = useCallback((tabId: string, noteId: string) => { + notesOpenRequestIdRef.current += 1; + const requestId = notesOpenRequestIdRef.current; setNotesOpenNoteByTab((prev) => { const next = new Map(prev); - next.set(tabId, noteId); + next.set(tabId, { noteId, requestId }); return next; }); setNotesMountedTabIds((prev) => addMountedSidePanelTabId(prev, tabId)); diff --git a/components/ai/ChatMessageList.test.tsx b/components/ai/ChatMessageList.test.tsx index 57cfc4542..97f848471 100644 --- a/components/ai/ChatMessageList.test.tsx +++ b/components/ai/ChatMessageList.test.tsx @@ -5,7 +5,7 @@ import { renderToStaticMarkup } from "react-dom/server"; import { I18nProvider } from "../../application/i18n/I18nProvider.tsx"; import type { ChatMessage } from "../../infrastructure/ai/types.ts"; -import ChatMessageList from "./ChatMessageList.tsx"; +import ChatMessageList, { shouldProvideVaultArtifactNavigation } from "./ChatMessageList.tsx"; const makeMessage = (index: number): ChatMessage => ({ id: `msg-${index}`, @@ -30,3 +30,13 @@ test("ChatMessageList only renders the recent message batch by default", () => { assert.match(markup, /message-10/); assert.match(markup, /message-59/); }); + +test("ChatMessageList wires vault artifact navigation when only note open is available", () => { + assert.equal(shouldProvideVaultArtifactNavigation({ + onOpenVaultNote: () => {}, + }), true); +}); + +test("ChatMessageList leaves vault artifact navigation disabled without open actions", () => { + assert.equal(shouldProvideVaultArtifactNavigation({}), false); +}); diff --git a/components/ai/ChatMessageList.tsx b/components/ai/ChatMessageList.tsx index 25cf5b0c8..35b66b122 100644 --- a/components/ai/ChatMessageList.tsx +++ b/components/ai/ChatMessageList.tsx @@ -57,6 +57,20 @@ interface ChatMessageListProps { onOpenVaultSection?: (section: 'notes' | 'hosts') => void; } +interface VaultArtifactNavigationCallbackOptions { + onOpenVaultNote?: (noteId: string) => void; + onOpenVaultHost?: (hostId: string) => void; + onOpenVaultSection?: (section: 'notes' | 'hosts') => void; +} + +export function shouldProvideVaultArtifactNavigation({ + onOpenVaultNote, + onOpenVaultHost, + onOpenVaultSection, +}: VaultArtifactNavigationCallbackOptions): boolean { + return Boolean(onOpenVaultNote || onOpenVaultHost || onOpenVaultSection); +} + const MESSAGE_RENDER_BATCH = 50; const MESSAGE_RENDER_STEP = 50; @@ -618,7 +632,7 @@ const ChatMessageList: React.FC = ({ ); - if (onOpenVaultNote && onOpenVaultHost && onOpenVaultSection) { + if (shouldProvideVaultArtifactNavigation({ onOpenVaultNote, onOpenVaultHost, onOpenVaultSection })) { return ( { assert.match(html, /ops\/prod/); }); +test('VaultArtifactCard does not render a clickable note without navigation wiring', () => { + const html = renderToStaticMarkup( + + + , + ); + + assert.doesNotMatch(html, /
)}
- {presentation.clickable && ( + {canNavigate && ( )} ); - if (!presentation.clickable) { + if (!canNavigate) { return ( -
+
{content}
); diff --git a/components/ai/toolArtifacts/VaultArtifactNavigationContext.tsx b/components/ai/toolArtifacts/VaultArtifactNavigationContext.tsx index 5b3c98a6d..020538386 100644 --- a/components/ai/toolArtifacts/VaultArtifactNavigationContext.tsx +++ b/components/ai/toolArtifacts/VaultArtifactNavigationContext.tsx @@ -5,27 +5,27 @@ import { toast } from '../../ui/toast'; import type { VaultToolArtifact } from './vaultToolArtifact'; export interface VaultArtifactNavigationActions { - openVaultNote: (noteId: string) => void; - openVaultHost: (hostId: string) => void; - openVaultSection: (section: 'notes' | 'hosts') => void; + openVaultNote?: (noteId: string) => void; + openVaultHost?: (hostId: string) => void; + openVaultSection?: (section: 'notes' | 'hosts') => void; } interface CreateVaultArtifactNavigationActionsOptions { notes: VaultNote[]; hosts: Host[]; t: (key: string) => string; - onOpenVaultNote: (noteId: string) => void; - onOpenVaultHost: (hostId: string) => void; - onOpenVaultSection: (section: 'notes' | 'hosts') => void; + onOpenVaultNote?: (noteId: string) => void; + onOpenVaultHost?: (hostId: string) => void; + onOpenVaultSection?: (section: 'notes' | 'hosts') => void; onUnavailable: (message: string, title: string) => void; } interface VaultArtifactNavigationProviderProps { notes: VaultNote[]; hosts: Host[]; - onOpenVaultNote: (noteId: string) => void; - onOpenVaultHost: (hostId: string) => void; - onOpenVaultSection: (section: 'notes' | 'hosts') => void; + onOpenVaultNote?: (noteId: string) => void; + onOpenVaultHost?: (hostId: string) => void; + onOpenVaultSection?: (section: 'notes' | 'hosts') => void; children: React.ReactNode; } @@ -40,25 +40,35 @@ export function createVaultArtifactNavigationActions({ onOpenVaultSection, onUnavailable, }: CreateVaultArtifactNavigationActionsOptions): VaultArtifactNavigationActions { - return { - openVaultNote: (noteId: string) => { + const actions: VaultArtifactNavigationActions = {}; + + if (onOpenVaultNote) { + actions.openVaultNote = (noteId: string) => { const exists = notes.some((note) => note.id === noteId); if (!exists) { onUnavailable(t('ai.chat.artifact.noteMissing'), t('ai.chat.artifact.unavailableTitle')); return; } onOpenVaultNote(noteId); - }, - openVaultHost: (hostId: string) => { + }; + } + + if (onOpenVaultHost) { + actions.openVaultHost = (hostId: string) => { const exists = hosts.some((host) => host.id === hostId); if (!exists) { onUnavailable(t('ai.chat.artifact.hostMissing'), t('ai.chat.artifact.unavailableTitle')); return; } onOpenVaultHost(hostId); - }, - openVaultSection: onOpenVaultSection, - }; + }; + } + + if (onOpenVaultSection) { + actions.openVaultSection = onOpenVaultSection; + } + + return actions; } export function VaultArtifactNavigationProvider({ @@ -102,18 +112,36 @@ export function navigateVaultArtifact( ): void { switch (artifact.kind) { case 'vault.note': - navigation.openVaultNote(artifact.noteId); + navigation.openVaultNote?.(artifact.noteId); break; case 'vault.host': - navigation.openVaultHost(artifact.hostId); + navigation.openVaultHost?.(artifact.hostId); break; case 'vault.hosts.batch': - navigation.openVaultSection('hosts'); + navigation.openVaultSection?.('hosts'); break; case 'vault.summary': - navigation.openVaultSection(artifact.section); + navigation.openVaultSection?.(artifact.section); break; default: break; } } + +export function canNavigateVaultArtifact( + artifact: VaultToolArtifact, + navigation: VaultArtifactNavigationActions | null, +): boolean { + if (!navigation) return false; + switch (artifact.kind) { + case 'vault.note': + return Boolean(navigation.openVaultNote); + case 'vault.host': + return Boolean(navigation.openVaultHost); + case 'vault.hosts.batch': + case 'vault.summary': + return Boolean(navigation.openVaultSection); + default: + return false; + } +} diff --git a/components/notes/NotesManager.test.tsx b/components/notes/NotesManager.test.tsx index 97b123be3..47a2bb1be 100644 --- a/components/notes/NotesManager.test.tsx +++ b/components/notes/NotesManager.test.tsx @@ -274,3 +274,10 @@ test("NotesManager sidebar mode opens the requested note without selecting its f assert.match(markup, /data-vault-tree-row="group"[^>]*data-selected="false"/); assert.match(markup, /data-vault-tree-row="item"[^>]*data-selected="true"[^>]*data-note-id="note-2"/); }); + +test("NotesManager can re-open the same sidebar note when the request id changes", () => { + const source = readFileSync(new URL("./NotesManager.tsx", import.meta.url), "utf8"); + + assert.match(source, /openNoteRequestId\?: number \| null/); + assert.match(source, /\[isSidebarMode, onOpenNoteIdHandled, openNoteId, openNoteRequestId, sortedNotes\]/); +}); diff --git a/components/notes/NotesManager.tsx b/components/notes/NotesManager.tsx index 4fe216cd9..4315d453d 100644 --- a/components/notes/NotesManager.tsx +++ b/components/notes/NotesManager.tsx @@ -115,6 +115,7 @@ export interface NotesManagerProps { onOpenHost?: (host: Host, source?: { noteId: string }) => void; displayMode?: "full" | "sidebar"; openNoteId?: string | null; + openNoteRequestId?: number | null; /** Called after a one-shot openNoteId focus request has been applied. */ onOpenNoteIdHandled?: () => void; } @@ -328,6 +329,7 @@ export const NotesManager: React.FC = ({ onOpenHost, displayMode = "full", openNoteId = null, + openNoteRequestId = null, onOpenNoteIdHandled, }) => { const { t } = useI18n(); @@ -427,7 +429,7 @@ export const NotesManager: React.FC = ({ setExpandedGroups((current) => new Set([...current, ...ancestorNoteGroupPaths(note.group || "")])); } onOpenNoteIdHandled?.(); - }, [isSidebarMode, onOpenNoteIdHandled, openNoteId, sortedNotes]); + }, [isSidebarMode, onOpenNoteIdHandled, openNoteId, openNoteRequestId, sortedNotes]); useEffect(() => { if (expandedPanel !== "search") return; diff --git a/components/terminalLayer/TerminalLayerSidePanelSection.test.ts b/components/terminalLayer/TerminalLayerSidePanelSection.test.ts index ffb6f1384..a8d629681 100644 --- a/components/terminalLayer/TerminalLayerSidePanelSection.test.ts +++ b/components/terminalLayer/TerminalLayerSidePanelSection.test.ts @@ -1,4 +1,5 @@ import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; import test from 'node:test'; import { @@ -81,3 +82,12 @@ test('side panel tab order can move the dragged tab after the target tab', () => ['sftp', 'history', 'theme', 'system', 'notes', 'ai', 'scripts'], ); }); + +test('notes side panel forwards repeated open-note requests', () => { + const layerSource = readFileSync(new URL('../TerminalLayer.tsx', import.meta.url), 'utf8'); + const sectionSource = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8'); + + assert.match(layerSource, /notesOpenRequestIdRef\.current \+= 1/); + assert.match(layerSource, /next\.set\(tabId, \{ noteId, requestId \}\)/); + assert.match(sectionSource, /openNoteRequestId=\{openNoteRequest\?\.requestId \?\? null\}/); +}); diff --git a/components/terminalLayer/TerminalLayerSidePanelSection.tsx b/components/terminalLayer/TerminalLayerSidePanelSection.tsx index 5974b101e..9b63bfcc1 100644 --- a/components/terminalLayer/TerminalLayerSidePanelSection.tsx +++ b/components/terminalLayer/TerminalLayerSidePanelSection.tsx @@ -649,6 +649,7 @@ function TerminalLayerSidePanelTabBody({ ctx }: { ctx: SidePanelContext }) { {notesMountedTabIds.map((tabId: string) => { const isVisibleNotesPanel = activeTabId === tabId && activeSidePanelTab === 'notes'; + const openNoteRequest = notesOpenNoteByTab.get(tabId) ?? null; return (
); diff --git a/components/terminalLayer/TerminalLayerTabBridge.test.ts b/components/terminalLayer/TerminalLayerTabBridge.test.ts index 435d50643..e52d9c1dc 100644 --- a/components/terminalLayer/TerminalLayerTabBridge.test.ts +++ b/components/terminalLayer/TerminalLayerTabBridge.test.ts @@ -25,3 +25,9 @@ test('terminal layer bridge refreshes when terminal settings change', () => { assert.match(source, /terminalSettings: s\.terminalSettings/); assert.match(source, /\[\s*[\s\S]*s\.terminalSettings[\s\S]*\]\);/); }); + +test('terminal layer bridge passes vault open callbacks into the side panel context', () => { + assert.match(source, /onOpenVaultNoteFromChat: s\.onOpenVaultNoteFromChat/); + assert.match(source, /onOpenVaultHostFromChat: s\.onOpenVaultHostFromChat/); + assert.match(source, /onOpenVaultSectionFromChat: s\.onOpenVaultSectionFromChat/); +}); diff --git a/components/terminalLayer/TerminalLayerTabBridge.tsx b/components/terminalLayer/TerminalLayerTabBridge.tsx index 7d6d23918..50b751d74 100644 --- a/components/terminalLayer/TerminalLayerTabBridge.tsx +++ b/components/terminalLayer/TerminalLayerTabBridge.tsx @@ -438,6 +438,9 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef }) onStartSessionRename: s.onStartSessionRename, onSubmitSessionRename: s.onSubmitSessionRename, onRemoveSessionFromWorkspace: s.onRemoveSessionFromWorkspace, + onOpenVaultNoteFromChat: s.onOpenVaultNoteFromChat, + onOpenVaultHostFromChat: s.onOpenVaultHostFromChat, + onOpenVaultSectionFromChat: s.onOpenVaultSectionFromChat, onStartSessionDrag: s.onStartSessionDrag, onEndSessionDrag: s.onEndSessionDrag, onSplitSession: s.onSplitSession, diff --git a/components/terminalLayer/terminalLayerStableSnapshot.ts b/components/terminalLayer/terminalLayerStableSnapshot.ts index 29a086e58..2a0436c1a 100644 --- a/components/terminalLayer/terminalLayerStableSnapshot.ts +++ b/components/terminalLayer/terminalLayerStableSnapshot.ts @@ -74,8 +74,8 @@ export type TerminalLayerStableSnapshot = { lastSidePanelTabRef: React.MutableRefObject>; notesMountedTabIds: string[]; setNotesMountedTabIds: React.Dispatch>; - notesOpenNoteByTab: Map; - setNotesOpenNoteByTab: React.Dispatch>>; + notesOpenNoteByTab: Map; + setNotesOpenNoteByTab: React.Dispatch>>; isComposeBarOpen: boolean; setIsComposeBarOpen: React.Dispatch>; splitHorizontalHandlersRef: React.MutableRefObject void>>; diff --git a/components/terminalLayer/terminalLayerViewMemo.test.ts b/components/terminalLayer/terminalLayerViewMemo.test.ts index 50961be76..807de8bf2 100644 --- a/components/terminalLayer/terminalLayerViewMemo.test.ts +++ b/components/terminalLayer/terminalLayerViewMemo.test.ts @@ -144,6 +144,21 @@ test("terminal layer side panel re-renders when follow terminal cwd setting chan ); }); +test("terminal layer side panel re-renders when vault note open callback changes", () => { + const baseCtx = { + mountedAiTabIds: ["workspace-1"], + onOpenVaultNoteFromChat: () => {}, + }; + + assert.equal( + terminalLayerSidePanelCtxEqual( + baseCtx, + { ...baseCtx, onOpenVaultNoteFromChat: () => {} }, + ), + false, + ); +}); + test("terminal layer focus sidebar re-renders when dynamic tab title mode changes", () => { const baseCtx = { isFocusMode: true, diff --git a/components/terminalLayer/terminalLayerViewMemo.ts b/components/terminalLayer/terminalLayerViewMemo.ts index 898742725..bd90025be 100644 --- a/components/terminalLayer/terminalLayerViewMemo.ts +++ b/components/terminalLayer/terminalLayerViewMemo.ts @@ -215,6 +215,9 @@ const SIDE_PANEL_CTX_KEYS = [ 'noteGroups', 'updateNotes', 'updateNoteGroups', + 'onOpenVaultNoteFromChat', + 'onOpenVaultHostFromChat', + 'onOpenVaultSectionFromChat', 't', ] as const; From 79944017d202e81944ce0edf8313b0dac327ee94 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 02:23:53 +0800 Subject: [PATCH 071/228] Handle wrapped external tool artifact results --- components/ai/ChatMessageList.test.tsx | 57 +++++++++++++++++++ .../terminalToolArtifact.test.ts | 34 +++++++++++ .../ai/toolArtifacts/terminalToolArtifact.ts | 20 +------ .../toolArtifactResultPayload.test.ts | 35 ++++++++++++ .../toolArtifactResultPayload.ts | 46 +++++++++++++++ .../toolArtifacts/vaultToolArtifact.test.ts | 21 +++++++ .../ai/toolArtifacts/vaultToolArtifact.ts | 20 +------ .../turnDrivers/externalSdkTurnDriver.ts | 12 ++-- 8 files changed, 203 insertions(+), 42 deletions(-) create mode 100644 components/ai/toolArtifacts/toolArtifactResultPayload.test.ts create mode 100644 components/ai/toolArtifacts/toolArtifactResultPayload.ts diff --git a/components/ai/ChatMessageList.test.tsx b/components/ai/ChatMessageList.test.tsx index c95aa92dd..4e1a9b16b 100644 --- a/components/ai/ChatMessageList.test.tsx +++ b/components/ai/ChatMessageList.test.tsx @@ -124,3 +124,60 @@ test("ChatMessageList renders Netcatty CLI vault results as artifact cards", () assert.match(markup, /prod\.example\.com:22/); assert.doesNotMatch(markup, /cli-call-1/); }); + +test("ChatMessageList renders Claude MCP list envelopes as summary cards", () => { + const messages: ChatMessage[] = [ + { + id: "assistant-1", + role: "assistant", + content: "", + timestamp: 1, + toolCalls: [ + { + id: "notes-call-1", + name: "mcp__netcatty-remote-hosts__vault_notes_list", + arguments: {}, + }, + ], + executionStatus: "completed", + }, + { + id: "tool-1", + role: "tool", + content: "", + timestamp: 2, + toolResults: [ + { + toolCallId: "notes-call-1", + content: JSON.stringify([ + { + type: "text", + text: JSON.stringify({ + ok: true, + notes: Array.from({ length: 8 }, (_value, index) => ({ + id: `note-${index}`, + title: `Note ${index}`, + })), + }), + }, + ]), + }, + ], + }, + ]; + + const markup = renderToStaticMarkup( + React.createElement( + I18nProvider, + { locale: "en" }, + React.createElement( + TooltipProvider, + null, + React.createElement(ChatMessageList, { messages }), + ), + ), + ); + + assert.match(markup, /8 notes in Vault/); + assert.doesNotMatch(markup, /notes-call-1/); +}); diff --git a/components/ai/toolArtifacts/terminalToolArtifact.test.ts b/components/ai/toolArtifacts/terminalToolArtifact.test.ts index b3183b765..4c7d3c399 100644 --- a/components/ai/toolArtifacts/terminalToolArtifact.test.ts +++ b/components/ai/toolArtifacts/terminalToolArtifact.test.ts @@ -46,3 +46,37 @@ test('parseTerminalToolArtifact maps errors', () => { message: 'Terminal session not found.', }); }); + +test('parseTerminalToolArtifact unwraps Claude MCP text result envelopes', () => { + const artifact = parseTerminalToolArtifact('mcp__netcatty-remote-hosts__terminal_read_context', JSON.stringify([ + { + type: 'text', + text: JSON.stringify({ + ok: true, + sessionId: 'session-1', + label: 'prod', + range: 'tail', + content: 'alpha\nbeta', + totalLines: 20, + startLine: 19, + endLine: 20, + returnedLines: 2, + }), + }, + ])); + + assert.deepEqual(artifact, { + kind: 'terminal.context', + sessionId: 'session-1', + label: 'prod', + range: 'tail', + totalLines: 20, + startLine: 19, + endLine: 20, + returnedLines: 2, + hasMoreBefore: false, + hasMoreAfter: false, + source: undefined, + preview: 'alpha\nbeta', + }); +}); diff --git a/components/ai/toolArtifacts/terminalToolArtifact.ts b/components/ai/toolArtifacts/terminalToolArtifact.ts index 627164e7e..ca8f90c67 100644 --- a/components/ai/toolArtifacts/terminalToolArtifact.ts +++ b/components/ai/toolArtifacts/terminalToolArtifact.ts @@ -1,4 +1,5 @@ import { normalizeArtifactToolName } from './toolArtifactNames'; +import { parseResultPayload } from './toolArtifactResultPayload'; export type TerminalToolArtifact = | { @@ -24,25 +25,6 @@ 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; } diff --git a/components/ai/toolArtifacts/toolArtifactResultPayload.test.ts b/components/ai/toolArtifacts/toolArtifactResultPayload.test.ts new file mode 100644 index 000000000..baf933d97 --- /dev/null +++ b/components/ai/toolArtifacts/toolArtifactResultPayload.test.ts @@ -0,0 +1,35 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { parseResultPayload } from './toolArtifactResultPayload.ts'; + +test('parseResultPayload unwraps MCP text content arrays', () => { + assert.deepEqual(parseResultPayload(JSON.stringify([ + { + type: 'text', + text: JSON.stringify({ ok: true, value: 42 }), + }, + ])), { + ok: true, + value: 42, + }); +}); + +test('parseResultPayload unwraps MCP content objects', () => { + assert.deepEqual(parseResultPayload({ + content: [ + { + type: 'text', + text: JSON.stringify({ ok: true, label: 'prod' }), + }, + ], + }), { + ok: true, + label: 'prod', + }); +}); + +test('parseResultPayload preserves plain result objects', () => { + const payload = { ok: true, name: 'plain' }; + assert.equal(parseResultPayload(payload), payload); +}); diff --git a/components/ai/toolArtifacts/toolArtifactResultPayload.ts b/components/ai/toolArtifacts/toolArtifactResultPayload.ts new file mode 100644 index 000000000..25e2805c0 --- /dev/null +++ b/components/ai/toolArtifacts/toolArtifactResultPayload.ts @@ -0,0 +1,46 @@ +function asRecord(value: unknown): Record | null { + return value && typeof value === 'object' && !Array.isArray(value) + ? value as Record + : null; +} + +function parseJsonRecord(value: string): Record | null { + try { + const parsed = JSON.parse(value) as unknown; + return parseResultPayload(parsed); + } catch { + return null; + } +} + +function unwrapMcpTextEnvelope(value: unknown): unknown { + if (Array.isArray(value)) { + const textPart = value.find((entry) => { + const record = asRecord(entry); + return record?.type === 'text' && typeof record.text === 'string'; + }); + const record = asRecord(textPart); + return typeof record?.text === 'string' ? record.text : value; + } + + const record = asRecord(value); + if (record?.type === 'text' && typeof record.text === 'string') { + return record.text; + } + if (Array.isArray(record?.content)) { + return unwrapMcpTextEnvelope(record.content); + } + + return value; +} + +export function parseResultPayload(result: unknown): Record | null { + if (result == null) return null; + const unwrapped = unwrapMcpTextEnvelope(result); + + if (typeof unwrapped === 'string') { + return parseJsonRecord(unwrapped); + } + + return asRecord(unwrapped); +} diff --git a/components/ai/toolArtifacts/vaultToolArtifact.test.ts b/components/ai/toolArtifacts/vaultToolArtifact.test.ts index c6b9557f2..d3289c716 100644 --- a/components/ai/toolArtifacts/vaultToolArtifact.test.ts +++ b/components/ai/toolArtifacts/vaultToolArtifact.test.ts @@ -72,3 +72,24 @@ test('parseVaultToolArtifact maps errors', () => { message: 'Vault note "missing" was not found.', }); }); + +test('parseVaultToolArtifact unwraps Claude MCP text result envelopes', () => { + const artifact = parseVaultToolArtifact('mcp__netcatty-remote-hosts__vault_notes_list', JSON.stringify([ + { + type: 'text', + text: JSON.stringify({ + ok: true, + notes: [ + { id: 'note-1', title: 'Docker Compose' }, + { id: 'note-2', title: 'Dokploy' }, + ], + }), + }, + ])); + + assert.deepEqual(artifact, { + kind: 'vault.summary', + section: 'notes', + count: 2, + }); +}); diff --git a/components/ai/toolArtifacts/vaultToolArtifact.ts b/components/ai/toolArtifacts/vaultToolArtifact.ts index 7e57dfc92..c8eca66a0 100644 --- a/components/ai/toolArtifacts/vaultToolArtifact.ts +++ b/components/ai/toolArtifacts/vaultToolArtifact.ts @@ -1,4 +1,5 @@ import { normalizeArtifactToolName } from './toolArtifactNames'; +import { parseResultPayload } from './toolArtifactResultPayload'; export type VaultToolArtifact = | { @@ -43,25 +44,6 @@ const VAULT_ARTIFACT_TOOL_NAMES = new Set([ 'host_get', ]); -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; } diff --git a/infrastructure/ai/harness/turnDrivers/externalSdkTurnDriver.ts b/infrastructure/ai/harness/turnDrivers/externalSdkTurnDriver.ts index 88732a913..ec767fe44 100644 --- a/infrastructure/ai/harness/turnDrivers/externalSdkTurnDriver.ts +++ b/infrastructure/ai/harness/turnDrivers/externalSdkTurnDriver.ts @@ -70,6 +70,7 @@ async function runExternalTurn(input: ExternalTurnInput, ctx: TurnDriverContext) } }; + const toolNamesByCallId = new Map(); const callbacks: SdkAgentCallbacks = { onTextDelta: (text: string) => { maybeCreateAssistantMsg(); @@ -96,18 +97,21 @@ async function runExternalTurn(input: ExternalTurnInput, ctx: TurnDriverContext) }, onToolCall: (toolName: string, args: Record, toolCallId?: string) => { maybeCreateAssistantMsg(); + const id = toolCallId || `tc_${Date.now()}`; + toolNamesByCallId.set(id, toolName); ui.updateLastMessage(sessionId, msg => ({ ...msg, - toolCalls: [...(msg.toolCalls || []), { id: toolCallId || `tc_${Date.now()}`, name: toolName, arguments: args }], + toolCalls: [...(msg.toolCalls || []), { id, name: toolName, arguments: args }], executionStatus: 'running', statusText: undefined, })); }, onToolResult: (toolCallId: string, result: string, toolName?: string) => { + const effectiveToolName = toolName ?? toolNamesByCallId.get(toolCallId); ui.updateLastMessage(sessionId, msg => { if (msg.role !== 'assistant' || msg.executionStatus !== 'running') return msg; - const updatedToolCalls = toolName && !toolName.includes('sdk_agent_dynamic_tool') && msg.toolCalls - ? msg.toolCalls.map(tc => tc.id === toolCallId && !tc.name ? { ...tc, name: toolName } : tc) + const updatedToolCalls = effectiveToolName && !effectiveToolName.includes('sdk_agent_dynamic_tool') && msg.toolCalls + ? msg.toolCalls.map(tc => tc.id === toolCallId && !tc.name ? { ...tc, name: effectiveToolName } : tc) : msg.toolCalls; return { ...msg, toolCalls: updatedToolCalls, executionStatus: 'completed', statusText: undefined }; }); @@ -117,7 +121,7 @@ async function runExternalTurn(input: ExternalTurnInput, ctx: TurnDriverContext) content: '', toolResults: [{ toolCallId, - toolName, + toolName: effectiveToolName, content: result, isError: isToolResultError(result), }], From 6b65d055fda6406ac71943a8113e8d3672da1167 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 02:28:23 +0800 Subject: [PATCH 072/228] Support OpenCode and Copilot artifact envelopes --- components/ai/ChatMessageList.test.tsx | 90 +++++++++++++++++++ .../toolArtifacts/toolArtifactNames.test.ts | 26 ++++++ .../ai/toolArtifacts/toolArtifactNames.ts | 17 ++++ .../toolArtifactResultPayload.test.ts | 30 +++++++ .../toolArtifactResultPayload.ts | 14 +++ 5 files changed, 177 insertions(+) diff --git a/components/ai/ChatMessageList.test.tsx b/components/ai/ChatMessageList.test.tsx index 4e1a9b16b..aaa078848 100644 --- a/components/ai/ChatMessageList.test.tsx +++ b/components/ai/ChatMessageList.test.tsx @@ -181,3 +181,93 @@ test("ChatMessageList renders Claude MCP list envelopes as summary cards", () => assert.match(markup, /8 notes in Vault/); assert.doesNotMatch(markup, /notes-call-1/); }); + +test("ChatMessageList renders OpenCode MCP-prefixed vault results as artifact cards", () => { + const messages: ChatMessage[] = [ + { + id: "tool-1", + role: "tool", + content: "", + timestamp: 1, + toolResults: [ + { + toolCallId: "opencode-call-1", + toolName: "netcatty-remote-hosts_vault_notes_get", + content: JSON.stringify({ + ok: true, + note: { + id: "note-1", + title: "2026-06-25 Host Import Report", + group: "infra/imports", + }, + }), + }, + ], + }, + ]; + + const markup = renderToStaticMarkup( + React.createElement( + I18nProvider, + { locale: "en" }, + React.createElement( + TooltipProvider, + null, + React.createElement(ChatMessageList, { messages }), + ), + ), + ); + + assert.match(markup, /2026-06-25 Host Import Report/); + assert.match(markup, /infra\/imports/); + assert.doesNotMatch(markup, /opencode-call-1/); +}); + +test("ChatMessageList renders Copilot MCP-prefixed wrapped vault results as artifact cards", () => { + const payload = { + ok: true, + notes: Array.from({ length: 8 }, (_value, index) => ({ + id: `note-${index}`, + title: `Note ${index}`, + })), + }; + const messages: ChatMessage[] = [ + { + id: "tool-1", + role: "tool", + content: "", + timestamp: 1, + toolResults: [ + { + toolCallId: "copilot-call-1", + toolName: "netcatty-remote-hosts-vault_notes_list", + content: JSON.stringify({ + content: JSON.stringify(payload), + detailedContent: JSON.stringify(payload), + contents: [ + { + type: "text", + text: JSON.stringify(payload), + }, + ], + }), + }, + ], + }, + ]; + + const markup = renderToStaticMarkup( + React.createElement( + I18nProvider, + { locale: "en" }, + React.createElement( + TooltipProvider, + null, + React.createElement(ChatMessageList, { messages }), + ), + ), + ); + + assert.match(markup, /8 notes in Vault/); + assert.doesNotMatch(markup, /copilot-call-1/); +}); diff --git a/components/ai/toolArtifacts/toolArtifactNames.test.ts b/components/ai/toolArtifacts/toolArtifactNames.test.ts index 927503075..b5737a13a 100644 --- a/components/ai/toolArtifacts/toolArtifactNames.test.ts +++ b/components/ai/toolArtifacts/toolArtifactNames.test.ts @@ -17,6 +17,32 @@ test('normalizeArtifactToolName unwraps MCP server prefixes', () => { ); }); +test('normalizeArtifactToolName unwraps OpenCode server prefixes', () => { + assert.equal( + normalizeArtifactToolName('netcatty-remote-hosts_vault_notes_get'), + 'vault_notes_get', + ); + assert.equal( + normalizeArtifactToolName('netcatty-remote-hosts_vault_hosts_list'), + 'vault_hosts_list', + ); + assert.equal( + normalizeArtifactToolName('netcatty-remote-hosts_terminal_read_context'), + 'terminal_read_context', + ); +}); + +test('normalizeArtifactToolName unwraps Copilot server prefixes', () => { + assert.equal( + normalizeArtifactToolName('netcatty-remote-hosts-vault_notes_list'), + 'vault_notes_list', + ); + assert.equal( + normalizeArtifactToolName('netcatty-remote-hosts-terminal_read_context'), + 'terminal_read_context', + ); +}); + test('inferArtifactToolNameFromCliArgs maps Netcatty CLI artifact commands', () => { assert.equal( inferArtifactToolNameFromCliArgs({ diff --git a/components/ai/toolArtifacts/toolArtifactNames.ts b/components/ai/toolArtifacts/toolArtifactNames.ts index 88c38235a..f06ab0b3a 100644 --- a/components/ai/toolArtifacts/toolArtifactNames.ts +++ b/components/ai/toolArtifacts/toolArtifactNames.ts @@ -1,5 +1,17 @@ const MCP_TOOL_NAME_PREFIX = 'mcp__'; +const KNOWN_ARTIFACT_TOOL_NAMES = [ + 'terminal_read_context', + 'vault_notes_create', + 'vault_notes_update', + 'vault_notes_get', + 'vault_notes_list', + 'vault_hosts_create', + 'vault_hosts_import', + 'vault_hosts_list', + 'host_get', +] as const; + const CLI_ARTIFACT_TOOL_NAMES = new Map([ ['vault host get', 'host_get'], ]); @@ -46,6 +58,11 @@ export function normalizeArtifactToolName(toolName: string | undefined): string return segments[segments.length - 1] || trimmed; } + const prefixedArtifactToolName = KNOWN_ARTIFACT_TOOL_NAMES.find((candidate) => ( + trimmed.endsWith(`_${candidate}`) || trimmed.endsWith(`-${candidate}`) + )); + if (prefixedArtifactToolName) return prefixedArtifactToolName; + return trimmed; } diff --git a/components/ai/toolArtifacts/toolArtifactResultPayload.test.ts b/components/ai/toolArtifacts/toolArtifactResultPayload.test.ts index baf933d97..2ef6549e6 100644 --- a/components/ai/toolArtifacts/toolArtifactResultPayload.test.ts +++ b/components/ai/toolArtifacts/toolArtifactResultPayload.test.ts @@ -29,6 +29,36 @@ test('parseResultPayload unwraps MCP content objects', () => { }); }); +test('parseResultPayload unwraps Copilot content string objects', () => { + assert.deepEqual(parseResultPayload({ + content: JSON.stringify({ ok: true, notes: [{ id: 'note-1' }] }), + detailedContent: JSON.stringify({ ok: true, notes: [{ id: 'note-1' }] }), + contents: [ + { + type: 'text', + text: JSON.stringify({ ok: true, notes: [{ id: 'note-1' }] }), + }, + ], + }), { + ok: true, + notes: [{ id: 'note-1' }], + }); +}); + +test('parseResultPayload unwraps Copilot contents arrays', () => { + assert.deepEqual(parseResultPayload({ + contents: [ + { + type: 'text', + text: JSON.stringify({ ok: true, hosts: [{ id: 'host-1' }] }), + }, + ], + }), { + ok: true, + hosts: [{ id: 'host-1' }], + }); +}); + test('parseResultPayload preserves plain result objects', () => { const payload = { ok: true, name: 'plain' }; assert.equal(parseResultPayload(payload), payload); diff --git a/components/ai/toolArtifacts/toolArtifactResultPayload.ts b/components/ai/toolArtifacts/toolArtifactResultPayload.ts index 25e2805c0..c35de66a0 100644 --- a/components/ai/toolArtifacts/toolArtifactResultPayload.ts +++ b/components/ai/toolArtifacts/toolArtifactResultPayload.ts @@ -13,6 +13,11 @@ function parseJsonRecord(value: string): Record | null { } } +function looksLikeJson(value: string): boolean { + const trimmed = value.trim(); + return trimmed.startsWith('{') || trimmed.startsWith('['); +} + function unwrapMcpTextEnvelope(value: unknown): unknown { if (Array.isArray(value)) { const textPart = value.find((entry) => { @@ -30,6 +35,15 @@ function unwrapMcpTextEnvelope(value: unknown): unknown { if (Array.isArray(record?.content)) { return unwrapMcpTextEnvelope(record.content); } + if (typeof record?.content === 'string' && looksLikeJson(record.content)) { + return record.content; + } + if (typeof record?.detailedContent === 'string' && looksLikeJson(record.detailedContent)) { + return record.detailedContent; + } + if (Array.isArray(record?.contents)) { + return unwrapMcpTextEnvelope(record.contents); + } return value; } From 5a993f200c0efa6c4cac7738948698039d864fb2 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 02:30:39 +0800 Subject: [PATCH 073/228] Prefer CLI artifact inference over generic tool names --- components/ai/ChatMessageList.test.tsx | 1 + components/ai/ChatMessageList.tsx | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/components/ai/ChatMessageList.test.tsx b/components/ai/ChatMessageList.test.tsx index aaa078848..a838df2e0 100644 --- a/components/ai/ChatMessageList.test.tsx +++ b/components/ai/ChatMessageList.test.tsx @@ -99,6 +99,7 @@ test("ChatMessageList renders Netcatty CLI vault results as artifact cards", () toolResults: [ { toolCallId: "cli-call-1", + toolName: "shell", content: JSON.stringify({ ok: true, host: { id: "host_1", label: "Prod", hostname: "prod.example.com", port: 22 }, diff --git a/components/ai/ChatMessageList.tsx b/components/ai/ChatMessageList.tsx index 07123558f..f7d876f58 100644 --- a/components/ai/ChatMessageList.tsx +++ b/components/ai/ChatMessageList.tsx @@ -264,8 +264,8 @@ const ChatMessageList: React.FC = ({ const resultToolName = typeof tr.toolName === 'string' ? tr.toolName : undefined; const pairedToolName = toolCallNames.get(tr.toolCallId); const artifactToolName = - normalizeArtifactToolName(resultToolName) - ?? inferArtifactToolNameFromCliArgs(args) + inferArtifactToolNameFromCliArgs(args) + ?? normalizeArtifactToolName(resultToolName) ?? normalizeArtifactToolName(pairedToolName); return { toolCallId: tr.toolCallId, From 59ae79837d44fc7ad8becd2569bb8f1dbfe5e355 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 02:43:59 +0800 Subject: [PATCH 074/228] Clean up lint warnings --- components/AIChatSidePanel.tsx | 1 - components/settings/tabs/ai/managedAgentState.ts | 1 - infrastructure/ai/harness/turnDrivers/types.ts | 1 - infrastructure/ai/shared/approvalGate.ts | 8 -------- 4 files changed, 11 deletions(-) diff --git a/components/AIChatSidePanel.tsx b/components/AIChatSidePanel.tsx index 53dc51352..e28203624 100644 --- a/components/AIChatSidePanel.tsx +++ b/components/AIChatSidePanel.tsx @@ -10,7 +10,6 @@ import type { AgentModelPreset, AISessionScope, DiscoveredAgent, - ExternalAgentConfig, } from '../infrastructure/ai/types'; import type { ExecutorContext } from '../infrastructure/ai/cattyAgent/executor'; import { getAgentModelPresets } from '../infrastructure/ai/types'; diff --git a/components/settings/tabs/ai/managedAgentState.ts b/components/settings/tabs/ai/managedAgentState.ts index b78e419ab..7d96dbaed 100644 --- a/components/settings/tabs/ai/managedAgentState.ts +++ b/components/settings/tabs/ai/managedAgentState.ts @@ -1,7 +1,6 @@ import type { ExternalAgentConfig } from "../../../../infrastructure/ai/types"; import { type ManagedAgentKey, - getExternalAgentSdkBackend, isPathLikeCommand, } from "../../../../infrastructure/ai/managedAgents"; import type { AgentPathInfo } from "./types"; diff --git a/infrastructure/ai/harness/turnDrivers/types.ts b/infrastructure/ai/harness/turnDrivers/types.ts index ba160c9b3..72a437d94 100644 --- a/infrastructure/ai/harness/turnDrivers/types.ts +++ b/infrastructure/ai/harness/turnDrivers/types.ts @@ -6,7 +6,6 @@ import type { ChatMessage, ChatMessageAttachment, ExternalAgentConfig, - ProviderAdvancedParams, ProviderConfig, WebSearchConfig, } from '../../types'; diff --git a/infrastructure/ai/shared/approvalGate.ts b/infrastructure/ai/shared/approvalGate.ts index ae54d3b5d..e76653bb5 100644 --- a/infrastructure/ai/shared/approvalGate.ts +++ b/infrastructure/ai/shared/approvalGate.ts @@ -47,19 +47,12 @@ export type GrantPersister = (rule: PermissionGrantRule) => void; let grantPersister: GrantPersister | null = null; const grantPersisterStack: GrantPersister[] = []; -let grantsHydrated = false; function refreshPermissionGrantsFromStorage(): void { if (typeof window === 'undefined') return; setActivePermissionGrants( sanitizePermissionGrants(localStorageAdapter.read(STORAGE_KEY_AI_PERMISSION_GRANTS)), ); - grantsHydrated = true; -} - -function ensureGrantsHydrated(): void { - if (grantsHydrated) return; - refreshPermissionGrantsFromStorage(); } export function setGrantPersister(persister: GrantPersister | null): void { @@ -112,7 +105,6 @@ function emitApprovalEvent( extra?: { outcome?: 'approved' | 'denied' | 'timeout'; persistedGrantId?: string }, ): void { const sessionId = request.chatSessionId ?? 'global'; - const capabilityId = request.capabilityId ?? resolveCapabilityId(request.toolName); const base = { sessionId, chatSessionId: request.chatSessionId, From ecbc967644ba8ba827f99dd8792859e6476c483a Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 02:51:33 +0800 Subject: [PATCH 075/228] Simplify confirm rules copy --- application/i18n/locales/en/ai.ts | 2 +- application/i18n/locales/ru/ai.ts | 2 +- application/i18n/locales/zh-CN/ai.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/application/i18n/locales/en/ai.ts b/application/i18n/locales/en/ai.ts index 0f2e76f24..c50c30f51 100644 --- a/application/i18n/locales/en/ai.ts +++ b/application/i18n/locales/en/ai.ts @@ -328,7 +328,7 @@ export const enAiMessages: Messages = { 'ai.safety.blocklist.add': 'Add pattern', 'ai.safety.grants.title': 'Permission memory', 'ai.safety.grants.heading': 'Confirm-mode allow rules', - 'ai.safety.grants.description': 'Rules apply globally in confirm mode (all terminal sessions/nodes). Terminal commands follow OpenCode: always-allow writes command prefix patterns (e.g. lscpu *, git checkout *).', + 'ai.safety.grants.description': 'Confirm mode asks before running an operation. Saved rules automatically allow matching operations across all terminal sessions/nodes, and can be edited manually.', 'ai.safety.grants.empty': 'No saved rules yet. Approve a tool with “Always allow”, or add one manually.', 'ai.safety.grants.capability': 'Capability', 'ai.safety.grants.sessionPattern': 'Session pattern', diff --git a/application/i18n/locales/ru/ai.ts b/application/i18n/locales/ru/ai.ts index bf2c3ec7e..94ef18a24 100644 --- a/application/i18n/locales/ru/ai.ts +++ b/application/i18n/locales/ru/ai.ts @@ -316,7 +316,7 @@ export const ruAiMessages: Messages = { 'ai.safety.blocklist.add': 'Добавить шаблон', 'ai.safety.grants.title': 'Память разрешений', 'ai.safety.grants.heading': 'Правила для режима confirm', - 'ai.safety.grants.description': 'Правила действуют глобально в режиме confirm (все терминальные сессии). Для команд используются префиксы OpenCode (например lscpu *).', + 'ai.safety.grants.description': 'В режиме confirm действие сначала требует подтверждения. Сохранённые правила автоматически разрешают похожие действия во всех терминальных сессиях, их можно редактировать вручную.', 'ai.safety.grants.empty': 'Правил пока нет. Выберите «Всегда разрешать» при одобрении или добавьте вручную.', 'ai.safety.grants.capability': 'Capability ID', 'ai.safety.grants.sessionPattern': 'Шаблон сессии', diff --git a/application/i18n/locales/zh-CN/ai.ts b/application/i18n/locales/zh-CN/ai.ts index 9b46d8882..f7a9c20da 100644 --- a/application/i18n/locales/zh-CN/ai.ts +++ b/application/i18n/locales/zh-CN/ai.ts @@ -328,7 +328,7 @@ export const zhCNAiMessages: Messages = { 'ai.safety.blocklist.add': '添加规则', 'ai.safety.grants.title': '许可记忆表', 'ai.safety.grants.heading': 'Confirm 模式放行规则', - 'ai.safety.grants.description': '规则在 confirm 模式下全局生效(所有终端节点/会话)。终端命令遵循 OpenCode:「一律许可」会写入「命令前缀 + *」(如 lscpu *、git checkout *),也可手动编辑。', + 'ai.safety.grants.description': 'Confirm 模式会先询问再执行;保存为规则后,匹配的同类操作会自动放行。规则对所有终端节点/会话生效,也可手动编辑。', 'ai.safety.grants.empty': '尚无规则。可在审批时选择「一律许可」,或手动添加。', 'ai.safety.grants.capability': '能力', 'ai.safety.grants.sessionPattern': '节点/会话模式', From c9db5d5429774c9e938f80dadbbe7b62d023e73b Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 03:02:41 +0800 Subject: [PATCH 076/228] Fix node-pty spawn helper permissions --- .../bridges/nodePtySpawnHelperPermissions.cjs | 51 +++++++++++++++++++ .../nodePtySpawnHelperPermissions.test.cjs | 48 +++++++++++++++++ electron/bridges/terminalBridge.cjs | 4 ++ 3 files changed, 103 insertions(+) create mode 100644 electron/bridges/nodePtySpawnHelperPermissions.cjs create mode 100644 electron/bridges/nodePtySpawnHelperPermissions.test.cjs diff --git a/electron/bridges/nodePtySpawnHelperPermissions.cjs b/electron/bridges/nodePtySpawnHelperPermissions.cjs new file mode 100644 index 000000000..b9430d88c --- /dev/null +++ b/electron/bridges/nodePtySpawnHelperPermissions.cjs @@ -0,0 +1,51 @@ +const fs = require("node:fs"); +const path = require("node:path"); + +function chmodExecutableIfNeeded(filePath) { + let stat; + try { + stat = fs.statSync(filePath); + } catch { + return false; + } + if (!stat.isFile()) return false; + if ((stat.mode & 0o111) !== 0) return false; + + fs.chmodSync(filePath, stat.mode | 0o111); + return true; +} + +function listNodePtySpawnHelperCandidates(packageRoot, options = {}) { + const platform = options.platform ?? process.platform; + const arch = options.arch ?? process.arch; + return [ + path.join(packageRoot, "build", "Release", "spawn-helper"), + path.join(packageRoot, "build", "Debug", "spawn-helper"), + path.join(packageRoot, "prebuilds", `${platform}-${arch}`, "spawn-helper"), + ]; +} + +function ensureNodePtySpawnHelperExecutable(options = {}) { + const platform = options.platform ?? process.platform; + if (platform === "win32") return []; + + const packageRoot = options.packageRoot ?? path.dirname(require.resolve("node-pty/package.json")); + const changed = []; + + for (const helperPath of listNodePtySpawnHelperCandidates(packageRoot, options)) { + try { + if (chmodExecutableIfNeeded(helperPath)) { + changed.push(helperPath); + } + } catch { + // Best effort: a permission fix must not prevent the app from starting. + } + } + + return changed; +} + +module.exports = { + ensureNodePtySpawnHelperExecutable, + listNodePtySpawnHelperCandidates, +}; diff --git a/electron/bridges/nodePtySpawnHelperPermissions.test.cjs b/electron/bridges/nodePtySpawnHelperPermissions.test.cjs new file mode 100644 index 000000000..b9a795def --- /dev/null +++ b/electron/bridges/nodePtySpawnHelperPermissions.test.cjs @@ -0,0 +1,48 @@ +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const test = require("node:test"); + +const { ensureNodePtySpawnHelperExecutable } = require("./nodePtySpawnHelperPermissions.cjs"); + +function makeTempPackageRoot() { + return fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-node-pty-perms-")); +} + +function writeHelper(root, relativePath, mode = 0o644) { + const filePath = path.join(root, relativePath); + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + fs.writeFileSync(filePath, "#!/bin/sh\nexit 0\n"); + fs.chmodSync(filePath, mode); + return filePath; +} + +test("ensureNodePtySpawnHelperExecutable marks packaged helpers executable", () => { + const root = makeTempPackageRoot(); + const prebuildHelper = writeHelper(root, "prebuilds/darwin-arm64/spawn-helper"); + const releaseHelper = writeHelper(root, "build/Release/spawn-helper"); + + const changed = ensureNodePtySpawnHelperExecutable({ + packageRoot: root, + platform: "darwin", + arch: "arm64", + }); + + assert.deepEqual( + changed.sort(), + [prebuildHelper, releaseHelper].sort(), + ); + assert.notEqual(fs.statSync(prebuildHelper).mode & 0o111, 0); + assert.notEqual(fs.statSync(releaseHelper).mode & 0o111, 0); +}); + +test("ensureNodePtySpawnHelperExecutable ignores missing helpers", () => { + const root = makeTempPackageRoot(); + + assert.deepEqual(ensureNodePtySpawnHelperExecutable({ + packageRoot: root, + platform: "darwin", + arch: "arm64", + }), []); +}); diff --git a/electron/bridges/terminalBridge.cjs b/electron/bridges/terminalBridge.cjs index 24c426265..4dc6d8da4 100644 --- a/electron/bridges/terminalBridge.cjs +++ b/electron/bridges/terminalBridge.cjs @@ -11,6 +11,10 @@ const { execFile, execFileSync } = require("node:child_process"); const path = require("node:path"); const { promisify } = require("node:util"); const { StringDecoder } = require("node:string_decoder"); +const { ensureNodePtySpawnHelperExecutable } = require("./nodePtySpawnHelperPermissions.cjs"); + +ensureNodePtySpawnHelperExecutable(); + const pty = require("node-pty"); const { SerialPort } = require("serialport"); const { emitTerminalSessionData } = require("./emitTerminalSessionData.cjs"); From f4ca635c1a01aa1e99881b01fca3787b6beb2f73 Mon Sep 17 00:00:00 2001 From: Zheng Liu Date: Fri, 26 Jun 2026 10:48:58 +0800 Subject: [PATCH 077/228] Fix restored terminal cwd tracking --- components/Terminal.tsx | 8 ++- components/TerminalLayer.tsx | 18 ++++--- .../terminal/restoredSessionGate.test.ts | 46 ++++++++++++++++ .../createTerminalSessionStarters.test.ts | 5 ++ .../runtime/createTerminalSessionStarters.ts | 1 + .../createTerminalSessionStarters.types.ts | 1 + components/terminal/useTerminalEffects.ts | 4 +- .../terminalLayer/commandCwdProbe.test.ts | 52 +++++++++++++++++++ components/terminalLayer/commandCwdProbe.ts | 28 ++++++++++ 9 files changed, 152 insertions(+), 11 deletions(-) create mode 100644 components/terminalLayer/commandCwdProbe.test.ts create mode 100644 components/terminalLayer/commandCwdProbe.ts diff --git a/components/Terminal.tsx b/components/Terminal.tsx index ab73f8668..2f7dfc45b 100644 --- a/components/Terminal.tsx +++ b/components/Terminal.tsx @@ -654,9 +654,10 @@ const TerminalComponent: React.FC = ({ return cwd ?? undefined; }, [terminalBackend, terminalCwdTracker]); - const clearTerminalCwd = useCallback(() => { + const clearTerminalCwd = useCallback((options?: { persistRestoreMetadata?: boolean }) => { terminalCwdTracker.clearRendererCwd(); knownCwdRef.current = undefined; + if (options?.persistRestoreMetadata === false) return; onTerminalCwdChange?.(sessionId, null); }, [onTerminalCwdChange, sessionId, terminalCwdTracker]); @@ -1145,7 +1146,7 @@ const TerminalComponent: React.FC = ({ setChainProgress, t, onSessionAttached: (id: string) => { - clearTerminalCwd(); + clearTerminalCwd({ persistRestoreMetadata: false }); // SSH: always sync. Its backend starts in utf-8 regardless of // host.charset, so the push is what keeps the UI state aligned // across reconnects — including localhost SSH targets, hence @@ -1170,6 +1171,9 @@ const TerminalComponent: React.FC = ({ setSessionEncoding(id, terminalEncodingRef.current); } }, + onRestoreCwdIntentConsumed: (cwd: string) => { + knownCwdRef.current = cwd; + }, onSessionExit: (closedSessionId, evt) => { clearTerminalCwd(); onSessionExit?.(closedSessionId, evt); diff --git a/components/TerminalLayer.tsx b/components/TerminalLayer.tsx index 2aa03c63b..e8feed8f3 100644 --- a/components/TerminalLayer.tsx +++ b/components/TerminalLayer.tsx @@ -63,9 +63,9 @@ import { resolveAiNoteArtifactPanelIntent } from './terminalLayer/aiNoteArtifact import { canUseDirectSessionWriteFallback, } from './terminalLayer/terminalLayerSessionRouting'; +import { shouldProbeCommandCwd } from './terminalLayer/commandCwdProbe'; import { resolvePreferredTerminalCwd, scheduleBackendCwdProbeAfterCommand } from './terminal/sftpCwd'; import { classifyDistroId, shouldProbeSessionCwd } from '../domain/host'; -import { resolveHostFollowTerminalCwd, resolveSftpFollowTerminalCwdTargetHost } from './sftp/sftpFollowTerminalCwd'; import { AIChatPanelsHost, @@ -712,14 +712,18 @@ const TerminalLayerInner: React.FC = ({ applySessionCodingCliProviderFromCommand(sessionId, command); const tabId = activeTabIdRef.current; - if (!tabId || sidePanelOpenTabsRef.current.get(tabId) !== 'sftp') return; - const session = sessionsRef.current.find((candidate) => candidate.id === sessionId); if (!session || !canReuseTerminalConnection(session)) return; const sessionHost = sessionHostsMapRef.current.get(sessionId); - const visibleSftpHost = sftpHostForTabRef.current.get(tabId) ?? null; - const followHost = resolveSftpFollowTerminalCwdTargetHost(visibleSftpHost, sessionHost); - if (!resolveHostFollowTerminalCwd(followHost?.sftpFollowTerminalCwd, sftpFollowTerminalCwdRef.current)) return; + const visibleSftpHost = tabId && sidePanelOpenTabsRef.current.get(tabId) === 'sftp' + ? sftpHostForTabRef.current.get(tabId) ?? null + : null; + if (!shouldProbeCommandCwd({ + restoreTerminalCwd, + visibleSftpHost, + sessionHost, + globalSftpFollowTerminalCwd: sftpFollowTerminalCwdRef.current, + })) return; const osc7SignalAtCommand = terminalOsc7SignalBySessionRef.current.get(sessionId) ?? 0; const probeGeneration = (cwdProbeGenerationRef.current.get(sessionId) ?? 0) + 1; @@ -751,7 +755,7 @@ const TerminalLayerInner: React.FC = ({ }, }); cwdProbeCancelersRef.current.set(sessionId, cancelProbe); - }, [applySessionCodingCliProviderFromCommand, handleTerminalCwdChange, terminalBackend]); + }, [applySessionCodingCliProviderFromCommand, handleTerminalCwdChange, restoreTerminalCwd, terminalBackend]); const handleCommandExecuted = useCallback((command: string, hostId: string, hostLabel: string, sessionId: string) => { onCommandExecuted?.(command, hostId, hostLabel, sessionId); diff --git a/components/terminal/restoredSessionGate.test.ts b/components/terminal/restoredSessionGate.test.ts index 7c80e0230..35ffa7609 100644 --- a/components/terminal/restoredSessionGate.test.ts +++ b/components/terminal/restoredSessionGate.test.ts @@ -82,3 +82,49 @@ test("manual reconnect captures restore cwd intent before clearing restored stat "manual retry must reactivate the boot guard before opening a backend session", ); }); + +test("startup and attach cwd cache clears preserve restore cwd metadata", () => { + const terminalSource = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); + const effectsSource = readFileSync(new URL("./useTerminalEffects.ts", import.meta.url), "utf8"); + + const clearDefinitionIndex = terminalSource.indexOf("const clearTerminalCwd = useCallback"); + const clearNotifyIndex = terminalSource.indexOf("onTerminalCwdChange?.(sessionId, null)", clearDefinitionIndex); + const persistGuardIndex = terminalSource.indexOf("persistRestoreMetadata", clearDefinitionIndex); + const attachIndex = terminalSource.indexOf("onSessionAttached: (id: string) =>"); + const attachClearIndex = terminalSource.indexOf("clearTerminalCwd({ persistRestoreMetadata: false })", attachIndex); + const startupClearIndex = effectsSource.indexOf("clearTerminalCwd({ persistRestoreMetadata: false })"); + + assert.notEqual(clearDefinitionIndex, -1); + assert.notEqual(clearNotifyIndex, -1); + assert.notEqual(persistGuardIndex, -1); + assert.notEqual(attachIndex, -1); + assert.notEqual(attachClearIndex, -1); + assert.notEqual(startupClearIndex, -1); + assert.ok( + persistGuardIndex < clearNotifyIndex, + "clearTerminalCwd must gate persisted restore metadata updates", + ); +}); + +test("restored cwd intent marks known cwd before initial backend pwd probe can persist home", () => { + const terminalSource = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); + const effectsSource = readFileSync(new URL("./useTerminalEffects.ts", import.meta.url), "utf8"); + + const callbackIndex = terminalSource.indexOf("onRestoreCwdIntentConsumed:"); + const knownAssignIndex = terminalSource.indexOf("knownCwdRef.current = cwd", callbackIndex); + const backendProbeGuardIndex = effectsSource.indexOf("knownCwdRef.current"); + const backendPwdWriteIndex = effectsSource.indexOf("onTerminalCwdChange?.(sessionId, cwd ?? null)", backendProbeGuardIndex); + + assert.notEqual(callbackIndex, -1); + assert.notEqual(knownAssignIndex, -1); + assert.notEqual(backendProbeGuardIndex, -1); + assert.notEqual(backendPwdWriteIndex, -1); + assert.ok( + knownAssignIndex > callbackIndex, + "Terminal must preserve the restore target as a known cwd when the restore command is sent", + ); + assert.ok( + backendProbeGuardIndex < backendPwdWriteIndex, + "initial backend pwd probe must remain guarded by knownCwdRef before it writes restore metadata", + ); +}); diff --git a/components/terminal/runtime/createTerminalSessionStarters.test.ts b/components/terminal/runtime/createTerminalSessionStarters.test.ts index 688a0d950..fe15e3860 100644 --- a/components/terminal/runtime/createTerminalSessionStarters.test.ts +++ b/components/terminal/runtime/createTerminalSessionStarters.test.ts @@ -871,6 +871,7 @@ test("ssh session restores cwd before startup command after attaching", async () const sessionWrites: Array<{ id: string; data: string; automated?: boolean }> = []; const executedCommands: string[] = []; const progressLogs: string[] = []; + const restoredCwds: string[] = []; const terminalBackend = { backendAvailable: () => true, @@ -906,6 +907,9 @@ test("ssh session restores cwd before startup command after attaching", async () setProgressLogs: (updater: (prev: string[]) => string[]) => { progressLogs.splice(0, progressLogs.length, ...updater(progressLogs)); }, + onRestoreCwdIntentConsumed: (cwd: string) => { + restoredCwds.push(cwd); + }, onCommandExecuted: (command: string) => { executedCommands.push(command); }, @@ -915,6 +919,7 @@ test("ssh session restores cwd before startup command after attaching", async () await new Promise((resolve) => setTimeout(resolve, 0)); assert.equal(restoreCwdIntentRef.current, null); + assert.deepEqual(restoredCwds, ["/srv/app dir"]); assert.deepEqual(sessionWrites, [ { id: "ssh-session", data: "cd -- '/srv/app dir'\r", automated: true }, { id: "ssh-session", data: "pwd\r", automated: true }, diff --git a/components/terminal/runtime/createTerminalSessionStarters.ts b/components/terminal/runtime/createTerminalSessionStarters.ts index 6517a74c2..d45b992ef 100644 --- a/components/terminal/runtime/createTerminalSessionStarters.ts +++ b/components/terminal/runtime/createTerminalSessionStarters.ts @@ -73,6 +73,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex ctx.setProgressLogs((prev) => [...prev, tr("terminal.restore.cwdLog", `Restoring working directory: ${intent.cwd}`) .replace("{cwd}", intent.cwd)]); ctx.terminalBackend.writeToSession(id, `${intent.command}\r`, { automated: true }); + ctx.onRestoreCwdIntentConsumed?.(intent.cwd); markPromptLineBreakCommandPending(ctx.promptLineBreakStateRef, term, intent.command); }; diff --git a/components/terminal/runtime/createTerminalSessionStarters.types.ts b/components/terminal/runtime/createTerminalSessionStarters.types.ts index f7d07ae46..f042b06ea 100644 --- a/components/terminal/runtime/createTerminalSessionStarters.types.ts +++ b/components/terminal/runtime/createTerminalSessionStarters.types.ts @@ -150,6 +150,7 @@ export type TerminalSessionStartersContext = { t?: (key: string) => string; onSessionAttached?: (sessionId: string) => void; + onRestoreCwdIntentConsumed?: (cwd: string) => void; onSessionExit?: (sessionId: string, evt: { exitCode?: number; signal?: number; error?: string; reason?: "exited" | "error" | "timeout" | "closed" }) => void; onTerminalDataCapture?: (sessionId: string, data: string) => void; onTerminalLogData?: (data: string) => void; diff --git a/components/terminal/useTerminalEffects.ts b/components/terminal/useTerminalEffects.ts index adbfe7fb4..5286605ba 100644 --- a/components/terminal/useTerminalEffects.ts +++ b/components/terminal/useTerminalEffects.ts @@ -125,8 +125,8 @@ export function useTerminalEffects(ctx: TerminalEffectsContext) { useEffect(() => { - clearTerminalCwd(); - return clearTerminalCwd; + clearTerminalCwd({ persistRestoreMetadata: false }); + return () => clearTerminalCwd({ persistRestoreMetadata: false }); }, [clearTerminalCwd, host.id]); diff --git a/components/terminalLayer/commandCwdProbe.test.ts b/components/terminalLayer/commandCwdProbe.test.ts new file mode 100644 index 000000000..ad5187312 --- /dev/null +++ b/components/terminalLayer/commandCwdProbe.test.ts @@ -0,0 +1,52 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { shouldProbeCommandCwd } from "./commandCwdProbe"; + +test("probes command cwd for session restore even when the SFTP panel is not visible", () => { + assert.equal( + shouldProbeCommandCwd({ + restoreTerminalCwd: true, + visibleSftpHost: null, + sessionHost: { sftpFollowTerminalCwd: false }, + globalSftpFollowTerminalCwd: false, + }), + true, + ); +}); + +test("does not probe command cwd when neither session restore nor SFTP follow cwd needs it", () => { + assert.equal( + shouldProbeCommandCwd({ + restoreTerminalCwd: false, + visibleSftpHost: null, + sessionHost: { sftpFollowTerminalCwd: true }, + globalSftpFollowTerminalCwd: true, + }), + false, + ); +}); + +test("probes command cwd for visible SFTP follow cwd using host override", () => { + assert.equal( + shouldProbeCommandCwd({ + restoreTerminalCwd: false, + visibleSftpHost: { sftpFollowTerminalCwd: true }, + sessionHost: { sftpFollowTerminalCwd: false }, + globalSftpFollowTerminalCwd: false, + }), + true, + ); +}); + +test("visible SFTP host override can disable command cwd probing", () => { + assert.equal( + shouldProbeCommandCwd({ + restoreTerminalCwd: false, + visibleSftpHost: { sftpFollowTerminalCwd: false }, + sessionHost: { sftpFollowTerminalCwd: true }, + globalSftpFollowTerminalCwd: true, + }), + false, + ); +}); diff --git a/components/terminalLayer/commandCwdProbe.ts b/components/terminalLayer/commandCwdProbe.ts new file mode 100644 index 000000000..e3f0664b2 --- /dev/null +++ b/components/terminalLayer/commandCwdProbe.ts @@ -0,0 +1,28 @@ +import { resolveHostFollowTerminalCwd, resolveSftpFollowTerminalCwdTargetHost } from "../sftp/sftpFollowTerminalCwd"; + +type FollowTerminalCwdHost = { + sftpFollowTerminalCwd?: boolean; +}; + +type ShouldProbeCommandCwdOptions = { + restoreTerminalCwd: boolean; + visibleSftpHost?: FollowTerminalCwdHost | null; + sessionHost?: FollowTerminalCwdHost | null; + globalSftpFollowTerminalCwd: boolean; +}; + +export const shouldProbeCommandCwd = ({ + restoreTerminalCwd, + visibleSftpHost, + sessionHost, + globalSftpFollowTerminalCwd, +}: ShouldProbeCommandCwdOptions): boolean => { + if (restoreTerminalCwd) return true; + + if (!visibleSftpHost) return false; + const followHost = resolveSftpFollowTerminalCwdTargetHost(visibleSftpHost, sessionHost); + return resolveHostFollowTerminalCwd( + followHost?.sftpFollowTerminalCwd, + globalSftpFollowTerminalCwd, + ); +}; From 97b1a2a336a7547253d989c89ac9f99d09ad82dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 11:15:46 +0800 Subject: [PATCH 078/228] Migrate Catty harness to AI SDK v7 and fix tool denial UI. (#1707) Adopts streamText instructions/runtimeContext/toolApproval APIs, lifecycle events, and denied-tool result rendering so observer blocks and approval rejections stay visible in chat history. Co-authored-by: Cursor --- AGENTS.md | 16 +- application/i18n/locales/en/ai.ts | 6 +- application/i18n/locales/zh-CN/ai.ts | 6 +- components/ai-elements/tool-call.tsx | 70 +++-- components/ai/ToolCallGroup.tsx | 2 +- components/ai/hooks/aiChatStreamingSupport.ts | 69 ++++- .../ai/harness/agentEventAdapter.test.ts | 67 +++++ .../ai/harness/agentEventAdapter.ts | 87 ++++++ .../ai/harness/capabilityTools.test.ts | 51 ++-- infrastructure/ai/harness/capabilityTools.ts | 112 +++++--- infrastructure/ai/harness/cattyRuntime.ts | 4 +- .../ai/harness/cattyRuntimeContext.ts | 72 +++++ .../ai/harness/cattyStreamProcessor.test.ts | 29 ++ .../ai/harness/cattyToolApproval.test.ts | 98 +++++++ .../ai/harness/cattyToolApproval.ts | 67 +++++ .../ai/harness/contextManager.test.ts | 40 ++- infrastructure/ai/harness/contextManager.ts | 44 ++- infrastructure/ai/harness/index.ts | 14 + infrastructure/ai/harness/streamTimeouts.ts | 29 ++ .../turnDrivers/cattyMessageBuilder.ts | 4 +- .../turnDrivers/cattyStreamProcessor.ts | 256 +++++++++++++++--- .../ai/harness/turnDrivers/cattyTurnDriver.ts | 41 +-- .../ai/harness/turnDrivers/types.ts | 1 + infrastructure/ai/harness/types.ts | 31 +++ .../ai/modelDiscoveryHeaders.test.ts | 2 +- .../ai/providersBridgeFetch.test.ts | 28 +- infrastructure/ai/sdk/providers.ts | 4 +- infrastructure/ai/sdkAgentAdapter.ts | 4 +- infrastructure/ai/shared/approvalGate.ts | 4 +- infrastructure/ai/shared/streamStateErrors.ts | 2 +- package-lock.json | 217 +++++++-------- package.json | 11 +- 32 files changed, 1153 insertions(+), 335 deletions(-) create mode 100644 infrastructure/ai/harness/agentEventAdapter.test.ts create mode 100644 infrastructure/ai/harness/cattyRuntimeContext.ts create mode 100644 infrastructure/ai/harness/cattyStreamProcessor.test.ts create mode 100644 infrastructure/ai/harness/cattyToolApproval.test.ts create mode 100644 infrastructure/ai/harness/cattyToolApproval.ts create mode 100644 infrastructure/ai/harness/streamTimeouts.ts diff --git a/AGENTS.md b/AGENTS.md index 52198855a..588840dd9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,10 +32,24 @@ Turn orchestration is centralized in **AgentRuntime**; the React hook `useAIChat | Drivers | `turnDrivers/cattyTurnDriver.ts`, `turnDrivers/externalSdkTurnDriver.ts` | Catty `streamText` + External SDK IPC; emit unified `AgentEvent`s | | Context | `contextManager.ts`, `tokenEstimator.ts`, `cattyRuntime.ts` | Pre-turn / 413 compaction, `prepareStepContext`, provider-aware token estimates | | Tools | `capabilityTools.ts`, `toolOutputStore.ts`, `toolResultDedup.ts` | Catalog tools, truncated output handles (`tool_output_read`), duplicate-read notices | -| Trace | `traceStore.ts`, `agentEventAdapter.ts` | Session event log incl. `usage` and `CompactionTrace` | +| Trace | `traceStore.ts`, `agentEventAdapter.ts` | Session event log incl. `usage`, `performance`, and `CompactionTrace` | **Stop** always goes through `stopAgentTurn()` (UI, `/stop`, MCP). Do not add parallel abort paths in hooks. +### AI SDK v7 (Catty path) + +Catty sidebar turns use **Vercel AI SDK 7** via `streamText` in `turnDrivers/cattyStreamProcessor.ts`. Key conventions: + +| Concern | Module | Notes | +|---------|--------|-------| +| `runtimeContext` | `cattyRuntimeContext.ts` | Per-turn orchestration state (`chatSessionId`, `turnId`, `agentKind`, `permissionMode`, scope, `lastCompaction`). Passed to `prepareStep` and lifecycle callbacks. **Does not replace** pre-turn compaction or 413 handling. | +| `toolsContext` | `capabilityTools.ts` | Per-tool keyed context (`bridge`, `getExecutorContext`, `toolOutputStore`, …). Tools read deps from `{ context }` in `execute`, not closure capture. | +| `toolApproval` | `cattyToolApproval.ts` | Write-tool gating for Catty `streamText` only. Calls `requestApproval()` in confirm mode; observer auto-denies writes. **External MCP agents** still approve via main-process `mcpServerBridge` → `setupMcpApprovalBridge()` — unchanged. | +| `timeout` | `streamTimeouts.ts` | `totalMs` / `stepMs` / `chunkMs` / `toolMs` on `streamText`; compaction `generateText` uses a shorter 90s timeout. | +| Lifecycle | `cattyStreamProcessor.ts` | `onStart` → `model_call_start`; `onStepEnd` → per-step `step_end` usage; `onEnd` → turn-total `usage`; `finalStep.performance` → `performance` event. Distinct from `AgentRuntime` turn_start/turn_end. | + +Compaction remains **`prepareTurnContext` / `compactCattyMessages`** (pre-turn + 413-retry). Step-level pruning is **`prepareStepContext`** only (typed compression + handle notices, no LLM summarize). + ### Capability exposure (Round 2 + gap fill) Single source of truth: `electron/capabilities/catalog/` + `electron/capabilities/codegen/toolSurfaces.cjs`. diff --git a/application/i18n/locales/en/ai.ts b/application/i18n/locales/en/ai.ts index c50c30f51..a7aa68ef2 100644 --- a/application/i18n/locales/en/ai.ts +++ b/application/i18n/locales/en/ai.ts @@ -220,10 +220,10 @@ export const enAiMessages: Messages = { 'ai.chat.noProvider': 'No AI provider is configured. Go to **Settings → AI → Providers** to add and enable a provider.', 'ai.chat.toolDenied': 'Action was rejected by the user.', 'ai.chat.toolApproved': 'Approved', - 'ai.chat.toolApprovalHint': 'Press Enter to approve once, Escape to reject', + 'ai.chat.toolApprovalHint': 'Enter once · Esc reject', 'ai.chat.approve': 'Approve', - 'ai.chat.approveOnce': 'Allow once', - 'ai.chat.alwaysAllow': 'Always allow', + 'ai.chat.approveOnce': 'Once', + 'ai.chat.alwaysAllow': 'Always', 'ai.chat.slashStopDesc': 'Stop the current AI turn and cancel in-flight tools', 'ai.chat.reject': 'Reject', 'ai.chat.toolLabel': 'Tool', diff --git a/application/i18n/locales/zh-CN/ai.ts b/application/i18n/locales/zh-CN/ai.ts index f7a9c20da..be381f060 100644 --- a/application/i18n/locales/zh-CN/ai.ts +++ b/application/i18n/locales/zh-CN/ai.ts @@ -220,10 +220,10 @@ export const zhCNAiMessages: Messages = { 'ai.chat.noProvider': '尚未配置 AI 提供商。请前往 **设置 → AI → 提供商** 添加并启用一个提供商。', 'ai.chat.toolDenied': '操作已被用户拒绝。', 'ai.chat.toolApproved': '已批准', - 'ai.chat.toolApprovalHint': 'Enter 仅当次许可,Escape 拒绝', + 'ai.chat.toolApprovalHint': 'Enter 允许 · Esc 拒绝', 'ai.chat.approve': '批准', - 'ai.chat.approveOnce': '仅当次许可', - 'ai.chat.alwaysAllow': '一律许可', + 'ai.chat.approveOnce': '允许', + 'ai.chat.alwaysAllow': '始终', 'ai.chat.slashStopDesc': '停止当前 AI 回合并取消进行中的工具', 'ai.chat.reject': '拒绝', 'ai.chat.toolLabel': '工具', diff --git a/components/ai-elements/tool-call.tsx b/components/ai-elements/tool-call.tsx index 8e053b58c..2b2552d38 100644 --- a/components/ai-elements/tool-call.tsx +++ b/components/ai-elements/tool-call.tsx @@ -227,7 +227,7 @@ export const ToolCall = ({ ref={cardRef} tabIndex={isPendingApproval ? 0 : undefined} onKeyDown={isPendingApproval ? handleKeyDown : undefined} - className={cn('rounded-md border overflow-hidden text-[12px] outline-none', borderClass, className)} + className={cn('min-w-0 rounded-md border overflow-hidden text-[12px] outline-none', borderClass, className)} {...props} > - - -
+
+

+ {t('ai.chat.toolApprovalHint')} +

+
+ + +
)} diff --git a/components/ai/ToolCallGroup.tsx b/components/ai/ToolCallGroup.tsx index 84644f8f0..20279aece 100644 --- a/components/ai/ToolCallGroup.tsx +++ b/components/ai/ToolCallGroup.tsx @@ -36,7 +36,7 @@ const ToolCallGroup: React.FC = ({ }, [defaultExpanded]); return ( -
+
-
-

- {t("terminal.osc7Setup.command")} -

-
-                    {osc7SetupCommand}
-                  
-
- diff --git a/components/terminal/osc7Setup.test.ts b/components/terminal/osc7Setup.test.ts index 9434ab4de..81dc01aac 100644 --- a/components/terminal/osc7Setup.test.ts +++ b/components/terminal/osc7Setup.test.ts @@ -5,7 +5,13 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync import { tmpdir } from "node:os"; import { basename, join } from "node:path"; -import { OSC7_MARKER, buildOsc7SetupCommand, shouldOfferOsc7SetupAction } from "./osc7Setup"; +import { + OSC7_MARKER, + buildOsc7SetupCommand, + buildOsc7SetupExecCommand, + runOsc7SetupAction, + shouldOfferOsc7SetupAction, +} from "./osc7Setup"; const runSetup = (env: NodeJS.ProcessEnv) => { execFileSync("/bin/sh", ["-c", buildOsc7SetupCommand()], { @@ -54,6 +60,70 @@ test("shouldOfferOsc7SetupAction only allows remote shell-style sessions", () => assert.equal(shouldOfferOsc7SetupAction({ protocol: "serial", isSerialConnection: true }), false); }); +test("runOsc7SetupAction configures in the background and only sends a small reload command", async () => { + const writes: Array<{ sessionId: string; data: string; automated?: boolean }> = []; + const localData: string[] = []; + let setupArgs: { sessionId: string; command: string } | null = null; + + const result = await runOsc7SetupAction({ + status: "connected", + sessionId: "session-1", + setupCommand: "printf setup-script", + setupOsc7Tracking: async (sessionId, command) => { + setupArgs = { sessionId, command }; + return { + success: true, + stdout: "__NETCATTY_OSC7_SETUP_SHELL__=bash\n__NETCATTY_OSC7_SETUP_CONFIG__=/home/me/.bashrc\n\u001b]7;file://host/home/me\u0007", + stderr: "", + code: 0, + }; + }, + writeToSession: (sessionId, data, options) => { + writes.push({ sessionId, data, automated: options?.automated }); + }, + writeLocalTerminalData: (data) => { + localData.push(data); + }, + }); + + assert.equal(result.success, true); + assert.deepEqual(setupArgs, { sessionId: "session-1", command: "printf setup-script" }); + assert.equal(writes.length, 1); + assert.equal(writes[0].sessionId, "session-1"); + assert.equal(writes[0].automated, true); + assert.match(writes[0].data, /source '\/home\/me\/\.bashrc'/); + assert.doesNotMatch(writes[0].data, /setup-script/); + assert.deepEqual(localData, ["\u001b]7;file://host/home/me\u0007"]); +}); + +test("runOsc7SetupAction fails without reload metadata instead of reporting a partial setup", async () => { + const writes: string[] = []; + const localData: string[] = []; + + const result = await runOsc7SetupAction({ + status: "connected", + sessionId: "session-1", + setupCommand: "printf setup-script", + setupOsc7Tracking: async () => ({ + success: true, + stdout: "\u001b]7;file://host/home/me\u0007", + stderr: "", + code: 0, + }), + writeToSession: (_sessionId, data) => { + writes.push(data); + }, + writeLocalTerminalData: (data) => { + localData.push(data); + }, + }); + + assert.equal(result.success, false); + assert.match(result.error || "", /reload metadata/); + assert.deepEqual(writes, []); + assert.deepEqual(localData, []); +}); + test("buildOsc7SetupCommand configures bash once and prompt loading stays idempotent", () => { withTempHome("netcatty-osc7-bash-", (home) => { runSetup({ HOME: home, SHELL: "/bin/bash" }); @@ -77,6 +147,47 @@ test("buildOsc7SetupCommand configures bash once and prompt loading stays idempo }); }); +test("buildOsc7SetupExecCommand configures bash through a background exec shell", () => { + withTempHome("netcatty-osc7-exec-bash-", (home) => { + const output = execFileSync("/bin/sh", ["-c", buildOsc7SetupExecCommand()], { + env: { ...process.env, HOME: home, SHELL: "/bin/bash" }, + stdio: "pipe", + }).toString("utf8"); + + assert.match(output, /__NETCATTY_OSC7_SETUP_SHELL__=bash/); + assert.match(output, new RegExp(`__NETCATTY_OSC7_SETUP_CONFIG__=${home.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/\\.bashrc`)); + const bashrc = readFileSync(join(home, ".bashrc"), "utf8"); + assert.equal(markerCount(bashrc), 2); + }); +}); + +test("buildOsc7SetupExecCommand carries the expected cwd for current-tab matching", () => { + const command = buildOsc7SetupExecCommand("/srv/app's cwd"); + + assert.match(command, /NETCATTY_OSC7_EXPECTED_CWD='\/srv\/app'\\''s cwd'/); +}); + +test("buildOsc7SetupExecCommand honors exported zsh ZDOTDIR fallback", (t) => { + const zshPath = existingShells(["/bin/zsh", "/usr/bin/zsh"])[0]; + if (!zshPath) { + t.skip("zsh is not installed on this runner"); + return; + } + + withTempHome("netcatty-osc7-exec-zsh-", (home) => { + const zdotdir = join(home, ".config", "zsh"); + const output = execFileSync("/bin/sh", ["-c", buildOsc7SetupExecCommand()], { + env: { ...process.env, HOME: home, SHELL: zshPath, ZDOTDIR: zdotdir }, + stdio: "pipe", + }).toString("utf8"); + + const zshrcPath = join(zdotdir, ".zshrc"); + assert.match(output, /__NETCATTY_OSC7_SETUP_SHELL__=zsh/); + assert.match(output, new RegExp(`__NETCATTY_OSC7_SETUP_CONFIG__=${zshrcPath.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`)); + assert.equal(markerCount(readFileSync(zshrcPath, "utf8")), 2); + }); +}); + test("buildOsc7SetupCommand honors zsh ZDOTDIR captured from the current shell", (t) => { const zshPath = existingShells(["/bin/zsh", "/usr/bin/zsh"])[0]; if (!zshPath) { diff --git a/components/terminal/osc7Setup.ts b/components/terminal/osc7Setup.ts index e45292d53..3cf06cbec 100644 --- a/components/terminal/osc7Setup.ts +++ b/components/terminal/osc7Setup.ts @@ -6,6 +6,9 @@ export const OSC7_SETUP_TARGETS = [ "~/.config/fish/config.fish", ] as const; +export const OSC7_SETUP_SHELL_MARKER = "__NETCATTY_OSC7_SETUP_SHELL__="; +export const OSC7_SETUP_CONFIG_MARKER = "__NETCATTY_OSC7_SETUP_CONFIG__="; + export type Osc7SetupActionContext = { protocol?: string; isLocalConnection?: boolean; @@ -13,6 +16,42 @@ export type Osc7SetupActionContext = { isNetworkDevice?: boolean; }; +export type Osc7SetupShell = "bash" | "zsh" | "fish"; + +export type Osc7SetupMetadata = { + shell: Osc7SetupShell; + configPath: string; +}; + +export type Osc7SetupRunResult = { + success: boolean; + pending?: boolean; + stdout?: string; + stderr?: string; + code?: number | null; + error?: string; + reloadCommand?: string; +}; + +export type RunOsc7SetupActionOptions = { + status: string; + sessionId: string; + setupCommand: string; + setupOsc7Tracking?: ( + sessionId: string, + command: string, + ) => Promise; + writeToSession: ( + sessionId: string, + data: string, + options?: { + automated?: boolean; + logRewrite?: { sentCommand: string; displayCommand: string }; + }, + ) => void; + writeLocalTerminalData?: (data: string) => void; +}; + export const shouldOfferOsc7SetupAction = ({ protocol, isLocalConnection, @@ -54,17 +93,126 @@ const URL_PATH_AWK_SCRIPT_QUOTED = quoteForSingleQuotedShellString(URL_PATH_AWK_ const POSIX_SETUP_SCRIPT = String.raw`set -eu marker="# >>> Netcatty OSC 7 cwd tracking >>>" +SELF=$$ +expected_cwd="${DOLLAR}{NETCATTY_OSC7_EXPECTED_CWD:-}" + +find_login_shell() { + _shell=$(ps -e -o pid=,ppid=,tty=,comm= 2>/dev/null | awk -v pp="$1" -v self="$SELF" ' + $1 != self && $2 == pp && $4 ~ /^-?(ba|z|fi|k|da|a)?sh$/ { + if ($3 != "?") { print $1; found=1; exit } + if (any == "") any=$1 + } + END { if (!found && any != "") print any } + ') + [ -n "$_shell" ] && { echo "$_shell"; return; } + [ -r "/proc/$SELF/environ" ] || return + _conn=$(tr '\0' '\n' < "/proc/$SELF/environ" 2>/dev/null | sed -n 's/^SSH_CONNECTION=//p' | head -n1) + [ -z "$_conn" ] && return + _any="" + for _d in /proc/[0-9]*; do + _pid=$(basename "$_d") + [ "$_pid" = "$SELF" ] && continue + [ -r "$_d/environ" ] || continue + _conn2=$(tr '\0' '\n' < "$_d/environ" 2>/dev/null | sed -n 's/^SSH_CONNECTION=//p' | head -n1) + [ "$_conn2" = "$_conn" ] || continue + _comm=$(cat "$_d/comm" 2>/dev/null) + case "$_comm" in + sh|bash|zsh|fish|ksh|dash|ash) ;; + *) continue ;; + esac + _tty=$(ps -p "$_pid" -o tty= 2>/dev/null | tr -d '[:space:]') + if [ "$_tty" != "?" ] && [ -n "$_tty" ]; then + echo "$_pid" + return + fi + [ -z "$_any" ] && _any="$_pid" + done + [ -n "$_any" ] && echo "$_any" +} + +find_active_shell() { + ps -e -o pid=,ppid=,stat=,comm= 2>/dev/null | awk -v start="$1" ' + { pp[$1]=$2; st[$1]=$3; cm[$1]=$4; ord[NR]=$1 } + function isshell(c) { return c ~ /^-?(ba|z|fi|k|da|a)?sh$/ } + function depth(p, d) { d=0; while (p != "" && d < 64) { if (p == start) return d; p=pp[p]; d++ } return -1 } + END { + best=-1; bp=""; + for (i=1; i<=NR; i++) { + p=ord[i]; + if (!isshell(cm[p])) continue; + if (index(st[p], "+") == 0) continue; + d=depth(p); if (d < 0) continue; + if (d > best) { best=d; bp=p } + } + print (bp != "" ? bp : start) + } + ' +} + +read_proc_env_value() { + [ -r "$1" ] || return 1 + tr '\0' '\n' < "$1" 2>/dev/null | sed -n "s/^$2=//p" | head -n1 +} + +active_shell_pid="" +login_shell_pid="" +if [ -d /proc ]; then + login_shell_pid=$(find_login_shell "$PPID" || true) + if [ -n "$login_shell_pid" ]; then + active_shell_pid=$(find_active_shell "$login_shell_pid" || true) + [ -n "$active_shell_pid" ] || active_shell_pid="$login_shell_pid" + fi +fi + +if [ -d /proc ] && [ -n "$expected_cwd" ]; then + if [ -z "$active_shell_pid" ]; then + printf "Netcatty OSC 7 setup: could not identify the active terminal shell\n" >&2 + exit 4 + fi + active_cwd=$(readlink "/proc/$active_shell_pid/cwd" 2>/dev/null || true) + if [ "$active_cwd" != "$expected_cwd" ]; then + printf "Netcatty OSC 7 setup: active terminal shell did not match the current tab\n" >&2 + exit 4 + fi +fi + +active_comm="" +active_home="" +active_shell_env="" +active_zdotdir="" +active_xdg_config_home="" +if [ -n "$active_shell_pid" ]; then + active_comm=$(cat "/proc/$active_shell_pid/comm" 2>/dev/null | sed "s/^-//" | tr -d "[:space:]") + active_env_file="/proc/$active_shell_pid/environ" + if [ -r "$active_env_file" ]; then + active_home=$(read_proc_env_value "$active_env_file" HOME || true) + active_shell_env=$(read_proc_env_value "$active_env_file" SHELL || true) + active_zdotdir=$(read_proc_env_value "$active_env_file" ZDOTDIR || true) + active_xdg_config_home=$(read_proc_env_value "$active_env_file" XDG_CONFIG_HOME || true) + elif [ "$active_shell_pid" != "$login_shell_pid" ]; then + printf "Netcatty OSC 7 setup: cannot silently configure an active shell owned by another user\n" >&2 + exit 3 + fi +fi + parent_shell=$(ps -p "$PPID" -o comm= 2>/dev/null | sed "s/^-//" | tr -d "[:space:]") -login_shell=$(basename "${DOLLAR}{SHELL:-sh}" | sed "s/^-//") +login_shell=$(basename "${DOLLAR}{active_shell_env:-${DOLLAR}{SHELL:-sh}}" | sed "s/^-//") shell_name="$login_shell" case "$parent_shell" in bash|zsh|fish) shell_name="$parent_shell" ;; esac +case "$active_comm" in + bash|zsh|fish) shell_name="$active_comm" ;; +esac + +home_dir="${DOLLAR}{active_home:-$HOME}" +zdotdir="${DOLLAR}{active_zdotdir:-${DOLLAR}{NETCATTY_ZDOTDIR:-${DOLLAR}{ZDOTDIR:-$home_dir}}}" +xdg_config_home="${DOLLAR}{active_xdg_config_home:-${DOLLAR}{NETCATTY_XDG_CONFIG_HOME:-${DOLLAR}{XDG_CONFIG_HOME:-$home_dir/.config}}}" case "$shell_name" in - bash) config="$HOME/.bashrc" ;; - zsh) config="${DOLLAR}{NETCATTY_ZDOTDIR:-$HOME}/.zshrc" ;; - fish) config="${DOLLAR}{NETCATTY_XDG_CONFIG_HOME:-$HOME/.config}/fish/config.fish" ;; + bash) config="$home_dir/.bashrc" ;; + zsh) config="$zdotdir/.zshrc" ;; + fish) config="$xdg_config_home/fish/config.fish" ;; *) printf "Netcatty OSC 7 setup: unsupported shell %s\n" "$shell_name" >&2 printf "Supported shells: bash, zsh, fish\n" >&2 @@ -143,8 +291,112 @@ NETCATTY_OSC7_FISH esac fi +printf '%s%s\n' '${OSC7_SETUP_SHELL_MARKER}' "$shell_name" +printf '%s%s\n' '${OSC7_SETUP_CONFIG_MARKER}' "$config" host=$(hostname 2>/dev/null || printf localhost) printf '\033]7;file://%s%s\a' "$host" "$(__netcatty_osc7_url_path "$PWD")"`; export const buildOsc7SetupCommand = (): string => `set +u 2>/dev/null || true; printf "%s\\n" ${quoteForSingleQuotedShellString(POSIX_SETUP_SCRIPT)} | env NETCATTY_ZDOTDIR="$ZDOTDIR" NETCATTY_XDG_CONFIG_HOME="$XDG_CONFIG_HOME" sh\n`; + +export const buildOsc7SetupExecCommand = (expectedCwd?: string): string => { + const envPrefix = expectedCwd + ? `env NETCATTY_OSC7_EXPECTED_CWD=${quoteForSingleQuotedShellString(expectedCwd)} ` + : ""; + return `exec ${envPrefix}sh -c ${quoteForSingleQuotedShellString(POSIX_SETUP_SCRIPT)}\n`; +}; + +const isOsc7SetupShell = (value: string): value is Osc7SetupShell => + value === "bash" || value === "zsh" || value === "fish"; + +const readMarkerLine = (stdout: string, marker: string): string | null => { + const line = stdout.split(/\r?\n/).find((entry) => entry.startsWith(marker)); + return line ? line.slice(marker.length).trim() : null; +}; + +export const parseOsc7SetupMetadata = (stdout: string): Osc7SetupMetadata | null => { + const shell = readMarkerLine(stdout, OSC7_SETUP_SHELL_MARKER); + const configPath = readMarkerLine(stdout, OSC7_SETUP_CONFIG_MARKER); + if (!shell || !isOsc7SetupShell(shell) || !configPath) return null; + return { shell, configPath }; +}; + +export const extractOsc7SetupTerminalData = (stdout: string): string => { + const escape = String.fromCharCode(0x1b); + const bell = String.fromCharCode(0x07); + const prefix = `${escape}]7;`; + let offset = 0; + let output = ""; + + while (offset < stdout.length) { + const start = stdout.indexOf(prefix, offset); + if (start < 0) break; + const bodyStart = start + prefix.length; + const bellEnd = stdout.indexOf(bell, bodyStart); + const stEnd = stdout.indexOf(`${escape}\\`, bodyStart); + const hasBellEnd = bellEnd >= 0; + const hasStEnd = stEnd >= 0; + if (!hasBellEnd && !hasStEnd) break; + + const useBell = hasBellEnd && (!hasStEnd || bellEnd < stEnd); + const end = useBell ? bellEnd : stEnd; + const terminatorLength = useBell ? 1 : 2; + output += stdout.slice(start, end + terminatorLength); + offset = end + terminatorLength; + } + + return output; +}; + +export const buildOsc7ReloadCommand = (metadata: Osc7SetupMetadata | null): string | null => { + if (!metadata) return null; + const sourceCommand = `source ${quoteForSingleQuotedShellString(metadata.configPath)} >/dev/null 2>&1`; + const emitCommand = metadata.shell === "fish" ? "__netcatty_osc7_cwd" : "osc7_cwd"; + return ` ${sourceCommand}; ${emitCommand} 2>/dev/null; true\r`; +}; + +export const runOsc7SetupAction = async ({ + status, + sessionId, + setupCommand, + setupOsc7Tracking, + writeToSession, + writeLocalTerminalData, +}: RunOsc7SetupActionOptions): Promise => { + if (status !== "connected") { + return { success: false, error: "Terminal is not connected" }; + } + if (!setupOsc7Tracking) { + return { success: false, error: "Directory tracking setup is unavailable" }; + } + + const result = await setupOsc7Tracking(sessionId, setupCommand); + if (!result.success || (typeof result.code === "number" && result.code !== 0)) { + return { + ...result, + success: false, + error: result.error || result.stderr?.trim() || "Directory tracking setup failed", + }; + } + + const metadata = parseOsc7SetupMetadata(result.stdout || ""); + const reloadCommand = buildOsc7ReloadCommand(metadata); + if (!reloadCommand) { + return { + ...result, + success: false, + error: "Directory tracking setup did not return reload metadata", + }; + } + + const terminalData = extractOsc7SetupTerminalData(result.stdout || ""); + if (terminalData) { + writeLocalTerminalData?.(terminalData); + } + writeToSession(sessionId, reloadCommand, { + automated: true, + logRewrite: { sentCommand: reloadCommand, displayCommand: "" }, + }); + + return { ...result, success: true, reloadCommand }; +}; diff --git a/electron/bridges/systemManagerBridge.cjs b/electron/bridges/systemManagerBridge.cjs index 03fb85e40..5d3fd0cac 100644 --- a/electron/bridges/systemManagerBridge.cjs +++ b/electron/bridges/systemManagerBridge.cjs @@ -210,6 +210,34 @@ function createSystemManagerBridge(deps) { return { success: true, code: result.code }; } + async function setupOsc7Tracking(event, payload) { + const sessionId = payload?.sessionId; + const command = payload?.command; + if (!sessionId || typeof command !== "string" || !command.trim()) { + return { success: false, error: "Missing sessionId or command" }; + } + + const result = await execOnSession(event, sessionId, command, 10000); + if (result.pending) return { success: false, pending: true, error: result.error }; + if (!result.success) return { success: false, error: result.error || "Directory tracking setup failed" }; + if (typeof result.code === "number" && result.code !== 0) { + const error = String(result.stderr || result.error || `Directory tracking setup failed with exit code ${result.code}`).trim(); + return { + success: false, + stdout: result.stdout || "", + stderr: result.stderr || "", + code: result.code, + error, + }; + } + return { + success: true, + stdout: result.stdout || "", + stderr: result.stderr || "", + code: result.code ?? 0, + }; + } + async function listTmuxSessions(event, payload) { const sessionId = typeof payload === "string" ? payload : payload?.sessionId; if (!sessionId) return { success: false, error: "Missing sessionId" }; @@ -287,6 +315,7 @@ function createSystemManagerBridge(deps) { ipcMain.handle("netcatty:system:probeCapabilities", probeCapabilities); ipcMain.handle("netcatty:system:listProcesses", listProcesses); ipcMain.handle("netcatty:system:signalProcess", signalProcess); + ipcMain.handle("netcatty:system:setupOsc7Tracking", setupOsc7Tracking); ipcMain.handle("netcatty:system:listTmuxSessions", listTmuxSessions); ipcMain.handle("netcatty:system:createTmuxSession", createTmuxSession); ipcMain.handle("netcatty:system:listTmuxWindows", listTmuxWindows); @@ -302,7 +331,7 @@ function createSystemManagerBridge(deps) { ipcMain.handle("netcatty:system:dockerImageAction", dockerImageAction); } - return { registerHandlers, probeCapabilities, listProcesses }; + return { registerHandlers, probeCapabilities, listProcesses, setupOsc7Tracking }; } module.exports = { createSystemManagerBridge }; diff --git a/electron/bridges/systemManagerBridge.processes.test.cjs b/electron/bridges/systemManagerBridge.processes.test.cjs index 82e6c6398..71730b49d 100644 --- a/electron/bridges/systemManagerBridge.processes.test.cjs +++ b/electron/bridges/systemManagerBridge.processes.test.cjs @@ -5,12 +5,13 @@ const assert = require("node:assert/strict"); const { EventEmitter } = require("node:events"); const { createSystemManagerBridge } = require("./systemManagerBridge.cjs"); -function createFakeExecStream(stdout) { +function createFakeExecStream(stdout, options = {}) { const stream = new EventEmitter(); stream.stderr = new EventEmitter(); process.nextTick(() => { - stream.emit("data", stdout); - stream.emit("close", 0); + if (stdout) stream.emit("data", stdout); + if (options.stderr) stream.stderr.emit("data", options.stderr); + stream.emit("close", options.code ?? 0); }); return stream; } @@ -67,3 +68,49 @@ test("probeCapabilities reports Docker when docker is installed even if plain do assert.equal(result.success, true); assert.equal(result.capabilities.hasDocker, true); }); + +test("setupOsc7Tracking runs the setup command through the active session executor", async () => { + let seenCommand = ""; + const conn = { + exec(command, callback) { + seenCommand = command; + callback(null, createFakeExecStream("__NETCATTY_OSC7_SETUP_SHELL__=bash\n")); + }, + }; + const sessions = new Map([["s1", { conn, type: "ssh" }]]); + const bridge = createSystemManagerBridge({ + getSessions: () => sessions, + process, + }); + + const result = await bridge.setupOsc7Tracking(null, { + sessionId: "s1", + command: "printf setup-script", + }); + + assert.equal(result.success, true); + assert.equal(result.stdout, "__NETCATTY_OSC7_SETUP_SHELL__=bash\n"); + assert.equal(seenCommand, "printf setup-script"); +}); + +test("setupOsc7Tracking reports non-zero setup exits as failures", async () => { + const conn = { + exec(_command, callback) { + callback(null, createFakeExecStream("", { code: 2, stderr: "unsupported shell\n" })); + }, + }; + const sessions = new Map([["s1", { conn, type: "ssh" }]]); + const bridge = createSystemManagerBridge({ + getSessions: () => sessions, + process, + }); + + const result = await bridge.setupOsc7Tracking(null, { + sessionId: "s1", + command: "printf setup-script", + }); + + assert.equal(result.success, false); + assert.equal(result.code, 2); + assert.match(result.error, /unsupported shell/); +}); diff --git a/electron/preload/api.cjs b/electron/preload/api.cjs index d3c02cacf..d1a3532ef 100644 --- a/electron/preload/api.cjs +++ b/electron/preload/api.cjs @@ -99,6 +99,9 @@ function createPreloadApi(ctx) { signalSystemProcess: async (options) => { return ipcRenderer.invoke("netcatty:system:signalProcess", options); }, + setupOsc7Tracking: async (sessionId, command) => { + return ipcRenderer.invoke("netcatty:system:setupOsc7Tracking", { sessionId, command }); + }, listTmuxSessions: async (sessionId) => { return ipcRenderer.invoke("netcatty:system:listTmuxSessions", { sessionId }); }, diff --git a/package-lock.json b/package-lock.json index 0348616f4..bfd0e599d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -330,6 +330,29 @@ "win32" ] }, + "node_modules/@anthropic-ai/sdk": { + "version": "0.106.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.106.0.tgz", + "integrity": "sha512-ufwVvYNDBj2dzOGupBCTaNzBLxqcTnGOzI4z8Wouxlt+mT3J3HuOmatgCy1VmwCHOUueqZ41ERhm0O99OUcbWA==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "json-schema-to-ts": "^3.1.1", + "standardwebhooks": "^1.0.0" + }, + "bin": { + "anthropic-ai-sdk": "bin/cli" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } + } + }, "node_modules/@aws-crypto/crc32": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/@aws-crypto/crc32/-/crc32-5.2.0.tgz", @@ -1259,7 +1282,6 @@ "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", @@ -1540,6 +1562,14 @@ "node": ">=6.9.0" } }, + "node_modules/@bufbuild/protobuf": { + "version": "1.10.1", + "resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-1.10.1.tgz", + "integrity": "sha512-wJ8ReQbHxsAfXhrf9ixl0aYbZorRuOWpBNzm8pL8ftmSxQx/wnJD5Eg861NwJU/czy2VXFIebCeZnZrI9rktIQ==", + "license": "(Apache-2.0 AND BSD-3-Clause)", + "optional": true, + "peer": true + }, "node_modules/@buttercup/fetch": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/@buttercup/fetch/-/fetch-0.2.1.tgz", @@ -1858,7 +1888,6 @@ "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.3.tgz", "integrity": "sha512-QwCZW6Tt1siP37Jet9Tb02Zs81TQt6qQrZR2H+eGMcFsL1zMrk2/b9CLC7/9ieP1fjIUMgviLWMmgiHoJrj+ZA==", "license": "MIT", - "peer": true, "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.23.0", @@ -1948,7 +1977,6 @@ "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.6.0.tgz", "integrity": "sha512-4nbvra5R5EtiCzr9BTHiTLc+MLXK2QGiAVYMyi8PkQd3SR+6ixar/Q/01Fa21TBIDOZXgeWV4WppsQolSreAPQ==", "license": "MIT", - "peer": true, "dependencies": { "@marijn/find-cluster-break": "^1.0.0" } @@ -1958,7 +1986,6 @@ "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.1.tgz", "integrity": "sha512-+BIjw/AG3tDQ4pJgTLPYdAW25eDE66YsvM4LKyVPgGzVgZ4a9Wj1SRX8kPVKgBDdPt8oHtZ15F0qx7p0oOHdHw==", "license": "MIT", - "peer": true, "dependencies": { "@codemirror/state": "^6.6.0", "crelt": "^1.0.6", @@ -1966,6 +1993,16 @@ "w3c-keyname": "^2.2.4" } }, + "node_modules/@connectrpc/connect": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@connectrpc/connect/-/connect-1.7.0.tgz", + "integrity": "sha512-iNKdJRi69YP3mq6AePRT8F/HrxWCewrhxnLMNm0vpqXAR8biwzRtO6Hjx80C6UvtKJ5sFmffQT7I4Baecz389w==", + "license": "Apache-2.0", + "optional": true, + "peerDependencies": { + "@bufbuild/protobuf": "^1.10.0" + } + }, "node_modules/@connectrpc/connect-node": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/@connectrpc/connect-node/-/connect-node-1.7.0.tgz", @@ -2413,6 +2450,7 @@ "dev": true, "license": "BSD-2-Clause", "optional": true, + "peer": true, "dependencies": { "cross-dirname": "^0.1.0", "debug": "^4.3.4", @@ -2434,6 +2472,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", @@ -3843,7 +3882,6 @@ "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz", "integrity": "sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==", "license": "MIT", - "peer": true, "dependencies": { "@lezer/common": "^1.3.0" } @@ -4126,7 +4164,6 @@ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz", "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==", "license": "MIT", - "peer": true, "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", @@ -7540,7 +7577,8 @@ "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz", "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==", "license": "MIT", - "optional": true + "optional": true, + "peer": true }, "node_modules/@standard-schema/spec": { "version": "1.1.0", @@ -8150,7 +8188,6 @@ "integrity": "sha512-hAAP5io/7csFStuOmR782YmTthKBJ9ND3WVL60hcOjvtGFb+HJxH4O5huAcmcZ9v9G8P+JETiZ/G1B8MALnWZQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.54.0", @@ -8180,7 +8217,6 @@ "integrity": "sha512-BtE0k6cjwjLZoZixN0t5AKP0kSzlGu7FctRXYuPAm//aaiZhmfq1JwdYpYr1brzEspYyFeF+8XF5j2VK6oalrA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.54.0", "@typescript-eslint/types": "8.54.0", @@ -8540,7 +8576,6 @@ "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.1.0-beta.220.tgz", "integrity": "sha512-rwEKE75wfwfNWeGnjl0iQRA1W50HigKoGcGMeF3o5CqDSdI9IjmwzpV9xHXqLH6CYj6s9N1g6bbKFVDou9dJ/A==", "license": "MIT", - "peer": true, "workspaces": [ "addons/*" ] @@ -8605,7 +8640,6 @@ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -9306,7 +9340,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", @@ -10132,7 +10165,8 @@ "integrity": "sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q==", "dev": true, "license": "MIT", - "optional": true + "optional": true, + "peer": true }, "node_modules/cross-env": { "version": "10.1.0", @@ -10429,7 +10463,6 @@ "integrity": "sha512-fMkjRqKyPtsz4Kzu/qGP0BGjqzMCIgp+/7kw/u6YH6lvn/8hvL3c0TXhoFayBoYdpPCnEinnCHztd4bW7/jetA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "app-builder-lib": "26.15.2", "builder-util": "26.15.0", @@ -10711,6 +10744,7 @@ "dev": true, "hasInstallScript": true, "license": "MIT", + "peer": true, "dependencies": { "@electron/asar": "^3.2.1", "debug": "^4.1.1", @@ -10731,6 +10765,7 @@ "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "graceful-fs": "^4.1.2", "jsonfile": "^4.0.0", @@ -10746,6 +10781,7 @@ "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", "dev": true, "license": "MIT", + "peer": true, "optionalDependencies": { "graceful-fs": "^4.1.6" } @@ -10756,6 +10792,7 @@ "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">= 4.0.0" } @@ -10980,7 +11017,6 @@ "integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.1", @@ -11434,7 +11470,8 @@ "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz", "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==", "license": "Unlicense", - "optional": true + "optional": true, + "peer": true }, "node_modules/fast-uri": { "version": "3.1.0", @@ -12371,7 +12408,6 @@ "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.14.tgz", "integrity": "sha512-am5zfg3yu6sqn5yjKBNqhnTX7Cv+m00ox+7jbaKkrLMRJ4rAdldd1xPd/JzbBWspqaQv6RSTrgFN95EsfhC+7w==", "license": "MIT", - "peer": true, "engines": { "node": ">=16.9.0" } @@ -12828,6 +12864,7 @@ "resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz", "integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==", "license": "MIT", + "peer": true, "funding": { "type": "GitHub Sponsors ❤", "url": "https://github.com/sponsors/dmonad" @@ -12949,6 +12986,7 @@ "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", "license": "MIT", "optional": true, + "peer": true, "dependencies": { "@babel/runtime": "^7.18.3", "ts-algebra": "^2.0.0" @@ -13106,6 +13144,7 @@ "resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.117.tgz", "integrity": "sha512-DeXj9X5xDCjgKLU/7RR+/HQEVzuuEUiwldwOGsHK/sfAfELGWEyTcf0x+uOvCvK3O2zPmZePXWL85vtia6GyZw==", "license": "MIT", + "peer": true, "dependencies": { "isomorphic.js": "^0.2.4" }, @@ -14051,7 +14090,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", @@ -15172,6 +15210,7 @@ "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "minimist": "^1.2.6" }, @@ -15191,7 +15230,6 @@ "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.55.1.tgz", "integrity": "sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A==", "license": "MIT", - "peer": true, "dependencies": { "dompurify": "3.2.7", "marked": "14.0.0" @@ -15942,6 +15980,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "commander": "^9.4.0" }, @@ -15959,6 +15998,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": "^12.20.0 || >=14" } @@ -16263,7 +16303,6 @@ "resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz", "integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==", "license": "MIT", - "peer": true, "engines": { "node": ">=0.10.0" } @@ -16273,7 +16312,6 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz", "integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==", "license": "MIT", - "peer": true, "dependencies": { "scheduler": "^0.27.0" }, @@ -17611,6 +17649,7 @@ "integrity": "sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==", "license": "MIT", "optional": true, + "peer": true, "dependencies": { "@stablelib/base64": "^1.0.0", "fast-sha256": "^1.3.0" @@ -17916,6 +17955,7 @@ "integrity": "sha512-yYrrsWnrXMcdsnu/7YMYAofM1ktpL5By7vZhf15CrXijWWrEYZks5AXBudalfSWJLlnen/QUJUB5aoB0kqZUGA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "mkdirp": "^0.5.1", "rimraf": "~2.6.2" @@ -17942,6 +17982,7 @@ "deprecated": "Rimraf versions prior to v4 are no longer supported", "dev": true, "license": "ISC", + "peer": true, "dependencies": { "glob": "^7.1.3" }, @@ -18016,7 +18057,6 @@ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -18111,7 +18151,8 @@ "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", "license": "MIT", - "optional": true + "optional": true, + "peer": true }, "node_modules/ts-api-utils": { "version": "2.4.0", @@ -18138,7 +18179,6 @@ "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "esbuild": "~0.27.0", "get-tsconfig": "^4.7.5" @@ -18250,7 +18290,6 @@ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -18291,7 +18330,6 @@ "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz", "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==", "license": "MIT", - "peer": true, "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", @@ -18667,7 +18705,6 @@ "integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", @@ -18761,7 +18798,6 @@ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -19049,7 +19085,6 @@ "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", "license": "MIT", - "peer": true, "funding": { "url": "https://github.com/sponsors/colinhacks" } diff --git a/types/global/netcatty-bridge-system.d.ts b/types/global/netcatty-bridge-system.d.ts index b91ef2df0..0d5d2917d 100644 --- a/types/global/netcatty-bridge-system.d.ts +++ b/types/global/netcatty-bridge-system.d.ts @@ -19,6 +19,14 @@ declare global { signal?: string; nice?: number; }): Promise<{ success: boolean; error?: string; code?: number }>; + setupOsc7Tracking?(sessionId: string, command: string): Promise<{ + success: boolean; + pending?: boolean; + stdout?: string; + stderr?: string; + code?: number | null; + error?: string; + }>; listTmuxSessions?(sessionId: string): Promise<{ success: boolean; error?: string; From fd3de5c6c1884c6c5619fd82268f3b1e834dfcab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 16:37:08 +0800 Subject: [PATCH 087/228] [codex] Lazy load OpenCode model catalogs Lazy load OpenCode model catalogs for OpenCode. --- application/state/useAgentDiscovery.ts | 13 +- components/AIChatSidePanel.tsx | 210 +++++++++++++++++---- components/AIChatSidePanelHelpers.test.tsx | 114 +++++++++++ components/AIChatSidePanelHelpers.ts | 96 ++++++++++ components/settings/tabs/SettingsAITab.tsx | 1 - components/settings/tabs/ai/types.ts | 1 + 6 files changed, 392 insertions(+), 43 deletions(-) diff --git a/application/state/useAgentDiscovery.ts b/application/state/useAgentDiscovery.ts index f924c025f..aa15585d7 100644 --- a/application/state/useAgentDiscovery.ts +++ b/application/state/useAgentDiscovery.ts @@ -148,7 +148,7 @@ export function useAgentDiscovery( ); if (!match) return ea; - // Check if args, SDK backend, or Claude's resolved system path differ + // Check if args, SDK backend, or managed SDK path env differ. const currentArgs = JSON.stringify(ea.args || []); const newArgs = JSON.stringify(match.args); const backend = match.sdkBackend ?? match.command; @@ -158,9 +158,12 @@ export function useAgentDiscovery( const matchPath = match.binPath || match.path; const env = match.command === 'claude' ? { ...(ea.env ?? {}), CLAUDE_CODE_EXECUTABLE: matchPath } - : ea.env; - const envChanged = match.command === 'claude' - && ea.env?.CLAUDE_CODE_EXECUTABLE !== matchPath; + : match.command === 'opencode' + ? { ...(ea.env ?? {}), OPENCODE_BIN: matchPath } + : ea.env; + const envChanged = + (match.command === 'claude' && ea.env?.CLAUDE_CODE_EXECUTABLE !== matchPath) + || (match.command === 'opencode' && ea.env?.OPENCODE_BIN !== matchPath); if (currentArgs !== newArgs || backendChanged || envChanged) { changed = true; const { acpCommand: _legacyCommand, acpArgs: _legacyArgs, ...rest } = ea; @@ -193,6 +196,8 @@ export function useAgentDiscovery( sdkBackend: backend, ...(agent.command === 'claude' ? { env: { CLAUDE_CODE_EXECUTABLE: agent.binPath || agent.path || '' } } + : agent.command === 'opencode' + ? { env: { OPENCODE_BIN: agent.binPath || agent.path || '' } } : {}), }; }, diff --git a/components/AIChatSidePanel.tsx b/components/AIChatSidePanel.tsx index 1a881a8ef..6d6db9003 100644 --- a/components/AIChatSidePanel.tsx +++ b/components/AIChatSidePanel.tsx @@ -10,6 +10,7 @@ import type { AgentModelPreset, AISessionScope, DiscoveredAgent, + ExternalAgentConfig, } from '../infrastructure/ai/types'; import type { ExecutorContext } from '../infrastructure/ai/cattyAgent/executor'; import { getAgentModelPresets } from '../infrastructure/ai/types'; @@ -54,11 +55,14 @@ import { useAIPermissionGrantsState } from '../application/state/useAIPermission import { useConversationExport } from './ai/hooks/useConversationExport'; import type { AIChatSidePanelProps } from './AIChatSidePanel.types'; import { + buildSdkRuntimeModelCacheKey, + sdkRuntimeModelCache, generateId, normalizeSdkRuntimeModelPresets, shouldAdoptSdkCurrentModel, shouldLoadSdkRuntimeModels, shouldUseStoredAgentModel, + type SdkRuntimeModelCatalog, } from './AIChatSidePanelHelpers'; import { AIChatPanelContent } from './AIChatPanelContent'; import { @@ -74,6 +78,13 @@ type UserSkillsStatusResult = { ok: boolean; skills?: Array<{ status: 'ready' | 'warning'; }> } | null; type UserSkillsStatusLoadResult = UserSkillsStatusResult | undefined; +type SdkRuntimeModelTarget = { + agentId: string; + cacheKey: string; + sdkBackend: string; + agentEnv?: Record; + agentCommand?: string; +}; const USER_SKILLS_STATUS_CACHE_TTL_MS = 60_000; let userSkillsStatusCache: { @@ -654,55 +665,178 @@ const AIChatSidePanelActive: React.FC = ({ const agentModelMapRef = useRef(agentModelMap); agentModelMapRef.current = agentModelMap; - useEffect(() => { - if (!isVisible) return; - const sdkBackend = getExternalAgentSdkBackend(currentAgentConfig); - if (!sdkBackend) return; - if (!shouldLoadSdkRuntimeModels(currentAgentConfig) && !isCodexManagedAgent) return; - - const bridge = getNetcattyBridge(); - if (!bridge?.aiSdkAgentListModels) return; - - let cancelled = false; - void bridge.aiSdkAgentListModels( + const buildExternalAgentRuntimeModelTarget = useCallback((agent: ExternalAgentConfig | undefined): SdkRuntimeModelTarget | null => { + if (!agent) return null; + const sdkBackend = getExternalAgentSdkBackend(agent); + if (!sdkBackend) return null; + return { + agentId: agent.id, + cacheKey: buildSdkRuntimeModelCacheKey(agent), sdkBackend, - undefined, - undefined, - `models_${currentAgentId}`, - currentAgentConfig.env, - getManualAgentCommand(currentAgentConfig), - ).then((result) => { - if (cancelled || !result?.ok || !Array.isArray(result.models)) return; - const runtimePresets = normalizeSdkRuntimeModelPresets(result.models, result.currentModelId); - const storedModelId = agentModelMapRef.current[currentAgentId]; - if (runtimePresets.length === 0) { - setRuntimeAgentModelPresets((prev) => { - if (!(currentAgentId in prev)) return prev; - const { [currentAgentId]: _removed, ...rest } = prev; - return rest; - }); - if (shouldAdoptSdkCurrentModel(result.currentModelId, storedModelId, runtimePresets)) { - setAgentModel(currentAgentId, result.currentModelId!); - } - return; - } + agentEnv: agent.env, + agentCommand: getManualAgentCommand(agent), + }; + }, []); + + const buildDiscoveredAgentRuntimeModelTarget = useCallback((agent: DiscoveredAgent): SdkRuntimeModelTarget | null => { + const sdkBackend = agent.sdkBackend ?? agent.command; + if (sdkBackend !== 'opencode') return null; + const command = agent.binPath || agent.path || agent.command; + const agentId = `discovered_${agent.command}`; + return { + agentId, + cacheKey: buildSdkRuntimeModelCacheKey({ + id: agentId, + command, + sdkBackend, + env: command ? { OPENCODE_BIN: command } : undefined, + }), + sdkBackend, + agentCommand: command, + }; + }, []); + + const applySdkRuntimeModelCatalog = useCallback(( + agentId: string, + catalog: SdkRuntimeModelCatalog, + options: { adoptCurrentModel?: boolean } = {}, + ) => { + const runtimePresets = normalizeSdkRuntimeModelPresets(catalog.models, catalog.currentModelId); + const storedModelId = agentModelMapRef.current[agentId]; + if (runtimePresets.length === 0) { + setRuntimeAgentModelPresets((prev) => { + if (!(agentId in prev)) return prev; + const { [agentId]: _removed, ...rest } = prev; + return rest; + }); + } else { setRuntimeAgentModelPresets((prev) => ({ ...prev, - [currentAgentId]: runtimePresets, + [agentId]: runtimePresets, })); - if (shouldAdoptSdkCurrentModel(result.currentModelId, storedModelId, runtimePresets)) { - setAgentModel(currentAgentId, result.currentModelId); - } - }).catch((err) => { - if (!cancelled) { + } + + if ( + options.adoptCurrentModel + && catalog.currentModelId + && shouldAdoptSdkCurrentModel(catalog.currentModelId, storedModelId, runtimePresets) + ) { + setAgentModel(agentId, catalog.currentModelId); + } + }, [setAgentModel]); + + const loadSdkRuntimeModelCatalog = useCallback(( + target: SdkRuntimeModelTarget, + options: { force?: boolean; logErrors?: boolean } = {}, + ): Promise => { + const bridge = getNetcattyBridge(); + if (!bridge?.aiSdkAgentListModels) return Promise.resolve(null); + + return sdkRuntimeModelCache.refresh( + target.cacheKey, + async () => { + const result = await bridge.aiSdkAgentListModels!( + target.sdkBackend, + undefined, + undefined, + `models_${target.agentId}`, + target.agentEnv, + target.agentCommand, + ); + if (!result?.ok || !Array.isArray(result.models)) { + throw new Error(result?.error || 'Failed to load SDK agent models'); + } + return { + currentModelId: result.currentModelId ?? null, + models: result.models, + }; + }, + { force: options.force }, + ).catch((err) => { + if (options.logErrors !== false) { console.warn('[AIChatSidePanel] Failed to load SDK agent models:', err); } + return null; + }); + }, []); + + useEffect(() => { + if (!isVisible) return; + if (!currentAgentConfig) return; + if (!shouldLoadSdkRuntimeModels(currentAgentConfig) && !isCodexManagedAgent) return; + + const target = buildExternalAgentRuntimeModelTarget(currentAgentConfig); + if (!target) return; + + const cached = sdkRuntimeModelCache.read(target.cacheKey); + if (cached) { + applySdkRuntimeModelCatalog(target.agentId, cached); + } + + let cancelled = false; + void loadSdkRuntimeModelCatalog(target, { + force: target.sdkBackend === 'opencode', + }).then((catalog) => { + if (cancelled || !catalog) return; + applySdkRuntimeModelCatalog(target.agentId, catalog, { adoptCurrentModel: true }); }); return () => { cancelled = true; }; - }, [isVisible, currentAgentConfig, currentAgentId, isCodexManagedAgent, setAgentModel]); + }, [ + isVisible, + currentAgentConfig, + isCodexManagedAgent, + buildExternalAgentRuntimeModelTarget, + loadSdkRuntimeModelCatalog, + applySdkRuntimeModelCatalog, + ]); + + useEffect(() => { + if (!isVisible) return; + const targets = new Map(); + const configuredTargetCacheKeys = new Set(); + + for (const agent of externalAgents) { + if (!agent.enabled || getExternalAgentSdkBackend(agent) !== 'opencode') continue; + const target = buildExternalAgentRuntimeModelTarget(agent); + if (target) { + targets.set(target.cacheKey, target); + configuredTargetCacheKeys.add(target.cacheKey); + } + } + + for (const agent of discoveredAgents) { + const target = buildDiscoveredAgentRuntimeModelTarget(agent); + if (target) targets.set(target.cacheKey, target); + } + + if (targets.size === 0) return; + + let cancelled = false; + for (const target of targets.values()) { + void loadSdkRuntimeModelCatalog(target, { logErrors: false }) + .then((catalog) => { + if (cancelled || !catalog) return; + if (configuredTargetCacheKeys.has(target.cacheKey)) { + applySdkRuntimeModelCatalog(target.agentId, catalog); + } + }); + } + + return () => { + cancelled = true; + }; + }, [ + isVisible, + externalAgents, + discoveredAgents, + buildExternalAgentRuntimeModelTarget, + buildDiscoveredAgentRuntimeModelTarget, + loadSdkRuntimeModelCatalog, + applySdkRuntimeModelCatalog, + ]); const hasCodexCustomConfig = codexCustomConfigResolved && isCodexManagedAgent; diff --git a/components/AIChatSidePanelHelpers.test.tsx b/components/AIChatSidePanelHelpers.test.tsx index 0bc2d5b68..5320ed3ff 100644 --- a/components/AIChatSidePanelHelpers.test.tsx +++ b/components/AIChatSidePanelHelpers.test.tsx @@ -2,6 +2,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { + createSdkRuntimeModelCache, modelPresetsContainId, normalizeSdkRuntimeModelPresets, shouldAdoptSdkCurrentModel, @@ -85,3 +86,116 @@ test('shouldUseStoredAgentModel trusts SDK defaults when no runtime list is retu false, ); }); + +test('SDK runtime model cache coalesces concurrent refreshes', async () => { + const cache = createSdkRuntimeModelCache(); + let calls = 0; + let resolveLoad!: (value: { currentModelId: string | null; models: AgentModelPreset[] }) => void; + const load = () => { + calls += 1; + return new Promise<{ currentModelId: string | null; models: AgentModelPreset[] }>((resolve) => { + resolveLoad = resolve; + }); + }; + + const first = cache.refresh('opencode:/opt/bin/opencode', load); + const second = cache.refresh('opencode:/opt/bin/opencode', load); + + assert.equal(first, second); + assert.equal(calls, 1); + + resolveLoad({ + currentModelId: 'openai/gpt-5.1', + models: [{ id: 'openai/gpt-5.1', name: 'GPT-5.1' }], + }); + assert.deepEqual(await first, { + currentModelId: 'openai/gpt-5.1', + models: [{ id: 'openai/gpt-5.1', name: 'GPT-5.1' }], + }); +}); + +test('SDK runtime model cache serves cached models while background refresh updates them', async () => { + let now = 1_000; + const cache = createSdkRuntimeModelCache({ now: () => now }); + + await cache.refresh('opencode:/opt/bin/opencode', async () => ({ + currentModelId: 'openai/gpt-5.1', + models: [{ id: 'openai/gpt-5.1', name: 'GPT-5.1' }], + })); + + assert.deepEqual(cache.read('opencode:/opt/bin/opencode')?.models, [ + { id: 'openai/gpt-5.1', name: 'GPT-5.1' }, + ]); + + now = 2_000; + const refresh = cache.refresh( + 'opencode:/opt/bin/opencode', + async () => ({ + currentModelId: 'anthropic/claude-sonnet-4-6', + models: [{ id: 'anthropic/claude-sonnet-4-6', name: 'Claude Sonnet 4.6' }], + }), + { force: true }, + ); + + assert.deepEqual(cache.read('opencode:/opt/bin/opencode')?.models, [ + { id: 'openai/gpt-5.1', name: 'GPT-5.1' }, + ]); + + await refresh; + assert.deepEqual(cache.read('opencode:/opt/bin/opencode')?.models, [ + { id: 'anthropic/claude-sonnet-4-6', name: 'Claude Sonnet 4.6' }, + ]); +}); + +test('SDK runtime model cache keeps the previous catalog when a refresh fails', async () => { + const cache = createSdkRuntimeModelCache(); + + await cache.refresh('opencode:/opt/bin/opencode', async () => ({ + currentModelId: 'openai/gpt-5.1', + models: [{ id: 'openai/gpt-5.1', name: 'GPT-5.1' }], + })); + + await assert.rejects( + cache.refresh( + 'opencode:/opt/bin/opencode', + async () => { + throw new Error('OpenCode unavailable'); + }, + { force: true }, + ), + /OpenCode unavailable/, + ); + + assert.deepEqual(cache.read('opencode:/opt/bin/opencode')?.models, [ + { id: 'openai/gpt-5.1', name: 'GPT-5.1' }, + ]); +}); + +test('SDK runtime model cache ignores degraded empty catalogs', async () => { + const cache = createSdkRuntimeModelCache(); + + await cache.refresh('opencode:/opt/bin/opencode', async () => ({ + currentModelId: 'openai/gpt-5.1', + models: [{ id: 'openai/gpt-5.1', name: 'GPT-5.1' }], + })); + + const refreshed = await cache.refresh( + 'opencode:/opt/bin/opencode', + async () => ({ currentModelId: null, models: [] }), + { force: true }, + ); + + assert.deepEqual(refreshed.models, [ + { id: 'openai/gpt-5.1', name: 'GPT-5.1' }, + ]); + assert.deepEqual(cache.read('opencode:/opt/bin/opencode')?.models, [ + { id: 'openai/gpt-5.1', name: 'GPT-5.1' }, + ]); + + const emptyCache = createSdkRuntimeModelCache(); + await emptyCache.refresh('opencode:/usr/bin/opencode', async () => ({ + currentModelId: null, + models: [], + })); + assert.equal(emptyCache.read('opencode:/usr/bin/opencode'), null); +}); diff --git a/components/AIChatSidePanelHelpers.ts b/components/AIChatSidePanelHelpers.ts index 350d8309a..d56caedd5 100644 --- a/components/AIChatSidePanelHelpers.ts +++ b/components/AIChatSidePanelHelpers.ts @@ -1,6 +1,102 @@ import type { AgentModelPreset, ExternalAgentConfig } from '../infrastructure/ai/types'; import { getExternalAgentSdkBackend } from '../infrastructure/ai/managedAgents'; +export type SdkRuntimeModelCatalog = { + currentModelId: string | null; + models: AgentModelPreset[]; +}; + +export type SdkRuntimeModelCacheEntry = SdkRuntimeModelCatalog & { + updatedAt: number; +}; + +type SdkRuntimeModelCacheOptions = { + ttlMs?: number; + now?: () => number; +}; + +type SdkRuntimeModelRefreshOptions = { + force?: boolean; +}; + +const SDK_RUNTIME_MODEL_CACHE_TTL_MS = 5 * 60 * 1000; +const MODEL_CACHE_ENV_HINTS = ['CLAUDE_CODE_EXECUTABLE', 'CODEBUDDY_CODE_PATH', 'OPENCODE_BIN'] as const; + +function cloneCatalog(catalog: SdkRuntimeModelCatalog): SdkRuntimeModelCatalog { + return { + currentModelId: catalog.currentModelId ?? null, + models: [...catalog.models], + }; +} + +function normalizeSdkRuntimeModelCatalog(catalog: SdkRuntimeModelCatalog): SdkRuntimeModelCatalog { + return { + currentModelId: catalog.currentModelId ?? null, + models: Array.isArray(catalog.models) + ? catalog.models.filter((model): model is AgentModelPreset => Boolean(model?.id)) + : [], + }; +} + +export function buildSdkRuntimeModelCacheKey(agent: { + id: string; + command?: string; + sdkBackend?: string; + acpCommand?: string; + env?: Record; +}): string { + const sdkBackend = agent.sdkBackend || agent.acpCommand || ''; + const envHints = MODEL_CACHE_ENV_HINTS.map((key) => `${key}=${agent.env?.[key] ?? ''}`); + return [agent.id, sdkBackend, agent.command ?? '', ...envHints].join('\u0000'); +} + +export function createSdkRuntimeModelCache(options: SdkRuntimeModelCacheOptions = {}) { + const ttlMs = options.ttlMs ?? SDK_RUNTIME_MODEL_CACHE_TTL_MS; + const now = options.now ?? (() => Date.now()); + const entries = new Map(); + const inFlight = new Map>(); + + return { + read(key: string): SdkRuntimeModelCacheEntry | null { + const entry = entries.get(key); + return entry ? { ...cloneCatalog(entry), updatedAt: entry.updatedAt } : null; + }, + refresh( + key: string, + load: () => Promise, + refreshOptions: SdkRuntimeModelRefreshOptions = {}, + ): Promise { + const cached = entries.get(key); + if (!refreshOptions.force && cached && now() - cached.updatedAt < ttlMs) { + return Promise.resolve(cloneCatalog(cached)); + } + + const existing = inFlight.get(key); + if (existing) return existing; + + const promise = Promise.resolve(load()) + .then((catalog) => { + const normalized = normalizeSdkRuntimeModelCatalog(catalog); + if (normalized.models.length === 0 && !normalized.currentModelId) { + return cached ? cloneCatalog(cached) : cloneCatalog(normalized); + } + entries.set(key, { ...cloneCatalog(normalized), updatedAt: now() }); + return cloneCatalog(normalized); + }) + .finally(() => { + if (inFlight.get(key) === promise) { + inFlight.delete(key); + } + }); + + inFlight.set(key, promise); + return promise; + }, + }; +} + +export const sdkRuntimeModelCache = createSdkRuntimeModelCache(); + export function modelPresetMatchesId(preset: AgentModelPreset, modelId: string): boolean { if (preset.thinkingLevels?.length) { return preset.thinkingLevels.some((level) => `${preset.id}/${level}` === modelId); diff --git a/components/settings/tabs/SettingsAITab.tsx b/components/settings/tabs/SettingsAITab.tsx index 708ecc9ea..a9d23c735 100644 --- a/components/settings/tabs/SettingsAITab.tsx +++ b/components/settings/tabs/SettingsAITab.tsx @@ -308,7 +308,6 @@ const SettingsAITab: React.FC = ({ const mountedRef = useRef(true); const agentPathRequestIdRef = useRef>>({}); const codexRequestIdRef = useRef(0); - useEffect(() => () => { mountedRef.current = false; codexRequestIdRef.current += 1; diff --git a/components/settings/tabs/ai/types.ts b/components/settings/tabs/ai/types.ts index c7172d0f7..402aca6cf 100644 --- a/components/settings/tabs/ai/types.ts +++ b/components/settings/tabs/ai/types.ts @@ -112,6 +112,7 @@ export interface NetcattyAiBridge { aiCodexCancelLogin?: (sessionId: string) => Promise<{ ok: boolean; found?: boolean; session?: CodexLoginSession; error?: string }>; aiCodexLogout?: (options?: { codexPath?: string }) => Promise<{ ok: boolean; state?: CodexIntegrationState; isConnected?: boolean; rawOutput?: string; logoutOutput?: string; error?: string }>; aiResolveCli?: (params: { command: string; customPath?: string; refreshShellEnv?: boolean; apiKeyPresent?: boolean }) => Promise; + aiSdkAgentListModels?: (sdkBackend: string, cwd?: string, providerId?: string, chatSessionId?: string, agentEnv?: Record, agentCommand?: string) => Promise<{ ok: boolean; models?: Array<{ id: string; name: string; description?: string; thinkingLevels?: string[] }>; currentModelId?: string | null; error?: string }>; aiUserSkillsGetStatus?: () => Promise; aiUserSkillsOpenFolder?: () => Promise; openExternal?: (url: string) => Promise; From 1c4be78060f314e7e08ca95f03fdb7567449226f Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 16:26:22 +0800 Subject: [PATCH 088/228] fix(autocomplete): clamp popup within terminal viewport --- .../terminalAutocompleteLayout.ts | 23 +++++--- .../terminalAutocompleteLayout.test.ts | 54 +++++++++++++++++-- 2 files changed, 64 insertions(+), 13 deletions(-) diff --git a/components/terminal/autocomplete/terminalAutocompleteLayout.ts b/components/terminal/autocomplete/terminalAutocompleteLayout.ts index 87d5e82c6..1d5583be2 100644 --- a/components/terminal/autocomplete/terminalAutocompleteLayout.ts +++ b/components/terminal/autocomplete/terminalAutocompleteLayout.ts @@ -246,14 +246,21 @@ export function computeAutocompletePopupPlacement( : spaceAbove > spaceBelow; const availableVerticalSpace = renderUpward ? spaceAbove : spaceBelow; - const effectiveMaxHeight = Math.max(0, Math.min(maxHeight, availableVerticalSpace)); + const availableViewportHeight = Math.max(0, bounds.height - viewportPadding * 2); + const effectiveMaxHeight = Math.max( + 0, + Math.min(maxHeight, availableVerticalSpace, availableViewportHeight), + ); const contentHeightForPlacement = Math.min(effectiveMaxHeight, cappedDesiredHeight); - const top = renderUpward + const unclampedTop = renderUpward ? Math.max(bounds.top + viewportPadding, anchorTop - anchorGap - contentHeightForPlacement) : Math.min( anchorBottom + anchorGap, boundsBottom - viewportPadding - contentHeightForPlacement, ); + const minTop = bounds.top + viewportPadding; + const maxTop = Math.max(minTop, boundsBottom - viewportPadding - contentHeightForPlacement); + const top = Math.max(minTop, Math.min(unclampedTop, maxTop)); // Right edge that keeps the clamped assembly inside the bounds. When the // assembly is wider than the available room this goes below the left padding, @@ -319,7 +326,7 @@ export function resolveAutocompleteCursorColumn( return Math.max(fromLine, fromPrompt); } -/** Clamp autocomplete popups to the active terminal pane in split workspaces. +/** Clamp autocomplete popups to the active terminal screen in split workspaces. * * Uses the visible `.xterm-screen` rect as the clamp boundary so the popup * never overflows the *actual* rendered terminal grid. The `.xterm-container` @@ -332,11 +339,11 @@ export function resolveAutocompleteClampViewport(container: HTMLElement | null): const pane = container?.closest('[data-section="terminal-split-pane"]'); const screen = container?.querySelector(".xterm-screen") ?? null; - // Prefer the split-pane bounds when present; otherwise clamp to the rendered - // screen so the popup cannot spill below the last row. If neither is - // available, fall back to the container rect or the full viewport. - const rect = pane?.getBoundingClientRect() - ?? screen?.getBoundingClientRect() + // Clamp to the rendered screen so the popup cannot spill past the visible + // terminal rows. If the screen is not mounted yet, fall back to the split + // pane/container rect or the full viewport. + const rect = screen?.getBoundingClientRect() + ?? pane?.getBoundingClientRect() ?? container?.getBoundingClientRect(); if (rect && rect.width > 0 && rect.height > 0) { return { diff --git a/components/terminal/terminalAutocompleteLayout.test.ts b/components/terminal/terminalAutocompleteLayout.test.ts index b88f6ee53..ce0493d03 100644 --- a/components/terminal/terminalAutocompleteLayout.test.ts +++ b/components/terminal/terminalAutocompleteLayout.test.ts @@ -259,6 +259,50 @@ test("short popup flips upward when the cursor is at the bottom of the screen", "popup should not be clipped above the viewport"); }); +test("clamps a downward popup back inside the terminal when the anchor is above the viewport", () => { + const p = computeAutocompletePopupPlacement({ + ...baseInput, + anchorTop: -60, + anchorBottom: -40, + desiredHeight: 96, + maxHeight: 240, + expandUpwardHint: false, + }); + const contentHeight = Math.min(p.maxHeight, 96); + + assert.equal(p.renderUpward, false); + assert.ok( + p.top >= baseInput.viewportPadding, + `popup top ${p.top} should stay inside the terminal viewport`, + ); + assert.ok( + p.top + contentHeight <= baseInput.viewportHeight - baseInput.viewportPadding + 0.001, + `popup bottom ${p.top + contentHeight} should stay inside the terminal viewport`, + ); +}); + +test("clamps an upward popup back inside the terminal when the anchor is below the viewport", () => { + const p = computeAutocompletePopupPlacement({ + ...baseInput, + anchorTop: 860, + anchorBottom: 880, + desiredHeight: 96, + maxHeight: 240, + expandUpwardHint: true, + }); + const contentHeight = Math.min(p.maxHeight, 96); + + assert.equal(p.renderUpward, true); + assert.ok( + p.top >= baseInput.viewportPadding, + `popup top ${p.top} should stay inside the terminal viewport`, + ); + assert.ok( + p.top + contentHeight <= baseInput.viewportHeight - baseInput.viewportPadding + 0.001, + `popup bottom ${p.top + contentHeight} should stay inside the terminal viewport`, + ); +}); + test("resolveAutocompleteClampViewport clamps to the xterm screen rect", () => { const container = { closest: () => null, @@ -297,7 +341,7 @@ test("resolveAutocompleteClampViewport clamps to the xterm screen rect", () => { assert.equal(clamp.width, 600); }); -test("resolveAutocompleteClampViewport prefers terminal split pane over screen", () => { +test("resolveAutocompleteClampViewport prefers the visible terminal screen over the split pane", () => { const pane = { getAttribute: (name: string) => (name === "data-section" ? "terminal-split-pane" : null), getBoundingClientRect: () => ({ @@ -344,10 +388,10 @@ test("resolveAutocompleteClampViewport prefers terminal split pane over screen", } as unknown as HTMLElement; const clamp = resolveAutocompleteClampViewport(container); - assert.equal(clamp.left, 20, "split pane left should win"); - assert.equal(clamp.top, 30, "split pane top should win"); - assert.equal(clamp.width, 500, "split pane width should win"); - assert.equal(clamp.height, 300, "split pane height should win"); + assert.equal(clamp.left, 25, "screen left should win"); + assert.equal(clamp.top, 35, "screen top should win"); + assert.equal(clamp.width, 490, "screen width should win"); + assert.equal(clamp.height, 280, "screen height should win"); }); test("resolveAutocompleteAnchorInViewport ignores the helper textarea horizontal position", () => { From e64df373a7629730ed4519f0b3fffd0c9bbc0338 Mon Sep 17 00:00:00 2001 From: mam15mon Date: Fri, 26 Jun 2026 16:44:08 +0800 Subject: [PATCH 089/228] Add group device type inheritance (#1708) * Add group device type inheritance * Sync package lock for CI * Persist group device type setting * Fix group device type inheritance controls * Fix device type inheritance with shell transports * Use resolved hosts for AI executor context * Reduce device type inheritance diff scope --------- Co-authored-by: mam15mon --- components/GroupDetailsPanel.tsx | 41 +++++++++++++ components/HostDetailsAdvancedSections.tsx | 17 +++--- .../terminalLayer/useTerminalAiContexts.ts | 4 +- domain/groupConfig.test.ts | 27 +++++++++ domain/groupConfig.ts | 2 +- domain/models/connection.ts | 1 + domain/terminalHostResolution.test.ts | 58 +++++++++++++++++++ domain/terminalHostResolution.ts | 12 +++- 8 files changed, 149 insertions(+), 13 deletions(-) diff --git a/components/GroupDetailsPanel.tsx b/components/GroupDetailsPanel.tsx index b172a87ee..a4a6ad7f0 100644 --- a/components/GroupDetailsPanel.tsx +++ b/components/GroupDetailsPanel.tsx @@ -1,4 +1,5 @@ import { + AlertTriangle, Check, Eye, EyeOff, @@ -6,6 +7,7 @@ import { MoreHorizontal, Palette, Plus, + Router, Settings2, Trash2, } from "lucide-react"; @@ -45,6 +47,7 @@ import { Button } from "./ui/button"; import { Combobox } from "./ui/combobox"; import { Dropdown, DropdownContent, DropdownTrigger } from "./ui/dropdown"; import { Input } from "./ui/input"; +import { Switch } from "./ui/switch"; import { TerminalFontSelect } from "./settings/TerminalFontSelect"; import { useAvailableFonts } from "../application/state/fontStore"; import { toast } from "./ui/toast"; @@ -52,6 +55,14 @@ import { GroupSshSettingsSection } from "./GroupSshSettingsSection"; type SubPanel = "none" | "proxy" | "chain" | "env-vars" | "theme-select"; +const ToggleRow: React.FC<{ label: string; hint?: React.ReactNode; enabled: boolean; onToggle: () => void }> = ({ label, hint, enabled, onToggle }) => { + return ( + + onToggle()} /> + + ); +}; + interface GroupDetailsPanelProps { groupPath: string; config: GroupConfig | undefined; @@ -104,6 +115,7 @@ const GroupDetailsPanel: React.FC = ({ const hasSshFields = (c: Partial) => c.protocol === 'ssh' || c.port !== undefined || !!c.username || !!c.password || !!c.identityFileId || + c.deviceType !== undefined || c.agentForwarding !== undefined || c.authMethod !== undefined || !!c.identityId || !!c.proxyProfileId || !!c.proxyConfig || !!c.hostChain || !!c.startupCommand || c.legacyAlgorithms !== undefined || c.skipEcdsaHostKey !== undefined || c.algorithms !== undefined || c.backspaceBehavior !== undefined || (c.environmentVariables && c.environmentVariables.length > 0) || @@ -164,6 +176,7 @@ const GroupDetailsPanel: React.FC = ({ delete next.identityId; delete next.identityFileId; delete next.identityFilePaths; + delete next.deviceType; delete next.agentForwarding; delete next.startupCommand; delete next.legacyAlgorithms; @@ -342,6 +355,11 @@ const GroupDetailsPanel: React.FC = ({ if (!parentGroup || groupConfigs.length === 0) return false; return !!resolveGroupDefaults(parentGroup, groupConfigs).skipEcdsaHostKey; }, [groupConfigs, parentGroup]); + const inheritedDeviceType = useMemo(() => { + if (!parentGroup || groupConfigs.length === 0) return undefined; + return resolveGroupDefaults(parentGroup, groupConfigs).deviceType; + }, [groupConfigs, parentGroup]); + const effectiveDeviceType = form.deviceType ?? inheritedDeviceType; const effectiveThemeId = form.themeOverride === false ? inheritedThemeId : (form.theme || inheritedThemeId); @@ -387,6 +405,7 @@ const GroupDetailsPanel: React.FC = ({ ...(form.identityId !== undefined && { identityId: form.identityId }), ...(form.identityFileId !== undefined && { identityFileId: form.identityFileId }), ...(form.identityFilePaths !== undefined && { identityFilePaths: form.identityFilePaths }), + ...(form.deviceType !== undefined && { deviceType: form.deviceType }), ...(form.agentForwarding !== undefined && { agentForwarding: form.agentForwarding }), ...(form.startupCommand !== undefined && { startupCommand: form.startupCommand }), ...(form.legacyAlgorithms !== undefined && { legacyAlgorithms: form.legacyAlgorithms }), @@ -594,6 +613,28 @@ const GroupDetailsPanel: React.FC = ({ chainedHosts={chainedHosts} /> + {sshEnabled && (!form.protocol || form.protocol === "ssh") && !form.moshEnabled && !form.etEnabled && ( + } + title={t("hostDetails.section.deviceType")} + > + update("deviceType", effectiveDeviceType === "network" ? "general" : "network")} + /> + {effectiveDeviceType === "network" && ( +
+ +

+ {t("hostDetails.deviceType.warning")} +

+
+ )} +
+ )} + {/* Telnet Section (if enabled) */} {telnetEnabled && ( ( +}) => { + const inheritedDeviceType = effectiveGroupDefaults?.deviceType; + const effectiveDeviceType = form.deviceType ?? inheritedDeviceType; + + return ( <> } @@ -176,7 +180,6 @@ export const HostDetailsAdvancedSections: React.FC update("deviceType", form.deviceType === 'network' ? undefined : 'network')} + enabled={effectiveDeviceType === 'network'} + onToggle={() => update("deviceType", effectiveDeviceType === 'network' ? 'general' : 'network')} /> - {form.deviceType === 'network' && ( + {effectiveDeviceType === 'network' && (

@@ -627,4 +629,5 @@ export const HostDetailsAdvancedSections: React.FC -); + ); +}; diff --git a/components/terminalLayer/useTerminalAiContexts.ts b/components/terminalLayer/useTerminalAiContexts.ts index 908e82bac..7050e7310 100644 --- a/components/terminalLayer/useTerminalAiContexts.ts +++ b/components/terminalLayer/useTerminalAiContexts.ts @@ -111,7 +111,7 @@ export function useTerminalAiContexts({ return { sessions: sessionIds.map((sid) => { const session = latestSessions.find((s) => s.id === sid); - const host = session?.hostId ? latestHosts.find((h) => h.id === session.hostId) : undefined; + const host = session ? sessionHostsMap.get(session.id) : undefined; return buildAITerminalSessionInfo(session, host, localOs, { allHosts: latestHosts, portForwardingRules: portForwardingRulesRef.current, @@ -130,7 +130,7 @@ export function useTerminalAiContexts({ return reader(request); }, }; - }, [hostsRef, portForwardingRulesRef, sessionsRef, terminalContextReadersRef, workspacesRef]); + }, [hostsRef, portForwardingRulesRef, sessionHostsMap, sessionsRef, terminalContextReadersRef, workspacesRef]); return { aiContextsByTabId, diff --git a/domain/groupConfig.test.ts b/domain/groupConfig.test.ts index a19a7c79b..9d81f589f 100644 --- a/domain/groupConfig.test.ts +++ b/domain/groupConfig.test.ts @@ -37,6 +37,33 @@ test("applyGroupDefaults lets a host custom proxy override a group proxy profile assert.deepEqual(result.proxyConfig, customProxy); }); +test("applyGroupDefaults inherits group device type when host does not set one", () => { + const result = applyGroupDefaults(host(), { deviceType: "network" }); + + assert.equal(result.deviceType, "network"); +}); + +test("applyGroupDefaults lets host device type override group device type", () => { + const result = applyGroupDefaults(host({ deviceType: "general" }), { deviceType: "network" }); + + assert.equal(result.deviceType, "general"); +}); + +test("resolveGroupDefaults lets child group device type override parent device type", () => { + const resolved = resolveGroupDefaults("prod/access", [ + { + path: "prod", + deviceType: "network", + }, + { + path: "prod/access", + deviceType: "general", + }, + ]); + + assert.equal(resolved.deviceType, "general"); +}); + test("resolveGroupDefaults treats saved and custom proxies as one inherited setting", () => { const resolved = resolveGroupDefaults("prod/api", [ { diff --git a/domain/groupConfig.ts b/domain/groupConfig.ts index 1af2fc960..cfc45e7fb 100644 --- a/domain/groupConfig.ts +++ b/domain/groupConfig.ts @@ -86,7 +86,7 @@ export function resolveGroupDefaults( const INHERITABLE_KEYS: (keyof GroupConfig)[] = [ 'username', 'password', 'savePassword', 'authMethod', 'identityId', 'identityFileId', 'identityFilePaths', - 'port', 'protocol', 'agentForwarding', 'proxyProfileId', 'proxyConfig', 'hostChain', 'startupCommand', + 'port', 'protocol', 'deviceType', 'agentForwarding', 'proxyProfileId', 'proxyConfig', 'hostChain', 'startupCommand', 'legacyAlgorithms', 'skipEcdsaHostKey', 'algorithms', 'environmentVariables', 'charset', 'moshEnabled', 'moshServerPath', 'etEnabled', 'etPort', diff --git a/domain/models/connection.ts b/domain/models/connection.ts index 7fd578af9..bedc53efa 100644 --- a/domain/models/connection.ts +++ b/domain/models/connection.ts @@ -325,6 +325,7 @@ export interface GroupConfig { identityFilePaths?: string[]; port?: number; protocol?: 'ssh' | 'telnet'; + deviceType?: 'general' | 'network'; agentForwarding?: boolean; proxyProfileId?: string; proxyConfig?: ProxyConfig; diff --git a/domain/terminalHostResolution.test.ts b/domain/terminalHostResolution.test.ts index d3f743c2c..5b3480cbc 100644 --- a/domain/terminalHostResolution.test.ts +++ b/domain/terminalHostResolution.test.ts @@ -120,6 +120,64 @@ test("resolveTerminalSessionHost keeps explicit missing local sessions local", ( assert.equal(resolved.os, "macos"); }); +test("resolveTerminalSessionHost suppresses inherited network device mode for Mosh sessions", () => { + const host: Host = { + id: "target", + label: "Target", + hostname: "target.example.test", + username: "alice", + port: 22, + protocol: "ssh", + tags: [], + os: "linux", + group: "prod/web", + }; + const groupConfigs: GroupConfig[] = [ + { path: "prod", deviceType: "network" }, + { path: "prod/web", moshEnabled: true }, + ]; + + const resolved = resolveTerminalSessionHost({ + session: baseSession, + hosts: [host], + groupConfigs, + proxyProfiles, + localOs: "linux", + }); + + assert.equal(resolved.moshEnabled, true); + assert.equal(resolved.deviceType, undefined); +}); + +test("resolveTerminalSessionHost suppresses explicit network device mode for ET session overrides", () => { + const host: Host = { + id: "target", + label: "Target", + hostname: "target.example.test", + username: "alice", + port: 22, + protocol: "ssh", + tags: [], + os: "linux", + deviceType: "network", + }; + + const resolved = resolveTerminalSessionHost({ + session: { + ...baseSession, + etEnabled: true, + }, + hosts: [host], + groupConfigs: [], + proxyProfiles, + localOs: "linux", + }); + + assert.equal(resolved.etEnabled, true); + assert.equal(resolved.deviceType, undefined); + assert.equal(host.deviceType, "network"); +}); + test("resolveTerminalChainHosts materializes proxy profiles on jump hosts", () => { const target: Host = { id: "target", diff --git a/domain/terminalHostResolution.ts b/domain/terminalHostResolution.ts index a572ab142..8f03f15cc 100644 --- a/domain/terminalHostResolution.ts +++ b/domain/terminalHostResolution.ts @@ -42,6 +42,12 @@ export function resolveEffectiveTerminalHost({ ); } +const suppressDeviceTypeForShellTransport = (host: Host): Host => { + if (!host.moshEnabled && !host.etEnabled) return host; + if (host.deviceType === undefined) return host; + return { ...host, deviceType: undefined }; +}; + function buildFallbackHostFromSession( session: TerminalSession, localOs: LocalOs, @@ -95,16 +101,16 @@ export function resolveTerminalSessionHost({ moshEnabled === existingHost.moshEnabled && etEnabled === existingHost.etEnabled ) { - return existingHost; + return suppressDeviceTypeForShellTransport(existingHost); } - return { + return suppressDeviceTypeForShellTransport({ ...existingHost, protocol, port, moshEnabled, etEnabled, - }; + }); } export function resolveTerminalChainHosts({ From 9ea1900f300c19638efd55256170a099341302f4 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 16:34:35 +0800 Subject: [PATCH 090/228] Fix serial autocomplete preview --- components/Terminal.tsx | 13 +- .../terminalAutocompleteKeyEvent.ts | 24 ++- .../terminalAutocompleteSettings.ts | 43 +++++ .../autocomplete/useTerminalAutocomplete.ts | 34 +++- .../terminalAutocompleteKeyEvent.test.ts | 147 ++++++++++++++++++ .../terminalAutocompleteSettings.test.ts | 56 +++++++ 6 files changed, 301 insertions(+), 16 deletions(-) create mode 100644 components/terminal/autocomplete/terminalAutocompleteSettings.ts create mode 100644 components/terminal/terminalAutocompleteKeyEvent.test.ts create mode 100644 components/terminal/terminalAutocompleteSettings.test.ts diff --git a/components/Terminal.tsx b/components/Terminal.tsx index 935c7cbbc..0e72321d8 100644 --- a/components/Terminal.tsx +++ b/components/Terminal.tsx @@ -88,6 +88,7 @@ import { useTerminalAuthState } from "./terminal/hooks/useTerminalAuthState"; import { useTerminalDragDrop } from "./terminal/hooks/useTerminalDragDrop"; import { useTerminalFilePaste } from "./terminal/hooks/useTerminalFilePaste"; import { TerminalAutocomplete } from "./terminal/TerminalAutocomplete"; +import { resolveTerminalAutocompleteSettings } from "./terminal/autocomplete/terminalAutocompleteSettings"; import { buildOsc7SetupExecCommand, runOsc7SetupAction, shouldOfferOsc7SetupAction } from "./terminal/osc7Setup"; import { getRemoteClipboardImageUploadErrorMessageKey, @@ -635,14 +636,10 @@ const TerminalComponent: React.FC = ({ const autocompleteHostOs: "linux" | "windows" | "macos" = host.protocol === "local" ? detectLocalOs(navigator.userAgent || navigator.platform) : (host.os || "linux"); - const autocompleteSettings = terminalSettings ? { - enabled: terminalSettings.autocompleteEnabled ?? true, - showGhostText: terminalSettings.autocompleteGhostText ?? true, - showPopupMenu: terminalSettings.autocompletePopupMenu ?? true, - debounceMs: terminalSettings.autocompleteDebounceMs ?? 100, - minChars: terminalSettings.autocompleteMinChars ?? 1, - maxSuggestions: terminalSettings.autocompleteMaxSuggestions ?? 8, - } : undefined; + const autocompleteSettings = resolveTerminalAutocompleteSettings({ + protocol: host.protocol, + terminalSettings, + }); const resolveSftpInitialPath = useCallback(async (options?: { preferFreshBackend?: boolean }): Promise => { const cwd = await resolvePreferredTerminalCwd({ diff --git a/components/terminal/autocomplete/terminalAutocompleteKeyEvent.ts b/components/terminal/autocomplete/terminalAutocompleteKeyEvent.ts index 43d868a69..f98c64c01 100644 --- a/components/terminal/autocomplete/terminalAutocompleteKeyEvent.ts +++ b/components/terminal/autocomplete/terminalAutocompleteKeyEvent.ts @@ -19,7 +19,8 @@ interface TerminalAutocompleteKeyEventContext { handleSubDirSelect: (level: number, entry: SubDirEntry) => void; fetchSubDirForIndex: (index: number) => void; renderPreviewSelection: (index: number) => void; - acceptSnippet: (snippet: Snippet) => void; + acceptPreviewlessSelection: (index: number) => boolean; + acceptSnippet: (snippet: Snippet) => boolean; } export function handleTerminalAutocompleteKeyEvent( @@ -42,6 +43,7 @@ export function handleTerminalAutocompleteKeyEvent( handleSubDirSelect, fetchSubDirForIndex, renderPreviewSelection, + acceptPreviewlessSelection, acceptSnippet, } = context; if (!settingsRef.current.enabled || e.type !== "keydown") return true; @@ -203,7 +205,7 @@ export function handleTerminalAutocompleteKeyEvent( }); // Live-render the highlighted entry's full path into the line (#1005). const newEntry = focusedPanel.entries[newIdx]; - if (newEntry) renderSubDirPath(focusLevel, newEntry); + if (newEntry && settingsRef.current.livePreview) renderSubDirPath(focusLevel, newEntry); // Auto-expand next level if the newly selected item is a directory if (newEntry?.type === "directory") { expandSubDir(focusLevel, newEntry); @@ -276,7 +278,7 @@ export function handleTerminalAutocompleteKeyEvent( selectedIndex: next, subDirPanels: [], subDirFocusLevel: -1, })); - renderPreviewSelection(next); + if (settingsRef.current.livePreview) renderPreviewSelection(next); if (next >= 0) fetchSubDirForIndex(next); return false; } @@ -290,11 +292,25 @@ export function handleTerminalAutocompleteKeyEvent( if (e.key === "Enter") { const selected = s.selectedIndex >= 0 ? s.suggestions[s.selectedIndex] : null; if (selected?.source === "snippet" && selected.snippet) { + if (!acceptSnippet(selected.snippet)) { + clearState(); + previewActiveRef.current = false; + return true; + } e.preventDefault(); previewActiveRef.current = false; - acceptSnippet(selected.snippet); return false; // consume — run the snippet, not the typed text } + if (!settingsRef.current.livePreview && selected) { + if (acceptPreviewlessSelection(s.selectedIndex)) { + e.preventDefault(); + previewActiveRef.current = false; + return false; + } + clearState(); + previewActiveRef.current = false; + return true; + } clearState(); previewActiveRef.current = false; return true; diff --git a/components/terminal/autocomplete/terminalAutocompleteSettings.ts b/components/terminal/autocomplete/terminalAutocompleteSettings.ts new file mode 100644 index 000000000..1525bec1b --- /dev/null +++ b/components/terminal/autocomplete/terminalAutocompleteSettings.ts @@ -0,0 +1,43 @@ +import type { AutocompleteSettings } from "./useTerminalAutocomplete"; + +type TerminalAutocompleteSettingFields = { + autocompleteEnabled?: boolean; + autocompleteGhostText?: boolean; + autocompletePopupMenu?: boolean; + autocompleteDebounceMs?: number; + autocompleteMinChars?: number; + autocompleteMaxSuggestions?: number; +}; + +export function resolveTerminalAutocompleteSettings(input: { + protocol?: string; + terminalSettings?: TerminalAutocompleteSettingFields; +}): Partial | undefined { + const { protocol, terminalSettings } = input; + + if (protocol === "serial") { + return { + enabled: terminalSettings?.autocompleteEnabled ?? true, + showGhostText: terminalSettings?.autocompleteGhostText ?? true, + showPopupMenu: terminalSettings?.autocompletePopupMenu ?? true, + livePreview: false, + allowLineReplacement: false, + debounceMs: terminalSettings?.autocompleteDebounceMs ?? 100, + minChars: terminalSettings?.autocompleteMinChars ?? 1, + maxSuggestions: terminalSettings?.autocompleteMaxSuggestions ?? 8, + }; + } + + if (!terminalSettings) return undefined; + + return { + enabled: terminalSettings.autocompleteEnabled ?? true, + showGhostText: terminalSettings.autocompleteGhostText ?? true, + showPopupMenu: terminalSettings.autocompletePopupMenu ?? true, + livePreview: true, + allowLineReplacement: true, + debounceMs: terminalSettings.autocompleteDebounceMs ?? 100, + minChars: terminalSettings.autocompleteMinChars ?? 1, + maxSuggestions: terminalSettings.autocompleteMaxSuggestions ?? 8, + }; +} diff --git a/components/terminal/autocomplete/useTerminalAutocomplete.ts b/components/terminal/autocomplete/useTerminalAutocomplete.ts index 2ef04d29f..45036cdb8 100644 --- a/components/terminal/autocomplete/useTerminalAutocomplete.ts +++ b/components/terminal/autocomplete/useTerminalAutocomplete.ts @@ -41,6 +41,10 @@ export interface AutocompleteSettings { enabled: boolean; showGhostText: boolean; showPopupMenu: boolean; + /** Whether popup navigation should render the highlighted candidate into the terminal input line. */ + livePreview: boolean; + /** Whether accepting a candidate may clear/replace the current input line. */ + allowLineReplacement: boolean; debounceMs: number; minChars: number; maxSuggestions: number; @@ -52,6 +56,8 @@ export const DEFAULT_AUTOCOMPLETE_SETTINGS: AutocompleteSettings = { enabled: true, showGhostText: true, showPopupMenu: true, + livePreview: true, + allowLineReplacement: true, debounceMs: 100, minChars: 1, maxSuggestions: 8, @@ -646,7 +652,7 @@ export function useTerminalAutocomplete( ); // Single query for both ghost text and popup - const completions = await getCompletions(input, { + let completions = await getCompletions(input, { hostId: hostIdRef.current, os: hostOsRef.current, maxResults: settingsRef.current.maxSuggestions, @@ -656,6 +662,11 @@ export function useTerminalAutocomplete( cwdSource: cwdResolution.source, snippets: snippetsRef.current, }); + if (!settingsRef.current.allowLineReplacement) { + completions = completions.filter((completion) => + completion.source !== "snippet" && completion.text.startsWith(input), + ); + } if (disposedRef.current || version !== fetchVersionRef.current) return; @@ -789,6 +800,7 @@ export function useTerminalAutocomplete( handleSubDirSelect, fetchSubDirForIndex, renderPreviewSelection, + acceptPreviewlessSelection, acceptSnippet, }), // eslint-disable-next-line react-hooks/exhaustive-deps -- handler uses refs and callbacks initialized below. @@ -800,6 +812,7 @@ export function useTerminalAutocomplete( * live-preview, #1005). `index < 0` restores the user's typed baseline. */ const renderPreviewSelection = useCallback((index: number) => { + if (!settingsRef.current.livePreview) return; const s = stateRef.current; const term = termRef.current; if (!term) return; @@ -836,11 +849,12 @@ export function useTerminalAutocomplete( /** Accept a snippet: clear the user's typed input, then run it via the * host-canonical send path (onAcceptSnippet). */ - const acceptSnippet = useCallback((snippet: Snippet) => { + const acceptSnippet = useCallback((snippet: Snippet): boolean => { const term = termRef.current; if (term) { const { prompt } = getAlignedPrompt(term, typedInputBufferRef.current, typedBufferReliableRef.current); if (prompt.isAtPrompt && prompt.userInput.length > 0) { + if (!settingsRef.current.allowLineReplacement) return false; const clearSequence = hostOsRef.current === "windows" ? "\b".repeat(prompt.userInput.length) : "\x15"; // Ctrl+U (readline kill-line) @@ -851,6 +865,7 @@ export function useTerminalAutocomplete( typedBufferReliableRef.current = true; onAcceptSnippetRef.current?.(snippet); clearState(); + return true; // eslint-disable-next-line react-hooks/exhaustive-deps -- clearState is stable }, [termRef, writeToTerminal]); @@ -861,12 +876,12 @@ export function useTerminalAutocomplete( const insertSuggestion = useCallback( (suggestion: CompletionSuggestion, execute: boolean) => { const term = termRef.current; - if (!term) return; + if (!term) return false; // Always use real-time prompt detection — lastPromptRef may be stale // if the user typed more characters after suggestions were fetched. const { prompt } = getAlignedPrompt(term, typedInputBufferRef.current, typedBufferReliableRef.current); - if (!prompt.isAtPrompt) return; + if (!prompt.isAtPrompt) return false; // If suggestion starts with the current input, insert only the remaining part. // Otherwise (fuzzy match), clear the line first and write the full suggestion. @@ -875,6 +890,7 @@ export function useTerminalAutocomplete( const textToInsert = suggestion.text.substring(prompt.userInput.length); payload = execute ? textToInsert + "\r" : textToInsert; } else { + if (!settingsRef.current.allowLineReplacement) return false; // Fuzzy match: clear current input, then write full command. // Ctrl+U works on POSIX shells (bash/zsh/fish). // On Windows (cmd.exe/PowerShell), use backspaces to erase instead. @@ -916,11 +932,21 @@ export function useTerminalAutocomplete( } clearState(); + return true; }, // eslint-disable-next-line react-hooks/exhaustive-deps -- clearState is stable [termRef, writeToTerminal], ); + const acceptPreviewlessSelection = useCallback((index: number): boolean => { + const suggestion = stateRef.current.suggestions[index]; + if (!suggestion) return false; + if (suggestion.source === "snippet" && suggestion.snippet) { + return acceptSnippet(suggestion.snippet); + } + return insertSuggestion(suggestion, true); + }, [acceptSnippet, insertSuggestion]); + /** * Select a suggestion from the popup (Tab / mouse click — insert only, no execute). */ diff --git a/components/terminal/terminalAutocompleteKeyEvent.test.ts b/components/terminal/terminalAutocompleteKeyEvent.test.ts new file mode 100644 index 000000000..8fe384f48 --- /dev/null +++ b/components/terminal/terminalAutocompleteKeyEvent.test.ts @@ -0,0 +1,147 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { handleTerminalAutocompleteKeyEvent } from "./autocomplete/terminalAutocompleteKeyEvent.ts"; + +const suggestion = (text: string) => ({ + text, + displayText: text, + source: "history" as const, + score: 1, +}); + +function keyEvent(key: string) { + return { + type: "keydown", + key, + ctrlKey: false, + metaKey: false, + altKey: false, + shiftKey: false, + defaultPrevented: false, + preventDefault() { + this.defaultPrevented = true; + }, + } as KeyboardEvent & { defaultPrevented: boolean }; +} + +function createContext(overrides: Record = {}) { + let state = { + suggestions: [suggestion("show version")], + selectedIndex: -1, + popupVisible: true, + popupAnchorViewport: { left: 0, top: 0, bottom: 0 }, + expandUpward: false, + subDirPanels: [], + subDirFocusLevel: -1, + }; + const writes: string[] = []; + const previews: number[] = []; + const accepted: number[] = []; + const clears: number[] = []; + const stateRef = { current: state }; + + return { + writes, + previews, + accepted, + clears, + context: { + settingsRef: { + current: { + enabled: true, + showGhostText: false, + showPopupMenu: true, + debounceMs: 100, + minChars: 1, + maxSuggestions: 8, + livePreview: false, + allowLineReplacement: false, + }, + }, + stateRef, + ghostAddonRef: { current: null }, + typedInputBufferRef: { current: "sh" }, + typedBufferReliableRef: { current: true }, + previewActiveRef: { current: false }, + lastAcceptedCommandRef: { current: null }, + setState(update: typeof state | ((prev: typeof state) => typeof state)) { + state = typeof update === "function" ? update(state) : update; + stateRef.current = state; + }, + expandSubDir() {}, + writeToTerminal(text: string) { writes.push(text); }, + clearState() { clears.push(1); }, + renderSubDirPath() {}, + handleSubDirSelect() {}, + fetchSubDirForIndex() {}, + renderPreviewSelection(index: number) { previews.push(index); }, + acceptSnippet() { return true; }, + acceptPreviewlessSelection(index: number) { accepted.push(index); return true; }, + ...overrides, + }, + }; +} + +test("serial-style popup navigation does not render candidates into the input line", () => { + const { context, previews } = createContext(); + const event = keyEvent("ArrowDown"); + + const result = handleTerminalAutocompleteKeyEvent(event, context); + + assert.equal(result, false); + assert.equal(event.defaultPrevented, true); + assert.deepEqual(previews, []); +}); + +test("serial-style popup Enter confirms the selected candidate instead of passing Enter through", () => { + const { context, accepted, clears } = createContext({ + stateRef: { + current: { + suggestions: [suggestion("show version")], + selectedIndex: 0, + popupVisible: true, + popupAnchorViewport: { left: 0, top: 0, bottom: 0 }, + expandUpward: false, + subDirPanels: [], + subDirFocusLevel: -1, + }, + }, + }); + const event = keyEvent("Enter"); + + const result = handleTerminalAutocompleteKeyEvent(event, context); + + assert.equal(result, false); + assert.equal(event.defaultPrevented, true); + assert.deepEqual(accepted, [0]); + assert.deepEqual(clears, []); +}); + +test("serial-style popup Enter passes through when the selected candidate is stale", () => { + const { context, accepted, clears } = createContext({ + stateRef: { + current: { + suggestions: [suggestion("show version")], + selectedIndex: 0, + popupVisible: true, + popupAnchorViewport: { left: 0, top: 0, bottom: 0 }, + expandUpward: false, + subDirPanels: [], + subDirFocusLevel: -1, + }, + }, + acceptPreviewlessSelection(index: number) { + accepted.push(index); + return false; + }, + }); + const event = keyEvent("Enter"); + + const result = handleTerminalAutocompleteKeyEvent(event, context); + + assert.equal(result, true); + assert.equal(event.defaultPrevented, false); + assert.deepEqual(accepted, [0]); + assert.deepEqual(clears, [1]); +}); diff --git a/components/terminal/terminalAutocompleteSettings.test.ts b/components/terminal/terminalAutocompleteSettings.test.ts new file mode 100644 index 000000000..435b4a4ba --- /dev/null +++ b/components/terminal/terminalAutocompleteSettings.test.ts @@ -0,0 +1,56 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { resolveTerminalAutocompleteSettings } from "./autocomplete/terminalAutocompleteSettings.ts"; + +test("keeps autocomplete enabled for shell-like terminal protocols", () => { + assert.deepEqual( + resolveTerminalAutocompleteSettings({ + protocol: "ssh", + terminalSettings: { + autocompleteEnabled: true, + autocompleteGhostText: false, + autocompletePopupMenu: true, + autocompleteDebounceMs: 120, + autocompleteMinChars: 2, + autocompleteMaxSuggestions: 6, + }, + }), + { + enabled: true, + showGhostText: false, + showPopupMenu: true, + livePreview: true, + allowLineReplacement: true, + debounceMs: 120, + minChars: 2, + maxSuggestions: 6, + }, + ); +}); + +test("keeps serial autocomplete available but disables input-line preview and replacement", () => { + assert.deepEqual( + resolveTerminalAutocompleteSettings({ + protocol: "serial", + terminalSettings: { + autocompleteEnabled: true, + autocompleteGhostText: false, + autocompletePopupMenu: true, + autocompleteDebounceMs: 100, + autocompleteMinChars: 1, + autocompleteMaxSuggestions: 8, + }, + }), + { + enabled: true, + showGhostText: false, + showPopupMenu: true, + debounceMs: 100, + minChars: 1, + maxSuggestions: 8, + livePreview: false, + allowLineReplacement: false, + }, + ); +}); From 8539747e29495ff330cc432f66d2d70bedffee2c Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 17:01:43 +0800 Subject: [PATCH 091/228] preserve zsh history hook during osc7 setup --- components/terminal/osc7Setup.test.ts | 36 +++++++++++++++++++++++++++ components/terminal/osc7Setup.ts | 10 +++++--- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/components/terminal/osc7Setup.test.ts b/components/terminal/osc7Setup.test.ts index 3529cc5ea..dee7e24ee 100644 --- a/components/terminal/osc7Setup.test.ts +++ b/components/terminal/osc7Setup.test.ts @@ -234,6 +234,42 @@ test("buildOsc7SetupCommand does not leave setup payload in zsh history", (t) => }); }); +test("buildOsc7SetupCommand preserves an existing zsh history hook", (t) => { + const zshPath = existingShells(["/bin/zsh", "/usr/bin/zsh"])[0]; + if (!zshPath) { + t.skip("zsh is not installed on this runner"); + return; + } + + withTempHome("netcatty-osc7-history-hook-zsh-", (home) => { + const functionDumpPath = join(home, "zshaddhistory-dump"); + const hookMarkerPath = join(home, "zshaddhistory-marker"); + const result = spawnSync(zshPath, ["-f", "-i"], { + env: { + ...process.env, + HOME: home, + HISTFILE: join(home, ".zsh_history"), + SHELL: zshPath, + ZDOTDIR: home, + }, + input: [ + `zshaddhistory(){ print -r -- preserved >> ${quoteShellArg(hookMarkerPath)}; return 0; }`, + buildOsc7SetupCommand(), + `functions zshaddhistory > ${quoteShellArg(functionDumpPath)}`, + "zshaddhistory", + "exit", + ].join("\n"), + encoding: "utf8", + }); + + assert.equal(result.status, 0, result.stderr || result.stdout); + const restoredFunction = readFileSync(functionDumpPath, "utf8"); + assert.match(restoredFunction, /preserved/); + assert.doesNotMatch(restoredFunction, /__netcatty_osc7|return 1/); + assert.match(readFileSync(hookMarkerPath, "utf8"), /preserved/); + }); +}); + test("buildOsc7SetupCommand runs under strict unset-variable mode", () => { for (const shellPath of existingShells(["/bin/bash", "/bin/zsh"])) { withTempHome(`netcatty-osc7-strict-${basename(shellPath)}-`, (home) => { diff --git a/components/terminal/osc7Setup.ts b/components/terminal/osc7Setup.ts index 072e766aa..e9e11a7fe 100644 --- a/components/terminal/osc7Setup.ts +++ b/components/terminal/osc7Setup.ts @@ -53,8 +53,11 @@ const quoteForSingleQuotedShellString = (value: string): string => const URL_PATH_AWK_SCRIPT_QUOTED = quoteForSingleQuotedShellString(URL_PATH_AWK_SCRIPT); const BASH_DELETE_CURRENT_HISTORY = String.raw`test -n "$BASH_VERSION" && history -d $(history 1 | sed "s/^ *\([0-9][0-9]*\).*/\1/") 2>/dev/null || true`; -const ZSH_SUPPRESS_NEXT_HISTORY = String.raw`test -n "$ZSH_VERSION" && eval 'zshaddhistory(){ return 1; }' || true`; -const ZSH_RESTORE_HISTORY_HOOK = String.raw`test -n "$ZSH_VERSION" && eval 'unfunction zshaddhistory 2>/dev/null || true' || true`; +const ZSH_SUPPRESS_SETUP_HISTORY = `test -n "$ZSH_VERSION" && eval '${[ + "__netcatty_osc7_zsh_history_suppressions=2", + "if functions zshaddhistory >/dev/null 2>&1; then functions -c zshaddhistory __netcatty_osc7_original_zshaddhistory; __netcatty_osc7_had_zshaddhistory=1; else __netcatty_osc7_had_zshaddhistory=0; fi", + `zshaddhistory(){ local __netcatty_osc7_remaining=${DOLLAR}{__netcatty_osc7_zsh_history_suppressions:-0}; if (( __netcatty_osc7_remaining > 1 )); then __netcatty_osc7_zsh_history_suppressions=${DOLLAR}(( __netcatty_osc7_remaining - 1 )); return 1; fi; if (( ${DOLLAR}{__netcatty_osc7_had_zshaddhistory:-0} )); then functions -c __netcatty_osc7_original_zshaddhistory zshaddhistory 2>/dev/null || true; unfunction __netcatty_osc7_original_zshaddhistory 2>/dev/null || true; else unfunction zshaddhistory 2>/dev/null || true; fi; unset __netcatty_osc7_zsh_history_suppressions __netcatty_osc7_had_zshaddhistory; return 1; }`, +].join("; ")}' || true`; const POSIX_SETUP_SCRIPT = String.raw`set -eu marker="# >>> Netcatty OSC 7 cwd tracking >>>" @@ -152,7 +155,6 @@ printf '\033]7;file://%s%s\a' "$host" "$(__netcatty_osc7_url_path "$PWD")"`; export const buildOsc7SetupCommand = (): string => [ - `set +u 2>/dev/null || true; ${ZSH_SUPPRESS_NEXT_HISTORY}; ${BASH_DELETE_CURRENT_HISTORY}`, + `set +u 2>/dev/null || true; ${ZSH_SUPPRESS_SETUP_HISTORY}; ${BASH_DELETE_CURRENT_HISTORY}`, `set +u 2>/dev/null || true; printf "%s\\n" ${quoteForSingleQuotedShellString(POSIX_SETUP_SCRIPT)} | env NETCATTY_ZDOTDIR="$ZDOTDIR" NETCATTY_XDG_CONFIG_HOME="$XDG_CONFIG_HOME" sh; ${BASH_DELETE_CURRENT_HISTORY}`, - `${ZSH_RESTORE_HISTORY_HOOK}; ${BASH_DELETE_CURRENT_HISTORY}`, ].join("\n") + "\n"; From 23719e955e144e0627fb4d70cfc1b08d229d42b7 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 17:52:03 +0800 Subject: [PATCH 092/228] fix osc7 reload history cleanup --- components/terminal/osc7Setup.test.ts | 122 ++++++++++++++++---------- components/terminal/osc7Setup.ts | 17 +--- 2 files changed, 77 insertions(+), 62 deletions(-) diff --git a/components/terminal/osc7Setup.test.ts b/components/terminal/osc7Setup.test.ts index c195deceb..280e20bac 100644 --- a/components/terminal/osc7Setup.test.ts +++ b/components/terminal/osc7Setup.test.ts @@ -176,6 +176,24 @@ test("buildOsc7SetupCommand configures bash once and prompt loading stays idempo }); }); +test("buildOsc7SetupCommand preserves setup failure status", () => { + withTempHome("netcatty-osc7-unsupported-shell-", (home) => { + const result = spawnSync("/bin/sh", ["-c", buildOsc7SetupCommand()], { + env: { + ...process.env, + HOME: home, + SHELL: "/bin/unknown", + ZDOTDIR: "", + XDG_CONFIG_HOME: "", + }, + encoding: "utf8", + }); + + assert.equal(result.status, 2, result.stderr || result.stdout); + assert.match(result.stderr, /unsupported shell unknown/); + }); +}); + test("buildOsc7SetupExecCommand configures bash through a background exec shell", () => { withTempHome("netcatty-osc7-exec-bash-", (home) => { const output = execFileSync("/bin/sh", ["-c", buildOsc7SetupExecCommand()], { @@ -303,9 +321,17 @@ test("buildOsc7SetupCommand can be pasted into supported shells", () => { } }); -test("buildOsc7SetupCommand does not leave setup payload in bash history", () => { - withTempHome("netcatty-osc7-history-bash-", (home) => { +test("buildOsc7ReloadCommand does not leave reload command in bash history", () => { + withTempHome("netcatty-osc7-reload-history-bash-", (home) => { + const bashrcPath = join(home, ".bashrc"); const dumpPath = join(home, "bash-history-dump"); + mkdirSync(home, { recursive: true }); + writeFileSync(bashrcPath, "osc7_cwd(){ :; }\n"); + const reloadCommand = buildOsc7ReloadCommand({ shell: "bash", configPath: bashrcPath }); + + assert.ok(reloadCommand); + assert.doesNotMatch(reloadCommand.slice(0, -1), /[\r\n]/); + const output = runInteractiveHistoryProbe({ shellPath: "/bin/bash", shellArgs: ["--noprofile", "--norc", "-i"], @@ -314,42 +340,47 @@ test("buildOsc7SetupCommand does not leave setup payload in bash history", () => env: { HOME: home, HISTFILE: join(home, ".bash_history"), + HISTCONTROL: "ignoreboth", SHELL: "/bin/bash", }, + input: `echo keepme\n${reloadCommand}`, }); - assert.doesNotMatch(output, /Netcatty OSC 7 cwd tracking|osc7_cwd|printf "%s\\n"/); + assert.match(output, /echo keepme/); + assert.doesNotMatch(output, /osc7_cwd|source .*\.bashrc|__netcatty_osc7|history -d/); }); }); -test("buildOsc7SetupCommand does not leave setup payload in zsh history", (t) => { - const zshPath = existingShells(["/bin/zsh", "/usr/bin/zsh"])[0]; - if (!zshPath) { - t.skip("zsh is not installed on this runner"); - return; - } +test("buildOsc7ReloadCommand preserves bash nounset", () => { + withTempHome("netcatty-osc7-reload-nounset-bash-", (home) => { + const bashrcPath = join(home, ".bashrc"); + const optionDumpPath = join(home, "bash-options-dump"); + mkdirSync(home, { recursive: true }); + writeFileSync(bashrcPath, "osc7_cwd(){ :; }\n"); - withTempHome("netcatty-osc7-history-zsh-", (home) => { - const dumpPath = join(home, "zsh-history-dump"); - const output = runInteractiveHistoryProbe({ - shellPath: zshPath, - shellArgs: ["-f", "-i"], - dumpHistoryCommand: `fc -ln 1 > ${quoteShellArg(dumpPath)}`, - dumpPath, + const result = spawnSync("/bin/bash", ["--noprofile", "--norc", "-i"], { env: { + ...process.env, HOME: home, - HISTFILE: join(home, ".zsh_history"), - SHELL: zshPath, - ZDOTDIR: home, + HISTFILE: join(home, ".bash_history"), + SHELL: "/bin/bash", }, + input: [ + "set -u", + (buildOsc7ReloadCommand({ shell: "bash", configPath: bashrcPath }) ?? "").replace(/\r/g, "\n"), + `set -o | grep nounset > ${quoteShellArg(optionDumpPath)}`, + "exit", + ].join("\n"), + encoding: "utf8", }); - assert.doesNotMatch(output, /Netcatty OSC 7 cwd tracking|osc7_cwd|printf "%s\\n"/); + assert.equal(result.status, 0, result.stderr || result.stdout); + assert.match(readFileSync(optionDumpPath, "utf8"), /\bon\b/); }); }); -test("buildOsc7ReloadCommand does not leave reload command in bash history", () => { - withTempHome("netcatty-osc7-reload-history-bash-", (home) => { +test("buildOsc7ReloadCommand does not delete bash history when reload is not recorded", () => { + withTempHome("netcatty-osc7-reload-ignored-history-bash-", (home) => { const bashrcPath = join(home, ".bashrc"); const dumpPath = join(home, "bash-history-dump"); mkdirSync(home, { recursive: true }); @@ -363,48 +394,43 @@ test("buildOsc7ReloadCommand does not leave reload command in bash history", () env: { HOME: home, HISTFILE: join(home, ".bash_history"), + HISTIGNORE: "*__netcatty_osc7_history_cleanup_marker__=1*", SHELL: "/bin/bash", }, - input: buildOsc7ReloadCommand({ shell: "bash", configPath: bashrcPath }) ?? "", + input: `echo keepme\n${buildOsc7ReloadCommand({ shell: "bash", configPath: bashrcPath }) ?? ""}`, }); + assert.match(output, /echo keepme/); assert.doesNotMatch(output, /osc7_cwd|source .*\.bashrc|__netcatty_osc7|history -d/); }); }); -test("buildOsc7SetupCommand preserves an existing zsh history hook", (t) => { - const zshPath = existingShells(["/bin/zsh", "/usr/bin/zsh"])[0]; - if (!zshPath) { - t.skip("zsh is not installed on this runner"); - return; - } +test("buildOsc7ReloadCommand bypasses custom bash history wrappers", () => { + withTempHome("netcatty-osc7-reload-wrapped-history-bash-", (home) => { + const bashrcPath = join(home, ".bashrc"); + const dumpPath = join(home, "bash-history-dump"); + mkdirSync(home, { recursive: true }); + writeFileSync(bashrcPath, "osc7_cwd(){ :; }\n"); - withTempHome("netcatty-osc7-history-hook-zsh-", (home) => { - const functionDumpPath = join(home, "zshaddhistory-dump"); - const hookMarkerPath = join(home, "zshaddhistory-marker"); - const result = spawnSync(zshPath, ["-f", "-i"], { + const output = runInteractiveHistoryProbe({ + shellPath: "/bin/bash", + shellArgs: ["--noprofile", "--norc", "-i"], + dumpHistoryCommand: `builtin history > ${quoteShellArg(dumpPath)}`, + dumpPath, env: { - ...process.env, HOME: home, - HISTFILE: join(home, ".zsh_history"), - SHELL: zshPath, - ZDOTDIR: home, + HISTFILE: join(home, ".bash_history"), + SHELL: "/bin/bash", }, input: [ - `zshaddhistory(){ print -r -- preserved >> ${quoteShellArg(hookMarkerPath)}; return 0; }`, - buildOsc7SetupCommand(), - `functions zshaddhistory > ${quoteShellArg(functionDumpPath)}`, - "zshaddhistory", - "exit", + 'history(){ echo custom; }', + "echo keepme", + buildOsc7ReloadCommand({ shell: "bash", configPath: bashrcPath }) ?? "", ].join("\n"), - encoding: "utf8", }); - assert.equal(result.status, 0, result.stderr || result.stdout); - const restoredFunction = readFileSync(functionDumpPath, "utf8"); - assert.match(restoredFunction, /preserved/); - assert.doesNotMatch(restoredFunction, /__netcatty_osc7|return 1/); - assert.match(readFileSync(hookMarkerPath, "utf8"), /preserved/); + assert.match(output, /echo keepme/); + assert.doesNotMatch(output, /osc7_cwd|source .*\.bashrc|__netcatty_osc7|history -d/); }); }); diff --git a/components/terminal/osc7Setup.ts b/components/terminal/osc7Setup.ts index 7a1f98994..389038998 100644 --- a/components/terminal/osc7Setup.ts +++ b/components/terminal/osc7Setup.ts @@ -91,15 +91,7 @@ const quoteForSingleQuotedShellString = (value: string): string => const URL_PATH_AWK_SCRIPT_QUOTED = quoteForSingleQuotedShellString(URL_PATH_AWK_SCRIPT); -const BASH_DELETE_CURRENT_HISTORY = String.raw`test -n "$BASH_VERSION" && history -d $(history 1 | sed "s/^ *\([0-9][0-9]*\).*/\1/") 2>/dev/null || true`; -const ZSH_SUPPRESS_NEXT_TWO_HISTORY_ENTRIES = `test -n "$ZSH_VERSION" && eval '${[ - "__netcatty_osc7_zsh_history_suppressions=2", - `__netcatty_osc7_original_zshaddhistory_name=__netcatty_osc7_original_zshaddhistory_${DOLLAR}${DOLLAR}`, - `if functions zshaddhistory >/dev/null 2>&1; then functions -c zshaddhistory "${DOLLAR}__netcatty_osc7_original_zshaddhistory_name"; __netcatty_osc7_had_zshaddhistory=1; else __netcatty_osc7_had_zshaddhistory=0; fi`, - `zshaddhistory(){ local __netcatty_osc7_remaining=${DOLLAR}{__netcatty_osc7_zsh_history_suppressions:-0}; if (( __netcatty_osc7_remaining > 1 )); then __netcatty_osc7_zsh_history_suppressions=${DOLLAR}(( __netcatty_osc7_remaining - 1 )); return 1; fi; if (( ${DOLLAR}{__netcatty_osc7_had_zshaddhistory:-0} )); then functions -c "${DOLLAR}__netcatty_osc7_original_zshaddhistory_name" zshaddhistory 2>/dev/null || true; unfunction "${DOLLAR}__netcatty_osc7_original_zshaddhistory_name" 2>/dev/null || true; else unfunction zshaddhistory 2>/dev/null || true; fi; unset __netcatty_osc7_zsh_history_suppressions __netcatty_osc7_had_zshaddhistory __netcatty_osc7_original_zshaddhistory_name; return 1; }`, -].join("; ")}' || true`; -const SUPPRESS_SHELL_HISTORY_COMMAND = `set +u 2>/dev/null || true; ${ZSH_SUPPRESS_NEXT_TWO_HISTORY_ENTRIES}; ${BASH_DELETE_CURRENT_HISTORY}`; -const SUPPRESS_BASH_HISTORY_COMMAND = `set +u 2>/dev/null || true; ${BASH_DELETE_CURRENT_HISTORY}`; +const BASH_DELETE_MARKED_HISTORY_COMMAND = String.raw`if test -n "${DOLLAR}{BASH_VERSION-}"; then __netcatty_osc7_history_cleanup_marker__=1; __netcatty_osc7_history_line=$(HISTTIMEFORMAT= builtin history 1 2>/dev/null) || __netcatty_osc7_history_line=""; case "$__netcatty_osc7_history_line" in *__netcatty_osc7_history_cleanup_marker__=1*) __netcatty_osc7_history_number=$(printf "%s\n" "$__netcatty_osc7_history_line" | sed "s/^ *\([0-9][0-9]*\).*/\1/"); case "$__netcatty_osc7_history_number" in ""|*[!0-9]*) ;; *) builtin history -d "$__netcatty_osc7_history_number" 2>/dev/null || true;; esac;; esac; unset __netcatty_osc7_history_cleanup_marker__ __netcatty_osc7_history_line __netcatty_osc7_history_number 2>/dev/null || true; fi`; const POSIX_SETUP_SCRIPT = String.raw`set -eu marker="# >>> Netcatty OSC 7 cwd tracking >>>" @@ -307,10 +299,7 @@ host=$(hostname 2>/dev/null || printf localhost) printf '\033]7;file://%s%s\a' "$host" "$(__netcatty_osc7_url_path "$PWD")"`; export const buildOsc7SetupCommand = (): string => - [ - SUPPRESS_SHELL_HISTORY_COMMAND, - `set +u 2>/dev/null || true; printf "%s\\n" ${quoteForSingleQuotedShellString(POSIX_SETUP_SCRIPT)} | env NETCATTY_ZDOTDIR="$ZDOTDIR" NETCATTY_XDG_CONFIG_HOME="$XDG_CONFIG_HOME" sh; ${BASH_DELETE_CURRENT_HISTORY}`, - ].join("\n") + "\n"; + `set +u 2>/dev/null || true; printf "%s\\n" ${quoteForSingleQuotedShellString(POSIX_SETUP_SCRIPT)} | env NETCATTY_ZDOTDIR="$ZDOTDIR" NETCATTY_XDG_CONFIG_HOME="$XDG_CONFIG_HOME" sh\n`; export const buildOsc7SetupExecCommand = (expectedCwd?: string): string => { const envPrefix = expectedCwd @@ -366,7 +355,7 @@ export const buildOsc7ReloadCommand = (metadata: Osc7SetupMetadata | null): stri const sourceCommand = `source ${quoteForSingleQuotedShellString(metadata.configPath)} >/dev/null 2>&1`; const emitCommand = metadata.shell === "fish" ? "__netcatty_osc7_cwd" : "osc7_cwd"; if (metadata.shell === "bash") { - return `${SUPPRESS_BASH_HISTORY_COMMAND}\n ${sourceCommand}; ${emitCommand} 2>/dev/null; true; ${BASH_DELETE_CURRENT_HISTORY}\r`; + return `${sourceCommand}; ${emitCommand} 2>/dev/null; true; ${BASH_DELETE_MARKED_HISTORY_COMMAND}\r`; } return ` ${sourceCommand}; ${emitCommand} 2>/dev/null; true\r`; }; From f95cc754e72b466886fccf8206e5cb3f0d9475a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 18:01:57 +0800 Subject: [PATCH 093/228] fix(windows): restore main-window input focus on show/hide hotkey (#1722) Route global hotkey/tray show paths through restoreWindowInputFocus, recover renderer focus on visibility/show, dismiss transient overlays before native hide, and cancel deferred focus callbacks on hide. Closes #1722 --- application/app/AppView.tsx | 41 +++++- .../useMainWindowInputFocusRecovery.test.ts | 53 ++++++++ .../state/useMainWindowInputFocusRecovery.ts | 69 ++++++++++ application/state/windowInputFocus.ts | 46 ++++++- components/ui/dropdown.tsx | 10 ++ electron/bridges/globalShortcutBridge.cjs | 57 +++----- .../bridges/globalShortcutBridge.test.cjs | 122 ++++++++++++++++++ electron/bridges/windowManager.cjs | 30 +++++ electron/bridges/windowManager/mainWindow.cjs | 4 + .../bridges/windowManagerReadiness.test.cjs | 57 ++++++++ electron/main.cjs | 14 +- electron/preload.cjs | 24 ++++ electron/preload/api.cjs | 8 ++ types/global/netcatty-bridge-sync.d.ts | 2 + 14 files changed, 474 insertions(+), 63 deletions(-) create mode 100644 application/state/useMainWindowInputFocusRecovery.test.ts create mode 100644 application/state/useMainWindowInputFocusRecovery.ts diff --git a/application/app/AppView.tsx b/application/app/AppView.tsx index 83e2687f8..41267557b 100644 --- a/application/app/AppView.tsx +++ b/application/app/AppView.tsx @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import React, { Suspense, lazy, useMemo } from 'react'; +import React, { Suspense, lazy, useCallback, useMemo } from 'react'; import { AlertTriangle, Download, Trash2 } from 'lucide-react'; import { activeTabStore, toEditorTabId, useIsEditorTabActive } from '../state/activeTabStore'; import { editorTabStore } from '../state/editorTabStore'; @@ -22,6 +22,7 @@ import { toast } from '../../components/ui/toast'; import { AppHostTreeLayer } from './AppHostTreeLayer'; import { getUiThemeById } from '../../infrastructure/config/uiThemes'; import { buildAppThemeCssVars } from '../state/settingsStateDefaults'; +import { useMainWindowInputFocusRecovery } from '../state/useMainWindowInputFocusRecovery'; const LazyProtocolSelectDialog = lazy(() => import('../../components/ProtocolSelectDialog')); const LazyQuickSwitcher = lazy(() => @@ -53,6 +54,36 @@ const TextEditorTabFallback = ({ tabId }: { tabId: string }) => { type AppViewContext = Record; export function AppView({ ctx }: { ctx: AppViewContext }) { + const { + resetSessionRename, + resetWorkspaceRename, + setAddToWorkspaceDialog, + setIsCreateWorkspaceOpen, + setIsQuickSwitcherOpen, + setProtocolSelectHost, + setQuickSearch, + } = ctx; + + const dismissTransientOverlays = useCallback(() => { + setIsQuickSwitcherOpen(false); + setQuickSearch(''); + setIsCreateWorkspaceOpen(false); + setProtocolSelectHost(null); + setAddToWorkspaceDialog(null); + resetSessionRename(); + resetWorkspaceRename(); + }, [ + resetSessionRename, + resetWorkspaceRename, + setAddToWorkspaceDialog, + setIsCreateWorkspaceOpen, + setIsQuickSwitcherOpen, + setProtocolSelectHost, + setQuickSearch, + ]); + + useMainWindowInputFocusRecovery({ onPageHidden: dismissTransientOverlays }); + const { accentMode, addShellHistoryEntry, addSessionToWorkspace, addToWorkspaceDialog, appendHostToWorkspace, appendLocalTerminalToWorkspace, clearAndRemoveSource, clearAndRemoveSources, clearUnsavedConnectionLogs, closeLogView, closeSession, closeTabsBatch, closeWorkspace, copySessionToNewWindowWithCurrentShell, copySessionWithCurrentShell, @@ -64,10 +95,10 @@ export function AppView({ ctx }: { ctx: AppViewContext }) { handleRequestCloseEditorTabRef, handleSessionStatusChange, handleSyncNowManual, handleTerminalDataCapture, handleToggleTheme, handleUpdateHostFromTerminal, hostById, hosts, hotkeyScheme, identities, importOrReuseKey, isBroadcastEnabled, isCreateWorkspaceOpen, isMacClient, isQuickSwitcherOpen, keyBindings, keyboardInteractiveQueue, keys, logViews, managedSources, navigateToSection, noteGroups, notes, openLogView, openNoteRequest, orderedTabsWithEditors, orphanSessions, - passphraseQueue, protocolSelectHost, proxyProfiles, portForwardingRules, quickResults, quickSearch, removeSessionFromWorkspace, reorderWorkTabs, reorderWorkspaceSessions, resetSessionRename, - resetWorkspaceRename, resolveEmptyVaultConflict, resolvedTheme, runSnippet, sessionLogsDir, sessionLogsEnabled, sessionLogsFormat, sessionLogsTimestampsEnabled, sessionRenameTarget, sshDebugLogsEnabled, - sessionRenameValue, sessions, setActiveTabId, setAddToWorkspaceDialog, setDeepLinkHostDraft, setDraggingSessionId, setEditorWordWrap, setIsCreateWorkspaceOpen, setIsQuickSwitcherOpen, - setNavigateToSection, setProtocolSelectHost, setQuickSearch, setSessionRenameValue, setTerminalFontFamilyId, setTerminalFontSize, setTerminalThemeId, setVaultFocusRequest, updateSessionFontSize, updateSessionRestoreCwd, updateSessionDynamicTitle, updateSessionCodingCliProvider, clearSessionFontSizeOverride, + passphraseQueue, protocolSelectHost, proxyProfiles, portForwardingRules, quickResults, quickSearch, removeSessionFromWorkspace, reorderWorkTabs, reorderWorkspaceSessions, + resolveEmptyVaultConflict, resolvedTheme, runSnippet, sessionLogsDir, sessionLogsEnabled, sessionLogsFormat, sessionLogsTimestampsEnabled, sessionRenameTarget, sshDebugLogsEnabled, + sessionRenameValue, sessions, setActiveTabId, setDeepLinkHostDraft, setDraggingSessionId, setEditorWordWrap, + setNavigateToSection, setSessionRenameValue, setTerminalFontFamilyId, setTerminalFontSize, setTerminalThemeId, setVaultFocusRequest, updateSessionFontSize, updateSessionRestoreCwd, updateSessionDynamicTitle, updateSessionCodingCliProvider, clearSessionFontSizeOverride, setWorkspaceFocusedSession, setWorkspaceRenameValue, settings, sftpAutoOpenSidebar, sftpFollowTerminalCwd, setSftpFollowTerminalCwd, sftpAutoSync, sftpDefaultViewMode, sftpDoubleClickBehavior, sftpShowHiddenFiles, sftpUseCompressedUpload, shellHistory, snippetPackages, snippets, splitSessionWithCurrentShell, startSessionRename, startWorkspaceRename, submitSessionRename, submitWorkspaceRename, t, terminalFontFamilyId, terminalFontSize, terminalSettings, terminalThemeId, themeById, diff --git a/application/state/useMainWindowInputFocusRecovery.test.ts b/application/state/useMainWindowInputFocusRecovery.test.ts new file mode 100644 index 000000000..5cba2c3ab --- /dev/null +++ b/application/state/useMainWindowInputFocusRecovery.test.ts @@ -0,0 +1,53 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import test from "node:test"; + +const root = fileURLToPath(new URL("../..", import.meta.url)); + +function readProjectFile(path: string): string { + return readFileSync(join(root, path), "utf8"); +} + +test("useMainWindowInputFocusRecovery listens for visibility and window focus", () => { + const source = readProjectFile("application/state/useMainWindowInputFocusRecovery.ts"); + + assert.match(source, /document\.visibilityState !== "visible"/); + assert.match(source, /scheduleWindowInputFocus\(\)/); + assert.match(source, /document\.addEventListener\("visibilitychange", onVisibilityChange\)/); + assert.match(source, /window\.addEventListener\("focus", recoverFocus\)/); +}); + +test("useMainWindowInputFocusRecovery dismisses transient UI when the page hides", () => { + const source = readProjectFile("application/state/useMainWindowInputFocusRecovery.ts"); + + assert.match(source, /document\.visibilityState === "hidden"/); + assert.match(source, /onPageHidden\?\.\(\)/); + assert.match(source, /onWindowShown/); + assert.match(source, /onWindowWillHide/); + assert.match(source, /cancelPendingFocusRecovery/); +}); + +test("scheduleWindowInputFocus skips deferred focus when the page is hidden", () => { + const source = readProjectFile("application/state/windowInputFocus.ts"); + + assert.match(source, /document\.visibilityState !== "visible"/); + assert.match(source, /cancelAnimationFrame/); + assert.match(source, /clearTimeout/); +}); + +test("AppView mounts main-window input focus recovery with overlay dismiss", () => { + const source = readProjectFile("application/app/AppView.tsx"); + + assert.match(source, /useMainWindowInputFocusRecovery\(\{ onPageHidden: dismissTransientOverlays \}\)/); + assert.match(source, /setIsQuickSwitcherOpen\(false\)/); + assert.match(source, /setProtocolSelectHost\(null\)/); +}); + +test("dropdown closes when the document becomes hidden", () => { + const source = readProjectFile("components/ui/dropdown.tsx"); + + assert.match(source, /document\.visibilityState === "hidden"/); + assert.match(source, /setOpen\(false\)/); +}); diff --git a/application/state/useMainWindowInputFocusRecovery.ts b/application/state/useMainWindowInputFocusRecovery.ts new file mode 100644 index 000000000..df96cc2a1 --- /dev/null +++ b/application/state/useMainWindowInputFocusRecovery.ts @@ -0,0 +1,69 @@ +import { useEffect } from "react"; + +import { netcattyBridge } from "../../infrastructure/services/netcattyBridge"; +import { + scheduleWindowInputFocus, + type ScheduledWindowInputFocus, +} from "./windowInputFocus"; + +export type MainWindowInputFocusRecoveryOptions = { + /** Close transient overlays before the window hides (#1722). */ + onPageHidden?: () => void; +}; + +/** + * Recover OS/renderer input focus when the main window returns from hide, + * another app, or a virtual desktop (#760, #1714, #1722). + */ +export function useMainWindowInputFocusRecovery( + options: MainWindowInputFocusRecoveryOptions = {}, +): void { + const { onPageHidden } = options; + + useEffect(() => { + let pendingFocusRecovery: ScheduledWindowInputFocus | null = null; + + const cancelPendingFocusRecovery = () => { + pendingFocusRecovery?.cancel(); + pendingFocusRecovery = null; + }; + + const recoverFocus = () => { + if (document.visibilityState !== "visible") return; + cancelPendingFocusRecovery(); + pendingFocusRecovery = scheduleWindowInputFocus(); + }; + + const dismissTransientUi = () => { + cancelPendingFocusRecovery(); + onPageHidden?.(); + }; + + const onVisibilityChange = () => { + if (document.visibilityState === "hidden") { + dismissTransientUi(); + return; + } + recoverFocus(); + }; + + document.addEventListener("visibilitychange", onVisibilityChange); + window.addEventListener("focus", recoverFocus); + + const bridge = netcattyBridge.get(); + const unsubscribeShown = bridge?.onWindowShown?.(() => { + recoverFocus(); + }); + const unsubscribeWillHide = bridge?.onWindowWillHide?.(() => { + dismissTransientUi(); + }); + + return () => { + cancelPendingFocusRecovery(); + document.removeEventListener("visibilitychange", onVisibilityChange); + window.removeEventListener("focus", recoverFocus); + unsubscribeShown?.(); + unsubscribeWillHide?.(); + }; + }, [onPageHidden]); +} diff --git a/application/state/windowInputFocus.ts b/application/state/windowInputFocus.ts index 97d56db2d..6e56db8bd 100644 --- a/application/state/windowInputFocus.ts +++ b/application/state/windowInputFocus.ts @@ -9,17 +9,49 @@ export const requestWindowInputFocus = (): void => { } }; -export const scheduleWindowInputFocus = (): void => { - const scheduleFrame: (callback: () => void) => unknown = +export type ScheduledWindowInputFocus = { + cancel: () => void; +}; + +export const scheduleWindowInputFocus = (): ScheduledWindowInputFocus => { + let cancelled = false; + let frameId: number | undefined; + let timeoutId: ReturnType | undefined; + + const cancel = () => { + cancelled = true; + if (frameId !== undefined && typeof cancelAnimationFrame === "function") { + cancelAnimationFrame(frameId); + frameId = undefined; + } + if (timeoutId !== undefined) { + clearTimeout(timeoutId); + timeoutId = undefined; + } + }; + + const runIfVisible = () => { + if (cancelled || document.visibilityState !== "visible") return; + requestWindowInputFocus(); + }; + + const scheduleFrame: (callback: FrameRequestCallback) => number = typeof requestAnimationFrame === "function" ? requestAnimationFrame : (callback) => { - callback(); - return undefined; + callback(0); + return 0; }; - scheduleFrame(() => { - requestWindowInputFocus(); - setTimeout(requestWindowInputFocus, 50); + frameId = scheduleFrame(() => { + frameId = undefined; + runIfVisible(); + if (cancelled) return; + timeoutId = setTimeout(() => { + timeoutId = undefined; + runIfVisible(); + }, 50); }); + + return { cancel }; }; diff --git a/components/ui/dropdown.tsx b/components/ui/dropdown.tsx index a9e43ac0a..a012bc0f1 100644 --- a/components/ui/dropdown.tsx +++ b/components/ui/dropdown.tsx @@ -50,6 +50,16 @@ const Dropdown: React.FC = ({ [controlledOpen, onOpenChange], ); + useEffect(() => { + const closeOnPageHidden = () => { + if (document.visibilityState === "hidden") { + setOpen(false); + } + }; + document.addEventListener("visibilitychange", closeOnPageHidden); + return () => document.removeEventListener("visibilitychange", closeOnPageHidden); + }, [setOpen]); + return ( {children} diff --git a/electron/bridges/globalShortcutBridge.cjs b/electron/bridges/globalShortcutBridge.cjs index cc339badc..f64f62911 100644 --- a/electron/bridges/globalShortcutBridge.cjs +++ b/electron/bridges/globalShortcutBridge.cjs @@ -87,6 +87,8 @@ function performPendingFullscreenHide(win) { clearPendingFullscreenHide(win); try { + const windowManager = require("./windowManager.cjs"); + windowManager.notifyWindowWillHide?.(win); win.hide(); return "hidden"; } catch (err) { @@ -161,19 +163,21 @@ function startPendingFullscreenHideWatchdog(win) { }, FULLSCREEN_LEAVE_WATCHDOG_MS); } -function openMainWindow() { - const { app } = electronModule; - const win = getMainWindow(); - if (!win) return; +function bringMainWindowToForeground(win) { + if (!win || win.isDestroyed?.()) return false; clearPendingFullscreenHide(win); - if (win.isMinimized()) win.restore(); - win.show(); - win.focus(); + const windowManager = require("./windowManager.cjs"); + const focused = windowManager.showAndFocusMainWindow?.(win) ?? false; try { - app.focus({ steal: true }); + electronModule?.app?.focus?.({ steal: true }); } catch { // ignore } + return focused; +} + +function openMainWindow() { + bringMainWindowToForeground(getMainWindow()); } function getTrayPanelUrl() { @@ -404,6 +408,8 @@ function hideWindowRespectingMacFullscreen(win) { } try { + const windowManager = require("./windowManager.cjs"); + windowManager.notifyWindowWillHide?.(win); win.hide(); return true; } catch (err) { @@ -477,42 +483,18 @@ function toggleWindowVisibility() { try { // Check if window is minimized first - minimized windows may still report isVisible() = true if (win.isMinimized()) { - clearPendingFullscreenHide(win); - win.restore(); - win.show(); - win.focus(); - const { app } = electronModule; - try { - app.focus({ steal: true }); - } catch { - // ignore - } + bringMainWindowToForeground(win); } else if (win.isVisible()) { if (win.isFocused()) { // Window is visible and focused - hide it hideWindowRespectingMacFullscreen(win); } else { // Window is visible but not focused - focus it - clearPendingFullscreenHide(win); - win.focus(); - const { app } = electronModule; - try { - app.focus({ steal: true }); - } catch { - // ignore - } + bringMainWindowToForeground(win); } } else { // Window is hidden - show and focus it - clearPendingFullscreenHide(win); - win.show(); - win.focus(); - const { app } = electronModule; - try { - app.focus({ steal: true }); - } catch { - // ignore - } + bringMainWindowToForeground(win); } } catch (err) { console.warn("[GlobalShortcut] Error toggling window visibility:", err); @@ -687,10 +669,7 @@ function buildTrayMenuTemplate() { click: () => { // Focus window and switch to this session const win = getMainWindow(); - if (win) { - if (win.isMinimized()) win.restore(); - win.show(); - win.focus(); + if (win && bringMainWindowToForeground(win)) { // Notify renderer to focus this session win.webContents?.send("netcatty:tray:focusSession", session.id); } diff --git a/electron/bridges/globalShortcutBridge.test.cjs b/electron/bridges/globalShortcutBridge.test.cjs index 89570d093..6f9d508f4 100644 --- a/electron/bridges/globalShortcutBridge.test.cjs +++ b/electron/bridges/globalShortcutBridge.test.cjs @@ -554,3 +554,125 @@ test("tray icon event registration is platform-dependent", async () => { bridge.cleanup(); }); }); + +test("toggleWindowVisibility show path delegates to showAndFocusMainWindow on win32", async () => { + await withPlatform("win32", async () => { + const windowManagerPath = require.resolve("./windowManager.cjs"); + const actualWindowManager = require(windowManagerPath); + const showCalls = []; + let appFocusCalls = 0; + + require.cache[windowManagerPath].exports = { + ...actualWindowManager, + showAndFocusMainWindow(win) { + showCalls.push(win); + return true; + }, + }; + + try { + const bridge = loadBridge(); + const electronModule = createElectronStub(); + electronModule.app.focus = () => { + appFocusCalls += 1; + }; + const win = new FakeWindow(); + win.visible = false; + win.focused = false; + electronModule.BrowserWindow.getAllWindows = () => [win]; + let toggleWindow = null; + electronModule.globalShortcut.register = (_accelerator, handler) => { + toggleWindow = handler; + return true; + }; + const { ipcMain } = await enableCloseToTray(bridge, electronModule); + await ipcMain.handlers.get("netcatty:globalHotkey:register")(null, { hotkey: "Ctrl + `" }); + + assert.ok(toggleWindow, "expected global hotkey handler to register"); + toggleWindow(); + + assert.equal(showCalls.length, 1); + assert.equal(showCalls[0], win); + assert.equal(appFocusCalls, 1); + assert.equal(win.showCalls, 0, "should not call bare win.show()"); + assert.equal(win.focusCalls, 0, "should not call bare win.focus()"); + } finally { + require.cache[windowManagerPath].exports = actualWindowManager; + } + }); +}); + +test("openMainWindow delegates to showAndFocusMainWindow on win32", async () => { + await withPlatform("win32", async () => { + const windowManagerPath = require.resolve("./windowManager.cjs"); + const actualWindowManager = require(windowManagerPath); + const showCalls = []; + + require.cache[windowManagerPath].exports = { + ...actualWindowManager, + showAndFocusMainWindow(win) { + showCalls.push(win); + return true; + }, + }; + + try { + const bridge = loadBridge(); + const electronModule = createElectronStub(); + electronModule.app.focus = () => {}; + const win = new FakeWindow(); + win.visible = false; + electronModule.BrowserWindow.getAllWindows = () => [win]; + const { ipcMain } = await enableCloseToTray(bridge, electronModule); + + await ipcMain.handlers.get("netcatty:trayPanel:openMainWindow")(); + + assert.equal(showCalls.length, 1); + assert.equal(showCalls[0], win); + assert.equal(win.showCalls, 0); + assert.equal(win.focusCalls, 0); + } finally { + require.cache[windowManagerPath].exports = actualWindowManager; + } + }); +}); + +test("toggleWindowVisibility focuses visible-but-unfocused windows via showAndFocusMainWindow", async () => { + await withPlatform("win32", async () => { + const windowManagerPath = require.resolve("./windowManager.cjs"); + const actualWindowManager = require(windowManagerPath); + const showCalls = []; + + require.cache[windowManagerPath].exports = { + ...actualWindowManager, + showAndFocusMainWindow(win) { + showCalls.push(win); + return true; + }, + }; + + try { + const bridge = loadBridge(); + const electronModule = createElectronStub(); + electronModule.app.focus = () => {}; + const win = new FakeWindow(); + win.visible = true; + win.focused = false; + electronModule.BrowserWindow.getAllWindows = () => [win]; + let toggleWindow = null; + electronModule.globalShortcut.register = (_accelerator, handler) => { + toggleWindow = handler; + return true; + }; + const { ipcMain } = await enableCloseToTray(bridge, electronModule); + await ipcMain.handlers.get("netcatty:globalHotkey:register")(null, { hotkey: "Ctrl + `" }); + + toggleWindow(); + + assert.equal(showCalls.length, 1); + assert.equal(win.hideCalls, 0); + } finally { + require.cache[windowManagerPath].exports = actualWindowManager; + } + }); +}); diff --git a/electron/bridges/windowManager.cjs b/electron/bridges/windowManager.cjs index 3d26c7b16..a310afa82 100644 --- a/electron/bridges/windowManager.cjs +++ b/electron/bridges/windowManager.cjs @@ -6,6 +6,8 @@ const path = require("node:path"); const fs = require("node:fs"); +const { safeSend } = require("./ipcUtils.cjs"); + const V8_CACHE_OPTIONS = "bypassHeatCheck"; function getGlobalShortcutBridge() { @@ -1225,6 +1227,32 @@ function getSettingsWindow() { return settingsWindow; } +/** + * Show the main window and restore reliable keyboard/caret routing (#760, #1722). + * Global hotkeys and tray entry points invoke this from non-foreground contexts + * where bare BrowserWindow.focus() is silently rejected on Windows. + */ +function showAndFocusMainWindow(win) { + if (!win || win.isDestroyed?.()) return false; + if (win.isMinimized?.()) { + try { + win.restore(); + } catch { + // ignore + } + } + return restoreWindowInputFocus(win, { show: true }); +} + +/** + * Tell the renderer to dismiss transient overlays before the native hide (#1722). + * Must run before BrowserWindow.hide(), not from Electron's post-hide event. + */ +function notifyWindowWillHide(win) { + if (!win || win.isDestroyed?.()) return; + safeSend(win.webContents, "netcatty:window:will-hide"); +} + module.exports = { createWindow, openSettingsWindow, @@ -1246,6 +1274,8 @@ module.exports = { isWindowUsable, registerWindowHandlers, restoreWindowInputFocus, + showAndFocusMainWindow, + notifyWindowWillHide, requestWindowCommandClose, shouldCloseWindowFromInput, WINDOW_COMMAND_CLOSE_CHANNEL, diff --git a/electron/bridges/windowManager/mainWindow.cjs b/electron/bridges/windowManager/mainWindow.cjs index a2ac10322..03cde7bd5 100644 --- a/electron/bridges/windowManager/mainWindow.cjs +++ b/electron/bridges/windowManager/mainWindow.cjs @@ -338,6 +338,10 @@ function createMainWindowApi(ctx) { updateNormalBounds(); scheduleSaveState(); }); + + win.on("show", () => { + safeSend("netcatty:window:shown"); + }); // Ensure native background matches frontend background, even before first paint. try { diff --git a/electron/bridges/windowManagerReadiness.test.cjs b/electron/bridges/windowManagerReadiness.test.cjs index 7ef4a8e03..a863a7b55 100644 --- a/electron/bridges/windowManagerReadiness.test.cjs +++ b/electron/bridges/windowManagerReadiness.test.cjs @@ -10,6 +10,8 @@ const { registerWindowHandlers, resolveSettingsWindowBounds, restoreWindowInputFocus, + showAndFocusMainWindow, + notifyWindowWillHide, requestWindowCommandClose, sendWhenRendererReady, shouldCloseWindowFromInput, @@ -216,6 +218,61 @@ test("restoreWindowInputFocus can show the window when requested", () => { assert.deepEqual(calls, ["show", "focus", "webContents.focus"]); }); +test("showAndFocusMainWindow restores minimized windows before focusing", () => { + const calls = []; + const win = { + isDestroyed() { + return false; + }, + isMinimized() { + return true; + }, + restore() { + calls.push("restore"); + }, + show() { + calls.push("show"); + }, + focus() { + calls.push("focus"); + }, + webContents: { + isDestroyed() { + return false; + }, + focus() { + calls.push("webContents.focus"); + }, + }, + }; + + const restored = showAndFocusMainWindow(win); + + assert.equal(restored, true); + assert.deepEqual(calls, ["restore", "show", "focus", "webContents.focus"]); +}); + +test("notifyWindowWillHide sends will-hide IPC before native hide", () => { + const sent = []; + const win = { + isDestroyed() { + return false; + }, + webContents: { + isDestroyed() { + return false; + }, + send(channel) { + sent.push(channel); + }, + }, + }; + + notifyWindowWillHide(win); + + assert.deepEqual(sent, ["netcatty:window:will-hide"]); +}); + test("buildAppMenu closes a non-app window directly when Cmd+W is invoked", () => { let capturedTemplate = null; const Menu = { diff --git a/electron/main.cjs b/electron/main.cjs index e04c69633..afa47670a 100644 --- a/electron/main.cjs +++ b/electron/main.cjs @@ -354,15 +354,7 @@ function focusMainWindow() { getGlobalShortcutBridge().clearPendingFullscreenHide?.(win); } catch {} - try { - if (win.isMinimized && win.isMinimized()) win.restore(); - } catch {} - try { - win.show(); - } catch {} - try { - win.focus(); - } catch {} + getWindowManager().showAndFocusMainWindow?.(win); try { app.focus({ steal: true }); } catch {} @@ -827,9 +819,7 @@ if (!gotLock) { try { getGlobalShortcutBridge().clearPendingFullscreenHide?.(mainWin); } catch {} - if (mainWin.isMinimized?.()) mainWin.restore(); - mainWin.show?.(); - mainWin.focus?.(); + getWindowManager().showAndFocusMainWindow?.(mainWin); try { app.focus({ steal: true }); } catch {} diff --git a/electron/preload.cjs b/electron/preload.cjs index fec02acd5..9cf766eec 100644 --- a/electron/preload.cjs +++ b/electron/preload.cjs @@ -27,6 +27,8 @@ const telnetAutoLoginCancelledListeners = new Map(); const telnetEchoModeListeners = new Map(); const languageChangeListeners = new Set(); const fullscreenChangeListeners = new Set(); +const windowShownListeners = new Set(); +const windowWillHideListeners = new Set(); const keyboardInteractiveListeners = new Set(); const hostKeyVerificationListeners = new Set(); const passphraseListeners = new Set(); @@ -285,6 +287,26 @@ ipcRenderer.on("netcatty:window:fullscreen-changed", (_event, isFullscreen) => { }); }); +ipcRenderer.on("netcatty:window:shown", () => { + windowShownListeners.forEach((cb) => { + try { + cb(); + } catch (err) { + console.error("Window shown callback failed", err); + } + }); +}); + +ipcRenderer.on("netcatty:window:will-hide", () => { + windowWillHideListeners.forEach((cb) => { + try { + cb(); + } catch (err) { + console.error("Window will-hide callback failed", err); + } + }); +}); + // Authentication failed events @@ -680,6 +702,8 @@ const api = createPreloadApi({ terminalDataBacklog, languageChangeListeners, fullscreenChangeListeners, + windowShownListeners, + windowWillHideListeners, keyboardInteractiveListeners, hostKeyVerificationListeners, passphraseListeners, diff --git a/electron/preload/api.cjs b/electron/preload/api.cjs index d1a3532ef..1a75e5314 100644 --- a/electron/preload/api.cjs +++ b/electron/preload/api.cjs @@ -508,6 +508,14 @@ function createPreloadApi(ctx) { fullscreenChangeListeners.add(cb); return () => fullscreenChangeListeners.delete(cb); }, + onWindowShown: (cb) => { + windowShownListeners.add(cb); + return () => windowShownListeners.delete(cb); + }, + onWindowWillHide: (cb) => { + windowWillHideListeners.add(cb); + return () => windowWillHideListeners.delete(cb); + }, // Settings window openSettingsWindow: () => ipcRenderer.invoke("netcatty:settings:open"), diff --git a/types/global/netcatty-bridge-sync.d.ts b/types/global/netcatty-bridge-sync.d.ts index c1f29a3df..3f2fc2e2f 100644 --- a/types/global/netcatty-bridge-sync.d.ts +++ b/types/global/netcatty-bridge-sync.d.ts @@ -26,6 +26,8 @@ declare global { }) => void): () => void; onWindowCommandCloseRequested?(cb: () => void): () => void; onWindowFullScreenChanged?(cb: (isFullscreen: boolean) => void): () => void; + onWindowShown?(cb: () => void): () => void; + onWindowWillHide?(cb: () => void): () => void; // Settings window openSettingsWindow?(): Promise; From 2dac87f56e431f204c792b1f602399c5cfa7bf76 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 19:31:26 +0800 Subject: [PATCH 094/228] fix ai command permission splitting --- electron/capabilities/policy.test.cjs | 279 ++++++++++ electron/shared/permissionGrants.cjs | 486 +++++++++++++++++- .../ai/harness/permissionGrants.test.ts | 321 ++++++++++++ infrastructure/ai/harness/permissionGrants.ts | 44 +- .../ai/shared/shellCommandGrant.test.ts | 123 +++++ infrastructure/ai/shared/shellCommandGrant.ts | 460 ++++++++++++++++- 6 files changed, 1686 insertions(+), 27 deletions(-) diff --git a/electron/capabilities/policy.test.cjs b/electron/capabilities/policy.test.cjs index 268e9ba9a..971bf60a7 100644 --- a/electron/capabilities/policy.test.cjs +++ b/electron/capabilities/policy.test.cjs @@ -195,3 +195,282 @@ test("evaluatePermissionWithGrants skips approval when a grant matches", () => { assert.equal(decision.allowed, true); assert.equal(decision.requiresApproval, false); }); + +test("evaluatePermissionWithGrants does not let a comment grant approve a multiline command", () => { + const decision = evaluatePermissionWithGrants({ + rpcMethod: "netcatty/exec", + permissionMode: PERMISSION_MODES.CONFIRM, + params: { + chatSessionId: "chat-1", + sessionId: "session-a", + command: [ + "# 1a) clear the kernel_options_post profile field", + "cobbler profile edit --name=openEuler-22.03-aarch64 --kernel-options-post=\"\"", + ].join("\n"), + }, + context: { chatSessionCancelled: false }, + }, [{ + id: "grant-comment", + capabilityId: "terminal.execute", + sessionPattern: "session-a", + commandPattern: "# *", + createdAt: Date.now(), + }]); + + assert.equal(decision.allowed, true); + assert.equal(decision.requiresApproval, true); +}); + +test("evaluatePermissionWithGrants does not let a here-doc body grant approve the command", () => { + const decision = evaluatePermissionWithGrants({ + rpcMethod: "netcatty/exec", + permissionMode: PERMISSION_MODES.CONFIRM, + params: { + chatSessionId: "chat-1", + sessionId: "session-a", + command: [ + "cat <<'EOF'", + "rm -rf /tmp/demo", + "EOF", + ].join("\n"), + }, + context: { chatSessionCancelled: false }, + }, [{ + id: "grant-rm", + capabilityId: "terminal.execute", + sessionPattern: "session-a", + commandPattern: "rm *", + createdAt: Date.now(), + }]); + + assert.equal(decision.allowed, true); + assert.equal(decision.requiresApproval, true); +}); + +test("evaluatePermissionWithGrants does not let a piped here-doc body grant approve the command", () => { + const decision = evaluatePermissionWithGrants({ + rpcMethod: "netcatty/exec", + permissionMode: PERMISSION_MODES.CONFIRM, + params: { + chatSessionId: "chat-1", + sessionId: "session-a", + command: [ + "cat < { + const decision = evaluatePermissionWithGrants({ + rpcMethod: "netcatty/exec", + permissionMode: PERMISSION_MODES.CONFIRM, + params: { + chatSessionId: "chat-1", + sessionId: "session-a", + command: [ + "cat 0< { + const decision = evaluatePermissionWithGrants({ + rpcMethod: "netcatty/exec", + permissionMode: PERMISSION_MODES.CONFIRM, + params: { + chatSessionId: "chat-1", + sessionId: "session-a", + command: "cd /tmp; sleep 1 & rm -rf demo", + }, + context: { chatSessionCancelled: false }, + }, [{ + id: "grant-sleep", + capabilityId: "terminal.execute", + sessionPattern: "session-a", + commandPattern: "sleep *", + createdAt: Date.now(), + }]); + + assert.equal(decision.allowed, true); + assert.equal(decision.requiresApproval, true); +}); + +test("evaluatePermissionWithGrants does not let cwd substitutions hide before a later grant", () => { + const decision = evaluatePermissionWithGrants({ + rpcMethod: "netcatty/exec", + permissionMode: PERMISSION_MODES.CONFIRM, + params: { + chatSessionId: "chat-1", + sessionId: "session-a", + command: "cd \"$(pwd)\"; ls -la", + }, + context: { chatSessionCancelled: false }, + }, [{ + id: "grant-ls", + capabilityId: "terminal.execute", + sessionPattern: "session-a", + commandPattern: "ls *", + createdAt: Date.now(), + }]); + + assert.equal(decision.allowed, true); + assert.equal(decision.requiresApproval, true); +}); + +test("evaluatePermissionWithGrants does not let quoted here-doc operator text hide later commands", () => { + const decision = evaluatePermissionWithGrants({ + rpcMethod: "netcatty/exec", + permissionMode: PERMISSION_MODES.CONFIRM, + params: { + chatSessionId: "chat-1", + sessionId: "session-a", + command: [ + "cd /tmp; echo '< { + const decision = evaluatePermissionWithGrants({ + rpcMethod: "netcatty/exec", + permissionMode: PERMISSION_MODES.CONFIRM, + params: { + chatSessionId: "chat-1", + sessionId: "session-a", + command: [ + "cat < { + const decision = evaluatePermissionWithGrants({ + rpcMethod: "netcatty/exec", + permissionMode: PERMISSION_MODES.CONFIRM, + params: { + chatSessionId: "chat-1", + sessionId: "session-a", + command: [ + "ls $((1 << 2))", + "rm -rf demo", + ].join("\n"), + }, + context: { chatSessionCancelled: false }, + }, [{ + id: "grant-ls", + capabilityId: "terminal.execute", + sessionPattern: "session-a", + commandPattern: "ls *", + createdAt: Date.now(), + }]); + + assert.equal(decision.allowed, true); + assert.equal(decision.requiresApproval, true); +}); + +test("evaluatePermissionWithGrants keeps commands after ANSI-C quoted here-doc delimiters grantable", () => { + const decision = evaluatePermissionWithGrants({ + rpcMethod: "netcatty/exec", + permissionMode: PERMISSION_MODES.CONFIRM, + params: { + chatSessionId: "chat-1", + sessionId: "session-a", + command: [ + "cat <<$'E\\x4fF'", + "body text", + "EOF", + "rm -rf demo", + ].join("\n"), + }, + context: { chatSessionCancelled: false }, + }, [{ + id: "grant-cat", + capabilityId: "terminal.execute", + sessionPattern: "session-a", + commandPattern: "cat *", + createdAt: Date.now(), + }]); + + assert.equal(decision.allowed, true); + assert.equal(decision.requiresApproval, true); +}); + +test("evaluatePermissionWithGrants keeps commands after dollar-quoted here-doc delimiters grantable", () => { + const decision = evaluatePermissionWithGrants({ + rpcMethod: "netcatty/exec", + permissionMode: PERMISSION_MODES.CONFIRM, + params: { + chatSessionId: "chat-1", + sessionId: "session-a", + command: [ + "cat <<$'EOF'", + "body text", + "EOF", + "rm -rf demo", + ].join("\n"), + }, + context: { chatSessionCancelled: false }, + }, [{ + id: "grant-cat", + capabilityId: "terminal.execute", + sessionPattern: "session-a", + commandPattern: "cat *", + createdAt: Date.now(), + }]); + + assert.equal(decision.allowed, true); + assert.equal(decision.requiresApproval, true); +}); diff --git a/electron/shared/permissionGrants.cjs b/electron/shared/permissionGrants.cjs index 829add637..e301e6fdc 100644 --- a/electron/shared/permissionGrants.cjs +++ b/electron/shared/permissionGrants.cjs @@ -57,20 +57,496 @@ function argsPatternMatches(argsPattern, args) { return true; } +const CWD_COMMANDS = new Set([ + "cd", + "chdir", + "popd", + "pushd", + "push-location", + "set-location", +]); + +function unquoteShellToken(token) { + if (token.length >= 2) { + const first = token[0]; + const last = token[token.length - 1]; + if ((first === "\"" || first === "'") && first === last) { + return token.slice(1, -1); + } + } + return token; +} + +function tokenizeShellCommand(command) { + const matches = command.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g) || []; + return matches.map(unquoteShellToken); +} + +function lastNonWhitespaceChar(value) { + return value.match(/\S(?=\s*$)/)?.[0]; +} + +function readArithmeticExpansionEnd(segment, startIndex) { + if (segment[startIndex] !== "$" || segment[startIndex + 1] !== "(" || segment[startIndex + 2] !== "(") { + return null; + } + + let depth = 1; + let quote = null; + + for (let index = startIndex + 3; index < segment.length; index += 1) { + const char = segment[index]; + const next = segment[index + 1]; + + if (quote) { + if (char === "\\" && quote !== "'" && next) { + index += 1; + continue; + } + if (char === quote) quote = null; + continue; + } + + if (char === "\\" && next) { + index += 1; + continue; + } + + if (char === "\"" || char === "'" || char === "`") { + quote = char; + continue; + } + + if (char === "(") { + depth += 1; + continue; + } + + if (char === ")") { + if (depth === 1 && next === ")") return index + 2; + if (depth > 1) depth -= 1; + } + } + + return segment.length; +} + +function hasExecutableShellExpansion(segment) { + let quote = null; + + for (let index = 0; index < segment.length; index += 1) { + const char = segment[index]; + const next = segment[index + 1]; + + if (quote) { + if (char === "\\" && quote === "\"" && next) { + index += 1; + continue; + } + if (char === quote) { + quote = null; + continue; + } + if (quote === "\"" && char === "$" && next === "(") return true; + if (quote === "\"" && char === "`") return true; + continue; + } + + if (char === "\\" && next) { + index += 1; + continue; + } + + if (char === "'") { + quote = char; + continue; + } + + if (char === "\"") { + quote = char; + continue; + } + + if (char === "`") return true; + if (char === "$" && next === "(") return true; + if ((char === "<" || char === ">") && next === "(") return true; + } + + return false; +} + +function readEscapeDigits(value, startIndex, maxLength, pattern) { + let endIndex = startIndex; + while ( + endIndex < value.length + && endIndex < startIndex + maxLength + && pattern.test(value[endIndex]) + ) { + endIndex += 1; + } + + if (endIndex === startIndex) return null; + return { digits: value.slice(startIndex, endIndex), endIndex: endIndex - 1 }; +} + +function codePointToString(codePoint) { + try { + return String.fromCodePoint(codePoint); + } catch { + return ""; + } +} + +function readAnsiCEscape(value, backslashIndex) { + const escapeIndex = backslashIndex + 1; + const char = value[escapeIndex]; + if (!char) return { text: "\\", endIndex: backslashIndex }; + + const simpleEscapes = { + a: "\x07", + b: "\b", + e: "\x1B", + E: "\x1B", + f: "\f", + n: "\n", + r: "\r", + t: "\t", + v: "\v", + "\\": "\\", + "'": "'", + "\"": "\"", + "?": "?", + }; + + const simple = simpleEscapes[char]; + if (simple !== undefined) return { text: simple, endIndex: escapeIndex }; + + if (char === "x") { + const digits = readEscapeDigits(value, escapeIndex + 1, 2, /[0-9a-fA-F]/); + if (!digits) return { text: "\\x", endIndex: escapeIndex }; + return { + text: codePointToString(Number.parseInt(digits.digits, 16)), + endIndex: digits.endIndex, + }; + } + + if (char === "u" || char === "U") { + const digits = readEscapeDigits(value, escapeIndex + 1, char === "u" ? 4 : 8, /[0-9a-fA-F]/); + if (!digits) return { text: `\\${char}`, endIndex: escapeIndex }; + return { + text: codePointToString(Number.parseInt(digits.digits, 16)), + endIndex: digits.endIndex, + }; + } + + if (/[0-7]/.test(char)) { + const digits = readEscapeDigits(value, escapeIndex, 3, /[0-7]/); + return { + text: codePointToString(Number.parseInt(digits.digits, 8)), + endIndex: digits.endIndex, + }; + } + + return { text: `\\${char}`, endIndex: escapeIndex }; +} + +function readHereDocDelimiterWord(segment, startIndex) { + let index = startIndex; + while (index < segment.length && /\s/.test(segment[index])) index += 1; + + let text = ""; + let quote = null; + let ansiQuote = false; + + for (; index < segment.length; index += 1) { + const char = segment[index]; + const next = segment[index + 1]; + + if (quote) { + if (ansiQuote && char === "\\") { + const escape = readAnsiCEscape(segment, index); + text += escape.text; + index = escape.endIndex; + continue; + } + if (char === "\\" && quote !== "'" && next) { + text += next; + index += 1; + continue; + } + if (char === quote) { + quote = null; + ansiQuote = false; + continue; + } + text += char; + continue; + } + + if (/\s/.test(char) || char === ";" || char === "|" || char === "&") break; + + if (char === "\\" && next) { + text += next; + index += 1; + continue; + } + + if (char === "$" && (next === "'" || next === "\"")) { + quote = next; + ansiQuote = next === "'"; + index += 1; + continue; + } + + if (char === "\"" || char === "'" || char === "`") { + quote = char; + ansiQuote = false; + continue; + } + + text += char; + } + + return text ? { text, endIndex: index } : null; +} + +function extractHereDocTerminators(segment) { + const terminators = []; + let quote = null; + + for (let index = 0; index < segment.length; index += 1) { + const char = segment[index]; + const next = segment[index + 1]; + + if (quote) { + if (char === "\\" && quote !== "'" && next) { + index += 1; + continue; + } + if (char === quote) quote = null; + continue; + } + + const arithmeticEnd = readArithmeticExpansionEnd(segment, index); + if (arithmeticEnd !== null) { + index = arithmeticEnd - 1; + continue; + } + + if (char === "\\" && next) { + index += 1; + continue; + } + + if (char === "\"" || char === "'" || char === "`") { + quote = char; + continue; + } + + if (char !== "<" || next !== "<") continue; + if (segment[index + 2] === "<") { + index += 2; + continue; + } + + const stripLeadingTabs = segment[index + 2] === "-"; + const delimiterStart = index + (stripLeadingTabs ? 3 : 2); + const delimiter = readHereDocDelimiterWord(segment, delimiterStart); + if (!delimiter) continue; + terminators.push({ text: delimiter.text, stripLeadingTabs }); + index = delimiter.endIndex - 1; + } + + return terminators; +} + +function skipHereDocBodies(command, startIndex, terminators) { + let cursor = startIndex; + + for (const terminator of terminators) { + while (cursor < command.length) { + const lineEnd = command.indexOf("\n", cursor); + const end = lineEnd === -1 ? command.length : lineEnd; + const rawLine = command.slice(cursor, end); + const line = terminator.stripLeadingTabs ? rawLine.replace(/^\t+/, "") : rawLine; + cursor = lineEnd === -1 ? command.length : lineEnd + 1; + + if (line === terminator.text) break; + } + } + + return cursor; +} + +function splitShellCommandSegments(command) { + const segments = []; + let current = ""; + let quote = null; + let inComment = false; + let lineHereDocTerminators = []; + + const flush = () => { + const segment = current.trim(); + if (segment) segments.push(segment); + current = ""; + }; + + const flushCommandSegment = () => { + lineHereDocTerminators.push(...extractHereDocTerminators(current)); + flush(); + }; + + const finishLine = (bodyStartIndex) => { + flushCommandSegment(); + const hereDocTerminators = lineHereDocTerminators; + lineHereDocTerminators = []; + if (hereDocTerminators.length === 0) return bodyStartIndex; + return skipHereDocBodies(command, bodyStartIndex, hereDocTerminators); + }; + + for (let index = 0; index < command.length; index += 1) { + const char = command[index]; + const next = command[index + 1]; + + if (inComment) { + if (char === "\n") { + inComment = false; + index = finishLine(index + 1) - 1; + } + continue; + } + + if (quote) { + current += char; + if (char === "\\" && quote !== "'" && next) { + current += next; + index += 1; + continue; + } + if (char === quote) quote = null; + continue; + } + + if (char === "\\" && next === "\n") { + index += 1; + continue; + } + + if (char === "\\" && next) { + current += char + next; + index += 1; + continue; + } + + if (char === "\"" || char === "'" || char === "`") { + quote = char; + current += char; + continue; + } + + const arithmeticEnd = readArithmeticExpansionEnd(command, index); + if (arithmeticEnd !== null) { + current += command.slice(index, arithmeticEnd); + index = arithmeticEnd - 1; + continue; + } + + if (char === "#") { + const previous = current[current.length - 1]; + if (!previous || /\s/.test(previous)) { + inComment = true; + continue; + } + } + + if (char === "\n") { + index = finishLine(index + 1) - 1; + continue; + } + + if (char === ";") { + flushCommandSegment(); + continue; + } + + if (char === "&" && next === "&") { + flushCommandSegment(); + index += 1; + continue; + } + + if (char === "|" && next === "|") { + flushCommandSegment(); + index += 1; + continue; + } + + if (char === "&") { + const previous = lastNonWhitespaceChar(current); + if (next === ">" || previous === ">" || previous === "<") { + current += char; + continue; + } + flushCommandSegment(); + continue; + } + + if (char === "|") { + flushCommandSegment(); + if (next === "&") index += 1; + continue; + } + + current += char; + } + + flush(); + return segments; +} + +function extractGrantableShellCommandSegments(command) { + return splitShellCommandSegments(command).filter((segment) => { + const tokens = tokenizeShellCommand(segment); + const cmd = tokens[0] && tokens[0].toLowerCase(); + return tokens.length > 0 && !(cmd && CWD_COMMANDS.has(cmd) && !hasExecutableShellExpansion(segment)); + }); +} + +function matchCommandPatternGrants(rules, ctx, command, args) { + const commandSegments = extractGrantableShellCommandSegments(command); + if (commandSegments.length === 0) return null; + + const eligibleRules = rules.filter((rule) => ( + rule + && rule.capabilityId === ctx?.capabilityId + && rule.commandPattern + && argsPatternMatches(rule.argsPattern, args) + )); + if (eligibleRules.length === 0) return null; + + let firstMatch = null; + for (const segment of commandSegments) { + const matched = eligibleRules.find((rule) => patternMatches(rule.commandPattern, segment)); + if (!matched) return null; + if (!firstMatch) firstMatch = matched; + } + + return firstMatch; +} + function matchPermissionGrant(rules, ctx) { if (!Array.isArray(rules) || rules.length === 0) return null; const args = ctx?.args && typeof ctx.args === "object" ? ctx.args : {}; + const command = typeof args.command === "string" ? args.command : ""; + const commandGrantMatch = command ? matchCommandPatternGrants(rules, ctx, command, args) : null; + if (commandGrantMatch) return commandGrantMatch; for (const rule of rules) { if (!rule || typeof rule.capabilityId !== "string") continue; if (rule.capabilityId !== ctx?.capabilityId) continue; - - if (rule.commandPattern) { - const command = typeof args.command === "string" ? args.command : ""; - if (!patternMatches(rule.commandPattern, command)) continue; - } + if (rule.commandPattern) continue; if (!argsPatternMatches(rule.argsPattern, args)) continue; diff --git a/infrastructure/ai/harness/permissionGrants.test.ts b/infrastructure/ai/harness/permissionGrants.test.ts index 0bb56716f..f408f1a4c 100644 --- a/infrastructure/ai/harness/permissionGrants.test.ts +++ b/infrastructure/ai/harness/permissionGrants.test.ts @@ -66,6 +66,327 @@ describe('permissionGrants', () => { assert.equal(grants[0]?.commandPattern, 'lscpu *'); }); + it('does not let a comment grant approve a multiline command', () => { + const rules = [baseRule({ sessionPattern: '*', commandPattern: '# *' })]; + const matched = matchPermissionGrant(rules, { + capabilityId: 'terminal.execute', + sessionId: 'session-a', + args: { + command: [ + '# 1a) clear the kernel_options_post profile field', + 'cobbler profile edit --name=openEuler-22.03-aarch64 --kernel-options-post=""', + ].join('\n'), + }, + }); + + assert.equal(matched, null); + }); + + it('requires every grantable command segment to be covered', () => { + const rules = [ + baseRule({ id: 'grant-lscpu', sessionPattern: '*', commandPattern: 'lscpu *' }), + baseRule({ id: 'grant-grep', sessionPattern: '*', commandPattern: 'grep *' }), + ]; + const matched = matchPermissionGrant(rules, { + capabilityId: 'terminal.execute', + sessionId: 'session-a', + args: { command: 'cd /tmp && lscpu | grep CPU' }, + }); + + assert.ok(matched); + + const missingPipeSegment = matchPermissionGrant([rules[0]!], { + capabilityId: 'terminal.execute', + sessionId: 'session-a', + args: { command: 'cd /tmp && lscpu | grep CPU' }, + }); + + assert.equal(missingPipeSegment, null); + }); + + it('requires every background command segment to be covered', () => { + const command = 'cd /tmp; sleep 1 & rm -rf demo'; + + const matchedBySleepOnly = matchPermissionGrant([ + baseRule({ id: 'grant-sleep', sessionPattern: '*', commandPattern: 'sleep *' }), + ], { + capabilityId: 'terminal.execute', + sessionId: 'session-a', + args: { command }, + }); + + assert.equal(matchedBySleepOnly, null); + + const matchedByBoth = matchPermissionGrant([ + baseRule({ id: 'grant-sleep', sessionPattern: '*', commandPattern: 'sleep *' }), + baseRule({ id: 'grant-rm', sessionPattern: '*', commandPattern: 'rm *' }), + ], { + capabilityId: 'terminal.execute', + sessionId: 'session-a', + args: { command }, + }); + + assert.ok(matchedByBoth); + }); + + it('requires cwd segments with shell substitutions to be covered', () => { + const command = 'cd "$(pwd)"; ls -la'; + + const matchedByLsOnly = matchPermissionGrant([ + baseRule({ id: 'grant-ls', sessionPattern: '*', commandPattern: 'ls *' }), + ], { + capabilityId: 'terminal.execute', + sessionId: 'session-a', + args: { command }, + }); + + assert.equal(matchedByLsOnly, null); + + const matchedByBoth = matchPermissionGrant([ + baseRule({ id: 'grant-cd', sessionPattern: '*', commandPattern: 'cd *' }), + baseRule({ id: 'grant-ls', sessionPattern: '*', commandPattern: 'ls *' }), + ], { + capabilityId: 'terminal.execute', + sessionId: 'session-a', + args: { command }, + }); + + assert.ok(matchedByBoth); + }); + + it('does not let a here-doc body grant approve the wrapping command', () => { + const command = [ + "cat <<'EOF'", + 'rm -rf /tmp/demo', + 'EOF', + ].join('\n'); + + const matchedByBody = matchPermissionGrant([ + baseRule({ id: 'grant-rm', sessionPattern: '*', commandPattern: 'rm *' }), + ], { + capabilityId: 'terminal.execute', + sessionId: 'session-a', + args: { command }, + }); + + assert.equal(matchedByBody, null); + + const matchedByWrapper = matchPermissionGrant([ + baseRule({ id: 'grant-cat', sessionPattern: '*', commandPattern: 'cat *' }), + ], { + capabilityId: 'terminal.execute', + sessionId: 'session-a', + args: { command }, + }); + + assert.ok(matchedByWrapper); + }); + + it('does not let a piped here-doc body grant approve the command', () => { + const command = [ + 'cat < { + const command = [ + 'cat 0< { + const command = [ + "cd /tmp; echo '< { + const command = [ + 'cat < { + const command = [ + "cat <<$'EOF'", + 'body text', + 'EOF', + 'rm -rf demo', + ].join('\n'); + + const matchedByCatOnly = matchPermissionGrant([ + baseRule({ id: 'grant-cat', sessionPattern: '*', commandPattern: 'cat *' }), + ], { + capabilityId: 'terminal.execute', + sessionId: 'session-a', + args: { command }, + }); + + assert.equal(matchedByCatOnly, null); + + const matchedByBoth = matchPermissionGrant([ + baseRule({ id: 'grant-cat', sessionPattern: '*', commandPattern: 'cat *' }), + baseRule({ id: 'grant-rm', sessionPattern: '*', commandPattern: 'rm *' }), + ], { + capabilityId: 'terminal.execute', + sessionId: 'session-a', + args: { command }, + }); + + assert.ok(matchedByBoth); + }); + + it('keeps commands after ANSI-C quoted here-doc delimiters grantable', () => { + const command = [ + "cat <<$'E\\x4fF'", + 'body text', + 'EOF', + 'rm -rf demo', + ].join('\n'); + + const matchedByCatOnly = matchPermissionGrant([ + baseRule({ id: 'grant-cat', sessionPattern: '*', commandPattern: 'cat *' }), + ], { + capabilityId: 'terminal.execute', + sessionId: 'session-a', + args: { command }, + }); + + assert.equal(matchedByCatOnly, null); + + const matchedByBoth = matchPermissionGrant([ + baseRule({ id: 'grant-cat', sessionPattern: '*', commandPattern: 'cat *' }), + baseRule({ id: 'grant-rm', sessionPattern: '*', commandPattern: 'rm *' }), + ], { + capabilityId: 'terminal.execute', + sessionId: 'session-a', + args: { command }, + }); + + assert.ok(matchedByBoth); + }); + + it('does not let arithmetic shifts hide following commands', () => { + const command = [ + 'ls $((1 << 2))', + 'rm -rf demo', + ].join('\n'); + + const matchedByLsOnly = matchPermissionGrant([ + baseRule({ id: 'grant-ls', sessionPattern: '*', commandPattern: 'ls *' }), + ], { + capabilityId: 'terminal.execute', + sessionId: 'session-a', + args: { command }, + }); + + assert.equal(matchedByLsOnly, null); + + const matchedByBoth = matchPermissionGrant([ + baseRule({ id: 'grant-ls', sessionPattern: '*', commandPattern: 'ls *' }), + baseRule({ id: 'grant-rm', sessionPattern: '*', commandPattern: 'rm *' }), + ], { + capabilityId: 'terminal.execute', + sessionId: 'session-a', + args: { command }, + }); + + assert.ok(matchedByBoth); + }); + it('OpenCode wildcard allows optional args after prefix', () => { assert.equal(patternMatches('lscpu *', 'lscpu'), true); assert.equal(patternMatches('lscpu *', 'lscpu -e'), true); diff --git a/infrastructure/ai/harness/permissionGrants.ts b/infrastructure/ai/harness/permissionGrants.ts index e7d623db8..744f0426b 100644 --- a/infrastructure/ai/harness/permissionGrants.ts +++ b/infrastructure/ai/harness/permissionGrants.ts @@ -1,5 +1,8 @@ import cattyToolSpecs from './generated/cattyToolSpecs.json'; -import { buildAlwaysAllowCommandPatterns } from '../shared/shellCommandGrant'; +import { + buildAlwaysAllowCommandPatterns, + extractGrantableShellCommandSegments, +} from '../shared/shellCommandGrant'; export interface PermissionGrantRule { id: string; @@ -106,14 +109,13 @@ export function matchPermissionGrant( if (rules.length === 0) return null; const args = ctx.args ?? {}; + const command = typeof args.command === 'string' ? args.command : ''; + const commandGrantMatch = command ? matchCommandPatternGrants(rules, ctx, command, args) : null; + if (commandGrantMatch) return commandGrantMatch; for (const rule of rules) { if (rule.capabilityId !== ctx.capabilityId) continue; - - if (rule.commandPattern) { - const command = typeof args.command === 'string' ? args.command : ''; - if (!patternMatches(rule.commandPattern, command)) continue; - } + if (rule.commandPattern) continue; if (!argsPatternMatches(rule.argsPattern, args)) continue; @@ -123,6 +125,32 @@ export function matchPermissionGrant( return null; } +function matchCommandPatternGrants( + rules: readonly PermissionGrantRule[], + ctx: PermissionGrantMatchContext, + command: string, + args: Record, +): PermissionGrantRule | null { + const commandSegments = extractGrantableShellCommandSegments(command); + if (commandSegments.length === 0) return null; + + const eligibleRules = rules.filter((rule) => ( + rule.capabilityId === ctx.capabilityId + && Boolean(rule.commandPattern) + && argsPatternMatches(rule.argsPattern, args) + )); + if (eligibleRules.length === 0) return null; + + let firstMatch: PermissionGrantRule | null = null; + for (const segment of commandSegments) { + const matched = eligibleRules.find((rule) => patternMatches(rule.commandPattern!, segment)); + if (!matched) return null; + firstMatch ??= matched; + } + + return firstMatch; +} + export function sanitizePermissionGrants(raw: unknown): PermissionGrantRule[] { if (!Array.isArray(raw)) return []; @@ -215,7 +243,7 @@ export function buildGrantsFromApproval( const commandPatterns = resolveCommandGrantPatterns(capabilityId, args); const createdAt = Date.now(); - if (!commandPatterns || commandPatterns.length === 0) { + if (!commandPatterns) { return [{ id: createPermissionGrantId(), capabilityId, @@ -224,6 +252,8 @@ export function buildGrantsFromApproval( }]; } + if (commandPatterns.length === 0) return []; + return commandPatterns.map((commandPattern) => ({ id: createPermissionGrantId(), capabilityId, diff --git a/infrastructure/ai/shared/shellCommandGrant.test.ts b/infrastructure/ai/shared/shellCommandGrant.test.ts index dfe657064..c8cc8c099 100644 --- a/infrastructure/ai/shared/shellCommandGrant.test.ts +++ b/infrastructure/ai/shared/shellCommandGrant.test.ts @@ -20,4 +20,127 @@ describe('shellCommandGrant (OpenCode always patterns)', () => { ['ls *'], ); }); + + it('keeps cwd segments that execute shell substitutions grantable', () => { + assert.deepEqual( + buildAlwaysAllowCommandPatterns('cd "$(pwd)"; ls -la'), + ['cd *', 'ls *'], + ); + }); + + it('splits single ampersand background commands', () => { + assert.deepEqual( + buildAlwaysAllowCommandPatterns('cd /tmp; sleep 1 & rm -rf demo'), + ['sleep *', 'rm *'], + ); + }); + + it('ignores comments when building grants for multiline commands', () => { + const command = [ + '# 1a) clear the kernel_options_post profile field', + 'cobbler profile edit --name=openEuler-22.03-aarch64 --kernel-options-post=""', + '', + '# verify', + "cobbler profile report --name=openEuler-22.03-aarch64 | grep -i 'kernel.options'", + ].join('\n'); + + assert.deepEqual(buildAlwaysAllowCommandPatterns(command), ['cobbler *', 'grep *']); + }); + + it('does not build grants from here-doc body lines', () => { + const command = [ + "cat <<'EOF'", + 'rm -rf /tmp/demo', + 'EOF', + ].join('\n'); + + assert.deepEqual(buildAlwaysAllowCommandPatterns(command), ['cat *']); + }); + + it('does not build grants from piped here-doc body lines', () => { + const command = [ + 'cat < { + assert.deepEqual( + buildAlwaysAllowCommandPatterns([ + 'cat 0< { + assert.deepEqual( + buildAlwaysAllowCommandPatterns([ + "cd /tmp; echo '< { + assert.deepEqual( + buildAlwaysAllowCommandPatterns([ + 'cat < { + assert.deepEqual( + buildAlwaysAllowCommandPatterns([ + "cat <<$'EOF'", + 'body text', + 'EOF', + 'rm -rf demo', + ].join('\n')), + ['cat *', 'rm *'], + ); + }); + + it('resumes parsing after ANSI-C quoted here-doc delimiters', () => { + assert.deepEqual( + buildAlwaysAllowCommandPatterns([ + "cat <<$'E\\x4fF'", + 'body text', + 'EOF', + 'rm -rf demo', + ].join('\n')), + ['cat *', 'rm *'], + ); + }); + + it('does not treat arithmetic shifts as here-doc delimiters', () => { + assert.deepEqual( + buildAlwaysAllowCommandPatterns([ + 'ls $((1 << 2))', + 'rm -rf demo', + ].join('\n')), + ['ls *', 'rm *'], + ); + }); }); diff --git a/infrastructure/ai/shared/shellCommandGrant.ts b/infrastructure/ai/shared/shellCommandGrant.ts index 2f7ecc41c..cb765db56 100644 --- a/infrastructure/ai/shared/shellCommandGrant.ts +++ b/infrastructure/ai/shared/shellCommandGrant.ts @@ -26,11 +26,451 @@ export function tokenizeShellCommand(command: string): string[] { return matches.map(unquoteShellToken); } +type HereDocTerminator = { + text: string; + stripLeadingTabs: boolean; +}; + +function lastNonWhitespaceChar(value: string): string | undefined { + return value.match(/\S(?=\s*$)/)?.[0]; +} + +function readArithmeticExpansionEnd(segment: string, startIndex: number): number | null { + if (segment[startIndex] !== '$' || segment[startIndex + 1] !== '(' || segment[startIndex + 2] !== '(') { + return null; + } + + let depth = 1; + let quote: '"' | "'" | '`' | null = null; + + for (let index = startIndex + 3; index < segment.length; index += 1) { + const char = segment[index]!; + const next = segment[index + 1]; + + if (quote) { + if (char === '\\' && quote !== "'" && next) { + index += 1; + continue; + } + if (char === quote) quote = null; + continue; + } + + if (char === '\\' && next) { + index += 1; + continue; + } + + if (char === '"' || char === "'" || char === '`') { + quote = char; + continue; + } + + if (char === '(') { + depth += 1; + continue; + } + + if (char === ')') { + if (depth === 1 && next === ')') return index + 2; + if (depth > 1) depth -= 1; + } + } + + return segment.length; +} + +function hasExecutableShellExpansion(segment: string): boolean { + let quote: '"' | "'" | null = null; + + for (let index = 0; index < segment.length; index += 1) { + const char = segment[index]!; + const next = segment[index + 1]; + + if (quote) { + if (char === '\\' && quote === '"' && next) { + index += 1; + continue; + } + if (char === quote) { + quote = null; + continue; + } + if (quote === '"' && char === '$' && next === '(') return true; + if (quote === '"' && char === '`') return true; + continue; + } + + if (char === '\\' && next) { + index += 1; + continue; + } + + if (char === "'") { + quote = char; + continue; + } + + if (char === '"') { + quote = char; + continue; + } + + if (char === '`') return true; + if (char === '$' && next === '(') return true; + if ((char === '<' || char === '>') && next === '(') return true; + } + + return false; +} + +function readEscapeDigits( + value: string, + startIndex: number, + maxLength: number, + pattern: RegExp, +): { digits: string; endIndex: number } | null { + let endIndex = startIndex; + while ( + endIndex < value.length + && endIndex < startIndex + maxLength + && pattern.test(value[endIndex]!) + ) { + endIndex += 1; + } + + if (endIndex === startIndex) return null; + return { digits: value.slice(startIndex, endIndex), endIndex: endIndex - 1 }; +} + +function codePointToString(codePoint: number): string { + try { + return String.fromCodePoint(codePoint); + } catch { + return ''; + } +} + +function readAnsiCEscape(value: string, backslashIndex: number): { text: string; endIndex: number } { + const escapeIndex = backslashIndex + 1; + const char = value[escapeIndex]; + if (!char) return { text: '\\', endIndex: backslashIndex }; + + const simpleEscapes: Record = { + a: '\x07', + b: '\b', + e: '\x1B', + E: '\x1B', + f: '\f', + n: '\n', + r: '\r', + t: '\t', + v: '\v', + '\\': '\\', + "'": "'", + '"': '"', + '?': '?', + }; + + const simple = simpleEscapes[char]; + if (simple !== undefined) return { text: simple, endIndex: escapeIndex }; + + if (char === 'x') { + const digits = readEscapeDigits(value, escapeIndex + 1, 2, /[0-9a-fA-F]/); + if (!digits) return { text: '\\x', endIndex: escapeIndex }; + return { + text: codePointToString(Number.parseInt(digits.digits, 16)), + endIndex: digits.endIndex, + }; + } + + if (char === 'u' || char === 'U') { + const digits = readEscapeDigits(value, escapeIndex + 1, char === 'u' ? 4 : 8, /[0-9a-fA-F]/); + if (!digits) return { text: `\\${char}`, endIndex: escapeIndex }; + return { + text: codePointToString(Number.parseInt(digits.digits, 16)), + endIndex: digits.endIndex, + }; + } + + if (/[0-7]/.test(char)) { + const digits = readEscapeDigits(value, escapeIndex, 3, /[0-7]/)!; + return { + text: codePointToString(Number.parseInt(digits.digits, 8)), + endIndex: digits.endIndex, + }; + } + + return { text: `\\${char}`, endIndex: escapeIndex }; +} + +function readHereDocDelimiterWord( + segment: string, + startIndex: number, +): { text: string; endIndex: number } | null { + let index = startIndex; + while (index < segment.length && /\s/.test(segment[index]!)) index += 1; + + let text = ''; + let quote: '"' | "'" | '`' | null = null; + let ansiQuote = false; + + for (; index < segment.length; index += 1) { + const char = segment[index]!; + const next = segment[index + 1]; + + if (quote) { + if (ansiQuote && char === '\\') { + const escape = readAnsiCEscape(segment, index); + text += escape.text; + index = escape.endIndex; + continue; + } + if (char === '\\' && quote !== "'" && next) { + text += next; + index += 1; + continue; + } + if (char === quote) { + quote = null; + ansiQuote = false; + continue; + } + text += char; + continue; + } + + if (/\s/.test(char) || char === ';' || char === '|' || char === '&') break; + + if (char === '\\' && next) { + text += next; + index += 1; + continue; + } + + if (char === '$' && (next === "'" || next === '"')) { + quote = next; + ansiQuote = next === "'"; + index += 1; + continue; + } + + if (char === '"' || char === "'" || char === '`') { + quote = char; + ansiQuote = false; + continue; + } + + text += char; + } + + return text ? { text, endIndex: index } : null; +} + +function extractHereDocTerminators(segment: string): HereDocTerminator[] { + const terminators: HereDocTerminator[] = []; + let quote: '"' | "'" | '`' | null = null; + + for (let index = 0; index < segment.length; index += 1) { + const char = segment[index]!; + const next = segment[index + 1]; + + if (quote) { + if (char === '\\' && quote !== "'" && next) { + index += 1; + continue; + } + if (char === quote) quote = null; + continue; + } + + const arithmeticEnd = readArithmeticExpansionEnd(segment, index); + if (arithmeticEnd !== null) { + index = arithmeticEnd - 1; + continue; + } + + if (char === '\\' && next) { + index += 1; + continue; + } + + if (char === '"' || char === "'" || char === '`') { + quote = char; + continue; + } + + if (char !== '<' || next !== '<') continue; + if (segment[index + 2] === '<') { + index += 2; + continue; + } + + const stripLeadingTabs = segment[index + 2] === '-'; + const delimiterStart = index + (stripLeadingTabs ? 3 : 2); + const delimiter = readHereDocDelimiterWord(segment, delimiterStart); + if (!delimiter) continue; + terminators.push({ text: delimiter.text, stripLeadingTabs }); + index = delimiter.endIndex - 1; + } + + return terminators; +} + +function skipHereDocBodies( + command: string, + startIndex: number, + terminators: HereDocTerminator[], +): number { + let cursor = startIndex; + + for (const terminator of terminators) { + while (cursor < command.length) { + const lineEnd = command.indexOf('\n', cursor); + const end = lineEnd === -1 ? command.length : lineEnd; + const rawLine = command.slice(cursor, end); + const line = terminator.stripLeadingTabs ? rawLine.replace(/^\t+/, '') : rawLine; + cursor = lineEnd === -1 ? command.length : lineEnd + 1; + + if (line === terminator.text) break; + } + } + + return cursor; +} + export function splitShellCommandSegments(command: string): string[] { - return command - .split(/\s*(?:&&|\|\||;)\s*/) - .map((segment) => segment.trim()) - .filter(Boolean); + const segments: string[] = []; + let current = ''; + let quote: '"' | "'" | '`' | null = null; + let inComment = false; + let lineHereDocTerminators: HereDocTerminator[] = []; + + const flush = () => { + const segment = current.trim(); + if (segment) segments.push(segment); + current = ''; + }; + + const flushCommandSegment = () => { + lineHereDocTerminators.push(...extractHereDocTerminators(current)); + flush(); + }; + + const finishLine = (bodyStartIndex: number): number => { + flushCommandSegment(); + const hereDocTerminators = lineHereDocTerminators; + lineHereDocTerminators = []; + if (hereDocTerminators.length === 0) return bodyStartIndex; + return skipHereDocBodies(command, bodyStartIndex, hereDocTerminators); + }; + + for (let index = 0; index < command.length; index += 1) { + const char = command[index]!; + const next = command[index + 1]; + + if (inComment) { + if (char === '\n') { + inComment = false; + index = finishLine(index + 1) - 1; + } + continue; + } + + if (quote) { + current += char; + if (char === '\\' && quote !== "'" && next) { + current += next; + index += 1; + continue; + } + if (char === quote) quote = null; + continue; + } + + if (char === '\\' && next === '\n') { + index += 1; + continue; + } + + if (char === '\\' && next) { + current += char + next; + index += 1; + continue; + } + + if (char === '"' || char === "'" || char === '`') { + quote = char; + current += char; + continue; + } + + const arithmeticEnd = readArithmeticExpansionEnd(command, index); + if (arithmeticEnd !== null) { + current += command.slice(index, arithmeticEnd); + index = arithmeticEnd - 1; + continue; + } + + if (char === '#') { + const previous = current[current.length - 1]; + if (!previous || /\s/.test(previous)) { + inComment = true; + continue; + } + } + + if (char === '\n') { + index = finishLine(index + 1) - 1; + continue; + } + + if (char === ';') { + flushCommandSegment(); + continue; + } + + if (char === '&' && next === '&') { + flushCommandSegment(); + index += 1; + continue; + } + + if (char === '|' && next === '|') { + flushCommandSegment(); + index += 1; + continue; + } + + if (char === '&') { + const previous = lastNonWhitespaceChar(current); + if (next === '>' || previous === '>' || previous === '<') { + current += char; + continue; + } + flushCommandSegment(); + continue; + } + + if (char === '|') { + flushCommandSegment(); + if (next === '&') index += 1; + continue; + } + + current += char; + } + + flush(); + return segments; +} + +export function extractGrantableShellCommandSegments(command: string): string[] { + return splitShellCommandSegments(command).filter((segment) => { + const tokens = tokenizeShellCommand(segment); + const cmd = tokens[0]?.toLowerCase(); + return tokens.length > 0 && !(cmd && CWD_COMMANDS.has(cmd) && !hasExecutableShellExpansion(segment)); + }); } /** @@ -42,24 +482,14 @@ export function buildAlwaysAllowCommandPatterns(command: string): string[] { if (!trimmed) return []; const patterns = new Set(); - const segments = splitShellCommandSegments(trimmed); + const segments = extractGrantableShellCommandSegments(trimmed); for (const segment of segments) { const tokens = tokenizeShellCommand(segment); - if (tokens.length === 0) continue; - const cmd = tokens[0]?.toLowerCase(); - if (cmd && CWD_COMMANDS.has(cmd)) continue; const prefix = bashArityPrefix(tokens); if (prefix.length === 0) continue; patterns.add(`${prefix.join(' ')} *`); } - if (patterns.size === 0) { - const tokens = tokenizeShellCommand(trimmed); - if (tokens.length > 0) { - patterns.add(`${bashArityPrefix(tokens).join(' ')} *`); - } - } - return [...patterns]; } From cff6aa2906028e075581edb9c4347c23a21072e5 Mon Sep 17 00:00:00 2001 From: shixu Date: Fri, 26 Jun 2026 15:10:30 +0800 Subject: [PATCH 095/228] Fix remote macOS stats detection --- components/HostDetailsPanel.helpers.ts | 7 +++- .../runtime/terminalDistroDetection.test.ts | 37 +++++++++++++++++++ .../runtime/terminalDistroDetection.ts | 9 ++++- domain/host.test.ts | 13 +++++++ domain/host.ts | 18 ++++++++- 5 files changed, 80 insertions(+), 4 deletions(-) diff --git a/components/HostDetailsPanel.helpers.ts b/components/HostDetailsPanel.helpers.ts index 18f3139a2..4369cec62 100644 --- a/components/HostDetailsPanel.helpers.ts +++ b/components/HostDetailsPanel.helpers.ts @@ -1,6 +1,10 @@ import type { GroupConfig } from "../domain/models"; import type { Host } from "../types"; -import { LINUX_DISTRO_OPTIONS, NETWORK_DEVICE_OPTIONS } from "../domain/host"; +import { + LINUX_DISTRO_OPTIONS, + NETWORK_DEVICE_OPTIONS, + POSIX_PLATFORM_OPTIONS, +} from "../domain/host"; export const parseOptionalPortInput = (value: string): number | undefined => value ? Number(value) : undefined; @@ -76,5 +80,6 @@ export const resolveDetailsTelnetPassword = ( export const LINUX_DISTRO_OPTION_IDS = [ ...LINUX_DISTRO_OPTIONS, + ...POSIX_PLATFORM_OPTIONS, ...NETWORK_DEVICE_OPTIONS, ]; diff --git a/components/terminal/runtime/terminalDistroDetection.test.ts b/components/terminal/runtime/terminalDistroDetection.test.ts index 506230e1a..be71b9f33 100644 --- a/components/terminal/runtime/terminalDistroDetection.test.ts +++ b/components/terminal/runtime/terminalDistroDetection.test.ts @@ -39,3 +39,40 @@ test("runDistroDetection uses SSH banner but skips POSIX probes for manually mar assert.equal(distroProbeCalls, 0); assert.deepEqual(detected, ["hpe"]); }); + +test("runDistroDetection normalizes Darwin probe output to macos", async () => { + let remoteInfoCalls = 0; + let distroProbeCalls = 0; + const detected: string[] = []; + const token = registerConnectionToken("macos-session"); + + await runDistroDetection({ + host: { + id: "macos-host", + label: "Mac mini", + hostname: "mac-mini.local", + username: "dev", + }, + terminalBackend: { + getSessionRemoteInfo: async () => { + remoteInfoCalls += 1; + return { success: true, remoteSshVersion: "SSH-2.0-OpenSSH_9.9" }; + }, + getSessionDistroInfo: async () => { + distroProbeCalls += 1; + return { + success: true, + stdout: "Darwin mac-mini.local 24.5.0 Darwin Kernel Version 24.5.0\n", + stderr: "", + }; + }, + }, + onOsDetected: (_hostId: string, distro: string) => { + detected.push(distro); + }, + } as never, "macos-session", token); + + assert.equal(remoteInfoCalls, 1); + assert.equal(distroProbeCalls, 1); + assert.deepEqual(detected, ["macos"]); +}); diff --git a/components/terminal/runtime/terminalDistroDetection.ts b/components/terminal/runtime/terminalDistroDetection.ts index bd1d5ab28..c7387b0e2 100644 --- a/components/terminal/runtime/terminalDistroDetection.ts +++ b/components/terminal/runtime/terminalDistroDetection.ts @@ -1,4 +1,8 @@ -import { classifyDistroId, detectVendorFromSshVersion } from "../../../domain/host"; +import { + classifyDistroId, + detectVendorFromSshVersion, + normalizeDistroId, +} from "../../../domain/host"; import { logger } from "../../../lib/logger"; import type { TerminalSessionStartersContext } from "./createTerminalSessionStarters.types"; @@ -87,9 +91,10 @@ export const runDistroDetection = async ( if (!res?.success) return; const data = `${res.stdout || ""}\n${res.stderr || ""}`; const idMatch = data.match(/^ID="?([\w-]+)"?$/im); - const distro = idMatch + const rawDistro = idMatch ? idMatch[1] : (data.split(/\s+/)[0] || "").toLowerCase(); + const distro = normalizeDistroId(rawDistro) || rawDistro; if (distro) ctx.onOsDetected?.(ctx.host.id, distro); } } catch (err) { diff --git a/domain/host.test.ts b/domain/host.test.ts index ee36520e6..4740ae617 100644 --- a/domain/host.test.ts +++ b/domain/host.test.ts @@ -3,6 +3,7 @@ import assert from "node:assert/strict"; import type { Host } from "./models.ts"; import { + classifyDistroId, detectVendorFromSshVersion, migrateHostsFromLegacyLineTimestamps, normalizeDistroId, @@ -326,6 +327,18 @@ test("normalizeDistroId maps openEuler before the generic Linux fallback", () => assert.notEqual(normalizeDistroId("openeuler"), "linux"); }); +test("normalizeDistroId maps Darwin and macOS labels to macos", () => { + assert.equal(normalizeDistroId("Darwin"), "macos"); + assert.equal(normalizeDistroId("Darwin Kernel Version 24.5.0"), "macos"); + assert.equal(normalizeDistroId("macOS"), "macos"); + assert.equal(normalizeDistroId("Mac OS X"), "macos"); +}); + +test("classifyDistroId treats macos as a POSIX stats target", () => { + assert.equal(classifyDistroId("macos"), "linux-like"); + assert.equal(classifyDistroId("Darwin"), "linux-like"); +}); + test("shouldProbeSessionCwd allows the probe on a plain Linux host", () => { assert.equal( shouldProbeSessionCwd({ isNetworkDevice: false, remoteSshVersion: "OpenSSH_9.6" }), diff --git a/domain/host.ts b/domain/host.ts index d6c1a50dd..f28c22be5 100644 --- a/domain/host.ts +++ b/domain/host.ts @@ -51,6 +51,10 @@ export const LINUX_DISTRO_OPTIONS = [ 'openeuler', ] as const; +export const POSIX_PLATFORM_OPTIONS = [ + 'macos', +] as const; + /** * Known network-device vendor IDs that Netcatty can detect from the SSH * server identification string. When a host is classified as one of these, @@ -76,6 +80,17 @@ export type NetworkDeviceVendor = typeof NETWORK_DEVICE_OPTIONS[number]; export const normalizeDistroId = (value?: string) => { const v = (value || '').toLowerCase().trim(); if (!v) return ''; + if ( + v === 'darwin' || + v === 'macos' || + v === 'mac os' || + v === 'mac os x' || + v.includes('darwin kernel') || + v.includes('macos') || + v.includes('mac os') + ) { + return 'macos'; + } if (v.includes('ubuntu')) return 'ubuntu'; if (v.includes('debian')) return 'debian'; if (v.includes('centos')) return 'centos'; @@ -177,10 +192,11 @@ export const detectVendorFromSshVersion = (softwareVersion?: string): '' | Netwo export type DeviceClass = 'linux-like' | 'network-device' | 'other'; export const classifyDistroId = (distroId?: string): DeviceClass => { - const v = (distroId || '').toLowerCase().trim(); + const v = normalizeDistroId(distroId) || (distroId || '').toLowerCase().trim(); if (!v) return 'other'; if ((NETWORK_DEVICE_OPTIONS as readonly string[]).includes(v)) return 'network-device'; if ((LINUX_DISTRO_OPTIONS as readonly string[]).includes(v)) return 'linux-like'; + if ((POSIX_PLATFORM_OPTIONS as readonly string[]).includes(v)) return 'linux-like'; return 'other'; }; From 983574ce8c13b2d823ec6c53e8e9254a1cca8f7d Mon Sep 17 00:00:00 2001 From: shixu Date: Fri, 26 Jun 2026 21:43:36 +0800 Subject: [PATCH 096/228] Improve remote macOS server stats collection --- components/terminal/TerminalServerStats.tsx | 42 +++++++++++-------- electron/bridges/sshBridge/sessionOps.cjs | 20 ++++----- .../sshBridge/sessionOps.serverStats.test.cjs | 35 ++++++++++++++++ 3 files changed, 69 insertions(+), 28 deletions(-) diff --git a/components/terminal/TerminalServerStats.tsx b/components/terminal/TerminalServerStats.tsx index 3f4666e44..a8db2053a 100644 --- a/components/terminal/TerminalServerStats.tsx +++ b/components/terminal/TerminalServerStats.tsx @@ -47,6 +47,8 @@ export const TerminalServerStats: React.FC = ({ isConnected, isVisible, }); + const hasNetworkDetails = serverStats.netInterfaces.length > 0; + const hasLatency = serverStats.latencyMs !== null; if (!enabled || !isConnected || !serverStats.lastUpdated) return null; @@ -316,7 +318,7 @@ export const TerminalServerStats: React.FC = ({ {/* Network - with HoverCard for per-interface details */} - {serverStats.netInterfaces.length > 0 && ( + {(hasNetworkDetails || hasLatency) && (

-
- {serverStats.netInterfaces.map((iface, index) => ( -
- - {iface.name} - -
- - - {formatNetSpeed(iface.rxSpeed)} - - - - {formatNetSpeed(iface.txSpeed)} + {hasNetworkDetails ? ( +
+ {serverStats.netInterfaces.map((iface, index) => ( +
+ + {iface.name} +
+ + + {formatNetSpeed(iface.rxSpeed)} + + + + {formatNetSpeed(iface.txSpeed)} + +
-
- ))} -
+ ))} +
+ ) : ( +
{t("terminal.serverStats.noData")}
+ )}
diff --git a/electron/bridges/sshBridge/sessionOps.cjs b/electron/bridges/sshBridge/sessionOps.cjs index ca70738e2..2a7ab98f2 100644 --- a/electron/bridges/sshBridge/sessionOps.cjs +++ b/electron/bridges/sshBridge/sessionOps.cjs @@ -667,7 +667,7 @@ function createSessionOpsApi(ctx) { function createEtStatsExecConn(etSession) { return { exec(command, cb) { - execOnEtSession(etSession, command, 4500, { + execOnEtSession(etSession, command, 10000, { requireTrustedHost: true, knownHosts: etSession.etStatsAuth?.knownHosts, }) @@ -725,16 +725,16 @@ function createSessionOpsApi(ctx) { return { success: false, error: 'Session not found or not connected' }; } - // macOS stats command: uses sysctl, vm_stat, top, ps, df, netstat - // CPU reported as direct percentage (top computes delta internally) + // macOS stats command: uses sysctl, vm_stat, ps, df, netstat + // CPU is a fast best-effort sum of process %CPU, clamped by the parser. // cpuPerCore not available on macOS without sudo const macosStatsCommand = [ `cores=$(sysctl -n hw.logicalcpu 2>/dev/null || echo "1")`, `pagesize=$(sysctl -n hw.pagesize 2>/dev/null || echo "4096")`, `memsize=$(sysctl -n hw.memsize 2>/dev/null || echo "0")`, - // CPU usage: top -l 1 gives one logging sample, parse idle% - `cpuline=$(top -l 1 -s 0 -n 0 2>/dev/null | grep "CPU usage:" | head -1)`, - `cpupct=$(echo "$cpuline" | awk '{for(i=1;i<=NF;i++){if($(i+1)~/^idle/){v=$i;gsub(/%/,"",v);idle=v+0;found=1}};if(found)printf "%.0f",100-idle}')`, + // CPU usage: avoid top here; on some remote macOS shells top can block long enough + // to trip the stats timeout. ps is fast and present on supported macOS versions. + `cpupct=$(ps -A -o %cpu= 2>/dev/null | awk '{s+=$1} END{if(s<0)s=0;if(s>100)s=100;printf "%.0f",s}')`, // Memory: single vm_stat pipe → awk extracts all page counts (strip trailing dots with gsub) // Outputs: "memfree memcached" in MB `vmmem=$(vm_stat 2>/dev/null | awk -v ps="$pagesize" '/^Pages free:/{gsub(/[^0-9]/,"",$NF);free=$NF+0} /^Pages speculative:/{gsub(/[^0-9]/,"",$NF);spec=$NF+0} /^Pages inactive:/{gsub(/[^0-9]/,"",$NF);inact=$NF+0} /^Pages purgeable:/{gsub(/[^0-9]/,"",$NF);purg=$NF+0} END{mfree=int((free+spec)*ps/1024/1024);mcached=int((inact+purg)*ps/1024/1024);printf "%d %d",mfree,mcached}')`, @@ -748,10 +748,10 @@ function createSessionOpsApi(ctx) { `swapfree=$(echo "$swaptotal $swapused" | awk '{printf "%.0f",$1-$2}')`, // Top processes by memory% `procs=$(ps -A -o pid=,%mem=,comm= 2>/dev/null | sort -k2 -rn | head -10 | awk '{gsub(/;/,"_",$3);printf "%s;%.1f;%s,",$1,$2,$3}' | sed 's/,$//')`, - // Disk: only show root "/" and external volumes "/Volumes/*", skip system APFS snapshots - `disks=$(df -k 2>/dev/null | awk 'NR>1&&index($1,"/dev/")==1&&NF>=9&&($NF=="/"||index($NF,"/Volumes/")==1){u=$3/1048576;t=$2/1048576;p=$5;gsub(/%/,"",p);printf "%s:%.0f:%.0f:%s,",$NF,u,t,p}' | sed 's/,$//')`, + // Disk: -P keeps a stable six-column POSIX layout on macOS. + `disks=$(df -kP 2>/dev/null | awk 'NR>1&&index($1,"/dev/")==1{m=$6;if(m=="/"||index(m,"/Volumes/")==1){u=$3/1048576;t=$2/1048576;p=$5;gsub(/%/,"",p);printf "%s:%.0f:%.0f:%s,",m,u,t,p}}' | sed 's/,$//')`, // Network: Link# lines only, exclude loopback, detect column shift (no MAC addr → cols shift left) - `net=$(netstat -ib 2>/dev/null | awk '/^[a-z]/&&$3~/Link/&&$1!~/^lo/{if($4~/:/){rx=$7;tx=$10}else{rx=$6;tx=$9};if((rx+0)>0){gsub(/[*]/,"",$1);printf "%s:%s:%s,",$1,rx,tx}}' | sed 's/,$//')`, + `net=$(netstat -ibn 2>/dev/null | awk 'NR==1{for(i=1;i<=NF;i++){if($i=="Ibytes")ib=i;if($i=="Obytes")ob=i}next} ib&&ob&&$1~/^[[:alpha:]]/&&$1!~/^lo/&&$0~/0||tx>0){seen[name]=rx ":" tx}} END{for(name in seen)printf "%s:%s,",name,seen[name]}' | sed 's/,$//')`, `echo "CPU:$cpupct|CORES:$cores|MEMINFO:$memtotal $memfree 0 $memcached $swaptotal $swapfree|PROCS:$procs|DISKS:$disks|NET:$net"`, ].join('; '); @@ -789,7 +789,7 @@ function createSessionOpsApi(ctx) { return new Promise((resolve) => { const timeout = setTimeout(() => { resolve({ success: false, error: 'Timeout getting server stats' }); - }, 5000); + }, 10000); const latencyStartedAt = Date.now(); conn.exec(statsCommand, (err, stream) => { diff --git a/electron/bridges/sshBridge/sessionOps.serverStats.test.cjs b/electron/bridges/sshBridge/sessionOps.serverStats.test.cjs index 2603f6657..9c0432407 100644 --- a/electron/bridges/sshBridge/sessionOps.serverStats.test.cjs +++ b/electron/bridges/sshBridge/sessionOps.serverStats.test.cjs @@ -30,6 +30,8 @@ function fakeConn(stdout) { // success gate only requires cpu OR memTotal OR cpuCores to be non-null. const LINUX_STATS = "CPURAW:1000 900|CORES:4|PERCORERAW:|MEMINFO:8000 4000 100 900 0 0|PROCS:|DISKS:|NET:"; +const MACOS_STATS = + "NC_LATENCY_MARK|CPU:27|CORES:10|MEMINFO:32768 4096 0 8192 2048 1536|PROCS:123;1.2;Finder|DISKS:/:120:460:26|NET:en0:1000:3000"; function makeSessionOps(sessions) { return createSessionOpsApi({ @@ -124,6 +126,39 @@ test("getServerStats does not touch the companion path for a normal SSH session" assert.equal(result.success, true); }); +test("getServerStats parses macOS stats and avoids blocking top command", async () => { + const sessions = new Map(); + let command = ""; + const session = { + type: "ssh", + conn: { + exec(cmd, cb) { + command = cmd; + cb(null, fakeStream(MACOS_STATS)); + }, + }, + }; + sessions.set("sid", session); + + const api = makeSessionOps(sessions); + const result = await api.getServerStats({ sender: {} }, { sessionId: "sid" }); + + assert.equal(result.success, true); + assert.match(command, /Darwin/); + assert.match(command, /ps -A -o %cpu=/); + assert.doesNotMatch(command, /top -l/); + assert.equal(result.stats.cpu, 27); + assert.equal(result.stats.cpuCores, 10); + assert.equal(result.stats.memTotal, 32768); + assert.equal(result.stats.memUsed, 20480); + assert.equal(result.stats.diskPercent, 26); + assert.equal(result.stats.netInterfaces.length, 1); + assert.equal(result.stats.netInterfaces[0].name, "en0"); + assert.equal(result.stats.netInterfaces[0].rxBytes, 1000); + assert.equal(result.stats.netInterfaces[0].txBytes, 3000); + assert.equal(typeof result.stats.latencyMs, "number"); +}); + test("getServerStats reports pending (not a hard failure) for a Mosh session before the handshake swap", async () => { const sessions = new Map(); // Connected (renderer polls) but moshStatsAuth not yet assigned. From 20f0ef77aee660fc62932e126bdc3a2794e2aacc Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 22:29:58 +0800 Subject: [PATCH 097/228] fix empty command approval grant --- infrastructure/ai/harness/permissionGrants.test.ts | 10 ++++++++++ infrastructure/ai/harness/permissionGrants.ts | 4 ++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/infrastructure/ai/harness/permissionGrants.test.ts b/infrastructure/ai/harness/permissionGrants.test.ts index f408f1a4c..b84637821 100644 --- a/infrastructure/ai/harness/permissionGrants.test.ts +++ b/infrastructure/ai/harness/permissionGrants.test.ts @@ -53,10 +53,20 @@ describe('permissionGrants', () => { sessionId: 'ssh-1', command: 'systemctl status nginx', }, 'chat-1'); + assert.ok(grant); assert.equal(grant.sessionPattern, '*'); assert.equal(grant.commandPattern, 'systemctl status *'); }); + it('buildGrantFromApproval returns null when no command grant is produced', () => { + const grant = buildGrantFromApproval('terminal.execute', { + sessionId: 'ssh-1', + command: 'cd /tmp', + }, 'chat-1'); + + assert.equal(grant, null); + }); + it('buildGrantsFromApproval emits one rule per chained command segment', () => { const grants = buildGrantsFromApproval('terminal.execute', { sessionId: 'ssh-1', diff --git a/infrastructure/ai/harness/permissionGrants.ts b/infrastructure/ai/harness/permissionGrants.ts index 744f0426b..c49101b27 100644 --- a/infrastructure/ai/harness/permissionGrants.ts +++ b/infrastructure/ai/harness/permissionGrants.ts @@ -267,8 +267,8 @@ export function buildGrantFromApproval( capabilityId: string, args: Record, chatSessionId?: string, -): PermissionGrantRule { - return buildGrantsFromApproval(capabilityId, args, chatSessionId)[0]; +): PermissionGrantRule | null { + return buildGrantsFromApproval(capabilityId, args, chatSessionId)[0] ?? null; } let activeRules: PermissionGrantRule[] = []; From f575317de8c4c464092555582e5275551f5491b8 Mon Sep 17 00:00:00 2001 From: shixu Date: Fri, 26 Jun 2026 22:52:39 +0800 Subject: [PATCH 098/228] Normalize macOS CPU stats by core count --- electron/bridges/sshBridge/sessionOps.cjs | 6 +++--- electron/bridges/sshBridge/sessionOps.serverStats.test.cjs | 2 ++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/electron/bridges/sshBridge/sessionOps.cjs b/electron/bridges/sshBridge/sessionOps.cjs index 2a7ab98f2..769a60b5d 100644 --- a/electron/bridges/sshBridge/sessionOps.cjs +++ b/electron/bridges/sshBridge/sessionOps.cjs @@ -726,7 +726,7 @@ function createSessionOpsApi(ctx) { } // macOS stats command: uses sysctl, vm_stat, ps, df, netstat - // CPU is a fast best-effort sum of process %CPU, clamped by the parser. + // CPU is a fast best-effort sum of process %CPU normalized by logical cores. // cpuPerCore not available on macOS without sudo const macosStatsCommand = [ `cores=$(sysctl -n hw.logicalcpu 2>/dev/null || echo "1")`, @@ -734,7 +734,7 @@ function createSessionOpsApi(ctx) { `memsize=$(sysctl -n hw.memsize 2>/dev/null || echo "0")`, // CPU usage: avoid top here; on some remote macOS shells top can block long enough // to trip the stats timeout. ps is fast and present on supported macOS versions. - `cpupct=$(ps -A -o %cpu= 2>/dev/null | awk '{s+=$1} END{if(s<0)s=0;if(s>100)s=100;printf "%.0f",s}')`, + `cpupct=$(ps -A -o %cpu= 2>/dev/null | awk -v c="$cores" '{s+=$1} END{if(c<=0)c=1;s=s/c;if(s<0)s=0;if(s>100)s=100;printf "%.0f",s}')`, // Memory: single vm_stat pipe → awk extracts all page counts (strip trailing dots with gsub) // Outputs: "memfree memcached" in MB `vmmem=$(vm_stat 2>/dev/null | awk -v ps="$pagesize" '/^Pages free:/{gsub(/[^0-9]/,"",$NF);free=$NF+0} /^Pages speculative:/{gsub(/[^0-9]/,"",$NF);spec=$NF+0} /^Pages inactive:/{gsub(/[^0-9]/,"",$NF);inact=$NF+0} /^Pages purgeable:/{gsub(/[^0-9]/,"",$NF);purg=$NF+0} END{mfree=int((free+spec)*ps/1024/1024);mcached=int((inact+purg)*ps/1024/1024);printf "%d %d",mfree,mcached}')`, @@ -846,7 +846,7 @@ function createSessionOpsApi(ctx) { for (const part of parts) { if (part.startsWith('CPU:')) { - // macOS: top reports CPU% directly (no delta needed) + // macOS: command reports normalized CPU% directly (no delta needed) const val = parseFloat(part.substring(4).trim()); if (!isNaN(val)) cpuDirect = Math.min(100, Math.max(0, Math.round(val))); } else if (part.startsWith('CPURAW:')) { diff --git a/electron/bridges/sshBridge/sessionOps.serverStats.test.cjs b/electron/bridges/sshBridge/sessionOps.serverStats.test.cjs index 9c0432407..76ab34c54 100644 --- a/electron/bridges/sshBridge/sessionOps.serverStats.test.cjs +++ b/electron/bridges/sshBridge/sessionOps.serverStats.test.cjs @@ -146,6 +146,8 @@ test("getServerStats parses macOS stats and avoids blocking top command", async assert.equal(result.success, true); assert.match(command, /Darwin/); assert.match(command, /ps -A -o %cpu=/); + assert.match(command, /awk -v c="\$cores"/); + assert.match(command, /s=s\/c/); assert.doesNotMatch(command, /top -l/); assert.equal(result.stats.cpu, 27); assert.equal(result.stats.cpuCores, 10); From 2d4c27b12c685f06874579aff9112826a2eae836 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 17:38:16 +0800 Subject: [PATCH 099/228] Add Copilot-style theme presets --- application/i18n/locales/en/core.ts | 3 + application/i18n/locales/ru/core.ts | 3 + application/i18n/locales/zh-CN/core.ts | 3 + components/settings/UiThemePresetModal.tsx | 223 ++++++++++++++++++ .../settings/tabs/SettingsAppearanceTab.tsx | 37 ++- index.css | 6 +- index.tsx | 6 +- infrastructure/config/uiFonts.test.ts | 12 + infrastructure/config/uiFonts.ts | 7 +- infrastructure/config/uiThemes.test.ts | 40 ++++ infrastructure/config/uiThemes.ts | 221 ++++++++++++++++- package-lock.json | 89 ++++--- package.json | 2 + 13 files changed, 596 insertions(+), 56 deletions(-) create mode 100644 components/settings/UiThemePresetModal.tsx create mode 100644 infrastructure/config/uiThemes.test.ts diff --git a/application/i18n/locales/en/core.ts b/application/i18n/locales/en/core.ts index a207e412e..655c50992 100644 --- a/application/i18n/locales/en/core.ts +++ b/application/i18n/locales/en/core.ts @@ -267,6 +267,9 @@ export const enCoreMessages: Messages = { 'settings.appearance.theme.light': 'Light', 'settings.appearance.theme.dark': 'Dark', 'settings.appearance.theme.system': 'System', + 'settings.appearance.themePresets': 'Theme presets', + 'settings.appearance.themePresets.desc': 'Choose a Copilot-style palette', + 'settings.appearance.themePresets.modalTitle': 'Theme presets', 'settings.appearance.accentColor': 'Accent Color', 'settings.appearance.customColor': 'Custom color', 'settings.appearance.accentColor.mode': 'Use custom accent', diff --git a/application/i18n/locales/ru/core.ts b/application/i18n/locales/ru/core.ts index 4804a74a3..5fb1b5a1f 100644 --- a/application/i18n/locales/ru/core.ts +++ b/application/i18n/locales/ru/core.ts @@ -256,6 +256,9 @@ export const ruCoreMessages: Messages = { 'settings.appearance.theme.light': 'Светлая', 'settings.appearance.theme.dark': 'Тёмная', 'settings.appearance.theme.system': 'Системная', + 'settings.appearance.themePresets': 'Готовые темы', + 'settings.appearance.themePresets.desc': 'Выберите палитру в стиле Copilot', + 'settings.appearance.themePresets.modalTitle': 'Готовые темы', 'settings.appearance.accentColor': 'Акцентный цвет', 'settings.appearance.customColor': 'Пользовательский цвет', 'settings.appearance.accentColor.mode': 'Использовать свой акцент', diff --git a/application/i18n/locales/zh-CN/core.ts b/application/i18n/locales/zh-CN/core.ts index b8509ba2c..29b3017e4 100644 --- a/application/i18n/locales/zh-CN/core.ts +++ b/application/i18n/locales/zh-CN/core.ts @@ -253,6 +253,9 @@ export const zhCNCoreMessages: Messages = { 'settings.appearance.theme.light': '浅色', 'settings.appearance.theme.dark': '深色', 'settings.appearance.theme.system': '系统', + 'settings.appearance.themePresets': '主题预设', + 'settings.appearance.themePresets.desc': '选择 Copilot 风格配色', + 'settings.appearance.themePresets.modalTitle': '主题预设', 'settings.appearance.accentColor': '强调色', 'settings.appearance.customColor': '自定义颜色', 'settings.appearance.accentColor.mode': '使用自定义强调色', diff --git a/components/settings/UiThemePresetModal.tsx b/components/settings/UiThemePresetModal.tsx new file mode 100644 index 000000000..20a804277 --- /dev/null +++ b/components/settings/UiThemePresetModal.tsx @@ -0,0 +1,223 @@ +import React, { useCallback, useEffect } from "react"; +import { createPortal } from "react-dom"; +import { Check, Palette, X } from "lucide-react"; +import { useI18n } from "../../application/i18n/I18nProvider"; +import type { UiThemePreset } from "../../infrastructure/config/uiThemes"; +import { cn } from "../../lib/utils"; + +type UiThemePresetModalProps = { + open: boolean; + onClose: () => void; + presets: UiThemePreset[]; + selectedThemeId: string; + onSelect: (themeId: string) => void; +}; + +const hsl = (value: string, alpha?: number) => ( + alpha === undefined ? `hsl(${value})` : `hsl(${value} / ${alpha})` +); + +const PreviewLine = ({ + color, + width, + alpha = 0.22, +}: { + color: string; + width: string; + alpha?: number; +}) => ( + +); + +const ThemePreview = ({ preset }: { preset: UiThemePreset }) => { + const { tokens } = preset; + const preview = preset.preview ?? { + sidebar: tokens.secondary, + activity: [tokens.destructive, tokens.primary, tokens.secondary, tokens.ring], + syntax: [tokens.primary, tokens.destructive, tokens.accent, tokens.ring], + }; + const activity = preview.activity.slice(0, 5); + const syntax = preview.syntax.slice(0, 4); + + return ( +
+
+
+
+ {[0, 1, 2].map((dot) => ( + + ))} +
+
+ + + +
+
+ +
+ + +
+
+
+
+
+
+ + +
+ +
+
+ + +
+
+
+ + + +
+
+ + + +
+
+
+ + +
+
+
+
+ {activity.map((stripe, index) => ( + + ))} +
+
+ ); +}; + +export function UiThemePresetModal({ + open, + onClose, + presets, + selectedThemeId, + onSelect, +}: UiThemePresetModalProps) { + const { t } = useI18n(); + const handleThemeSelect = useCallback((themeId: string) => { + onSelect(themeId); + onClose(); + }, [onClose, onSelect]); + + useEffect(() => { + if (!open) return; + const handleKeyDown = (event: KeyboardEvent) => { + if (event.key === "Escape") onClose(); + }; + document.addEventListener("keydown", handleKeyDown); + return () => document.removeEventListener("keydown", handleKeyDown); + }, [onClose, open]); + + const handleBackdropClick = useCallback((event: React.MouseEvent) => { + if (event.target === event.currentTarget) onClose(); + }, [onClose]); + + if (!open) return null; + + const modalTitleId = "ui-theme-preset-modal-title"; + + return createPortal( +
+
event.stopPropagation()} + > +
+
+
+ +
+

+ {t("settings.appearance.themePresets.modalTitle")} +

+
+ +
+
+
+ {presets.map((preset) => { + const selected = selectedThemeId === preset.id; + return ( + + ); + })} +
+
+
+
, + document.body, + ); +} + +export default UiThemePresetModal; diff --git a/components/settings/tabs/SettingsAppearanceTab.tsx b/components/settings/tabs/SettingsAppearanceTab.tsx index d8aa8ad0a..5f6958c75 100644 --- a/components/settings/tabs/SettingsAppearanceTab.tsx +++ b/components/settings/tabs/SettingsAppearanceTab.tsx @@ -1,15 +1,20 @@ -import React, { memo, useCallback } from "react"; +import React, { memo, useCallback, useState } from "react"; import { applyCustomCssToDocument } from "../../../lib/customCss"; import { DebouncedTextarea } from "../DebouncedTextarea"; import { Check, Monitor, Moon, Palette, Sun } from "lucide-react"; import { useI18n } from "../../../application/i18n/I18nProvider"; -import { DARK_UI_THEMES, LIGHT_UI_THEMES } from "../../../infrastructure/config/uiThemes"; +import { + COPILOT_LIGHT_UI_THEMES, + DARK_UI_THEMES, + LIGHT_UI_THEMES, +} from "../../../infrastructure/config/uiThemes"; import { useAvailableUIFonts } from "../../../application/state/uiFontStore"; import { SUPPORTED_UI_LOCALES } from "../../../infrastructure/config/i18n"; import { cn } from "../../../lib/utils"; import { SectionHeader, SettingsTabContent, SettingRow, Toggle, Select } from "../settings-ui"; import { FontSelect } from "../FontSelect"; import { Tooltip, TooltipContent, TooltipTrigger } from "../../ui/tooltip"; +import { UiThemePresetModal } from "../UiThemePresetModal"; function SettingsAppearanceTab(props: { theme: "dark" | "light" | "system"; @@ -41,6 +46,7 @@ function SettingsAppearanceTab(props: { }) { const { t } = useI18n(); const availableUIFonts = useAvailableUIFonts(); + const [themePresetModalOpen, setThemePresetModalOpen] = useState(false); const { theme, setTheme, @@ -77,6 +83,7 @@ function SettingsAppearanceTab(props: { ] as const; const getHslStyle = useCallback((hsl: string) => ({ backgroundColor: `hsl(${hsl})` }), []); + const selectedLightTheme = LIGHT_UI_THEMES.find((preset) => preset.id === lightUiThemeId) ?? LIGHT_UI_THEMES[0]; const hexToHsl = useCallback((hex: string) => { const r = parseInt(hex.slice(1, 3), 16) / 255; @@ -160,6 +167,12 @@ function SettingsAppearanceTab(props: {
); + const handlePresetSelect = useCallback((themeId: string) => { + setTheme("light"); + setLightUiThemeId(themeId); + setAccentMode("theme"); + }, [setAccentMode, setLightUiThemeId, setTheme]); + return ( @@ -254,7 +267,27 @@ function SettingsAppearanceTab(props: { ))}
+ + +
+ setThemePresetModalOpen(false)} + presets={COPILOT_LIGHT_UI_THEMES} + selectedThemeId={lightUiThemeId} + onSelect={handlePresetSelect} + />
diff --git a/index.css b/index.css index 8ddeb00e1..acef637fa 100644 --- a/index.css +++ b/index.css @@ -100,7 +100,7 @@ --radius-sm: calc(var(--radius) - 4px); /* Fonts */ - --font-sans: "Space Grotesk", system-ui, sans-serif; + --font-sans: "Mona Sans", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif; --font-mono: "JetBrains Mono", monospace; /* Animations */ @@ -140,10 +140,10 @@ } -/* Windows: bundled flag font + Segoe UI Emoji ahead of Space Grotesk so host +/* Windows: bundled flag font + Segoe UI Emoji ahead of Mona Sans so host labels render flag icons instead of ISO country codes (#1589, #1604). */ html.platform-win32 { - --font-sans: "Noto Color Emoji Flags", "Segoe UI Emoji", "Segoe UI Symbol", "Space Grotesk", system-ui, sans-serif; + --font-sans: "Noto Color Emoji Flags", "Segoe UI Emoji", "Segoe UI Symbol", "Mona Sans", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif; } @keyframes top-tab-enter { diff --git a/index.tsx b/index.tsx index edb0d1b5c..cc8bfd037 100755 --- a/index.tsx +++ b/index.tsx @@ -1,5 +1,9 @@ import { Suspense, lazy } from 'react'; import ReactDOM from 'react-dom/client'; +import '@fontsource/mona-sans/400.css'; +import '@fontsource/mona-sans/500.css'; +import '@fontsource/mona-sans/600.css'; +import '@fontsource/mona-sans/700.css'; import '@fontsource/space-grotesk/400.css'; import '@fontsource/space-grotesk/500.css'; import '@fontsource/space-grotesk/600.css'; @@ -24,7 +28,7 @@ function SettingsWindowFallback() { flexDirection: 'column', background: 'hsl(var(--background))', color: 'hsl(var(--foreground))', - fontFamily: 'Space Grotesk, system-ui, sans-serif', + fontFamily: 'Mona Sans, PingFang SC, system-ui, sans-serif', }} >
{ assert.match(stack, /Space Grotesk/); }); }); + +describe('default UI font', () => { + it('uses Mona Sans while keeping Chinese fallbacks in the stack', () => { + const defaultFont = UI_FONTS.find((font) => font.id === DEFAULT_UI_FONT_ID); + assert.equal(DEFAULT_UI_FONT_ID, 'mona-sans'); + assert.equal(defaultFont?.name, 'Mona Sans'); + assert.match(defaultFont?.family ?? '', /Mona Sans/); + assert.match(defaultFont?.family ?? '', /PingFang SC/); + }); +}); diff --git a/infrastructure/config/uiFonts.ts b/infrastructure/config/uiFonts.ts index 59d9359f2..442e60b7e 100644 --- a/infrastructure/config/uiFonts.ts +++ b/infrastructure/config/uiFonts.ts @@ -70,6 +70,11 @@ export function withWindowsEmojiFallback( } const BASE_UI_FONTS: UIFont[] = [ + { + id: 'mona-sans', + name: 'Mona Sans', + family: '"Mona Sans", system-ui', + }, { id: 'space-grotesk', name: 'Space Grotesk', @@ -182,4 +187,4 @@ export const UI_FONTS: UIFont[] = BASE_UI_FONTS.map((font) => ({ family: withUiCjkFallback(font.family), })); -export const DEFAULT_UI_FONT_ID = 'space-grotesk'; +export const DEFAULT_UI_FONT_ID = 'mona-sans'; diff --git a/infrastructure/config/uiThemes.test.ts b/infrastructure/config/uiThemes.test.ts new file mode 100644 index 000000000..5fbe6cd36 --- /dev/null +++ b/infrastructure/config/uiThemes.test.ts @@ -0,0 +1,40 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; + +import { + COPILOT_LIGHT_UI_THEMES, + LIGHT_UI_THEMES, + getUiThemeById, +} from "./uiThemes"; + +describe("Copilot light UI themes", () => { + it("adds every Copilot preset to the light theme list", () => { + const expectedIds = [ + "github", + "fox", + "ic-orange-ppl", + "monochrome", + "noctis-azureus", + "notionish", + "polychrome", + "selene-selenized", + "tokyo-night", + "xotopia", + ]; + + assert.deepEqual(COPILOT_LIGHT_UI_THEMES.map((theme) => theme.id), expectedIds); + for (const id of expectedIds) { + assert.equal(getUiThemeById("light", id).id, id); + } + }); + + it("keeps theme accents distinct from the original default blue", () => { + const originalDefaultBlue = "221.2 83.2% 53.3%"; + const accents = new Set(COPILOT_LIGHT_UI_THEMES.map((theme) => theme.tokens.accent)); + + assert.equal(COPILOT_LIGHT_UI_THEMES.length, 10); + assert.equal(LIGHT_UI_THEMES.filter((theme) => theme.collection === "copilot").length, 10); + assert.ok(accents.size > 6); + assert.ok(!accents.has(originalDefaultBlue)); + }); +}); diff --git a/infrastructure/config/uiThemes.ts b/infrastructure/config/uiThemes.ts index 8f3bbb6c3..a7a2a7262 100644 --- a/infrastructure/config/uiThemes.ts +++ b/infrastructure/config/uiThemes.ts @@ -23,13 +23,68 @@ export type UiThemeTokens = { export type UiThemePreset = { id: string; name: string; + collection?: "core" | "copilot"; + preview?: { + sidebar: string; + activity: string[]; + syntax: string[]; + }; tokens: UiThemeTokens; }; -export const LIGHT_UI_THEMES: UiThemePreset[] = [ +type CopilotThemeConfig = { + id: string; + name: string; + background: string; + foreground: string; + card: string; + secondary: string; + muted: string; + mutedForeground: string; + border: string; + primary: string; + added: string; + removed: string; + skill: string; +}; + +const createCopilotLightTheme = (config: CopilotThemeConfig): UiThemePreset => ({ + id: config.id, + name: config.name, + collection: "copilot", + preview: { + sidebar: config.secondary, + activity: [config.removed, config.skill, config.added, config.primary], + syntax: [config.primary, config.removed, config.added, config.skill], + }, + tokens: { + background: config.background, + foreground: config.foreground, + card: config.card, + cardForeground: config.foreground, + popover: config.card, + popoverForeground: config.foreground, + primary: config.primary, + primaryForeground: "0 0% 100%", + secondary: config.secondary, + secondaryForeground: config.foreground, + muted: config.muted, + mutedForeground: config.mutedForeground, + accent: config.primary, + accentForeground: "0 0% 100%", + destructive: config.removed, + destructiveForeground: "0 0% 100%", + border: config.border, + input: config.border, + ring: config.primary, + }, +}); + +export const CORE_LIGHT_UI_THEMES: UiThemePreset[] = [ { id: "snow", name: "Snow", + collection: "core", tokens: { background: "216 33% 96%", foreground: "222 47% 12%", @@ -55,6 +110,7 @@ export const LIGHT_UI_THEMES: UiThemePreset[] = [ { id: "pure-white", name: "Pure White", + collection: "core", tokens: { background: "0 0% 100%", foreground: "222 47% 12%", @@ -80,6 +136,7 @@ export const LIGHT_UI_THEMES: UiThemePreset[] = [ { id: "ivory", name: "Ivory", + collection: "core", tokens: { background: "38 40% 95%", foreground: "222 47% 12%", @@ -105,6 +162,7 @@ export const LIGHT_UI_THEMES: UiThemePreset[] = [ { id: "mist", name: "Mist", + collection: "core", tokens: { background: "210 20% 97%", foreground: "222 47% 12%", @@ -130,6 +188,7 @@ export const LIGHT_UI_THEMES: UiThemePreset[] = [ { id: "mint", name: "Mint", + collection: "core", tokens: { background: "150 30% 96%", foreground: "222 47% 12%", @@ -155,6 +214,7 @@ export const LIGHT_UI_THEMES: UiThemePreset[] = [ { id: "sand", name: "Sand", + collection: "core", tokens: { background: "34 30% 94%", foreground: "222 47% 12%", @@ -180,6 +240,7 @@ export const LIGHT_UI_THEMES: UiThemePreset[] = [ { id: "lavender", name: "Lavender", + collection: "core", tokens: { background: "270 30% 97%", foreground: "222 47% 12%", @@ -204,6 +265,164 @@ export const LIGHT_UI_THEMES: UiThemePreset[] = [ }, ]; +export const COPILOT_LIGHT_UI_THEMES: UiThemePreset[] = [ + createCopilotLightTheme({ + id: "github", + name: "GitHub", + background: "0 0% 97%", + foreground: "261 36% 23%", + card: "0 0% 100%", + secondary: "220 12% 94%", + muted: "220 10% 91%", + mutedForeground: "220 7% 48%", + border: "220 10% 84%", + primary: "261 69% 59%", + added: "137 57% 41%", + removed: "356 72% 47%", + skill: "261 51% 51%", + }), + createCopilotLightTheme({ + id: "fox", + name: "Fox", + background: "15 33% 95%", + foreground: "260 34% 27%", + card: "20 28% 98%", + secondary: "15 18% 91%", + muted: "15 15% 89%", + mutedForeground: "260 12% 48%", + border: "15 14% 84%", + primary: "225 62% 48%", + added: "133 14% 49%", + removed: "0 43% 59%", + skill: "262 83% 58%", + }), + createCopilotLightTheme({ + id: "ic-orange-ppl", + name: "IC Orange PPL", + background: "37 35% 93%", + foreground: "257 35% 25%", + card: "38 33% 96%", + secondary: "38 22% 88%", + muted: "38 18% 85%", + mutedForeground: "37 12% 45%", + border: "36 18% 80%", + primary: "15 90% 41%", + added: "56 44% 35%", + removed: "16 37% 48%", + skill: "45 100% 24%", + }), + createCopilotLightTheme({ + id: "monochrome", + name: "Monochrome", + background: "215 38% 94%", + foreground: "221 39% 11%", + card: "210 40% 98%", + secondary: "215 25% 88%", + muted: "215 20% 86%", + mutedForeground: "220 9% 46%", + border: "215 16% 78%", + primary: "222 47% 11%", + added: "220 9% 46%", + removed: "218 11% 65%", + skill: "221 39% 11%", + }), + createCopilotLightTheme({ + id: "noctis-azureus", + name: "Noctis Azureus", + background: "51 49% 92%", + foreground: "216 28% 27%", + card: "51 70% 97%", + secondary: "124 18% 90%", + muted: "150 14% 86%", + mutedForeground: "190 12% 50%", + border: "124 14% 82%", + primary: "337 100% 65%", + added: "143 47% 53%", + removed: "13 100% 71%", + skill: "193 100% 42%", + }), + createCopilotLightTheme({ + id: "notionish", + name: "Notionish", + background: "45 20% 96%", + foreground: "246 33% 25%", + card: "0 0% 100%", + secondary: "45 8% 93%", + muted: "45 8% 90%", + mutedForeground: "246 8% 48%", + border: "45 8% 84%", + primary: "261 51% 51%", + added: "139 51% 37%", + removed: "5 73% 64%", + skill: "262 83% 58%", + }), + createCopilotLightTheme({ + id: "polychrome", + name: "Polychrome", + background: "253 100% 97%", + foreground: "266 43% 22%", + card: "0 0% 100%", + secondary: "253 45% 93%", + muted: "253 35% 90%", + mutedForeground: "266 14% 48%", + border: "253 30% 84%", + primary: "258 90% 66%", + added: "142 71% 45%", + removed: "351 95% 71%", + skill: "271 91% 65%", + }), + createCopilotLightTheme({ + id: "selene-selenized", + name: "Selene Selenized", + background: "47 70% 90%", + foreground: "258 31% 23%", + card: "48 80% 96%", + secondary: "48 45% 84%", + muted: "48 35% 82%", + mutedForeground: "48 11% 42%", + border: "48 26% 76%", + primary: "323 56% 55%", + added: "92 45% 43%", + removed: "6 70% 62%", + skill: "17 88% 40%", + }), + createCopilotLightTheme({ + id: "tokyo-night", + name: "Tokyo Night", + background: "219 56% 92%", + foreground: "220 32% 22%", + card: "219 60% 96%", + secondary: "221 38% 86%", + muted: "221 32% 83%", + mutedForeground: "220 16% 45%", + border: "221 28% 76%", + primary: "273 68% 59%", + added: "90 18% 53%", + removed: "349 89% 72%", + skill: "221 89% 72%", + }), + createCopilotLightTheme({ + id: "xotopia", + name: "Xotopia", + background: "0 6% 94%", + foreground: "267 33% 24%", + card: "0 8% 98%", + secondary: "0 5% 89%", + muted: "0 4% 86%", + mutedForeground: "267 9% 48%", + border: "0 4% 80%", + primary: "332 67% 54%", + added: "159 28% 53%", + removed: "357 80% 67%", + skill: "203 38% 53%", + }), +]; + +export const LIGHT_UI_THEMES: UiThemePreset[] = [ + ...CORE_LIGHT_UI_THEMES, + ...COPILOT_LIGHT_UI_THEMES, +]; + export const DARK_UI_THEMES: UiThemePreset[] = [ { id: "pure-black", diff --git a/package-lock.json b/package-lock.json index bfd0e599d..4a512e68b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,7 +14,9 @@ "@ai-sdk/google": "^4.0.0", "@ai-sdk/openai": "^4.0.0", "@aws-sdk/client-s3": "^3.956.0", + "@connectrpc/connect": "^1.7.0", "@fontsource/jetbrains-mono": "^5.2.8", + "@fontsource/mona-sans": "^5.2.8", "@fontsource/space-grotesk": "^5.2.10", "@mdxeditor/editor": "^4.0.4", "@modelcontextprotocol/sdk": "^1.29.0", @@ -330,29 +332,6 @@ "win32" ] }, - "node_modules/@anthropic-ai/sdk": { - "version": "0.106.0", - "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.106.0.tgz", - "integrity": "sha512-ufwVvYNDBj2dzOGupBCTaNzBLxqcTnGOzI4z8Wouxlt+mT3J3HuOmatgCy1VmwCHOUueqZ41ERhm0O99OUcbWA==", - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "json-schema-to-ts": "^3.1.1", - "standardwebhooks": "^1.0.0" - }, - "bin": { - "anthropic-ai-sdk": "bin/cli" - }, - "peerDependencies": { - "zod": "^3.25.0 || ^4.0.0" - }, - "peerDependenciesMeta": { - "zod": { - "optional": true - } - } - }, "node_modules/@aws-crypto/crc32": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/@aws-crypto/crc32/-/crc32-5.2.0.tgz", @@ -1282,6 +1261,7 @@ "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", @@ -1567,7 +1547,6 @@ "resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-1.10.1.tgz", "integrity": "sha512-wJ8ReQbHxsAfXhrf9ixl0aYbZorRuOWpBNzm8pL8ftmSxQx/wnJD5Eg861NwJU/czy2VXFIebCeZnZrI9rktIQ==", "license": "(Apache-2.0 AND BSD-3-Clause)", - "optional": true, "peer": true }, "node_modules/@buttercup/fetch": { @@ -1888,6 +1867,7 @@ "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.3.tgz", "integrity": "sha512-QwCZW6Tt1siP37Jet9Tb02Zs81TQt6qQrZR2H+eGMcFsL1zMrk2/b9CLC7/9ieP1fjIUMgviLWMmgiHoJrj+ZA==", "license": "MIT", + "peer": true, "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.23.0", @@ -1977,6 +1957,7 @@ "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.6.0.tgz", "integrity": "sha512-4nbvra5R5EtiCzr9BTHiTLc+MLXK2QGiAVYMyi8PkQd3SR+6ixar/Q/01Fa21TBIDOZXgeWV4WppsQolSreAPQ==", "license": "MIT", + "peer": true, "dependencies": { "@marijn/find-cluster-break": "^1.0.0" } @@ -1986,6 +1967,7 @@ "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.1.tgz", "integrity": "sha512-+BIjw/AG3tDQ4pJgTLPYdAW25eDE66YsvM4LKyVPgGzVgZ4a9Wj1SRX8kPVKgBDdPt8oHtZ15F0qx7p0oOHdHw==", "license": "MIT", + "peer": true, "dependencies": { "@codemirror/state": "^6.6.0", "crelt": "^1.0.6", @@ -1998,7 +1980,7 @@ "resolved": "https://registry.npmjs.org/@connectrpc/connect/-/connect-1.7.0.tgz", "integrity": "sha512-iNKdJRi69YP3mq6AePRT8F/HrxWCewrhxnLMNm0vpqXAR8biwzRtO6Hjx80C6UvtKJ5sFmffQT7I4Baecz389w==", "license": "Apache-2.0", - "optional": true, + "peer": true, "peerDependencies": { "@bufbuild/protobuf": "^1.10.0" } @@ -2450,7 +2432,6 @@ "dev": true, "license": "BSD-2-Clause", "optional": true, - "peer": true, "dependencies": { "cross-dirname": "^0.1.0", "debug": "^4.3.4", @@ -2472,7 +2453,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", @@ -3220,6 +3200,15 @@ "url": "https://github.com/sponsors/ayuhito" } }, + "node_modules/@fontsource/mona-sans": { + "version": "5.2.8", + "resolved": "https://registry.npmjs.org/@fontsource/mona-sans/-/mona-sans-5.2.8.tgz", + "integrity": "sha512-xsZE75lQlcPx/WzAuz7EfOHyPbaOMoHU6FAeLUB3J4f8zjPe8g5Ifh8JCWID9vjpQM9Ty1UxqLXgCMVSktlOlw==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, "node_modules/@fontsource/space-grotesk": { "version": "5.2.10", "resolved": "https://registry.npmjs.org/@fontsource/space-grotesk/-/space-grotesk-5.2.10.tgz", @@ -3882,6 +3871,7 @@ "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz", "integrity": "sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==", "license": "MIT", + "peer": true, "dependencies": { "@lezer/common": "^1.3.0" } @@ -4164,6 +4154,7 @@ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz", "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==", "license": "MIT", + "peer": true, "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", @@ -7577,8 +7568,7 @@ "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz", "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==", "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/@standard-schema/spec": { "version": "1.1.0", @@ -8188,6 +8178,7 @@ "integrity": "sha512-hAAP5io/7csFStuOmR782YmTthKBJ9ND3WVL60hcOjvtGFb+HJxH4O5huAcmcZ9v9G8P+JETiZ/G1B8MALnWZQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.54.0", @@ -8217,6 +8208,7 @@ "integrity": "sha512-BtE0k6cjwjLZoZixN0t5AKP0kSzlGu7FctRXYuPAm//aaiZhmfq1JwdYpYr1brzEspYyFeF+8XF5j2VK6oalrA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.54.0", "@typescript-eslint/types": "8.54.0", @@ -8576,6 +8568,7 @@ "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.1.0-beta.220.tgz", "integrity": "sha512-rwEKE75wfwfNWeGnjl0iQRA1W50HigKoGcGMeF3o5CqDSdI9IjmwzpV9xHXqLH6CYj6s9N1g6bbKFVDou9dJ/A==", "license": "MIT", + "peer": true, "workspaces": [ "addons/*" ] @@ -8640,6 +8633,7 @@ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "license": "MIT", + "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -9340,6 +9334,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", @@ -10165,8 +10160,7 @@ "integrity": "sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q==", "dev": true, "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/cross-env": { "version": "10.1.0", @@ -10463,6 +10457,7 @@ "integrity": "sha512-fMkjRqKyPtsz4Kzu/qGP0BGjqzMCIgp+/7kw/u6YH6lvn/8hvL3c0TXhoFayBoYdpPCnEinnCHztd4bW7/jetA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "app-builder-lib": "26.15.2", "builder-util": "26.15.0", @@ -10744,7 +10739,6 @@ "dev": true, "hasInstallScript": true, "license": "MIT", - "peer": true, "dependencies": { "@electron/asar": "^3.2.1", "debug": "^4.1.1", @@ -10765,7 +10759,6 @@ "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "graceful-fs": "^4.1.2", "jsonfile": "^4.0.0", @@ -10781,7 +10774,6 @@ "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", "dev": true, "license": "MIT", - "peer": true, "optionalDependencies": { "graceful-fs": "^4.1.6" } @@ -10792,7 +10784,6 @@ "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">= 4.0.0" } @@ -11017,6 +11008,7 @@ "integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.1", @@ -11470,8 +11462,7 @@ "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz", "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==", "license": "Unlicense", - "optional": true, - "peer": true + "optional": true }, "node_modules/fast-uri": { "version": "3.1.0", @@ -12408,6 +12399,7 @@ "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.14.tgz", "integrity": "sha512-am5zfg3yu6sqn5yjKBNqhnTX7Cv+m00ox+7jbaKkrLMRJ4rAdldd1xPd/JzbBWspqaQv6RSTrgFN95EsfhC+7w==", "license": "MIT", + "peer": true, "engines": { "node": ">=16.9.0" } @@ -12864,7 +12856,6 @@ "resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz", "integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==", "license": "MIT", - "peer": true, "funding": { "type": "GitHub Sponsors ❤", "url": "https://github.com/sponsors/dmonad" @@ -12986,7 +12977,6 @@ "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", "license": "MIT", "optional": true, - "peer": true, "dependencies": { "@babel/runtime": "^7.18.3", "ts-algebra": "^2.0.0" @@ -13144,7 +13134,6 @@ "resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.117.tgz", "integrity": "sha512-DeXj9X5xDCjgKLU/7RR+/HQEVzuuEUiwldwOGsHK/sfAfELGWEyTcf0x+uOvCvK3O2zPmZePXWL85vtia6GyZw==", "license": "MIT", - "peer": true, "dependencies": { "isomorphic.js": "^0.2.4" }, @@ -14090,6 +14079,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", @@ -15210,7 +15200,6 @@ "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "minimist": "^1.2.6" }, @@ -15230,6 +15219,7 @@ "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.55.1.tgz", "integrity": "sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A==", "license": "MIT", + "peer": true, "dependencies": { "dompurify": "3.2.7", "marked": "14.0.0" @@ -15980,7 +15970,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "commander": "^9.4.0" }, @@ -15998,7 +15987,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": "^12.20.0 || >=14" } @@ -16303,6 +16291,7 @@ "resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz", "integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==", "license": "MIT", + "peer": true, "engines": { "node": ">=0.10.0" } @@ -16312,6 +16301,7 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz", "integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==", "license": "MIT", + "peer": true, "dependencies": { "scheduler": "^0.27.0" }, @@ -17649,7 +17639,6 @@ "integrity": "sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==", "license": "MIT", "optional": true, - "peer": true, "dependencies": { "@stablelib/base64": "^1.0.0", "fast-sha256": "^1.3.0" @@ -17955,7 +17944,6 @@ "integrity": "sha512-yYrrsWnrXMcdsnu/7YMYAofM1ktpL5By7vZhf15CrXijWWrEYZks5AXBudalfSWJLlnen/QUJUB5aoB0kqZUGA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "mkdirp": "^0.5.1", "rimraf": "~2.6.2" @@ -17982,7 +17970,6 @@ "deprecated": "Rimraf versions prior to v4 are no longer supported", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "glob": "^7.1.3" }, @@ -18057,6 +18044,7 @@ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -18151,8 +18139,7 @@ "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/ts-api-utils": { "version": "2.4.0", @@ -18179,6 +18166,7 @@ "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "esbuild": "~0.27.0", "get-tsconfig": "^4.7.5" @@ -18290,6 +18278,7 @@ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -18330,6 +18319,7 @@ "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz", "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==", "license": "MIT", + "peer": true, "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", @@ -18705,6 +18695,7 @@ "integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", @@ -18798,6 +18789,7 @@ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -19085,6 +19077,7 @@ "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", "license": "MIT", + "peer": true, "funding": { "url": "https://github.com/sponsors/colinhacks" } diff --git a/package.json b/package.json index 233ea0e33..8135d3d7b 100644 --- a/package.json +++ b/package.json @@ -46,7 +46,9 @@ "@ai-sdk/google": "^4.0.0", "@ai-sdk/openai": "^4.0.0", "@aws-sdk/client-s3": "^3.956.0", + "@connectrpc/connect": "^1.7.0", "@fontsource/jetbrains-mono": "^5.2.8", + "@fontsource/mona-sans": "^5.2.8", "@fontsource/space-grotesk": "^5.2.10", "@mdxeditor/editor": "^4.0.4", "@modelcontextprotocol/sdk": "^1.29.0", From 89ed8735e723252451f6c8f8744fd705f864d8ed Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 19:57:38 +0800 Subject: [PATCH 100/228] Embed system theme presets --- application/i18n/locales/en/core.ts | 3 - application/i18n/locales/ru/core.ts | 3 - application/i18n/locales/zh-CN/core.ts | 3 - components/SettingsPage.tsx | 1 + components/settings/UiThemePresetModal.tsx | 223 -- .../settings/tabs/SettingsAppearanceTab.tsx | 73 +- domain/terminalAppearance.test.ts | 25 + domain/terminalAppearance.ts | 125 +- infrastructure/config/terminalThemes.ts | 2 + .../config/terminalThemes/classic.ts | 8 +- infrastructure/config/terminalThemes/extra.ts | 34 +- .../config/terminalThemes/systemPresets.ts | 2975 +++++++++++++++++ infrastructure/config/uiThemes.test.ts | 113 +- infrastructure/config/uiThemes.ts | 2937 ++++++++++++++-- 14 files changed, 6001 insertions(+), 524 deletions(-) delete mode 100644 components/settings/UiThemePresetModal.tsx create mode 100644 infrastructure/config/terminalThemes/systemPresets.ts diff --git a/application/i18n/locales/en/core.ts b/application/i18n/locales/en/core.ts index 655c50992..a207e412e 100644 --- a/application/i18n/locales/en/core.ts +++ b/application/i18n/locales/en/core.ts @@ -267,9 +267,6 @@ export const enCoreMessages: Messages = { 'settings.appearance.theme.light': 'Light', 'settings.appearance.theme.dark': 'Dark', 'settings.appearance.theme.system': 'System', - 'settings.appearance.themePresets': 'Theme presets', - 'settings.appearance.themePresets.desc': 'Choose a Copilot-style palette', - 'settings.appearance.themePresets.modalTitle': 'Theme presets', 'settings.appearance.accentColor': 'Accent Color', 'settings.appearance.customColor': 'Custom color', 'settings.appearance.accentColor.mode': 'Use custom accent', diff --git a/application/i18n/locales/ru/core.ts b/application/i18n/locales/ru/core.ts index 5fb1b5a1f..4804a74a3 100644 --- a/application/i18n/locales/ru/core.ts +++ b/application/i18n/locales/ru/core.ts @@ -256,9 +256,6 @@ export const ruCoreMessages: Messages = { 'settings.appearance.theme.light': 'Светлая', 'settings.appearance.theme.dark': 'Тёмная', 'settings.appearance.theme.system': 'Системная', - 'settings.appearance.themePresets': 'Готовые темы', - 'settings.appearance.themePresets.desc': 'Выберите палитру в стиле Copilot', - 'settings.appearance.themePresets.modalTitle': 'Готовые темы', 'settings.appearance.accentColor': 'Акцентный цвет', 'settings.appearance.customColor': 'Пользовательский цвет', 'settings.appearance.accentColor.mode': 'Использовать свой акцент', diff --git a/application/i18n/locales/zh-CN/core.ts b/application/i18n/locales/zh-CN/core.ts index 29b3017e4..b8509ba2c 100644 --- a/application/i18n/locales/zh-CN/core.ts +++ b/application/i18n/locales/zh-CN/core.ts @@ -253,9 +253,6 @@ export const zhCNCoreMessages: Messages = { 'settings.appearance.theme.light': '浅色', 'settings.appearance.theme.dark': '深色', 'settings.appearance.theme.system': '系统', - 'settings.appearance.themePresets': '主题预设', - 'settings.appearance.themePresets.desc': '选择 Copilot 风格配色', - 'settings.appearance.themePresets.modalTitle': '主题预设', 'settings.appearance.accentColor': '强调色', 'settings.appearance.customColor': '自定义颜色', 'settings.appearance.accentColor.mode': '使用自定义强调色', diff --git a/components/SettingsPage.tsx b/components/SettingsPage.tsx index 45ebfd5d3..79f0868d8 100644 --- a/components/SettingsPage.tsx +++ b/components/SettingsPage.tsx @@ -411,6 +411,7 @@ const SettingsPageContent: React.FC<{ settings: SettingsState }> = ({ settings } void; - presets: UiThemePreset[]; - selectedThemeId: string; - onSelect: (themeId: string) => void; -}; - -const hsl = (value: string, alpha?: number) => ( - alpha === undefined ? `hsl(${value})` : `hsl(${value} / ${alpha})` -); - -const PreviewLine = ({ - color, - width, - alpha = 0.22, -}: { - color: string; - width: string; - alpha?: number; -}) => ( - -); - -const ThemePreview = ({ preset }: { preset: UiThemePreset }) => { - const { tokens } = preset; - const preview = preset.preview ?? { - sidebar: tokens.secondary, - activity: [tokens.destructive, tokens.primary, tokens.secondary, tokens.ring], - syntax: [tokens.primary, tokens.destructive, tokens.accent, tokens.ring], - }; - const activity = preview.activity.slice(0, 5); - const syntax = preview.syntax.slice(0, 4); - - return ( -
-
-
-
- {[0, 1, 2].map((dot) => ( - - ))} -
-
- - - -
-
- -
- - -
-
-
-
-
-
- - -
- -
-
- - -
-
-
- - - -
-
- - - -
-
-
- - -
-
-
-
- {activity.map((stripe, index) => ( - - ))} -
-
- ); -}; - -export function UiThemePresetModal({ - open, - onClose, - presets, - selectedThemeId, - onSelect, -}: UiThemePresetModalProps) { - const { t } = useI18n(); - const handleThemeSelect = useCallback((themeId: string) => { - onSelect(themeId); - onClose(); - }, [onClose, onSelect]); - - useEffect(() => { - if (!open) return; - const handleKeyDown = (event: KeyboardEvent) => { - if (event.key === "Escape") onClose(); - }; - document.addEventListener("keydown", handleKeyDown); - return () => document.removeEventListener("keydown", handleKeyDown); - }, [onClose, open]); - - const handleBackdropClick = useCallback((event: React.MouseEvent) => { - if (event.target === event.currentTarget) onClose(); - }, [onClose]); - - if (!open) return null; - - const modalTitleId = "ui-theme-preset-modal-title"; - - return createPortal( -
-
event.stopPropagation()} - > -
-
-
- -
-

- {t("settings.appearance.themePresets.modalTitle")} -

-
- -
-
-
- {presets.map((preset) => { - const selected = selectedThemeId === preset.id; - return ( - - ); - })} -
-
-
-
, - document.body, - ); -} - -export default UiThemePresetModal; diff --git a/components/settings/tabs/SettingsAppearanceTab.tsx b/components/settings/tabs/SettingsAppearanceTab.tsx index 5f6958c75..44d8678b7 100644 --- a/components/settings/tabs/SettingsAppearanceTab.tsx +++ b/components/settings/tabs/SettingsAppearanceTab.tsx @@ -1,23 +1,19 @@ -import React, { memo, useCallback, useState } from "react"; +import React, { memo, useCallback } from "react"; import { applyCustomCssToDocument } from "../../../lib/customCss"; import { DebouncedTextarea } from "../DebouncedTextarea"; import { Check, Monitor, Moon, Palette, Sun } from "lucide-react"; import { useI18n } from "../../../application/i18n/I18nProvider"; -import { - COPILOT_LIGHT_UI_THEMES, - DARK_UI_THEMES, - LIGHT_UI_THEMES, -} from "../../../infrastructure/config/uiThemes"; +import { DARK_UI_THEMES, LIGHT_UI_THEMES } from "../../../infrastructure/config/uiThemes"; import { useAvailableUIFonts } from "../../../application/state/uiFontStore"; import { SUPPORTED_UI_LOCALES } from "../../../infrastructure/config/i18n"; import { cn } from "../../../lib/utils"; import { SectionHeader, SettingsTabContent, SettingRow, Toggle, Select } from "../settings-ui"; import { FontSelect } from "../FontSelect"; import { Tooltip, TooltipContent, TooltipTrigger } from "../../ui/tooltip"; -import { UiThemePresetModal } from "../UiThemePresetModal"; function SettingsAppearanceTab(props: { theme: "dark" | "light" | "system"; + resolvedTheme: "dark" | "light"; setTheme: (theme: "dark" | "light" | "system") => void; lightUiThemeId: string; setLightUiThemeId: (themeId: string) => void; @@ -46,9 +42,9 @@ function SettingsAppearanceTab(props: { }) { const { t } = useI18n(); const availableUIFonts = useAvailableUIFonts(); - const [themePresetModalOpen, setThemePresetModalOpen] = useState(false); const { theme, + resolvedTheme, setTheme, lightUiThemeId, setLightUiThemeId, @@ -83,7 +79,6 @@ function SettingsAppearanceTab(props: { ] as const; const getHslStyle = useCallback((hsl: string) => ({ backgroundColor: `hsl(${hsl})` }), []); - const selectedLightTheme = LIGHT_UI_THEMES.find((preset) => preset.id === lightUiThemeId) ?? LIGHT_UI_THEMES[0]; const hexToHsl = useCallback((hex: string) => { const r = parseInt(hex.slice(1, 3), 16) / 255; @@ -144,7 +139,7 @@ function SettingsAppearanceTab(props: { value: string, onChange: (next: string) => void, ) => ( -
+
{options.map((preset) => ( @@ -167,11 +162,9 @@ function SettingsAppearanceTab(props: {
); - const handlePresetSelect = useCallback((themeId: string) => { - setTheme("light"); - setLightUiThemeId(themeId); - setAccentMode("theme"); - }, [setAccentMode, setLightUiThemeId, setTheme]); + const visibleUiThemes = resolvedTheme === "dark" ? DARK_UI_THEMES : LIGHT_UI_THEMES; + const visibleUiThemeId = resolvedTheme === "dark" ? darkUiThemeId : lightUiThemeId; + const setVisibleUiThemeId = resolvedTheme === "dark" ? setDarkUiThemeId : setLightUiThemeId; return ( @@ -245,10 +238,7 @@ function SettingsAppearanceTab(props: {
- +
{THEME_OPTIONS.map((opt) => ( - -
- setThemePresetModalOpen(false)} - presets={COPILOT_LIGHT_UI_THEMES} - selectedThemeId={lightUiThemeId} - onSelect={handlePresetSelect} - /> - - -
+
+
+ {resolvedTheme === "dark" + ? t("settings.appearance.themeColor.dark") + : t("settings.appearance.themeColor.light")} +
+ {renderThemeSwatches(visibleUiThemes, visibleUiThemeId, setVisibleUiThemeId)} +
- -
- - {renderThemeSwatches(LIGHT_UI_THEMES, lightUiThemeId, setLightUiThemeId)} - - - {renderThemeSwatches(DARK_UI_THEMES, darkUiThemeId, setDarkUiThemeId)} - -
-
{ + assert.equal( + resolveFollowedTerminalThemeId({ + resolvedTheme: "light", + terminalThemeDarkId: TERMINAL_THEME_AUTO, + terminalThemeLightId: TERMINAL_THEME_AUTO, + lightUiThemeId: "github", + darkUiThemeId: "github", + fallbackThemeId: "netcatty-dark", + }), + "system-github-light", + ); + assert.equal( + resolveFollowedTerminalThemeId({ + resolvedTheme: "dark", + terminalThemeDarkId: TERMINAL_THEME_AUTO, + terminalThemeLightId: TERMINAL_THEME_AUTO, + lightUiThemeId: "github", + darkUiThemeId: "github", + fallbackThemeId: "netcatty-dark", + }), + "system-github-dark", + ); +}); + test("follow-theme resolver: explicit dark override wins over auto-matching", () => { assert.equal( resolveFollowedTerminalThemeId({ diff --git a/domain/terminalAppearance.ts b/domain/terminalAppearance.ts index 4252d5a12..b8aabb117 100644 --- a/domain/terminalAppearance.ts +++ b/domain/terminalAppearance.ts @@ -88,8 +88,127 @@ const UI_TO_TERMINAL_THEME: Record = { 'forest': 'ui-forest', }; -export const getTerminalThemeForUiTheme = (uiThemeId: string): string | undefined => - UI_TO_TERMINAL_THEME[uiThemeId]; +const SYSTEM_LIGHT_UI_TO_TERMINAL_THEME: Record = { + "a-cup-of-coffee": "system-a-cup-of-coffee-light", + "abolkog": "system-abolkog-light", + "aurora": "system-aurora-light", + "ayu": "system-ayu-light", + "base16-flat": "system-base16-flat-light", + "base16-mocha": "system-base16-mocha-light", + "blue-dolphin": "system-blue-dolphin-light", + "calm-days-sober-nights-sky": "system-calm-days-sober-nights-sky-light", + "catppuccin": "system-catppuccin-light", + "chai": "system-chai-light", + "chinolor": "system-chinolor-light", + "cyberdyne": "system-cyberdyne-light", + "desert": "system-desert-light", + "django-reborn-again": "system-django-reborn-again-light", + "espresso": "system-espresso-light", + "eyehealth": "system-eyehealth-light", + "flexoki": "system-flexoki-light", + "fox": "system-fox-light", + "garbage-oracle": "system-garbage-oracle-light", + "github": "system-github-light", + "gruvbox-material": "system-gruvbox-material-light", + "homebrew": "system-homebrew-light", + "ic-orange-ppl": "system-ic-orange-ppl-light", + "ikki": "system-ikki-light", + "kanso-ink": "system-kanso-ink-light", + "kary-pro-colors": "system-kary-pro-colors-light", + "light-purple": "system-light-purple-light", + "mondrian": "system-mondrian-light", + "monochrome": "system-monochrome-light", + "monochrome-stone": "system-monochrome-stone-light", + "monokai-pro-spectrum": "system-monokai-pro-spectrum-light", + "monospace": "system-monospace-light", + "noctis-azureus": "system-noctis-azureus-light", + "noctis-hibernus": "system-noctis-hibernus-light", + "noir-essence": "system-noir-essence-light", + "nord-midnight": "system-nord-midnight-light", + "notionish": "system-notionish-light", + "phonebook": "system-phonebook-light", + "polychrome": "system-polychrome-light", + "purplepeter": "system-purplepeter-light", + "rainglow-codecourse": "system-rainglow-codecourse-light", + "rainglow-crisp": "system-rainglow-crisp-light", + "rainglow-lavender": "system-rainglow-lavender-light", + "remedy-tilted": "system-remedy-tilted-light", + "rose-pine": "system-rose-pine-light", + "selene-selenized": "system-selene-selenized-light", + "soft-color": "system-soft-color-light", + "tearout": "system-tearout-light", + "tokyo-night": "system-tokyo-night-light", + "tomorrow-night-eighties": "system-tomorrow-night-eighties-light", + "vaporizer-turquoise": "system-vaporizer-turquoise-light", + "xotopio": "system-xotopio-light", + "yuttari": "system-yuttari-light", + "zenbones-rosebones": "system-zenbones-rosebones-light", + "zhxo-red": "system-zhxo-red-light", +}; + +const SYSTEM_DARK_UI_TO_TERMINAL_THEME: Record = { + "a-cup-of-coffee": "system-a-cup-of-coffee-dark", + "abolkog": "system-abolkog-dark", + "aurora": "system-aurora-dark", + "ayu": "system-ayu-dark", + "base16-flat": "system-base16-flat-dark", + "base16-mocha": "system-base16-mocha-dark", + "blue-dolphin": "system-blue-dolphin-dark", + "calm-days-sober-nights-sky": "system-calm-days-sober-nights-sky-dark", + "catppuccin": "system-catppuccin-dark", + "chai": "system-chai-dark", + "chinolor": "system-chinolor-dark", + "cyberdyne": "system-cyberdyne-dark", + "desert": "system-desert-dark", + "django-reborn-again": "system-django-reborn-again-dark", + "espresso": "system-espresso-dark", + "eyehealth": "system-eyehealth-dark", + "flexoki": "system-flexoki-dark", + "fox": "system-fox-dark", + "garbage-oracle": "system-garbage-oracle-dark", + "github": "system-github-dark", + "gruvbox-material": "system-gruvbox-material-dark", + "homebrew": "system-homebrew-dark", + "ic-orange-ppl": "system-ic-orange-ppl-dark", + "ikki": "system-ikki-dark", + "kanso-ink": "system-kanso-ink-dark", + "kary-pro-colors": "system-kary-pro-colors-dark", + "light-purple": "system-light-purple-dark", + "mondrian": "system-mondrian-dark", + "monochrome": "system-monochrome-dark", + "monochrome-stone": "system-monochrome-stone-dark", + "monokai-pro-spectrum": "system-monokai-pro-spectrum-dark", + "monospace": "system-monospace-dark", + "noctis-azureus": "system-noctis-azureus-dark", + "noctis-hibernus": "system-noctis-hibernus-dark", + "noir-essence": "system-noir-essence-dark", + "nord-midnight": "system-nord-midnight-dark", + "notionish": "system-notionish-dark", + "phonebook": "system-phonebook-dark", + "polychrome": "system-polychrome-dark", + "purplepeter": "system-purplepeter-dark", + "rainglow-codecourse": "system-rainglow-codecourse-dark", + "rainglow-crisp": "system-rainglow-crisp-dark", + "rainglow-lavender": "system-rainglow-lavender-dark", + "remedy-tilted": "system-remedy-tilted-dark", + "rose-pine": "system-rose-pine-dark", + "selene-selenized": "system-selene-selenized-dark", + "soft-color": "system-soft-color-dark", + "tearout": "system-tearout-dark", + "tokyo-night": "system-tokyo-night-dark", + "tomorrow-night-eighties": "system-tomorrow-night-eighties-dark", + "vaporizer-turquoise": "system-vaporizer-turquoise-dark", + "xotopio": "system-xotopio-dark", + "yuttari": "system-yuttari-dark", + "zenbones-rosebones": "system-zenbones-rosebones-dark", + "zhxo-red": "system-zhxo-red-dark", +}; + +export const getTerminalThemeForUiTheme = (uiThemeId: string, resolvedTheme?: 'light' | 'dark'): string | undefined => { + if (resolvedTheme === 'light') return SYSTEM_LIGHT_UI_TO_TERMINAL_THEME[uiThemeId] ?? UI_TO_TERMINAL_THEME[uiThemeId]; + if (resolvedTheme === 'dark') return SYSTEM_DARK_UI_TO_TERMINAL_THEME[uiThemeId] ?? UI_TO_TERMINAL_THEME[uiThemeId]; + return UI_TO_TERMINAL_THEME[uiThemeId]; +}; /** * Sentinel stored in the per-mode follow-theme settings meaning "let the @@ -121,7 +240,7 @@ export const resolveFollowedTerminalThemeId = (args: { const activeUiThemeId = args.resolvedTheme === 'dark' ? args.darkUiThemeId : args.lightUiThemeId; - return getTerminalThemeForUiTheme(activeUiThemeId) ?? args.fallbackThemeId; + return getTerminalThemeForUiTheme(activeUiThemeId, args.resolvedTheme) ?? args.fallbackThemeId; }; export const getFollowAppTerminalThemeSelectionUpdate = ( diff --git a/infrastructure/config/terminalThemes.ts b/infrastructure/config/terminalThemes.ts index 7bc4c4a0b..30d616aae 100755 --- a/infrastructure/config/terminalThemes.ts +++ b/infrastructure/config/terminalThemes.ts @@ -1,5 +1,6 @@ import type { TerminalTheme } from '../../domain/models'; import { classicTerminalThemes } from './terminalThemes/classic'; +import { systemPresetTerminalThemes } from './terminalThemes/systemPresets'; import { coreTerminalThemes } from './terminalThemes/core'; import { extraTerminalThemes } from './terminalThemes/extra'; import { modernTerminalThemes } from './terminalThemes/modern'; @@ -30,6 +31,7 @@ export const TERMINAL_THEMES: TerminalTheme[] = [ ...uiMatchTerminalThemes, ...modernTerminalThemes, ...classicTerminalThemes, + ...systemPresetTerminalThemes, ...extraTerminalThemes, ]; diff --git a/infrastructure/config/terminalThemes/classic.ts b/infrastructure/config/terminalThemes/classic.ts index 394ba1654..6cab010d6 100644 --- a/infrastructure/config/terminalThemes/classic.ts +++ b/infrastructure/config/terminalThemes/classic.ts @@ -224,16 +224,16 @@ export const classicTerminalThemes: TerminalTheme[] = [ colors: { background: '#1a1b26', foreground: '#c0caf5', - cursor: '#7aa2f7', - selection: '#33467c', - black: '#15202b', + cursor: '#7dcfff', + selection: '#3c5870', + black: '#15161e', red: '#f7768e', green: '#9ece6a', yellow: '#e0af68', blue: '#7aa2f7', magenta: '#bb9af7', cyan: '#7dcfff', - white: '#c0caf5', + white: '#a9b1d6', brightBlack: '#414868', brightRed: '#f7768e', brightGreen: '#9ece6a', diff --git a/infrastructure/config/terminalThemes/extra.ts b/infrastructure/config/terminalThemes/extra.ts index 55b80fb49..950fef4ca 100644 --- a/infrastructure/config/terminalThemes/extra.ts +++ b/infrastructure/config/terminalThemes/extra.ts @@ -35,24 +35,24 @@ export const extraTerminalThemes: TerminalTheme[] = [ colors: { background: '#000000', foreground: '#00ff00', - cursor: '#00ff00', - selection: '#003300', + cursor: '#00a6b2', + selection: '#00383d', black: '#000000', - red: '#ff0000', - green: '#00ff00', - yellow: '#ffff00', - blue: '#0000ff', - magenta: '#ff00ff', - cyan: '#00ffff', - white: '#ffffff', - brightBlack: '#808080', - brightRed: '#ff0000', - brightGreen: '#00ff00', - brightYellow: '#ffff00', - brightBlue: '#0000ff', - brightMagenta: '#ff00ff', - brightCyan: '#00ffff', - brightWhite: '#ffffff' + red: '#990000', + green: '#00a600', + yellow: '#999900', + blue: '#4d72ff', + magenta: '#b200b2', + cyan: '#00a6b2', + white: '#bfbfbf', + brightBlack: '#666666', + brightRed: '#e50000', + brightGreen: '#00d900', + brightYellow: '#e5e500', + brightBlue: '#5a7aff', + brightMagenta: '#e500e5', + brightCyan: '#00e5e5', + brightWhite: '#e5e5e5' } }, { diff --git a/infrastructure/config/terminalThemes/systemPresets.ts b/infrastructure/config/terminalThemes/systemPresets.ts new file mode 100644 index 000000000..6b52fe38e --- /dev/null +++ b/infrastructure/config/terminalThemes/systemPresets.ts @@ -0,0 +1,2975 @@ +import type { TerminalTheme } from '../../../domain/models'; + +// Embedded system theme presets. +export const systemPresetTerminalThemes: TerminalTheme[] = [ + { + id: "system-a-cup-of-coffee-light", + name: "A cup of coffee Light", + type: "light", + colors: { + background: "#fbfbfb", + foreground: "#000000", + cursor: "#0451a5", + selection: "#c0d2e6", + black: "#000000", + red: "#cd3131", + green: "#00bc00", + yellow: "#949800", + blue: "#0451a5", + magenta: "#bc05bc", + cyan: "#0598bc", + white: "#555555", + brightBlack: "#666666", + brightRed: "#cd3131", + brightGreen: "#14ce14", + brightYellow: "#b5ba00", + brightBlue: "#0451a5", + brightMagenta: "#bc05bc", + brightCyan: "#0598bc", + brightWhite: "#a5a5a5", + }, + }, + { + id: "system-a-cup-of-coffee-dark", + name: "A cup of coffee Dark", + type: "dark", + colors: { + background: "#1e1e1e", + foreground: "#bebebe", + cursor: "#e5e510", + selection: "#626219", + black: "#929292", + red: "#cd3131", + green: "#0dbc79", + yellow: "#e5e510", + blue: "#2472c8", + magenta: "#bc3fbc", + cyan: "#11a8cd", + white: "#e5e5e5", + brightBlack: "#666666", + brightRed: "#f14c4c", + brightGreen: "#23d18b", + brightYellow: "#f5f543", + brightBlue: "#3b8eea", + brightMagenta: "#d670d6", + brightCyan: "#29b8db", + brightWhite: "#e5e5e5", + }, + }, + { + id: "system-abolkog-light", + name: "ABOLKOG Light", + type: "light", + colors: { + background: "#ffffff", + foreground: "#24292e", + cursor: "#ebcb8b", + selection: "#faf3e3", + black: "#3b4252", + red: "#bf616a", + green: "#a3be8c", + yellow: "#ebcb8b", + blue: "#81a1c1", + magenta: "#b48ead", + cyan: "#88c0d0", + white: "#e5e9f0", + brightBlack: "#4c566a", + brightRed: "#bf616a", + brightGreen: "#a3be8c", + brightYellow: "#ebcb8b", + brightBlue: "#81a1c1", + brightMagenta: "#b48ead", + brightCyan: "#8fbcbb", + brightWhite: "#eceff4", + }, + }, + { + id: "system-abolkog-dark", + name: "ABOLKOG Dark", + type: "dark", + colors: { + background: "#282c34", + foreground: "#d8dee9", + cursor: "#ebcb8b", + selection: "#6a6252", + black: "#3b4252", + red: "#bf616a", + green: "#a3be8c", + yellow: "#ebcb8b", + blue: "#81a1c1", + magenta: "#b48ead", + cyan: "#88c0d0", + white: "#e5e9f0", + brightBlack: "#4c566a", + brightRed: "#bf616a", + brightGreen: "#a3be8c", + brightYellow: "#ebcb8b", + brightBlue: "#81a1c1", + brightMagenta: "#b48ead", + brightCyan: "#8fbcbb", + brightWhite: "#eceff4", + }, + }, + { + id: "system-aurora-light", + name: "Aurora Light", + type: "light", + colors: { + background: "#fdf5de", + foreground: "#4a3200", + cursor: "#007060", + selection: "#c0d5c0", + black: "#2a2d38", + red: "#b80038", + green: "#3a7a20", + yellow: "#8a6000", + blue: "#2040c8", + magenta: "#b82c1c", + cyan: "#007060", + white: "#7015b0", + brightBlack: "#4c505e", + brightRed: "#d0104c", + brightGreen: "#4a9c30", + brightYellow: "#a07800", + brightBlue: "#007060", + brightMagenta: "#c43828", + brightCyan: "#007060", + brightWhite: "#9028d0", + }, + }, + { + id: "system-aurora-dark", + name: "Aurora Dark", + type: "dark", + colors: { + background: "#23262e", + foreground: "#ffca28", + cursor: "#03d6b8", + selection: "#18625d", + black: "#23262e", + red: "#f0266f", + green: "#8fd46d", + yellow: "#ffe66d", + blue: "#4f6ef7", + magenta: "#ee5d43", + cyan: "#03d6b8", + white: "#c74ded", + brightBlack: "#4f545e", + brightRed: "#f92672", + brightGreen: "#8fd46d", + brightYellow: "#ffe66d", + brightBlue: "#6680ff", + brightMagenta: "#ee5d43", + brightCyan: "#03d6b8", + brightWhite: "#c74ded", + }, + }, + { + id: "system-ayu-light", + name: "Ayu Light", + type: "light", + colors: { + background: "#f8f9fa", + foreground: "#5c6166", + cursor: "#86b300", + selection: "#dde8be", + black: "#86878c", + red: "#f07171", + green: "#86b300", + yellow: "#eba400", + blue: "#22a4e6", + magenta: "#a37acc", + cyan: "#4cbf99", + white: "#adaeb1", + brightBlack: "#939498", + brightRed: "#f07171", + brightGreen: "#86b300", + brightYellow: "#eba400", + brightBlue: "#22a4e6", + brightMagenta: "#a37acc", + brightCyan: "#4cbf99", + brightWhite: "#c5c5c8", + }, + }, + { + id: "system-ayu-dark", + name: "Ayu Dark", + type: "dark", + colors: { + background: "#1f2430", + foreground: "#cccac2", + cursor: "#d09ffd", + selection: "#5b4e76", + black: "#0a0000", + red: "#f06b5c", + green: "#bfe76d", + yellow: "#e6b752", + blue: "#3bbbf4", + magenta: "#d09ffd", + cyan: "#84ceb5", + white: "#d2d6dc", + brightBlack: "#0a0000", + brightRed: "#f39184", + brightGreen: "#d5ff80", + brightYellow: "#ffcd66", + brightBlue: "#73d0ff", + brightMagenta: "#dfbfff", + brightCyan: "#95e6cb", + brightWhite: "#e3e6ea", + }, + }, + { + id: "system-base16-flat-light", + name: "Base16 Flat Light", + type: "light", + colors: { + background: "#ecf0f1", + foreground: "#7f8c8d", + cursor: "#3498db", + selection: "#c0dbec", + black: "#e0e0e0", + red: "#e74c3c", + green: "#2ecc71", + yellow: "#e67e22", + blue: "#3498db", + magenta: "#9b59b6", + cyan: "#1abc9c", + white: "#34495e", + brightBlack: "#bdc3c7", + brightRed: "#e74c3c", + brightGreen: "#2ecc71", + brightYellow: "#f1c40f", + brightBlue: "#3498db", + brightMagenta: "#9b59b6", + brightCyan: "#1abc9c", + brightWhite: "#2c3e50", + }, + }, + { + id: "system-base16-flat-dark", + name: "Base16 Flat Dark", + type: "dark", + colors: { + background: "#2c3e50", + foreground: "#e0e0e0", + cursor: "#1abc9c", + selection: "#26696a", + black: "#7f8c8d", + red: "#e74c3c", + green: "#2ecc71", + yellow: "#e67e22", + blue: "#3498db", + magenta: "#9b59b6", + cyan: "#1abc9c", + white: "#f5f5f5", + brightBlack: "#95a5a6", + brightRed: "#e74c3c", + brightGreen: "#2ecc71", + brightYellow: "#f1c40f", + brightBlue: "#3498db", + brightMagenta: "#9b59b6", + brightCyan: "#1abc9c", + brightWhite: "#ecf0f1", + }, + }, + { + id: "system-base16-mocha-light", + name: "Base16 Mocha Light", + type: "light", + colors: { + background: "#f5eeeb", + foreground: "#645240", + cursor: "#d28b71", + selection: "#edd6ce", + black: "#d0c8c6", + red: "#cb6077", + green: "#beb55b", + yellow: "#d28b71", + blue: "#8ab3b5", + magenta: "#a89bb9", + cyan: "#7bbda4", + white: "#534636", + brightBlack: "#b8afad", + brightRed: "#cb6077", + brightGreen: "#beb55b", + brightYellow: "#f4bc87", + brightBlue: "#8ab3b5", + brightMagenta: "#a89bb9", + brightCyan: "#7bbda4", + brightWhite: "#3b3228", + }, + }, + { + id: "system-base16-mocha-dark", + name: "Base16 Mocha Dark", + type: "dark", + colors: { + background: "#3b3228", + foreground: "#d0c8c6", + cursor: "#d28b71", + selection: "#6e5041", + black: "#645240", + red: "#cb6077", + green: "#beb55b", + yellow: "#d28b71", + blue: "#8ab3b5", + magenta: "#a89bb9", + cyan: "#7bbda4", + white: "#e9e1dd", + brightBlack: "#7e705a", + brightRed: "#cb6077", + brightGreen: "#beb55b", + brightYellow: "#f4bc87", + brightBlue: "#8ab3b5", + brightMagenta: "#a89bb9", + brightCyan: "#7bbda4", + brightWhite: "#f5eeeb", + }, + }, + { + id: "system-blue-dolphin-light", + name: "Blue Dolphin Light", + type: "light", + colors: { + background: "#eaf3f6", + foreground: "#0d343f", + cursor: "#006080", + selection: "#b2d0da", + black: "#1a2030", + red: "#b82838", + green: "#1a6828", + yellow: "#7a5800", + blue: "#1a58a0", + magenta: "#6028a0", + cyan: "#006080", + white: "#383838", + brightBlack: "#485870", + brightRed: "#d03040", + brightGreen: "#1a8038", + brightYellow: "#9a7000", + brightBlue: "#2070c0", + brightMagenta: "#7038b8", + brightCyan: "#008098", + brightWhite: "#606060", + }, + }, + { + id: "system-blue-dolphin-dark", + name: "Blue Dolphin Dark", + type: "dark", + colors: { + background: "#006984", + foreground: "#c5f2ff", + cursor: "#aac8ff", + selection: "#3a89ae", + black: "#292d3e", + red: "#ff8288", + green: "#b4e88d", + yellow: "#f4d69f", + blue: "#aac8ff", + magenta: "#d8a8ff", + cyan: "#89ebff", + white: "#d0d0d0", + brightBlack: "#838798", + brightRed: "#ff8b92", + brightGreen: "#ddffa7", + brightYellow: "#ffe585", + brightBlue: "#c0d8ff", + brightMagenta: "#e8c0ff", + brightCyan: "#a3f7ff", + brightWhite: "#ffffff", + }, + }, + { + id: "system-calm-days-sober-nights-sky-light", + name: "Calm Days, Sober Nights Sky Light", + type: "light", + colors: { + background: "#ffffff", + foreground: "#687082", + cursor: "#00b342", + selection: "#c2edd2", + black: "#000000", + red: "#eb6c81", + green: "#00b342", + yellow: "#edc045", + blue: "#2ea0d1", + magenta: "#b375c7", + cyan: "#46acba", + white: "#c5cde0", + brightBlack: "#929bb0", + brightRed: "#f07186", + brightGreen: "#00b342", + brightYellow: "#f2c549", + brightBlue: "#36a6d6", + brightMagenta: "#b87acc", + brightCyan: "#4cb2bf", + brightWhite: "#dae1f0", + }, + }, + { + id: "system-calm-days-sober-nights-sky-dark", + name: "Calm Days, Sober Nights Sky Dark", + type: "dark", + colors: { + background: "#192030", + foreground: "#d3dae8", + cursor: "#6ed0fa", + selection: "#365c75", + black: "#000000", + red: "#ed7480", + green: "#70cc92", + yellow: "#f2d988", + blue: "#6ed0fa", + magenta: "#eab9fa", + cyan: "#90d7e0", + white: "#d2ddfa", + brightBlack: "#63708c", + brightRed: "#f27985", + brightGreen: "#70cc92", + brightYellow: "#f7dd8d", + brightBlue: "#73d5ff", + brightMagenta: "#efbfff", + brightCyan: "#95dde6", + brightWhite: "#ffffff", + }, + }, + { + id: "system-catppuccin-light", + name: "Catppuccin Light", + type: "light", + colors: { + background: "#eff1f5", + foreground: "#4c4f69", + cursor: "#1e66f5", + selection: "#bdd0f5", + black: "#5c5f77", + red: "#d20f39", + green: "#40a02b", + yellow: "#df8e1d", + blue: "#1e66f5", + magenta: "#ea76cb", + cyan: "#179299", + white: "#acb0be", + brightBlack: "#6c6f85", + brightRed: "#d20f39", + brightGreen: "#40a02b", + brightYellow: "#df8e1d", + brightBlue: "#1e66f5", + brightMagenta: "#ea76cb", + brightCyan: "#179299", + brightWhite: "#bcc0cc", + }, + }, + { + id: "system-catppuccin-dark", + name: "Catppuccin Dark", + type: "dark", + colors: { + background: "#303446", + foreground: "#c6d0f5", + cursor: "#f4b8e4", + selection: "#73617c", + black: "#51576d", + red: "#e78284", + green: "#a6d189", + yellow: "#e5c890", + blue: "#8caaee", + magenta: "#f4b8e4", + cyan: "#81c8be", + white: "#a5adce", + brightBlack: "#626880", + brightRed: "#e78284", + brightGreen: "#a6d189", + brightYellow: "#e5c890", + brightBlue: "#8caaee", + brightMagenta: "#f4b8e4", + brightCyan: "#81c8be", + brightWhite: "#b5bfe2", + }, + }, + { + id: "system-chai-light", + name: "Chai Light", + type: "light", + colors: { + background: "#f7f7f7", + foreground: "#383a42", + cursor: "#823ef0", + selection: "#dbcbf5", + black: "#373a41", + red: "#d52652", + green: "#239749", + yellow: "#df621b", + blue: "#275fe4", + magenta: "#823ef0", + cyan: "#26608c", + white: "#b9bac1", + brightBlack: "#676a77", + brightRed: "#ff637f", + brightGreen: "#3cbc66", + brightYellow: "#c5a231", + brightBlue: "#0099e0", + brightMagenta: "#ce32c0", + brightCyan: "#6d92ba", + brightWhite: "#d3d3d3", + }, + }, + { + id: "system-chai-dark", + name: "Chai Dark", + type: "dark", + colors: { + background: "#010107", + foreground: "#becfda", + cursor: "#49ace9", + selection: "#193b54", + black: "#28353e", + red: "#e66533", + green: "#49e9a6", + yellow: "#e4b781", + blue: "#49ace9", + magenta: "#df769b", + cyan: "#49d6e9", + white: "#aec3d0", + brightBlack: "#475e6c", + brightRed: "#e97749", + brightGreen: "#60ebb1", + brightYellow: "#e69533", + brightBlue: "#60b6eb", + brightMagenta: "#e798b3", + brightCyan: "#60dbeb", + brightWhite: "#becfda", + }, + }, + { + id: "system-chinolor-light", + name: "Chinolor Light", + type: "light", + colors: { + background: "#f8f4ed", + foreground: "#2b312c", + cursor: "#7a6200", + selection: "#dad1b4", + black: "#000000", + red: "#ee3f4d", + green: "#96c24e", + yellow: "#7a6200", + blue: "#619ac3", + magenta: "#d276a3", + cyan: "#57c3c2", + white: "#e4dfd7", + brightBlack: "#2b312c", + brightRed: "#ee3f4d", + brightGreen: "#41ae3c", + brightYellow: "#b78d12", + brightBlue: "#619ac3", + brightMagenta: "#cc5595", + brightCyan: "#12aa9c", + brightWhite: "#f8f4ed", + }, + }, + { + id: "system-chinolor-dark", + name: "Chinolor Dark", + type: "dark", + colors: { + background: "#2b312c", + foreground: "#e4dfd7", + cursor: "#f9d367", + selection: "#716840", + black: "#000000", + red: "#ee3f4d", + green: "#96c24e", + yellow: "#f9d367", + blue: "#619ac3", + magenta: "#d276a3", + cyan: "#57c3c2", + white: "#e4dfd7", + brightBlack: "#8a988e", + brightRed: "#ee3f4d", + brightGreen: "#41ae3c", + brightYellow: "#b78d12", + brightBlue: "#619ac3", + brightMagenta: "#cc5595", + brightCyan: "#12aa9c", + brightWhite: "#f8f4ed", + }, + }, + { + id: "system-cyberdyne-light", + name: "Cyberdyne Light", + type: "light", + colors: { + background: "#edecf3", + foreground: "#0a3824", + cursor: "#0048a0", + selection: "#b4c5df", + black: "#080808", + red: "#b83018", + green: "#006838", + yellow: "#786000", + blue: "#0048a0", + magenta: "#8050b0", + cyan: "#008068", + white: "#484848", + brightBlack: "#404040", + brightRed: "#d85038", + brightGreen: "#308040", + brightYellow: "#987828", + brightBlue: "#4880c8", + brightMagenta: "#a060c0", + brightCyan: "#50a090", + brightWhite: "#787878", + }, + }, + { + id: "system-cyberdyne-dark", + name: "Cyberdyne Dark", + type: "dark", + colors: { + background: "#151144", + foreground: "#00ff92", + cursor: "#ff90fe", + selection: "#653c83", + black: "#080808", + red: "#ff8373", + green: "#00c172", + yellow: "#d2a700", + blue: "#0071cf", + magenta: "#ff90fe", + cyan: "#6bffdd", + white: "#f1f1f1", + brightBlack: "#474747", + brightRed: "#ffc4be", + brightGreen: "#d6fcba", + brightYellow: "#fffed5", + brightBlue: "#c2e3ff", + brightMagenta: "#ffb2fe", + brightCyan: "#e6e7fe", + brightWhite: "#ffffff", + }, + }, + { + id: "system-desert-light", + name: "Desert Light", + type: "light", + colors: { + background: "#f3f0ec", + foreground: "#59300d", + cursor: "#006830", + selection: "#b9cfbf", + black: "#3c3c3c", + red: "#b80000", + green: "#006830", + yellow: "#6a5800", + blue: "#6a3c18", + magenta: "#886020", + cyan: "#885050", + white: "#585438", + brightBlack: "#585858", + brightRed: "#bb2222", + brightGreen: "#005a00", + brightYellow: "#666600", + brightBlue: "#3870a0", + brightMagenta: "#880088", + brightCyan: "#909000", + brightWhite: "#707070", + }, + }, + { + id: "system-desert-dark", + name: "Desert Dark", + type: "dark", + colors: { + background: "#333333", + foreground: "#ffffff", + cursor: "#ffdead", + selection: "#786d5c", + black: "#4d4d4d", + red: "#ff2b2b", + green: "#98fb98", + yellow: "#f0e68c", + blue: "#cd853f", + magenta: "#ffdead", + cyan: "#ffa0a0", + white: "#f5deb3", + brightBlack: "#626262", + brightRed: "#ff5555", + brightGreen: "#55ff55", + brightYellow: "#ffff55", + brightBlue: "#87ceff", + brightMagenta: "#ff55ff", + brightCyan: "#ffd700", + brightWhite: "#ffffff", + }, + }, + { + id: "system-django-reborn-again-light", + name: "Django Reborn Again Light", + type: "light", + colors: { + background: "#ecf4f0", + foreground: "#143829", + cursor: "#7a6800", + selection: "#d1d2b6", + black: "#181818", + red: "#b84000", + green: "#1a5818", + yellow: "#7a6800", + blue: "#1a3820", + magenta: "#484848", + cyan: "#1a6020", + white: "#383838", + brightBlack: "#3c3c3c", + brightRed: "#c86020", + brightGreen: "#1a7818", + brightYellow: "#9a8800", + brightBlue: "#305848", + brightMagenta: "#686868", + brightCyan: "#1a8028", + brightWhite: "#585858", + }, + }, + { + id: "system-django-reborn-again-dark", + name: "Django Reborn Again Dark", + type: "dark", + colors: { + background: "#051f14", + foreground: "#dadedc", + cursor: "#ffe862", + selection: "#5a632f", + black: "#000000", + red: "#fd6209", + green: "#5dba5a", + yellow: "#ffe862", + blue: "#3d7a60", + magenta: "#f8f8f8", + cyan: "#9df39f", + white: "#ffffff", + brightBlack: "#4c4c4c", + brightRed: "#ff943b", + brightGreen: "#73da70", + brightYellow: "#ffff94", + brightBlue: "#568264", + brightMagenta: "#ffffff", + brightCyan: "#cfffd1", + brightWhite: "#ffffff", + }, + }, + { + id: "system-espresso-light", + name: "Espresso Light", + type: "light", + colors: { + background: "#f0eee7", + foreground: "#1b3c3c", + cursor: "#4a6670", + selection: "#c8cdca", + black: "#213535", + red: "#9e5a5a", + green: "#6b7d5e", + yellow: "#8b7355", + blue: "#4a6670", + magenta: "#7a6b7a", + cyan: "#4a7a75", + white: "#e8e6df", + brightBlack: "#6b6b65", + brightRed: "#b86b6b", + brightGreen: "#7a8e6d", + brightYellow: "#a08560", + brightBlue: "#5a7a85", + brightMagenta: "#8e7d8e", + brightCyan: "#5a8e88", + brightWhite: "#f5f3ec", + }, + }, + { + id: "system-espresso-dark", + name: "Espresso Dark", + type: "dark", + colors: { + background: "#1e1714", + foreground: "#d4c4b0", + cursor: "#e8c878", + selection: "#635336", + black: "#2a211a", + red: "#e88878", + green: "#a4c484", + yellow: "#e8c878", + blue: "#88b4d4", + magenta: "#c4a4dd", + cyan: "#8ac4c4", + white: "#d4c4b0", + brightBlack: "#6a5a48", + brightRed: "#ffaa98", + brightGreen: "#c4e4a4", + brightYellow: "#ffe898", + brightBlue: "#a8d4f4", + brightMagenta: "#e4c4ff", + brightCyan: "#aae4e4", + brightWhite: "#faf4e8", + }, + }, + { + id: "system-eyehealth-light", + name: "EyeHealth Light", + type: "light", + colors: { + background: "#fffae8", + foreground: "#8d634a", + cursor: "#ff9800", + selection: "#ffe2b0", + black: "#434a54", + red: "#da4453", + green: "#37bc9b", + yellow: "#ff9800", + blue: "#4a89dc", + magenta: "#d770ad", + cyan: "#3bafda", + white: "#8cc152", + brightBlack: "#656d78", + brightRed: "#ed5565", + brightGreen: "#48cfad", + brightYellow: "#ffb74d", + brightBlue: "#5d9cec", + brightMagenta: "#ec87c0", + brightCyan: "#4fc1e9", + brightWhite: "#a0d468", + }, + }, + { + id: "system-eyehealth-dark", + name: "EyeHealth Dark", + type: "dark", + colors: { + background: "#424242", + foreground: "#ffffff", + cursor: "#ff9800", + selection: "#825f2c", + black: "#e6e9ed", + red: "#da4453", + green: "#37bc9b", + yellow: "#ff9800", + blue: "#4a89dc", + magenta: "#d770ad", + cyan: "#3bafda", + white: "#8cc152", + brightBlack: "#f5f7fa", + brightRed: "#ed5565", + brightGreen: "#48cfad", + brightYellow: "#ffb74d", + brightBlue: "#5d9cec", + brightMagenta: "#ec87c0", + brightCyan: "#4fc1e9", + brightWhite: "#a0d468", + }, + }, + { + id: "system-flexoki-light", + name: "Flexoki Light", + type: "light", + colors: { + background: "#fffcf0", + foreground: "#100f0f", + cursor: "#ad8301", + selection: "#ebdfb7", + black: "#282726", + red: "#af3029", + green: "#66800b", + yellow: "#ad8301", + blue: "#205ea6", + magenta: "#a02f6f", + cyan: "#24837b", + white: "#878580", + brightBlack: "#575653", + brightRed: "#c03e35", + brightGreen: "#768d21", + brightYellow: "#be9207", + brightBlue: "#3171b2", + brightMagenta: "#b74583", + brightCyan: "#2f968d", + brightWhite: "#b7b5ac", + }, + }, + { + id: "system-flexoki-dark", + name: "Flexoki Dark", + type: "dark", + colors: { + background: "#100f0f", + foreground: "#cecdc3", + cursor: "#d0a215", + selection: "#514111", + black: "#575653", + red: "#d14d41", + green: "#879a39", + yellow: "#d0a215", + blue: "#4385be", + magenta: "#ce5d97", + cyan: "#3aa99f", + white: "#878580", + brightBlack: "#6f6e69", + brightRed: "#e8705f", + brightGreen: "#a0af54", + brightYellow: "#dfb431", + brightBlue: "#66a0c8", + brightMagenta: "#e47da8", + brightCyan: "#5abdac", + brightWhite: "#b7b5ac", + }, + }, + { + id: "system-fox-light", + name: "Fox Light", + type: "light", + colors: { + background: "#f6f2ee", + foreground: "#3d2b5a", + cursor: "#ac5402", + selection: "#e4ccb5", + black: "#352c24", + red: "#a5222f", + green: "#396847", + yellow: "#ac5402", + blue: "#2848a9", + magenta: "#6e33ce", + cyan: "#287980", + white: "#bfb6ae", + brightBlack: "#534c45", + brightRed: "#b3434e", + brightGreen: "#577f63", + brightYellow: "#b86e28", + brightBlue: "#4863b6", + brightMagenta: "#8452d5", + brightCyan: "#488d93", + brightWhite: "#f4ece6", + }, + }, + { + id: "system-fox-dark", + name: "Fox Dark", + type: "dark", + colors: { + background: "#192330", + foreground: "#cdcecf", + cursor: "#63cdcf", + selection: "#325d66", + black: "#393b44", + red: "#c94f6d", + green: "#81b29a", + yellow: "#dbc074", + blue: "#719cd6", + magenta: "#9d79d6", + cyan: "#63cdcf", + white: "#dfdfe0", + brightBlack: "#575860", + brightRed: "#d16983", + brightGreen: "#8ebaa4", + brightYellow: "#e0c989", + brightBlue: "#86abdc", + brightMagenta: "#baa1e2", + brightCyan: "#7ad5d6", + brightWhite: "#e4e4e5", + }, + }, + { + id: "system-garbage-oracle-light", + name: "Garbage Oracle Light", + type: "light", + colors: { + background: "#f2e2f1", + foreground: "#870058", + cursor: "#7b3e19", + selection: "#d5bbbd", + black: "#f2e2f1", + red: "#a4303f", + green: "#376954", + yellow: "#734d90", + blue: "#684f54", + magenta: "#7b3e19", + cyan: "#3f59b7", + white: "#96206e", + brightBlack: "#e3c2db", + brightRed: "#2b5b75", + brightGreen: "#3f59b7", + brightYellow: "#734d90", + brightBlue: "#684f54", + brightMagenta: "#7b3e19", + brightCyan: "#3f59b7", + brightWhite: "#870058", + }, + }, + { + id: "system-garbage-oracle-dark", + name: "Garbage Oracle Dark", + type: "dark", + colors: { + background: "#371d32", + foreground: "#f2e2f1", + cursor: "#aafdb0", + selection: "#5e695d", + black: "#371d32", + red: "#fb9495", + green: "#c1edcc", + yellow: "#a9cdd6", + blue: "#19d3db", + magenta: "#aafdb0", + cyan: "#b0c0bc", + white: "#d7c6d6", + brightBlack: "#52394d", + brightRed: "#bbbcf0", + brightGreen: "#b0c0bc", + brightYellow: "#a9cdd6", + brightBlue: "#19d3db", + brightMagenta: "#aafdb0", + brightCyan: "#b0c0bc", + brightWhite: "#f2e2f1", + }, + }, + { + id: "system-github-light", + name: "GitHub Light", + type: "light", + colors: { + background: "#ffffff", + foreground: "#1f2328", + cursor: "#0969da", + selection: "#c4dbf6", + black: "#6e7781", + red: "#cf222e", + green: "#116329", + yellow: "#9a6700", + blue: "#0969da", + magenta: "#8250df", + cyan: "#1b7c83", + white: "#6e7781", + brightBlack: "#57606a", + brightRed: "#a40e26", + brightGreen: "#1a7f37", + brightYellow: "#633c01", + brightBlue: "#218bff", + brightMagenta: "#a475f9", + brightCyan: "#3192aa", + brightWhite: "#8c959f", + }, + }, + { + id: "system-github-dark", + name: "GitHub Dark", + type: "dark", + colors: { + background: "#0d1117", + foreground: "#e6edf3", + cursor: "#58a6ff", + selection: "#274466", + black: "#484f58", + red: "#ff7b72", + green: "#3fb950", + yellow: "#d29922", + blue: "#58a6ff", + magenta: "#bc8cff", + cyan: "#39c5cf", + white: "#b1bac4", + brightBlack: "#6e7681", + brightRed: "#ffa198", + brightGreen: "#56d364", + brightYellow: "#e3b341", + brightBlue: "#79c0ff", + brightMagenta: "#d2a8ff", + brightCyan: "#56d4dd", + brightWhite: "#f0f6fc", + }, + }, + { + id: "system-gruvbox-material-light", + name: "Gruvbox Material Light", + type: "light", + colors: { + background: "#fbf1c7", + foreground: "#654735", + cursor: "#b47109", + selection: "#ead299", + black: "#4f3829", + red: "#c14a4a", + green: "#6c782e", + yellow: "#b47109", + blue: "#45707a", + magenta: "#945e80", + cyan: "#4c7a5d", + white: "#928374", + brightBlack: "#654735", + brightRed: "#c14a4a", + brightGreen: "#6c782e", + brightYellow: "#b47109", + brightBlue: "#45707a", + brightMagenta: "#945e80", + brightCyan: "#4c7a5d", + brightWhite: "#f2e5bc", + }, + }, + { + id: "system-gruvbox-material-dark", + name: "Gruvbox Material Dark", + type: "dark", + colors: { + background: "#292828", + foreground: "#d4be98", + cursor: "#ea6962", + selection: "#6b3e3c", + black: "#32302f", + red: "#ea6962", + green: "#a9b665", + yellow: "#d8a657", + blue: "#7daea3", + magenta: "#d3869b", + cyan: "#89b482", + white: "#d4be98", + brightBlack: "#928374", + brightRed: "#ea6962", + brightGreen: "#a9b665", + brightYellow: "#d8a657", + brightBlue: "#7daea3", + brightMagenta: "#d3869b", + brightCyan: "#89b482", + brightWhite: "#ddc7a1", + }, + }, + { + id: "system-homebrew-light", + name: "Homebrew Light", + type: "light", + colors: { + background: "#eaf6ea", + foreground: "#0d3f0d", + cursor: "#780078", + selection: "#cfbbcf", + black: "#001800", + red: "#7a0000", + green: "#005800", + yellow: "#585800", + blue: "#080878", + magenta: "#780078", + cyan: "#005868", + white: "#484848", + brightBlack: "#3c3c3c", + brightRed: "#a80000", + brightGreen: "#007000", + brightYellow: "#787800", + brightBlue: "#0000a0", + brightMagenta: "#a000a0", + brightCyan: "#009898", + brightWhite: "#686868", + }, + }, + { + id: "system-homebrew-dark", + name: "Homebrew Dark", + type: "dark", + colors: { + background: "#000000", + foreground: "#00ff00", + cursor: "#00a6b2", + selection: "#00383d", + black: "#000000", + red: "#990000", + green: "#00a600", + yellow: "#999900", + blue: "#4d72ff", + magenta: "#b200b2", + cyan: "#00a6b2", + white: "#bfbfbf", + brightBlack: "#666666", + brightRed: "#e50000", + brightGreen: "#00d900", + brightYellow: "#e5e500", + brightBlue: "#5a7aff", + brightMagenta: "#e500e5", + brightCyan: "#00e5e5", + brightWhite: "#e5e5e5", + }, + }, + { + id: "system-ic-orange-ppl-light", + name: "IC Orange PPL Light", + type: "light", + colors: { + background: "#f6f1ea", + foreground: "#3f2a0d", + cursor: "#783000", + selection: "#d8c3b2", + black: "#1a1000", + red: "#882000", + green: "#585000", + yellow: "#785800", + blue: "#783000", + magenta: "#b83000", + cyan: "#886800", + white: "#503010", + brightBlack: "#483010", + brightRed: "#b04830", + brightGreen: "#b0b000", + brightYellow: "#c08800", + brightBlue: "#a07030", + brightMagenta: "#c05818", + brightCyan: "#986848", + brightWhite: "#888888", + }, + }, + { + id: "system-ic-orange-ppl-dark", + name: "IC Orange PPL Dark", + type: "dark", + colors: { + background: "#262626", + foreground: "#ffcb83", + cursor: "#f79500", + selection: "#6d4c19", + black: "#000000", + red: "#c13900", + green: "#a4a900", + yellow: "#caaf00", + blue: "#bd6d00", + magenta: "#fc5e00", + cyan: "#f79500", + white: "#ffc88a", + brightBlack: "#6a4f2a", + brightRed: "#ff8c68", + brightGreen: "#f6ff40", + brightYellow: "#ffe36e", + brightBlue: "#ffbe55", + brightMagenta: "#fc874f", + brightCyan: "#c69752", + brightWhite: "#fafaff", + }, + }, + { + id: "system-ikki-light", + name: "IKKI Light", + type: "light", + colors: { + background: "#fffcf4", + foreground: "#8d634a", + cursor: "#ff9800", + selection: "#ffe4b9", + black: "#434a54", + red: "#da4453", + green: "#37bc9b", + yellow: "#ff9800", + blue: "#4a89dc", + magenta: "#d770ad", + cyan: "#3bafda", + white: "#8cc152", + brightBlack: "#656d78", + brightRed: "#ed5565", + brightGreen: "#48cfad", + brightYellow: "#ffb74d", + brightBlue: "#5d9cec", + brightMagenta: "#ec87c0", + brightCyan: "#4fc1e9", + brightWhite: "#a0d468", + }, + }, + { + id: "system-ikki-dark", + name: "IKKI Dark", + type: "dark", + colors: { + background: "#535353", + foreground: "#d6d6d6", + cursor: "#ff9800", + selection: "#8d6a37", + black: "#e6e9ed", + red: "#da4453", + green: "#37bc9b", + yellow: "#ff9800", + blue: "#4a89dc", + magenta: "#d770ad", + cyan: "#3bafda", + white: "#8cc152", + brightBlack: "#f5f7fa", + brightRed: "#ed5565", + brightGreen: "#48cfad", + brightYellow: "#ffb74d", + brightBlue: "#5d9cec", + brightMagenta: "#ec87c0", + brightCyan: "#4fc1e9", + brightWhite: "#a0d468", + }, + }, + { + id: "system-kanso-ink-light", + name: "Kanso Ink Light", + type: "light", + colors: { + background: "#f2f1ef", + foreground: "#22262d", + cursor: "#c84053", + selection: "#e8c7ca", + black: "#1f1f28", + red: "#c84053", + green: "#6f894e", + yellow: "#77713f", + blue: "#4d699b", + magenta: "#b35b79", + cyan: "#597b75", + white: "#22262d", + brightBlack: "#6d6d69", + brightRed: "#d7474b", + brightGreen: "#6e915f", + brightYellow: "#836f4a", + brightBlue: "#6693bf", + brightMagenta: "#624c83", + brightCyan: "#5e857a", + brightWhite: "#43436c", + }, + }, + { + id: "system-kanso-ink-dark", + name: "Kanso Ink Dark", + type: "dark", + colors: { + background: "#14171d", + foreground: "#c5c9c7", + cursor: "#c4b28a", + selection: "#504c42", + black: "#22262d", + red: "#c4746e", + green: "#8a9a7b", + yellow: "#c4b28a", + blue: "#8ba4b0", + magenta: "#a292a3", + cyan: "#8ea4a2", + white: "#c5c9c7", + brightBlack: "#9e9b93", + brightRed: "#e46876", + brightGreen: "#87a987", + brightYellow: "#e6c384", + brightBlue: "#7fb4ca", + brightMagenta: "#938aa9", + brightCyan: "#7aa89f", + brightWhite: "#c5c9c7", + }, + }, + { + id: "system-kary-pro-colors-light", + name: "Kary Pro Colors Light", + type: "light", + colors: { + background: "#f0f6fb", + foreground: "#3778b7", + cursor: "#a56416", + selection: "#ded3c4", + black: "#1a1a1a", + red: "#c94824", + green: "#428226", + yellow: "#a56416", + blue: "#3778b7", + magenta: "#b052a1", + cyan: "#3778b7", + white: "#f7f7f7", + brightBlack: "#9b9b9b", + brightRed: "#c94824", + brightGreen: "#428226", + brightYellow: "#a56416", + brightBlue: "#3778b7", + brightMagenta: "#b052a1", + brightCyan: "#3778b7", + brightWhite: "#f7f7f7", + }, + }, + { + id: "system-kary-pro-colors-dark", + name: "Kary Pro Colors Dark", + type: "dark", + colors: { + background: "#1a1a1a", + foreground: "#cccccc", + cursor: "#d38569", + selection: "#593e35", + black: "#1a1a1a", + red: "#d38569", + green: "#7da76f", + yellow: "#bc9550", + blue: "#819dc2", + magenta: "#b98eb2", + cyan: "#819dc2", + white: "#cccccc", + brightBlack: "#474747", + brightRed: "#d38569", + brightGreen: "#7da76f", + brightYellow: "#bc9550", + brightBlue: "#819dc2", + brightMagenta: "#b98eb2", + brightCyan: "#819dc2", + brightWhite: "#f7f7f7", + }, + }, + { + id: "system-light-purple-light", + name: "Light purple Light", + type: "light", + colors: { + background: "#efeae9", + foreground: "#4e3163", + cursor: "#e0af02", + selection: "#ebdcb2", + black: "#4e3163", + red: "#de3d3b", + green: "#08916a", + yellow: "#e0af02", + blue: "#288ed7", + magenta: "#d6438a", + cyan: "#715ab1", + white: "#e4e4e4", + brightBlack: "#4e3163", + brightRed: "#de3d3b", + brightGreen: "#08916a", + brightYellow: "#b1951d", + brightBlue: "#288ed7", + brightMagenta: "#d6438a", + brightCyan: "#715ab1", + brightWhite: "#e4e4e4", + }, + }, + { + id: "system-light-purple-dark", + name: "Light purple Dark", + type: "dark", + colors: { + background: "#39293b", + foreground: "#ffe3e3", + cursor: "#9ae0f0", + selection: "#5a6779", + black: "#9c6f9f", + red: "#e05470", + green: "#a4bc77", + yellow: "#ebb984", + blue: "#8078d1", + magenta: "#eb579c", + cyan: "#9ae0f0", + white: "#ffe3e3", + brightBlack: "#9c6f9f", + brightRed: "#ef4568", + brightGreen: "#a7c966", + brightYellow: "#f9b975", + brightBlue: "#9994ff", + brightMagenta: "#e54386", + brightCyan: "#87ddee", + brightWhite: "#fff0f0", + }, + }, + { + id: "system-mondrian-light", + name: "Mondrian Light", + type: "light", + colors: { + background: "#ffffff", + foreground: "#000000", + cursor: "#4285f4", + selection: "#d2e2fc", + black: "#000000", + red: "#db4437", + green: "#0f9d58", + yellow: "#f4b400", + blue: "#4285f4", + magenta: "#db4437", + cyan: "#4285f4", + white: "#bfbfbf", + brightBlack: "#000000", + brightRed: "#db4437", + brightGreen: "#0f9d58", + brightYellow: "#f4b400", + brightBlue: "#4285f4", + brightMagenta: "#4285f4", + brightCyan: "#0f9d58", + brightWhite: "#ffffff", + }, + }, + { + id: "system-mondrian-dark", + name: "Mondrian Dark", + type: "dark", + colors: { + background: "#1a1a2e", + foreground: "#ffffff", + cursor: "#00acc1", + selection: "#114c60", + black: "#1a1a2e", + red: "#ea4335", + green: "#34a853", + yellow: "#fbbc04", + blue: "#4285f4", + magenta: "#9c27b0", + cyan: "#00acc1", + white: "#bfbfbf", + brightBlack: "#3a3a52", + brightRed: "#ff6b5b", + brightGreen: "#57c276", + brightYellow: "#ffd34e", + brightBlue: "#669df6", + brightMagenta: "#ba68c8", + brightCyan: "#4dd0e1", + brightWhite: "#ffffff", + }, + }, + { + id: "system-monochrome-light", + name: "Monochrome Light", + type: "light", + colors: { + background: "#f1f5f9", + foreground: "#0f172a", + cursor: "#0f172a", + selection: "#bbc0c7", + black: "#f1f5f9", + red: "#0f172a", + green: "#69707d", + yellow: "#0f172a", + blue: "#979ca6", + magenta: "#0f172a", + cyan: "#3c4353", + white: "#0f172a", + brightBlack: "#c4c9d0", + brightRed: "#0f172a", + brightGreen: "#69707d", + brightYellow: "#0f172a", + brightBlue: "#979ca6", + brightMagenta: "#0f172a", + brightCyan: "#3c4353", + brightWhite: "#0f172a", + }, + }, + { + id: "system-monochrome-dark", + name: "Monochrome Dark", + type: "dark", + colors: { + background: "#0f172a", + foreground: "#f1f5f9", + cursor: "#f1f5f9", + selection: "#5c6270", + black: "#0f172a", + red: "#f1f5f9", + green: "#979ca6", + yellow: "#f1f5f9", + blue: "#69707d", + magenta: "#f1f5f9", + cyan: "#c4c9d0", + white: "#f1f5f9", + brightBlack: "#3c4353", + brightRed: "#f1f5f9", + brightGreen: "#979ca6", + brightYellow: "#f1f5f9", + brightBlue: "#69707d", + brightMagenta: "#f1f5f9", + brightCyan: "#c4c9d0", + brightWhite: "#f1f5f9", + }, + }, + { + id: "system-monochrome-stone-light", + name: "Monochrome Stone Light", + type: "light", + colors: { + background: "#f5f5f4", + foreground: "#1c1917", + cursor: "#1c1917", + selection: "#c1c0bf", + black: "#f5f5f4", + red: "#1c1917", + green: "#73716f", + yellow: "#1c1917", + blue: "#9e9d9c", + magenta: "#1c1917", + cyan: "#474543", + white: "#1c1917", + brightBlack: "#cac9c8", + brightRed: "#1c1917", + brightGreen: "#73716f", + brightYellow: "#1c1917", + brightBlue: "#9e9d9c", + brightMagenta: "#1c1917", + brightCyan: "#474543", + brightWhite: "#1c1917", + }, + }, + { + id: "system-monochrome-stone-dark", + name: "Monochrome Stone Dark", + type: "dark", + colors: { + background: "#1c1917", + foreground: "#f5f5f4", + cursor: "#f5f5f4", + selection: "#666462", + black: "#1c1917", + red: "#f5f5f4", + green: "#9e9d9c", + yellow: "#f5f5f4", + blue: "#73716f", + magenta: "#f5f5f4", + cyan: "#cac9c8", + white: "#f5f5f4", + brightBlack: "#474543", + brightRed: "#f5f5f4", + brightGreen: "#9e9d9c", + brightYellow: "#f5f5f4", + brightBlue: "#73716f", + brightMagenta: "#f5f5f4", + brightCyan: "#cac9c8", + brightWhite: "#f5f5f4", + }, + }, + { + id: "system-monokai-pro-spectrum-light", + name: "Monokai Pro Spectrum Light", + type: "light", + colors: { + background: "#f8efe7", + foreground: "#2c232e", + cursor: "#b16803", + selection: "#e7cfb0", + black: "#f8efe7", + red: "#ce4770", + green: "#218871", + yellow: "#b16803", + blue: "#d4572b", + magenta: "#6851a2", + cyan: "#2473b6", + white: "#2c232e", + brightBlack: "#a59c9c", + brightRed: "#ce4770", + brightGreen: "#218871", + brightYellow: "#b16803", + brightBlue: "#d4572b", + brightMagenta: "#6851a2", + brightCyan: "#2473b6", + brightWhite: "#2c232e", + }, + }, + { + id: "system-monokai-pro-spectrum-dark", + name: "Monokai Pro Spectrum Dark", + type: "dark", + colors: { + background: "#222222", + foreground: "#f7f1ff", + cursor: "#fd9353", + selection: "#6c4833", + black: "#222222", + red: "#fc618d", + green: "#7bd88f", + yellow: "#fce566", + blue: "#fd9353", + magenta: "#948ae3", + cyan: "#5ad4e6", + white: "#f7f1ff", + brightBlack: "#69676c", + brightRed: "#fc618d", + brightGreen: "#7bd88f", + brightYellow: "#fce566", + brightBlue: "#fd9353", + brightMagenta: "#948ae3", + brightCyan: "#5ad4e6", + brightWhite: "#f7f1ff", + }, + }, + { + id: "system-monospace-light", + name: "Monospace Light", + type: "light", + colors: { + background: "#ffffff", + foreground: "#1f2939", + cursor: "#0075a2", + selection: "#c2dee9", + black: "#333e4f", + red: "#d03941", + green: "#007b49", + yellow: "#a65921", + blue: "#3c60dd", + magenta: "#6f4cde", + cyan: "#0075a2", + white: "#5d6a7d", + brightBlack: "#000000", + brightRed: "#a52430", + brightGreen: "#00522f", + brightYellow: "#904b1a", + brightBlue: "#002487", + brightMagenta: "#4d21bb", + brightCyan: "#00607e", + brightWhite: "#475365", + }, + }, + { + id: "system-monospace-dark", + name: "Monospace Dark", + type: "dark", + colors: { + background: "#171f2b", + foreground: "#d9dfe7", + cursor: "#708fff", + selection: "#354573", + black: "#738295", + red: "#f76769", + green: "#17b877", + yellow: "#ffa23e", + blue: "#708fff", + magenta: "#a87ffb", + cyan: "#25a6e9", + white: "#a4afbd", + brightBlack: "#8b98a9", + brightRed: "#fc8f8e", + brightGreen: "#66ce98", + brightYellow: "#ffc26e", + brightBlue: "#a2b6ff", + brightMagenta: "#c8aaff", + brightCyan: "#71c2ee", + brightWhite: "#fafbfe", + }, + }, + { + id: "system-noctis-azureus-light", + name: "Noctis Azureus Light", + type: "light", + colors: { + background: "#fef8ec", + foreground: "#005661", + cursor: "#0094f0", + selection: "#c1e0ed", + black: "#003b42", + red: "#e34e1c", + green: "#00b368", + yellow: "#f49725", + blue: "#0094f0", + magenta: "#ff5792", + cyan: "#00bdd6", + white: "#8ca6a6", + brightBlack: "#004d57", + brightRed: "#ff4000", + brightGreen: "#00d17a", + brightYellow: "#ff8c00", + brightBlue: "#0fa3ff", + brightMagenta: "#ff6b9f", + brightCyan: "#00cbe6", + brightWhite: "#bbc3c4", + }, + }, + { + id: "system-noctis-azureus-dark", + name: "Noctis Azureus Dark", + type: "dark", + colors: { + background: "#07273b", + foreground: "#becfda", + cursor: "#49d6e9", + selection: "#1d6376", + black: "#28353e", + red: "#e66533", + green: "#49e9a6", + yellow: "#e4b781", + blue: "#49ace9", + magenta: "#df769b", + cyan: "#49d6e9", + white: "#aec3d0", + brightBlack: "#475e6c", + brightRed: "#e97749", + brightGreen: "#60ebb1", + brightYellow: "#e69533", + brightBlue: "#60b6eb", + brightMagenta: "#e798b3", + brightCyan: "#60dbeb", + brightWhite: "#becfda", + }, + }, + { + id: "system-noctis-hibernus-light", + name: "Noctis Hibernus Light", + type: "light", + colors: { + background: "#f4f6f6", + foreground: "#005661", + cursor: "#0094f0", + selection: "#b9def5", + black: "#003b42", + red: "#e34e1c", + green: "#00b368", + yellow: "#f49725", + blue: "#0094f0", + magenta: "#ff5792", + cyan: "#00bdd6", + white: "#8ca6a6", + brightBlack: "#004d57", + brightRed: "#ff4000", + brightGreen: "#00d17a", + brightYellow: "#ff8c00", + brightBlue: "#0fa3ff", + brightMagenta: "#ff6b9f", + brightCyan: "#00cbe6", + brightWhite: "#bbc3c4", + }, + }, + { + id: "system-noctis-hibernus-dark", + name: "Noctis Hibernus Dark", + type: "dark", + colors: { + background: "#292640", + foreground: "#c5c2d6", + cursor: "#49d6e9", + selection: "#346279", + black: "#302f3d", + red: "#e66533", + green: "#49e9a6", + yellow: "#e4b781", + blue: "#49ace9", + magenta: "#df769b", + cyan: "#49d6e9", + white: "#b6b3cc", + brightBlack: "#504e65", + brightRed: "#e97749", + brightGreen: "#60ebb1", + brightYellow: "#e69533", + brightBlue: "#60b6eb", + brightMagenta: "#e798b3", + brightCyan: "#60dbeb", + brightWhite: "#c5c2d6", + }, + }, + { + id: "system-noir-essence-light", + name: "Noir Essence Light", + type: "light", + colors: { + background: "#f7f3ea", + foreground: "#000000", + cursor: "#7a6e00", + selection: "#d9d3b2", + black: "#111314", + red: "#d15f59", + green: "#a9b665", + yellow: "#7a6e00", + blue: "#699289", + magenta: "#c47d90", + cyan: "#81a97a", + white: "#c7c3ba", + brightBlack: "#666666", + brightRed: "#ea6962", + brightGreen: "#a9b665", + brightYellow: "#eadb62", + brightBlue: "#7daea3", + brightMagenta: "#d3869b", + brightCyan: "#89b482", + brightWhite: "#b4b1aa", + }, + }, + { + id: "system-noir-essence-dark", + name: "Noir Essence Dark", + type: "dark", + colors: { + background: "#111314", + foreground: "#f7f3ea", + cursor: "#e78a4e", + selection: "#5a3b28", + black: "#2b2d2d", + red: "#ea6962", + green: "#89b482", + yellow: "#e78a4e", + blue: "#7daea3", + magenta: "#d3869b", + cyan: "#a9b665", + white: "#f7f3ea", + brightBlack: "#434545", + brightRed: "#ea6962", + brightGreen: "#89b482", + brightYellow: "#e78a4e", + brightBlue: "#7daea3", + brightMagenta: "#d3869b", + brightCyan: "#a9b665", + brightWhite: "#f7f3ea", + }, + }, + { + id: "system-nord-midnight-light", + name: "Nord Midnight Light", + type: "light", + colors: { + background: "#eceff4", + foreground: "#2e3440", + cursor: "#0d7d8c", + selection: "#b6d4db", + black: "#3b4252", + red: "#bf616a", + green: "#6b8b4f", + yellow: "#b8941e", + blue: "#3b5e85", + magenta: "#8b5e84", + cyan: "#0d7d8c", + white: "#e5e9f0", + brightBlack: "#4c566a", + brightRed: "#bf616a", + brightGreen: "#a3be8c", + brightYellow: "#ebcb8b", + brightBlue: "#5e81ac", + brightMagenta: "#b48ead", + brightCyan: "#88c0d0", + brightWhite: "#eceff4", + }, + }, + { + id: "system-nord-midnight-dark", + name: "Nord Midnight Dark", + type: "dark", + colors: { + background: "#1a1d23", + foreground: "#d8dee9", + cursor: "#ebcb8b", + selection: "#615846", + black: "#3b4252", + red: "#bf616a", + green: "#a3be8c", + yellow: "#ebcb8b", + blue: "#81a1c1", + magenta: "#b48ead", + cyan: "#88c0d0", + white: "#e5e9f0", + brightBlack: "#4c566a", + brightRed: "#bf616a", + brightGreen: "#a3be8c", + brightYellow: "#ebcb8b", + brightBlue: "#81a1c1", + brightMagenta: "#b48ead", + brightCyan: "#8fbcbb", + brightWhite: "#eceff4", + }, + }, + { + id: "system-notionish-light", + name: "Notionish Light", + type: "light", + colors: { + background: "#ffffff", + foreground: "#191918", + cursor: "#0075de", + selection: "#c2def7", + black: "#191918", + red: "#e32d14", + green: "#14832b", + yellow: "#e89d01", + blue: "#0075de", + magenta: "#7237ae", + cyan: "#0a7b77", + white: "#615d59", + brightBlack: "#494744", + brightRed: "#f64932", + brightGreen: "#1aae39", + brightYellow: "#ffb110", + brightBlue: "#097fe8", + brightMagenta: "#9849e8", + brightCyan: "#27918d", + brightWhite: "#a39e98", + }, + }, + { + id: "system-notionish-dark", + name: "Notionish Dark", + type: "dark", + colors: { + background: "#191918", + foreground: "#f6f5f4", + cursor: "#ffc95e", + selection: "#675530", + black: "#494744", + red: "#f77463", + green: "#68ce7e", + yellow: "#ffc95e", + blue: "#62aef0", + magenta: "#ad6ded", + cyan: "#2a9d99", + white: "#a39e98", + brightBlack: "#615d59", + brightRed: "#ff8b7c", + brightGreen: "#abe5b8", + brightYellow: "#ffd786", + brightBlue: "#93cdfe", + brightMagenta: "#d6b6f6", + brightCyan: "#83cbc9", + brightWhite: "#dfdcd9", + }, + }, + { + id: "system-phonebook-light", + name: "Phonebook Light", + type: "light", + colors: { + background: "#e4d7c4", + foreground: "#4a341c", + cursor: "#00acc1", + selection: "#adcdc3", + black: "#231e1a", + red: "#f54e42", + green: "#2f9369", + yellow: "#d69a00", + blue: "#1e88e5", + magenta: "#6547b8", + cyan: "#00acc1", + white: "#eee7dd", + brightBlack: "#666666", + brightRed: "#db6057", + brightGreen: "#42b885", + brightYellow: "#d69a00", + brightBlue: "#64b5f6", + brightMagenta: "#a993e6", + brightCyan: "#00bcd4", + brightWhite: "#f7f3ee", + }, + }, + { + id: "system-phonebook-dark", + name: "Phonebook Dark", + type: "dark", + colors: { + background: "#2c2621", + foreground: "#e7c56f", + cursor: "#00acc1", + selection: "#1d5457", + black: "#231e1a", + red: "#f54e42", + green: "#27a06c", + yellow: "#ebc300", + blue: "#1e88e5", + magenta: "#6547b8", + cyan: "#00acc1", + white: "#dedede", + brightBlack: "#666666", + brightRed: "#db6057", + brightGreen: "#38d687", + brightYellow: "#f8d668", + brightBlue: "#64b5f6", + brightMagenta: "#a993e6", + brightCyan: "#00bcd4", + brightWhite: "#ffffff", + }, + }, + { + id: "system-polychrome-light", + name: "Polychrome Light", + type: "light", + colors: { + background: "#fbfaf9", + foreground: "#502db4", + cursor: "#6b3df1", + selection: "#d8cdf7", + black: "#d1c2f9", + red: "#f42a2a", + green: "#6b3df1", + yellow: "#a97e50", + blue: "#502db4", + magenta: "#a97e50", + cyan: "#9e7ff5", + white: "#f5f5f5", + brightBlack: "#bda58c", + brightRed: "#a97e50", + brightGreen: "#6b3df1", + brightYellow: "#bda58c", + brightBlue: "#351e78", + brightMagenta: "#bda58c", + brightCyan: "#351e78", + brightWhite: "#000000", + }, + }, + { + id: "system-polychrome-dark", + name: "Polychrome Dark", + type: "dark", + colors: { + background: "#2a2833", + foreground: "#bbb4d8", + cursor: "#ffe685", + selection: "#72694f", + black: "#484459", + red: "#ff6347", + green: "#a59ccc", + yellow: "#ffe685", + blue: "#bbb4d8", + magenta: "#ffe685", + cyan: "#767092", + white: "#f5f5f5", + brightBlack: "#b7a870", + brightRed: "#ffe685", + brightGreen: "#a59ccc", + brightYellow: "#b7a870", + brightBlue: "#d2cde5", + brightMagenta: "#b7a870", + brightCyan: "#d2cde5", + brightWhite: "#ffffff", + }, + }, + { + id: "system-purplepeter-light", + name: "Purplepeter Light", + type: "light", + colors: { + background: "#f0ecf7", + foreground: "#1e113b", + cursor: "#0d7d94", + selection: "#bad1df", + black: "#080010", + red: "#b04848", + green: "#487040", + yellow: "#806848", + blue: "#0d7d94", + magenta: "#883878", + cyan: "#583898", + white: "#704838", + brightBlack: "#383050", + brightRed: "#c06058", + brightGreen: "#687858", + brightYellow: "#b09068", + brightBlue: "#3880a0", + brightMagenta: "#785890", + brightCyan: "#6868a0", + brightWhite: "#786878", + }, + }, + { + id: "system-purplepeter-dark", + name: "Purplepeter Dark", + type: "dark", + colors: { + background: "#2a1a4a", + foreground: "#ece7fa", + cursor: "#ba8cff", + selection: "#5b4188", + black: "#0a0520", + red: "#ff796d", + green: "#99b481", + yellow: "#efdfac", + blue: "#66d9ef", + magenta: "#e78fcd", + cyan: "#ba8cff", + white: "#ffba81", + brightBlack: "#504b63", + brightRed: "#f99f92", + brightGreen: "#b4be8f", + brightYellow: "#f2e9bf", + brightBlue: "#79daed", + brightMagenta: "#ba91d4", + brightCyan: "#a0a0d6", + brightWhite: "#b9aed3", + }, + }, + { + id: "system-rainglow-codecourse-light", + name: "Rainglow Codecourse Light", + type: "light", + colors: { + background: "#ffffff", + foreground: "#547f91", + cursor: "#1ea8fc", + selection: "#c9eafe", + black: "#ffffff", + red: "#ba0e2e", + green: "#1ea8fc", + yellow: "#5dcdfd", + blue: "#547f91", + magenta: "#1ea8fc", + cyan: "#5dcdfd", + white: "#5d8da1", + brightBlack: "#ffffff", + brightRed: "#f03e5f", + brightGreen: "#83cffd", + brightYellow: "#c2ecfe", + brightBlue: "#8eafbd", + brightMagenta: "#83cffd", + brightCyan: "#c2ecfe", + brightWhite: "#8eafbd", + }, + }, + { + id: "system-rainglow-codecourse-dark", + name: "Rainglow Codecourse Dark", + type: "dark", + colors: { + background: "#05080a", + foreground: "#b6ced8", + cursor: "#1ea8fc", + selection: "#0e3e5c", + black: "#0d161b", + red: "#ba0e2e", + green: "#1ea8fc", + yellow: "#5dcdfd", + blue: "#ffffff", + magenta: "#1ea8fc", + cyan: "#5dcdfd", + white: "#c7d9e1", + brightBlack: "#273e4e", + brightRed: "#f03e5f", + brightGreen: "#83cffd", + brightYellow: "#c2ecfe", + brightBlue: "#ffffff", + brightMagenta: "#83cffd", + brightCyan: "#c2ecfe", + brightWhite: "#f8fbfc", + }, + }, + { + id: "system-rainglow-crisp-light", + name: "Rainglow Crisp Light", + type: "light", + colors: { + background: "#ffffff", + foreground: "#221a22", + cursor: "#fc6a0f", + selection: "#fedbc5", + black: "#ffffff", + red: "#ba0e2e", + green: "#99769b", + yellow: "#765478", + blue: "#fc6a0f", + magenta: "#fc6a0f", + cyan: "#99769b", + white: "#302530", + brightBlack: "#ffffff", + brightRed: "#f03e5f", + brightGreen: "#c5b1c6", + brightYellow: "#a987ab", + brightBlue: "#fda974", + brightMagenta: "#fda974", + brightCyan: "#c5b1c6", + brightWhite: "#5c465c", + }, + }, + { + id: "system-rainglow-crisp-dark", + name: "Rainglow Crisp Dark", + type: "dark", + colors: { + background: "#0c090c", + foreground: "#ffffff", + cursor: "#fc6a0f", + selection: "#5e2a0d", + black: "#1b141b", + red: "#ba0e2e", + green: "#cba0cd", + yellow: "#765478", + blue: "#fc6a0f", + magenta: "#fc6a0f", + cyan: "#cba0cd", + white: "#ffffff", + brightBlack: "#463546", + brightRed: "#f03e5f", + brightGreen: "#f0e3f0", + brightYellow: "#a987ab", + brightBlue: "#fda974", + brightMagenta: "#fda974", + brightCyan: "#f0e3f0", + brightWhite: "#ffffff", + }, + }, + { + id: "system-rainglow-lavender-light", + name: "Rainglow Lavender Light", + type: "light", + colors: { + background: "#ffffff", + foreground: "#29222e", + cursor: "#b657ff", + selection: "#edd7ff", + black: "#ffffff", + red: "#ba0e2e", + green: "#a29dfa", + yellow: "#b657ff", + blue: "#f5b0ef", + magenta: "#8e6da6", + cyan: "#8e69c9", + white: "#362d3d", + brightBlack: "#ffffff", + brightRed: "#f03e5f", + brightGreen: "#fefeff", + brightYellow: "#e2bdff", + brightBlue: "#ffffff", + brightMagenta: "#bfaccd", + brightCyan: "#c7b4e4", + brightWhite: "#5d4d69", + }, + }, + { + id: "system-rainglow-lavender-dark", + name: "Rainglow Lavender Dark", + type: "dark", + colors: { + background: "#080709", + foreground: "#e0ceed", + cursor: "#b657ff", + selection: "#43225d", + black: "#151217", + red: "#ba0e2e", + green: "#a29dfa", + yellow: "#b657ff", + blue: "#f5b0ef", + magenta: "#8e6da6", + cyan: "#8e69c9", + white: "#ece1f4", + brightBlack: "#3b3442", + brightRed: "#f03e5f", + brightGreen: "#fefeff", + brightYellow: "#e2bdff", + brightBlue: "#ffffff", + brightMagenta: "#bfaccd", + brightCyan: "#c7b4e4", + brightWhite: "#ffffff", + }, + }, + { + id: "system-remedy-tilted-light", + name: "Remedy Tilted Light", + type: "light", + colors: { + background: "#fef8eb", + foreground: "#563d0e", + cursor: "#de935f", + selection: "#f6e0c9", + black: "#282a2e", + red: "#a54242", + green: "#8c9440", + yellow: "#de935f", + blue: "#5f819d", + magenta: "#85678f", + cyan: "#5e8d87", + white: "#707880", + brightBlack: "#9ca19e", + brightRed: "#cc6666", + brightGreen: "#b5bd68", + brightYellow: "#d79a22", + brightBlue: "#81a2be", + brightMagenta: "#b294bb", + brightCyan: "#8abeb7", + brightWhite: "#535961", + }, + }, + { + id: "system-remedy-tilted-dark", + name: "Remedy Tilted Dark", + type: "dark", + colors: { + background: "#3f3433", + foreground: "#f7e0b4", + cursor: "#de935f", + selection: "#755442", + black: "#282a2e", + red: "#a54242", + green: "#8c9440", + yellow: "#de935f", + blue: "#5f819d", + magenta: "#85678f", + cyan: "#5e8d87", + white: "#707880", + brightBlack: "#535961", + brightRed: "#cc6666", + brightGreen: "#b5bd68", + brightYellow: "#f0c674", + brightBlue: "#81a2be", + brightMagenta: "#b294bb", + brightCyan: "#8abeb7", + brightWhite: "#eeefee", + }, + }, + { + id: "system-rose-pine-light", + name: "Rosé Pine Light", + type: "light", + colors: { + background: "#faf4ed", + foreground: "#575279", + cursor: "#ea9d34", + selection: "#f6dfc1", + black: "#f2e9e1", + red: "#b4637a", + green: "#286983", + yellow: "#ea9d34", + blue: "#56949f", + magenta: "#907aa9", + cyan: "#d7827e", + white: "#575279", + brightBlack: "#797593", + brightRed: "#b4637a", + brightGreen: "#286983", + brightYellow: "#ea9d34", + brightBlue: "#56949f", + brightMagenta: "#907aa9", + brightCyan: "#d7827e", + brightWhite: "#575279", + }, + }, + { + id: "system-rose-pine-dark", + name: "Rosé Pine Dark", + type: "dark", + colors: { + background: "#191724", + foreground: "#e0def4", + cursor: "#f6c177", + selection: "#645140", + black: "#26233a", + red: "#eb6f92", + green: "#31748f", + yellow: "#f6c177", + blue: "#9ccfd8", + magenta: "#c4a7e7", + cyan: "#ebbcba", + white: "#e0def4", + brightBlack: "#908caa", + brightRed: "#eb6f92", + brightGreen: "#31748f", + brightYellow: "#f6c177", + brightBlue: "#9ccfd8", + brightMagenta: "#c4a7e7", + brightCyan: "#ebbcba", + brightWhite: "#e0def4", + }, + }, + { + id: "system-selene-selenized-light", + name: "Selene Selenized Light", + type: "light", + colors: { + background: "#fef3da", + foreground: "#384c52", + cursor: "#0073d2", + selection: "#c1d4d8", + black: "#f0e4cc", + red: "#d4212b", + green: "#539100", + yellow: "#b38800", + blue: "#0073d2", + magenta: "#cb4c99", + cyan: "#009c8f", + white: "#52666d", + brightBlack: "#fef3da", + brightRed: "#c75d20", + brightGreen: "#539100", + brightYellow: "#b38800", + brightBlue: "#0073d2", + brightMagenta: "#7d64c5", + brightCyan: "#0073d2", + brightWhite: "#384c52", + }, + }, + { + id: "system-selene-selenized-dark", + name: "Selene Selenized Dark", + type: "dark", + colors: { + background: "#053d48", + foreground: "#c8d7d8", + cursor: "#0096f5", + selection: "#035b83", + black: "#0e4956", + red: "#fd564e", + green: "#80b83c", + yellow: "#e3b230", + blue: "#0096f5", + magenta: "#f176bd", + cyan: "#39c7b9", + white: "#adbcbc", + brightBlack: "#053d48", + brightRed: "#f38649", + brightGreen: "#80b83c", + brightYellow: "#e3b230", + brightBlue: "#0096f5", + brightMagenta: "#a58cec", + brightCyan: "#0096f5", + brightWhite: "#c8d7d8", + }, + }, + { + id: "system-soft-color-light", + name: "Soft Color Light", + type: "light", + colors: { + background: "#f8fff3", + foreground: "#5a5a5a", + cursor: "#0451a5", + selection: "#bdd5e0", + black: "#000000", + red: "#cd3131", + green: "#00bc00", + yellow: "#949800", + blue: "#0451a5", + magenta: "#bc05bc", + cyan: "#0598bc", + white: "#555555", + brightBlack: "#666666", + brightRed: "#cd3131", + brightGreen: "#14ce14", + brightYellow: "#b5ba00", + brightBlue: "#0451a5", + brightMagenta: "#bc05bc", + brightCyan: "#0598bc", + brightWhite: "#a5a5a5", + }, + }, + { + id: "system-soft-color-dark", + name: "Soft Color Dark", + type: "dark", + colors: { + background: "#252525", + foreground: "#e6fff3", + cursor: "#e5e510", + selection: "#66661e", + black: "#000000", + red: "#cd3131", + green: "#0dbc79", + yellow: "#e5e510", + blue: "#2472c8", + magenta: "#bc3fbc", + cyan: "#11a8cd", + white: "#e5e5e5", + brightBlack: "#666666", + brightRed: "#f14c4c", + brightGreen: "#23d18b", + brightYellow: "#f5f543", + brightBlue: "#3b8eea", + brightMagenta: "#d670d6", + brightCyan: "#29b8db", + brightWhite: "#e5e5e5", + }, + }, + { + id: "system-tearout-light", + name: "Tearout Light", + type: "light", + colors: { + background: "#e5ede0", + foreground: "#262923", + cursor: "#785038", + selection: "#cbc7b8", + black: "#3c2818", + red: "#905048", + green: "#505038", + yellow: "#305028", + blue: "#705038", + magenta: "#785038", + cyan: "#706048", + white: "#503820", + brightBlack: "#503428", + brightRed: "#905048", + brightGreen: "#505038", + brightYellow: "#305028", + brightBlue: "#705038", + brightMagenta: "#785038", + brightCyan: "#706048", + brightWhite: "#503820", + }, + }, + { + id: "system-tearout-dark", + name: "Tearout Dark", + type: "dark", + colors: { + background: "#34392d", + foreground: "#f4d2ae", + cursor: "#d7c483", + selection: "#6b684a", + black: "#685742", + red: "#cc967b", + green: "#97976d", + yellow: "#6c9861", + blue: "#b5955e", + magenta: "#c9a554", + cyan: "#d7c483", + white: "#b5955e", + brightBlack: "#74634e", + brightRed: "#cc967b", + brightGreen: "#97976d", + brightYellow: "#6c9861", + brightBlue: "#b5955e", + brightMagenta: "#c9a554", + brightCyan: "#d7c483", + brightWhite: "#b5955e", + }, + }, + { + id: "system-tokyo-night-light", + name: "Tokyo Night Light", + type: "light", + colors: { + background: "#e1e2e7", + foreground: "#3760bf", + cursor: "#007197", + selection: "#abc7d4", + black: "#e9e9ed", + red: "#f52a65", + green: "#587539", + yellow: "#8c6c3e", + blue: "#2e7de9", + magenta: "#9854f1", + cyan: "#007197", + white: "#6172b0", + brightBlack: "#a1a6c5", + brightRed: "#f52a65", + brightGreen: "#587539", + brightYellow: "#8c6c3e", + brightBlue: "#2e7de9", + brightMagenta: "#9854f1", + brightCyan: "#007197", + brightWhite: "#3760bf", + }, + }, + { + id: "system-tokyo-night-dark", + name: "Tokyo Night Dark", + type: "dark", + colors: { + background: "#1a1b26", + foreground: "#c0caf5", + cursor: "#7dcfff", + selection: "#3c5870", + black: "#15161e", + red: "#f7768e", + green: "#9ece6a", + yellow: "#e0af68", + blue: "#7aa2f7", + magenta: "#bb9af7", + cyan: "#7dcfff", + white: "#a9b1d6", + brightBlack: "#414868", + brightRed: "#f7768e", + brightGreen: "#9ece6a", + brightYellow: "#e0af68", + brightBlue: "#7aa2f7", + brightMagenta: "#bb9af7", + brightCyan: "#7dcfff", + brightWhite: "#c0caf5", + }, + }, + { + id: "system-tomorrow-night-eighties-light", + name: "Tomorrow Night Eighties Light", + type: "light", + colors: { + background: "#ffffff", + foreground: "#4d4d4c", + cursor: "#718c00", + selection: "#dde3c2", + black: "#1d1f21", + red: "#c82829", + green: "#718c00", + yellow: "#eab700", + blue: "#4271ae", + magenta: "#8959a8", + cyan: "#3e999f", + white: "#c5c8c6", + brightBlack: "#969896", + brightRed: "#cc6666", + brightGreen: "#b5bd68", + brightYellow: "#f0c674", + brightBlue: "#81a2be", + brightMagenta: "#b294bb", + brightCyan: "#8abeb7", + brightWhite: "#ffffff", + }, + }, + { + id: "system-tomorrow-night-eighties-dark", + name: "Tomorrow Night Eighties Dark", + type: "dark", + colors: { + background: "#2d2d2d", + foreground: "#cccccc", + cursor: "#ffcc66", + selection: "#746340", + black: "#000000", + red: "#f2777a", + green: "#99cc99", + yellow: "#ffcc66", + blue: "#6699cc", + magenta: "#cc99cc", + cyan: "#66cccc", + white: "#d3d3d3", + brightBlack: "#999999", + brightRed: "#f2777a", + brightGreen: "#99cc99", + brightYellow: "#ffcc66", + brightBlue: "#6699cc", + brightMagenta: "#cc99cc", + brightCyan: "#66cccc", + brightWhite: "#ffffff", + }, + }, + { + id: "system-vaporizer-turquoise-light", + name: "Vaporizer Turquoise Light", + type: "light", + colors: { + background: "#f3f3f3", + foreground: "#1a4818", + cursor: "#bc05bc", + selection: "#e6bae6", + black: "#000000", + red: "#cd3131", + green: "#00bc64", + yellow: "#949800", + blue: "#5f9fe6", + magenta: "#bc05bc", + cyan: "#0598bc", + white: "#555555", + brightBlack: "#666666", + brightRed: "#cd3131", + brightGreen: "#00bc64", + brightYellow: "#b5ba00", + brightBlue: "#3f75b0", + brightMagenta: "#bc05bc", + brightCyan: "#0598bc", + brightWhite: "#a5a5a5", + }, + }, + { + id: "system-vaporizer-turquoise-dark", + name: "Vaporizer Turquoise Dark", + type: "dark", + colors: { + background: "#191919", + foreground: "#9bc793", + cursor: "#00bc64", + selection: "#115033", + black: "#000000", + red: "#cd3131", + green: "#00bc64", + yellow: "#949800", + blue: "#5f9fe6", + magenta: "#bc05bc", + cyan: "#0598bc", + white: "#555555", + brightBlack: "#666666", + brightRed: "#cd3131", + brightGreen: "#00bc64", + brightYellow: "#b5ba00", + brightBlue: "#3f75b0", + brightMagenta: "#bc05bc", + brightCyan: "#0598bc", + brightWhite: "#a5a5a5", + }, + }, + { + id: "system-xotopio-light", + name: "Xotopio Light", + type: "light", + colors: { + background: "#f7f5f4", + foreground: "#212121", + cursor: "#d6438a", + selection: "#efcadb", + black: "#403f53", + red: "#de3d3b", + green: "#3f987f", + yellow: "#c9bd62", + blue: "#5885a5", + magenta: "#d6438a", + cyan: "#2aa298", + white: "#f0f0f0", + brightBlack: "#403f53", + brightRed: "#de3d3b", + brightGreen: "#08916a", + brightYellow: "#daaa01", + brightBlue: "#288ed7", + brightMagenta: "#ba5887", + brightCyan: "#2aa298", + brightWhite: "#f0f0f0", + }, + }, + { + id: "system-xotopio-dark", + name: "Xotopio Dark", + type: "dark", + colors: { + background: "#040616", + foreground: "#ffffff", + cursor: "#54d4ff", + selection: "#1f4c65", + black: "#3a3a3a", + red: "#f90086", + green: "#44b6fc", + yellow: "#fff900", + blue: "#54d4ff", + magenta: "#f90086", + cyan: "#54d4ff", + white: "#ffffff", + brightBlack: "#3a3a3a", + brightRed: "#f90086", + brightGreen: "#44b6fc", + brightYellow: "#fff900", + brightBlue: "#54d4ff", + brightMagenta: "#f90086", + brightCyan: "#54d4ff", + brightWhite: "#ffffff", + }, + }, + { + id: "system-yuttari-light", + name: "Yuttari Light", + type: "light", + colors: { + background: "#ffedf4", + foreground: "#4a3c42", + cursor: "#7a8bb8", + selection: "#dfd5e6", + black: "#3a2e34", + red: "#b85e5e", + green: "#7a9b7a", + yellow: "#c2a875", + blue: "#7a8bb8", + magenta: "#a67ba6", + cyan: "#7bb8b8", + white: "#b0a4aa", + brightBlack: "#6b5c62", + brightRed: "#d47979", + brightGreen: "#8fb58f", + brightYellow: "#c4a570", + brightBlue: "#8fa5d4", + brightMagenta: "#c299c2", + brightCyan: "#70b0b0", + brightWhite: "#e0d0d8", + }, + }, + { + id: "system-yuttari-dark", + name: "Yuttari Dark", + type: "dark", + colors: { + background: "#1e181c", + foreground: "#ffedf4", + cursor: "#ccb07e", + selection: "#594c3d", + black: "#2e262a", + red: "#c06868", + green: "#82a682", + yellow: "#ccb07e", + blue: "#8494c0", + magenta: "#b085b0", + cyan: "#82c0c0", + white: "#d4c8ce", + brightBlack: "#4a3e44", + brightRed: "#e08a8a", + brightGreen: "#9cc49c", + brightYellow: "#e6cda6", + brightBlue: "#a0b4de", + brightMagenta: "#cda6cd", + brightCyan: "#a6dede", + brightWhite: "#ffedf4", + }, + }, + { + id: "system-zenbones-rosebones-light", + name: "Zenbones Rosebones Light", + type: "light", + colors: { + background: "#fbf6f0", + foreground: "#724341", + cursor: "#ec9d33", + selection: "#f7e1c3", + black: "#fbf6f0", + red: "#b5637a", + green: "#286a84", + yellow: "#ec9d33", + blue: "#5795a0", + magenta: "#917ba9", + cyan: "#5795a0", + white: "#724341", + brightBlack: "#e8c48b", + brightRed: "#a54a66", + brightGreen: "#1c5970", + brightYellow: "#c68223", + brightBlue: "#407d88", + brightMagenta: "#855aac", + brightCyan: "#407d88", + brightWhite: "#a4635f", + }, + }, + { + id: "system-zenbones-rosebones-dark", + name: "Zenbones Rosebones Dark", + type: "dark", + colors: { + background: "#1a1825", + foreground: "#e1d4d4", + cursor: "#f6c074", + selection: "#655140", + black: "#1a1825", + red: "#eb7193", + green: "#317490", + yellow: "#f6c074", + blue: "#9ccfd8", + magenta: "#c4a7e7", + cyan: "#9ccfd8", + white: "#e1d4d4", + brightBlack: "#3a3651", + brightRed: "#f289a4", + brightGreen: "#358daf", + brightYellow: "#f9ca8e", + brightBlue: "#94dae6", + brightMagenta: "#ceb3ef", + brightCyan: "#94dae6", + brightWhite: "#bf9b99", + }, + }, + { + id: "system-zhxo-red-light", + name: "Zhxo'red Light", + type: "light", + colors: { + background: "#fff6f0", + foreground: "#777790", + cursor: "#a313d7", + selection: "#e9c0ea", + black: "#131313", + red: "#c43d3d", + green: "#00bc6d", + yellow: "#cf9e0d", + blue: "#1f5fa5", + magenta: "#a313d7", + cyan: "#1fa1c0", + white: "#585858", + brightBlack: "#303030", + brightRed: "#ea5959", + brightGreen: "#29d18a", + brightYellow: "#e6ba38", + brightBlue: "#4181c7", + brightMagenta: "#c421ff", + brightCyan: "#34d0f5", + brightWhite: "#949494", + }, + }, + { + id: "system-zhxo-red-dark", + name: "Zhxo'red Dark", + type: "dark", + colors: { + background: "#1a1a1d", + foreground: "#ababab", + cursor: "#10ccd5", + selection: "#17575c", + black: "#3b3b3b", + red: "#e03c3c", + green: "#22cd8b", + yellow: "#eec051", + blue: "#668be2", + magenta: "#a34bb0", + cyan: "#10ccd5", + white: "#cbcbcb", + brightBlack: "#66676f", + brightRed: "#f08359", + brightGreen: "#3fe6a3", + brightYellow: "#fbfb7b", + brightBlue: "#81a6fd", + brightMagenta: "#c970d6", + brightCyan: "#4deaea", + brightWhite: "#ffffff", + }, + } +]; diff --git a/infrastructure/config/uiThemes.test.ts b/infrastructure/config/uiThemes.test.ts index 5fbe6cd36..8a01dedfb 100644 --- a/infrastructure/config/uiThemes.test.ts +++ b/infrastructure/config/uiThemes.test.ts @@ -2,39 +2,110 @@ import { describe, it } from "node:test"; import assert from "node:assert/strict"; import { - COPILOT_LIGHT_UI_THEMES, + DARK_UI_THEMES, + EXTENDED_DARK_UI_THEMES, + EXTENDED_LIGHT_UI_THEMES, LIGHT_UI_THEMES, getUiThemeById, } from "./uiThemes"; +import { TERMINAL_THEMES } from "./terminalThemes"; -describe("Copilot light UI themes", () => { - it("adds every Copilot preset to the light theme list", () => { - const expectedIds = [ - "github", - "fox", - "ic-orange-ppl", - "monochrome", - "noctis-azureus", - "notionish", - "polychrome", - "selene-selenized", - "tokyo-night", - "xotopia", - ]; +const SYSTEM_PRESET_THEME_IDS = [ + "a-cup-of-coffee", + "abolkog", + "aurora", + "ayu", + "base16-flat", + "base16-mocha", + "blue-dolphin", + "calm-days-sober-nights-sky", + "catppuccin", + "chai", + "chinolor", + "cyberdyne", + "desert", + "django-reborn-again", + "espresso", + "eyehealth", + "flexoki", + "fox", + "garbage-oracle", + "github", + "gruvbox-material", + "homebrew", + "ic-orange-ppl", + "ikki", + "kanso-ink", + "kary-pro-colors", + "light-purple", + "mondrian", + "monochrome", + "monochrome-stone", + "monokai-pro-spectrum", + "monospace", + "noctis-azureus", + "noctis-hibernus", + "noir-essence", + "nord-midnight", + "notionish", + "phonebook", + "polychrome", + "purplepeter", + "rainglow-codecourse", + "rainglow-crisp", + "rainglow-lavender", + "remedy-tilted", + "rose-pine", + "selene-selenized", + "soft-color", + "tearout", + "tokyo-night", + "tomorrow-night-eighties", + "vaporizer-turquoise", + "xotopio", + "yuttari", + "zenbones-rosebones", + "zhxo-red", +]; - assert.deepEqual(COPILOT_LIGHT_UI_THEMES.map((theme) => theme.id), expectedIds); - for (const id of expectedIds) { +describe("system preset UI themes", () => { + it("adds every imported preset at the same level as the existing UI themes", () => { + assert.deepEqual(EXTENDED_LIGHT_UI_THEMES.map((theme) => theme.id), SYSTEM_PRESET_THEME_IDS); + assert.deepEqual(EXTENDED_DARK_UI_THEMES.map((theme) => theme.id), SYSTEM_PRESET_THEME_IDS); + + for (const id of SYSTEM_PRESET_THEME_IDS) { assert.equal(getUiThemeById("light", id).id, id); + assert.equal(getUiThemeById("dark", id).id, id); } + + assert.equal(EXTENDED_LIGHT_UI_THEMES.length, 55); + assert.equal(EXTENDED_DARK_UI_THEMES.length, 55); + assert.equal(LIGHT_UI_THEMES.length, 7 + 55); + assert.equal(DARK_UI_THEMES.length, 7 + 55); + assert.equal([...LIGHT_UI_THEMES, ...DARK_UI_THEMES].filter((theme) => theme.collection !== undefined && theme.collection !== "core").length, 0); }); it("keeps theme accents distinct from the original default blue", () => { const originalDefaultBlue = "221.2 83.2% 53.3%"; - const accents = new Set(COPILOT_LIGHT_UI_THEMES.map((theme) => theme.tokens.accent)); + const accents = new Set([ + ...EXTENDED_LIGHT_UI_THEMES.map((theme) => theme.tokens.accent), + ...EXTENDED_DARK_UI_THEMES.map((theme) => theme.tokens.accent), + ]); - assert.equal(COPILOT_LIGHT_UI_THEMES.length, 10); - assert.equal(LIGHT_UI_THEMES.filter((theme) => theme.collection === "copilot").length, 10); - assert.ok(accents.size > 6); + assert.ok(accents.size > 20); assert.ok(!accents.has(originalDefaultBlue)); }); + + it("adds matching terminal themes for every imported light and dark UI preset", () => { + const terminalThemeIds = new Set(TERMINAL_THEMES.map((theme) => theme.id)); + assert.equal(terminalThemeIds.size, TERMINAL_THEMES.length); + + for (const id of SYSTEM_PRESET_THEME_IDS) { + const lightTerminalTheme = TERMINAL_THEMES.find((theme) => theme.id === `system-${id}-light`); + const darkTerminalTheme = TERMINAL_THEMES.find((theme) => theme.id === `system-${id}-dark`); + + assert.equal(lightTerminalTheme?.type, "light", id); + assert.equal(darkTerminalTheme?.type, "dark", id); + } + }); }); diff --git a/infrastructure/config/uiThemes.ts b/infrastructure/config/uiThemes.ts index a7a2a7262..bf89811f2 100644 --- a/infrastructure/config/uiThemes.ts +++ b/infrastructure/config/uiThemes.ts @@ -23,63 +23,10 @@ export type UiThemeTokens = { export type UiThemePreset = { id: string; name: string; - collection?: "core" | "copilot"; - preview?: { - sidebar: string; - activity: string[]; - syntax: string[]; - }; + collection?: "core"; tokens: UiThemeTokens; }; -type CopilotThemeConfig = { - id: string; - name: string; - background: string; - foreground: string; - card: string; - secondary: string; - muted: string; - mutedForeground: string; - border: string; - primary: string; - added: string; - removed: string; - skill: string; -}; - -const createCopilotLightTheme = (config: CopilotThemeConfig): UiThemePreset => ({ - id: config.id, - name: config.name, - collection: "copilot", - preview: { - sidebar: config.secondary, - activity: [config.removed, config.skill, config.added, config.primary], - syntax: [config.primary, config.removed, config.added, config.skill], - }, - tokens: { - background: config.background, - foreground: config.foreground, - card: config.card, - cardForeground: config.foreground, - popover: config.card, - popoverForeground: config.foreground, - primary: config.primary, - primaryForeground: "0 0% 100%", - secondary: config.secondary, - secondaryForeground: config.foreground, - muted: config.muted, - mutedForeground: config.mutedForeground, - accent: config.primary, - accentForeground: "0 0% 100%", - destructive: config.removed, - destructiveForeground: "0 0% 100%", - border: config.border, - input: config.border, - ring: config.primary, - }, -}); - export const CORE_LIGHT_UI_THEMES: UiThemePreset[] = [ { id: "snow", @@ -265,165 +212,2768 @@ export const CORE_LIGHT_UI_THEMES: UiThemePreset[] = [ }, ]; -export const COPILOT_LIGHT_UI_THEMES: UiThemePreset[] = [ - createCopilotLightTheme({ - id: "github", - name: "GitHub", - background: "0 0% 97%", - foreground: "261 36% 23%", - card: "0 0% 100%", - secondary: "220 12% 94%", - muted: "220 10% 91%", - mutedForeground: "220 7% 48%", - border: "220 10% 84%", - primary: "261 69% 59%", - added: "137 57% 41%", - removed: "356 72% 47%", - skill: "261 51% 51%", - }), - createCopilotLightTheme({ +export const EXTENDED_LIGHT_UI_THEMES: UiThemePreset[] = [ + { + id: "a-cup-of-coffee", + name: "A cup of coffee", + tokens: { + background: "0 0% 98.4%", + foreground: "0 0% 0%", + card: "0 0% 99.2%", + cardForeground: "0 0% 0%", + popover: "0 0% 99.2%", + popoverForeground: "0 0% 0%", + primary: "211.3 95.3% 33.1%", + primaryForeground: "0 0% 100%", + secondary: "0 0% 92.9%", + secondaryForeground: "0 0% 0%", + muted: "0 0% 90.2%", + mutedForeground: "0 0% 33.3%", + accent: "211.3 95.3% 33.1%", + accentForeground: "0 0% 100%", + destructive: "0 61.4% 49.8%", + destructiveForeground: "0 0% 100%", + border: "0 0% 83.5%", + input: "0 0% 83.5%", + ring: "211.3 95.3% 33.1%", + }, + }, + { + id: "abolkog", + name: "ABOLKOG", + tokens: { + background: "0 0% 100%", + foreground: "210 12.2% 16.1%", + card: "0 0% 100%", + cardForeground: "210 12.2% 16.1%", + popover: "0 0% 100%", + popoverForeground: "210 12.2% 16.1%", + primary: "40 70.6% 73.3%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 94.5%", + secondaryForeground: "210 12.2% 16.1%", + muted: "0 0% 91.4%", + mutedForeground: "205.7 3.1% 44.5%", + accent: "40 70.6% 73.3%", + accentForeground: "0 0% 0%", + destructive: "354.3 42.3% 56.5%", + destructiveForeground: "0 0% 0%", + border: "0 0% 85.1%", + input: "0 0% 85.1%", + ring: "40 70.6% 73.3%", + }, + }, + { + id: "aurora", + name: "Aurora", + tokens: { + background: "44.5 88.6% 93.1%", + foreground: "40.5 100% 14.5%", + card: "47.1 87.5% 96.9%", + cardForeground: "40.5 100% 14.5%", + popover: "47.1 87.5% 96.9%", + popoverForeground: "40.5 100% 14.5%", + primary: "171.4 100% 22%", + primaryForeground: "0 0% 100%", + secondary: "45.5 47.5% 88%", + secondaryForeground: "40.5 100% 14.5%", + muted: "45 36.8% 85.1%", + mutedForeground: "41 28.6% 41.2%", + accent: "171.4 100% 22%", + accentForeground: "0 0% 100%", + destructive: "341.7 100% 36.1%", + destructiveForeground: "0 0% 100%", + border: "43.8 24.5% 79.2%", + input: "43.8 24.5% 79.2%", + ring: "171.4 100% 22%", + }, + }, + { + id: "ayu", + name: "Ayu", + tokens: { + background: "210 16.7% 97.6%", + foreground: "210 5.2% 38%", + card: "240 20% 99%", + cardForeground: "210 5.2% 38%", + popover: "240 20% 99%", + popoverForeground: "210 5.2% 38%", + primary: "75.1 100% 35.1%", + primaryForeground: "0 0% 0%", + secondary: "210 5% 92.2%", + secondaryForeground: "210 5.2% 38%", + muted: "210 3.7% 89.4%", + mutedForeground: "205.7 3.3% 58.2%", + accent: "75.1 100% 35.1%", + accentForeground: "0 0% 0%", + destructive: "0 80.9% 69.2%", + destructiveForeground: "0 0% 0%", + border: "210 2.3% 83.1%", + input: "210 2.3% 83.1%", + ring: "75.1 100% 35.1%", + }, + }, + { + id: "base16-flat", + name: "Base16 Flat", + tokens: { + background: "192 15.2% 93.5%", + foreground: "184.3 5.8% 52.5%", + card: "200 20% 97.1%", + cardForeground: "184.3 5.8% 52.5%", + popover: "200 20% 97.1%", + popoverForeground: "184.3 5.8% 52.5%", + primary: "204.1 69.9% 53.1%", + primaryForeground: "0 0% 0%", + secondary: "192 8.5% 88.4%", + secondaryForeground: "184.3 5.8% 52.5%", + muted: "192 6.8% 85.7%", + mutedForeground: "185.5 6.4% 66.5%", + accent: "204.1 69.9% 53.1%", + accentForeground: "0 0% 0%", + destructive: "5.6 78.1% 57.1%", + destructiveForeground: "0 0% 0%", + border: "195 3.8% 79.6%", + input: "195 3.8% 79.6%", + ring: "204.1 69.9% 53.1%", + }, + }, + { + id: "base16-mocha", + name: "Base16 Mocha", + tokens: { + background: "18 33.3% 94.1%", + foreground: "30 22% 32.2%", + card: "12 38.5% 97.5%", + cardForeground: "30 22% 32.2%", + popover: "12 38.5% 97.5%", + popoverForeground: "30 22% 32.2%", + primary: "16.1 51.9% 63.3%", + primaryForeground: "0 0% 0%", + secondary: "18 17.9% 89%", + secondaryForeground: "30 22% 32.2%", + muted: "20 12.7% 86.1%", + mutedForeground: "28.9 11.3% 53.1%", + accent: "16.1 51.9% 63.3%", + accentForeground: "0 0% 0%", + destructive: "347.1 50.7% 58.6%", + destructiveForeground: "0 0% 0%", + border: "15 7.8% 80%", + input: "15 7.8% 80%", + ring: "16.1 51.9% 63.3%", + }, + }, + { + id: "blue-dolphin", + name: "Blue Dolphin", + tokens: { + background: "195 40% 94.1%", + foreground: "193.2 65.8% 14.9%", + card: "192 38.5% 97.5%", + cardForeground: "193.2 65.8% 14.9%", + popover: "192 38.5% 97.5%", + popoverForeground: "193.2 65.8% 14.9%", + primary: "195 100% 25.1%", + primaryForeground: "0 0% 100%", + secondary: "190.9 19.3% 88.8%", + secondaryForeground: "193.2 65.8% 14.9%", + muted: "196.4 15.5% 86.1%", + mutedForeground: "193 17.4% 41.8%", + accent: "195 100% 25.1%", + accentForeground: "0 0% 100%", + destructive: "353.3 64.3% 43.9%", + destructiveForeground: "0 0% 100%", + border: "192 9.8% 80%", + input: "192 9.8% 80%", + ring: "195 100% 25.1%", + }, + }, + { + id: "calm-days-sober-nights-sky", + name: "Calm Days, Sober Nights Sky", + tokens: { + background: "0 0% 100%", + foreground: "221.5 11.1% 45.9%", + card: "0 0% 100%", + cardForeground: "221.5 11.1% 45.9%", + popover: "0 0% 100%", + popoverForeground: "221.5 11.1% 45.9%", + primary: "142.1 100% 35.1%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 94.5%", + secondaryForeground: "221.5 11.1% 45.9%", + muted: "0 0% 91.4%", + mutedForeground: "220 9.9% 64.3%", + accent: "142.1 100% 35.1%", + accentForeground: "0 0% 0%", + destructive: "350.1 76% 67.3%", + destructiveForeground: "0 0% 0%", + border: "0 0% 85.1%", + input: "0 0% 85.1%", + ring: "142.1 100% 35.1%", + }, + }, + { + id: "catppuccin", + name: "Catppuccin", + tokens: { + background: "220 23.1% 94.9%", + foreground: "233.8 16% 35.5%", + card: "220 27.3% 97.8%", + cardForeground: "233.8 16% 35.5%", + popover: "220 27.3% 97.8%", + popoverForeground: "233.8 16% 35.5%", + primary: "219.9 91.5% 53.9%", + primaryForeground: "0 0% 100%", + secondary: "220 11.5% 89.8%", + secondaryForeground: "233.8 16% 35.5%", + muted: "216 7.5% 86.9%", + mutedForeground: "231.8 9.7% 55.7%", + accent: "219.9 91.5% 53.9%", + accentForeground: "0 0% 100%", + destructive: "347.1 86.7% 44.1%", + destructiveForeground: "0 0% 100%", + border: "216 5.1% 80.6%", + input: "216 5.1% 80.6%", + ring: "219.9 91.5% 53.9%", + }, + }, + { + id: "chai", + name: "Chai", + tokens: { + background: "0 0% 96.9%", + foreground: "228 8.2% 23.9%", + card: "0 0% 98.4%", + cardForeground: "228 8.2% 23.9%", + popover: "0 0% 98.4%", + popoverForeground: "228 8.2% 23.9%", + primary: "262.9 85.6% 59.2%", + primaryForeground: "0 0% 100%", + secondary: "0 0% 91.4%", + secondaryForeground: "228 8.2% 23.9%", + muted: "0 0% 88.6%", + mutedForeground: "231.4 2.8% 48.8%", + accent: "262.9 85.6% 59.2%", + accentForeground: "0 0% 100%", + destructive: "344.9 69.7% 49.2%", + destructiveForeground: "0 0% 100%", + border: "0 0% 82.4%", + input: "0 0% 82.4%", + ring: "262.9 85.6% 59.2%", + }, + }, + { + id: "chinolor", + name: "Chinolor", + tokens: { + background: "38.2 44% 95.1%", + foreground: "130 6.5% 18%", + card: "36 45.5% 97.8%", + cardForeground: "130 6.5% 18%", + popover: "36 45.5% 97.8%", + popoverForeground: "130 6.5% 18%", + primary: "48.2 100% 23.9%", + primaryForeground: "0 0% 100%", + secondary: "42 19.2% 89.8%", + secondaryForeground: "130 6.5% 18%", + muted: "36 15.2% 87.1%", + mutedForeground: "84 2.2% 44.1%", + accent: "48.2 100% 23.9%", + accentForeground: "0 0% 100%", + destructive: "355.2 83.7% 59%", + destructiveForeground: "0 0% 0%", + border: "36 10.2% 80.8%", + input: "36 10.2% 80.8%", + ring: "48.2 100% 23.9%", + }, + }, + { + id: "cyberdyne", + name: "Cyberdyne", + tokens: { + background: "248.6 22.6% 93.9%", + foreground: "153.9 69.7% 12.9%", + card: "255 28.6% 97.3%", + cardForeground: "153.9 69.7% 12.9%", + popover: "255 28.6% 97.3%", + popoverForeground: "153.9 69.7% 12.9%", + primary: "213 100% 31.4%", + primaryForeground: "0 0% 100%", + secondary: "248.6 12.3% 88.8%", + secondaryForeground: "153.9 69.7% 12.9%", + muted: "250 8.3% 85.9%", + mutedForeground: "158 14.7% 40%", + accent: "213 100% 31.4%", + accentForeground: "0 0% 100%", + destructive: "9 76.9% 40.8%", + destructiveForeground: "0 0% 100%", + border: "240 5.9% 80%", + input: "240 5.9% 80%", + ring: "213 100% 31.4%", + }, + }, + { + id: "desert", + name: "Desert", + tokens: { + background: "34.3 22.6% 93.9%", + foreground: "27.6 74.5% 20%", + card: "30 28.6% 97.3%", + cardForeground: "27.6 74.5% 20%", + popover: "30 28.6% 97.3%", + popoverForeground: "27.6 74.5% 20%", + primary: "147.7 100% 20.4%", + primaryForeground: "0 0% 100%", + secondary: "34.3 12.3% 88.8%", + secondaryForeground: "27.6 74.5% 20%", + muted: "40 8.3% 85.9%", + mutedForeground: "27.7 22.6% 45.1%", + accent: "147.7 100% 20.4%", + accentForeground: "0 0% 100%", + destructive: "0 100% 36.1%", + destructiveForeground: "0 0% 100%", + border: "30 5.9% 80%", + input: "30 5.9% 80%", + ring: "147.7 100% 20.4%", + }, + }, + { + id: "django-reborn-again", + name: "Django Reborn Again", + tokens: { + background: "150 26.7% 94.1%", + foreground: "155 47.4% 14.9%", + card: "150 28.6% 97.3%", + cardForeground: "155 47.4% 14.9%", + popover: "150 28.6% 97.3%", + popoverForeground: "155 47.4% 14.9%", + primary: "51.1 100% 23.9%", + primaryForeground: "0 0% 100%", + secondary: "150 14.3% 89%", + secondaryForeground: "155 47.4% 14.9%", + muted: "154.3 9.9% 86.1%", + mutedForeground: "155.6 12.7% 41.8%", + accent: "51.1 100% 23.9%", + accentForeground: "0 0% 100%", + destructive: "20.9 100% 36.1%", + destructiveForeground: "0 0% 100%", + border: "150 5.9% 80%", + input: "150 5.9% 80%", + ring: "51.1 100% 23.9%", + }, + }, + { + id: "espresso", + name: "Espresso", + tokens: { + background: "46.7 23.1% 92.4%", + foreground: "180 37.9% 17.1%", + card: "45 22.2% 96.5%", + cardForeground: "180 37.9% 17.1%", + popover: "45 22.2% 96.5%", + popoverForeground: "180 37.9% 17.1%", + primary: "195.8 20.4% 36.5%", + primaryForeground: "0 0% 100%", + secondary: "46.7 13.8% 87.3%", + secondaryForeground: "180 37.9% 17.1%", + muted: "46.7 11.4% 84.5%", + mutedForeground: "171.8 10% 43.1%", + accent: "195.8 20.4% 36.5%", + accentForeground: "0 0% 100%", + destructive: "0 27.4% 48.6%", + destructiveForeground: "0 0% 100%", + border: "45 7.3% 78.4%", + input: "45 7.3% 78.4%", + ring: "195.8 20.4% 36.5%", + }, + }, + { + id: "eyehealth", + name: "EyeHealth", + tokens: { + background: "47 100% 95.5%", + foreground: "22.4 31.2% 42.2%", + card: "48 100% 98%", + cardForeground: "22.4 31.2% 42.2%", + popover: "48 100% 98%", + popoverForeground: "22.4 31.2% 42.2%", + primary: "35.8 100% 50%", + primaryForeground: "0 0% 0%", + secondary: "46.4 44% 90.2%", + secondaryForeground: "22.4 31.2% 42.2%", + muted: "48.6 32.3% 87.3%", + mutedForeground: "25.4 25.7% 60.4%", + accent: "35.8 100% 50%", + accentForeground: "0 0% 0%", + destructive: "354 67% 56.1%", + destructiveForeground: "0 0% 0%", + border: "48 20.8% 81.2%", + input: "48 20.8% 81.2%", + ring: "35.8 100% 50%", + }, + }, + { + id: "flexoki", + name: "Flexoki", + tokens: { + background: "48 100% 97.1%", + foreground: "0 3.2% 6.1%", + card: "51.4 100% 98.6%", + cardForeground: "0 3.2% 6.1%", + popover: "51.4 100% 98.6%", + popoverForeground: "0 3.2% 6.1%", + primary: "45.3 98.9% 34.1%", + primaryForeground: "0 0% 0%", + secondary: "47.1 33.3% 91.8%", + secondaryForeground: "0 3.2% 6.1%", + muted: "50.8 22.8% 88.8%", + mutedForeground: "48 2.6% 37.1%", + accent: "45.3 98.9% 34.1%", + accentForeground: "0 0% 0%", + destructive: "3.1 62% 42.4%", + destructiveForeground: "0 0% 100%", + border: "46.2 14.6% 82.5%", + input: "46.2 14.6% 82.5%", + ring: "45.3 98.9% 34.1%", + }, + }, + { id: "fox", name: "Fox", - background: "15 33% 95%", - foreground: "260 34% 27%", - card: "20 28% 98%", - secondary: "15 18% 91%", - muted: "15 15% 89%", - mutedForeground: "260 12% 48%", - border: "15 14% 84%", - primary: "225 62% 48%", - added: "133 14% 49%", - removed: "0 43% 59%", - skill: "262 83% 58%", - }), - createCopilotLightTheme({ + tokens: { + background: "30 30.8% 94.9%", + foreground: "263 35.3% 26.1%", + card: "30 33.3% 97.6%", + cardForeground: "263 35.3% 26.1%", + popover: "30 33.3% 97.6%", + popoverForeground: "263 35.3% 26.1%", + primary: "28.9 97.7% 34.1%", + primaryForeground: "0 0% 100%", + secondary: "34.3 13.2% 89.6%", + secondaryForeground: "263 35.3% 26.1%", + muted: "25.7 10.4% 86.9%", + mutedForeground: "266.9 11.6% 49.2%", + accent: "28.9 97.7% 34.1%", + accentForeground: "0 0% 100%", + destructive: "354 65.8% 39%", + destructiveForeground: "0 0% 100%", + border: "34.3 7.1% 80.6%", + input: "34.3 7.1% 80.6%", + ring: "28.9 97.7% 34.1%", + }, + }, + { + id: "garbage-oracle", + name: "Garbage Oracle", + tokens: { + background: "303.8 38.1% 91.8%", + foreground: "320.9 100% 26.5%", + card: "300 36.8% 96.3%", + cardForeground: "320.9 100% 26.5%", + popover: "300 36.8% 96.3%", + popoverForeground: "320.9 100% 26.5%", + primary: "22.7 66.2% 29%", + primaryForeground: "0 0% 100%", + secondary: "304 22.4% 86.9%", + secondaryForeground: "320.9 100% 26.5%", + muted: "300 17.1% 83.9%", + mutedForeground: "319.8 37.9% 48.6%", + accent: "22.7 66.2% 29%", + accentForeground: "0 0% 100%", + destructive: "352.2 54.7% 41.6%", + destructiveForeground: "0 0% 100%", + border: "304.3 12.5% 78%", + input: "304.3 12.5% 78%", + ring: "22.7 66.2% 29%", + }, + }, + { + id: "github", + name: "GitHub", + tokens: { + background: "0 0% 100%", + foreground: "213.3 12.7% 13.9%", + card: "0 0% 100%", + cardForeground: "213.3 12.7% 13.9%", + popover: "0 0% 100%", + popoverForeground: "213.3 12.7% 13.9%", + primary: "212.4 92.1% 44.5%", + primaryForeground: "0 0% 100%", + secondary: "0 0% 94.5%", + secondaryForeground: "213.3 12.7% 13.9%", + muted: "0 0% 91.4%", + mutedForeground: "210 2.7% 43.1%", + accent: "212.4 92.1% 44.5%", + accentForeground: "0 0% 100%", + destructive: "355.8 71.8% 47.3%", + destructiveForeground: "0 0% 100%", + border: "0 0% 85.1%", + input: "0 0% 85.1%", + ring: "212.4 92.1% 44.5%", + }, + }, + { + id: "gruvbox-material", + name: "Gruvbox Material", + tokens: { + background: "48.5 86.7% 88.2%", + foreground: "22.5 31.2% 30.2%", + card: "49.6 85.2% 94.7%", + cardForeground: "22.5 31.2% 30.2%", + popover: "49.6 85.2% 94.7%", + popoverForeground: "22.5 31.2% 30.2%", + primary: "36.5 90.5% 37.1%", + primaryForeground: "0 0% 0%", + secondary: "49 57.6% 83.3%", + secondaryForeground: "22.5 31.2% 30.2%", + muted: "48.8 49% 80.8%", + mutedForeground: "31.8 19.2% 50%", + accent: "36.5 90.5% 37.1%", + accentForeground: "0 0% 0%", + destructive: "0 49% 52.4%", + destructiveForeground: "0 0% 100%", + border: "49.1 34.4% 74.9%", + input: "49.1 34.4% 74.9%", + ring: "36.5 90.5% 37.1%", + }, + }, + { + id: "homebrew", + name: "Homebrew", + tokens: { + background: "120 40% 94.1%", + foreground: "120 65.8% 14.9%", + card: "120 38.5% 97.5%", + cardForeground: "120 65.8% 14.9%", + popover: "120 38.5% 97.5%", + popoverForeground: "120 65.8% 14.9%", + primary: "300 100% 23.5%", + primaryForeground: "0 0% 100%", + secondary: "120 19.3% 88.8%", + secondaryForeground: "120 65.8% 14.9%", + muted: "120 15.5% 86.1%", + mutedForeground: "120 17.4% 41.8%", + accent: "300 100% 23.5%", + accentForeground: "0 0% 100%", + destructive: "0 100% 23.9%", + destructiveForeground: "0 0% 100%", + border: "120 9.8% 80%", + input: "120 9.8% 80%", + ring: "300 100% 23.5%", + }, + }, + { id: "ic-orange-ppl", name: "IC Orange PPL", - background: "37 35% 93%", - foreground: "257 35% 25%", - card: "38 33% 96%", - secondary: "38 22% 88%", - muted: "38 18% 85%", - mutedForeground: "37 12% 45%", - border: "36 18% 80%", - primary: "15 90% 41%", - added: "56 44% 35%", - removed: "16 37% 48%", - skill: "45 100% 24%", - }), - createCopilotLightTheme({ + tokens: { + background: "35 40% 94.1%", + foreground: "34.8 65.8% 14.9%", + card: "36 38.5% 97.5%", + cardForeground: "34.8 65.8% 14.9%", + popover: "36 38.5% 97.5%", + popoverForeground: "34.8 65.8% 14.9%", + primary: "24 100% 23.5%", + primaryForeground: "0 0% 100%", + secondary: "38.2 19.3% 88.8%", + secondaryForeground: "34.8 65.8% 14.9%", + muted: "38.2 15.5% 86.1%", + mutedForeground: "35.7 17.4% 41.8%", + accent: "24 100% 23.5%", + accentForeground: "0 0% 100%", + destructive: "14.1 100% 26.7%", + destructiveForeground: "0 0% 100%", + border: "36 9.8% 80%", + input: "36 9.8% 80%", + ring: "24 100% 23.5%", + }, + }, + { + id: "ikki", + name: "IKKI", + tokens: { + background: "43.6 100% 97.8%", + foreground: "22.4 31.2% 42.2%", + card: "48 100% 99%", + cardForeground: "22.4 31.2% 42.2%", + popover: "48 100% 99%", + popoverForeground: "22.4 31.2% 42.2%", + primary: "35.8 100% 50%", + primaryForeground: "0 0% 0%", + secondary: "42 26.3% 92.5%", + secondaryForeground: "22.4 31.2% 42.2%", + muted: "48 18.5% 89.4%", + mutedForeground: "23.7 24.2% 61.2%", + accent: "35.8 100% 50%", + accentForeground: "0 0% 0%", + destructive: "354 67% 56.1%", + destructiveForeground: "0 0% 0%", + border: "42 11.6% 83.1%", + input: "42 11.6% 83.1%", + ring: "35.8 100% 50%", + }, + }, + { + id: "kanso-ink", + name: "Kanso Ink", + tokens: { + background: "40 10.3% 94.3%", + foreground: "218.2 13.9% 15.5%", + card: "60 7.7% 97.5%", + cardForeground: "218.2 13.9% 15.5%", + popover: "60 7.7% 97.5%", + popoverForeground: "218.2 13.9% 15.5%", + primary: "351.6 55.3% 51.8%", + primaryForeground: "0 0% 100%", + secondary: "40 5.5% 89.2%", + secondaryForeground: "218.2 13.9% 15.5%", + muted: "60 2.9% 86.3%", + mutedForeground: "220 2.8% 42.4%", + accent: "351.6 55.3% 51.8%", + accentForeground: "0 0% 100%", + destructive: "351.6 55.3% 51.8%", + destructiveForeground: "0 0% 100%", + border: "40 3% 80.2%", + input: "40 3% 80.2%", + ring: "351.6 55.3% 51.8%", + }, + }, + { + id: "kary-pro-colors", + name: "Kary Pro Colors", + tokens: { + background: "207.3 57.9% 96.3%", + foreground: "209.5 53.8% 46.7%", + card: "204 55.6% 98.2%", + cardForeground: "209.5 53.8% 46.7%", + popover: "204 55.6% 98.2%", + popoverForeground: "209.5 53.8% 46.7%", + primary: "32.7 76.5% 36.7%", + primaryForeground: "0 0% 100%", + secondary: "210 21.7% 91%", + secondaryForeground: "209.5 53.8% 46.7%", + muted: "210 16.7% 88.2%", + mutedForeground: "209.3 47.3% 63.5%", + accent: "32.7 76.5% 36.7%", + accentForeground: "0 0% 100%", + destructive: "13.1 69.6% 46.5%", + destructiveForeground: "0 0% 100%", + border: "206.7 9.7% 81.8%", + input: "206.7 9.7% 81.8%", + ring: "32.7 76.5% 36.7%", + }, + }, + { + id: "light-purple", + name: "Light purple", + tokens: { + background: "10 15.8% 92.5%", + foreground: "274.8 33.8% 29%", + card: "20 17.6% 96.7%", + cardForeground: "274.8 33.8% 29%", + popover: "20 17.6% 96.7%", + popoverForeground: "274.8 33.8% 29%", + primary: "46.8 98.2% 44.3%", + primaryForeground: "0 0% 0%", + secondary: "10 9.4% 87.5%", + secondaryForeground: "274.8 33.8% 29%", + muted: "10 7.7% 84.7%", + mutedForeground: "278.2 13% 50.4%", + accent: "46.8 98.2% 44.3%", + accentForeground: "0 0% 0%", + destructive: "0.7 71.2% 55.1%", + destructiveForeground: "0 0% 0%", + border: "12 4.6% 78.6%", + input: "12 4.6% 78.6%", + ring: "46.8 98.2% 44.3%", + }, + }, + { + id: "mondrian", + name: "Mondrian", + tokens: { + background: "0 0% 100%", + foreground: "0 0% 0%", + card: "0 0% 100%", + cardForeground: "0 0% 0%", + popover: "0 0% 100%", + popoverForeground: "0 0% 0%", + primary: "217.4 89% 60.8%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 94.5%", + secondaryForeground: "0 0% 0%", + muted: "0 0% 91.4%", + mutedForeground: "0 0% 34.1%", + accent: "217.4 89% 60.8%", + accentForeground: "0 0% 0%", + destructive: "4.8 69.5% 53.7%", + destructiveForeground: "0 0% 0%", + border: "0 0% 85.1%", + input: "0 0% 85.1%", + ring: "217.4 89% 60.8%", + }, + }, + { id: "monochrome", name: "Monochrome", - background: "215 38% 94%", - foreground: "221 39% 11%", - card: "210 40% 98%", - secondary: "215 25% 88%", - muted: "215 20% 86%", - mutedForeground: "220 9% 46%", - border: "215 16% 78%", - primary: "222 47% 11%", - added: "220 9% 46%", - removed: "218 11% 65%", - skill: "221 39% 11%", - }), - createCopilotLightTheme({ + tokens: { + background: "210 40% 96.1%", + foreground: "222.2 47.4% 11.2%", + card: "200 33.3% 98.2%", + cardForeground: "222.2 47.4% 11.2%", + popover: "200 33.3% 98.2%", + popoverForeground: "222.2 47.4% 11.2%", + primary: "222.2 47.4% 11.2%", + primaryForeground: "0 0% 100%", + secondary: "205.7 14.9% 90.8%", + secondaryForeground: "222.2 47.4% 11.2%", + muted: "214.3 11.5% 88%", + mutedForeground: "222 9.8% 40%", + accent: "222.2 47.4% 11.2%", + accentForeground: "0 0% 100%", + destructive: "222.2 47.4% 11.2%", + destructiveForeground: "0 0% 100%", + border: "214.3 7.5% 81.8%", + input: "214.3 7.5% 81.8%", + ring: "222.2 47.4% 11.2%", + }, + }, + { + id: "monochrome-stone", + name: "Monochrome Stone", + tokens: { + background: "60 4.8% 95.9%", + foreground: "24 9.8% 10%", + card: "60 11.1% 98.2%", + cardForeground: "24 9.8% 10%", + popover: "60 11.1% 98.2%", + popoverForeground: "24 9.8% 10%", + primary: "24 9.8% 10%", + primaryForeground: "0 0% 100%", + secondary: "60 2.1% 90.8%", + secondaryForeground: "24 9.8% 10%", + muted: "60 1.6% 87.6%", + mutedForeground: "30 2% 39.2%", + accent: "24 9.8% 10%", + accentForeground: "0 0% 100%", + destructive: "24 9.8% 10%", + destructiveForeground: "0 0% 100%", + border: "60 1.1% 81.4%", + input: "60 1.1% 81.4%", + ring: "24 9.8% 10%", + }, + }, + { + id: "monokai-pro-spectrum", + name: "Monokai Pro Spectrum", + tokens: { + background: "28.2 54.8% 93.9%", + foreground: "289.1 13.6% 15.9%", + card: "30 57.1% 97.3%", + cardForeground: "289.1 13.6% 15.9%", + popover: "30 57.1% 97.3%", + popoverForeground: "289.1 13.6% 15.9%", + primary: "34.8 96.7% 35.3%", + primaryForeground: "0 0% 0%", + secondary: "30 27.6% 88.6%", + secondaryForeground: "289.1 13.6% 15.9%", + muted: "30 22.2% 85.9%", + mutedForeground: "326.7 4.1% 42.5%", + accent: "34.8 96.7% 35.3%", + accentForeground: "0 0% 0%", + destructive: "341.8 57.9% 54.3%", + destructiveForeground: "0 0% 0%", + border: "28 14.6% 79.8%", + input: "28 14.6% 79.8%", + ring: "34.8 96.7% 35.3%", + }, + }, + { + id: "monospace", + name: "Monospace", + tokens: { + background: "0 0% 100%", + foreground: "216.9 29.5% 17.3%", + card: "0 0% 100%", + cardForeground: "216.9 29.5% 17.3%", + popover: "0 0% 100%", + popoverForeground: "216.9 29.5% 17.3%", + primary: "196.7 100% 31.8%", + primaryForeground: "0 0% 100%", + secondary: "0 0% 94.5%", + secondaryForeground: "216.9 29.5% 17.3%", + muted: "0 0% 91.4%", + mutedForeground: "215.3 7.4% 45.3%", + accent: "196.7 100% 31.8%", + accentForeground: "0 0% 100%", + destructive: "356.8 61.6% 52%", + destructiveForeground: "0 0% 100%", + border: "0 0% 85.1%", + input: "0 0% 85.1%", + ring: "196.7 100% 31.8%", + }, + }, + { id: "noctis-azureus", name: "Noctis Azureus", - background: "51 49% 92%", - foreground: "216 28% 27%", - card: "51 70% 97%", - secondary: "124 18% 90%", - muted: "150 14% 86%", - mutedForeground: "190 12% 50%", - border: "124 14% 82%", - primary: "337 100% 65%", - added: "143 47% 53%", - removed: "13 100% 71%", - skill: "193 100% 42%", - }), - createCopilotLightTheme({ + tokens: { + background: "40 90% 96.1%", + foreground: "186.8 100% 19%", + card: "40 100% 98.2%", + cardForeground: "186.8 100% 19%", + popover: "40 100% 98.2%", + popoverForeground: "186.8 100% 19%", + primary: "203 100% 47.1%", + primaryForeground: "0 0% 0%", + secondary: "38.8 36.2% 90.8%", + secondaryForeground: "186.8 100% 19%", + muted: "41.2 25.8% 87.8%", + mutedForeground: "183.1 25.2% 45.1%", + accent: "203 100% 47.1%", + accentForeground: "0 0% 0%", + destructive: "15.1 78% 50%", + destructiveForeground: "0 0% 0%", + border: "40 16.1% 81.8%", + input: "40 16.1% 81.8%", + ring: "203 100% 47.1%", + }, + }, + { + id: "noctis-hibernus", + name: "Noctis Hibernus", + tokens: { + background: "180 10% 96.1%", + foreground: "186.8 100% 19%", + card: "180 11.1% 98.2%", + cardForeground: "186.8 100% 19%", + popover: "180 11.1% 98.2%", + popoverForeground: "186.8 100% 19%", + primary: "203 100% 47.1%", + primaryForeground: "0 0% 0%", + secondary: "180 2.1% 90.8%", + secondaryForeground: "186.8 100% 19%", + muted: "180 3.2% 87.8%", + mutedForeground: "187.4 28.1% 45.3%", + accent: "203 100% 47.1%", + accentForeground: "0 0% 0%", + destructive: "15.1 78% 50%", + destructiveForeground: "0 0% 0%", + border: "180 2.1% 81.6%", + input: "180 2.1% 81.6%", + ring: "203 100% 47.1%", + }, + }, + { + id: "noir-essence", + name: "Noir Essence", + tokens: { + background: "41.5 44.8% 94.3%", + foreground: "0 0% 0%", + card: "48 38.5% 97.5%", + cardForeground: "0 0% 0%", + popover: "48 38.5% 97.5%", + popoverForeground: "0 0% 0%", + primary: "54.1 100% 23.9%", + primaryForeground: "0 0% 100%", + secondary: "45 21.4% 89%", + secondaryForeground: "0 0% 0%", + muted: "40 17.1% 86.3%", + mutedForeground: "45 2.4% 32.2%", + accent: "54.1 100% 23.9%", + accentForeground: "0 0% 100%", + destructive: "3 56.6% 58.4%", + destructiveForeground: "0 0% 0%", + border: "43.6 10.9% 80.2%", + input: "43.6 10.9% 80.2%", + ring: "54.1 100% 23.9%", + }, + }, + { + id: "nord-midnight", + name: "Nord Midnight", + tokens: { + background: "217.5 26.7% 94.1%", + foreground: "220 16.4% 21.6%", + card: "210 28.6% 97.3%", + cardForeground: "220 16.4% 21.6%", + popover: "210 28.6% 97.3%", + popoverForeground: "220 16.4% 21.6%", + primary: "187.1 83% 30%", + primaryForeground: "0 0% 100%", + secondary: "217.5 14.3% 89%", + secondaryForeground: "220 16.4% 21.6%", + muted: "214.3 9.9% 86.1%", + mutedForeground: "218.6 5.9% 46.3%", + accent: "187.1 83% 30%", + accentForeground: "0 0% 100%", + destructive: "354.3 42.3% 56.5%", + destructiveForeground: "0 0% 0%", + border: "220 5.9% 80%", + input: "220 5.9% 80%", + ring: "187.1 83% 30%", + }, + }, + { id: "notionish", name: "Notionish", - background: "45 20% 96%", - foreground: "246 33% 25%", - card: "0 0% 100%", - secondary: "45 8% 93%", - muted: "45 8% 90%", - mutedForeground: "246 8% 48%", - border: "45 8% 84%", - primary: "261 51% 51%", - added: "139 51% 37%", - removed: "5 73% 64%", - skill: "262 83% 58%", - }), - createCopilotLightTheme({ + tokens: { + background: "0 0% 100%", + foreground: "60 2% 9.6%", + card: "0 0% 100%", + cardForeground: "60 2% 9.6%", + popover: "0 0% 100%", + popoverForeground: "60 2% 9.6%", + primary: "208.4 100% 43.5%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 94.5%", + secondaryForeground: "60 2% 9.6%", + muted: "0 0% 91.4%", + mutedForeground: "0 0% 40.4%", + accent: "208.4 100% 43.5%", + accentForeground: "0 0% 0%", + destructive: "7.2 83.8% 48.4%", + destructiveForeground: "0 0% 0%", + border: "0 0% 85.1%", + input: "0 0% 85.1%", + ring: "208.4 100% 43.5%", + }, + }, + { + id: "phonebook", + name: "Phonebook", + tokens: { + background: "35.6 37.2% 83.1%", + foreground: "31.3 45.1% 20%", + card: "36 38.5% 92.4%", + cardForeground: "31.3 45.1% 20%", + popover: "36 38.5% 92.4%", + popoverForeground: "31.3 45.1% 20%", + primary: "186.5 100% 37.8%", + primaryForeground: "0 0% 0%", + secondary: "36 27.3% 78.4%", + secondaryForeground: "31.3 45.1% 20%", + muted: "36 24.6% 76.1%", + mutedForeground: "32.2 19.4% 41.4%", + accent: "186.5 100% 37.8%", + accentForeground: "0 0% 0%", + destructive: "4 89.9% 61%", + destructiveForeground: "0 0% 0%", + border: "35.6 18.1% 70.8%", + input: "35.6 18.1% 70.8%", + ring: "186.5 100% 37.8%", + }, + }, + { id: "polychrome", name: "Polychrome", - background: "253 100% 97%", - foreground: "266 43% 22%", - card: "0 0% 100%", - secondary: "253 45% 93%", - muted: "253 35% 90%", - mutedForeground: "266 14% 48%", - border: "253 30% 84%", - primary: "258 90% 66%", - added: "142 71% 45%", - removed: "351 95% 71%", - skill: "271 91% 65%", - }), - createCopilotLightTheme({ + tokens: { + background: "30 20% 98%", + foreground: "255.6 60% 44.1%", + card: "60 20% 99%", + cardForeground: "255.6 60% 44.1%", + popover: "60 20% 99%", + popoverForeground: "255.6 60% 44.1%", + primary: "255.3 86.5% 59.2%", + primaryForeground: "0 0% 100%", + secondary: "30 5.3% 92.5%", + secondaryForeground: "255.6 60% 44.1%", + muted: "30 3.8% 89.8%", + mutedForeground: "255.7 45.8% 62.4%", + accent: "255.3 86.5% 59.2%", + accentForeground: "0 0% 100%", + destructive: "0 90.2% 56.1%", + destructiveForeground: "0 0% 0%", + border: "60 1.2% 83.3%", + input: "60 1.2% 83.3%", + ring: "255.3 86.5% 59.2%", + }, + }, + { + id: "purplepeter", + name: "Purplepeter", + tokens: { + background: "261.8 40.7% 94.7%", + foreground: "258.6 55.3% 14.9%", + card: "264 38.5% 97.5%", + cardForeground: "258.6 55.3% 14.9%", + popover: "264 38.5% 97.5%", + popoverForeground: "258.6 55.3% 14.9%", + primary: "190.2 83.9% 31.6%", + primaryForeground: "0 0% 100%", + secondary: "264 18.5% 89.4%", + secondaryForeground: "258.6 55.3% 14.9%", + muted: "264 14.7% 86.7%", + mutedForeground: "258.8 15% 42%", + accent: "190.2 83.9% 31.6%", + accentForeground: "0 0% 100%", + destructive: "0 41.9% 48.6%", + destructiveForeground: "0 0% 100%", + border: "260 9.1% 80.6%", + input: "260 9.1% 80.6%", + ring: "190.2 83.9% 31.6%", + }, + }, + { + id: "rainglow-codecourse", + name: "Rainglow Codecourse", + tokens: { + background: "0 0% 100%", + foreground: "197.7 26.6% 44.9%", + card: "0 0% 100%", + cardForeground: "197.7 26.6% 44.9%", + popover: "0 0% 100%", + popoverForeground: "197.7 26.6% 44.9%", + primary: "202.7 97.4% 55.3%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 94.5%", + secondaryForeground: "197.7 26.6% 44.9%", + muted: "0 0% 91.4%", + mutedForeground: "196.5 21.5% 63.5%", + accent: "202.7 97.4% 55.3%", + accentForeground: "0 0% 0%", + destructive: "348.8 86% 39.2%", + destructiveForeground: "0 0% 100%", + border: "0 0% 85.1%", + input: "0 0% 85.1%", + ring: "202.7 97.4% 55.3%", + }, + }, + { + id: "rainglow-crisp", + name: "Rainglow Crisp", + tokens: { + background: "0 0% 100%", + foreground: "300 13.3% 11.8%", + card: "0 0% 100%", + cardForeground: "300 13.3% 11.8%", + popover: "0 0% 100%", + popoverForeground: "300 13.3% 11.8%", + primary: "23 97.5% 52.4%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 94.5%", + secondaryForeground: "300 13.3% 11.8%", + muted: "0 0% 91.4%", + mutedForeground: "300 2.3% 41.8%", + accent: "23 97.5% 52.4%", + accentForeground: "0 0% 0%", + destructive: "348.8 86% 39.2%", + destructiveForeground: "0 0% 100%", + border: "0 0% 85.1%", + input: "0 0% 85.1%", + ring: "23 97.5% 52.4%", + }, + }, + { + id: "rainglow-lavender", + name: "Rainglow Lavender", + tokens: { + background: "0 0% 100%", + foreground: "275 15% 15.7%", + card: "0 0% 100%", + cardForeground: "275 15% 15.7%", + popover: "0 0% 100%", + popoverForeground: "275 15% 15.7%", + primary: "273.9 100% 67.1%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 94.5%", + secondaryForeground: "275 15% 15.7%", + muted: "0 0% 91.4%", + mutedForeground: "277.5 3.5% 44.3%", + accent: "273.9 100% 67.1%", + accentForeground: "0 0% 0%", + destructive: "348.8 86% 39.2%", + destructiveForeground: "0 0% 100%", + border: "0 0% 85.1%", + input: "0 0% 85.1%", + ring: "273.9 100% 67.1%", + }, + }, + { + id: "remedy-tilted", + name: "Remedy Tilted", + tokens: { + background: "41.1 90.5% 95.9%", + foreground: "39.2 72% 19.6%", + card: "40 100% 98.2%", + cardForeground: "39.2 72% 19.6%", + popover: "40 100% 98.2%", + popoverForeground: "39.2 72% 19.6%", + primary: "24.6 65.8% 62.2%", + primaryForeground: "0 0% 0%", + secondary: "40 37.5% 90.6%", + secondaryForeground: "39.2 72% 19.6%", + muted: "42.4 27% 87.6%", + mutedForeground: "40 23.3% 45.5%", + accent: "24.6 65.8% 62.2%", + accentForeground: "0 0% 0%", + destructive: "0 42.9% 45.3%", + destructiveForeground: "0 0% 100%", + border: "41.2 17% 81.6%", + input: "41.2 17% 81.6%", + ring: "24.6 65.8% 62.2%", + }, + }, + { + id: "rose-pine", + name: "Rosé Pine", + tokens: { + background: "32.3 56.5% 95.5%", + foreground: "247.7 19.2% 39.8%", + card: "30 60% 98%", + cardForeground: "247.7 19.2% 39.8%", + popover: "30 60% 98%", + popoverForeground: "247.7 19.2% 39.8%", + primary: "34.6 81.2% 56.1%", + primaryForeground: "0 0% 0%", + secondary: "35 24% 90.2%", + secondaryForeground: "247.7 19.2% 39.8%", + muted: "30 18.8% 87.5%", + mutedForeground: "253 10.8% 58.2%", + accent: "34.6 81.2% 56.1%", + accentForeground: "0 0% 0%", + destructive: "343 35.1% 54.7%", + destructiveForeground: "0 0% 0%", + border: "30 12.5% 81.2%", + input: "30 12.5% 81.2%", + ring: "34.6 81.2% 56.1%", + }, + }, + { id: "selene-selenized", name: "Selene Selenized", - background: "47 70% 90%", - foreground: "258 31% 23%", - card: "48 80% 96%", - secondary: "48 45% 84%", - muted: "48 35% 82%", - mutedForeground: "48 11% 42%", - border: "48 26% 76%", - primary: "323 56% 55%", - added: "92 45% 43%", - removed: "6 70% 62%", - skill: "17 88% 40%", - }), - createCopilotLightTheme({ + tokens: { + background: "41.7 94.7% 92.5%", + foreground: "193.8 18.8% 27.1%", + card: "42.4 100% 96.7%", + cardForeground: "193.8 18.8% 27.1%", + popover: "42.4 100% 96.7%", + popoverForeground: "193.8 18.8% 27.1%", + primary: "207.1 100% 41.2%", + primaryForeground: "0 0% 100%", + secondary: "42.4 53.1% 87.5%", + secondaryForeground: "193.8 18.8% 27.1%", + muted: "41.8 41.8% 84.5%", + mutedForeground: "150 3.9% 50.2%", + accent: "207.1 100% 41.2%", + accentForeground: "0 0% 100%", + destructive: "356.6 73.1% 48%", + destructiveForeground: "0 0% 100%", + border: "42.6 28.4% 78.6%", + input: "42.6 28.4% 78.6%", + ring: "207.1 100% 41.2%", + }, + }, + { + id: "soft-color", + name: "Soft Color", + tokens: { + background: "95 100% 97.6%", + foreground: "0 0% 35.3%", + card: "96 100% 99%", + cardForeground: "0 0% 35.3%", + popover: "96 100% 99%", + popoverForeground: "0 0% 35.3%", + primary: "211.3 95.3% 33.1%", + primaryForeground: "0 0% 100%", + secondary: "98.2 28.2% 92.4%", + secondaryForeground: "0 0% 35.3%", + muted: "92.7 20% 89.2%", + mutedForeground: "90 1.8% 56.5%", + accent: "211.3 95.3% 33.1%", + accentForeground: "0 0% 100%", + destructive: "0 61.4% 49.8%", + destructiveForeground: "0 0% 100%", + border: "96 11.6% 83.1%", + input: "96 11.6% 83.1%", + ring: "211.3 95.3% 33.1%", + }, + }, + { + id: "tearout", + name: "Tearout", + tokens: { + background: "96.9 26.5% 90.4%", + foreground: "90 7.9% 14.9%", + card: "100 27.3% 95.7%", + cardForeground: "90 7.9% 14.9%", + popover: "100 27.3% 95.7%", + popoverForeground: "90 7.9% 14.9%", + primary: "22.5 36.4% 34.5%", + primaryForeground: "0 0% 100%", + secondary: "100 16.2% 85.5%", + secondaryForeground: "90 7.9% 14.9%", + muted: "95 13.6% 82.7%", + mutedForeground: "93.3 4.3% 40.6%", + accent: "22.5 36.4% 34.5%", + accentForeground: "0 0% 100%", + destructive: "6.7 33.3% 42.4%", + destructiveForeground: "0 0% 100%", + border: "92.7 9.2% 76.7%", + input: "92.7 9.2% 76.7%", + ring: "22.5 36.4% 34.5%", + }, + }, + { id: "tokyo-night", name: "Tokyo Night", - background: "219 56% 92%", - foreground: "220 32% 22%", - card: "219 60% 96%", - secondary: "221 38% 86%", - muted: "221 32% 83%", - mutedForeground: "220 16% 45%", - border: "221 28% 76%", - primary: "273 68% 59%", - added: "90 18% 53%", - removed: "349 89% 72%", - skill: "221 89% 72%", - }), - createCopilotLightTheme({ - id: "xotopia", - name: "Xotopia", - background: "0 6% 94%", - foreground: "267 33% 24%", - card: "0 8% 98%", - secondary: "0 5% 89%", - muted: "0 4% 86%", - mutedForeground: "267 9% 48%", - border: "0 4% 80%", - primary: "332 67% 54%", - added: "159 28% 53%", - removed: "357 80% 67%", - skill: "203 38% 53%", - }), + tokens: { + background: "230 11.1% 89.4%", + foreground: "221.9 55.3% 48.2%", + card: "240 8.3% 95.3%", + cardForeground: "221.9 55.3% 48.2%", + popover: "240 8.3% 95.3%", + popoverForeground: "221.9 55.3% 48.2%", + primary: "195.1 100% 29.6%", + primaryForeground: "0 0% 100%", + secondary: "228 6.3% 84.5%", + secondaryForeground: "221.9 55.3% 48.2%", + muted: "228 5.4% 81.8%", + mutedForeground: "222.4 47.9% 62.4%", + accent: "195.1 100% 29.6%", + accentForeground: "0 0% 100%", + destructive: "342.6 91% 56.3%", + destructiveForeground: "0 0% 0%", + border: "228 4.1% 75.9%", + input: "228 4.1% 75.9%", + ring: "195.1 100% 29.6%", + }, + }, + { + id: "tomorrow-night-eighties", + name: "Tomorrow Night Eighties", + tokens: { + background: "0 0% 100%", + foreground: "60 0.7% 30%", + card: "0 0% 100%", + cardForeground: "60 0.7% 30%", + popover: "0 0% 100%", + popoverForeground: "60 0.7% 30%", + primary: "71.6 100% 27.5%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 94.5%", + secondaryForeground: "60 0.7% 30%", + muted: "0 0% 91.4%", + mutedForeground: "60 0.4% 53.9%", + accent: "71.6 100% 27.5%", + accentForeground: "0 0% 0%", + destructive: "359.6 66.7% 47.1%", + destructiveForeground: "0 0% 100%", + border: "0 0% 85.1%", + input: "0 0% 85.1%", + ring: "71.6 100% 27.5%", + }, + }, + { + id: "vaporizer-turquoise", + name: "Vaporizer Turquoise", + tokens: { + background: "0 0% 95.3%", + foreground: "117.5 50% 18.8%", + card: "0 0% 98%", + cardForeground: "117.5 50% 18.8%", + popover: "0 0% 98%", + popoverForeground: "117.5 50% 18.8%", + primary: "300 94.8% 37.8%", + primaryForeground: "0 0% 100%", + secondary: "0 0% 90.2%", + secondaryForeground: "117.5 50% 18.8%", + muted: "0 0% 87.1%", + mutedForeground: "116.3 14% 44.7%", + accent: "300 94.8% 37.8%", + accentForeground: "0 0% 100%", + destructive: "0 61.4% 49.8%", + destructiveForeground: "0 0% 100%", + border: "0 0% 81.2%", + input: "0 0% 81.2%", + ring: "300 94.8% 37.8%", + }, + }, + { + id: "xotopio", + name: "Xotopio", + tokens: { + background: "20 15.8% 96.3%", + foreground: "0 0% 12.9%", + card: "60 11.1% 98.2%", + cardForeground: "0 0% 12.9%", + popover: "60 11.1% 98.2%", + popoverForeground: "0 0% 12.9%", + primary: "331 64.2% 55.1%", + primaryForeground: "0 0% 0%", + secondary: "30 4.3% 91%", + secondaryForeground: "0 0% 12.9%", + muted: "20 4.9% 88%", + mutedForeground: "0 0.5% 41.4%", + accent: "331 64.2% 55.1%", + accentForeground: "0 0% 0%", + destructive: "0.7 71.2% 55.1%", + destructiveForeground: "0 0% 0%", + border: "20 3.2% 81.8%", + input: "20 3.2% 81.8%", + ring: "331 64.2% 55.1%", + }, + }, + { + id: "yuttari", + name: "Yuttari", + tokens: { + background: "336.7 100% 96.5%", + foreground: "334.3 10.4% 26.3%", + card: "337.5 100% 98.4%", + cardForeground: "334.3 10.4% 26.3%", + popover: "337.5 100% 98.4%", + popoverForeground: "334.3 10.4% 26.3%", + primary: "223.5 30.4% 60%", + primaryForeground: "0 0% 0%", + secondary: "335.3 37.8% 91.2%", + secondaryForeground: "334.3 10.4% 26.3%", + muted: "337.5 26.7% 88.2%", + mutedForeground: "333.8 6.3% 50.2%", + accent: "223.5 30.4% 60%", + accentForeground: "0 0% 0%", + destructive: "0 38.8% 54.5%", + destructiveForeground: "0 0% 0%", + border: "337.5 17.4% 82%", + input: "337.5 17.4% 82%", + ring: "223.5 30.4% 60%", + }, + }, + { + id: "zenbones-rosebones", + name: "Zenbones Rosebones", + tokens: { + background: "32.7 57.9% 96.3%", + foreground: "2.4 27.4% 35.1%", + card: "36 55.6% 98.2%", + cardForeground: "2.4 27.4% 35.1%", + popover: "36 55.6% 98.2%", + popoverForeground: "2.4 27.4% 35.1%", + primary: "34.4 83% 56.3%", + primaryForeground: "0 0% 0%", + secondary: "30 21.7% 91%", + secondaryForeground: "2.4 27.4% 35.1%", + muted: "30 16.7% 88.2%", + mutedForeground: "5 16.1% 56.1%", + accent: "34.4 83% 56.3%", + accentForeground: "0 0% 0%", + destructive: "343.2 35.7% 54.9%", + destructiveForeground: "0 0% 0%", + border: "33.3 9.7% 81.8%", + input: "33.3 9.7% 81.8%", + ring: "34.4 83% 56.3%", + }, + }, + { + id: "zhxo-red", + name: "Zhxo'red", + tokens: { + background: "24 100% 97.1%", + foreground: "240 10.1% 51.6%", + card: "25.7 100% 98.6%", + cardForeground: "240 10.1% 51.6%", + popover: "25.7 100% 98.6%", + popoverForeground: "240 10.1% 51.6%", + primary: "284.1 83.8% 45.9%", + primaryForeground: "0 0% 100%", + secondary: "21.4 33.3% 91.8%", + secondaryForeground: "240 10.1% 51.6%", + muted: "23.1 22.8% 88.8%", + mutedForeground: "252 8.8% 66.5%", + accent: "284.1 83.8% 45.9%", + accentForeground: "0 0% 100%", + destructive: "0 53.4% 50.4%", + destructiveForeground: "0 0% 100%", + border: "23.1 14.6% 82.5%", + input: "23.1 14.6% 82.5%", + ring: "284.1 83.8% 45.9%", + }, + } ]; export const LIGHT_UI_THEMES: UiThemePreset[] = [ ...CORE_LIGHT_UI_THEMES, - ...COPILOT_LIGHT_UI_THEMES, + ...EXTENDED_LIGHT_UI_THEMES, ]; -export const DARK_UI_THEMES: UiThemePreset[] = [ +export const EXTENDED_DARK_UI_THEMES: UiThemePreset[] = [ + { + id: "a-cup-of-coffee", + name: "A cup of coffee", + tokens: { + background: "0 0% 11.8%", + foreground: "0 0% 74.5%", + card: "0 0% 15.7%", + cardForeground: "0 0% 74.5%", + popover: "0 0% 15.7%", + popoverForeground: "0 0% 74.5%", + primary: "60 86.9% 48%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 19.2%", + secondaryForeground: "0 0% 74.5%", + muted: "0 0% 24.3%", + mutedForeground: "0 0% 56.9%", + accent: "60 86.9% 48%", + accentForeground: "0 0% 0%", + destructive: "0 61.4% 49.8%", + destructiveForeground: "0 0% 100%", + border: "0 0% 29.4%", + input: "0 0% 29.4%", + ring: "60 86.9% 48%", + }, + }, + { + id: "abolkog", + name: "ABOLKOG", + tokens: { + background: "220 13% 18%", + foreground: "218.8 27.9% 88%", + card: "223.6 9.9% 21.8%", + cardForeground: "218.8 27.9% 88%", + popover: "223.6 9.9% 21.8%", + popoverForeground: "218.8 27.9% 88%", + primary: "40 70.6% 73.3%", + primaryForeground: "0 0% 0%", + secondary: "218.2 8.7% 24.9%", + secondaryForeground: "218.8 27.9% 88%", + muted: "216 6.7% 29.4%", + mutedForeground: "220 9.3% 68.4%", + accent: "40 70.6% 73.3%", + accentForeground: "0 0% 0%", + destructive: "354.3 42.3% 56.5%", + destructiveForeground: "0 0% 0%", + border: "222 5.7% 34.5%", + input: "222 5.7% 34.5%", + ring: "40 70.6% 73.3%", + }, + }, + { + id: "aurora", + name: "Aurora", + tokens: { + background: "223.6 13.6% 15.9%", + foreground: "45.2 100% 57.8%", + card: "222 10% 19.6%", + cardForeground: "45.2 100% 57.8%", + popover: "222 10% 19.6%", + popoverForeground: "45.2 100% 57.8%", + primary: "171.5 97.2% 42.5%", + primaryForeground: "0 0% 0%", + secondary: "228 8.5% 23.1%", + secondaryForeground: "45.2 100% 57.8%", + muted: "226.7 6.4% 27.6%", + mutedForeground: "45.3 64.3% 46.1%", + accent: "171.5 97.2% 42.5%", + accentForeground: "0 0% 0%", + destructive: "338.3 87.1% 54.5%", + destructiveForeground: "0 0% 0%", + border: "226.7 5.4% 32.7%", + input: "226.7 5.4% 32.7%", + ring: "171.5 97.2% 42.5%", + }, + }, + { + id: "ayu", + name: "Ayu", + tokens: { + background: "222.4 21.5% 15.5%", + foreground: "48 8.9% 78%", + card: "221.3 16.3% 19.2%", + cardForeground: "48 8.9% 78%", + popover: "221.3 16.3% 19.2%", + popoverForeground: "48 8.9% 78%", + primary: "271.3 95.9% 80.8%", + primaryForeground: "0 0% 0%", + secondary: "221.3 13.8% 22.7%", + secondaryForeground: "48 8.9% 78%", + muted: "220 10.8% 27.3%", + mutedForeground: "60 1.5% 60.6%", + accent: "271.3 95.9% 80.8%", + accentForeground: "0 0% 0%", + destructive: "6.1 83.1% 65.1%", + destructiveForeground: "0 0% 0%", + border: "221.5 7.9% 32.4%", + input: "221.5 7.9% 32.4%", + ring: "271.3 95.9% 80.8%", + }, + }, + { + id: "base16-flat", + name: "Base16 Flat", + tokens: { + background: "210 29% 24.3%", + foreground: "0 0% 87.8%", + card: "209.1 24.8% 27.6%", + cardForeground: "0 0% 87.8%", + popover: "209.1 24.8% 27.6%", + popoverForeground: "0 0% 87.8%", + primary: "168.1 75.7% 42%", + primaryForeground: "0 0% 0%", + secondary: "210.9 21% 30.8%", + secondaryForeground: "0 0% 87.8%", + muted: "211 17.3% 35.1%", + mutedForeground: "210 6.6% 70.2%", + accent: "168.1 75.7% 42%", + accentForeground: "0 0% 0%", + destructive: "5.6 78.1% 57.1%", + destructiveForeground: "0 0% 0%", + border: "209 14.4% 39.4%", + input: "209 14.4% 39.4%", + ring: "168.1 75.7% 42%", + }, + }, + { + id: "base16-mocha", + name: "Base16 Mocha", + tokens: { + background: "31.6 19.2% 19.4%", + foreground: "12 9.6% 79.6%", + card: "30 15.3% 23.1%", + cardForeground: "12 9.6% 79.6%", + popover: "30 15.3% 23.1%", + popoverForeground: "12 9.6% 79.6%", + primary: "16.1 51.9% 63.3%", + primaryForeground: "0 0% 0%", + secondary: "30 13.4% 26.3%", + secondaryForeground: "12 9.6% 79.6%", + muted: "33.7 10.3% 30.6%", + mutedForeground: "20 6.3% 62.7%", + accent: "16.1 51.9% 63.3%", + accentForeground: "0 0% 0%", + destructive: "347.1 50.7% 58.6%", + destructiveForeground: "0 0% 0%", + border: "32 8.3% 35.5%", + input: "32 8.3% 35.5%", + ring: "16.1 51.9% 63.3%", + }, + }, + { + id: "blue-dolphin", + name: "Blue Dolphin", + tokens: { + background: "192.3 100% 25.9%", + foreground: "193.4 100% 88.6%", + card: "192.3 85.2% 29.2%", + cardForeground: "193.4 100% 88.6%", + popover: "192.3 85.2% 29.2%", + popoverForeground: "193.4 100% 88.6%", + primary: "218.8 100% 83.3%", + primaryForeground: "0 0% 0%", + secondary: "192 73.2% 32.2%", + secondaryForeground: "193.4 100% 88.6%", + muted: "192.2 61.1% 36.3%", + mutedForeground: "192.9 53.7% 71.2%", + accent: "218.8 100% 83.3%", + accentForeground: "0 0% 0%", + destructive: "357.1 100% 75.5%", + destructiveForeground: "0 0% 0%", + border: "192.5 51% 40.8%", + input: "192.5 51% 40.8%", + ring: "218.8 100% 83.3%", + }, + }, + { + id: "calm-days-sober-nights-sky", + name: "Calm Days, Sober Nights Sky", + tokens: { + background: "221.7 31.5% 14.3%", + foreground: "220 31.3% 86.9%", + card: "220.9 23.9% 18%", + cardForeground: "220 31.3% 86.9%", + popover: "220.9 23.9% 18%", + popoverForeground: "220 31.3% 86.9%", + primary: "198 93.3% 70.6%", + primaryForeground: "0 0% 0%", + secondary: "222.9 18.9% 21.8%", + secondaryForeground: "220 31.3% 86.9%", + muted: "222 14.9% 26.3%", + mutedForeground: "220 12.3% 66.5%", + accent: "198 93.3% 70.6%", + accentForeground: "0 0% 0%", + destructive: "354 77.1% 69.2%", + destructiveForeground: "0 0% 0%", + border: "220 11.2% 31.4%", + input: "220 11.2% 31.4%", + ring: "198 93.3% 70.6%", + }, + }, + { + id: "catppuccin", + name: "Catppuccin", + tokens: { + background: "229.1 18.6% 23.1%", + foreground: "227.2 70.1% 86.9%", + card: "228.6 15.6% 26.5%", + cardForeground: "227.2 70.1% 86.9%", + popover: "228.6 15.6% 26.5%", + popoverForeground: "227.2 70.1% 86.9%", + primary: "316 73.2% 83.9%", + primaryForeground: "0 0% 0%", + secondary: "231 13.2% 29.8%", + secondaryForeground: "227.2 70.1% 86.9%", + muted: "230.5 11% 33.9%", + mutedForeground: "228 25.3% 69%", + accent: "316 73.2% 83.9%", + accentForeground: "0 0% 0%", + destructive: "358.8 67.8% 70.8%", + destructiveForeground: "0 0% 0%", + border: "226.7 9.2% 38.4%", + input: "226.7 9.2% 38.4%", + ring: "316 73.2% 83.9%", + }, + }, + { + id: "chai", + name: "Chai", + tokens: { + background: "240 75% 1.6%", + foreground: "203.6 27.5% 80%", + card: "240 20% 5.9%", + cardForeground: "203.6 27.5% 80%", + popover: "240 20% 5.9%", + popoverForeground: "203.6 27.5% 80%", + primary: "202.9 78.4% 60%", + primaryForeground: "0 0% 0%", + secondary: "240 9.8% 10%", + secondaryForeground: "203.6 27.5% 80%", + muted: "240 6.3% 15.5%", + mutedForeground: "207.3 10.3% 58%", + accent: "202.9 78.4% 60%", + accentForeground: "0 0% 0%", + destructive: "16.8 78.2% 55.1%", + destructiveForeground: "0 0% 0%", + border: "240 4.6% 21.4%", + input: "240 4.6% 21.4%", + ring: "202.9 78.4% 60%", + }, + }, + { + id: "chinolor", + name: "Chinolor", + tokens: { + background: "130 6.5% 18%", + foreground: "36.9 19.4% 86.9%", + card: "120 4.5% 21.8%", + cardForeground: "36.9 19.4% 86.9%", + popover: "120 4.5% 21.8%", + popoverForeground: "36.9 19.4% 86.9%", + primary: "44.4 92.4% 69%", + primaryForeground: "0 0% 0%", + secondary: "130 4.7% 25.1%", + secondaryForeground: "36.9 19.4% 86.9%", + muted: "132 3.3% 29.6%", + mutedForeground: "46.7 5.4% 67.3%", + accent: "44.4 92.4% 69%", + accentForeground: "0 0% 0%", + destructive: "355.2 83.7% 59%", + destructiveForeground: "0 0% 0%", + border: "132 2.9% 34.3%", + input: "132 2.9% 34.3%", + ring: "44.4 92.4% 69%", + }, + }, + { + id: "cyberdyne", + name: "Cyberdyne", + tokens: { + background: "244.7 60% 16.7%", + foreground: "154.4 100% 50%", + card: "245 46.2% 20.4%", + cardForeground: "154.4 100% 50%", + popover: "245 46.2% 20.4%", + popoverForeground: "154.4 100% 50%", + primary: "300.5 100% 78.2%", + primaryForeground: "0 0% 0%", + secondary: "245.1 38.8% 23.7%", + secondaryForeground: "154.4 100% 50%", + muted: "245.5 30.6% 28.2%", + mutedForeground: "158.9 93.8% 38%", + accent: "300.5 100% 78.2%", + accentForeground: "0 0% 0%", + destructive: "6.9 100% 72.5%", + destructiveForeground: "0 0% 0%", + border: "244.5 23.5% 33.3%", + input: "244.5 23.5% 33.3%", + ring: "300.5 100% 78.2%", + }, + }, + { + id: "desert", + name: "Desert", + tokens: { + background: "0 0% 20%", + foreground: "0 0% 100%", + card: "0 0% 23.5%", + cardForeground: "0 0% 100%", + popover: "0 0% 23.5%", + popoverForeground: "0 0% 100%", + primary: "35.9 100% 83.9%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 26.7%", + secondaryForeground: "0 0% 100%", + muted: "0 0% 31.4%", + mutedForeground: "0 0% 77.6%", + accent: "35.9 100% 83.9%", + accentForeground: "0 0% 0%", + destructive: "0 100% 58.4%", + destructiveForeground: "0 0% 0%", + border: "0 0% 36.1%", + input: "0 0% 36.1%", + ring: "35.9 100% 83.9%", + }, + }, + { + id: "django-reborn-again", + name: "Django Reborn Again", + tokens: { + background: "154.6 72.2% 7.1%", + foreground: "150 5.7% 86.3%", + card: "156 43.9% 11.2%", + cardForeground: "150 5.7% 86.3%", + popover: "156 43.9% 11.2%", + popoverForeground: "150 5.7% 86.3%", + primary: "51.2 100% 69.2%", + primaryForeground: "0 0% 0%", + secondary: "155 31.6% 14.9%", + secondaryForeground: "150 5.7% 86.3%", + muted: "155.5 21.6% 20%", + mutedForeground: "152.7 6% 64.1%", + accent: "51.2 100% 69.2%", + accentForeground: "0 0% 0%", + destructive: "21.9 98.4% 51.4%", + destructiveForeground: "0 0% 0%", + border: "154.3 16% 25.7%", + input: "154.3 16% 25.7%", + ring: "51.2 100% 69.2%", + }, + }, + { + id: "espresso", + name: "Espresso", + tokens: { + background: "18 20% 9.8%", + foreground: "33.3 29.5% 76.1%", + card: "13.3 12.7% 13.9%", + cardForeground: "33.3 29.5% 76.1%", + popover: "13.3 12.7% 13.9%", + popoverForeground: "33.3 29.5% 76.1%", + primary: "42.9 70.9% 69%", + primaryForeground: "0 0% 0%", + secondary: "20 10.1% 17.5%", + secondaryForeground: "33.3 29.5% 76.1%", + muted: "13.3 7.8% 22.5%", + mutedForeground: "33.1 13.4% 57.5%", + accent: "42.9 70.9% 69%", + accentForeground: "0 0% 0%", + destructive: "8.6 70.9% 69%", + destructiveForeground: "0 0% 0%", + border: "15 5.6% 27.8%", + input: "15 5.6% 27.8%", + ring: "42.9 70.9% 69%", + }, + }, + { + id: "eyehealth", + name: "EyeHealth", + tokens: { + background: "0 0% 25.9%", + foreground: "0 0% 100%", + card: "0 0% 29.4%", + cardForeground: "0 0% 100%", + popover: "0 0% 29.4%", + popoverForeground: "0 0% 100%", + primary: "35.8 100% 50%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 32.2%", + secondaryForeground: "0 0% 100%", + muted: "0 0% 36.1%", + mutedForeground: "0 0% 79.2%", + accent: "35.8 100% 50%", + accentForeground: "0 0% 0%", + destructive: "354 67% 56.1%", + destructiveForeground: "0 0% 0%", + border: "0 0% 40.8%", + input: "0 0% 40.8%", + ring: "35.8 100% 50%", + }, + }, + { + id: "flexoki", + name: "Flexoki", + tokens: { + background: "0 3.2% 6.1%", + foreground: "54.5 10.1% 78.6%", + card: "0 1.9% 10.4%", + cardForeground: "54.5 10.1% 78.6%", + popover: "0 1.9% 10.4%", + popoverForeground: "54.5 10.1% 78.6%", + primary: "45.2 81.7% 44.9%", + primaryForeground: "0 0% 0%", + secondary: "0 1.4% 13.9%", + secondaryForeground: "54.5 10.1% 78.6%", + muted: "0 0% 19.2%", + mutedForeground: "52.5 3.8% 58.4%", + accent: "45.2 81.7% 44.9%", + accentForeground: "0 0% 0%", + destructive: "5 61% 53.7%", + destructiveForeground: "0 0% 0%", + border: "0 0.8% 24.9%", + input: "0 0.8% 24.9%", + ring: "45.2 81.7% 44.9%", + }, + }, + { + id: "fox", + name: "Fox", + tokens: { + background: "213.9 31.5% 14.3%", + foreground: "210 2% 80.8%", + card: "212.7 23.9% 18%", + cardForeground: "210 2% 80.8%", + popover: "212.7 23.9% 18%", + popoverForeground: "210 2% 80.8%", + primary: "181.1 52.9% 60%", + primaryForeground: "0 0% 0%", + secondary: "214.3 18.9% 21.8%", + secondaryForeground: "210 2% 80.8%", + muted: "213 14.9% 26.3%", + mutedForeground: "214.3 3.6% 62.2%", + accent: "181.1 52.9% 60%", + accentForeground: "0 0% 0%", + destructive: "345.2 53% 54.9%", + destructiveForeground: "0 0% 0%", + border: "213.3 11.2% 31.4%", + input: "213.3 11.2% 31.4%", + ring: "181.1 52.9% 60%", + }, + }, + { + id: "garbage-oracle", + name: "Garbage Oracle", + tokens: { + background: "311.5 31% 16.5%", + foreground: "303.8 38.1% 91.8%", + card: "312 24.3% 20.2%", + cardForeground: "303.8 38.1% 91.8%", + popover: "312 24.3% 20.2%", + popoverForeground: "303.8 38.1% 91.8%", + primary: "124.3 95.4% 82.9%", + primaryForeground: "0 0% 0%", + secondary: "312.5 20% 23.5%", + secondaryForeground: "303.8 38.1% 91.8%", + muted: "310.9 15.3% 28.2%", + mutedForeground: "306.3 12.8% 70.8%", + accent: "124.3 95.4% 82.9%", + accentForeground: "0 0% 0%", + destructive: "359.4 92.8% 78.2%", + destructiveForeground: "0 0% 0%", + border: "311.4 12.4% 33.1%", + input: "311.4 12.4% 33.1%", + ring: "124.3 95.4% 82.9%", + }, + }, + { + id: "github", + name: "GitHub", + tokens: { + background: "216 27.8% 7.1%", + foreground: "207.7 35.1% 92.7%", + card: "213.3 15.8% 11.2%", + cardForeground: "207.7 35.1% 92.7%", + popover: "213.3 15.8% 11.2%", + popoverForeground: "207.7 35.1% 92.7%", + primary: "212 100% 67.3%", + primaryForeground: "0 0% 0%", + secondary: "220 11.7% 15.1%", + secondaryForeground: "207.7 35.1% 92.7%", + muted: "217.5 7.8% 20%", + mutedForeground: "210 7.5% 68.6%", + accent: "212 100% 67.3%", + accentForeground: "0 0% 0%", + destructive: "3.8 100% 72.4%", + destructiveForeground: "0 0% 0%", + border: "210 6.2% 25.5%", + input: "210 6.2% 25.5%", + ring: "212 100% 67.3%", + }, + }, + { + id: "gruvbox-material", + name: "Gruvbox Material", + tokens: { + background: "0 1.2% 15.9%", + foreground: "38 41.1% 71.4%", + card: "0 1% 19.8%", + cardForeground: "38 41.1% 71.4%", + popover: "0 1% 19.8%", + popoverForeground: "38 41.1% 71.4%", + primary: "3.1 76.4% 65.1%", + primaryForeground: "0 0% 0%", + secondary: "0 0.9% 22.9%", + secondaryForeground: "38 41.1% 71.4%", + muted: "0 0.7% 27.6%", + mutedForeground: "37.7 19.1% 55.9%", + accent: "3.1 76.4% 65.1%", + accentForeground: "0 0% 0%", + destructive: "3.1 76.4% 65.1%", + destructiveForeground: "0 0% 0%", + border: "0 0.6% 32.7%", + input: "0 0.6% 32.7%", + ring: "3.1 76.4% 65.1%", + }, + }, + { + id: "homebrew", + name: "Homebrew", + tokens: { + background: "0 0% 0%", + foreground: "120 100% 50%", + card: "0 0% 4.3%", + cardForeground: "120 100% 50%", + popover: "0 0% 4.3%", + popoverForeground: "120 100% 50%", + primary: "184 100% 34.9%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 8.6%", + secondaryForeground: "120 100% 50%", + muted: "0 0% 14.1%", + mutedForeground: "120 100% 36.1%", + accent: "184 100% 34.9%", + accentForeground: "0 0% 0%", + destructive: "0 100% 30%", + destructiveForeground: "0 0% 100%", + border: "0 0% 20%", + input: "0 0% 20%", + ring: "184 100% 34.9%", + }, + }, + { + id: "ic-orange-ppl", + name: "IC Orange PPL", + tokens: { + background: "0 0% 14.9%", + foreground: "34.8 100% 75.7%", + card: "0 0% 18.8%", + cardForeground: "34.8 100% 75.7%", + popover: "0 0% 18.8%", + popoverForeground: "34.8 100% 75.7%", + primary: "36.2 100% 48.4%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 22%", + secondaryForeground: "34.8 100% 75.7%", + muted: "0 0% 26.7%", + mutedForeground: "35.1 42.2% 58.6%", + accent: "36.2 100% 48.4%", + accentForeground: "0 0% 0%", + destructive: "17.7 100% 37.8%", + destructiveForeground: "0 0% 100%", + border: "0 0% 31.8%", + input: "0 0% 31.8%", + ring: "36.2 100% 48.4%", + }, + }, + { + id: "ikki", + name: "IKKI", + tokens: { + background: "0 0% 32.5%", + foreground: "0 0% 83.9%", + card: "0 0% 35.7%", + cardForeground: "0 0% 83.9%", + popover: "0 0% 35.7%", + popoverForeground: "0 0% 83.9%", + primary: "35.8 100% 50%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 38.4%", + secondaryForeground: "0 0% 83.9%", + muted: "0 0% 42%", + mutedForeground: "0 0% 69.4%", + accent: "35.8 100% 50%", + accentForeground: "0 0% 0%", + destructive: "354 67% 56.1%", + destructiveForeground: "0 0% 0%", + border: "0 0% 45.9%", + input: "0 0% 45.9%", + ring: "35.8 100% 50%", + }, + }, + { + id: "kanso-ink", + name: "Kanso Ink", + tokens: { + background: "220 18.4% 9.6%", + foreground: "150 3.6% 78%", + card: "225 11.4% 13.7%", + cardForeground: "150 3.6% 78%", + popover: "225 11.4% 13.7%", + popoverForeground: "150 3.6% 78%", + primary: "41.4 33% 65.5%", + primaryForeground: "0 0% 0%", + secondary: "217.5 9.1% 17.3%", + secondaryForeground: "150 3.6% 78%", + muted: "225 7% 22.4%", + mutedForeground: "180 1.9% 58.4%", + accent: "41.4 33% 65.5%", + accentForeground: "0 0% 0%", + destructive: "4.2 42.2% 60%", + destructiveForeground: "0 0% 0%", + border: "222.9 5% 27.6%", + input: "222.9 5% 27.6%", + ring: "41.4 33% 65.5%", + }, + }, + { + id: "kary-pro-colors", + name: "Kary Pro Colors", + tokens: { + background: "0 0% 10.2%", + foreground: "0 0% 80%", + card: "0 0% 14.1%", + cardForeground: "0 0% 80%", + popover: "0 0% 14.1%", + popoverForeground: "0 0% 80%", + primary: "15.8 54.6% 62%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 17.6%", + secondaryForeground: "0 0% 80%", + muted: "0 0% 22.7%", + mutedForeground: "0 0% 60.4%", + accent: "15.8 54.6% 62%", + accentForeground: "0 0% 0%", + destructive: "15.8 54.6% 62%", + destructiveForeground: "0 0% 0%", + border: "0 0% 28.2%", + input: "0 0% 28.2%", + ring: "15.8 54.6% 62%", + }, + }, + { + id: "light-purple", + name: "Light purple", + tokens: { + background: "293.3 18% 19.6%", + foreground: "0 100% 94.5%", + card: "292.9 14.3% 23.3%", + cardForeground: "0 100% 94.5%", + popover: "292.9 14.3% 23.3%", + popoverForeground: "0 100% 94.5%", + primary: "191.2 74.1% 77.3%", + primaryForeground: "0 0% 0%", + secondary: "292.9 12.6% 26.5%", + secondaryForeground: "0 100% 94.5%", + muted: "296 9.6% 30.8%", + mutedForeground: "348 18.5% 73.5%", + accent: "191.2 74.1% 77.3%", + accentForeground: "0 0% 0%", + destructive: "348 69.3% 60.4%", + destructiveForeground: "0 0% 0%", + border: "295.7 7.7% 35.7%", + input: "295.7 7.7% 35.7%", + ring: "191.2 74.1% 77.3%", + }, + }, + { + id: "mondrian", + name: "Mondrian", + tokens: { + background: "240 27.8% 14.1%", + foreground: "0 0% 100%", + card: "240 20.9% 17.8%", + cardForeground: "0 0% 100%", + popover: "240 20.9% 17.8%", + popoverForeground: "0 0% 100%", + primary: "186.5 100% 37.8%", + primaryForeground: "0 0% 0%", + secondary: "240 17.4% 21.4%", + secondaryForeground: "0 0% 100%", + muted: "240 12.8% 26.1%", + mutedForeground: "240 4.1% 75.9%", + accent: "186.5 100% 37.8%", + accentForeground: "0 0% 0%", + destructive: "4.6 81.2% 56.3%", + destructiveForeground: "0 0% 0%", + border: "240 10% 31.4%", + input: "240 10% 31.4%", + ring: "186.5 100% 37.8%", + }, + }, + { + id: "monochrome", + name: "Monochrome", + tokens: { + background: "222.2 47.4% 11.2%", + foreground: "210 40% 96.1%", + card: "223.8 33.3% 15.3%", + cardForeground: "210 40% 96.1%", + popover: "223.8 33.3% 15.3%", + popoverForeground: "210 40% 96.1%", + primary: "210 40% 96.1%", + primaryForeground: "0 0% 0%", + secondary: "220.8 26.3% 18.6%", + secondaryForeground: "210 40% 96.1%", + muted: "224.3 19% 23.7%", + mutedForeground: "216.9 9.2% 72.4%", + accent: "210 40% 96.1%", + accentForeground: "0 0% 0%", + destructive: "210 40% 96.1%", + destructiveForeground: "0 0% 0%", + border: "223.6 14.9% 29%", + input: "223.6 14.9% 29%", + ring: "210 40% 96.1%", + }, + }, + { + id: "monochrome-stone", + name: "Monochrome Stone", + tokens: { + background: "24 9.8% 10%", + foreground: "60 4.8% 95.9%", + card: "24 7% 13.9%", + cardForeground: "60 4.8% 95.9%", + popover: "24 7% 13.9%", + popoverForeground: "60 4.8% 95.9%", + primary: "60 4.8% 95.9%", + primaryForeground: "0 0% 0%", + secondary: "30 4.4% 17.6%", + secondaryForeground: "60 4.8% 95.9%", + muted: "24 4.3% 22.5%", + mutedForeground: "30 1.4% 71.8%", + accent: "60 4.8% 95.9%", + accentForeground: "0 0% 0%", + destructive: "60 4.8% 95.9%", + destructiveForeground: "0 0% 0%", + border: "30 2.8% 27.8%", + input: "30 2.8% 27.8%", + ring: "60 4.8% 95.9%", + }, + }, + { + id: "monokai-pro-spectrum", + name: "Monokai Pro Spectrum", + tokens: { + background: "0 0% 13.3%", + foreground: "265.7 100% 97.3%", + card: "0 0% 17.3%", + cardForeground: "265.7 100% 97.3%", + popover: "0 0% 17.3%", + popoverForeground: "265.7 100% 97.3%", + primary: "22.6 97.7% 65.9%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 20.8%", + secondaryForeground: "265.7 100% 97.3%", + muted: "0 0% 25.5%", + mutedForeground: "264 7.5% 73.7%", + accent: "22.6 97.7% 65.9%", + accentForeground: "0 0% 0%", + destructive: "343 96.3% 68.4%", + destructiveForeground: "0 0% 0%", + border: "0 0% 30.6%", + input: "0 0% 30.6%", + ring: "22.6 97.7% 65.9%", + }, + }, + { + id: "monospace", + name: "Monospace", + tokens: { + background: "216 30.3% 12.9%", + foreground: "214.3 22.6% 87.8%", + card: "216 23.3% 16.9%", + cardForeground: "214.3 22.6% 87.8%", + popover: "216 23.3% 16.9%", + popoverForeground: "214.3 22.6% 87.8%", + primary: "227 100% 72%", + primaryForeground: "0 0% 0%", + secondary: "216.7 17.3% 20.4%", + secondaryForeground: "214.3 22.6% 87.8%", + muted: "216.7 14.1% 25.1%", + mutedForeground: "216 8.9% 66.9%", + accent: "227 100% 72%", + accentForeground: "0 0% 0%", + destructive: "359.2 90% 68.6%", + destructiveForeground: "0 0% 0%", + border: "213.8 10.4% 30.2%", + input: "213.8 10.4% 30.2%", + ring: "227 100% 72%", + }, + }, + { + id: "noctis-azureus", + name: "Noctis Azureus", + tokens: { + background: "203.1 78.8% 12.9%", + foreground: "203.6 27.5% 80%", + card: "202.8 58.1% 16.9%", + cardForeground: "203.6 27.5% 80%", + popover: "202.8 58.1% 16.9%", + popoverForeground: "203.6 27.5% 80%", + primary: "187.1 78.4% 60%", + primaryForeground: "0 0% 0%", + secondary: "203.7 46.2% 20.4%", + secondaryForeground: "203.6 27.5% 80%", + muted: "203.2 34.4% 25.1%", + mutedForeground: "202.9 17.2% 61.2%", + accent: "187.1 78.4% 60%", + accentForeground: "0 0% 0%", + destructive: "16.8 78.2% 55.1%", + destructiveForeground: "0 0% 0%", + border: "203.4 26.5% 30.4%", + input: "203.4 26.5% 30.4%", + ring: "187.1 78.4% 60%", + }, + }, + { + id: "noctis-hibernus", + name: "Noctis Hibernus", + tokens: { + background: "246.9 25.5% 20%", + foreground: "249 19.6% 80%", + card: "247.2 20.7% 23.7%", + cardForeground: "249 19.6% 80%", + popover: "247.2 20.7% 23.7%", + popoverForeground: "249 19.6% 80%", + primary: "187.1 78.4% 60%", + primaryForeground: "0 0% 0%", + secondary: "247.5 17.6% 26.7%", + secondaryForeground: "249 19.6% 80%", + muted: "247.8 14.5% 31.2%", + mutedForeground: "248.2 11.7% 63.1%", + accent: "187.1 78.4% 60%", + accentForeground: "0 0% 0%", + destructive: "16.8 78.2% 55.1%", + destructiveForeground: "0 0% 0%", + border: "248.6 11.5% 35.9%", + input: "248.6 11.5% 35.9%", + ring: "187.1 78.4% 60%", + }, + }, + { + id: "noir-essence", + name: "Noir Essence", + tokens: { + background: "200 8.1% 7.3%", + foreground: "41.5 44.8% 94.3%", + card: "200 5.1% 11.6%", + cardForeground: "41.5 44.8% 94.3%", + popover: "200 5.1% 11.6%", + popoverForeground: "41.5 44.8% 94.3%", + primary: "23.5 76.1% 60.6%", + primaryForeground: "0 0% 0%", + secondary: "200 3.9% 15.1%", + secondaryForeground: "41.5 44.8% 94.3%", + muted: "200 2.9% 20.2%", + mutedForeground: "40 5.9% 70%", + accent: "23.5 76.1% 60.6%", + accentForeground: "0 0% 0%", + destructive: "3.1 76.4% 65.1%", + destructiveForeground: "0 0% 0%", + border: "210 1.5% 25.9%", + input: "210 1.5% 25.9%", + ring: "23.5 76.1% 60.6%", + }, + }, + { + id: "nord-midnight", + name: "Nord Midnight", + tokens: { + background: "220 14.8% 12%", + foreground: "218.8 27.9% 88%", + card: "220 11.1% 15.9%", + cardForeground: "218.8 27.9% 88%", + popover: "220 11.1% 15.9%", + popoverForeground: "218.8 27.9% 88%", + primary: "40 70.6% 73.3%", + primaryForeground: "0 0% 0%", + secondary: "220 9.1% 19.4%", + secondaryForeground: "218.8 27.9% 88%", + muted: "217.5 6.5% 24.3%", + mutedForeground: "220 8.9% 66.9%", + accent: "40 70.6% 73.3%", + accentForeground: "0 0% 0%", + destructive: "354.3 42.3% 56.5%", + destructiveForeground: "0 0% 0%", + border: "222.9 4.6% 29.6%", + input: "222.9 4.6% 29.6%", + ring: "40 70.6% 73.3%", + }, + }, + { + id: "notionish", + name: "Notionish", + tokens: { + background: "60 2% 9.6%", + foreground: "30 10% 96.1%", + card: "60 1.4% 13.5%", + cardForeground: "30 10% 96.1%", + popover: "60 1.4% 13.5%", + popoverForeground: "30 10% 96.1%", + primary: "39.9 100% 68.4%", + primaryForeground: "0 0% 0%", + secondary: "60 1.1% 17.5%", + secondaryForeground: "30 10% 96.1%", + muted: "60 0.9% 22.2%", + mutedForeground: "30 1.4% 71.8%", + accent: "39.9 100% 68.4%", + accentForeground: "0 0% 0%", + destructive: "6.9 90.2% 67.8%", + destructiveForeground: "0 0% 0%", + border: "60 0.7% 27.6%", + input: "60 0.7% 27.6%", + ring: "39.9 100% 68.4%", + }, + }, + { + id: "phonebook", + name: "Phonebook", + tokens: { + background: "27.3 14.3% 15.1%", + foreground: "43 71.4% 67.1%", + card: "30 10.4% 18.8%", + cardForeground: "43 71.4% 67.1%", + popover: "30 10.4% 18.8%", + popoverForeground: "43 71.4% 67.1%", + primary: "186.5 100% 37.8%", + primaryForeground: "0 0% 0%", + secondary: "24 8.8% 22.4%", + secondaryForeground: "43 71.4% 67.1%", + muted: "24 7.2% 27.1%", + mutedForeground: "42 37.2% 52.5%", + accent: "186.5 100% 37.8%", + accentForeground: "0 0% 0%", + destructive: "4 89.9% 61%", + destructiveForeground: "0 0% 0%", + border: "26.7 5.5% 32%", + input: "26.7 5.5% 32%", + ring: "186.5 100% 37.8%", + }, + }, + { + id: "polychrome", + name: "Polychrome", + tokens: { + background: "250.9 12.1% 17.8%", + foreground: "251.7 31.6% 77.6%", + card: "252 9.1% 21.6%", + cardForeground: "251.7 31.6% 77.6%", + popover: "252 9.1% 21.6%", + popoverForeground: "251.7 31.6% 77.6%", + primary: "47.7 100% 76.1%", + primaryForeground: "0 0% 0%", + secondary: "252 7.9% 24.7%", + secondaryForeground: "251.7 31.6% 77.6%", + muted: "252 6.7% 29.4%", + mutedForeground: "250.3 14.6% 61%", + accent: "47.7 100% 76.1%", + accentForeground: "0 0% 0%", + destructive: "9.1 100% 63.9%", + destructiveForeground: "0 0% 0%", + border: "253.3 5.1% 34.3%", + input: "253.3 5.1% 34.3%", + ring: "47.7 100% 76.1%", + }, + }, + { + id: "purplepeter", + name: "Purplepeter", + tokens: { + background: "260 48% 19.6%", + foreground: "255.8 65.5% 94.3%", + card: "260.9 39% 23.1%", + cardForeground: "255.8 65.5% 94.3%", + popover: "260.9 39% 23.1%", + popoverForeground: "255.8 65.5% 94.3%", + primary: "264 100% 77.5%", + primaryForeground: "0 0% 0%", + secondary: "260.5 32.8% 26.3%", + secondaryForeground: "255.8 65.5% 94.3%", + muted: "260.5 26.1% 30.8%", + mutedForeground: "257.8 20% 73.5%", + accent: "264 100% 77.5%", + accentForeground: "0 0% 0%", + destructive: "4.9 100% 71.4%", + destructiveForeground: "0 0% 0%", + border: "260.5 20.9% 35.7%", + input: "260.5 20.9% 35.7%", + ring: "264 100% 77.5%", + }, + }, + { + id: "rainglow-codecourse", + name: "Rainglow Codecourse", + tokens: { + background: "204 33.3% 2.9%", + foreground: "197.6 30.4% 78%", + card: "204 13.5% 7.3%", + cardForeground: "197.6 30.4% 78%", + popover: "204 13.5% 7.3%", + popoverForeground: "197.6 30.4% 78%", + primary: "202.7 97.4% 55.3%", + primaryForeground: "0 0% 0%", + secondary: "204 8.8% 11.2%", + secondaryForeground: "197.6 30.4% 78%", + muted: "195 4.8% 16.5%", + mutedForeground: "196.2 11.8% 56.9%", + accent: "202.7 97.4% 55.3%", + accentForeground: "0 0% 0%", + destructive: "348.8 86% 39.2%", + destructiveForeground: "0 0% 100%", + border: "210 3.5% 22.4%", + input: "210 3.5% 22.4%", + ring: "202.7 97.4% 55.3%", + }, + }, + { + id: "rainglow-crisp", + name: "Rainglow Crisp", + tokens: { + background: "300 14.3% 4.1%", + foreground: "0 0% 100%", + card: "300 7% 8.4%", + cardForeground: "0 0% 100%", + popover: "300 7% 8.4%", + popoverForeground: "0 0% 100%", + primary: "23 97.5% 52.4%", + primaryForeground: "0 0% 0%", + secondary: "300 4.8% 12.4%", + secondaryForeground: "0 0% 100%", + muted: "300 3.4% 17.5%", + mutedForeground: "300 0.7% 73.1%", + accent: "23 97.5% 52.4%", + accentForeground: "0 0% 0%", + destructive: "348.8 86% 39.2%", + destructiveForeground: "0 0% 100%", + border: "300 2.5% 23.3%", + input: "300 2.5% 23.3%", + ring: "23 97.5% 52.4%", + }, + }, + { + id: "rainglow-lavender", + name: "Rainglow Lavender", + tokens: { + background: "270 12.5% 3.1%", + foreground: "274.8 46.3% 86.9%", + card: "270 5.3% 7.5%", + cardForeground: "274.8 46.3% 86.9%", + popover: "270 5.3% 7.5%", + popoverForeground: "274.8 46.3% 86.9%", + primary: "273.9 100% 67.1%", + primaryForeground: "0 0% 0%", + secondary: "270 3.4% 11.4%", + secondaryForeground: "274.8 46.3% 86.9%", + muted: "300 1.2% 16.7%", + mutedForeground: "276.5 12.3% 63.3%", + accent: "273.9 100% 67.1%", + accentForeground: "0 0% 0%", + destructive: "348.8 86% 39.2%", + destructiveForeground: "0 0% 100%", + border: "240 0.9% 22.5%", + input: "240 0.9% 22.5%", + ring: "273.9 100% 67.1%", + }, + }, + { + id: "remedy-tilted", + name: "Remedy Tilted", + tokens: { + background: "5 10.5% 22.4%", + foreground: "39.4 80.7% 83.7%", + card: "5 9.1% 25.9%", + cardForeground: "39.4 80.7% 83.7%", + popover: "5 9.1% 25.9%", + popoverForeground: "39.4 80.7% 83.7%", + primary: "24.6 65.8% 62.2%", + primaryForeground: "0 0% 0%", + secondary: "5.5 7.5% 28.8%", + secondaryForeground: "39.4 80.7% 83.7%", + muted: "0 5.9% 33.3%", + mutedForeground: "37.6 29.8% 66.5%", + accent: "24.6 65.8% 62.2%", + accentForeground: "0 0% 0%", + destructive: "0 42.9% 45.3%", + destructiveForeground: "0 0% 100%", + border: "6.7 4.7% 37.8%", + input: "6.7 4.7% 37.8%", + ring: "24.6 65.8% 62.2%", + }, + }, + { + id: "rose-pine", + name: "Rosé Pine", + tokens: { + background: "249.2 22% 11.6%", + foreground: "245.5 50% 91.4%", + card: "249.2 16.5% 15.5%", + cardForeground: "245.5 50% 91.4%", + popover: "249.2 16.5% 15.5%", + popoverForeground: "245.5 50% 91.4%", + primary: "35 87.6% 71.6%", + primaryForeground: "0 0% 0%", + secondary: "250 12.2% 19.2%", + secondaryForeground: "245.5 50% 91.4%", + muted: "250 9.8% 23.9%", + mutedForeground: "246 12.7% 69%", + accent: "35 87.6% 71.6%", + accentForeground: "0 0% 0%", + destructive: "343.1 75.6% 67.8%", + destructiveForeground: "0 0% 0%", + border: "250.9 7.4% 29.2%", + input: "250.9 7.4% 29.2%", + ring: "35 87.6% 71.6%", + }, + }, + { + id: "selene-selenized", + name: "Selene Selenized", + tokens: { + background: "189.9 87% 15.1%", + foreground: "183.8 17% 81.6%", + card: "189.4 66.7% 18.8%", + cardForeground: "183.8 17% 81.6%", + popover: "189.4 66.7% 18.8%", + popoverForeground: "183.8 17% 81.6%", + primary: "203.3 100% 48%", + primaryForeground: "0 0% 0%", + secondary: "190.6 54.4% 22.4%", + secondaryForeground: "183.8 17% 81.6%", + muted: "190.3 42% 27.1%", + mutedForeground: "187.7 16.4% 62.9%", + accent: "203.3 100% 48%", + accentForeground: "0 0% 0%", + destructive: "2.7 97.8% 64.9%", + destructiveForeground: "0 0% 0%", + border: "190 32.9% 32.2%", + input: "190 32.9% 32.2%", + ring: "203.3 100% 48%", + }, + }, + { + id: "soft-color", + name: "Soft Color", + tokens: { + background: "0 0% 14.5%", + foreground: "151.2 100% 95.1%", + card: "0 0% 18.4%", + cardForeground: "151.2 100% 95.1%", + popover: "0 0% 18.4%", + popoverForeground: "151.2 100% 95.1%", + primary: "60 86.9% 48%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 22%", + secondaryForeground: "151.2 100% 95.1%", + muted: "0 0% 26.7%", + mutedForeground: "150 12.9% 72.5%", + accent: "60 86.9% 48%", + accentForeground: "0 0% 0%", + destructive: "0 61.4% 49.8%", + destructiveForeground: "0 0% 100%", + border: "0 0% 31.8%", + input: "0 0% 31.8%", + ring: "60 86.9% 48%", + }, + }, + { + id: "tearout", + name: "Tearout", + tokens: { + background: "85 11.8% 20%", + foreground: "30.9 76.1% 82%", + card: "85 10% 23.5%", + cardForeground: "30.9 76.1% 82%", + popover: "85 10% 23.5%", + popoverForeground: "30.9 76.1% 82%", + primary: "46.4 51.2% 67.8%", + primaryForeground: "0 0% 0%", + secondary: "87.3 8% 26.9%", + secondaryForeground: "30.9 76.1% 82%", + muted: "87.3 6.9% 31.2%", + mutedForeground: "33.5 28.6% 64.3%", + accent: "46.4 51.2% 67.8%", + accentForeground: "0 0% 0%", + destructive: "20 44.3% 64.1%", + destructiveForeground: "0 0% 0%", + border: "84 5.4% 36.1%", + input: "84 5.4% 36.1%", + ring: "46.4 51.2% 67.8%", + }, + }, + { + id: "tokyo-night", + name: "Tokyo Night", + tokens: { + background: "235 18.8% 12.5%", + foreground: "228.7 72.6% 85.7%", + card: "235 14.3% 16.5%", + cardForeground: "228.7 72.6% 85.7%", + popover: "235 14.3% 16.5%", + popoverForeground: "228.7 72.6% 85.7%", + primary: "202.2 100% 74.5%", + primaryForeground: "0 0% 0%", + secondary: "234.5 10.9% 19.8%", + secondaryForeground: "228.7 72.6% 85.7%", + muted: "234 7.9% 24.7%", + mutedForeground: "229.8 23.2% 65.3%", + accent: "202.2 100% 74.5%", + accentForeground: "0 0% 0%", + destructive: "348.8 89% 71.6%", + destructiveForeground: "0 0% 0%", + border: "233.3 5.9% 30%", + input: "233.3 5.9% 30%", + ring: "202.2 100% 74.5%", + }, + }, + { + id: "tomorrow-night-eighties", + name: "Tomorrow Night Eighties", + tokens: { + background: "0 0% 17.6%", + foreground: "0 0% 80%", + card: "0 0% 21.2%", + cardForeground: "0 0% 80%", + popover: "0 0% 21.2%", + popoverForeground: "0 0% 80%", + primary: "40 100% 70%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 24.7%", + secondaryForeground: "0 0% 80%", + muted: "0 0% 29%", + mutedForeground: "0 0% 62.4%", + accent: "40 100% 70%", + accentForeground: "0 0% 0%", + destructive: "358.5 82.6% 70.8%", + destructiveForeground: "0 0% 0%", + border: "0 0% 34.1%", + input: "0 0% 34.1%", + ring: "40 100% 70%", + }, + }, + { + id: "vaporizer-turquoise", + name: "Vaporizer Turquoise", + tokens: { + background: "0 0% 9.8%", + foreground: "110.8 31.7% 67.8%", + card: "0 0% 13.7%", + cardForeground: "110.8 31.7% 67.8%", + popover: "0 0% 13.7%", + popoverForeground: "110.8 31.7% 67.8%", + primary: "151.9 100% 36.9%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 17.6%", + secondaryForeground: "110.8 31.7% 67.8%", + muted: "0 0% 22.4%", + mutedForeground: "110.3 15% 51.6%", + accent: "151.9 100% 36.9%", + accentForeground: "0 0% 0%", + destructive: "0 61.4% 49.8%", + destructiveForeground: "0 0% 100%", + border: "0 0% 27.8%", + input: "0 0% 27.8%", + ring: "151.9 100% 36.9%", + }, + }, + { + id: "xotopio", + name: "Xotopio", + tokens: { + background: "233.3 69.2% 5.1%", + foreground: "0 0% 100%", + card: "232.9 36.2% 9.2%", + cardForeground: "0 0% 100%", + popover: "232.9 36.2% 9.2%", + popoverForeground: "0 0% 100%", + primary: "195.1 100% 66.5%", + primaryForeground: "0 0% 0%", + secondary: "232.9 25.4% 13.1%", + secondaryForeground: "0 0% 100%", + muted: "232.5 17% 18.4%", + mutedForeground: "240 3.7% 73.5%", + accent: "195.1 100% 66.5%", + accentForeground: "0 0% 0%", + destructive: "327.7 100% 48.8%", + destructiveForeground: "0 0% 0%", + border: "232 12.2% 24.1%", + input: "232 12.2% 24.1%", + ring: "195.1 100% 66.5%", + }, + }, + { + id: "yuttari", + name: "Yuttari", + tokens: { + background: "320 11.1% 10.6%", + foreground: "336.7 100% 96.5%", + card: "320 8.1% 14.5%", + cardForeground: "336.7 100% 96.5%", + popover: "320 8.1% 14.5%", + popoverForeground: "336.7 100% 96.5%", + primary: "38.5 43.3% 64.7%", + primaryForeground: "0 0% 0%", + secondary: "324 5.4% 18.2%", + secondaryForeground: "336.7 100% 96.5%", + muted: "320 5.1% 23.1%", + mutedForeground: "332 10.6% 72.4%", + accent: "38.5 43.3% 64.7%", + accentForeground: "0 0% 0%", + destructive: "0 41.1% 58%", + destructiveForeground: "0 0% 0%", + border: "324 3.4% 28.4%", + input: "324 3.4% 28.4%", + ring: "38.5 43.3% 64.7%", + }, + }, + { + id: "zenbones-rosebones", + name: "Zenbones Rosebones", + tokens: { + background: "249.2 21.3% 12%", + foreground: "0 17.8% 85.7%", + card: "249.2 16% 15.9%", + cardForeground: "0 17.8% 85.7%", + popover: "249.2 16% 15.9%", + popoverForeground: "0 17.8% 85.7%", + primary: "35.1 87.8% 71%", + primaryForeground: "0 0% 0%", + secondary: "245 12% 19.6%", + secondaryForeground: "0 17.8% 85.7%", + muted: "250 9.7% 24.3%", + mutedForeground: "336 5.5% 64.3%", + accent: "35.1 87.8% 71%", + accentForeground: "0 0% 0%", + destructive: "343.3 75.3% 68.2%", + destructiveForeground: "0 0% 0%", + border: "250.9 7.3% 29.6%", + input: "250.9 7.3% 29.6%", + ring: "35.1 87.8% 71%", + }, + }, + { + id: "zhxo-red", + name: "Zhxo'red", + tokens: { + background: "240 5.5% 10.8%", + foreground: "0 0% 67.1%", + card: "240 4% 14.7%", + cardForeground: "0 0% 67.1%", + popover: "240 4% 14.7%", + popoverForeground: "0 0% 67.1%", + primary: "182.7 86% 44.9%", + primaryForeground: "0 0% 0%", + secondary: "240 3.2% 18.2%", + secondaryForeground: "0 0% 67.1%", + muted: "240 2.5% 23.3%", + mutedForeground: "240 0.4% 51.2%", + accent: "182.7 86% 44.9%", + accentForeground: "0 0% 0%", + destructive: "0 72.6% 55.7%", + destructiveForeground: "0 0% 0%", + border: "240 1.4% 28.6%", + input: "240 1.4% 28.6%", + ring: "182.7 86% 44.9%", + }, + } +]; + +export const CORE_DARK_UI_THEMES: UiThemePreset[] = [ { id: "pure-black", name: "Pure Black", @@ -601,6 +3151,11 @@ export const DARK_UI_THEMES: UiThemePreset[] = [ }, ]; +export const DARK_UI_THEMES: UiThemePreset[] = [ + ...CORE_DARK_UI_THEMES, + ...EXTENDED_DARK_UI_THEMES, +]; + export const getUiThemeById = (theme: "light" | "dark", id: string): UiThemePreset => { const list = theme === "dark" ? DARK_UI_THEMES : LIGHT_UI_THEMES; const found = list.find((preset) => preset.id === id); From 0e80c874d640da543ffdc4ac759e1b9bb051a3b1 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 21:21:22 +0800 Subject: [PATCH 101/228] Clarify terminal theme follow behavior --- App.tsx | 22 +- application/i18n/locales/en/core.ts | 1 + application/i18n/locales/ru/core.ts | 1 + application/i18n/locales/zh-CN/terminal.ts | 1 + .../state/settingsTerminalTheme.test.ts | 36 +++ application/state/settingsTerminalTheme.ts | 20 +- components/SettingsPage.tsx | 4 + .../settings/tabs/SettingsTerminalTab.tsx | 228 +++++++++--------- .../tabs/SettingsTerminalTabControls.tsx | 11 +- components/terminal/ThemeSidePanel.tsx | 43 ++-- .../useTerminalThemePanelState.test.ts | 2 +- domain/terminalAppearance.test.ts | 52 ++-- domain/terminalAppearance.ts | 89 +++++-- 13 files changed, 316 insertions(+), 194 deletions(-) create mode 100644 application/state/settingsTerminalTheme.test.ts diff --git a/App.tsx b/App.tsx index 9e6c704dd..c9a421174 100755 --- a/App.tsx +++ b/App.tsx @@ -39,7 +39,7 @@ import { resolveCloseIntent } from './application/state/resolveCloseIntent'; import { resolveSnippetsShortcutIntent } from './application/state/resolveSnippetsShortcutIntent'; import { resolveWindowCommandCloseIntent } from './application/state/windowCommandClose'; import { TERMINAL_THEMES } from './infrastructure/config/terminalThemes'; -import { customThemeStore, useCustomThemes } from './application/state/customThemeStore'; +import { useCustomThemes } from './application/state/customThemeStore'; import type { SyncPayload } from './domain/sync'; import { applySyncPayload, buildLocalVaultPayload, hasMeaningfulSyncData } from './application/syncPayload'; import { @@ -116,13 +116,13 @@ function App({ settings }: { settings: SettingsState }) { const { theme, setTheme, + setLightUiThemeId, + setDarkUiThemeId, resolvedTheme, accentMode, customAccent, terminalThemeId, setTerminalThemeId, - setTerminalThemeDarkId, - setTerminalThemeLightId, followAppTerminalTheme, currentTerminalTheme, terminalFontFamilyId, @@ -1052,17 +1052,15 @@ function App({ settings }: { settings: SettingsState }) { const handleToggleTheme = useCallback(() => { return handleToggleThemeImpl(() => ({ openSettingsWindow, resolvedTheme, setTheme, t, theme, toast })); }, [openSettingsWindow, resolvedTheme, setTheme, t, theme]); const handleFollowAppTerminalThemeChange = useCallback((themeId: string) => { - const selectedTheme = customThemeStore.getThemeById(themeId); - if (!selectedTheme) return; - const update = getFollowAppTerminalThemeSelectionUpdate(selectedTheme); - if (update.terminalThemeDarkId) { - setTerminalThemeDarkId(update.terminalThemeDarkId); - } - if (update.terminalThemeLightId) { - setTerminalThemeLightId(update.terminalThemeLightId); + const update = getFollowAppTerminalThemeSelectionUpdate(themeId); + if (!update) return; + if (update.appTheme === 'dark') { + setDarkUiThemeId(update.uiThemeId); + } else { + setLightUiThemeId(update.uiThemeId); } setTheme(update.appTheme); - }, [setTerminalThemeDarkId, setTerminalThemeLightId, setTheme]); + }, [setDarkUiThemeId, setLightUiThemeId, setTheme]); const handleOpenQuickSwitcher = useCallback(() => { setIsQuickSwitcherOpen(true); diff --git a/application/i18n/locales/en/core.ts b/application/i18n/locales/en/core.ts index a207e412e..3f7e99e9b 100644 --- a/application/i18n/locales/en/core.ts +++ b/application/i18n/locales/en/core.ts @@ -295,6 +295,7 @@ export const enCoreMessages: Messages = { 'settings.terminal.theme.selectButton': 'Select Theme', 'settings.terminal.theme.followApp': 'Follow Application Theme', 'settings.terminal.theme.followApp.desc': 'Automatically match the terminal background to the current app theme for a seamless look.', + 'settings.terminal.theme.followingTheme': 'Current automatic terminal theme', 'settings.terminal.theme.darkTheme': 'Dark mode terminal theme', 'settings.terminal.theme.lightTheme': 'Light mode terminal theme', 'settings.terminal.theme.auto': 'Auto (match app theme)', diff --git a/application/i18n/locales/ru/core.ts b/application/i18n/locales/ru/core.ts index 4804a74a3..a00ad7163 100644 --- a/application/i18n/locales/ru/core.ts +++ b/application/i18n/locales/ru/core.ts @@ -284,6 +284,7 @@ export const ruCoreMessages: Messages = { 'settings.terminal.theme.selectButton': 'Выбрать тему', 'settings.terminal.theme.followApp': 'Следовать теме приложения', 'settings.terminal.theme.followApp.desc': 'Автоматически подбирать фон терминала под текущую тему приложения для более цельного вида.', + 'settings.terminal.theme.followingTheme': 'Текущая автоматическая тема терминала', 'settings.terminal.theme.darkTheme': 'Тема терминала для тёмного режима', 'settings.terminal.theme.lightTheme': 'Тема терминала для светлого режима', 'settings.terminal.theme.auto': 'Авто (как тема приложения)', diff --git a/application/i18n/locales/zh-CN/terminal.ts b/application/i18n/locales/zh-CN/terminal.ts index 6675657b5..4fa55751a 100644 --- a/application/i18n/locales/zh-CN/terminal.ts +++ b/application/i18n/locales/zh-CN/terminal.ts @@ -178,6 +178,7 @@ export const zhCNTerminalMessages: Messages = { 'settings.terminal.theme.selectButton': '选择主题', 'settings.terminal.theme.followApp': '跟随应用主题', 'settings.terminal.theme.followApp.desc': '终端背景色自动匹配当前应用主题,保持视觉一致性。', + 'settings.terminal.theme.followingTheme': '当前自动终端主题', 'settings.terminal.theme.darkTheme': '深色模式终端主题', 'settings.terminal.theme.lightTheme': '浅色模式终端主题', 'settings.terminal.theme.auto': '自动(跟随界面主题)', diff --git a/application/state/settingsTerminalTheme.test.ts b/application/state/settingsTerminalTheme.test.ts new file mode 100644 index 000000000..0f2c122e7 --- /dev/null +++ b/application/state/settingsTerminalTheme.test.ts @@ -0,0 +1,36 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { resolveCurrentTerminalTheme } from "./settingsTerminalTheme"; + +const commonArgs = { + terminalThemeId: "netcatty-dark", + customThemes: [], + resolvedTheme: "dark" as const, + lightUiThemeId: "snow", + darkUiThemeId: "github", + accentMode: "theme" as const, + customAccent: "", +}; + +test("follow-app terminal theme ignores manual per-mode terminal picks", () => { + const theme = resolveCurrentTerminalTheme({ + ...commonArgs, + followAppTerminalTheme: true, + terminalThemeDarkId: "dracula", + terminalThemeLightId: "solarized-light", + }); + + assert.equal(theme.id, "system-github-dark"); +}); + +test("manual terminal theme uses the active per-mode pick", () => { + const theme = resolveCurrentTerminalTheme({ + ...commonArgs, + followAppTerminalTheme: false, + terminalThemeDarkId: "dracula", + terminalThemeLightId: "solarized-light", + }); + + assert.equal(theme.id, "dracula"); +}); diff --git a/application/state/settingsTerminalTheme.ts b/application/state/settingsTerminalTheme.ts index acefdb6e5..5a523bdd6 100644 --- a/application/state/settingsTerminalTheme.ts +++ b/application/state/settingsTerminalTheme.ts @@ -1,6 +1,10 @@ import type { TerminalTheme } from '../../domain/models'; import { TERMINAL_THEMES } from '../../infrastructure/config/terminalThemes'; -import { applyCustomAccentToTerminalTheme, resolveFollowedTerminalThemeId } from '../../domain/terminalAppearance'; +import { + applyCustomAccentToTerminalTheme, + resolveFollowedTerminalThemeId, + resolveManualTerminalThemeId, +} from '../../domain/terminalAppearance'; interface ResolveCurrentTerminalThemeParams { terminalThemeId: string; @@ -30,8 +34,6 @@ export function resolveCurrentTerminalTheme({ if (followAppTerminalTheme) { const followedId = resolveFollowedTerminalThemeId({ resolvedTheme, - terminalThemeDarkId, - terminalThemeLightId, lightUiThemeId, darkUiThemeId, fallbackThemeId: terminalThemeId, @@ -42,7 +44,17 @@ export function resolveCurrentTerminalTheme({ return applyCustomAccentToTerminalTheme(followed, accentMode, customAccent); } } - const baseTheme = TERMINAL_THEMES.find(t => t.id === terminalThemeId) + const manualThemeId = resolveManualTerminalThemeId({ + resolvedTheme, + terminalThemeDarkId, + terminalThemeLightId, + lightUiThemeId, + darkUiThemeId, + fallbackThemeId: terminalThemeId, + }); + const baseTheme = TERMINAL_THEMES.find(t => t.id === manualThemeId) + || customThemes.find(t => t.id === manualThemeId) + || TERMINAL_THEMES.find(t => t.id === terminalThemeId) || customThemes.find(t => t.id === terminalThemeId) || TERMINAL_THEMES[0]; return applyCustomAccentToTerminalTheme(baseTheme, accentMode, customAccent); diff --git a/components/SettingsPage.tsx b/components/SettingsPage.tsx index 79f0868d8..9acc2d4cc 100644 --- a/components/SettingsPage.tsx +++ b/components/SettingsPage.tsx @@ -96,6 +96,7 @@ type TerminalTabSettingsProps = Pick< SettingsState, | 'terminalThemeId' | 'setTerminalThemeId' + | 'resolvedTheme' | 'followAppTerminalTheme' | 'setFollowAppTerminalTheme' | 'terminalThemeDarkId' @@ -117,6 +118,7 @@ type TerminalTabSettingsProps = Pick< const SettingsTerminalTabContainer = React.memo(function SettingsTerminalTabContainer({ terminalThemeId, setTerminalThemeId, + resolvedTheme, followAppTerminalTheme, setFollowAppTerminalTheme, terminalThemeDarkId, @@ -140,6 +142,7 @@ const SettingsTerminalTabContainer = React.memo(functi = ({ settings } void; + resolvedTheme: "dark" | "light"; followAppTerminalTheme: boolean; setFollowAppTerminalTheme: (value: boolean) => void; terminalThemeDarkId: string; @@ -67,6 +68,7 @@ function SettingsTerminalTab(props: { const { terminalThemeId, setTerminalThemeId, + resolvedTheme, followAppTerminalTheme, setFollowAppTerminalTheme, terminalThemeDarkId, @@ -114,50 +116,59 @@ function SettingsTerminalTab(props: { setCustomArgsDraft(formatShellArgs(terminalSettings.localShellArgs ?? [])); setCustomShellModalOpen(true); }, [terminalSettings.localShell, terminalSettings.localShellArgs]); - const [themeModalOpen, setThemeModalOpen] = useState(false); const [themeModalSlot, setThemeModalSlot] = useState<'dark' | 'light' | null>(null); // Subscribe to custom theme changes so editing in-place triggers re-render const customThemes = useCustomThemes(); - // Get current selected theme - const currentTheme = useMemo(() => { - return TERMINAL_THEMES.find(t => t.id === terminalThemeId) - || customThemes.find(t => t.id === terminalThemeId) - || TERMINAL_THEMES[0]; - }, [terminalThemeId, customThemes]); + const findTerminalTheme = useCallback((id: string) => ( + TERMINAL_THEMES.find(t => t.id === id) + || customThemes.find(t => t.id === id) + || null + ), [customThemes]); - // Preview themes for the follow-app per-mode pickers. resolvedTheme is - // forced per slot so each preview reflects exactly that mode's selection. - const darkPreviewTheme = useMemo(() => { + const followedPreviewTheme = useMemo(() => { const id = resolveFollowedTerminalThemeId({ + resolvedTheme, + lightUiThemeId, + darkUiThemeId, + fallbackThemeId: terminalThemeId, + }); + return findTerminalTheme(id) || findTerminalTheme(terminalThemeId) || TERMINAL_THEMES[0]; + }, [darkUiThemeId, findTerminalTheme, lightUiThemeId, resolvedTheme, terminalThemeId]); + + const darkPreviewTheme = useMemo(() => { + const id = resolveManualTerminalThemeId({ resolvedTheme: 'dark', terminalThemeDarkId, terminalThemeLightId, lightUiThemeId, darkUiThemeId, fallbackThemeId: terminalThemeId, }); - return TERMINAL_THEMES.find(t => t.id === id) - || customThemes.find(t => t.id === id) - // Mirror the runtime fallback in useSettingsState.currentTerminalTheme: - // a deleted per-mode override falls back to the manual theme, not [0]. - || TERMINAL_THEMES.find(t => t.id === terminalThemeId) - || customThemes.find(t => t.id === terminalThemeId) - || TERMINAL_THEMES[0]; - }, [terminalThemeDarkId, terminalThemeLightId, lightUiThemeId, darkUiThemeId, terminalThemeId, customThemes]); + return findTerminalTheme(id) || findTerminalTheme(terminalThemeId) || TERMINAL_THEMES[0]; + }, [darkUiThemeId, findTerminalTheme, lightUiThemeId, terminalThemeDarkId, terminalThemeId, terminalThemeLightId]); const lightPreviewTheme = useMemo(() => { - const id = resolveFollowedTerminalThemeId({ + const id = resolveManualTerminalThemeId({ resolvedTheme: 'light', terminalThemeDarkId, terminalThemeLightId, lightUiThemeId, darkUiThemeId, fallbackThemeId: terminalThemeId, }); - return TERMINAL_THEMES.find(t => t.id === id) - || customThemes.find(t => t.id === id) - // Mirror the runtime fallback in useSettingsState.currentTerminalTheme: - // a deleted per-mode override falls back to the manual theme, not [0]. - || TERMINAL_THEMES.find(t => t.id === terminalThemeId) - || customThemes.find(t => t.id === terminalThemeId) - || TERMINAL_THEMES[0]; - }, [terminalThemeDarkId, terminalThemeLightId, lightUiThemeId, darkUiThemeId, terminalThemeId, customThemes]); + return findTerminalTheme(id) || findTerminalTheme(terminalThemeId) || TERMINAL_THEMES[0]; + }, [darkUiThemeId, findTerminalTheme, lightUiThemeId, terminalThemeDarkId, terminalThemeId, terminalThemeLightId]); + + const currentTheme = followAppTerminalTheme + ? followedPreviewTheme + : resolvedTheme === 'dark' + ? darkPreviewTheme + : lightPreviewTheme; + + const setManualThemeForResolvedMode = useCallback((themeId: string) => { + if (resolvedTheme === 'dark') { + setTerminalThemeDarkId(themeId); + } else { + setTerminalThemeLightId(themeId); + } + setTerminalThemeId(themeId); + }, [resolvedTheme, setTerminalThemeDarkId, setTerminalThemeId, setTerminalThemeLightId]); const fontWeightOptions = useMemo(() => ( FONT_WEIGHT_OPTIONS.map((option) => ({ @@ -194,7 +205,7 @@ function SettingsTerminalTab(props: { const parsed = parseItermcolors(xml, name); if (parsed) { customThemeStore.addTheme(parsed); - setTerminalThemeId(parsed.id); + setManualThemeForResolvedMode(parsed.id); } else { console.error('[Settings] Failed to parse .itermcolors file:', file.name); window.alert(t('terminal.customTheme.importError') || 'Failed to parse the selected file. Please ensure it is a valid .itermcolors XML file.'); @@ -205,7 +216,7 @@ function SettingsTerminalTab(props: { }; reader.readAsText(file); e.target.value = ''; - }, [setTerminalThemeId, t]); + }, [setManualThemeForResolvedMode, t]); // New custom theme modal const [customThemeModalOpen, setCustomThemeModalOpen] = useState(false); @@ -218,9 +229,7 @@ function SettingsTerminalTab(props: { }, [currentTheme]); const handleNewCustomTheme = useCallback(() => { - const base = TERMINAL_THEMES.find(t => t.id === terminalThemeId) - || customThemeStore.getThemeById(terminalThemeId) - || TERMINAL_THEMES[0]; + const base = currentTheme || TERMINAL_THEMES[0]; const newTheme: TerminalTheme = { ...base, id: `custom-${Date.now()}`, @@ -231,7 +240,7 @@ function SettingsTerminalTab(props: { setCustomThemeData(newTheme); setIsEditingTheme(false); setCustomThemeModalOpen(true); - }, [terminalThemeId]); + }, [currentTheme]); const handleEditCustomTheme = useCallback(() => { if (!currentTheme?.isCustom) return; @@ -243,8 +252,8 @@ function SettingsTerminalTab(props: { const handleDeleteCustomTheme = useCallback(() => { if (!currentTheme?.isCustom) return; customThemeStore.deleteTheme(currentTheme.id); - setTerminalThemeId(TERMINAL_THEMES[0].id); - }, [currentTheme, setTerminalThemeId]); + setManualThemeForResolvedMode(followedPreviewTheme.id); + }, [currentTheme, followedPreviewTheme.id, setManualThemeForResolvedMode]); // Fetch default shell on mount useEffect(() => { @@ -349,6 +358,18 @@ function SettingsTerminalTab(props: {
{followAppTerminalTheme && ( +
+
+ {t("settings.terminal.theme.followingTheme")} +
+ +
+ )} + {!followAppTerminalTheme && ( <>
@@ -357,9 +378,7 @@ function SettingsTerminalTab(props: { setThemeModalSlot('dark')} - buttonLabel={terminalThemeDarkId === TERMINAL_THEME_AUTO - ? t("settings.terminal.theme.auto") - : t("settings.terminal.theme.selectButton")} + buttonLabel={t("settings.terminal.theme.selectButton")} />
@@ -369,95 +388,76 @@ function SettingsTerminalTab(props: { setThemeModalSlot('light')} - buttonLabel={terminalThemeLightId === TERMINAL_THEME_AUTO - ? t("settings.terminal.theme.auto") - : t("settings.terminal.theme.selectButton")} - /> -
- - )} - {!followAppTerminalTheme && ( -
-
- {t("terminal.themeModal.globalTheme")} -
- setThemeModalOpen(true)} buttonLabel={t("settings.terminal.theme.selectButton")} />
+ )}
- setThemeModalOpen(false)} - selectedThemeId={terminalThemeId} - onSelect={setTerminalThemeId} - /> setThemeModalSlot(null)} - selectedThemeId={themeModalSlot === 'dark' ? terminalThemeDarkId : terminalThemeLightId} + selectedThemeId={themeModalSlot === 'dark' ? darkPreviewTheme.id : lightPreviewTheme.id} onSelect={(id) => { if (themeModalSlot === 'dark') setTerminalThemeDarkId(id); else if (themeModalSlot === 'light') setTerminalThemeLightId(id); + setTerminalThemeId(id); }} filterType={themeModalSlot === 'light' ? 'light' : 'dark'} - showAutoOption /> - {/* Theme action buttons */} -
- - - {isCustomTheme && ( - <> - - - - )} - -
+ {!followAppTerminalTheme && ( +
+ + + {isCustomTheme && ( + <> + + + + )} + +
+ )} {/* Custom Theme Modal */} {customThemeData && ( @@ -471,13 +471,13 @@ function SettingsTerminalTab(props: { } else { customThemeStore.addTheme(theme); } - setTerminalThemeId(theme.id); + setManualThemeForResolvedMode(theme.id); setCustomThemeModalOpen(false); setCustomThemeData(null); }} onDelete={isEditingTheme ? (themeId) => { customThemeStore.deleteTheme(themeId); - setTerminalThemeId(TERMINAL_THEMES[0].id); + setManualThemeForResolvedMode(followedPreviewTheme.id); setCustomThemeModalOpen(false); setCustomThemeData(null); } : undefined} diff --git a/components/settings/tabs/SettingsTerminalTabControls.tsx b/components/settings/tabs/SettingsTerminalTabControls.tsx index 0639b0123..024fdf3fb 100644 --- a/components/settings/tabs/SettingsTerminalTabControls.tsx +++ b/components/settings/tabs/SettingsTerminalTabControls.tsx @@ -249,15 +249,18 @@ export const KeywordHighlightRulesEditor: React.FC<{ // Theme preview button component export const ThemePreviewButton: React.FC<{ theme: (typeof TERMINAL_THEMES)[0]; - onClick: () => void; + onClick?: () => void; buttonLabel: string; -}> = ({ theme, onClick, buttonLabel }) => { + disabled?: boolean; +}> = ({ theme, onClick, buttonLabel, disabled = false }) => { const c = theme.colors; return ( ); diff --git a/components/terminal/ThemeSidePanel.tsx b/components/terminal/ThemeSidePanel.tsx index 7638fffc0..cfe3228b6 100644 --- a/components/terminal/ThemeSidePanel.tsx +++ b/components/terminal/ThemeSidePanel.tsx @@ -6,7 +6,7 @@ * Changes apply in real-time. */ -import React, { memo, useCallback, useMemo, useRef, useState } from 'react'; +import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { Check, Download, Minus, Palette, Pencil, Plus, Sparkles, Type } from 'lucide-react'; import { useI18n } from '../../application/i18n/I18nProvider'; import { useAvailableFonts } from '../../application/state/fontStore'; @@ -19,6 +19,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '. import { cn } from '../../lib/utils'; import { TerminalTheme } from '../../domain/models'; import { ScrollArea } from '../ui/scroll-area'; +import { isFollowAppTerminalThemeId } from '../../domain/terminalAppearance'; type TabType = 'theme' | 'font' | 'custom'; @@ -154,6 +155,7 @@ interface ThemeSidePanelProps { } const ThemeSidePanelInner: React.FC = ({ + followAppTerminalTheme = false, currentThemeId, globalThemeId, currentFontFamilyId, @@ -185,6 +187,13 @@ const ThemeSidePanelInner: React.FC = ({ const [isNewTheme, setIsNewTheme] = useState(false); const fileInputRef = useRef(null); + useEffect(() => { + if (followAppTerminalTheme && activeTab === 'custom') { + setActiveTab('theme'); + setEditingTheme(null); + } + }, [activeTab, followAppTerminalTheme]); + const allThemes = useMemo( () => [...TERMINAL_THEMES, ...customThemes], [customThemes] @@ -274,7 +283,9 @@ const ThemeSidePanelInner: React.FC = ({ if (!isVisible) return null; - const builtinThemes = USER_VISIBLE_TERMINAL_THEMES; + const builtinThemes = followAppTerminalTheme + ? TERMINAL_THEMES.filter((theme) => isFollowAppTerminalThemeId(theme.id)) + : USER_VISIBLE_TERMINAL_THEMES; const footerLabel = `${allThemes.find(t => t.id === currentThemeId)?.name ?? currentThemeId} • ${availableFonts.find(f => f.id === currentFontFamilyId)?.name ?? currentFontFamilyId} • ${currentFontSize}px • ${currentFontWeight}`; const panelVars = { @@ -325,17 +336,19 @@ const ThemeSidePanelInner: React.FC = ({ {t('terminal.themeModal.tab.font')} - + {!followAppTerminalTheme && ( + + )}
{/* List Content */} @@ -343,7 +356,7 @@ const ThemeSidePanelInner: React.FC = ({
{activeTab === 'theme' && (
- {hiddenSelectedTheme && ( + {!followAppTerminalTheme && hiddenSelectedTheme && ( = ({ onSelect={handleThemeSelect} /> ))} - {customThemes.length > 0 && ( + {!followAppTerminalTheme && customThemes.length > 0 && ( <>
{t('terminal.customTheme.section')} diff --git a/components/terminalLayer/useTerminalThemePanelState.test.ts b/components/terminalLayer/useTerminalThemePanelState.test.ts index beaaa111b..f8a3e5bf6 100644 --- a/components/terminalLayer/useTerminalThemePanelState.test.ts +++ b/components/terminalLayer/useTerminalThemePanelState.test.ts @@ -4,7 +4,7 @@ import test from "node:test"; const source = readFileSync(new URL("./useTerminalThemePanelState.ts", import.meta.url), "utf8"); -test("follow-app side panel theme changes update the global terminal theme", () => { +test("follow-app side panel theme changes update the followed app theme", () => { assert.match(source, /onUpdateFollowAppTerminalThemeId\?\.\(themeId\)/); assert.match(source, /if \(followAppTerminalTheme\) \{/); }); diff --git a/domain/terminalAppearance.test.ts b/domain/terminalAppearance.test.ts index 1eba14d34..6e9a92da2 100644 --- a/domain/terminalAppearance.test.ts +++ b/domain/terminalAppearance.test.ts @@ -4,9 +4,12 @@ import assert from "node:assert/strict"; import { applyCustomAccentToTerminalTheme, applySessionFontSizeToHost, + getFollowAppTerminalThemeIds, getFollowAppTerminalThemeSelectionUpdate, + isFollowAppTerminalThemeId, mergeTerminalHostUpdate, resolveFollowedTerminalThemeId, + resolveManualTerminalThemeId, TERMINAL_THEME_AUTO, } from "./terminalAppearance"; import type { Host, TerminalTheme } from "./models"; @@ -205,8 +208,6 @@ test("follow-theme resolver: dark + auto follows the active dark UI preset", () assert.equal( resolveFollowedTerminalThemeId({ resolvedTheme: "dark", - terminalThemeDarkId: TERMINAL_THEME_AUTO, - terminalThemeLightId: TERMINAL_THEME_AUTO, lightUiThemeId: "snow", darkUiThemeId: "midnight", fallbackThemeId: "netcatty-dark", @@ -219,8 +220,6 @@ test("follow-theme resolver: light + auto follows the active light UI preset", ( assert.equal( resolveFollowedTerminalThemeId({ resolvedTheme: "light", - terminalThemeDarkId: TERMINAL_THEME_AUTO, - terminalThemeLightId: TERMINAL_THEME_AUTO, lightUiThemeId: "snow", darkUiThemeId: "midnight", fallbackThemeId: "netcatty-dark", @@ -233,8 +232,6 @@ test("follow-theme resolver: imported system presets follow the active light or assert.equal( resolveFollowedTerminalThemeId({ resolvedTheme: "light", - terminalThemeDarkId: TERMINAL_THEME_AUTO, - terminalThemeLightId: TERMINAL_THEME_AUTO, lightUiThemeId: "github", darkUiThemeId: "github", fallbackThemeId: "netcatty-dark", @@ -244,8 +241,6 @@ test("follow-theme resolver: imported system presets follow the active light or assert.equal( resolveFollowedTerminalThemeId({ resolvedTheme: "dark", - terminalThemeDarkId: TERMINAL_THEME_AUTO, - terminalThemeLightId: TERMINAL_THEME_AUTO, lightUiThemeId: "github", darkUiThemeId: "github", fallbackThemeId: "netcatty-dark", @@ -254,9 +249,21 @@ test("follow-theme resolver: imported system presets follow the active light or ); }); -test("follow-theme resolver: explicit dark override wins over auto-matching", () => { +test("follow-theme resolver: explicit dark override is ignored while following app theme", () => { assert.equal( resolveFollowedTerminalThemeId({ + resolvedTheme: "dark", + lightUiThemeId: "snow", + darkUiThemeId: "midnight", + fallbackThemeId: "netcatty-dark", + }), + "ui-midnight", + ); +}); + +test("manual-theme resolver: explicit per-mode theme wins when not following app theme", () => { + assert.equal( + resolveManualTerminalThemeId({ resolvedTheme: "dark", terminalThemeDarkId: "dracula", terminalThemeLightId: TERMINAL_THEME_AUTO, @@ -266,11 +273,8 @@ test("follow-theme resolver: explicit dark override wins over auto-matching", () }), "dracula", ); -}); - -test("follow-theme resolver: explicit light override wins over auto-matching", () => { assert.equal( - resolveFollowedTerminalThemeId({ + resolveManualTerminalThemeId({ resolvedTheme: "light", terminalThemeDarkId: TERMINAL_THEME_AUTO, terminalThemeLightId: "solarized-light", @@ -284,27 +288,37 @@ test("follow-theme resolver: explicit light override wins over auto-matching", ( test("follow-app theme selection updates the matching mode and app theme", () => { assert.deepEqual( - getFollowAppTerminalThemeSelectionUpdate({ id: "snow", type: "light" }), + getFollowAppTerminalThemeSelectionUpdate("ui-snow"), { appTheme: "light", - terminalThemeLightId: "snow", + uiThemeId: "snow", }, ); assert.deepEqual( - getFollowAppTerminalThemeSelectionUpdate({ id: "midnight", type: "dark" }), + getFollowAppTerminalThemeSelectionUpdate("system-github-dark"), { appTheme: "dark", - terminalThemeDarkId: "midnight", + uiThemeId: "github", }, ); }); +test("follow-app theme list only includes terminal themes backed by UI themes", () => { + const lightIds = getFollowAppTerminalThemeIds("light"); + const darkIds = getFollowAppTerminalThemeIds("dark"); + + assert.ok(lightIds.includes("ui-snow")); + assert.ok(lightIds.includes("system-github-light")); + assert.ok(darkIds.includes("ui-midnight")); + assert.ok(darkIds.includes("system-github-dark")); + assert.equal(isFollowAppTerminalThemeId("dracula"), false); + assert.equal(isFollowAppTerminalThemeId("custom-theme"), false); +}); + test("follow-theme resolver: auto with no UI match falls back to fallbackThemeId", () => { assert.equal( resolveFollowedTerminalThemeId({ resolvedTheme: "dark", - terminalThemeDarkId: TERMINAL_THEME_AUTO, - terminalThemeLightId: TERMINAL_THEME_AUTO, lightUiThemeId: "no-such-ui-theme", darkUiThemeId: "no-such-ui-theme", fallbackThemeId: "netcatty-dark", diff --git a/domain/terminalAppearance.ts b/domain/terminalAppearance.ts index b8aabb117..995d96d00 100644 --- a/domain/terminalAppearance.ts +++ b/domain/terminalAppearance.ts @@ -69,8 +69,7 @@ export const resolveHostTerminalThemeId = (host: Host | null | undefined, defaul * terminal blends seamlessly with the app chrome. Returns undefined if no * match exists (caller should fall back to the global terminal theme). */ -const UI_TO_TERMINAL_THEME: Record = { - // Light +const CORE_LIGHT_UI_TO_TERMINAL_THEME: Record = { 'snow': 'ui-snow', 'pure-white': 'ui-pure-white', 'ivory': 'ui-ivory', @@ -78,7 +77,9 @@ const UI_TO_TERMINAL_THEME: Record = { 'mint': 'ui-mint', 'sand': 'ui-sand', 'lavender': 'ui-lavender', - // Dark +}; + +const CORE_DARK_UI_TO_TERMINAL_THEME: Record = { 'pure-black': 'ui-pure-black', 'midnight': 'ui-midnight', 'deep-blue': 'ui-deep-blue', @@ -88,6 +89,11 @@ const UI_TO_TERMINAL_THEME: Record = { 'forest': 'ui-forest', }; +const UI_TO_TERMINAL_THEME: Record = { + ...CORE_LIGHT_UI_TO_TERMINAL_THEME, + ...CORE_DARK_UI_TO_TERMINAL_THEME, +}; + const SYSTEM_LIGHT_UI_TO_TERMINAL_THEME: Record = { "a-cup-of-coffee": "system-a-cup-of-coffee-light", "abolkog": "system-abolkog-light", @@ -210,22 +216,68 @@ export const getTerminalThemeForUiTheme = (uiThemeId: string, resolvedTheme?: 'l return UI_TO_TERMINAL_THEME[uiThemeId]; }; +export type FollowAppTerminalThemeSelection = { + appTheme: TerminalTheme['type']; + uiThemeId: string; +}; + +const createTerminalThemeToUiThemeMap = (): Record => { + const entries: Array<[string, FollowAppTerminalThemeSelection]> = []; + for (const [uiThemeId, terminalThemeId] of Object.entries(CORE_LIGHT_UI_TO_TERMINAL_THEME)) { + entries.push([terminalThemeId, { appTheme: 'light', uiThemeId }]); + } + for (const [uiThemeId, terminalThemeId] of Object.entries(CORE_DARK_UI_TO_TERMINAL_THEME)) { + entries.push([terminalThemeId, { appTheme: 'dark', uiThemeId }]); + } + for (const [uiThemeId, terminalThemeId] of Object.entries(SYSTEM_LIGHT_UI_TO_TERMINAL_THEME)) { + entries.push([terminalThemeId, { appTheme: 'light', uiThemeId }]); + } + for (const [uiThemeId, terminalThemeId] of Object.entries(SYSTEM_DARK_UI_TO_TERMINAL_THEME)) { + entries.push([terminalThemeId, { appTheme: 'dark', uiThemeId }]); + } + return Object.fromEntries(entries); +}; + +const TERMINAL_THEME_TO_UI_THEME = createTerminalThemeToUiThemeMap(); + +export const getFollowAppTerminalThemeIds = (type?: TerminalTheme['type']): string[] => + Object.entries(TERMINAL_THEME_TO_UI_THEME) + .filter(([, selection]) => !type || selection.appTheme === type) + .map(([terminalThemeId]) => terminalThemeId); + +export const isFollowAppTerminalThemeId = (themeId: string): boolean => + Object.prototype.hasOwnProperty.call(TERMINAL_THEME_TO_UI_THEME, themeId); + +export const getFollowAppTerminalThemeSelectionUpdate = ( + themeId: string, +): FollowAppTerminalThemeSelection | null => + TERMINAL_THEME_TO_UI_THEME[themeId] ?? null; + /** - * Sentinel stored in the per-mode follow-theme settings meaning "let the - * terminal theme follow the active UI theme preset" (the legacy - * auto-matching behavior), as opposed to a concrete terminal theme id. + * Sentinel stored in the per-mode manual terminal theme settings. It means + * the user has not chosen a concrete terminal theme for that mode yet, so the + * app can use the UI-matched default. */ export const TERMINAL_THEME_AUTO = 'auto'; /** * Resolve which terminal theme id to use while "Follow Application Theme" is - * enabled, honoring the user's per-mode override. - * - * - A concrete theme id in the active mode's setting is used as-is. - * - `TERMINAL_THEME_AUTO` (the default) keeps the legacy behavior: match the - * active UI theme preset, then `fallbackThemeId` when no UI match exists. + * enabled. This is intentionally not overrideable: the terminal follows the + * active UI theme preset, then `fallbackThemeId` when no UI match exists. */ export const resolveFollowedTerminalThemeId = (args: { + resolvedTheme: 'light' | 'dark'; + lightUiThemeId: string; + darkUiThemeId: string; + fallbackThemeId: string; +}): string => { + const activeUiThemeId = args.resolvedTheme === 'dark' + ? args.darkUiThemeId + : args.lightUiThemeId; + return getTerminalThemeForUiTheme(activeUiThemeId, args.resolvedTheme) ?? args.fallbackThemeId; +}; + +export const resolveManualTerminalThemeId = (args: { resolvedTheme: 'light' | 'dark'; terminalThemeDarkId: string; terminalThemeLightId: string; @@ -237,22 +289,9 @@ export const resolveFollowedTerminalThemeId = (args: { ? args.terminalThemeDarkId : args.terminalThemeLightId; if (selected && selected !== TERMINAL_THEME_AUTO) return selected; - const activeUiThemeId = args.resolvedTheme === 'dark' - ? args.darkUiThemeId - : args.lightUiThemeId; - return getTerminalThemeForUiTheme(activeUiThemeId, args.resolvedTheme) ?? args.fallbackThemeId; + return resolveFollowedTerminalThemeId(args); }; -export const getFollowAppTerminalThemeSelectionUpdate = ( - theme: Pick, -): { - appTheme: TerminalTheme['type']; - terminalThemeDarkId?: string; - terminalThemeLightId?: string; -} => theme.type === 'dark' - ? { appTheme: 'dark', terminalThemeDarkId: theme.id } - : { appTheme: 'light', terminalThemeLightId: theme.id }; - type ParsedHslToken = { hue: number; saturation: number; From 32b46b1ef3934159486ece829e4c352f17e25333 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 21:29:08 +0800 Subject: [PATCH 102/228] Remove UI match suffix from terminal theme names --- infrastructure/config/terminalThemes/modern.ts | 14 +++++++------- infrastructure/config/terminalThemes/uiMatch.ts | 14 +++++++------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/infrastructure/config/terminalThemes/modern.ts b/infrastructure/config/terminalThemes/modern.ts index 8c1263ae8..d6aaf300b 100644 --- a/infrastructure/config/terminalThemes/modern.ts +++ b/infrastructure/config/terminalThemes/modern.ts @@ -1,49 +1,49 @@ import type { TerminalTheme } from '../../../domain/models'; export const modernTerminalThemes: TerminalTheme[] = [ - { id: 'ui-pure-black', name: 'Pure Black (UI Match)', type: 'dark', colors: { + { id: 'ui-pure-black', name: 'Pure Black', type: 'dark', colors: { background: '#000000', foreground: '#c9d1d9', cursor: '#58a6ff', selection: '#264f78', black: '#000000', red: '#ff7b72', green: '#3fb950', yellow: '#d29922', blue: '#58a6ff', magenta: '#bc8cff', cyan: '#39c5cf', white: '#b1bac4', brightBlack: '#6e7681', brightRed: '#ffa198', brightGreen: '#56d364', brightYellow: '#e3b341', brightBlue: '#79c0ff', brightMagenta: '#d2a8ff', brightCyan: '#56d4dd', brightWhite: '#f0f6fc', }}, - { id: 'ui-midnight', name: 'Midnight (UI Match)', type: 'dark', colors: { + { id: 'ui-midnight', name: 'Midnight', type: 'dark', colors: { background: '#141822', foreground: '#c9d1d9', cursor: '#58a6ff', selection: '#264f78', black: '#141822', red: '#ff7b72', green: '#3fb950', yellow: '#d29922', blue: '#58a6ff', magenta: '#bc8cff', cyan: '#39c5cf', white: '#b1bac4', brightBlack: '#6e7681', brightRed: '#ffa198', brightGreen: '#56d364', brightYellow: '#e3b341', brightBlue: '#79c0ff', brightMagenta: '#d2a8ff', brightCyan: '#56d4dd', brightWhite: '#f0f6fc', }}, - { id: 'ui-deep-blue', name: 'Deep Blue (UI Match)', type: 'dark', colors: { + { id: 'ui-deep-blue', name: 'Deep Blue', type: 'dark', colors: { background: '#111722', foreground: '#c9d1d9', cursor: '#58a6ff', selection: '#264f78', black: '#111722', red: '#ff7b72', green: '#3fb950', yellow: '#d29922', blue: '#58a6ff', magenta: '#bc8cff', cyan: '#39c5cf', white: '#b1bac4', brightBlack: '#6e7681', brightRed: '#ffa198', brightGreen: '#56d364', brightYellow: '#e3b341', brightBlue: '#79c0ff', brightMagenta: '#d2a8ff', brightCyan: '#56d4dd', brightWhite: '#f0f6fc', }}, - { id: 'ui-vscode', name: 'VS Code (UI Match)', type: 'dark', colors: { + { id: 'ui-vscode', name: 'VS Code', type: 'dark', colors: { background: '#1f1f1f', foreground: '#cccccc', cursor: '#aeafad', selection: '#264f78', black: '#1f1f1f', red: '#f44747', green: '#6a9955', yellow: '#dcdcaa', blue: '#569cd6', magenta: '#c586c0', cyan: '#4ec9b0', white: '#d4d4d4', brightBlack: '#808080', brightRed: '#f44747', brightGreen: '#6a9955', brightYellow: '#dcdcaa', brightBlue: '#569cd6', brightMagenta: '#c586c0', brightCyan: '#4ec9b0', brightWhite: '#e5e5e5', }}, - { id: 'ui-graphite', name: 'Graphite (UI Match)', type: 'dark', colors: { + { id: 'ui-graphite', name: 'Graphite', type: 'dark', colors: { background: '#1c1e21', foreground: '#c9d1d9', cursor: '#58a6ff', selection: '#264f78', black: '#1c1e21', red: '#ff7b72', green: '#3fb950', yellow: '#d29922', blue: '#58a6ff', magenta: '#bc8cff', cyan: '#39c5cf', white: '#b1bac4', brightBlack: '#6e7681', brightRed: '#ffa198', brightGreen: '#56d364', brightYellow: '#e3b341', brightBlue: '#79c0ff', brightMagenta: '#d2a8ff', brightCyan: '#56d4dd', brightWhite: '#f0f6fc', }}, - { id: 'ui-obsidian', name: 'Obsidian (UI Match)', type: 'dark', colors: { + { id: 'ui-obsidian', name: 'Obsidian', type: 'dark', colors: { background: '#131316', foreground: '#c9d1d9', cursor: '#a78bfa', selection: '#3b3175', black: '#131316', red: '#ff7b72', green: '#3fb950', yellow: '#d29922', blue: '#58a6ff', magenta: '#bc8cff', cyan: '#39c5cf', white: '#b1bac4', brightBlack: '#6e7681', brightRed: '#ffa198', brightGreen: '#56d364', brightYellow: '#e3b341', brightBlue: '#79c0ff', brightMagenta: '#d2a8ff', brightCyan: '#56d4dd', brightWhite: '#f0f6fc', }}, - { id: 'ui-forest', name: 'Forest (UI Match)', type: 'dark', colors: { + { id: 'ui-forest', name: 'Forest', type: 'dark', colors: { background: '#161d1a', foreground: '#c9d1d9', cursor: '#34d399', selection: '#1a4a3a', black: '#161d1a', red: '#ff7b72', green: '#3fb950', yellow: '#d29922', blue: '#58a6ff', magenta: '#bc8cff', cyan: '#39c5cf', white: '#b1bac4', diff --git a/infrastructure/config/terminalThemes/uiMatch.ts b/infrastructure/config/terminalThemes/uiMatch.ts index 66a26aa35..f89339175 100644 --- a/infrastructure/config/terminalThemes/uiMatch.ts +++ b/infrastructure/config/terminalThemes/uiMatch.ts @@ -7,49 +7,49 @@ export const uiMatchTerminalThemes: TerminalTheme[] = [ // ANSI palette based on netcatty-light (for light) / netcatty-dark (for dark)., // ====================================================================, // Light UI matches, - { id: 'ui-snow', name: 'Snow (UI Match)', type: 'light', colors: { + { id: 'ui-snow', name: 'Snow', type: 'light', colors: { background: '#f1f4f8', foreground: '#24292f', cursor: '#0969da', selection: '#add6ff', black: '#24292f', red: '#cf222e', green: '#116329', yellow: '#9a6700', blue: '#0969da', magenta: '#8250df', cyan: '#0e7574', white: '#6e7781', brightBlack: '#57606a', brightRed: '#a40e26', brightGreen: '#1a7f37', brightYellow: '#7d4e00', brightBlue: '#218bff', brightMagenta: '#a475f9', brightCyan: '#0c7875', brightWhite: '#8c959f', }}, - { id: 'ui-pure-white', name: 'Pure White (UI Match)', type: 'light', colors: { + { id: 'ui-pure-white', name: 'Pure White', type: 'light', colors: { background: '#ffffff', foreground: '#24292f', cursor: '#0969da', selection: '#add6ff', black: '#24292f', red: '#cf222e', green: '#116329', yellow: '#9a6700', blue: '#0969da', magenta: '#8250df', cyan: '#0e7574', white: '#6e7781', brightBlack: '#57606a', brightRed: '#a40e26', brightGreen: '#1a7f37', brightYellow: '#7d4e00', brightBlue: '#218bff', brightMagenta: '#a475f9', brightCyan: '#0c7875', brightWhite: '#8c959f', }}, - { id: 'ui-ivory', name: 'Ivory (UI Match)', type: 'light', colors: { + { id: 'ui-ivory', name: 'Ivory', type: 'light', colors: { background: '#f7f4ed', foreground: '#24292f', cursor: '#b45309', selection: '#fde68a', black: '#24292f', red: '#cf222e', green: '#116329', yellow: '#9a6700', blue: '#0969da', magenta: '#8250df', cyan: '#0e7574', white: '#6e7781', brightBlack: '#57606a', brightRed: '#a40e26', brightGreen: '#1a7f37', brightYellow: '#7d4e00', brightBlue: '#218bff', brightMagenta: '#a475f9', brightCyan: '#0c7875', brightWhite: '#8c959f', }}, - { id: 'ui-mist', name: 'Mist (UI Match)', type: 'light', colors: { + { id: 'ui-mist', name: 'Mist', type: 'light', colors: { background: '#f6f7f9', foreground: '#24292f', cursor: '#0891b2', selection: '#a5f3fc', black: '#24292f', red: '#cf222e', green: '#116329', yellow: '#9a6700', blue: '#0969da', magenta: '#8250df', cyan: '#0e7574', white: '#6e7781', brightBlack: '#57606a', brightRed: '#a40e26', brightGreen: '#1a7f37', brightYellow: '#7d4e00', brightBlue: '#218bff', brightMagenta: '#a475f9', brightCyan: '#0c7875', brightWhite: '#8c959f', }}, - { id: 'ui-mint', name: 'Mint (UI Match)', type: 'light', colors: { + { id: 'ui-mint', name: 'Mint', type: 'light', colors: { background: '#f2f8f5', foreground: '#24292f', cursor: '#059669', selection: '#a7f3d0', black: '#24292f', red: '#cf222e', green: '#116329', yellow: '#9a6700', blue: '#0969da', magenta: '#8250df', cyan: '#0e7574', white: '#6e7781', brightBlack: '#57606a', brightRed: '#a40e26', brightGreen: '#1a7f37', brightYellow: '#7d4e00', brightBlue: '#218bff', brightMagenta: '#a475f9', brightCyan: '#0c7875', brightWhite: '#8c959f', }}, - { id: 'ui-sand', name: 'Sand (UI Match)', type: 'light', colors: { + { id: 'ui-sand', name: 'Sand', type: 'light', colors: { background: '#f4f0eb', foreground: '#24292f', cursor: '#c2410c', selection: '#fed7aa', black: '#24292f', red: '#cf222e', green: '#116329', yellow: '#9a6700', blue: '#0969da', magenta: '#8250df', cyan: '#0e7574', white: '#6e7781', brightBlack: '#57606a', brightRed: '#a40e26', brightGreen: '#1a7f37', brightYellow: '#7d4e00', brightBlue: '#218bff', brightMagenta: '#a475f9', brightCyan: '#0c7875', brightWhite: '#8c959f', }}, - { id: 'ui-lavender', name: 'Lavender (UI Match)', type: 'light', colors: { + { id: 'ui-lavender', name: 'Lavender', type: 'light', colors: { background: '#f7f5fa', foreground: '#24292f', cursor: '#7c3aed', selection: '#ddd6fe', black: '#24292f', red: '#cf222e', green: '#116329', yellow: '#9a6700', blue: '#0969da', magenta: '#8250df', cyan: '#0e7574', white: '#6e7781', From 99f4d4b5c0b906a62750798ff446528d386f8658 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 21:44:20 +0800 Subject: [PATCH 103/228] Optimize terminal theme lookup paths --- application/state/settingsTerminalTheme.ts | 8 +-- components/Terminal.tsx | 4 +- components/terminal/ThemeSidePanel.tsx | 51 +++++++++++-------- .../useTerminalThemePanelState.ts | 10 ++-- infrastructure/config/terminalThemes.ts | 4 ++ 5 files changed, 44 insertions(+), 33 deletions(-) diff --git a/application/state/settingsTerminalTheme.ts b/application/state/settingsTerminalTheme.ts index 5a523bdd6..68cb523d4 100644 --- a/application/state/settingsTerminalTheme.ts +++ b/application/state/settingsTerminalTheme.ts @@ -1,5 +1,5 @@ import type { TerminalTheme } from '../../domain/models'; -import { TERMINAL_THEMES } from '../../infrastructure/config/terminalThemes'; +import { TERMINAL_THEMES, getBuiltinTerminalThemeById } from '../../infrastructure/config/terminalThemes'; import { applyCustomAccentToTerminalTheme, resolveFollowedTerminalThemeId, @@ -38,7 +38,7 @@ export function resolveCurrentTerminalTheme({ darkUiThemeId, fallbackThemeId: terminalThemeId, }); - const followed = TERMINAL_THEMES.find(t => t.id === followedId) + const followed = getBuiltinTerminalThemeById(followedId) || customThemes.find(t => t.id === followedId); if (followed) { return applyCustomAccentToTerminalTheme(followed, accentMode, customAccent); @@ -52,9 +52,9 @@ export function resolveCurrentTerminalTheme({ darkUiThemeId, fallbackThemeId: terminalThemeId, }); - const baseTheme = TERMINAL_THEMES.find(t => t.id === manualThemeId) + const baseTheme = getBuiltinTerminalThemeById(manualThemeId) || customThemes.find(t => t.id === manualThemeId) - || TERMINAL_THEMES.find(t => t.id === terminalThemeId) + || getBuiltinTerminalThemeById(terminalThemeId) || customThemes.find(t => t.id === terminalThemeId) || TERMINAL_THEMES[0]; return applyCustomAccentToTerminalTheme(baseTheme, accentMode, customAccent); diff --git a/components/Terminal.tsx b/components/Terminal.tsx index 0e72321d8..b5ba2857e 100644 --- a/components/Terminal.tsx +++ b/components/Terminal.tsx @@ -46,7 +46,7 @@ import { toast } from "./ui/toast"; import { useAvailableFonts } from "../application/state/fontStore"; import { composeFontFamilyStack, type SupportedPlatform } from "../infrastructure/config/cjkFonts"; import { resolveTerminalFontFamilyId } from "../infrastructure/config/fonts"; -import { TERMINAL_THEMES } from "../infrastructure/config/terminalThemes"; +import { getBuiltinTerminalThemeById } from "../infrastructure/config/terminalThemes"; import { useCustomThemes } from "../application/state/customThemeStore"; import { TerminalConnectionDialog } from "./terminal/TerminalConnectionDialog"; @@ -867,7 +867,7 @@ const TerminalComponent: React.FC = ({ ); let baseTheme = terminalTheme; if (themeId) { - const hostTheme = TERMINAL_THEMES.find((t) => t.id === themeId) + const hostTheme = getBuiltinTerminalThemeById(themeId) || customThemes.find((t) => t.id === themeId); if (hostTheme) baseTheme = hostTheme; } diff --git a/components/terminal/ThemeSidePanel.tsx b/components/terminal/ThemeSidePanel.tsx index cfe3228b6..01c169b99 100644 --- a/components/terminal/ThemeSidePanel.tsx +++ b/components/terminal/ThemeSidePanel.tsx @@ -10,7 +10,7 @@ import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from ' import { Check, Download, Minus, Palette, Pencil, Plus, Sparkles, Type } from 'lucide-react'; import { useI18n } from '../../application/i18n/I18nProvider'; import { useAvailableFonts } from '../../application/state/fontStore'; -import { TERMINAL_THEMES, TerminalThemeConfig, USER_VISIBLE_TERMINAL_THEMES, isUiMatchTerminalThemeId } from '../../infrastructure/config/terminalThemes'; +import { TERMINAL_THEMES, TerminalThemeConfig, USER_VISIBLE_TERMINAL_THEMES, getBuiltinTerminalThemeById, isUiMatchTerminalThemeId } from '../../infrastructure/config/terminalThemes'; import { MIN_FONT_SIZE, MAX_FONT_SIZE, TerminalFont } from '../../infrastructure/config/fonts'; import { useCustomThemes, useCustomThemeActions } from '../../application/state/customThemeStore'; import { parseItermcolors } from '../../infrastructure/parsers/itermcolorsParser'; @@ -194,23 +194,36 @@ const ThemeSidePanelInner: React.FC = ({ } }, [activeTab, followAppTerminalTheme]); - const allThemes = useMemo( - () => [...TERMINAL_THEMES, ...customThemes], - [customThemes] + const customThemeById = useMemo( + () => new Map(customThemes.map((theme) => [theme.id, theme])), + [customThemes], ); + const fontById = useMemo( + () => new Map(availableFonts.map((font) => [font.id, font])), + [availableFonts], + ); + const getThemeById = useCallback((themeId: string): TerminalTheme | undefined => + getBuiltinTerminalThemeById(themeId) ?? customThemeById.get(themeId), + [customThemeById]); const globalTheme = useMemo( - () => allThemes.find((theme) => theme.id === globalThemeId) || TERMINAL_THEMES[0], - [allThemes, globalThemeId], + () => getThemeById(globalThemeId) || TERMINAL_THEMES[0], + [getThemeById, globalThemeId], ); const hiddenSelectedTheme = useMemo( () => (isUiMatchTerminalThemeId(currentThemeId) - ? TERMINAL_THEMES.find((theme) => theme.id === currentThemeId) || null + ? getBuiltinTerminalThemeById(currentThemeId) || null : null), [currentThemeId], ); const globalFont = useMemo( - () => availableFonts.find((font) => font.id === globalFontFamilyId) || availableFonts[0], - [availableFonts, globalFontFamilyId], + () => fontById.get(globalFontFamilyId) || availableFonts[0], + [availableFonts, fontById, globalFontFamilyId], + ); + const builtinThemes = useMemo( + () => (followAppTerminalTheme + ? TERMINAL_THEMES.filter((theme) => isFollowAppTerminalThemeId(theme.id)) + : USER_VISIBLE_TERMINAL_THEMES), + [followAppTerminalTheme], ); const handleThemeSelect = useCallback((themeId: string) => { @@ -228,7 +241,7 @@ const ThemeSidePanelInner: React.FC = ({ }, [currentFontSize, onFontSizeChange]); const handleNewTheme = useCallback(() => { - const base = allThemes.find(t => t.id === currentThemeId) || TERMINAL_THEMES[0]; + const base = getThemeById(currentThemeId) || TERMINAL_THEMES[0]; const newTheme: TerminalTheme = { ...base, id: `custom-${Date.now()}`, @@ -238,7 +251,7 @@ const ThemeSidePanelInner: React.FC = ({ }; setEditingTheme(newTheme); setIsNewTheme(true); - }, [currentThemeId, allThemes]); + }, [currentThemeId, getThemeById]); const handleImportFile = useCallback(() => { fileInputRef.current?.click(); @@ -265,12 +278,12 @@ const ThemeSidePanelInner: React.FC = ({ }, [addTheme, onThemeChange, t]); const handleEditTheme = useCallback((themeId: string) => { - const theme = customThemes.find(t => t.id === themeId); + const theme = customThemeById.get(themeId); if (theme) { setEditingTheme({ ...theme, colors: { ...theme.colors } }); setIsNewTheme(false); } - }, [customThemes]); + }, [customThemeById]); const handleEditorDelete = useCallback((themeId: string) => { deleteTheme(themeId); @@ -283,11 +296,9 @@ const ThemeSidePanelInner: React.FC = ({ if (!isVisible) return null; - const builtinThemes = followAppTerminalTheme - ? TERMINAL_THEMES.filter((theme) => isFollowAppTerminalThemeId(theme.id)) - : USER_VISIBLE_TERMINAL_THEMES; - - const footerLabel = `${allThemes.find(t => t.id === currentThemeId)?.name ?? currentThemeId} • ${availableFonts.find(f => f.id === currentFontFamilyId)?.name ?? currentFontFamilyId} • ${currentFontSize}px • ${currentFontWeight}`; + const footerThemeName = getThemeById(currentThemeId)?.name ?? currentThemeId; + const footerFontName = fontById.get(currentFontFamilyId)?.name ?? currentFontFamilyId; + const footerLabel = `${footerThemeName} • ${footerFontName} • ${currentFontSize}px • ${currentFontWeight}`; const panelVars = { ['--terminal-panel-bg' as never]: previewColors?.background ?? 'var(--background)', ['--terminal-panel-fg' as never]: previewColors?.foreground ?? 'var(--foreground)', @@ -297,10 +308,6 @@ const ThemeSidePanelInner: React.FC = ({ ['--terminal-panel-active' as never]: 'color-mix(in srgb, var(--terminal-panel-fg) 16%, var(--terminal-panel-bg) 84%)', } as React.CSSProperties; - if (!isVisible) { - return null; - } - return ( <>
(`[data-session-id="${sessionId}"]`); - const baseTheme = TERMINAL_THEMES.find((entry) => entry.id === themeId) + const baseTheme = getBuiltinTerminalThemeById(themeId) || customThemes.find((entry) => entry.id === themeId); if (!pane || !baseTheme) { clearTerminalPreviewVars(sessionId); @@ -202,7 +202,7 @@ export function useTerminalThemePanelState({ clearHostTreePreviewVars(); return; } - const baseTheme = TERMINAL_THEMES.find((entry) => entry.id === themeId) + const baseTheme = getBuiltinTerminalThemeById(themeId) || customThemes.find((entry) => entry.id === themeId); if (!baseTheme) { clearHostTreePreviewVars(); @@ -218,7 +218,7 @@ export function useTerminalThemePanelState({ return; } const tabsRoot = document.querySelector('[data-top-tabs-root]'); - const baseTheme = TERMINAL_THEMES.find((entry) => entry.id === themeId) + const baseTheme = getBuiltinTerminalThemeById(themeId) || customThemes.find((entry) => entry.id === themeId); if (!tabsRoot || !baseTheme) { clearTopTabsPreviewVars(); @@ -345,7 +345,7 @@ export function useTerminalThemePanelState({ const resolvedPreviewTheme = useMemo(() => { const themeId = previewedOrVisibleThemeId; - const baseTheme = TERMINAL_THEMES.find((theme) => theme.id === themeId) + const baseTheme = getBuiltinTerminalThemeById(themeId) || customThemes.find((theme) => theme.id === themeId) || terminalTheme; return applyCustomAccentToTerminalTheme(baseTheme, accentMode, customAccent); diff --git a/infrastructure/config/terminalThemes.ts b/infrastructure/config/terminalThemes.ts index 30d616aae..0309f00f8 100755 --- a/infrastructure/config/terminalThemes.ts +++ b/infrastructure/config/terminalThemes.ts @@ -35,6 +35,10 @@ export const TERMINAL_THEMES: TerminalTheme[] = [ ...extraTerminalThemes, ]; +const TERMINAL_THEME_BY_ID = new Map(TERMINAL_THEMES.map((theme) => [theme.id, theme])); + +export const getBuiltinTerminalThemeById = (themeId: string): TerminalTheme | undefined => + TERMINAL_THEME_BY_ID.get(themeId); export const isUiMatchTerminalThemeId = (themeId: string): boolean => UI_MATCH_TERMINAL_THEME_IDS.has(themeId); From 7d321a4f03f3f4348b25bc357009b9c9b80b6db7 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 26 Jun 2026 22:02:41 +0800 Subject: [PATCH 104/228] Hide terminal theme preview when following app theme --- application/i18n/locales/en/core.ts | 1 - application/i18n/locales/ru/core.ts | 1 - application/i18n/locales/zh-CN/terminal.ts | 1 - .../settings/tabs/SettingsTerminalTab.test.ts | 6 ++--- .../settings/tabs/SettingsTerminalTab.tsx | 22 ++++--------------- 5 files changed, 7 insertions(+), 24 deletions(-) diff --git a/application/i18n/locales/en/core.ts b/application/i18n/locales/en/core.ts index 3f7e99e9b..a207e412e 100644 --- a/application/i18n/locales/en/core.ts +++ b/application/i18n/locales/en/core.ts @@ -295,7 +295,6 @@ export const enCoreMessages: Messages = { 'settings.terminal.theme.selectButton': 'Select Theme', 'settings.terminal.theme.followApp': 'Follow Application Theme', 'settings.terminal.theme.followApp.desc': 'Automatically match the terminal background to the current app theme for a seamless look.', - 'settings.terminal.theme.followingTheme': 'Current automatic terminal theme', 'settings.terminal.theme.darkTheme': 'Dark mode terminal theme', 'settings.terminal.theme.lightTheme': 'Light mode terminal theme', 'settings.terminal.theme.auto': 'Auto (match app theme)', diff --git a/application/i18n/locales/ru/core.ts b/application/i18n/locales/ru/core.ts index a00ad7163..4804a74a3 100644 --- a/application/i18n/locales/ru/core.ts +++ b/application/i18n/locales/ru/core.ts @@ -284,7 +284,6 @@ export const ruCoreMessages: Messages = { 'settings.terminal.theme.selectButton': 'Выбрать тему', 'settings.terminal.theme.followApp': 'Следовать теме приложения', 'settings.terminal.theme.followApp.desc': 'Автоматически подбирать фон терминала под текущую тему приложения для более цельного вида.', - 'settings.terminal.theme.followingTheme': 'Текущая автоматическая тема терминала', 'settings.terminal.theme.darkTheme': 'Тема терминала для тёмного режима', 'settings.terminal.theme.lightTheme': 'Тема терминала для светлого режима', 'settings.terminal.theme.auto': 'Авто (как тема приложения)', diff --git a/application/i18n/locales/zh-CN/terminal.ts b/application/i18n/locales/zh-CN/terminal.ts index 4fa55751a..6675657b5 100644 --- a/application/i18n/locales/zh-CN/terminal.ts +++ b/application/i18n/locales/zh-CN/terminal.ts @@ -178,7 +178,6 @@ export const zhCNTerminalMessages: Messages = { 'settings.terminal.theme.selectButton': '选择主题', 'settings.terminal.theme.followApp': '跟随应用主题', 'settings.terminal.theme.followApp.desc': '终端背景色自动匹配当前应用主题,保持视觉一致性。', - 'settings.terminal.theme.followingTheme': '当前自动终端主题', 'settings.terminal.theme.darkTheme': '深色模式终端主题', 'settings.terminal.theme.lightTheme': '浅色模式终端主题', 'settings.terminal.theme.auto': '自动(跟随界面主题)', diff --git a/components/settings/tabs/SettingsTerminalTab.test.ts b/components/settings/tabs/SettingsTerminalTab.test.ts index 908ef0954..e26257973 100644 --- a/components/settings/tabs/SettingsTerminalTab.test.ts +++ b/components/settings/tabs/SettingsTerminalTab.test.ts @@ -4,9 +4,9 @@ import test from "node:test"; const source = readFileSync(new URL("./SettingsTerminalTab.tsx", import.meta.url), "utf8"); -test("terminal settings keep the global theme picker visible while following app theme", () => { - assert.doesNotMatch(source, /\{followAppTerminalTheme \? \(/); - assert.match(source, /terminal\.themeModal\.globalTheme/); +test("terminal settings hide terminal theme pickers while following app theme", () => { + assert.match(source, /\{!followAppTerminalTheme && \(/); + assert.doesNotMatch(source, /settings\.terminal\.theme\.followingTheme/); }); test("terminal settings expose host key verification toggle", () => { diff --git a/components/settings/tabs/SettingsTerminalTab.tsx b/components/settings/tabs/SettingsTerminalTab.tsx index 91d43f43f..1491b9d45 100644 --- a/components/settings/tabs/SettingsTerminalTab.tsx +++ b/components/settings/tabs/SettingsTerminalTab.tsx @@ -356,21 +356,8 @@ function SettingsTerminalTab(props: { />
-
- {followAppTerminalTheme && ( -
-
- {t("settings.terminal.theme.followingTheme")} -
- -
- )} - {!followAppTerminalTheme && ( - <> + {!followAppTerminalTheme && ( +
{t("settings.terminal.theme.darkTheme")} @@ -391,9 +378,8 @@ function SettingsTerminalTab(props: { buttonLabel={t("settings.terminal.theme.selectButton")} />
- - )} -
+
+ )} Date: Fri, 26 Jun 2026 22:09:47 +0800 Subject: [PATCH 105/228] Prevent hidden vault header actions retaining focus --- components/VaultViewLayout.test.ts | 8 ++++++++ components/vault/VaultViewLayout.tsx | 23 +++++++++++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/components/VaultViewLayout.test.ts b/components/VaultViewLayout.test.ts index 107688916..297de1e24 100644 --- a/components/VaultViewLayout.test.ts +++ b/components/VaultViewLayout.test.ts @@ -14,3 +14,11 @@ test("vault notes stay mounted while switching sections", () => { assert.match(vaultViewLayoutSource, /currentSection !== "notes" && "hidden"/); assert.doesNotMatch(vaultViewLayoutSource, /currentSection === "notes" && \(\s*