Compare commits

...
Author SHA1 Message Date
陈大猫 04249a822c fix(plugins): acknowledge lifecycle calls when runtime is disabled 2026-11-21 19:59:42 +08:00
陈大猫 a23868ee88 fix(ai): reject invalid IPv6 External MCP listen addresses in settings (#4295)
Fixes #4293
2026-11-21 19:52:28 +08:00
陈大猫andCodex 6829f9b082 fix(notes): collapse markdown toolbar overflow instead of scrolling (#4294)
Co-authored-by: Codex <codex@openai.com>
2026-11-21 19:52:21 +08:00
陈大猫 519c463048 Merge pull request #4291 from binaricat/fix/4275-retain-configured-default-agent
fix(ai): retain the configured default agent when its probe fails
2026-11-21 17:56:30 +08:00
陈大猫 14767f6a48 Merge pull request #4264 from binaricat/fix/4017-isolate-unpackaged-profile
fix(electron): isolate unpackaged app profiles
2026-11-21 17:46:00 +08:00
陈大猫 e185306e50 Merge pull request #4265 from binaricat/fix/3570-folder-partial-pause
fix(sftp): show folder pause failures without resuming siblings
2026-11-21 17:41:32 +08:00
陈大猫 b864bf55b6 fix(ai): retain configured default agent during failed discovery 2026-11-21 17:38:41 +08:00
陈大猫 9c49a07e16 Merge pull request #4290 from binaricat/fix/4262-compose-right-click
fix(terminal): keep composer right-click out of the live terminal
2026-11-21 17:04:47 +08:00
陈大猫 c5a855d885 Merge pull request #4289 from binaricat/fix/4261-rtl-pane-guard-8e86279
fix(terminal): render RTL text without destabilizing WebGL (#4261)
2026-11-21 16:52:50 +08:00
陈大猫 a2e04556b7 Merge pull request #4216 from binaricat/fix/4214-codebuddy-empty-tools
fix(ai): do not pass empty CodeBuddy tools whitelist that hides MCP tools
2026-11-21 16:51:55 +08:00
陈大猫 0fbf1cdc14 fix(terminal): fit wide RTL runs without clipping glyphs 2026-11-21 16:08:53 +08:00
陈大猫 7bbff7ce6e fix(terminal): preserve RTL DOM cell widths and detect astral RTL 2026-11-21 15:49:45 +08:00
陈大猫 57227dfe1b Merge pull request #4288 from binaricat/fix/release-hide-plugin-platform
fix(release): temporarily hide the plugin platform
2026-11-21 15:35:43 +08:00
陈大猫 470628b1a3 fix(terminal): keep composer right-click out of the live terminal
Address the unintended paste described in #4262.
2026-11-21 13:55:51 +08:00
陈大猫 ef99e0daf7 Merge pull request #4182 from binaricat/fix/4181-mcp-session-reconnect-discoverability
fix(mcp): advertise sessions reconnect tools to agents
2026-11-21 13:41:12 +08:00
陈大猫 18a9000278 Merge pull request #4225 from binaricat/fix/4224-max-iteration-visible-continue
fix(ai): surface max-iteration stop with a Continue action (Fixes #4224)
2026-11-21 13:41:06 +08:00
陈大猫 19ff28528d fix(ai): keep CodeBuddy MCP discovery isolated 2026-11-21 12:17:23 +08:00
陈大猫 8e862798e4 fix(terminal): keep RTL shaping off the WebGL atlas
Preserve the original RTL implementation and keep affected panes on the DOM renderer to avoid an oversized WebGL glyph allocation. Unchanged ASCII panes retain their renderer.
2026-11-21 11:02:05 +08:00
陈大猫 5b9d5351d7 fix(release): hide the plugin platform by default 2026-11-21 10:31:43 +08:00
Serag AhmedandClaude Opus 5.5 112bab7292 fix(terminal): draw RTL text in display order with joined letters
xterm.js has no bidi support and draws every cell on its own, so Arabic,
Persian and Hebrew words came out reversed and Arabic letters unjoined
(#4261).

Register a character joiner that marks the parts of each line the Unicode
Bidirectional Algorithm (bidi-js) puts at a right-to-left or number level
in a left-to-right paragraph. Both the WebGL and DOM renderers draw a
joined range as one string through the browser's text engine, which
orders it, shapes the letters and mirrors brackets. The buffer is
unchanged, so selection, copy, search and cursor positions still use the
logical text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:50:08 +03:00
陈大猫 ed9da31034 fix(terminal): keep Shift+Insert as paste when Kitty keyboard is active
Related #4279

When a TUI such as Claude Code enables the Kitty keyboard protocol, Shift+Insert was encoded as an Insert key (CSI 2;2~) instead of pasting. Netcatty always constructs xterm with Kitty support, so this happened even with the user Kitty setting off.

This claims bare Shift+Insert as clipboard paste (the same onPaste path as the paste keybinding) after user/snippet shortcuts and before Kitty/Win32 encoding.

This does not change right-click / context-menu behavior while mouse tracking is active.
2026-11-20 15:53:40 +08:00
陈大猫 3d302e2456 fix(ai): recognize bracket prompts with a time field as idle (#4277)
Fixes #4276
2026-11-20 12:47:23 +08:00
GOUKI9999 f987341bf2 fix(ai): preserve saved harness paths on failed probes 2026-11-19 16:20:43 +08:00
陈大猫 5e4195bf7f fix(ui): snap and thicken magnified pane chrome on low-DPR displays (#4270)
Related #4168

On ~1–1.2× displays the 1px rounded accent border around a magnified
pane drops out at the corners, and a box that is not aligned to the
device-pixel grid turns the stroke into a faint, doubled hairline.

Snap the magnified terminal overlay (after the 12px inset) to integer
device pixels, and use a 2px accent stroke when devicePixelRatio is
below 1.5 on both the terminal and side-panel chrome. Higher-DPR
displays keep the existing 1px stroke.
2026-11-18 23:23:21 +08:00
陈大猫 9c292460e3 fix(ai): treat models-list 404 as a warning and send Anthropic Bearer auth (#4269)
* fix(ai): treat models-list 404 as a warning and send Anthropic Bearer on custom bases

Custom OpenAI-compatible gateways that omit a /models listing were
shown as a hard detect failure on HTTP 404. Treat 404 as a warning.
Official Anthropic stays on x-api-key only; custom Anthropic-compat
bases also send Authorization: Bearer so Agent Plan and similar
proxies authenticate.

* fix(ai): use the versioned Ark Agent Plan messages endpoint
2026-11-18 19:21:16 +08:00
陈大猫 5e1bdd85d8 fix(sftp): preserve settled folder pause failure on stale owner publish 2026-11-18 15:18:54 +08:00
陈大猫 450d1df2e7 fix(sftp): keep partial pause feedback consistent across transfer views 2026-11-18 15:07:28 +08:00
陈大猫 3ed22954db fix(sftp): preserve partial folder pause results 2026-11-18 14:44:35 +08:00
陈大猫 3260bf4206 fix(electron): isolate unpackaged app profiles 2026-11-18 14:05:02 +08:00
陈大猫 8b3832feef fix(notes): keep MDX link dialog inside the editor container (#4258)
MDXEditor portals the link preview toolbar to document.body by default.
Notes stays retained-mounted and is only CSS-hidden, so the toolbar was
left floating over other vault pages and terminal sessions.

Fixes #4257
2026-11-17 14:53:32 +08:00
github-actions[bot]andgithub-actions[bot] 83d0d5f949 chore: update star history charts [skip ci] (#4247)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-11-16 00:09:01 +00:00
GOUKI9999and陈大猫 0a4ff8875f feat(ai): make unrecognized shell prompts an actionable unknown state instead of a terminal block (#4198)
* feat(ai): make unrecognized shell prompts an actionable unknown state instead of a terminal block

Composes #3935 (advisory semantics), #4110 (OSC 133 marker authority + pending-input guards) and #4195 (asymmetric harm / state-model proposal). An unrecognized prompt on a live shell now yields a non-terminal SHELL_READINESS_UNKNOWN result with a read-only/confirm viable path; PROVEN-busy states keep the exact hard SHELL_NOT_READY block. Never blind-types into unknown; never claims ready without evidence.

* fix(ai): propagate unknown readiness code through the active Catty SDK path

---------

Co-authored-by: 陈大猫 <16399091+binaricat@users.noreply.github.com>
2026-11-15 01:27:43 +08:00
rnaranyand陈大猫 8433302959 fix(i18n): complete zh-TW strings and unify Taiwan terminology (#4185)
* fix(i18n): complete zh-TW strings and unify Taiwan terminology

- Translate the 19 settings.plugins.sources.* keys that were still in
  Simplified Chinese, and add the 9 missing ai.providers.headers.* keys.
- Add the two zh-CN keys the dialog already looked up (createWorkspace.title,
  field.selectHosts) so those labels no longer fall back to English.
- Keep {{name}} / {{name:default}} literal in snippets.field.variablesHelp;
  the previous text translated the metavariable names.
- Unify zh-TW terms in the shipped UI: 外掛, 市集, 行程, 指令碼, 金鑰,
  佔位符, 檔案系統, 網路, 資料, 使用者, 預設.
- Tighten localeParityLocales: zh-CN and zh-TW are at full parity, so move
  them out of LOCALES_PENDING_PARITY and check interpolation placeholders for
  every translated locale, not just es.

* fix(i18n): finish zh-TW plugin wording and :default placeholders

Review follow-up on the terminology pass:

- Replace the remaining mainland terms on the plugin settings screen:
  導入→匯入, 卸載→解除安裝, 存儲→儲存, 遠程→遠端, 加載→載入. 網路設備 is
  correct Taiwan usage and stays.
- Widen the interpolation token regex so {{name:default}} is compared too;
  the previous \w+ form silently ignored the colon and could not catch a
  translated metavariable. Add a direct assertion for that form.

* test(ci): pin Vite contract probe to numeric loopback

---------

Co-authored-by: 陈大猫 <16399091+binaricat@users.noreply.github.com>
2026-11-14 23:37:53 +08:00
陈大猫 51cb14955c fix(logs): finalize session logs on quit and pre-connect close (#4236)
* fix(logs): finalize session logs when the app quits without closing tabs

Fixes #4235

* fix(logs): finalize logs when unconnected sessions close

Capture never-connected terminal logs at explicit session removal, including empty buffers, without finalizing logs during runtime remounts. Cover tab close, failed-dialog close, batch close, and workspace close with persistence regressions.

Fixes #4235

* fix(logs): tolerate unavailable finalization IPC

Preserve window close and layout saves when session-log finalization IPC cannot be set up, and clear its timeout on setup failures.

Follow-up for #4235 / PR #4236.
2026-11-14 21:36:08 +08:00
陈大猫 1d5cef09ec fix(settings): index later-added settings in search catalog (Fixes #4230) (#4232)
* fix(settings): index later-added settings in search catalog

Fixes #4230

Follow-up after #4231. Settings search still missed later-added
rows such as Appearance "Code font" (代码字体) and System session
log "Add timestamps" (时间戳), which already rendered in their
tabs. Index those destinations and other visible setting rows
that had the same catalog/anchor omission.

* fix(settings): fall back to visible parent when search target is gated
2026-11-14 21:30:27 +08:00
陈大猫 17d53152ec merge(main): pick up plugin-contract CI hang fix from #4240 2026-11-14 20:42:36 +08:00
陈大猫 cf7f998689 fix(ci): prevent plugin-contract lint-and-test hang (#4240) 2026-11-14 20:17:13 +08:00
陈大猫andCodex db3a9e88e2 fix(terminal): cap WebGL contexts for visible split panes (Fixes #4128) (#4239)
The #4122 budget of 12 only released hidden panes, so 17+ visible
splits still crossed Chromium’s 16-context limit and the 50ms
rebuild avalanched into white panes until the DOM breaker tripped.

Refuse new visible contexts when visible holders fill the cap while
preserving recently hidden holders during the tab-flip grace period.
Cover acquisition limits, missed visibility syncs, and recovery at cap.

Co-authored-by: Codex <codex@openai.com>
2026-11-14 18:21:32 +08:00
陈大猫andCodex 65435c06f5 fix(x11): hide fd-bearing X11 extensions on byte-only forwards (Fixes #4200) (#4238)
Clear QueryExtension present for DRI3 and MIT-SHM on built-in X11 forwards so clients avoid SCM_RIGHTS replies that the SSH byte stream cannot transport. Preserve framing, byte order, sequence isolation and cookie rewriting.

Strip AppImage ARGV0 from local shell PTY environments so zsh preserves ssh argv[0] and Xorg recognizes system SSH forwarding. Add protocol and environment regression tests. Fixes #4200.

Co-authored-by: Codex <codex@openai.com>
2026-11-14 16:28:28 +08:00
陈大猫 3096f86889 fix(sftp): use remote cp for fresh same-host copies (Fixes #4207) (#4226)
* fix(sftp): use remote cp for fresh same-host copies (Fixes #4207)

Ordinary SFTP tasks were marked resumable, which skipped the existing file and directory cp optimizations. Select the non-resumable route only when creating fresh matching-host copies with eligible encodings, keeping transfer-center rows and recursive children consistent. Existing checkpointed transfers retain their saved resumable path; failed cp attempts retain the download/upload fallback.

* fix(sftp): skip same-host directory cp when auto encoding resolves to non-UTF-8

* fix(sftp): preserve dest mode when same-host cp replaces a file

* fix(sftp): skip same-host cp for symlinks and directory merges

* test(sftp): mock missing dest in same-host cp cache fixture

* fix(sftp): expose lstat on session-backed copy clients
2026-11-13 17:24:27 +08:00
陈大猫 94f8bd9bc7 fix(ai): recognize Enter-PSSession remoting prompts as idle (#4229)
Fixes #4228

PowerShell remoting (Enter-PSSession / WinRM) prefixes the default
prompt with [ComputerName]: , which POWERSHELL_PROMPT_PATTERN missed,
so the readiness gate returned SHELL_NOT_READY and never sent the
command. Accept one or more [token]: prefixes before the existing
PS ...> shape, including [DBG]:.
2026-11-13 16:47:59 +08:00
陈大猫 5cd42cb518 fix(settings): include folder compression in settings search (#4231)
Fixes #4230

Settings search uses a static catalog. The SFTP "Enable folder
compression" row was already in the tab but missing from the catalog
and had no anchor, so queries such as 压缩 showed no matches. Index
that destination, plus the skip-unchanged and SSH keep-alive rows in
the same tab that had the same omission.
2026-11-13 16:30:21 +08:00
陈大猫 f05ea0c9b7 fix(ai): surface max-iteration stop with a Continue action (Fixes #4224) 2026-11-13 12:04:16 +08:00
陈大猫 bb81b72ff0 fix(ai): avoid empty CodeBuddy tools whitelist that hides MCP tools (#4214)
Omit tools in MCP mode and explicitly disallow CodeBuddy built-ins, preserving injected MCP visibility and the skills-mode Bash whitelist.

Fixes #4214
2026-11-12 14:13:14 +08:00
陈大猫 d0fffac598 chore: retrigger CI after plugin-contract runner cancel 2026-11-08 09:48:34 +08:00
陈大猫 106e39a797 chore: retrigger CI after lint-and-test runner shutdown (exit 143) 2026-11-08 09:23:48 +08:00
陈大猫 3bf4c9df1a fix(mcp): advertise sessions reconnect tools to agents 2026-11-08 01:06:02 +08:00
162 changed files with 6329 additions and 755 deletions

No files matched your search

+17
View File
@@ -1220,6 +1220,23 @@ export function handleConnectToHostImpl(getCtx: AppContextGetter, host: Host, hi
}
}
export function startRestoredSessionConnectionLogImpl(getCtx: AppContextGetter, session: TerminalSession) {
const { addConnectionLog, systemInfoRef } = getCtx();
const { username, hostname } = systemInfoRef.current;
addConnectionLog({
sessionId: session.id,
hostId: session.hostId,
hostLabel: session.hostLabel,
hostname: session.hostname,
username: session.username,
protocol: session.protocol || 'ssh',
startTime: Date.now(),
localUsername: username,
localHostname: hostname,
saved: false,
});
}
export async function handleTerminalDataCaptureImpl(getCtx: AppContextGetter, sessionId: string, data: string) {
const { IS_DEV, connectionLogs, selectConnectionLogForTerminalDataCapture, sessions, updateConnectionLog } = getCtx();
{
+12 -2
View File
@@ -104,7 +104,7 @@ import { collectSnippetDeleteIds } from '../../domain/snippetSelection.ts';
import { shouldOpenLocalTerminalOnStartup, resolveStartupLandingSetting } from '../../domain/startupLanding';
import { createOpenTerminalQueue } from './openTerminalQueue';
import { useAppStartupEffects } from './useAppStartupEffects';
import { handleTrayJumpToSessionImpl, handleTrayTogglePortForwardImpl, handleTrayPanelConnectImpl, handleTrayPanelConnectRequestImpl, flushQueuedTrayPanelConnectHostsImpl, handleGlobalHotkeyKeyDownImpl, handleEscapeKeyDownImpl, handleKeyboardInteractiveSubmitImpl, handleKeyboardInteractiveCancelImpl, handlePassphraseSubmitImpl, handlePassphraseCancelImpl, handlePassphraseSkipImpl, handleFidoPromptSubmitImpl, handleFidoPromptCancelImpl, createLocalTerminalWithCurrentShellImpl, splitSessionWithCurrentShellImpl, copySessionWithCurrentShellImpl, duplicateSessionWithCurrentShellImpl, copyWorkspaceWithCurrentShellImpl, copySessionToNewWindowWithCurrentShellImpl, confirmIfBusyLocalTerminalImpl, closeTabsBatchImpl, executeHotkeyActionImpl, handleCreateLocalTerminalImpl, handleConnectToHostImpl, handleTerminalDataCaptureImpl, hasMultipleProtocolsImpl, handleHostConnectWithProtocolCheckImpl, handleProtocolSelectImpl, handleRootContextMenuImpl, markForwardedNativeShortcutEvent } from './AppHandlers';
import { handleTrayJumpToSessionImpl, handleTrayTogglePortForwardImpl, handleTrayPanelConnectImpl, handleTrayPanelConnectRequestImpl, flushQueuedTrayPanelConnectHostsImpl, handleGlobalHotkeyKeyDownImpl, handleEscapeKeyDownImpl, handleKeyboardInteractiveSubmitImpl, handleKeyboardInteractiveCancelImpl, handlePassphraseSubmitImpl, handlePassphraseCancelImpl, handlePassphraseSkipImpl, handleFidoPromptSubmitImpl, handleFidoPromptCancelImpl, createLocalTerminalWithCurrentShellImpl, splitSessionWithCurrentShellImpl, copySessionWithCurrentShellImpl, duplicateSessionWithCurrentShellImpl, copyWorkspaceWithCurrentShellImpl, copySessionToNewWindowWithCurrentShellImpl, confirmIfBusyLocalTerminalImpl, closeTabsBatchImpl, executeHotkeyActionImpl, handleCreateLocalTerminalImpl, handleConnectToHostImpl, handleTerminalDataCaptureImpl, startRestoredSessionConnectionLogImpl, hasMultipleProtocolsImpl, handleHostConnectWithProtocolCheckImpl, handleProtocolSelectImpl, handleRootContextMenuImpl, markForwardedNativeShortcutEvent } from './AppHandlers';
type OpenSessionInNewWindowPayload = {
title?: string;
@@ -1895,8 +1895,18 @@ export function AppSideEffects() {
setActiveTabId('vault');
}, [setActiveTabId]);
const restoredSessionLogsStartedRef = useRef(new Set<string>());
// A restored tab retains its session ID, but its previous ConnectionLog is closed.
// Start the new incarnation's log before updateSessionStatus clears restoreState.
// Wrap updateSessionStatus to track lastConnectedAt on successful connection
const handleSessionStatusChange = useCallback((sessionId: string, status: TerminalSession['status']) => {
const session = sessionByIdRef.current.get(sessionId);
if (session?.restoreState === 'restored-disconnected'
&& (status === 'connecting' || status === 'connected')
&& !restoredSessionLogsStartedRef.current.has(sessionId)) {
restoredSessionLogsStartedRef.current.add(sessionId);
startRestoredSessionConnectionLogImpl(() => ({ addConnectionLog, systemInfoRef }), session);
}
updateSessionStatus(sessionId, status);
if (status === 'connected') {
const session = sessionByIdRef.current.get(sessionId);
@@ -1904,7 +1914,7 @@ export function AppSideEffects() {
updateHostLastConnected(session.hostId);
}
}
}, [updateSessionStatus, updateHostLastConnected]);
}, [addConnectionLog, updateSessionStatus, updateHostLastConnected]);
const handleUpdateHostFromTerminal = useCallback((host: TerminalHostUpdate) => {
// Functional update + identity-preserving updateHosts: only the patched
@@ -0,0 +1,206 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { readFileSync } from 'node:fs';
import React, { useEffect, useRef } from 'react';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
import { JSDOM } from 'jsdom';
import { installBrowserLockFixture } from '../testSupport/browserLockFixture';
import { useSessionState } from '../state/useSessionState';
import { captureClosingTerminalSessions, useTerminalSessionCloseCapture } from '../state/terminalSessionCloseCapture';
import { selectConnectionLogForTerminalDataCapture } from '../../domain/connectionLog';
import { createConnectionLogBuffer } from '../../components/terminal/connectionLogBuffer';
import { TerminalConnectionProgress } from '../../components/terminal/TerminalConnectionProgress';
import { I18nProvider } from '../i18n/I18nProvider';
import { handleTerminalDataCaptureImpl } from './AppHandlers';
const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
test('explicit close persists never-connected logs; runtime remounts leave them open', async (t) => {
const dom = new JSDOM('', { url: 'http://localhost' });
const globals = ['window', 'localStorage', 'CustomEvent', 'navigator', 'IS_REACT_ACT_ENVIRONMENT'];
const previous = new Map(globals.map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
Object.defineProperties(globalThis, {
window: { value: dom.window, configurable: true },
localStorage: { value: dom.window.localStorage, configurable: true },
CustomEvent: { value: dom.window.CustomEvent, configurable: true },
IS_REACT_ACT_ENVIRONMENT: { value: true, configurable: true },
});
installBrowserLockFixture();
const { useVaultState } = await import('../state/useVaultState');
try {
for (const scenario of [
{ name: 'tab X before connected, empty buffer', status: 'connecting', data: '' },
{ name: 'failed-dialog close, empty buffer', status: 'disconnected', data: '' },
{ name: 'failed-dialog close preserves buffered diagnostics', status: 'disconnected', data: 'SSH diagnostic\r\n' },
{ name: 'batch close before connected', status: 'connecting', data: '', closeMode: 'batch' },
{ name: 'workspace close before connected', status: 'connecting', data: '', closeMode: 'workspace' },
] as const) {
await t.test(scenario.name, async () => {
let vault!: ReturnType<typeof useVaultState>;
let state!: ReturnType<typeof useSessionState>;
let root: ReactTestRenderer | undefined;
let sessionId!: string;
let logId!: string;
const captures: Promise<void>[] = [];
const capturedData: string[] = [];
function TerminalProbe() {
const hasConnectedRef = useRef(false);
const terminalDataCapturedRef = useRef(false);
const buffer = useRef(createConnectionLogBuffer(10000));
useEffect(() => {
buffer.current.append(scenario.data);
return () => { buffer.current.reset(); };
}, []);
useTerminalSessionCloseCapture({
sessionId, enabled: true, hasConnectedRef, terminalDataCapturedRef,
finalizeTerminalLogData: () => buffer.current.toString(),
onTerminalDataCapture: (id, data, options) => {
assert.equal(options.finalized, true);
assert.ok(state.sessions.some((session) => session.id === id), 'capture starts before removal');
terminalDataCapturedRef.current = true;
capturedData.push(data);
const pending = handleTerminalDataCaptureImpl(() => ({
IS_DEV: false, connectionLogs: vault.connectionLogs, sessions: state.sessions,
selectConnectionLogForTerminalDataCapture, updateConnectionLog: vault.updateConnectionLog,
}), id, data);
captures.push(pending);
return pending;
},
});
return scenario.status === 'disconnected' ? React.createElement(
I18nProvider, { locale: 'en' }, React.createElement(TerminalConnectionProgress, {
status: 'disconnected', error: 'Connection refused', timeLeft: 0,
isCancelling: false, showLogs: false, progressLogs: [],
onCancelConnect: () => {}, onCloseSession: () => state.closeSession(sessionId),
}),
) : null;
}
function Probe({ showTerminal = true }) {
vault = useVaultState();
state = useSessionState({ persistSessionRestore: false });
return showTerminal && state.sessions.some((session) => session.id === sessionId)
? React.createElement(TerminalProbe) : null;
}
const mount = async () => {
await act(async () => { root = create(React.createElement(Probe)); });
for (let attempt = 0; !vault.isInitialized && attempt < 50; attempt++) {
await act(async () => { await tick(); });
}
assert.equal(vault.isInitialized, true);
};
try {
await mount();
await act(async () => { sessionId = state.createLocalTerminal(); });
await act(async () => {
state.updateSessionStatus(sessionId, scenario.status);
const session = state.sessions.find((candidate) => candidate.id === sessionId)!;
logId = vault.addConnectionLog({
sessionId, hostId: session.hostId, hostLabel: session.hostLabel,
hostname: session.hostname, username: session.username,
protocol: session.protocol, startTime: Date.now(),
localUsername: 'local-user', localHostname: 'local-host', saved: false,
});
await vault.updateConnectionLog(logId, {});
});
if ('closeMode' in scenario && scenario.closeMode === 'workspace') {
let otherId!: string;
await act(async () => { otherId = state.createLocalTerminal(); });
await act(async () => { state.createWorkspaceFromSessions(sessionId, otherId, 'right'); });
}
// Recycle the renderer while retaining the session, as with a pane
// remount. Neither disposal nor the replacement runtime may end its log.
await act(async () => { root!.update(React.createElement(Probe, { showTerminal: false })); });
await act(async () => { root!.update(React.createElement(Probe)); });
assert.equal(captures.length, 0);
assert.equal(vault.connectionLogs.find((log) => log.id === logId)?.endTime, undefined);
// Both UI actions converge here. This exercises the actual state
// removal, owning-terminal hook, capture handler and vault persistence.
await act(async () => {
if ('closeMode' in scenario && scenario.closeMode === 'workspace') {
state.closeWorkspace(state.workspaces[0].id);
} else if ('closeMode' in scenario && scenario.closeMode === 'batch') {
state.closeSessions([sessionId]);
} else if (scenario.status === 'disconnected') {
// Click the actual Close button rendered inside the failed dialog.
root!.root.findByType('button').props.onClick();
} else {
state.closeSession(sessionId);
}
await Promise.all(captures);
});
assert.equal(state.sessions.some((session) => session.id === sessionId), false);
assert.deepEqual(capturedData, [scenario.data]);
await act(async () => { state.closeSession(sessionId); });
assert.equal(captures.length, 1, 'removed runtimes must unregister their capture');
await act(async () => { root!.unmount(); });
root = undefined;
await mount();
const persisted = vault.connectionLogs.find((log) => log.id === logId)!;
assert.ok(persisted.endTime, 'a durable endTime must exist even without terminal output');
assert.equal(persisted.terminalData || '', scenario.data);
} finally {
await act(async () => { root?.unmount(); });
}
});
}
} finally {
dom.window.close();
for (const key of globals) {
const descriptor = previous.get(key);
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
}
});
test('close capture skips non-owning, already connected and already captured runtimes', async (t) => {
const previous = Object.getOwnPropertyDescriptor(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { value: true, configurable: true });
try {
for (const scenario of [
{ name: 'attached popup / inactive restored placeholder', enabled: false, connected: false, captured: false },
{ name: 'connected terminal uses existing drain path', enabled: true, connected: true, captured: false },
{ name: 'quit already captured the log', enabled: true, connected: false, captured: true },
]) {
await t.test(scenario.name, async () => {
let calls = 0;
let root!: ReactTestRenderer;
function Probe() {
useTerminalSessionCloseCapture({
sessionId: 'guarded', enabled: scenario.enabled,
hasConnectedRef: useRef(scenario.connected),
terminalDataCapturedRef: useRef(scenario.captured),
finalizeTerminalLogData: () => { calls++; return ''; },
onTerminalDataCapture: () => { calls++; },
});
return null;
}
await act(async () => { root = create(React.createElement(Probe)); });
try {
await act(async () => { captureClosingTerminalSessions(['guarded']); });
assert.equal(calls, 0);
} finally {
await act(async () => { root.unmount(); });
}
});
}
} finally {
if (previous) Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', previous);
else Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
test('both UI close paths reach session removal and Terminal registers the owning capture', () => {
const read = (path: string) => readFileSync(new URL(path, import.meta.url), 'utf8');
const app = read('./AppView.tsx');
assert.match(app, /onCloseSession=\{closeSession\}/);
assert.match(read('../../components/top-tabs/TopTabItems.tsx'), /onClick=\{\(e\) => onCloseSession\(session\.id, e\)\}/);
const terminal = read('../../components/Terminal.tsx');
assert.match(terminal, /useTerminalSessionCloseCapture\(\{\s*sessionId,\s*enabled: !attachExistingSession && restoreState !== "restored-disconnected",\s*hasConnectedRef,\s*terminalDataCapturedRef,\s*finalizeTerminalLogData,\s*onTerminalDataCapture: handleTerminalDataCaptureOnce,/);
const handler = terminal.slice(terminal.indexOf('const handleCloseDisconnectedSession ='), terminal.indexOf('const handleHostKeyClose ='));
assert.match(handler, /onCloseSession\?\.\(sessionId\)/);
assert.match(read('../../components/TerminalLayer.tsx'), /onCloseSession\(sessionId\)/);
assert.match(read('../../components/terminal/TerminalView.tsx'), /onCloseSession: handleCloseDisconnectedSession/);
assert.match(read('../../components/terminal/TerminalConnectionProgress.tsx'), /onClick=\{onCloseSession\}/);
});
@@ -0,0 +1,132 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { readFileSync } from 'node:fs';
import { EventEmitter } from 'node:events';
import React from 'react';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
import { JSDOM } from 'jsdom';
import { installBrowserLockFixture } from '../testSupport/browserLockFixture';
import { withVaultImportLock } from '../state/vaultManagedImportLock';
import { selectConnectionLogForTerminalDataCapture } from '../../domain/connectionLog';
import type { TerminalSession } from '../../domain/models';
import { createConnectionLogBuffer } from '../../components/terminal/connectionLogBuffer';
import { handleTerminalDataCaptureImpl, startRestoredSessionConnectionLogImpl } from './AppHandlers';
import { createPreloadApi } from '../../electron/preload/api.cjs';
import { finalizeSessionLogs } from '../../electron/bridges/sessionLogShutdown.cjs';
const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
test('quit persists replay before acknowledgment; restored reconnect keeps the old log and starts a new one', async () => {
const dom = new JSDOM('', { url: 'http://localhost' });
const globals = ['window', 'localStorage', 'CustomEvent', 'navigator', 'IS_REACT_ACT_ENVIRONMENT'];
const previous = new Map(globals.map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
Object.defineProperties(globalThis, {
window: { value: dom.window, configurable: true },
localStorage: { value: dom.window.localStorage, configurable: true },
CustomEvent: { value: dom.window.CustomEvent, configurable: true },
IS_REACT_ACT_ENVIRONMENT: { value: true, configurable: true },
});
installBrowserLockFixture();
const { useVaultState } = await import('../state/useVaultState');
let vault!: ReturnType<typeof useVaultState>;
let root: ReactTestRenderer | undefined;
const Probe = () => { vault = useVaultState(); return null; };
const mount = async () => {
await act(async () => { root = create(React.createElement(Probe)); });
for (let attempt = 0; !vault.isInitialized && attempt < 50; attempt++) {
await act(async () => { await tick(); });
}
assert.equal(vault.isInitialized, true);
};
const session: TerminalSession = {
id: 'restorable-tab', hostId: 'host', hostLabel: 'Host', hostname: 'host.test',
username: 'user', protocol: 'ssh', status: 'connected',
};
const systemInfoRef = { current: { username: 'local-user', hostname: 'local-host' } };
const capture = (data: string) => handleTerminalDataCaptureImpl(() => ({
IS_DEV: false, connectionLogs: vault.connectionLogs, sessions: [session],
selectConnectionLogForTerminalDataCapture, updateConnectionLog: vault.updateConnectionLog,
}), session.id, data);
try {
await mount();
let oldId!: string;
await act(async () => {
oldId = vault.addConnectionLog({
sessionId: session.id, hostId: session.hostId, hostLabel: session.hostLabel,
hostname: session.hostname, username: session.username, protocol: 'ssh', startTime: 1,
localUsername: 'local-user', localHostname: 'local-host', saved: false,
});
// Wait for the initial catalog write before blocking the capture write.
await vault.updateConnectionLog(oldId, {});
});
const buffer = createConnectionLogBuffer(10000);
buffer.append('output before quitting\r\n');
const ipcMain = new EventEmitter();
const ipcRenderer = new EventEmitter() as EventEmitter & { send: (channel: string, payload: unknown) => void };
const webContents = { send: (channel: string, payload: unknown) => ipcRenderer.emit(channel, {}, payload) };
ipcRenderer.send = (channel, payload) => ipcMain.emit(channel, { sender: webContents }, payload);
const api = createPreloadApi({ ipcRenderer });
const off = api.onFinalizeSessionLogs(() => capture(buffer.toString()));
let release!: () => void;
const blockedWrite = withVaultImportLock('connection-logs', () => new Promise<void>((resolve) => { release = resolve; }));
await tick();
let acknowledged = false;
await act(async () => {
const quit = finalizeSessionLogs(webContents, { ipcMain }).then((success: boolean) => {
acknowledged = true;
assert.equal(success, true);
});
await tick();
assert.equal(acknowledged, false, 'main must wait for the persistence queue');
release();
await blockedWrite;
await quit;
});
off();
// Remounting reads durable storage. Node has no IndexedDB, so this also
// exercises the existing localStorage replay fallback.
await act(async () => { root?.unmount(); });
await mount();
const oldLog = vault.connectionLogs.find((log) => log.id === oldId)!;
assert.ok(oldLog.endTime);
assert.equal(oldLog.terminalData, 'output before quitting\r\n');
await act(async () => {
startRestoredSessionConnectionLogImpl(() => ({ addConnectionLog: vault.addConnectionLog, systemInfoRef }), {
...session, status: 'disconnected', restoreState: 'restored-disconnected',
});
});
const newLog = vault.connectionLogs.find((log) => log.id !== oldId)!;
assert.equal(newLog.sessionId, session.id);
assert.equal(newLog.endTime, undefined);
assert.equal(newLog.terminalData, undefined);
await act(async () => { await capture('output after reconnect\r\n'); });
await act(async () => { root?.unmount(); });
await mount();
assert.equal(vault.connectionLogs.find((log) => log.id === oldId)?.terminalData, oldLog.terminalData);
assert.equal(vault.connectionLogs.find((log) => log.id === oldId)?.endTime, oldLog.endTime);
assert.equal(vault.connectionLogs.find((log) => log.id === newLog.id)?.terminalData, 'output after reconnect\r\n');
assert.ok(vault.connectionLogs.find((log) => log.id === newLog.id)?.endTime);
} finally {
await act(async () => { root?.unmount(); });
dom.window.close();
for (const key of globals) {
const descriptor = previous.get(key);
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
}
});
test('terminal quit listener drains output and awaits capture without tearing down tabs', () => {
const source = readFileSync(new URL('../../components/Terminal.tsx', import.meta.url), 'utf8');
const start = source.indexOf('onFinalizeSessionLogs?.(async () => {');
assert.ok(start > 0);
const listener = source.slice(start, source.indexOf('const attachHomeWebContentsIdRef', start));
assert.match(listener, /await flushPendingTerminalWritesBeforeHibernate\(term\)/);
assert.match(listener, /await handleTerminalDataCaptureOnce\(sessionId, finalizeTerminalLogData\(\), \{ finalized: true \}\)/);
assert.doesNotMatch(listener, /closeSession|teardown/);
const effects = readFileSync(new URL('./AppSideEffects.tsx', import.meta.url), 'utf8');
const handler = effects.slice(effects.indexOf('const handleSessionStatusChange ='), effects.indexOf('const handleUpdateHostFromTerminal ='));
assert.ok(handler.indexOf('startRestoredSessionConnectionLogImpl(') < handler.indexOf('updateSessionStatus(sessionId, status)'));
assert.match(handler, /restoredSessionLogsStartedRef\.current\.has\(sessionId\)/);
});
@@ -0,0 +1,18 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { enAiMessages } from './en/ai';
import { esAiMessages } from './es/ai';
import { ruAiMessages } from './ru/ai';
import { zhCNAiMessages } from './zh-CN/ai';
import { zhTWAiMessages } from './zh-TW/ai';
for (const [locale, messages] of Object.entries({
en: enAiMessages, es: esAiMessages, ru: ruAiMessages,
'zh-CN': zhCNAiMessages, 'zh-TW': zhTWAiMessages,
})) {
test(`${locale} translates the Catty iteration limit notice and Continue action`, () => {
assert.ok(messages['ai.chat.iterationLimitReached']);
assert.match(messages['ai.chat.iterationLimitReached'], /\{limit\}/);
assert.ok(messages['ai.chat.continue']);
});
}
+3
View File
@@ -1,6 +1,8 @@
import type { Messages } from '../types';
export const enAiMessages: Messages = {
'ai.chat.iterationLimitReached': 'Tool-loop limit ({limit} iterations) reached. You can continue in this chat. Running terminal jobs are not stopped.',
'ai.chat.continue': 'Continue',
'ai.chat.attachmentContentUnavailable': 'Content not available on this device',
// AI Settings
'ai.agentSettings': 'Agent Settings',
@@ -333,6 +335,7 @@ export const enAiMessages: Messages = {
'ai.defaultAgent': 'Default Agent',
'ai.defaultAgent.description': 'Agent to use when starting a new AI session',
'ai.defaultAgent.catty': 'Catty (Built-in)',
'ai.defaultAgent.unavailable': 'Unavailable',
'ai.toolAccess.title': 'Tool Access',
'ai.toolAccess.mode': 'Netcatty Access Mode',
'ai.toolAccess.description': 'Choose how external agents access Netcatty sessions. MCP exposes the built-in server, while Skills + CLI points agents to the local Netcatty skill and CLI commands.',
+3
View File
@@ -1,6 +1,8 @@
import type { Messages } from '../types';
export const esAiMessages: Messages = {
'ai.chat.iterationLimitReached': 'Se alcanzó el límite del bucle de herramientas ({limit} iteraciones). Puedes continuar en este chat. Las tareas de terminal en ejecución no se detienen.',
'ai.chat.continue': 'Continuar',
'ai.chat.attachmentContentUnavailable': 'Contenido no disponible en este dispositivo',
// AI Settings
'ai.agentSettings': 'Configuración del agente',
@@ -333,6 +335,7 @@ export const esAiMessages: Messages = {
'ai.defaultAgent': 'Agente predeterminado',
'ai.defaultAgent.description': 'Agente que se usará al iniciar una nueva sesión de IA',
'ai.defaultAgent.catty': 'Catty (Integrado)',
'ai.defaultAgent.unavailable': 'No disponible',
'ai.toolAccess.title': 'Acceso a herramientas',
'ai.toolAccess.mode': 'Modo de acceso de Netcatty',
'ai.toolAccess.description': 'Elige cómo acceden los agentes externos a las sesiones de Netcatty. MCP expone el servidor integrado, mientras que Habilidades + CLI apunta a los agentes hacia las habilidades locales de Netcatty y los comandos de CLI.',
@@ -12,16 +12,23 @@ import zhTW from "./zh-TW.ts";
// so the remaining debt stays visible instead of silently rendering in English
// through the `DEFAULT_UI_LOCALE` fallback in `I18nProvider.resolveMessage`.
// Move a locale out of this list once it covers every `en` key.
const LOCALES_PENDING_PARITY = ["ru", "zh-CN", "zh-TW"] as const;
const LOCALES_PENDING_PARITY = ["ru"] as const;
const hasKey = (messages: Record<string, string>, key: string) =>
Object.hasOwn(messages, key);
const interpolationTokens = (value: string) =>
[...value.matchAll(/\{\{\s*\w+\s*\}\}|\{\s*\w+\s*\}/g)]
[...value.matchAll(/\{\{\s*[^}]+\s*\}\}|\{\s*\w+\s*\}/g)]
.map((match) => match[0].replace(/[{}]/g, "").trim())
.sort();
test("interpolationTokens reads the :default placeholder form", () => {
assert.deepEqual(interpolationTokens("{{name}} or {{name:default}}"), [
"name",
"name:default",
]);
});
test("es defines every message key that en defines", () => {
const missing = Object.keys(en).filter((key) => !hasKey(es, key));
@@ -42,22 +49,31 @@ test("es defines no message keys that en does not define", () => {
);
});
test("es keeps the same interpolation placeholders as en", () => {
const mismatched: string[] = [];
test("every translated locale keeps the same interpolation placeholders as en", () => {
const locales = [
{ name: "es", messages: es },
{ name: "ru", messages: ru },
{ name: "zh-CN", messages: zhCN },
{ name: "zh-TW", messages: zhTW },
];
for (const key of Object.keys(es)) {
if (!hasKey(en, key)) continue;
for (const locale of locales) {
const mismatched: string[] = [];
const expected = interpolationTokens(en[key] ?? "").join(",");
const actual = interpolationTokens(es[key] ?? "").join(",");
if (expected !== actual) mismatched.push(key);
for (const key of Object.keys(locale.messages)) {
if (!hasKey(en, key)) continue;
const expected = interpolationTokens(en[key] ?? "").join(",");
const actual = interpolationTokens(locale.messages[key] ?? "").join(",");
if (expected !== actual) mismatched.push(key);
}
assert.deepEqual(
mismatched,
[],
`${locale.name} changes interpolation placeholders for ${mismatched.length} keys`,
);
}
assert.deepEqual(
mismatched,
[],
`es changes interpolation placeholders for ${mismatched.length} keys`,
);
});
test("every default shortcut has a label in en and es", () => {
+3
View File
@@ -1,6 +1,8 @@
import type { Messages } from '../types';
export const ruAiMessages: Messages = {
'ai.chat.iterationLimitReached': 'Достигнут лимит цикла инструментов ({limit} итераций). Можно продолжить в этом чате. Запущенные задачи терминала не останавливаются.',
'ai.chat.continue': 'Продолжить',
'ai.chat.attachmentContentUnavailable': 'Содержимое недоступно на этом устройстве',
'ai.chat.contextUsage': 'Контекст: {used} / {max} токенов',
// AI Settings
@@ -273,6 +275,7 @@ export const ruAiMessages: Messages = {
'ai.defaultAgent': 'Агент по умолчанию',
'ai.defaultAgent.description': 'Агент, который будет использоваться при запуске новой AI-сессии',
'ai.defaultAgent.catty': 'Catty (встроенный)',
'ai.defaultAgent.unavailable': 'Недоступен',
'ai.toolAccess.title': 'Доступ к инструментам',
'ai.toolAccess.mode': 'Режим доступа Netcatty',
'ai.toolAccess.description': 'Выберите, как внешние агенты получают доступ к сессиям Netcatty. MCP предоставляет встроенный сервер, а Skills + CLI указывает агентам на локальный skill Netcatty и команды CLI.',
+3
View File
@@ -1,6 +1,8 @@
import type { Messages } from '../types';
export const zhCNAiMessages: Messages = {
'ai.chat.iterationLimitReached': '已达到工具循环上限({limit} 次迭代)。你可以在此对话中继续,正在运行的终端任务不会停止。',
'ai.chat.continue': '继续',
'ai.chat.attachmentContentUnavailable': '附件内容未保留在此设备',
// AI Settings
'ai.agentSettings': 'Agent 设置',
@@ -333,6 +335,7 @@ export const zhCNAiMessages: Messages = {
'ai.defaultAgent': '默认 Agent',
'ai.defaultAgent.description': '创建新 AI 会话时使用的 Agent',
'ai.defaultAgent.catty': 'Catty(内置)',
'ai.defaultAgent.unavailable': '暂不可用',
'ai.toolAccess.title': '工具接入',
'ai.toolAccess.mode': 'Netcatty 接入模式',
'ai.toolAccess.description': '选择外部 Agent 访问 Netcatty 会话的方式。MCP 会暴露内置服务器,Skills + CLI 会引导 Agent 读取本地 Skill 并调用 Netcatty CLI。',
+2
View File
@@ -121,9 +121,11 @@ export const zhCNCoreMessages: Messages = {
'confirm.closeBusyTerminal.messageWithMore': '进程 "{command}" 及其他 {count} 个正在运行的进程将被终止。',
'confirm.closeBusyTerminal.cancel': '取消',
'confirm.closeBusyTerminal.close': '关闭',
'dialog.createWorkspace.title': '创建工作区',
'dialog.renameWorkspace.title': '重命名工作区',
'dialog.renameSession.title': '重命名会话',
'field.name': '名称',
'field.selectHosts': '选择主机',
'placeholder.workspaceName': '工作区名称',
'placeholder.sessionName': '会话名称',
'placeholder.searchHosts': '搜索主机或标签...',
+1 -1
View File
@@ -969,7 +969,7 @@ export const zhCNTerminalMessages: Messages = {
'snippets.variables.placeholderDefault': '默认:{value}',
'snippets.variables.required': '请填写此变量',
'snippets.variables.run': '运行',
'snippets.field.variablesHelp': '在脚本中使用 {{名称}} 或 {{名称:默认值}} 定义变量。',
'snippets.field.variablesHelp': '在脚本中使用 {{name}} 或 {{name:default}} 作为占位符。',
'snippets.field.variablesDetected': '变量',
'snippets.field.variableDefault': '默认 {value}',
+15 -3
View File
@@ -1,6 +1,8 @@
import type { Messages } from '../types';
export const zhTWAiMessages: Messages = {
'ai.chat.iterationLimitReached': '已達到工具迴圈上限({limit} 次迭代)。你可以在此對話中繼續,正在執行的終端工作不會停止。',
'ai.chat.continue': '繼續',
'ai.chat.attachmentContentUnavailable': '附件內容未保留在此裝置',
// AI Settings
'ai.agentSettings': 'Agent 設定',
@@ -39,6 +41,15 @@ export const zhTWAiMessages: Messages = {
'ai.providers.noApiKey': '未設定 API Key',
'ai.providers.configure': '設定',
'ai.providers.remove': '移除',
'ai.providers.headers': '自訂 HTTP 請求標頭',
'ai.providers.headers.help': '為此服務新增選用請求標頭。內容會隱藏顯示,並在儲存時加密。',
'ai.providers.headers.name': '請求標頭名稱',
'ai.providers.headers.value': '請求標頭內容',
'ai.providers.headers.add': '新增請求標頭',
'ai.providers.headers.remove': '刪除請求標頭',
'ai.providers.headers.invalid': '請填寫有效且不重複的請求標頭。Content-Length 和 Transfer-Encoding 由應用程式自動設定。',
'ai.providers.headers.loadError': '無法解鎖已儲存的請求標頭。請取消編輯,解鎖系統鑰匙圈後重試。',
'ai.providers.headers.saveError': '無法安全儲存。請確認系統鑰匙圈可用後重試。',
'ai.providers.name': '顯示名稱',
'ai.providers.name.placeholder': '例如 我的供應商',
'ai.providers.style': '協定風格',
@@ -324,6 +335,7 @@ export const zhTWAiMessages: Messages = {
'ai.defaultAgent': '預設 Agent',
'ai.defaultAgent.description': '建立新 AI 工作階段時使用的 Agent',
'ai.defaultAgent.catty': 'Catty(內建)',
'ai.defaultAgent.unavailable': '暫時無法使用',
'ai.toolAccess.title': '工具介接',
'ai.toolAccess.mode': 'Netcatty 介接模式',
'ai.toolAccess.description': '選擇外部 Agent 存取 Netcatty 工作階段的方式。MCP 會公開內建伺服器,Skills + CLI 會引導 Agent 讀取本機 Skill 並呼叫 Netcatty CLI。',
@@ -385,8 +397,8 @@ export const zhTWAiMessages: Messages = {
"ai.privacy.cidrs.description": "每行一個 IPv4 或 IPv6 CIDR。留空則僅使用內建規則。",
"ai.privacy.patterns": "自訂正規表示式",
"ai.privacy.patterns.description": "每行一個相容 RE2 的模式,不含 / 分隔符號或旗標。不支援或不安全的模式會遭拒絕。",
"ai.privacy.connectionScope": "預留位置在同一個受管對話或外部 MCP 連線內保持穩定。只有同一範圍內的 Netcatty 受管工具呼叫才能還原原始值。",
"ai.privacy.reconnect": "套用變更後,請建立新的受管對話並重新連接外部 MCP 用戶端。現有對話和連線不得重複使用預留位置。",
"ai.privacy.connectionScope": "佔位符在同一個受管對話或外部 MCP 連線內保持穩定。只有同一範圍內的 Netcatty 受管工具呼叫才能還原原始值。",
"ai.privacy.reconnect": "套用變更後,請建立新的受管對話並重新連接外部 MCP 用戶端。現有對話和連線不得重複使用佔位符。",
"ai.privacy.apply": "套用",
"ai.privacy.applying": "正在套用...",
"ai.privacy.applied": "AI 隱私設定已套用。請建立新的受管對話並重新連接外部 MCP 用戶端。",
@@ -657,7 +669,7 @@ export const zhTWAiMessages: Messages = {
'ai.chatHistory.messageCap.unit': '則訊息',
// AI Error
'ai.codex.bridgeError': 'Codex 主程序處理器尚未載入。請完全重新啟動 Netcatty 或重新啟動 Electron 開發程序,然後重試。',
'ai.codex.bridgeError': 'Codex 主行程處理器尚未載入。請完全重新啟動 Netcatty 或重新啟動 Electron 開發行程,然後重試。',
// AI Web Search
'ai.webSearch.title': '網路搜尋',
+48 -48
View File
@@ -6,7 +6,7 @@ export const zhTWCoreMessages: Messages = {
"settings.plugins.github.repository": "GitHub 儲存庫",
"settings.plugins.github.formats": "支援 https://github.com/owner/repo、github.com/owner/repo 或 owner/repo。",
"settings.plugins.github.busy": "正在下載、驗證或安裝套件…",
"settings.plugins.github.review": "確認儲存庫來源並通過完整性驗證,並不代表發布者值得信任。安裝過程不會執行建置腳本,外掛安裝後預設停用。啟用前,請確認來源可信並檢查各項權限的授權方式。",
"settings.plugins.github.review": "確認儲存庫來源並通過完整性驗證,並不代表發布者值得信任。安裝過程不會執行建置指令碼,外掛安裝後預設停用。啟用前,請確認來源可信並檢查各項權限的授權方式。",
"settings.plugins.github.accept": "已審查並信任此儲存庫,且已查看宣告的權限。",
"settings.plugins.github.confirm": "安裝並保持停用",
"settings.plugins.github.download": "下載並審查",
@@ -117,8 +117,8 @@ export const zhTWCoreMessages: Messages = {
'confirm.deleteIdentity': '刪除身分 "{name}"?',
'confirm.removeProvider': '移除供應商 "{name}"?',
'confirm.closeBusyTerminal.title': '確認關閉',
'confirm.closeBusyTerminal.message': '程序 "{command}" 仍在執行,關閉後會被終止。',
'confirm.closeBusyTerminal.messageWithMore': '程序 "{command}" 及其他 {count} 個正在執行的程序將被終止。',
'confirm.closeBusyTerminal.message': '行程 "{command}" 仍在執行,關閉後會被終止。',
'confirm.closeBusyTerminal.messageWithMore': '行程 "{command}" 及其他 {count} 個正在執行的行程將被終止。',
'confirm.closeBusyTerminal.cancel': '取消',
'confirm.closeBusyTerminal.close': '關閉',
'dialog.createWorkspace.title': '建立工作區',
@@ -296,7 +296,7 @@ export const zhTWCoreMessages: Messages = {
// Settings > System > Crash Logs
'settings.system.crashLogs.title': '崩潰日誌',
'settings.system.crashLogs.description': '檢視主程序錯誤日誌,協助診斷異常行為。',
'settings.system.crashLogs.description': '檢視主行程錯誤日誌,協助診斷異常行為。',
'settings.system.crashLogs.noLogs': '未找到崩潰日誌。',
'settings.system.crashLogs.entries': '{count} 條記錄',
'settings.system.crashLogs.clear': '清除所有日誌',
@@ -1245,16 +1245,16 @@ Vaults 分頁維持扁平,不使用這塊背景。
'settings.tab.plugins': '外掛程式',
"settings.plugins.author.official": "官方維護",
"settings.plugins.author.officialMeaning": "由 Netcatty 專案維護。這不是安全認證。",
"settings.plugins.manager.installed": "已安裝插件",
"settings.plugins.manager.import": "導入 .ncpkg",
"settings.plugins.manager.preview": "導入的插件保持停用,請檢查後再啟用。",
"settings.plugins.manager.empty": "導入本地插件包以開始使用。",
"settings.plugins.manager.installed": "已安裝外掛",
"settings.plugins.manager.import": "匯入 .ncpkg",
"settings.plugins.manager.preview": "匯入的外掛保持停用,請檢查後再啟用。",
"settings.plugins.manager.empty": "匯入本地外掛包以開始使用。",
"settings.plugins.manager.enabled": "已啟用",
"settings.plugins.manager.disabled": "已停用",
"settings.plugins.manager.enable": "啟用",
"settings.plugins.manager.disable": "停用",
"settings.plugins.manager.remove": "卸載",
"settings.plugins.manager.removeNote": "卸載會移除插件代碼和本地 KV 數據,保留用戶設置、秘密存儲和同步 sidecar。",
"settings.plugins.manager.remove": "解除安裝",
"settings.plugins.manager.removeNote": "解除安裝會移除外掛代碼和本地 KV 資料,保留使用者設定、秘密儲存和同步 sidecar。",
"settings.plugins.permissions.statusUnknown": "狀態不明",
"plugins.sidebar.extensions": "擴充功能頁面",
"plugins.sidebar.selectTerminal": "請先選擇已開啟的終端。",
@@ -1315,44 +1315,44 @@ Vaults 分頁維持扁平,不使用這塊背景。
"settings.plugins.themes.invalid": "部分主題配色未通過驗證或無法使用。",
"settings.plugins.themes.failed": "無法套用主題。",
"settings.plugins.manager.dataTheme": "主題套件:已驗證配色,不啟動程式執行環境。",
"settings.plugins.manager.browser": "瀏覽器運行時:特權訪問通過宿主權限代理。",
"settings.plugins.manager.advanced": "高級運行時:擁有完整 Node 文件系統和網絡能力,代理權限無法限制這些訪問。僅供開發預覽。",
"settings.plugins.manager.data": "本地 KV 僅保留在此設備。只有明確標記為同步的非秘密設置進入加密雲 sidecar。插件包和權限授權不參與同步。",
"settings.plugins.manager.browser": "瀏覽器運行時:特權存取通過宿主權限代理。",
"settings.plugins.manager.advanced": "高級運行時:擁有完整 Node 檔案系統和網路能力,代理權限無法限制這些存取。僅供開發預覽。",
"settings.plugins.manager.data": "本地 KV 僅保留在此裝置。只有明確標記為同步的非秘密設置進入加密雲 sidecar。外掛包和權限授權不參與同步。",
"settings.plugins.manager.unbounded": "未宣告更細的資源範圍,仍受應用程式驗證和所選權限模式約束。",
"settings.plugins.openView": "開啟",
"settings.plugins.openManager": "開啟插件管理",
"settings.plugins.sources.conflict": "此 ID 已从其他来源安装。请先卸载并明确清理旧来源数据,再换源重装。原来源:",
"settings.plugins.sources.clearPrivate": "同时清除本来源的私有数据、授权和秘密,以便显式换源重装。此操作不可撤销。",
"settings.plugins.openManager": "開啟外掛管理",
"settings.plugins.sources.conflict": "此 ID 已從其他來源安裝。請先解除安裝並明確清理舊來源資料,再換源重新安裝。原來源:",
"settings.plugins.sources.clearPrivate": "同時清除本來源的私有資料、授權和秘密,以便明確換源重新安裝。此操作無法復原。",
"settings.plugins.sources.short.official": "官方",
"settings.plugins.sources.short.thirdparty": "第三方",
"settings.plugins.sources.short.local": "本機",
"settings.plugins.sources.official": "官方市场",
"settings.plugins.sources.thirdparty": "第三方市场",
"settings.plugins.sources.manage": "管理来源",
"settings.plugins.sources.select": "选择来源",
"settings.plugins.sources.empty": "选择或添加第三方来源。",
"settings.plugins.sources.add": "添加来源",
"settings.plugins.sources.remove": "移除来源",
"settings.plugins.sources.name": "来源名称",
"settings.plugins.sources.address": "HTTPS 来源地址",
"settings.plugins.sources.risk": "第三方来源不代表 Netcatty 维护或认可。安装前请核对真实域名、插件权限与作者。",
"settings.plugins.sources.accept": "我信任此域名提供插件目录和软件包。此操作不会授予插件权限。",
"settings.plugins.sources.removeNote": "保留已安装插件及数据,停止此来源更新,不会自动切换到其他来源。",
"settings.plugins.sources.disablePlugins": "同时停用来自该来源的插件",
"settings.plugins.sources.installConfirm": "确认第三方安装",
"settings.plugins.sources.source": "来源",
"settings.plugins.sources.local": "本地导入",
"settings.plugins.sources.all": "全部来源",
"settings.plugins.title": "插件",
"settings.plugins.configuration": "插件設定",
"settings.plugins.description": "管理已安裝插件,瀏覽精選目錄。",
"settings.plugins.sources.official": "官方市集",
"settings.plugins.sources.thirdparty": "第三方市集",
"settings.plugins.sources.manage": "管理來源",
"settings.plugins.sources.select": "選擇來源",
"settings.plugins.sources.empty": "選擇或新增第三方來源。",
"settings.plugins.sources.add": "新增來源",
"settings.plugins.sources.remove": "移除來源",
"settings.plugins.sources.name": "來源名稱",
"settings.plugins.sources.address": "HTTPS 來源位址",
"settings.plugins.sources.risk": "第三方來源不代表 Netcatty 維護或認可。安裝前請核對真實網域、外掛權限與作者。",
"settings.plugins.sources.accept": "我信任此網域提供外掛目錄和套件。此操作不會授予外掛權限。",
"settings.plugins.sources.removeNote": "保留已安裝外掛及資料,停止此來源更新,不會自動切換到其他來源。",
"settings.plugins.sources.disablePlugins": "同時停用來自該來源的外掛",
"settings.plugins.sources.installConfirm": "確認第三方安裝",
"settings.plugins.sources.source": "來源",
"settings.plugins.sources.local": "本機匯入",
"settings.plugins.sources.all": "全部來源",
"settings.plugins.title": "外掛",
"settings.plugins.configuration": "外掛設定",
"settings.plugins.description": "管理已安裝外掛,瀏覽精選目錄。",
'settings.plugins.loading': '正在載入外掛程式設定…',
"settings.plugins.market.results": "{count} 個插件",
"settings.plugins.market.results": "{count} 個外掛",
"settings.plugins.manager.lastError": "上次記錄的錯誤",
"settings.plugins.sources.offline": "來源暫不可用。如已快取此來源通過驗證的目錄,僅可繼續瀏覽;重新整理成功前無法安裝。",
"settings.plugins.sources.note": "此目錄由所選第三方提供,不屬於 Netcatty 精選目錄。安裝前請核對來源網域和權限,更新需手動確認。",
"settings.plugins.sources.sourceOnly": "此提供方僅提供原始碼項目,沒有可下載外掛套件;請查看作者的建置和匯入說明。",
"settings.plugins.market.offline": "官方目錄暫時無法使用,正在顯示上次有效目錄或內建範例。重新整理成功前無法從市場安裝。",
"settings.plugins.market.offline": "官方目錄暫時無法使用,正在顯示上次有效目錄或內建範例。重新整理成功前無法從市集安裝。",
"settings.plugins.manager.details": "查看詳情",
"settings.plugins.manager.noDescription": "作者尚未提供功能簡介。",
"settings.plugins.status": "{count} 項提醒",
@@ -1362,22 +1362,22 @@ Vaults 分頁維持扁平,不使用這塊背景。
"settings.plugins.market.readmeInfo": "README 來源說明",
"settings.plugins.market.installed": "已安裝",
"settings.plugins.market.sourceBadge": "原始碼範例",
"settings.plugins.market.title": "插件市場",
"settings.plugins.market.note": "精選開源插件。審核不代表安全認證,更新由你手動確認。",
"settings.plugins.market.back": "所有插件",
"settings.plugins.market.title": "外掛市集",
"settings.plugins.market.note": "精選開源外掛。審核不代表安全認證,更新由你手動確認。",
"settings.plugins.market.back": "所有外掛",
"settings.plugins.market.install": "安裝此版本(保持停用)",
"settings.plugins.market.installNote": "這會替換並停止已安裝版本。請在已安裝列表檢查權限後再啟用。",
"settings.plugins.market.sourceOnly": "第一方源碼示例。請用本地 CLI 構建並導入 .ncpkg;尚未發佈可下載發行包。",
"settings.plugins.market.readmeNote": "固定到上面的提交。HTML 不執行,遠程圖片不加載。內容由插件作者提供。",
"settings.plugins.manager.noVault": "系統密鑰存儲不可用。秘密和憑據操作被阻止;瀏覽市場和不使用秘密的插件仍可使用。",
"settings.plugins.market.sourceOnly": "第一方源碼示例。請用本地 CLI 構建並匯入 .ncpkg;尚未發佈可下載發行包。",
"settings.plugins.market.readmeNote": "固定到上面的提交。HTML 不執行,遠端圖片不載入。內容由外掛作者提供。",
"settings.plugins.manager.noVault": "系統金鑰儲存不可用。秘密和憑據操作被阻止;瀏覽市集和不使用秘密的外掛仍可使用。",
"settings.plugins.manager.sensitive": "敏感存取:此能力可能涉及私密資料,可在權限設定中調整其模式。",
"settings.plugins.manager.dual": "默認使用瀏覽器運行時,但包中還包含擁有完整設備權限的 Node 入口;僅限開發者模式。",
"settings.plugins.manager.advancedDeclaration": "瀏覽器入口聲明瞭高級權限。不適用於普通瀏覽器插件模式;請逐項檢查聲明權限。",
"settings.plugins.manager.dual": "預設使用瀏覽器運行時,但包中還包含擁有完整裝置權限的 Node 入口;僅限開發者模式。",
"settings.plugins.manager.advancedDeclaration": "瀏覽器入口聲明瞭高級權限。不適用於普通瀏覽器外掛模式;請逐項檢查聲明權限。",
"settings.plugins.market.retry": "重試",
"settings.plugins.market.empty": "目錄暫無插件,仍可導入本地瀏覽器插件。",
"settings.plugins.market.empty": "目錄暫無外掛,仍可匯入本地瀏覽器外掛。",
"settings.plugins.market.emptyReadme": "README 內容為空。",
"settings.plugins.market.search": "搜索名稱、作者或描述",
"settings.plugins.market.noResults": "沒有匹配插件,請嘗試其他關鍵詞。",
"settings.plugins.market.noResults": "沒有匹配外掛,請嘗試其他關鍵詞。",
"settings.plugins.market.manifest": "兼容性與權限",
'settings.plugins.empty': '目前沒有已啟用外掛程式提供設定。',
'settings.plugins.scopeContext': '請在對應的 {scope} 情境中開啟此設定。',
+18 -18
View File
@@ -4,10 +4,10 @@ export const zhTwSystemManagerMessages: Messages = {
'terminal.layer.system': '系統',
'systemManager.noSession': '沒有使用中的終端工作階段。',
'systemManager.notConnected': '請先連線到主機以管理程序與服務。',
'systemManager.notConnected': '請先連線到主機以管理行程與服務。',
'systemManager.empty': '暫無資料。',
'systemManager.tabs.overview': '概覽',
'systemManager.tabs.processes': '程序',
'systemManager.tabs.processes': '行程',
'systemManager.tabs.ports': '連接埠',
'systemManager.tabs.services': '服務',
'systemManager.tabs.tmux': 'tmux',
@@ -17,7 +17,7 @@ export const zhTwSystemManagerMessages: Messages = {
'systemManager.popup.loading': '正在開啟終端…',
'systemManager.popup.startupFailed': '啟動指令未順利完成。請確認目標仍可使用後再試一次。',
'systemManager.errors.loadProcesses': '載入程序列表失敗',
'systemManager.errors.loadProcesses': '載入行程列表失敗',
'systemManager.errors.loadTmux': '載入 tmux 工作階段失敗',
'systemManager.errors.loadTmuxWindows': '載入 tmux 視窗失敗',
'systemManager.errors.loadTmuxPanes': '載入 tmux 窗格失敗',
@@ -58,13 +58,13 @@ export const zhTwSystemManagerMessages: Messages = {
'systemManager.overview.cpuCores': 'CPU 核心',
'systemManager.overview.disks': '磁碟',
'systemManager.overview.interfaces': '網路介面',
'systemManager.overview.topProcesses': '記憶體佔用最高程序',
'systemManager.overview.topProcesses': '記憶體佔用最高行程',
'systemManager.overview.noData': '暫無資料',
'systemManager.overview.noDisks': '暫無磁碟資料',
'systemManager.overview.noInterfaces': '暫無網路卡資料',
'systemManager.overview.noTopProcesses': '暫無程序資料',
'systemManager.overview.noTopProcesses': '暫無行程資料',
'systemManager.processes.search': '搜尋程序…',
'systemManager.processes.search': '搜尋行程…',
'systemManager.processes.command': '指令',
'systemManager.processes.user': '使用者',
'systemManager.processes.term': '終止',
@@ -75,18 +75,18 @@ export const zhTwSystemManagerMessages: Messages = {
'systemManager.processes.renice': '調整優先順序',
'systemManager.processes.renicePrompt': 'Nice 值 (-20 到 19)',
'systemManager.processes.reniceInvalid': 'Nice 值必須在 -20 到 19 之間',
'systemManager.processes.confirmKill': '向程序 {{pid}} 傳送 SIGKILL?',
'systemManager.processes.confirmSignal': '向程序 {{pid}} 傳送 SIG{{signal}}?',
'systemManager.processes.confirmKill': '向行程 {{pid}} 傳送 SIGKILL?',
'systemManager.processes.confirmSignal': '向行程 {{pid}} 傳送 SIG{{signal}}?',
'systemManager.processes.filter.all': '全部',
'systemManager.processes.filter.running': '執行中',
'systemManager.processes.ppid': '父程序 PID',
'systemManager.processes.ppid': '父行程 PID',
'systemManager.processes.rss': '實體記憶體',
'systemManager.processes.vsz': '虛擬記憶體',
'systemManager.processes.elapsed': '執行時長',
'systemManager.processes.stat': '狀態',
'systemManager.processes.meta': '{{count}} 個程序',
'systemManager.processes.loading': '正在載入程序…',
'systemManager.processes.loadingMore': '正在載入更多程序…',
'systemManager.processes.meta': '{{count}} 個行程',
'systemManager.processes.loading': '正在載入行程…',
'systemManager.processes.loadingMore': '正在載入更多行程…',
'systemManager.processes.state.running': '執行中',
'systemManager.processes.state.sleeping': '睡眠',
'systemManager.processes.state.stopped': '已暫停',
@@ -236,9 +236,9 @@ export const zhTwSystemManagerMessages: Messages = {
'systemManager.ports.search': '搜尋連接埠…',
'systemManager.ports.meta': '{{count}} 個監聽',
'systemManager.ports.filter.all': '全部',
'systemManager.ports.unknownProcess': '未知程序',
'systemManager.ports.terminate': '結束程序',
'systemManager.ports.confirmTerminate': '向佔用該連接埠的程序 {{pid}} 傳送 SIGTERM?',
'systemManager.ports.unknownProcess': '未知行程',
'systemManager.ports.terminate': '結束行程',
'systemManager.ports.confirmTerminate': '向佔用該連接埠的行程 {{pid}} 傳送 SIGTERM?',
'systemManager.services.unavailable': '此主機未偵測到 systemctl。',
'systemManager.services.loading': '正在載入 systemd 服務…',
@@ -261,10 +261,10 @@ export const zhTwSystemManagerMessages: Messages = {
'systemManager.gpu.unavailable': '此主機未偵測到 NVIDIA GPU 或昇騰 NPU 工具。',
'systemManager.gpu.loading': '正在載入加速卡狀態…',
'systemManager.gpu.empty': '已偵測到加速卡工具,但未回傳裝置資訊。',
'systemManager.gpu.meta': '{{devices}} 張卡 · {{processes}} 個程序',
'systemManager.gpu.meta': '{{devices}} 張卡 · {{processes}} 個行程',
'systemManager.gpu.devices': '裝置',
'systemManager.gpu.processes': '計算程序',
'systemManager.gpu.noProcesses': '目前沒有計算程序。',
'systemManager.gpu.processes': '計算行程',
'systemManager.gpu.noProcesses': '目前沒有計算行程。',
'systemManager.gpu.vendor.nvidia': 'NVIDIA',
'systemManager.gpu.vendor.ascend': '昇騰',
'systemManager.gpu.util': '使用率',
+3 -3
View File
@@ -510,8 +510,8 @@ export const zhTWTerminalMessages: Messages = {
'settings.terminal.serverStats.refreshInterval.desc': '伺服器狀態重新整理的頻率。',
'settings.terminal.serverStats.seconds': '秒',
'settings.terminal.section.systemManager': '系統管理',
'settings.terminal.systemManager.processRefreshInterval': '程序列表重新整理間隔',
'settings.terminal.systemManager.processRefreshInterval.desc': '系統管理側欄中程序列表的重新整理頻率。',
'settings.terminal.systemManager.processRefreshInterval': '行程列表重新整理間隔',
'settings.terminal.systemManager.processRefreshInterval.desc': '系統管理側欄中行程列表的重新整理頻率。',
'settings.terminal.systemManager.tmuxRefreshInterval': 'tmux 工作階段重新整理間隔',
'settings.terminal.systemManager.tmuxRefreshInterval.desc': 'tmux 工作階段列表的重新整理頻率。',
'settings.terminal.systemManager.dockerListRefreshInterval': '容器列表重新整理間隔',
@@ -969,7 +969,7 @@ export const zhTWTerminalMessages: Messages = {
'snippets.variables.placeholderDefault': '預設:{value}',
'snippets.variables.required': '請填寫此變數',
'snippets.variables.run': '執行',
'snippets.field.variablesHelp': '在指令碼中使用 {{名稱}} 或 {{名稱:預設值}} 定義變數。',
'snippets.field.variablesHelp': '在指令碼中使用 {{name}} 或 {{name:default}} 作為佔位符。',
'snippets.field.variablesDetected': '變數',
'snippets.field.variableDefault': '預設 {value}',
+1 -1
View File
@@ -580,7 +580,7 @@ export const zhTWVaultMessages: Messages = {
'terminal.serverStats.swapUsed': '已用交換',
'terminal.serverStats.swapFree': '空閒交換',
'terminal.serverStats.swapTotal': '總計',
'terminal.serverStats.topProcesses': '記憶體佔用前十程序',
'terminal.serverStats.topProcesses': '記憶體佔用前十行程',
'terminal.serverStats.disk': '磁碟使用',
'terminal.serverStats.diskDetails': '已掛載磁碟',
'terminal.serverStats.network': '網路速度',
@@ -541,3 +541,98 @@ test("late pause acknowledgement cannot restart a cancelling stream before settl
await pause;
assert.equal(resumes, 0);
});
for (const rejected of [false, true]) {
test(`folder pause retains successful children without claiming failed children paused: rejected=${rejected}`, async (t) => {
t.after(resetTransferPauseLatchesForTests);
let fail = true;
let resumes = 0;
const id = `partial-folder-${rejected}`;
const { host, getTasks } = createHost([
{ ...makeTask(id), isDirectory: true },
{ ...makeTask(`${id}-ok`), parentTaskId: id },
{ ...makeTask(`${id}-bad`), parentTaskId: id },
], () => ({
pauseTransfer: async (childId) => {
if (fail && childId.endsWith('-bad')) {
if (rejected) throw new Error('pause IPC unavailable');
return { success: false, reason: 'This transfer cannot be paused safely' };
}
return { success: true, checkpointBytes: 10 };
},
resumeTransfer: async () => { resumes++; return { success: true }; },
}));
await softPauseTransfer(host, id);
await new Promise<void>(resolve => setImmediate(resolve));
assert.equal(getTasks()[0].status, 'pausing');
assert.match(getTasks()[0].pauseUnavailableReason || '', /pause/i);
assert.equal(getTasks()[1].status, 'paused');
assert.equal(getTasks()[2].status, 'transferring');
assert.equal(isTransferPauseLatched(id), true);
assert.equal(resumes, 0, 'failed pause must not resume successful siblings');
fail = false;
await softPauseTransfer(host, id);
await new Promise<void>(resolve => setImmediate(resolve));
assert.ok(getTasks().every(row => row.status === 'paused'));
assert.equal(getTasks()[0].pauseUnavailableReason, undefined);
});
}
test('folder pause does not claim success while acknowledgements are pending or retry budget expires', async (t) => {
t.after(resetTransferPauseLatchesForTests);
const id = 'slow-start-folder';
let calls = 0;
const { host, getTasks } = createHost([
{ ...makeTask(id), isDirectory: true },
{ ...makeTask(`${id}-child`), parentTaskId: id },
], () => ({ pauseTransfer: async () => {
calls++;
return { success: false, reason: 'This transfer cannot be paused yet' };
} }));
assert.equal(await softPauseTransfer(host, id), 'pausing');
assert.equal(getTasks()[0].status, 'pausing');
// Wait for the bounded startup retry budget (four 40ms delays).
await new Promise(resolve => setTimeout(resolve, 220));
assert.equal(calls, 5);
assert.equal(getTasks()[0].status, 'pausing');
assert.match(getTasks()[0].pauseUnavailableReason || '', /cannot be paused yet/);
assert.equal(getTasks()[1].status, 'transferring');
});
test('explicit resume after partial folder pause releases successful siblings and walk latch', async (t) => {
t.after(resetTransferPauseLatchesForTests);
const id = 'resume-partial-folder';
const resumed: string[] = [];
const { host, getTasks } = createHost([
{ ...makeTask(id), isDirectory: true },
{ ...makeTask(`${id}-ok`), parentTaskId: id },
{ ...makeTask(`${id}-bad`), parentTaskId: id },
], () => ({
pauseTransfer: async childId => childId.endsWith('-ok')
? { success: true } : { success: false, reason: 'Pause rejected' },
resumeTransfer: async childId => { resumed.push(childId); return { success: true }; },
}));
await softPauseTransfer(host, id);
await new Promise<void>(resolve => setImmediate(resolve));
assert.equal((await softResumeTransfer(host, id)).handled, true);
assert.equal(isTransferPauseLatched(id), false);
assert.ok(getTasks().every(row => row.status === 'transferring'));
assert.deepEqual(resumed.sort(), [`${id}-bad`, `${id}-ok`]);
});
test('child completion during a rejected folder pause does not leave a false failure', async (t) => {
t.after(resetTransferPauseLatchesForTests);
const id = 'completed-during-folder-pause';
let finish!: (result: { success: boolean; reason: string }) => void;
const { host, getTasks } = createHost([
{ ...makeTask(id), isDirectory: true },
{ ...makeTask(`${id}-child`), parentTaskId: id },
], () => ({ pauseTransfer: () => new Promise(resolve => { finish = resolve; }) }));
await softPauseTransfer(host, id);
host.setTasks(getTasks().map(row => row.parentTaskId ? { ...row, status: 'completed' } : row));
finish({ success: false, reason: 'Pause rejected' });
await new Promise<void>(resolve => setImmediate(resolve));
assert.equal(getTasks()[0].status, 'paused');
assert.equal(getTasks()[0].pauseUnavailableReason, undefined);
assert.equal(getTasks()[1].status, 'completed');
});
@@ -184,7 +184,7 @@ export async function softPauseTransfer(
try { globalSftpTransferScheduler.pause(id); } catch { /* best-effort */ }
}
const immediateStatus = task.isDirectory ? "paused" as const : "pausing" as const;
const immediateStatus = "pausing" as const;
// Freeze via latch/status; leave lifecycleEpoch alone until bridge responds.
host.setTasks(paintTreeStatus(
host.getTasks(),
@@ -271,7 +271,11 @@ export async function softPauseTransfer(
if (!pauseStillCurrent()) {
return { id, result: { success: false, reason: "Pause superseded by resume" } };
}
const result = await pauseOne(id);
// A rejected IPC is a failed acknowledgement, not proof of pause.
const result: Awaited<ReturnType<NonNullable<TransferControlBridge["pauseTransfer"]>>> = await pauseOne(id).catch((error: unknown) => ({
success: false,
reason: error instanceof Error ? error.message : "Could not pause transfer",
}));
if (wasSuperseded(result)) return { id, result };
const live = host.getTasks().find((candidate) => candidate.id === taskId);
const userResumed = !pauseStillCurrent()
@@ -293,16 +297,26 @@ export async function softPauseTransfer(
if (after.status !== "paused" && after.status !== "pausing") return;
const byId = new Map(pauseResults.map((row) => [row.id, row.result]));
const bridgeEpoch = maxBridgeLifecycleEpoch(pauseResults.map((row) => row.result));
// Final directory paint: parent + unfinished children all go paused (do not
// leave children stuck on transferring under a paused parent).
const liveTasks = host.getTasks();
const failed = pauseResults.filter(({ id, result }) => {
const live = liveTasks.find((candidate) => candidate.id === id);
return live && !["completed", "cancelled", "failed"].includes(live.status)
&& !result.success && !isBenignPauseMiss(result.reason);
});
// Keep acknowledged children paused and retain the walk latch. Never
// auto-resume siblings to roll back a partial pause. Failed children may
// still be streaming; expose that truth and allow an explicit retry.
const pauseFailure = failed.length > 0
? (failed[0].result.reason || "Could not pause all folder transfers")
: undefined;
host.setTasks(host.getTasks().map((candidate) => {
if (candidate.id === taskId) {
return {
...candidate,
status: "paused" as const,
status: pauseFailure ? "pausing" as const : "paused" as const,
speed: 0,
checkpointBytes: candidate.transferredBytes,
pauseUnavailableReason: undefined,
pauseUnavailableReason: pauseFailure,
phase: undefined,
// Bridge epoch only — control-plane pauseEpoch must not poison ingest.
...(bridgeEpoch !== undefined ? { lifecycleEpoch: bridgeEpoch } : null),
@@ -311,24 +325,25 @@ export async function softPauseTransfer(
if (candidate.parentTaskId !== taskId && !backendIds.includes(candidate.id)) return candidate;
if (["completed", "cancelled", "failed"].includes(candidate.status)) return candidate;
const result = byId.get(candidate.id);
const childFailed = result && !result.success && !isBenignPauseMiss(result.reason);
const childEpoch = Number.isFinite(result?.lifecycleEpoch)
? (result!.lifecycleEpoch as number)
: bridgeEpoch;
: childFailed ? undefined : bridgeEpoch;
return {
...candidate,
status: "paused" as const,
status: childFailed ? "transferring" as const : "paused" as const,
speed: 0,
checkpointBytes: result?.checkpointBytes ?? candidate.checkpointBytes ?? candidate.transferredBytes,
resumeStage: result?.resumeStage ?? candidate.resumeStage,
downloadCheckpointBytes: result?.downloadCheckpointBytes ?? candidate.downloadCheckpointBytes,
uploadCheckpointBytes: result?.uploadCheckpointBytes ?? candidate.uploadCheckpointBytes,
sourceFingerprint: result?.sourceFingerprint ?? candidate.sourceFingerprint,
pauseUnavailableReason: undefined,
pauseUnavailableReason: childFailed ? (result.reason || "Could not pause transfer") : undefined,
...(childEpoch !== undefined ? { lifecycleEpoch: childEpoch } : null),
};
}));
})().catch(() => { /* best-effort */ });
return "paused";
return "pausing";
}
// Single-file: await soft-drain with supersede guards.
@@ -122,8 +122,11 @@ test("runtime soft-resumes live walk after owner teardown simulation (no dedicat
resetGlobals();
const resumeCalls: string[] = [];
let dedicatedHandlerCalls = 0;
let acknowledgePause!: () => void;
installBridge(t, {
pauseTransfer: async () => ({ success: true, checkpointBytes: 5 }),
pauseTransfer: () => new Promise((resolve) => {
acknowledgePause = () => resolve({ success: true, checkpointBytes: 5 });
}),
resumeTransfer: async (id) => {
resumeCalls.push(id);
return { success: true };
@@ -151,6 +154,9 @@ test("runtime soft-resumes live walk after owner teardown simulation (no dedicat
]);
await runtime.pause("folder");
assert.equal(runtime.getTask("folder")?.status, "pausing");
acknowledgePause();
await new Promise<void>((resolve) => setImmediate(resolve));
assert.equal(runtime.getTask("folder")?.status, "paused");
assert.equal(isTransferPauseLatched("folder"), true);
assert.equal(isTransferWalkInFlight("folder"), true);
@@ -6,6 +6,7 @@ import { act, create, type ReactTestRenderer } from "react-test-renderer";
import { PREFLIGHT_STAT_CONCURRENCY, PREFLIGHT_STAT_MAX_FILES, useSftpTransfers } from "./useSftpTransfers";
import { sftpTransferCenterStore } from "../sftpTransferCenterStore";
import type { SftpPane } from "./types";
import { buildCacheKey } from "./sharedRemoteHostCache";
for (const direction of ["download", "upload"] as const) {
test(`failed ${direction} connection replaces Waiting with the actual error (#3698)`, async () => {
@@ -999,3 +1000,86 @@ test("no-conflict local copy awaits discovery so a late stat cannot overwrite th
restore();
}
});
for (const scenario of ["folder-cp", "folder-fallback", "file-cp", "different-key", "missing-key", "non-utf8"] as const) {
test(`fresh remote copy selects a consistent strategy: ${scenario} (#4207)`, async () => {
const isDirectory = scenario.startsWith("folder");
const source = makePane("left");
const target = makePane("left");
target.connection = { ...target.connection!, id: "target-conn", currentPath: "/usr/tmp" };
if (scenario === "non-utf8") target.filenameEncoding = "gb18030";
const key = buildCacheKey("host-1", "debian", 22, "ssh", false, "user", "sftp");
const keys = new Map([["remote-conn", key], ["target-conn", key]]);
if (scenario === "different-key") keys.set("target-conn", buildCacheKey("host-2", "debian", 22, "ssh", false, "user", "sftp"));
if (scenario === "missing-key") keys.delete("target-conn");
const ownerId = `same-host-${scenario}-4207`;
const streams: Array<{ resumable: boolean; sameHost?: boolean; parentTaskId?: string }> = [];
const copies: unknown[][] = [];
let listings = 0;
let ops: ReturnType<typeof useSftpTransfers> | undefined;
let renderer: ReactTestRenderer | undefined;
const restore = installGlobals({
statSftp: async (id: string) => id === "sftp-source"
? { type: "file", size: 3626, lastModified: 1758000001000 }
: null,
mkdirSftp: async () => undefined,
sameHostCopyDirectory: async (...args: unknown[]) => {
copies.push(args);
assert.equal(sftpTransferCenterStore.getTask(args[4] as string)?.resumable, false);
return { success: scenario !== "folder-fallback" };
},
startStreamTransfer: async (options: { transferId: string; resumable: boolean; sameHost?: boolean; parentTaskId?: string }) => {
streams.push(options);
assert.equal(sftpTransferCenterStore.getTask(options.transferId)?.resumable, options.resumable);
sftpTransferCenterStore.ingestBackgroundEvent({
type: "completed", transferId: options.transferId,
transferred: 3626, totalBytes: 3626, lifecycleEpoch: 0,
});
return {};
},
});
function Probe() {
ops = useSftpTransfers({
ownerId,
getActivePane: (side) => side === "left" ? source : target,
getPaneByConnectionId: () => null,
getTabByConnectionId: () => null,
updateTab: () => undefined,
refresh: async () => undefined,
clearCacheForConnection: () => undefined,
handleSessionError: () => undefined,
sftpSessionsRef: { current: new Map([["remote-conn", "sftp-source"], ["target-conn", "sftp-target"]]) },
connectionCacheKeyMapRef: { current: keys },
listLocalFiles: async () => [],
listRemoteFiles: async () => { listings++; return source.files; },
});
return null;
}
try {
await act(async () => { renderer = create(React.createElement(Probe)); });
await act(async () => {
const results = await ops!.startTransfer(
[{ name: isDirectory ? "bt_mine" : "aops_dns_view_demo.sh", isDirectory }], "left", "right",
);
assert.equal(results[0]?.status, "completed");
});
const eligible = ["folder-cp", "folder-fallback", "file-cp"].includes(scenario);
const rows = sftpTransferCenterStore.getOwnerTasks(ownerId);
assert.ok(rows.length > 0);
assert.ok(rows.every(row => row.resumable === !eligible));
assert.equal(copies.length, isDirectory ? 1 : 0);
if (isDirectory) assert.deepEqual(copies[0]?.slice(0, 4), ["sftp-source", "/opt/bt_mine", "/usr/tmp/bt_mine", "auto"]);
assert.equal(listings, scenario === "folder-fallback" ? 1 : 0);
assert.equal(streams.length, scenario === "folder-cp" ? 0 : 1);
if (streams.length) {
assert.equal(streams[0].resumable, !eligible);
assert.equal(streams[0].sameHost, !["different-key", "missing-key"].includes(scenario) || undefined);
if (isDirectory) assert.ok(streams[0].parentTaskId);
}
} finally {
await act(async () => { renderer?.unmount(); });
for (const row of sftpTransferCenterStore.getOwnerTasks(ownerId)) sftpTransferCenterStore.dismiss(row.id);
restore();
}
});
}
+15 -2
View File
@@ -1348,6 +1348,17 @@ export const useSftpTransfers = ({
const sourceConnectionId = options?.sourceConnectionId ?? sourcePane.connection.id;
const batchId = crypto.randomUUID();
const usesLegacyScp = sourcePane.connection.fileProtocol === "scp" || targetPane.connection.fileProtocol === "scp";
const sourceCacheKey = connectionCacheKeyMapRef.current.get(sourcePane.connection.id);
const targetCacheKey = connectionCacheKeyMapRef.current.get(targetPane.connection.id);
const encodingSafeForExec = [sourcePane.filenameEncoding, targetPane.filenameEncoding]
.every((encoding) => !encoding || encoding === "utf-8" || encoding === "auto");
// Select the existing non-resumable cp route only for newly created copies.
// Resume/recovery keeps its saved strategy and checkpoints. If cp fails,
// recursive/download+upload fallback also remains non-resumable.
const useSameHostCopy = !usesLegacyScp
&& !sourcePane.connection.isLocal && !targetPane.connection.isLocal
&& !!sourceCacheKey && sourceCacheKey === targetCacheKey
&& encodingSafeForExec;
const newTasks: TransferTask[] = [];
const skippedResults: TransferResult[] = [];
@@ -1582,8 +1593,10 @@ export const useSftpTransfers = ({
sourceLastModified,
preflightStatSkipped: preflightSkippedNames.has(file.name),
origin: "manual",
resumable: !usesLegacyScp,
pauseUnavailableReason: usesLegacyScp ? "This server uses legacy SCP; cancel and retry from the beginning instead" : undefined,
resumable: !usesLegacyScp && !useSameHostCopy,
pauseUnavailableReason: usesLegacyScp
? "This server uses legacy SCP; cancel and retry from the beginning instead"
: useSameHostCopy ? "Same-host copies cannot be paused; cancel and retry from the beginning instead" : undefined,
phase: file.isDirectory ? "scanning" : "transferring",
});
}
@@ -1505,6 +1505,7 @@ test("pause after terminal close works without any React owner", async () => {
await store.pause("stale-dir");
await new Promise<void>((resolve) => setImmediate(resolve));
assert.equal(store.getSnapshot().tasks.find((row) => row.id === "stale-dir")?.status, "paused");
assert.equal(isTransferPauseLatched("stale-dir"), true);
assert.ok(pauseCalls.includes("stale-child"));
@@ -2413,6 +2414,7 @@ test("dedicated directory resume after soft-pause winds down then startFresh (no
// Soft-pause paints paused under dedicated-resume.
await store.pause("dir");
await new Promise<void>((resolve) => setImmediate(resolve));
assert.equal(store.getSnapshot().tasks.find((task) => task.id === "dir")?.status, "paused");
// Resume must cancel soft-paused children, clear sticky latches, await wind-down, then startFresh.
@@ -2621,7 +2623,7 @@ test("async folder soft-drain does not re-pause after immediate resume", async (
// Pause returns immediately (async soft-drain).
await store.pause("dir-race");
assert.equal(store.getSnapshot().tasks.find((row) => row.id === "dir-race")?.status, "paused");
assert.equal(store.getSnapshot().tasks.find((row) => row.id === "dir-race")?.status, "pausing");
// User hits resume before soft-drain finishes — full store resume (bumps epoch
// + releases latch tree), which is what the UI does.
@@ -2690,21 +2692,33 @@ test("orphan directory pause stays latched even when some children hard-miss pau
await store.pause("dir");
// Folder pause is async: UI is paused immediately; soft-drain may still be running.
// Folder pause stays pending until the child acknowledgements settle.
const dir = store.getSnapshot().tasks.find((task) => task.id === "dir");
assert.equal(dir?.status, "paused", "folder parent must paint paused without waiting on children");
assert.equal(store.getSnapshot().tasks.find((task) => task.id === "c-ok")?.status, "paused");
assert.equal(store.getSnapshot().tasks.find((task) => task.id === "c-fail")?.status, "paused");
// Soft-drain is fire-and-forget — give it a tick to hit the bridge.
await new Promise((resolve) => setTimeout(resolve, 20));
assert.equal(dir?.status, "pausing");
const ownerSnapshotDuringDrain = store.getSnapshot().tasks.map((row) => ({ ...row }));
await new Promise<void>((resolve) => setImmediate(resolve));
assert.equal(store.getTask("c-ok")?.status, "paused");
assert.equal(store.getTask("c-fail")?.status, "transferring");
assert.deepEqual(pauseCalls.sort(), ["c-fail", "c-ok"]);
// Latch-first: do not bridge-resume partial successes (that re-opened the queue).
assert.deepEqual(resumeCalls, []);
assert.equal(
store.getSnapshot().tasks.find((task) => task.id === "dir")?.status,
"paused",
"hard-miss soft-drain must not demote folder out of paused",
"pausing",
"hard miss keeps the folder latched without claiming a successful pause",
);
assert.equal(store.getTask("dir")?.pauseUnavailableReason, "This transfer cannot be paused safely");
store.publishOwner("dedicated-resume", ownerSnapshotDuringDrain);
assert.equal(store.getTask("dir")?.status, "pausing");
assert.equal(store.getTask("dir")?.pauseUnavailableReason, "This transfer cannot be paused safely");
assert.equal(store.getTask("c-ok")?.status, "paused");
assert.equal(store.getTask("c-fail")?.status, "transferring");
store.ingestBackgroundEvent({ type: "progress", transferId: "c-fail", transferred: 25, speed: 10 });
assert.equal(store.getTask("c-fail")?.status, "transferring");
assert.equal(store.getTask("c-fail")?.transferredBytes, 25);
store.patchTask("c-fail", { transferredBytes: 50, speed: 10 });
assert.equal(store.getTask("c-fail")?.status, "transferring");
assert.equal(store.getTask("c-fail")?.transferredBytes, 50);
});
test("dedicated resume source-changed marks attention and can reset checkpoint", async () => {
+27 -11
View File
@@ -353,7 +353,22 @@ export function mergeOwnerPublishedTask(
// Only a strictly newer lifecycle epoch may re-open transferring (resume).
const incomingPaused = incoming.status === "paused" || incoming.status === "pausing";
const existingPaused = existing.status === "paused" || existing.status === "pausing";
if (incomingPaused && incomingLifecycleEpoch >= existingLifecycleEpoch) {
// The panel can publish a snapshot from before the child acknowledgements
// arrived. Only a newer control decision may clear the folder's failure.
const rejectedFolderPause = existing.isDirectory && !existing.parentTaskId
&& existing.status === "pausing" && !!existing.pauseUnavailableReason
&& incomingLifecycleEpoch <= existingLifecycleEpoch
&& isTransferPauseLatched(existing.id);
const rejectedChildPause = parentStatus === "pausing"
&& !!existing.parentTaskId && existing.status === "transferring" && !!existing.pauseUnavailableReason;
if (rejectedFolderPause) {
merged.status = "pausing";
merged.speed = 0;
merged.pauseUnavailableReason = existing.pauseUnavailableReason;
} else if (rejectedChildPause && incomingLifecycleEpoch <= existingLifecycleEpoch) {
merged.status = "transferring";
merged.pauseUnavailableReason = existing.pauseUnavailableReason;
} else if (incomingPaused && incomingLifecycleEpoch >= existingLifecycleEpoch) {
merged.status = incoming.status;
merged.speed = 0;
// Pin the visible bar while paused/latched. Soft-drain must not keep
@@ -392,6 +407,7 @@ export function mergeOwnerPublishedTask(
const parentHoldsPause = parentStatus === "paused" || parentStatus === "pausing";
if (
parentHoldsPause
&& !rejectedChildPause
&& !["completed", "cancelled", "failed"].includes(merged.status)
&& (merged.status === "transferring" || merged.status === "pending" || merged.status === "queued")
) {
@@ -1722,17 +1738,15 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
// Soft-drain / walk progress must not move the visible bar after Pause.
// Latch or paused/pausing freezes transferredBytes/speed unless this patch
// is an explicit resume (transferring + epoch, or dedicated-resume).
const pauseHeld = isTransferOrRootPauseLatched(task.parentTaskId ?? task.id, task.id)
const parent = task.parentTaskId ? tasks.find((candidate) => candidate.id === task.parentTaskId) : undefined;
const rejectedChildPause = parent?.status === "pausing" && !!parent.pauseUnavailableReason
&& task.status === "transferring" && !!task.pauseUnavailableReason;
const pauseHeld = !rejectedChildPause && (isTransferOrRootPauseLatched(task.parentTaskId ?? task.id, task.id)
|| isTransferPauseLatched(task.id)
|| task.status === "paused"
|| task.status === "pausing"
|| (!!task.parentTaskId && (
isTransferPauseLatched(task.parentTaskId)
|| (() => {
const parent = tasks.find((candidate) => candidate.id === task.parentTaskId);
return parent?.status === "paused" || parent?.status === "pausing";
})()
));
|| parent?.status === "paused"
|| parent?.status === "pausing");
if (pauseHeld && !explicitResume) {
// Keep lifecycle at paused/pausing; allow checkpoint metadata only.
if (task.status === "pausing" || task.status === "paused") {
@@ -2451,10 +2465,12 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
task.parentTaskId ?? task.id,
task.id,
) || isTransferPauseLatched(task.id);
const uiPauseLatched = task.status === "paused"
const rejectedChildPause = parentRow?.status === "pausing" && !!parentRow.pauseUnavailableReason
&& task.status === "transferring" && !!task.pauseUnavailableReason;
const uiPauseLatched = !rejectedChildPause && (task.status === "paused"
|| task.status === "pausing"
|| parentHoldsPause
|| selfLatched;
|| selfLatched);
const explicitResume = lifecycleStatus === "transferring"
&& event.lifecycleEpoch !== undefined
&& incomingEpoch > currentEpoch;
@@ -0,0 +1,57 @@
import { useEffect, type RefObject } from 'react';
import { logger } from '../../lib/logger';
const closeCaptures = new Map<string, Set<() => void>>();
/** Notify owning terminals before explicit session removal, never on runtime cleanup. */
export function captureClosingTerminalSessions(sessionIds: readonly string[]): void {
for (const sessionId of new Set(sessionIds)) {
for (const capture of closeCaptures.get(sessionId) ?? []) capture();
}
}
export function useTerminalSessionCloseCapture({
sessionId,
enabled,
hasConnectedRef,
terminalDataCapturedRef,
finalizeTerminalLogData,
onTerminalDataCapture,
}: {
sessionId: string;
enabled: boolean;
hasConnectedRef: RefObject<boolean>;
terminalDataCapturedRef: RefObject<boolean>;
finalizeTerminalLogData: () => string;
onTerminalDataCapture: (
sessionId: string,
data: string,
options: { finalized: true },
) => void | Promise<void>;
}): void {
useEffect(() => {
if (!enabled) return;
const capture = () => {
// Connected terminals retain their existing drain/serialize close path.
if (hasConnectedRef.current || terminalDataCapturedRef.current) return;
try {
// A never-connected runtime is disposed synchronously on unmount.
// Finish its log now, even if empty, so persistence can set endTime.
void Promise.resolve(onTerminalDataCapture(
sessionId, finalizeTerminalLogData(), { finalized: true },
)).catch((err: unknown) => {
logger.warn('Failed to capture terminal log on session close', err);
});
} catch (err) {
logger.warn('Failed to capture terminal log on session close', err);
}
};
const captures = closeCaptures.get(sessionId) ?? new Set<() => void>();
closeCaptures.set(sessionId, captures);
captures.add(capture);
return () => {
captures.delete(capture);
if (!captures.size) closeCaptures.delete(sessionId);
};
}, [sessionId, enabled, hasConnectedRef, terminalDataCapturedRef, finalizeTerminalLogData, onTerminalDataCapture]);
}
+3
View File
@@ -75,6 +75,7 @@ import {
getSessionConnectionLabel,
} from '../../domain/sessionTabTitle';
import { cleanupClosedTerminalSessions } from './aiStateSnapshots';
import { captureClosingTerminalSessions } from './terminalSessionCloseCapture';
import { syncSessionHostLabels } from '../../domain/syncSessionHostLabels';
import { useVaultSnapshotField } from './vaultSnapshotStore';
@@ -603,6 +604,7 @@ export const useSessionState = ({
const closedIds = sessionsRef.current
.filter(session => session.workspaceId === workspaceId)
.map(session => session.id);
captureClosingTerminalSessions(closedIds);
cleanupClosedTerminalSessions(closedIds);
for (const sessionId of closedIds) {
sessionPresentationStore.clearSession(sessionId);
@@ -626,6 +628,7 @@ export const useSessionState = ({
}, [setActiveTabId]);
const closeSessions = useCallback((sessionIds: string[]) => {
captureClosingTerminalSessions(sessionIds);
cleanupClosedTerminalSessions(sessionIds);
for (const sessionId of sessionIds) {
sessionPresentationStore.clearSession(sessionId);
+3 -1
View File
@@ -55,7 +55,7 @@ interface AIChatPanelContentProps {
contextUsage?: import('../application/state/useAgentCompactionUi').AgentContextUsage | null;
inputValue: string;
setInputValue: (value: string) => void;
handleSend: () => void;
handleSend: (textOverride?: string) => void;
handleCompact: () => void;
/** Rename a chat by id (history drawer edit affordance). Panel action, never agent content. */
onRenameSession?: (sessionId: string, title: string) => void;
@@ -211,6 +211,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
parked = false,
sending = false,
}) => {
const handleContinue = React.useCallback(() => handleSend(t('ai.chat.continue')), [handleSend, t]);
const mentionHosts = React.useMemo(
() => terminalSessions.map((session) => ({
sessionId: session.sessionId,
@@ -345,6 +346,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
<ChatMessageList
messages={messages}
isStreaming={isStreaming}
onContinue={handleContinue}
activeSessionId={activeSessionId}
activeCompaction={activeCompaction}
contextCompaction={activeSession?.contextCompaction}
+10 -10
View File
@@ -1610,14 +1610,14 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
}, [currentAgentId, enterScopeDraftMode, updateScopeDraft]);
const handleSend = useCallback(async () => {
const handleSend = useCallback(async (textOverride?: string) => {
const draft = currentDraftRef.current;
const currentPanelView = panelViewRef.current;
const currentSessionView = activeSessionRef.current;
if (!validateNoteMentions(draft?.attachments ?? [])) return;
const trimmed = draft?.text.trim() ?? '';
if (textOverride === undefined && !validateNoteMentions(draft?.attachments ?? [])) return;
const trimmed = (textOverride ?? draft?.text ?? '').trim();
const sendScopeKey = scopeKey;
const attachments = (draft?.attachments ?? []).map((file) => ({
const attachments = (textOverride === undefined ? draft?.attachments ?? [] : []).map((file) => ({
base64Data: file.base64Data,
mediaType: file.mediaType,
filename: file.filename,
@@ -1645,12 +1645,12 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
const agentConfig = sendAgentId !== 'catty' ? findEnabledExternalAgent(externalAgents, sendAgentId) : undefined;
if (sendAgentId !== 'catty' && !agentConfig) return;
const selectedSkillSlugs = draft?.selectedUserSkillSlugs ?? [];
const selectedSkillSlugs = textOverride === undefined ? draft?.selectedUserSkillSlugs ?? [] : [];
const modelPrompt = buildPromptWithTerminalSelectionAttachments(trimmed, attachments);
const modelAttachments = attachments.filter((attachment) => !isInlineTextAttachment(attachment));
const isDraftMode = currentPanelView.mode === 'draft';
flushDraftText();
if (textOverride === undefined) flushDraftText();
const submittedText = draft?.text ?? '';
const keepPendingAfterSend = () => {
const pending = pendingComposerTextRef.current;
@@ -1739,7 +1739,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
const createdSession = createSession(scope, sendAgentId);
sessionId = createdSession.id;
currentSession = createdSession;
clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
if (textOverride === undefined) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
showScopeSessionView(createdSession.id);
setActiveSessionId(createdSession.id);
sessionSendGateKey = sessionId;
@@ -1770,7 +1770,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
});
addMessageToSession(sessionId, { id: generateId(), role: 'assistant', content: t('ai.chat.noProvider'), timestamp: Date.now() });
if (currentPanelView.mode === 'session') {
clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
if (textOverride === undefined) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
showScopeSessionView(sessionId);
}
return;
@@ -1785,7 +1785,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
});
addMessageToSession(sessionId, { id: generateId(), role: 'assistant', content: t('ai.chat.noProviderModel'), timestamp: Date.now() });
if (currentPanelView.mode === 'session') {
clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
if (textOverride === undefined) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
showScopeSessionView(sessionId);
}
return;
@@ -1798,7 +1798,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
...(selectedSkillSlugs.length > 0 ? { selectedUserSkillSlugs: selectedSkillSlugs } : {}),
timestamp: Date.now(),
});
clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
if (textOverride === undefined) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
showScopeSessionView(sessionId);
setActiveSessionId(sessionId);
setStreamingForScope(sessionId, true);
+8 -5
View File
@@ -436,7 +436,7 @@ function TransferRow({
task: TransferTask;
children: TransferTask[];
} | null>(null);
if (task.status === "pausing") {
if (task.status === "pausing" && !task.pauseUnavailableReason) {
if (!pausingSnapshotRef.current) {
pausingSnapshotRef.current = {
task: { ...task },
@@ -464,20 +464,23 @@ function TransferRow({
&& !task.error;
const sharedResuming = useSftpTransferResuming(task.id);
const isResuming = sharedResuming || storeResuming;
const canPause = task.resumable !== false && task.status === "transferring" && canControl && !isResuming;
const pauseFailed = task.status === "pausing" && !!task.pauseUnavailableReason;
const canPause = task.resumable !== false && (task.status === "transferring" || pauseFailed) && canControl && !isResuming;
// Orphaned tasks after app restart (interrupted / attention / paused without a
// live panel owner) must still expose resume/cancel from the global center.
// Conflict rows must use resolveConflict — Resume would overwrite blindly.
// Non-resumable attention rows (e.g. duplicate-destination refusals) are
// terminal: resuming them would start a second writer on the same path.
// Do not show Resume during soft-drain "pausing" — play + spinner together
// makes the row twitch as buttons appear/disappear mid-drain.
// makes the row twitch as buttons appear/disappear mid-drain. A settled
// partial failure is different: offer Retry Pause and explicit Resume.
const canResume = !isResuming && !task.conflict && (
["paused", "interrupted"].includes(task.status)
|| (pauseFailed && task.resumable !== false)
|| (task.status === "attention" && task.resumable !== false)
|| (task.status === "failed" && task.resumable !== false && (task.checkpointBytes ?? 0) > 0)
) && canControl;
const isPausing = task.status === "pausing";
const isPausing = task.status === "pausing" && !pauseFailed;
const canCancel = ["pending", "queued", "transferring", "pausing", "paused", "interrupted", "attention"].includes(task.status) && canControl;
const canRetry = task.status === "failed" && task.retryable !== false && canControl;
const isTerminal = ["completed", "failed", "cancelled"].includes(task.status);
@@ -577,7 +580,7 @@ function TransferRow({
<Pause size={13} />
</TransferAction>
)}
{task.status === "pausing" && (
{task.status === "pausing" && !pauseFailed && (
<div className="flex h-8 w-8 items-center justify-center" role="status" aria-label={t("sftp.transferCenter.status.pausing")}>
<Loader2 size={13} className="animate-spin text-amber-500" />
</div>
+2
View File
@@ -409,6 +409,7 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
const nestedDelayMs = (request.aiSubTab || request.syncSubTab) ? 80 : 40;
const focusHandle = window.setTimeout(() => {
void focusSettingsAnchor(request.anchorId, {
fallbackAnchorId: request.fallbackAnchorId,
attempts: 48,
delayMs: 50,
}).finally(() => {
@@ -549,6 +550,7 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
{mountedTabs.has("appearance") && (
<SettingsLazyTab value="appearance">
<LazySettingsAppearanceTab
pluginRuntimeAvailable={pluginRuntimeAvailable}
theme={settings.theme}
resolvedTheme={settings.resolvedTheme}
setTheme={settings.setTheme}
+17
View File
@@ -206,6 +206,23 @@ test("surfaces pause unavailable reason on a transferring row", () => {
assert.match(markup, /This transfer cannot be paused yet/);
});
test("shows a settled folder pause failure with retry and resume instead of a spinner", () => {
const markup = renderTransferItem({
...baseTask,
isDirectory: true,
status: "pausing",
error: undefined,
speed: 0,
resumable: true,
pauseUnavailableReason: "This transfer cannot be paused yet",
}, { onPause: () => {}, onResume: () => {} });
assert.match(markup, /This transfer cannot be paused yet/);
assert.match(markup, /aria-label="Pause: archive\.tar\.gz"/);
assert.match(markup, /aria-label="Resume: archive\.tar\.gz"/);
assert.doesNotMatch(markup, /aria-busy="true"|aria-label="Pausing:/);
});
test("renders child resize handle as a keyboard-reachable separator", () => {
const markup = renderTransferItem(
{
+23
View File
@@ -82,6 +82,7 @@ import { useStoredBoolean } from "../application/state/useStoredBoolean";
import { readOptionalStoredStringValue, useStoredString } from "../application/state/useStoredString";
import { performSessionLogAction, type SessionLogAction } from "../application/state/sessionLogActions";
import { useSessionLogBackend } from "../application/state/useSessionLogBackend";
import { useTerminalSessionCloseCapture } from "../application/state/terminalSessionCloseCapture";
import { useTerminalLayoutSuppressActive } from "../application/state/terminalLayoutSuppressStore";
import { useAppearanceChromeStore } from "../application/state/appearanceChromeStore";
import {
@@ -1676,6 +1677,28 @@ const TerminalComponent: React.FC<TerminalProps> = ({
return captureHandler(capturedSessionId, capturedData);
}, [finalizeTerminalLogData]);
useTerminalSessionCloseCapture({
sessionId,
enabled: !attachExistingSession && restoreState !== "restored-disconnected",
hasConnectedRef,
terminalDataCapturedRef,
finalizeTerminalLogData,
onTerminalDataCapture: handleTerminalDataCaptureOnce,
});
useEffect(() => {
// Attached popups do not own the ConnectionLog; the home terminal captures it.
if (attachExistingSession) return;
return netcattyBridge.get()?.onFinalizeSessionLogs?.(async () => {
if (terminalDataCapturedRef.current || (restoreState === "restored-disconnected" && statusRef.current === "disconnected")) return;
const term = termRef.current;
if (term && !await flushPendingTerminalWritesBeforeHibernate(term)) {
throw new Error("Terminal output did not drain before quit capture");
}
await handleTerminalDataCaptureOnce(sessionId, finalizeTerminalLogData(), { finalized: true });
});
}, [attachExistingSession, restoreState, sessionId, finalizeTerminalLogData, handleTerminalDataCaptureOnce]);
const attachHomeWebContentsIdRef = useRef<number | null | undefined>(undefined);
useEffect(() => {
+62
View File
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import React from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import { I18nProvider } from "../../application/i18n/I18nProvider.tsx";
import type { ChatMessage } from "../../infrastructure/ai/types.ts";
@@ -644,3 +645,64 @@ test('fork is offered only for safe completed replies and hidden while streaming
assert.equal((render(false).match(/Fork from here/g) ?? []).length, 1);
assert.equal((render(true).match(/Fork from here/g) ?? []).length, 0);
});
test('ChatMessageList renders a non-error iteration limit notice with a Continue action', () => {
const messages: ChatMessage[] = [
{ id: 'poll', role: 'tool', content: '', timestamp: 1,
toolResults: [{ toolCallId: 'poll-1', content: '{"jobId":"job-1","status":"running"}' }] },
{ id: 'limit', role: 'assistant', content: '', timestamp: 2, iterationLimit: 20 },
];
const render = (isStreaming: boolean) => renderToStaticMarkup(
<I18nProvider locale="en">
<TooltipProvider>
<ChatMessageList messages={messages} isStreaming={isStreaming} onContinue={() => {}} />
</TooltipProvider>
</I18nProvider>,
);
const markup = render(false);
assert.match(markup, /Tool-loop limit \(20 iterations\) reached/);
assert.match(markup, /<button[^>]*>Continue<\/button>/);
assert.doesNotMatch(markup, /bg-destructive/);
assert.match(render(true), /<button[^>]*disabled=""[^>]*>Continue<\/button>/);
const source = readFileSync(new URL('./ChatMessageList.tsx', import.meta.url), 'utf8');
const panel = readFileSync(new URL('../AIChatPanelContent.tsx', import.meta.url), 'utf8');
const sidePanel = readFileSync(new URL('../AIChatSidePanel.tsx', import.meta.url), 'utf8');
assert.match(source, /onClick=\{onContinue\}/);
assert.match(panel, /onContinue=\{handleContinue\}/);
assert.match(panel, /handleContinue = React.useCallback\(\(\) => handleSend\(t\('ai.chat.continue'\)\)/);
assert.match(sidePanel, /const handleSend = useCallback\(async \(textOverride\?: string\)/);
assert.match(sidePanel, /const trimmed = \(textOverride \?\? draft\?\.text \?\? ''\)\.trim\(\)/);
});
test('iteration limit Continue button invokes the provided send callback', async t => {
const previousWindow = globalThis.window;
const actGlobal = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
const previousActEnvironment = actGlobal.IS_REACT_ACT_ENVIRONMENT;
globalThis.window = { setTimeout, clearTimeout } as unknown as Window & typeof globalThis;
actGlobal.IS_REACT_ACT_ENVIRONMENT = true;
t.after(() => {
globalThis.window = previousWindow;
actGlobal.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
});
let continued = 0;
let renderer: ReactTestRenderer;
await act(async () => {
renderer = create(
<I18nProvider locale="en">
<TooltipProvider>
<ChatMessageList
messages={[{ id: 'limit', role: 'assistant', content: '', timestamp: 1, iterationLimit: 20 }]}
onContinue={() => { continued += 1; }}
/>
</TooltipProvider>
</I18nProvider>,
);
});
const button = renderer!.root.findAllByType('button').find(node => node.children.includes('Continue'));
assert.ok(button);
assert.equal(button.props.disabled, false);
await act(async () => { button.props.onClick(); });
assert.equal(continued, 1);
await act(async () => { renderer!.unmount(); });
});
+16
View File
@@ -90,6 +90,7 @@ import ChatJumpNav from './ChatJumpNav';
interface ChatMessageListProps {
messages: ChatMessage[];
isStreaming?: boolean;
onContinue?: () => void;
/** Active chat session ID — used to filter standalone MCP approval blocks */
activeSessionId?: string | null;
activeCompaction?: ActiveCompactionUi | null;
@@ -185,6 +186,7 @@ export function pruneResolvedApprovals(
const ChatMessageList: React.FC<ChatMessageListProps> = ({
messages,
isStreaming,
onContinue,
activeSessionId,
activeCompaction = null,
contextCompaction,
@@ -813,6 +815,18 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
</div>
)}
{message.iterationLimit != null && (
<div role="status" className="rounded-md border border-border/60 bg-muted/30 px-3 py-2 text-sm">
<p>{t('ai.chat.iterationLimitReached', { limit: message.iterationLimit })}</p>
<button
type="button"
onClick={onContinue}
disabled={!!isStreaming || !onContinue}
className="mt-2 rounded-md border border-border px-2 py-1 text-xs font-medium hover:bg-muted disabled:opacity-50 disabled:cursor-not-allowed"
>{t('ai.chat.continue')}</button>
</div>
)}
{/* Error info */}
{message.errorInfo && (
<div className="flex items-start gap-2 px-3 py-2 rounded-md bg-destructive/10 border border-destructive/20 text-sm">
@@ -1079,6 +1093,7 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
function areMessagesEqual(prev: ChatMessageListProps, next: ChatMessageListProps): boolean {
if (prev.isStreaming !== next.isStreaming) return false;
if (prev.onContinue !== next.onContinue) return false;
if (prev.activeSessionId !== next.activeSessionId) return false;
if (prev.notes !== next.notes) return false;
if (prev.hosts !== next.hosts) return false;
@@ -1107,6 +1122,7 @@ function areMessagesEqual(prev: ChatMessageListProps, next: ChatMessageListProps
p.statusText !== n.statusText ||
p.executionStatus !== n.executionStatus ||
p.errorInfo !== n.errorInfo ||
p.iterationLimit !== n.iterationLimit ||
p.toolCalls !== n.toolCalls ||
p.toolResults !== n.toolResults ||
p.agentActivities !== n.agentActivities ||
+24
View File
@@ -71,6 +71,30 @@ test('buildManagedAgentState keeps unrelated defaults when removing stale manage
assert.equal(state.defaultAgentId, 'custom-agent');
});
test('a failed saved-path probe keeps the override, preferences, and default until recovery', () => {
const agent: ExternalAgentConfig = {
id: 'discovered_copilot',
name: 'GitHub Copilot CLI',
command: 'C:/npm/copilot.cmd',
commandSource: 'manual',
sdkBackend: 'copilot',
enabled: false,
available: true,
};
const unavailable = buildManagedAgentState([agent], agent.id, 'copilot', null, 'manual');
assert.deepEqual(unavailable.agents, [{ ...agent, available: false }]);
assert.equal(unavailable.defaultAgentId, agent.id);
assert.equal(getInitialManagedAgentPaths(unavailable.agents).copilot, agent.command);
const recovered = buildManagedAgentState(unavailable.agents, agent.id, 'copilot', {
path: agent.command, version: '1.0.106', available: true,
}, 'manual');
assert.equal(recovered.agents[0].available, true);
assert.equal(recovered.agents[0].enabled, false);
assert.equal(recovered.defaultAgentId, agent.id);
assert.deepEqual(buildManagedAgentState(recovered.agents, agent.id, 'copilot', null, 'auto').agents, []);
});
test('buildManagedAgentState stores the system Claude executable for SDK runs', () => {
const state = buildManagedAgentState(
[],
+18 -22
View File
@@ -392,10 +392,9 @@ test("note editor exposes its modes from a borderless title-row dropdown", () =>
// The app-owned NoteToolbar (not MDXEditor's toolbarPlugin) hosts the
// formatting controls; MDXEditor must not render its own toolbar.
assert.doesNotMatch(source, /toolbarPlugin\(/);
assert.match(toolbarSource, /onAction\?\.\("undo"\)/);
assert.match(toolbarSource, /onAction\?\.\("redo"\)/);
assert.match(toolbarSource, /<Undo2 size=\{14\} \/>/);
assert.match(toolbarSource, /<Redo2 size=\{14\} \/>/);
assert.match(toolbarSource, /id: "undo", icon: Undo2/);
assert.match(toolbarSource, /id: "redo", icon: Redo2/);
assert.match(toolbarSource, /onAction\?\.\(item\.id\)/);
// Preview and edit both use MDXEditor (readOnly in preview).
assert.match(source, /readOnly=\{editorMode === "preview"\}/);
assert.match(source, /key=\{editorMode\}/);
@@ -439,24 +438,21 @@ test("note markdown toolbar remains usable in narrow panes", () => {
styles,
/\.netcatty-mdx-editor\s*\{[^}]*transform:\s*translateZ\(0\);/s,
);
// The app-owned NoteToolbar scrolls horizontally when the pane is narrow so
// formatting buttons are never clipped; the scrollbar stays visible.
assert.match(
toolbarSource,
/overflow-x-auto [^"]*\[scrollbar-width:thin\]/,
);
assert.match(
toolbarSource,
/\[&::-webkit-scrollbar\]:h-1\.5/,
);
assert.match(
toolbarSource,
/\[&::-webkit-scrollbar-thumb\]:bg-border\/70/,
);
assert.match(
toolbarSource,
/flex flex-1 items-center gap-0\.5 min-w-0 overflow-x-auto/,
);
// The app-owned NoteToolbar collapses excess controls into the shared menu.
assert.match(toolbarSource, /<ToolbarOverflowMenu/);
assert.match(toolbarSource, /data-note-format-toolbar/);
assert.doesNotMatch(toolbarSource, /overflow-x-auto|scrollbar-width:thin|webkit-scrollbar/);
});
test("MDX link dialog overlay stays inside the retained notes editor container", () => {
const source = readFileSync(new URL("./InlineMarkdownEditor.tsx", import.meta.url), "utf8");
// Default MDXEditor popup target is document.body. Keep the overlay in the
// editor container so section `hidden` and vault visibility:hidden hide it (#4257).
assert.match(source, /const \[overlayContainer, setOverlayContainer\] = useState<HTMLElement \| null>\(null\);/);
assert.match(source, /setOverlayContainer\(\(current\) => \(current === node \? current : node\)\);/);
assert.match(source, /ref=\{setEditorContainer\}/);
assert.match(source, /overlayContainer=\{overlayContainer \?\? undefined\}/);
});
test("preview mode opens links directly without showing the edit hover action", () => {
+10 -1
View File
@@ -946,6 +946,14 @@ export const InlineMarkdownEditor = React.memo(
});
const containerRef = useRef<HTMLDivElement>(null);
// MDXEditor portals .mdxeditor-popup-container to document.body unless
// overlayContainer is set. Notes stays mounted and is only CSS-hidden, so a
// body portal would leave the link preview toolbar over other pages (#4257).
const [overlayContainer, setOverlayContainer] = useState<HTMLElement | null>(null);
const setEditorContainer = useCallback((node: HTMLDivElement | null) => {
containerRef.current = node;
setOverlayContainer((current) => (current === node ? current : node));
}, []);
const getSelectedText = useCallback((): string => {
const container = containerRef.current;
@@ -2063,7 +2071,7 @@ export const InlineMarkdownEditor = React.memo(
return (
<div
ref={containerRef}
ref={setEditorContainer}
className="relative flex h-full flex-col"
style={{
["--note-font-family" as string]: noteFontFamily || undefined,
@@ -2223,6 +2231,7 @@ export const InlineMarkdownEditor = React.memo(
<MDXEditor
key={editorMode}
ref={editorRef}
overlayContainer={overlayContainer ?? undefined}
markdown={
mdxRetry !== null && value === mdxRetry.staleValue
? normalizeNotePublicAssetPaths(mdxRetry.markdown)
+242
View File
@@ -0,0 +1,242 @@
import assert from "node:assert/strict";
import test from "node:test";
import { JSDOM } from "jsdom";
test("NoteToolbar fits formatting controls to the available row width", async (t) => {
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', {
pretendToBeVisual: true,
url: "http://localhost",
});
const { window } = dom;
const previousGlobals = new Map<string, PropertyDescriptor | undefined>();
const installGlobal = (key: string, value: unknown) => {
previousGlobals.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
};
let rowWidth = 900;
const observers = new Set<ResizeObserverStub>();
class ResizeObserverStub {
target: Element | null = null;
constructor(readonly callback: ResizeObserverCallback) { observers.add(this); }
observe(target: Element) { this.target = target; }
unobserve() { this.target = null; }
disconnect() { observers.delete(this); }
}
const originalRect = window.HTMLElement.prototype.getBoundingClientRect;
window.HTMLElement.prototype.getBoundingClientRect = function () {
if (this.hasAttribute("data-note-format-toolbar")) {
return new window.DOMRect(0, 0, rowWidth, 26);
}
return originalRect.call(this);
};
for (const key of [
"document", "navigator", "HTMLElement", "HTMLInputElement", "HTMLButtonElement",
"Element", "SVGElement", "Node", "NodeFilter", "MutationObserver", "CustomEvent",
"Event", "MouseEvent", "DOMRect",
]) {
installGlobal(key, window[key as keyof typeof window]);
}
installGlobal("window", window);
installGlobal("getComputedStyle", window.getComputedStyle.bind(window));
installGlobal("requestAnimationFrame", window.requestAnimationFrame.bind(window));
installGlobal("cancelAnimationFrame", window.cancelAnimationFrame.bind(window));
installGlobal("ResizeObserver", ResizeObserverStub);
installGlobal("IS_REACT_ACT_ENVIRONMENT", true);
const { default: React, act } = await import("react");
const { createRoot } = await import("react-dom/client");
const { I18nProvider } = await import("../../application/i18n/I18nProvider.tsx");
const { TooltipProvider } = await import("../ui/tooltip.tsx");
const { NoteToolbar } = await import("./NoteToolbar.tsx");
const { EMPTY_ACTIVE_FORMATS } = await import("./noteEditorTypes.ts");
const root = createRoot(window.document.getElementById("root")!);
const actions: string[] = [];
const sizes: number[] = [];
const codeSizes: number[] = [];
const fonts: string[] = [];
const render = async (mode: "edit" | "source" | "preview" = "edit") => {
await act(async () => root.render(
<I18nProvider locale="en">
<TooltipProvider>
<NoteToolbar
editorMode={mode}
onAction={(action) => actions.push(action)}
onChangeNoteFontFamily={(font) => fonts.push(font)}
onChangeNoteFontSize={(size) => sizes.push(size)}
onChangeNoteCodeFontSize={(size) => codeSizes.push(size)}
activeFormats={{ ...EMPTY_ACTIVE_FORMATS, bold: true }}
/>
</TooltipProvider>
</I18nProvider>,
));
};
const row = (): HTMLElement => {
const element = window.document.querySelector<HTMLElement>("[data-note-format-toolbar]");
assert.ok(element);
assert.ok(element.classList.contains("overflow-hidden"));
assert.doesNotMatch(element.className, /overflow-x-auto|overflow-auto|scrollbar/);
assert.ok(!element.classList.contains("flex-wrap"));
return element;
};
const button = (label: string, parent: ParentNode = window.document) => {
const element = Array.from(parent.querySelectorAll<HTMLButtonElement>("button"))
.find((candidate) => candidate.title === label || candidate.textContent?.trim() === label);
assert.ok(element, `${label} should be reachable`);
return element;
};
const click = async (element: HTMLElement) => {
await act(async () => {
element.click();
await new Promise((resolve) => window.setTimeout(resolve, 70));
});
};
const resize = async (width: number) => {
rowWidth = width;
await act(async () => {
for (const observer of observers) {
if (observer.target?.hasAttribute("data-note-format-toolbar")) {
observer.callback([{
target: observer.target,
contentRect: new window.DOMRect(0, 0, width, 26),
} as ResizeObserverEntry], observer as unknown as ResizeObserver);
}
}
});
};
const openOverflow = async (): Promise<HTMLElement> => {
const trigger = row().querySelector<HTMLButtonElement>("[data-toolbar-overflow-trigger]");
assert.ok(trigger);
await click(trigger);
const menu = window.document.querySelector<HTMLElement>("[data-toolbar-overflow-menu]");
assert.ok(menu);
return menu;
};
try {
await render();
const defaultOrder = Array.from(row().querySelectorAll("button"), (element) => element.title);
await t.test("wide row preserves all controls inline without a scrollbar track", async () => {
assert.equal(defaultOrder.length, 19);
assert.deepEqual(defaultOrder.slice(0, 5), ["Undo (Ctrl+Z)", "Redo (Ctrl+Y)", "Code font and typography settings", "Heading Level", "Bold (Ctrl+B)"]);
assert.equal(defaultOrder.at(-1), "Insert Image");
assert.equal(row().querySelector("[data-toolbar-overflow-trigger]"), null);
assert.ok(button("Bold (Ctrl+B)", row()).classList.contains("bg-primary/15"));
const mouseDown = new window.MouseEvent("mousedown", { bubbles: true, cancelable: true });
button("Bold (Ctrl+B)", row()).dispatchEvent(mouseDown);
assert.equal(mouseDown.defaultPrevented, true, "formatting preserves the editor selection");
await click(button("Bold (Ctrl+B)", row()));
assert.equal(actions.at(-1), "bold");
});
await t.test("narrow row spills the end of the existing order and keeps every action reachable", async () => {
await resize(320);
const inlineLabels = Array.from(row().querySelectorAll<HTMLButtonElement>("button[title]"), (element) => element.title);
assert.ok(inlineLabels.length < defaultOrder.length);
assert.deepEqual(inlineLabels, defaultOrder.slice(0, inlineLabels.length));
const menu = await openOverflow();
const overflowLabels = Array.from(menu.querySelectorAll("button"), (element) => element.title);
assert.deepEqual([...inlineLabels, ...overflowLabels], defaultOrder);
const expectedActions = ["bullet", "number", "task", "quote", "codeblock", "math", "table", "divider", "link", "image"];
for (let index = 0; index < overflowLabels.length; index += 1) {
const currentMenu = index === 0 ? menu : await openOverflow();
await click(button(overflowLabels[index], currentMenu));
assert.equal(actions.at(-1), expectedActions[index]);
assert.equal(window.document.querySelector("[data-toolbar-overflow-menu]"), null);
}
});
await t.test("very narrow row exposes undo, headings, and typography through nested overflow menus", async () => {
await resize(26);
assert.equal(row().querySelectorAll("button").length, 1);
await click(button("Undo (Ctrl+Z)", await openOverflow()));
assert.equal(actions.at(-1), "undo");
await click(button("Redo (Ctrl+Y)", await openOverflow()));
assert.equal(actions.at(-1), "redo");
await click(button("Heading Level", await openOverflow()));
assert.ok(window.document.querySelector("[data-toolbar-overflow-menu]"));
let nested = window.document.querySelector<HTMLElement>("[data-toolbar-nested-menu]");
assert.ok(nested);
await click(nested.querySelector<HTMLButtonElement>("button")!);
assert.equal(actions.at(-1), "h1");
assert.equal(window.document.querySelector("[data-toolbar-overflow-menu]"), null);
for (const setting of ["font", "body", "code"] as const) {
await click(button("Code font and typography settings", await openOverflow()));
nested = window.document.querySelector<HTMLElement>("[data-toolbar-nested-menu]");
assert.ok(nested);
assert.ok(window.document.querySelector("[data-toolbar-overflow-menu]"));
const sections = nested.children;
const section = sections[setting === "font" ? 0 : setting === "body" ? 1 : 2];
await click(section.querySelector<HTMLButtonElement>("button")!);
assert.equal(window.document.querySelector("[data-toolbar-overflow-menu]"), null);
}
assert.deepEqual(fonts, [""]);
assert.deepEqual(sizes, [12]);
assert.deepEqual(codeSizes, [11]);
});
await t.test("resizing back to wide restores controls and removes the overflow trigger", async () => {
await resize(900);
assert.deepEqual(Array.from(row().querySelectorAll("button"), (element) => element.title), defaultOrder);
assert.equal(row().querySelector("[data-toolbar-overflow-trigger]"), null);
});
await t.test("source mode and returning from preview remeasure the same format row", async () => {
await render("preview");
assert.equal(window.document.querySelector("[data-note-format-toolbar]"), null);
rowWidth = 200;
await render("source");
const menu = await openOverflow();
assert.ok(button("Bold (Ctrl+B)", row()).classList.contains("bg-primary/15"));
await click(button("Insert Image", menu));
assert.equal(actions.at(-1), "image");
});
} finally {
await act(async () => {
root.unmount();
await new Promise((resolve) => window.setTimeout(resolve, 100));
});
assert.equal(observers.size, 0);
dom.window.close();
for (const [key, descriptor] of previousGlobals) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
}
});
test("full notes and the sidebar overlay both render the shared format toolbar", async () => {
const { renderToStaticMarkup } = await import("react-dom/server");
const { I18nProvider } = await import("../../application/i18n/I18nProvider.tsx");
const { TooltipProvider } = await import("../ui/tooltip.tsx");
const { NotesManager } = await import("./NotesManager.tsx");
for (const displayMode of ["full", "sidebar"] as const) {
const markup = renderToStaticMarkup(
<I18nProvider locale="en">
<TooltipProvider>
<NotesManager
notes={[{ id: "note-1", title: "Test note", content: "# Note", group: "", createdAt: 1, updatedAt: 1, order: 1 }]}
noteGroups={[]}
hosts={[]}
onUpdateNotes={() => undefined}
onUpdateNoteGroups={() => undefined}
displayMode={displayMode}
openNoteId="note-1"
/>
</TooltipProvider>
</I18nProvider>,
);
const dom = new JSDOM(markup);
try {
const rows = dom.window.document.querySelectorAll("[data-note-format-toolbar]");
assert.equal(rows.length, 1, `${displayMode} should use NoteToolbar`);
assert.doesNotMatch(rows[0].className, /overflow-x-auto|overflow-auto|scrollbar/);
assert.equal(rows[0].querySelectorAll("button").length, 19);
assert.equal(dom.window.document.querySelector("[data-note-title-row] button[title='Undo (Ctrl+Z)']"), null);
} finally {
dom.window.close();
}
}
});
+288 -348
View File
@@ -28,13 +28,14 @@ import {
Underline,
Undo2,
} from "lucide-react";
import React, { useMemo, useState } from "react";
import React, { useLayoutEffect, useMemo, useRef, useState } from "react";
import { type MarkdownActionType } from "../../domain/notes";
import { useAvailableFonts } from "../../application/state/fontStore";
import { useI18n } from "../../application/i18n/I18nProvider";
import type { ActiveTextFormats, NoteEditorMode } from "./noteEditorTypes";
import { EMPTY_ACTIVE_FORMATS } from "./noteEditorTypes";
import { Dropdown, DropdownContent, DropdownTrigger } from "../ui/dropdown";
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
import { ToolbarOverflowMenu, useToolbarOverflowClose } from "../ui/toolbar-item-layout";
import { Select, SelectContent, SelectItem, SelectTrigger } from "../ui/select";
import { cn } from "../../lib/utils";
@@ -62,6 +63,76 @@ export interface NoteModeDropdownProps {
const FONT_SIZES = [12, 13, 14, 15, 16, 18, 20];
const CODE_FONT_SIZES = [11, 12, 13, 14, 15, 16, 18];
const toolbarButtonClass = "flex h-[26px] w-[26px] shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground transition-colors";
const overflowItemClass = "flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs text-muted-foreground hover:bg-muted hover:text-foreground transition-colors";
// Preserve the format row's visual order, including the existing group boundaries.
const FORMAT_ITEMS = [
{ id: "undo", icon: Undo2, label: "undo" },
{ id: "redo", icon: Redo2, label: "redo" },
{ id: "typography", icon: Type, label: "typography", separator: true },
{ id: "heading", icon: Heading, label: "headingLevel" },
{ id: "bold", icon: Bold, label: "bold", format: "bold" },
{ id: "italic", icon: Italic, label: "italic", format: "italic" },
{ id: "strikethrough", icon: Strikethrough, label: "strikethrough", format: "strikethrough" },
{ id: "underline", icon: Underline, label: "underline", format: "underline" },
{ id: "code", icon: Code, label: "inlineCode", format: "code" },
{ id: "bullet", icon: List, label: "bulletList", separator: true },
{ id: "number", icon: ListOrdered, label: "orderedList" },
{ id: "task", icon: CheckSquare, label: "taskList" },
{ id: "quote", icon: Quote, label: "quote", separator: true },
{ id: "codeblock", icon: FileCode, label: "codeBlock" },
{ id: "math", icon: Sigma, label: "mathFormula" },
{ id: "table", icon: TableIcon, label: "table" },
{ id: "divider", icon: Minus, label: "divider" },
{ id: "link", icon: LinkIcon, label: "link" },
{ id: "image", icon: ImageIcon, label: "image" },
] as const;
// 26px icon buttons, 2px gaps; each separator adds 9px plus another gap.
const formatRowWidth = (count: number) =>
count * 28 - 2 + FORMAT_ITEMS.slice(0, count).filter((item) => "separator" in item).length * 11;
/** Nested controls follow the same keep-open / leaf-close contract as SFTP. */
const NoteToolbarPopover: React.FC<{
label: string;
icon: React.ReactNode;
collapsed: boolean;
contentClassName: string;
children: React.ReactNode;
}> = ({ label, icon, collapsed, contentClassName, children }) => {
const closeOverflow = useToolbarOverflowClose();
return (
<Popover>
<PopoverTrigger asChild>
<button
type="button"
className={collapsed ? overflowItemClass : toolbarButtonClass}
title={label}
aria-label={label}
data-toolbar-overflow-keep-open="true"
onMouseDown={(event) => event.preventDefault()}
>
{icon}
{collapsed && <span>{label}</span>}
</button>
</PopoverTrigger>
<PopoverContent
align="start"
className={contentClassName}
data-toolbar-nested-menu="true"
onOpenAutoFocus={(event) => event.preventDefault()}
onCloseAutoFocus={(event) => event.preventDefault()}
onClick={(event) => {
if ((event.target as Element).closest("button")) closeOverflow();
}}
>
{children}
</PopoverContent>
</Popover>
);
};
export const NoteModeDropdown: React.FC<NoteModeDropdownProps> = ({
editorMode,
onChangeMode,
@@ -163,360 +234,229 @@ export const NoteToolbar: React.FC<NoteToolbarProps> = ({
const isEditing = editorMode === "edit" || editorMode === "live" || editorMode === "source";
const formatRowRef = useRef<HTMLDivElement>(null);
const [availableWidth, setAvailableWidth] = useState(Infinity);
useLayoutEffect(() => {
const row = formatRowRef.current;
if (!row) return;
setAvailableWidth(row.getBoundingClientRect().width);
const observer = new ResizeObserver((entries) => {
for (const entry of entries) setAvailableWidth(entry.contentRect.width);
});
observer.observe(row);
return () => observer.disconnect();
}, [isEditing]);
if (!isEditing) return null;
// Highlight style for toggles that are active at the current selection.
const formatButtonClass = (active: boolean) =>
cn(
"p-1.5 rounded-md transition-colors",
active
? "bg-primary/15 text-primary hover:bg-primary/20 hover:text-primary"
: "hover:bg-muted text-muted-foreground hover:text-foreground",
let inlineCount = FORMAT_ITEMS.length;
if (formatRowWidth(inlineCount) > availableWidth) {
// Reserve a button and gap for the overflow trigger, then spill from the end.
while (inlineCount > 0 && formatRowWidth(inlineCount) + 28 > availableWidth) {
inlineCount -= 1;
}
}
const renderItem = (item: (typeof FORMAT_ITEMS)[number], collapsed = false) => {
const Icon = item.icon;
const label = t(`notes.toolbar.${item.label}`);
if (item.id === "typography") {
return (
<NoteToolbarPopover
key={item.id}
label={label}
icon={<Icon size={14} />}
collapsed={collapsed}
contentClassName="w-64 p-2.5 space-y-2.5 text-xs shadow-lg"
>
<div className="space-y-1.5">
<div className="flex items-center justify-between text-[11px] font-medium text-muted-foreground">
<span>{t("notes.toolbar.customCodeFont")}</span>
<span className="text-[10px] opacity-70">
{t("notes.toolbar.fontsAvailable", { count: systemFontList.length })}
</span>
</div>
{/* Search Bar */}
<div className="relative flex items-center">
<Search size={12} className="absolute left-2 text-muted-foreground pointer-events-none" />
<input
type="text"
placeholder={t("notes.toolbar.searchFont")}
value={fontSearch}
onChange={(e) => setFontSearch(e.target.value)}
className="w-full pl-6 pr-2 py-1 rounded border border-border bg-background text-[11px] text-foreground outline-none focus:border-primary placeholder:text-muted-foreground/60"
/>
</div>
{/* Scrollable Font List */}
<div className="space-y-0.5 max-h-52 overflow-y-auto pr-1">
{filteredFonts.length === 0 ? (
<div className="py-2 text-center text-muted-foreground text-[11px]">
{t("notes.toolbar.noFontsFound")}
</div>
) : (
filteredFonts.map((f) => (
<button
key={f.value}
type="button"
style={{ fontFamily: f.value || undefined }}
className={cn(
"w-full px-2 py-1 rounded text-left text-xs transition-colors flex items-center justify-between gap-1.5",
(noteFontFamily || "") === f.value
? "bg-primary text-primary-foreground font-medium"
: "hover:bg-secondary text-foreground",
)}
onClick={() => onChangeNoteFontFamily?.(f.value)}
>
<span className="truncate">{f.label}</span>
{(noteFontFamily || "") === f.value && <Check size={12} className="shrink-0" />}
</button>
))
)}
</div>
</div>
<div className="border-t border-border/60 pt-2">
<div className="text-[11px] font-medium text-muted-foreground mb-1">{t("notes.toolbar.bodyFontSize")}</div>
<div className="flex flex-wrap gap-1">
{FONT_SIZES.map((sz) => (
<button
key={sz}
type="button"
className={cn(
"px-2 py-0.5 rounded text-xs border transition-colors",
(noteFontSize || 14) === sz
? "bg-primary text-primary-foreground border-primary font-medium"
: "border-border hover:bg-secondary text-foreground",
)}
onClick={() => onChangeNoteFontSize?.(sz)}
>
{sz}px
</button>
))}
</div>
</div>
<div className="border-t border-border/60 pt-2">
<div className="text-[11px] font-medium text-muted-foreground mb-1">{t("notes.toolbar.codeFontSize")}</div>
<div className="flex flex-wrap gap-1">
{CODE_FONT_SIZES.map((sz) => (
<button
key={sz}
type="button"
className={cn(
"px-2 py-0.5 rounded text-xs border transition-colors font-mono",
(noteCodeFontSize || 13) === sz
? "bg-primary text-primary-foreground border-primary font-medium"
: "border-border hover:bg-secondary text-foreground",
)}
onClick={() => onChangeNoteCodeFontSize?.(sz)}
>
{sz}px
</button>
))}
</div>
</div>
</NoteToolbarPopover>
);
}
if (item.id === "heading") {
return (
<NoteToolbarPopover
key={item.id}
label={label}
icon={<Icon size={14} />}
collapsed={collapsed}
contentClassName="w-32 py-1 text-xs"
>
<button
type="button"
className="w-full px-3 py-1.5 flex items-center gap-2 hover:bg-secondary text-foreground transition-colors text-left"
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("h1")}
>
<Heading1 size={14} className="text-primary" />
<span>{t("notes.toolbar.h1")}</span>
</button>
<button
type="button"
className="w-full px-3 py-1.5 flex items-center gap-2 hover:bg-secondary text-foreground transition-colors text-left"
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("h2")}
>
<Heading2 size={14} className="text-primary" />
<span>{t("notes.toolbar.h2")}</span>
</button>
<button
type="button"
className="w-full px-3 py-1.5 flex items-center gap-2 hover:bg-secondary text-foreground transition-colors text-left"
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("h3")}
>
<Heading3 size={14} className="text-primary" />
<span>{t("notes.toolbar.h3")}</span>
</button>
<button
type="button"
className="w-full px-3 py-1.5 flex items-center gap-2 hover:bg-secondary text-foreground transition-colors text-left"
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("h4")}
>
<Heading4 size={14} className="text-primary" />
<span>{t("notes.toolbar.h4")}</span>
</button>
</NoteToolbarPopover>
);
}
const active = "format" in item && activeFormats[item.format];
return (
<button
key={item.id}
type="button"
className={cn(
collapsed ? overflowItemClass : toolbarButtonClass,
active && "bg-primary/15 text-primary hover:bg-primary/20 hover:text-primary",
)}
onMouseDown={(event) => event.preventDefault()}
onClick={() => onAction?.(item.id)}
title={label}
aria-label={label}
>
<Icon size={14} />
{collapsed && <span>{label}</span>}
</button>
);
};
return (
<div
className={`flex items-center gap-1.5 px-3 py-1.5 border-b border-border/70 bg-card/40 text-xs select-none min-w-0 ${className}`}
>
{/* Formatting Tools (Available in Live Preview & Source Mode) */}
<div className="flex flex-1 items-center gap-0.5 min-w-0 overflow-x-auto [scrollbar-width:thin] [&::-webkit-scrollbar]:h-1.5 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-border/70 [&::-webkit-scrollbar-track]:bg-transparent">
{/* Undo / Redo */}
<button
type="button"
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0"
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("undo")}
title={t("notes.toolbar.undo")}
>
<Undo2 size={14} />
</button>
<button
type="button"
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0"
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("redo")}
title={t("notes.toolbar.redo")}
>
<Redo2 size={14} />
</button>
<div className="h-4 w-px bg-border mx-1 shrink-0" />
{/* Code Font & Typography Settings Dropdown */}
<Dropdown>
<DropdownTrigger asChild>
<button
type="button"
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0"
title={t("notes.toolbar.typography")}
onMouseDown={(e) => e.preventDefault()}
>
<Type size={14} />
</button>
</DropdownTrigger>
<DropdownContent align="start" className="w-64 p-2.5 space-y-2.5 z-50 text-xs shadow-lg">
<div className="space-y-1.5">
<div className="flex items-center justify-between text-[11px] font-medium text-muted-foreground">
<span>{t("notes.toolbar.customCodeFont")}</span>
<span className="text-[10px] opacity-70">
{t("notes.toolbar.fontsAvailable", { count: systemFontList.length })}
</span>
</div>
{/* Search Bar */}
<div className="relative flex items-center">
<Search size={12} className="absolute left-2 text-muted-foreground pointer-events-none" />
<input
type="text"
placeholder={t("notes.toolbar.searchFont")}
value={fontSearch}
onChange={(e) => setFontSearch(e.target.value)}
className="w-full pl-6 pr-2 py-1 rounded border border-border bg-background text-[11px] text-foreground outline-none focus:border-primary placeholder:text-muted-foreground/60"
/>
</div>
{/* Scrollable Font List */}
<div className="space-y-0.5 max-h-52 overflow-y-auto pr-1">
{filteredFonts.length === 0 ? (
<div className="py-2 text-center text-muted-foreground text-[11px]">
{t("notes.toolbar.noFontsFound")}
</div>
) : (
filteredFonts.map((f) => (
<button
key={f.value}
type="button"
style={{ fontFamily: f.value || undefined }}
className={cn(
"w-full px-2 py-1 rounded text-left text-xs transition-colors flex items-center justify-between gap-1.5",
(noteFontFamily || "") === f.value
? "bg-primary text-primary-foreground font-medium"
: "hover:bg-secondary text-foreground",
)}
onClick={() => onChangeNoteFontFamily?.(f.value)}
>
<span className="truncate">{f.label}</span>
{(noteFontFamily || "") === f.value && <Check size={12} className="shrink-0" />}
</button>
))
)}
</div>
</div>
<div className="border-t border-border/60 pt-2">
<div className="text-[11px] font-medium text-muted-foreground mb-1">{t("notes.toolbar.bodyFontSize")}</div>
<div className="flex flex-wrap gap-1">
{FONT_SIZES.map((sz) => (
<button
key={sz}
type="button"
className={cn(
"px-2 py-0.5 rounded text-xs border transition-colors",
(noteFontSize || 14) === sz
? "bg-primary text-primary-foreground border-primary font-medium"
: "border-border hover:bg-secondary text-foreground",
)}
onClick={() => onChangeNoteFontSize?.(sz)}
>
{sz}px
</button>
))}
</div>
</div>
<div className="border-t border-border/60 pt-2">
<div className="text-[11px] font-medium text-muted-foreground mb-1">{t("notes.toolbar.codeFontSize")}</div>
<div className="flex flex-wrap gap-1">
{CODE_FONT_SIZES.map((sz) => (
<button
key={sz}
type="button"
className={cn(
"px-2 py-0.5 rounded text-xs border transition-colors font-mono",
(noteCodeFontSize || 13) === sz
? "bg-primary text-primary-foreground border-primary font-medium"
: "border-border hover:bg-secondary text-foreground",
)}
onClick={() => onChangeNoteCodeFontSize?.(sz)}
>
{sz}px
</button>
))}
</div>
</div>
</DropdownContent>
</Dropdown>
{/* Heading Dropdown (Using Portal Dropdown to avoid clipping) */}
<Dropdown>
<DropdownTrigger asChild>
<button
type="button"
className="flex items-center gap-1 p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
onMouseDown={(e) => e.preventDefault()}
title={t("notes.toolbar.headingLevel")}
>
<Heading size={14} />
</button>
</DropdownTrigger>
<DropdownContent align="start" className="w-32 py-1 z-50 text-xs">
<button
type="button"
className="w-full px-3 py-1.5 flex items-center gap-2 hover:bg-secondary text-foreground transition-colors text-left"
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("h1")}
>
<Heading1 size={14} className="text-primary" />
<span>{t("notes.toolbar.h1")}</span>
</button>
<button
type="button"
className="w-full px-3 py-1.5 flex items-center gap-2 hover:bg-secondary text-foreground transition-colors text-left"
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("h2")}
>
<Heading2 size={14} className="text-primary" />
<span>{t("notes.toolbar.h2")}</span>
</button>
<button
type="button"
className="w-full px-3 py-1.5 flex items-center gap-2 hover:bg-secondary text-foreground transition-colors text-left"
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("h3")}
>
<Heading3 size={14} className="text-primary" />
<span>{t("notes.toolbar.h3")}</span>
</button>
<button
type="button"
className="w-full px-3 py-1.5 flex items-center gap-2 hover:bg-secondary text-foreground transition-colors text-left"
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("h4")}
>
<Heading4 size={14} className="text-primary" />
<span>{t("notes.toolbar.h4")}</span>
</button>
</DropdownContent>
</Dropdown>
{/* Inline Styles */}
<button
type="button"
className={formatButtonClass(activeFormats.bold)}
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("bold")}
title={t("notes.toolbar.bold")}
>
<Bold size={14} />
</button>
<button
type="button"
className={formatButtonClass(activeFormats.italic)}
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("italic")}
title={t("notes.toolbar.italic")}
>
<Italic size={14} />
</button>
<button
type="button"
className={formatButtonClass(activeFormats.strikethrough)}
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("strikethrough")}
title={t("notes.toolbar.strikethrough")}
>
<Strikethrough size={14} />
</button>
<button
type="button"
className={formatButtonClass(activeFormats.underline)}
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("underline")}
title={t("notes.toolbar.underline")}
>
<Underline size={14} />
</button>
<button
type="button"
className={formatButtonClass(activeFormats.code)}
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("code")}
title={t("notes.toolbar.inlineCode")}
>
<Code size={14} />
</button>
<div className="h-4 w-px bg-border mx-1 shrink-0" />
{/* Lists */}
<button
type="button"
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("bullet")}
title={t("notes.toolbar.bulletList")}
>
<List size={14} />
</button>
<button
type="button"
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("number")}
title={t("notes.toolbar.orderedList")}
>
<ListOrdered size={14} />
</button>
<button
type="button"
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("task")}
title={t("notes.toolbar.taskList")}
>
<CheckSquare size={14} />
</button>
<div className="h-4 w-px bg-border mx-1 shrink-0" />
{/* Blocks */}
<button
type="button"
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("quote")}
title={t("notes.toolbar.quote")}
>
<Quote size={14} />
</button>
<button
type="button"
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("codeblock")}
title={t("notes.toolbar.codeBlock")}
>
<FileCode size={14} />
</button>
<button
type="button"
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("math")}
title={t("notes.toolbar.mathFormula")}
>
<Sigma size={14} />
</button>
<button
type="button"
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("table")}
title={t("notes.toolbar.table")}
>
<TableIcon size={14} />
</button>
<button
type="button"
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("divider")}
title={t("notes.toolbar.divider")}
>
<Minus size={14} />
</button>
<button
type="button"
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("link")}
title={t("notes.toolbar.link")}
>
<LinkIcon size={14} />
</button>
<button
type="button"
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
onMouseDown={(e) => e.preventDefault()}
onClick={() => onAction?.("image")}
title={t("notes.toolbar.image")}
>
<ImageIcon size={14} />
</button>
<div
ref={formatRowRef}
data-note-format-toolbar
className="flex flex-1 items-center gap-[2px] min-w-0 overflow-hidden"
>
{FORMAT_ITEMS.slice(0, inlineCount).map((item) => (
<React.Fragment key={item.id}>
{"separator" in item && <div className="h-4 w-px bg-border mx-[4px] shrink-0" />}
{renderItem(item)}
</React.Fragment>
))}
<ToolbarOverflowMenu
hasItems={inlineCount < FORMAT_ITEMS.length}
label={t("terminal.toolbar.more")}
orientation="vertical"
buttonClassName={toolbarButtonClass}
contentClassName="max-h-[min(32rem,var(--radix-popover-content-available-height))] overflow-y-auto"
align="start"
>
<div className="flex min-w-[140px] flex-col">
{FORMAT_ITEMS.slice(inlineCount).map((item) => renderItem(item, true))}
</div>
</ToolbarOverflowMenu>
</div>
</div>
);
@@ -93,6 +93,7 @@ export function SettingsSearchControl({
aiSubTab: hit.entry.aiSubTab,
syncSubTab: hit.entry.syncSubTab,
anchorId: hit.entry.id,
fallbackAnchorId: hit.entry.fallbackAnchorId,
});
collapseSearch(false);
};
+2 -1
View File
@@ -36,7 +36,7 @@ export const Toggle: React.FC<ToggleProps> = ({ checked, onChange, disabled, ari
interface SelectProps {
value: string;
options: { value: string; label: string; icon?: React.ReactNode }[];
options: { value: string; label: string; icon?: React.ReactNode; disabled?: boolean }[];
onChange: (value: string) => void;
className?: string;
disabled?: boolean;
@@ -87,6 +87,7 @@ export const Select: React.FC<SelectProps> = ({
<SelectPrimitive.Item
key={opt.value}
value={opt.value}
disabled={opt.disabled}
className="relative flex w-full min-w-0 cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
+97 -1
View File
@@ -1,6 +1,102 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import test, { type TestContext } from "node:test";
import { settingsAnchorDomId } from "../../domain/settingsSearchCatalog.ts";
import { focusSettingsAnchor } from "./settingsFocus.ts";
function setupFocusDom(t: TestContext) {
t.mock.timers.enable({ apis: ["setTimeout"] });
const anchors = new Map<string, HTMLElement>();
const focused: string[] = [];
const scrolled: string[] = [];
const globals = {
document: {
getElementById: (id: string) => anchors.get(id) ?? null,
querySelectorAll: () => [],
documentElement: {},
body: {},
},
window: { setTimeout, clearTimeout },
CSS: { escape: (value: string) => value },
requestAnimationFrame: (callback: FrameRequestCallback) => { callback(0); return 0; },
};
for (const [key, value] of Object.entries(globals)) {
const previous = Object.getOwnPropertyDescriptor(globalThis, key);
Object.defineProperty(globalThis, key, { configurable: true, value });
t.after(() => {
if (previous) Object.defineProperty(globalThis, key, previous);
else Reflect.deleteProperty(globalThis, key);
});
}
const mount = (id: string, visible = true) => {
const classes = new Set<string>();
const el = {
closest: () => null,
checkVisibility: () => visible,
classList: { add: (name: string) => classes.add(name), remove: (name: string) => classes.delete(name) },
matches: () => true,
hasAttribute: () => true,
focus: () => focused.push(id),
scrollIntoView: () => scrolled.push(id),
} as unknown as HTMLElement;
anchors.set(settingsAnchorDomId(id), el);
return classes;
};
return { mount, focused, scrolled };
}
test("missing search target focuses and highlights its visible parent after a short mount window", async (t) => {
const { mount, focused, scrolled } = setupFocusDom(t);
const parentClasses = mount("parent");
const result = focusSettingsAnchor("child", { fallbackAnchorId: "parent", attempts: 48, delayMs: 50 });
for (let retry = 0; retry < 3; retry += 1) t.mock.timers.tick(50);
t.mock.timers.tick(49);
assert.deepEqual(focused, []);
t.mock.timers.tick(1);
assert.equal(await result, true);
assert.deepEqual(focused, ["parent"]);
assert.deepEqual(scrolled, ["parent"]);
assert.ok(parentClasses.has("settings-search-highlight"));
});
test("search focus prefers a visible primary over its fallback", async (t) => {
const { mount, focused } = setupFocusDom(t);
const childClasses = mount("child");
const parentClasses = mount("parent");
assert.equal(await focusSettingsAnchor("child", { fallbackAnchorId: "parent" }), true);
assert.deepEqual(focused, ["child"]);
assert.ok(childClasses.has("settings-search-highlight"));
assert.equal(parentClasses.has("settings-search-highlight"), false);
});
test("search focus waits for a lazy primary before using a visible fallback", async (t) => {
const { mount, focused } = setupFocusDom(t);
mount("parent");
const result = focusSettingsAnchor("child", { fallbackAnchorId: "parent" });
t.mock.timers.tick(50);
t.mock.timers.tick(50);
mount("child");
t.mock.timers.tick(50);
assert.equal(await result, true);
assert.deepEqual(focused, ["child"]);
});
test("search focus skips a hidden primary and waits for a visible fallback", async (t) => {
const { mount, focused } = setupFocusDom(t);
mount("child", false);
mount("parent", false);
const result = focusSettingsAnchor("child", { fallbackAnchorId: "parent" });
for (let retry = 0; retry < 4; retry += 1) t.mock.timers.tick(50);
assert.deepEqual(focused, []);
mount("parent");
t.mock.timers.tick(50);
assert.equal(await result, true);
assert.deepEqual(focused, ["parent"]);
});
test("system setting hints sit below their cards with a shared top gap", () => {
const uiSource = readFileSync(new URL("./settings-ui.tsx", import.meta.url), "utf8");
+24 -15
View File
@@ -4,12 +4,15 @@ const HIGHLIGHT_CLASS = "settings-search-highlight";
const HIGHLIGHT_MS = 1600;
/** Keep focused anchors slightly below the top of the settings content pane. */
const SCROLL_TOP_PADDING_PX = 24;
/** Allow 200ms at the default retry delay for lazy tab / sub-tab mounts. */
const FALLBACK_AFTER_ATTEMPTS = 5;
export type SettingsFocusTarget = {
tab: string;
aiSubTab?: string;
syncSubTab?: string;
anchorId: string;
fallbackAnchorId?: string;
};
let focusGeneration = 0;
@@ -30,6 +33,18 @@ function isAnchorVisible(el: HTMLElement): boolean {
return el.getClientRects().length > 0;
}
function findVisibleAnchor(anchorId: string): HTMLElement | undefined {
const candidates = [
document.getElementById(settingsAnchorDomId(anchorId)),
...Array.from(
document.querySelectorAll<HTMLElement>(
`[data-settings-anchor="${CSS.escape(anchorId)}"]`,
),
),
].filter((node): node is HTMLElement => Boolean(node));
return candidates.find((node) => isAnchorVisible(node));
}
function focusAnchorElement(el: HTMLElement): void {
const focusable = el.matches("button, a, input, select, textarea, [tabindex]")
? el
@@ -103,15 +118,16 @@ export function scrollSettingsAnchorIntoView(
/**
* Scroll the settings content pane to a catalog anchor and briefly highlight it.
* Retries to cover lazy tab mounts / nested sub-tab switches.
* After a short mount window, use a visible parent fallback for gated rows.
*/
export function focusSettingsAnchor(
anchorId: string,
options?: { attempts?: number; delayMs?: number },
options?: { attempts?: number; delayMs?: number; fallbackAnchorId?: string },
): Promise<boolean> {
const attempts = options?.attempts ?? 40;
const delayMs = options?.delayMs ?? 50;
const generation = ++focusGeneration;
let remaining = attempts;
let attempt = 0;
return new Promise((resolve) => {
const finish = (ok: boolean) => {
@@ -125,20 +141,13 @@ export function focusSettingsAnchor(
return;
}
const domId = settingsAnchorDomId(anchorId);
const candidates = [
document.getElementById(domId),
...Array.from(
document.querySelectorAll<HTMLElement>(
`[data-settings-anchor="${CSS.escape(anchorId)}"]`,
),
),
].filter((node): node is HTMLElement => Boolean(node));
const el = candidates.find((node) => isAnchorVisible(node));
attempt += 1;
let el = findVisibleAnchor(anchorId);
if (!el && options?.fallbackAnchorId && attempt >= Math.min(FALLBACK_AFTER_ATTEMPTS, attempts)) {
el = findVisibleAnchor(options.fallbackAnchorId);
}
if (!el) {
remaining -= 1;
if (remaining > 0) {
if (attempt < attempts) {
window.setTimeout(tryFocus, delayMs);
return;
}
@@ -258,6 +258,7 @@ export const AppLockSettingsSection: React.FC<AppLockSettingsSectionProps> = ({
</SettingRow>
<SettingRow
anchorId="system-app-lock-timeout"
label={t('settings.appLock.timeout')}
description={t('settings.appLock.timeoutDesc')}
>
@@ -66,9 +66,15 @@ test('local logging controls default off, disclose verbose risk, and call host-o
assert.match(document.querySelector('[role=alert]')!.textContent!, /synthetic preferences write failed/);
await act(async () => button('Close').click());
assert.equal(document.querySelector('[role=dialog]'), null);
assert.equal(document.activeElement, configure);
// Radix restores focus in a setTimeout(0) after the dialog unmounts.
// act() can finish before that timer, so drain it before checking focus.
await new Promise((resolve) => setTimeout(resolve, 0));
// Comparing DOM objects directly makes Node inspect the entire JSDOM graph
// on failure, which can stall the test process while formatting the diff.
assert.ok(document.activeElement === configure, `expected focus on Configure, got ${document.activeElement?.tagName}`);
} finally {
await act(async () => root.unmount());
await new Promise((resolve) => setTimeout(resolve, 0));
dom.window.close();
for (const [key, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
@@ -2,9 +2,12 @@ import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import vm from "node:vm";
import React, { useCallback, useEffect, useRef, useState } from "react";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import TestRenderer, { act } from "react-test-renderer";
import ts from "typescript";
import { canSendWithAgent } from "../../ai/agentSendEligibility";
import { buildManagedAgentState, getUnavailablePreferredHarness } from "./ai/managedAgentState";
import type { ExternalAgentConfig } from "../../../infrastructure/ai/types";
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -94,3 +97,61 @@ test("an older AI detection result cannot replace or finish the newer request",
assert.equal(h.state.busy, false);
} finally { await act(async () => h.root.unmount()); }
});
// Mount the same option computation and normalization effect that the
// Settings tab runs after a probe has updated the actual saved agent state.
const pickerStart = source.indexOf(" // Agent options for default agent");
const pickerEnd = source.indexOf("\n useEffect(() => {\n const bridge", pickerStart);
assert.ok(pickerStart >= 0 && pickerEnd > pickerStart);
const runDefaultPicker = vm.runInNewContext(ts.transpile(`(function(ctx) {
const { useMemo, useEffect, externalAgents, defaultAgentId, setDefaultAgentId, t,
canSendWithAgent, getUnavailablePreferredHarness, React, AgentIconBadge } = ctx;
${source.slice(pickerStart, pickerEnd)}
return agentOptions;
})`, { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React }), { console }) as
(ctx: Record<string, unknown>) => { value: string; disabled?: boolean }[];
test("Settings retains the unavailable saved default, blocks sends and restores the same choice", async () => {
const agent: ExternalAgentConfig = {
id: "discovered_copilot",
name: "GitHub Copilot CLI",
command: "/fixture/copilot",
commandSource: "manual",
sdkBackend: "copilot",
enabled: true,
available: true,
};
let options: ReturnType<typeof runDefaultPicker> = [];
let choice = "";
function Harness({ agents }: { agents: ExternalAgentConfig[] }) {
const [defaultAgentId, setDefaultAgentId] = useState(agent.id);
options = runDefaultPicker({
useMemo, useEffect, externalAgents: agents, defaultAgentId, setDefaultAgentId,
t: (key: string) => key, canSendWithAgent, getUnavailablePreferredHarness, React,
AgentIconBadge: () => null,
});
choice = defaultAgentId;
return null;
}
const failed = buildManagedAgentState([agent], agent.id, "copilot", null, "manual");
const recovered = buildManagedAgentState(failed.agents, agent.id, "copilot", {
path: agent.command, available: true, version: "1.0.106",
}, "manual");
let root!: TestRenderer.ReactTestRenderer;
const render = (agents: ExternalAgentConfig[]) => React.createElement(Harness, { agents });
try {
await act(async () => { root = TestRenderer.create(render([agent])); });
await act(async () => { root.update(render(failed.agents)); });
assert.equal(choice, agent.id);
assert.equal(options.find(option => option.value === agent.id)?.disabled, true);
assert.equal(canSendWithAgent(choice, failed.agents), false);
await act(async () => { root.update(render(recovered.agents)); });
assert.equal(choice, agent.id);
assert.equal(options.find(option => option.value === agent.id)?.disabled, undefined);
assert.equal(canSendWithAgent(choice, recovered.agents), true);
const reset = buildManagedAgentState(recovered.agents, agent.id, "copilot", null, "auto");
await act(async () => { root.update(render(reset.agents)); });
assert.equal(choice, "catty");
} finally { await act(async () => root.unmount()); }
});
+31 -12
View File
@@ -68,6 +68,7 @@ import {
areExternalAgentListsEqual,
buildManagedAgentState,
getInitialManagedAgentPaths,
getUnavailablePreferredHarness,
updateCodebuddyManagedEnv,
updateCodebuddyManagedOptions,
} from "./ai/managedAgentState";
@@ -392,6 +393,10 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
: setMimoPathInfo;
setInfo(result);
const savedPaths = initialManagedPathsRef.current;
if (savedPaths && (commandSource === "auto" || (result?.available && result.path))) {
savedPaths[agentKey] = commandSource === "manual" ? result?.path ?? "" : "";
}
let nextDefaultId: string | null = null;
setExternalAgents((prev) => {
@@ -414,7 +419,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
apiKeyPresent?: boolean;
refreshShellEnv?: boolean;
commandSource?: "manual" | "auto";
removeUnavailableManualPath?: boolean;
recheckSavedPath?: boolean;
},
) => {
const bridge = getBridge();
@@ -461,7 +466,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
options?.commandSource === "manual"
&& customPath.trim()
&& !result?.available
&& !options.removeUnavailableManualPath
&& !options.recheckSavedPath
) {
const setInfo = agentKey === "codex"
? setCodexPathInfo
@@ -525,9 +530,14 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
void resolveAgentPath(task.key, task.path, {
...task.options,
commandSource: task.path ? "manual" : "auto",
removeUnavailableManualPath: Boolean(task.path),
}).finally(() => {
autoResolvedAgentStateRef.current[task.key] = "done";
recheckSavedPath: Boolean(task.path),
}).then((result) => {
if (result?.available) {
autoResolvedAgentStateRef.current[task.key] = "done";
} else {
// Retry a failed check on the next visit to the Agents tab.
delete autoResolvedAgentStateRef.current[task.key];
}
});
}, task.delayMs));
return () => {
@@ -646,13 +656,22 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
[removeProvider, editingProviderId, removeProviderConfirm],
);
// Agent options for default agent
const agentOptions = useMemo(() => [
{ value: "catty", label: t('ai.defaultAgent.catty'), icon: <AgentIconBadge agent={{ id: "catty", type: "builtin" }} size="xs" variant="plain" /> },
...externalAgents
.filter((a) => canSendWithAgent(a.id, externalAgents))
.map((a) => ({ value: a.id, label: a.name, icon: <AgentIconBadge agent={a} size="xs" variant="plain" /> })),
], [externalAgents, t]);
// Agent options for default agent. Include a saved default that is temporarily offline as a disabled option.
// This preserves the setting without offering that harness for new selections.
const agentOptions = useMemo(() => {
const unavailable = getUnavailablePreferredHarness(externalAgents, defaultAgentId);
return [
{ value: "catty", label: t('ai.defaultAgent.catty'), icon: <AgentIconBadge agent={{ id: "catty", type: "builtin" }} size="xs" variant="plain" /> },
...externalAgents
.filter((a) => a === unavailable || canSendWithAgent(a.id, externalAgents))
.map((a) => ({
value: a.id,
label: a === unavailable ? `${a.name} (${t('ai.defaultAgent.unavailable')})` : a.name,
icon: <AgentIconBadge agent={a} size="xs" variant="plain" />,
disabled: a === unavailable ? true : undefined,
})),
];
}, [externalAgents, defaultAgentId, t]);
useEffect(() => {
if (!agentOptions.some((option) => option.value === defaultAgentId)) {
@@ -40,6 +40,7 @@ const CUSTOM_CSS_HELP_PROSE_CLASS =
"text-xs text-foreground/90 leading-relaxed [&>*:first-child]:mt-0 [&>*:last-child]:mb-0";
function SettingsAppearanceTab(props: {
pluginRuntimeAvailable: boolean;
theme: "dark" | "light" | "system";
resolvedTheme: "dark" | "light";
setTheme: (theme: "dark" | "light" | "system") => void;
@@ -366,7 +367,9 @@ function SettingsAppearanceTab(props: {
{renderThemeSwatches(visibleUiThemes, visibleUiThemeId, setVisibleUiThemeId)}
</div>
</SettingsAnchor>
<PluginThemePicker mode={resolvedTheme} onRestore={() => (resolvedTheme === "dark" ? setDarkUiThemeId : setLightUiThemeId)(resolvedTheme === "dark" ? "midnight" : "snow")} />
{props.pluginRuntimeAvailable && (
<PluginThemePicker mode={resolvedTheme} onRestore={() => (resolvedTheme === "dark" ? setDarkUiThemeId : setLightUiThemeId)(resolvedTheme === "dark" ? "midnight" : "snow")} />
)}
{pluginThemeError && <p role="alert" className="text-xs text-destructive">{pluginThemeError}</p>}
<SettingRow
anchorId="appearance-accent-mode"
@@ -9,6 +9,13 @@ test("SFTP settings imports the shared Toggle used by its option rows", () => {
assert.match(source, /Toggle,\s*\n\s*Select,/);
});
test("folder compression row exposes its settings search anchor", () => {
assert.match(
source,
/<SettingRow\s+anchorId="sftp-compressed-upload"\s+label=\{t\('settings\.sftp\.compressedUpload\.enable'\)\}/,
);
});
function functionBody(functionName: string): string {
const start = source.indexOf(`const ${functionName} = useCallback`);
assert.notEqual(start, -1, `${functionName} should exist`);
@@ -180,6 +180,7 @@ export default function SettingsFileAssociationsTab() {
<SectionHeader title={t('settings.sftp.compressedUpload')} />
<SettingCard>
<SettingRow
anchorId="sftp-compressed-upload"
label={t('settings.sftp.compressedUpload.enable')}
description={t('settings.sftp.compressedUpload.enableDesc')}
>
@@ -231,12 +232,14 @@ export default function SettingsFileAssociationsTab() {
</div>
</SettingRow>
<SettingRow
anchorId="sftp-skip-unchanged"
label={t('settings.sftp.skipUnchanged.enable')}
description={t('settings.sftp.skipUnchanged.enableDesc')}
>
<Toggle checked={sftpSkipUnchanged} onChange={setSftpSkipUnchanged} />
</SettingRow>
<SettingRow
anchorId="sftp-transport-idle-ttl"
label={t('settings.ssh.transportIdleTtl')}
description={t('settings.ssh.transportIdleTtl.desc')}
>
@@ -693,6 +693,7 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
{httpNetworkProxy.mode === "custom" && (
<>
<SettingRow
anchorId="system-network-proxy-url"
label={t("settings.system.networkProxy.url")}
description={t("settings.system.networkProxy.url.desc")}
>
@@ -710,6 +711,7 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
/>
</SettingRow>
<SettingRow
anchorId="system-network-proxy-bypass"
label={t("settings.system.networkProxy.bypass")}
description={t("settings.system.networkProxy.bypass.desc")}
>
@@ -1088,7 +1090,7 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
</SettingRow>
{/* Directory Selection */}
<div className="space-y-2">
<SettingsAnchor anchorId="system-session-logs-directory" className="space-y-2">
<div className="flex items-center gap-2">
<span className="text-sm font-medium">{t("settings.sessionLogs.directory")}</span>
</div>
@@ -1125,10 +1127,11 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
<p className="text-xs text-muted-foreground">
{t("settings.sessionLogs.directoryHint")}
</p>
</div>
</SettingsAnchor>
{/* Format Selection */}
<SettingRow
anchorId="system-session-logs-format"
label={t("settings.sessionLogs.format")}
description={t("settings.sessionLogs.formatDesc")}
>
@@ -1141,6 +1144,7 @@ const SettingsSystemTab: React.FC<SettingsSystemTabProps> = ({
</SettingRow>
<SettingRow
anchorId="system-session-logs-timestamps"
label={t("settings.sessionLogs.timestamps")}
description={t("settings.sessionLogs.timestampsDesc")}
>
@@ -814,6 +814,7 @@ function SettingsTerminalTab(props: {
</SettingRow>
<SettingRow
anchorId="terminal-side-panel-auto-open-pane"
label={t("settings.terminal.sidePanel.autoOpenPane")}
description={t("settings.terminal.sidePanel.autoOpenPane.desc")}
>
@@ -841,6 +842,7 @@ function SettingsTerminalTab(props: {
</SettingRow>
<SettingRow
anchorId="terminal-local-shell-side-panel-auto-open-pane"
label={t("settings.terminal.localShellSidePanel.autoOpenPane")}
description={t("settings.terminal.localShellSidePanel.autoOpenPane.desc")}
>
@@ -945,6 +947,7 @@ function SettingsTerminalTab(props: {
</SettingRow>
<SettingRow
anchorId="terminal-local-shell-start-dir"
label={t("settings.terminal.localShell.startDir")}
description={t("settings.terminal.localShell.startDir.desc")}
>
@@ -1048,6 +1051,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-keepalive-count-max"
label={t("settings.terminal.connection.keepaliveCountMax")}
description={t("settings.terminal.connection.keepaliveCountMax.desc")}
>
@@ -1082,6 +1086,7 @@ function SettingsTerminalTab(props: {
<SectionHeader title={t("settings.terminal.section.serverStats")} />
<div className="space-y-0 divide-y divide-border rounded-lg border bg-card px-4">
<SettingRow
anchorId="terminal-host-info-bar-show"
label={t("settings.terminal.hostInfoBar.show")}
description={t("settings.terminal.hostInfoBar.show.desc")}
>
@@ -1092,6 +1097,7 @@ function SettingsTerminalTab(props: {
</SettingRow>
{terminalSettings.showHostInfoBar && (
<SettingRow
anchorId="terminal-host-info-bar-title-mode"
label={t("settings.terminal.hostInfoBar.titleMode")}
description={t("settings.terminal.hostInfoBar.titleMode.desc")}
>
@@ -1119,6 +1125,7 @@ function SettingsTerminalTab(props: {
{terminalSettings.showServerStats && (
<SettingRow
anchorId="terminal-server-stats-refresh-interval"
label={t("settings.terminal.serverStats.refreshInterval")}
description={t("settings.terminal.serverStats.refreshInterval.desc")}
>
@@ -1145,6 +1152,7 @@ function SettingsTerminalTab(props: {
<SectionHeader title={t("settings.terminal.section.systemManager")} />
<div className="space-y-0 divide-y divide-border rounded-lg border bg-card px-4">
<SettingRow
anchorId="terminal-system-manager-process-refresh-interval"
label={t("settings.terminal.systemManager.processRefreshInterval")}
description={t("settings.terminal.systemManager.processRefreshInterval.desc")}
>
@@ -1166,6 +1174,7 @@ function SettingsTerminalTab(props: {
</div>
</SettingRow>
<SettingRow
anchorId="terminal-system-manager-tmux-refresh-interval"
label={t("settings.terminal.systemManager.tmuxRefreshInterval")}
description={t("settings.terminal.systemManager.tmuxRefreshInterval.desc")}
>
@@ -1187,6 +1196,7 @@ function SettingsTerminalTab(props: {
</div>
</SettingRow>
<SettingRow
anchorId="terminal-system-manager-docker-list-refresh-interval"
label={t("settings.terminal.systemManager.dockerListRefreshInterval")}
description={t("settings.terminal.systemManager.dockerListRefreshInterval.desc")}
>
@@ -1208,6 +1218,7 @@ function SettingsTerminalTab(props: {
</div>
</SettingRow>
<SettingRow
anchorId="terminal-system-manager-docker-stats-refresh-interval"
label={t("settings.terminal.systemManager.dockerStatsRefreshInterval")}
description={t("settings.terminal.systemManager.dockerStatsRefreshInterval.desc")}
>
@@ -1249,6 +1260,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-hibernate-hidden-tabs"
label={t("settings.terminal.rendering.hibernateHiddenTabs")}
description={t("settings.terminal.rendering.hibernateHiddenTabs.desc")}
>
@@ -1260,6 +1272,7 @@ function SettingsTerminalTab(props: {
{terminalSettings.hibernateHiddenTabs && (
<>
<SettingRow
anchorId="terminal-hibernate-hidden-tabs-delay"
label={t("settings.terminal.rendering.hibernateHiddenTabsDelay")}
description={t("settings.terminal.rendering.hibernateHiddenTabsDelay.desc")}
>
@@ -1281,6 +1294,7 @@ function SettingsTerminalTab(props: {
</div>
</SettingRow>
<SettingRow
anchorId="terminal-hibernate-skip-alt-screen"
label={t("settings.terminal.rendering.hibernateSkipAltScreen")}
description={t("settings.terminal.rendering.hibernateSkipAltScreen.desc")}
>
@@ -1290,6 +1304,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-hibernate-keep-renderer-count"
label={t("settings.terminal.rendering.hibernateKeepRendererCount")}
description={t("settings.terminal.rendering.hibernateKeepRendererCount.desc")}
>
@@ -1308,6 +1323,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-hibernate-replay-chunk-bytes"
label={t("settings.terminal.rendering.hibernateReplayChunkBytes")}
description={t("settings.terminal.rendering.hibernateReplayChunkBytes.desc")}
>
@@ -1327,6 +1343,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-hibernate-prefer-wasm-serialize"
label={t("settings.terminal.rendering.hibernatePreferWasmSerialize")}
description={t("settings.terminal.rendering.hibernatePreferWasmSerialize.desc")}
>
@@ -1354,6 +1371,7 @@ function SettingsTerminalTab(props: {
{terminalSettings.inlineImagesEnabled && (
<>
<SettingRow
anchorId="terminal-inline-images-kitty"
label={t("settings.terminal.inlineImages.kitty")}
description={t("settings.terminal.inlineImages.kitty.desc")}
>
@@ -1363,6 +1381,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-inline-images-sixel"
label={t("settings.terminal.inlineImages.sixel")}
description={t("settings.terminal.inlineImages.sixel.desc")}
>
@@ -1372,6 +1391,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-inline-images-iip"
label={t("settings.terminal.inlineImages.iip")}
description={t("settings.terminal.inlineImages.iip.desc")}
>
@@ -1381,6 +1401,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-inline-images-storage-limit"
label={t("settings.terminal.inlineImages.storageLimit")}
description={t("settings.terminal.inlineImages.storageLimit.desc")}
>
@@ -1406,6 +1427,7 @@ function SettingsTerminalTab(props: {
</div>
</SettingRow>
<SettingRow
anchorId="terminal-inline-images-max-megapixels"
label={t("settings.terminal.inlineImages.maxMegapixels")}
description={t("settings.terminal.inlineImages.maxMegapixels.desc")}
>
@@ -1431,6 +1453,7 @@ function SettingsTerminalTab(props: {
</div>
</SettingRow>
<SettingRow
anchorId="terminal-inline-images-sequence-limit"
label={t("settings.terminal.inlineImages.sequenceLimit")}
description={t("settings.terminal.inlineImages.sequenceLimit.desc")}
>
@@ -1496,6 +1519,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-autocomplete-ghost-text"
label={t("settings.terminal.autocomplete.ghostText")}
description={t("settings.terminal.autocomplete.ghostText.desc")}
>
@@ -1506,6 +1530,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-autocomplete-popup-menu"
label={t("settings.terminal.autocomplete.popupMenu")}
description={t("settings.terminal.autocomplete.popupMenu.desc")}
>
@@ -1516,6 +1541,7 @@ function SettingsTerminalTab(props: {
/>
</SettingRow>
<SettingRow
anchorId="terminal-autocomplete-history-scope"
label={t("settings.terminal.autocomplete.historyScope")}
description={t("settings.terminal.autocomplete.historyScope.desc")}
>
@@ -101,6 +101,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-right-click-long-press-menu"
label={t("settings.terminal.behavior.rightClick.longPressMenu")}
description={t("settings.terminal.behavior.rightClick.longPressMenu.desc")}
>
@@ -111,6 +112,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-right-click-fullscreen-menu"
label={t("settings.terminal.behavior.rightClick.fullscreenMenu")}
description={t("settings.terminal.behavior.rightClick.fullscreenMenu.desc")}
>
@@ -228,6 +230,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-shift-enter-newline-text"
label={t("settings.terminal.behavior.shiftEnterNewlineText")}
description={t("settings.terminal.behavior.shiftEnterNewlineText.desc")}
>
@@ -260,6 +263,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-preserve-selection-on-input"
label={t("settings.terminal.behavior.preserveSelectionOnInput")}
description={t("settings.terminal.behavior.preserveSelectionOnInput.desc")}
>
@@ -267,6 +271,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-force-prompt-new-line"
label={t("settings.terminal.behavior.forcePromptNewLine")}
description={t("settings.terminal.behavior.forcePromptNewLine.desc")}
>
@@ -341,6 +346,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-scroll-on-input"
label={t("settings.terminal.behavior.scrollOnInput")}
description={t("settings.terminal.behavior.scrollOnInput.desc")}
>
@@ -348,6 +354,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-scroll-on-output"
label={t("settings.terminal.behavior.scrollOnOutput")}
description={t("settings.terminal.behavior.scrollOnOutput.desc")}
>
@@ -355,6 +362,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-scroll-on-key-press"
label={t("settings.terminal.behavior.scrollOnKeyPress")}
description={t("settings.terminal.behavior.scrollOnKeyPress.desc")}
>
@@ -362,6 +370,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-scroll-on-paste"
label={t("settings.terminal.behavior.scrollOnPaste")}
description={t("settings.terminal.behavior.scrollOnPaste.desc")}
>
@@ -369,6 +378,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-smooth-scrolling"
label={t("settings.terminal.behavior.smoothScrolling")}
description={t("settings.terminal.behavior.smoothScrolling.desc")}
>
@@ -392,6 +402,7 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
</SettingRow>
<SettingRow
anchorId="terminal-link-modifier"
label={t("settings.terminal.behavior.linkModifier")}
description={t("settings.terminal.behavior.linkModifier.desc")}
>
@@ -756,7 +756,7 @@ export const ExternalMcpCard: React.FC = () => {
</div>
<SettingsAnchor anchorId="ai-external-mcp-approval-alert">
<SettingRow className="flex-col items-start md:flex-row md:items-center" label={t("ai.toolSettings.behavior")} description={t(mode === "persistent" ? "ai.externalMcp.mode.persistent" : "ai.externalMcp.mode.temporary")}>
<SettingRow anchorId="ai-external-mcp-behavior" className="flex-col items-start md:flex-row md:items-center" label={t("ai.toolSettings.behavior")} description={t(mode === "persistent" ? "ai.externalMcp.mode.persistent" : "ai.externalMcp.mode.temporary")}>
<ToolSettingsDialog title={t("ai.toolSettings.behavior")} triggerLabel={t("ai.toolSettings.configureBehavior")} immediate open={behaviorOpen} onOpenChange={setBehaviorOpen}>
<SettingCard divided className="border-0 bg-transparent p-0">
<SettingRow
@@ -879,7 +879,7 @@ export const ExternalMcpCard: React.FC = () => {
/>
<SettingCard>
<SettingRow className="flex-col items-start md:flex-row md:items-center" label={t("ai.externalMcp.clientConfiguration")} description={t("ai.externalMcp.clientConfiguration.description")}>
<SettingRow anchorId="ai-external-mcp-client-configuration" className="flex-col items-start md:flex-row md:items-center" label={t("ai.externalMcp.clientConfiguration")} description={t("ai.externalMcp.clientConfiguration.description")}>
<ToolSettingsDialog title={t("ai.externalMcp.clientConfiguration")} triggerLabel={t("ai.toolSettings.configureClients")}>
<div className="space-y-2">
@@ -6,6 +6,7 @@ import {
buildExternalMcpHttpUrl,
buildGenericHttpMcpJson,
DEFAULT_EXTERNAL_MCP_HTTP_PORT,
isExternalMcpHttpIpAddress,
} from "../../../../domain/externalMcpHttp";
import { useI18n } from "../../../../application/i18n/I18nProvider";
import { Button } from "../../../ui/button";
@@ -58,15 +59,6 @@ function isWildcardAddress(value: string): boolean {
return address === "0.0.0.0" || address === "::";
}
function isIpAddress(value: string): boolean {
const address = value.trim();
const ipv4 = address.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
if (ipv4) {
return ipv4.slice(1).every((part) => Number(part) <= 255 && String(Number(part)) === part);
}
return address.includes(":") && /^[0-9a-fA-F:]+$/.test(address);
}
function parsePort(value: string): number | null {
if (!/^\d+$/.test(value.trim())) return null;
const port = Number(value);
@@ -157,7 +149,7 @@ export const ExternalMcpHttpSection: React.FC<ExternalMcpHttpSectionProps> = ({
const commitClientHost = () => {
const clientHost = clientHostDraft.trim();
if (clientHost && (!isIpAddress(clientHost) || isWildcardAddress(clientHost))) {
if (clientHost && (!isExternalMcpHttpIpAddress(clientHost) || isWildcardAddress(clientHost))) {
setClientHostError(true);
return;
}
@@ -168,7 +160,7 @@ export const ExternalMcpHttpSection: React.FC<ExternalMcpHttpSectionProps> = ({
const commitAddress = () => {
const address = addressDraft.trim();
if (!isIpAddress(address)) {
if (!isExternalMcpHttpIpAddress(address)) {
setAddressError(true);
return;
}
@@ -154,7 +154,7 @@ export const ModelSelector: React.FC<{
await bridge.aiAllowlistAddHost(baseURL);
}
const url = buildProviderProbeUrl(baseURL, effectiveModelsEndpoint);
const headers = buildModelDiscoveryHeaders(resolvedStyle, apiKey, customHeaders);
const headers = buildModelDiscoveryHeaders(resolvedStyle, apiKey, customHeaders, baseURL);
const result = await bridge.aiFetch(url, "GET", headers, undefined, undefined, undefined, undefined, skipTLSVerify);
if (!result.ok) {
if (discoveryKeyRef.current !== requestKey) return;
@@ -136,6 +136,7 @@ export const SafetySettings: React.FC<{
</SettingRow>
<SettingRow
anchorId="ai-safety-max-iterations"
label={t('ai.safety.maxIterations')}
description={t('ai.safety.maxIterations.description')}
>
@@ -144,6 +144,7 @@ export const WebSearchSettings: React.FC<{
{/* API Key (hidden for SearXNG) */}
{preset.requiresApiKey && (
<SettingRow
anchorId="ai-web-search-api-key"
label={t("ai.webSearch.apiKey")}
description={t("ai.webSearch.apiKey.description")}
>
@@ -170,6 +171,7 @@ export const WebSearchSettings: React.FC<{
{/* API Host */}
<SettingRow
anchorId="ai-web-search-api-host"
label={t("ai.webSearch.apiHost")}
description={
config.providerId === "searxng"
@@ -188,6 +190,7 @@ export const WebSearchSettings: React.FC<{
{/* Max Results */}
<SettingRow
anchorId="ai-web-search-max-results"
label={t("ai.webSearch.maxResults")}
description={t("ai.webSearch.maxResults.description")}
>
@@ -1,12 +1,26 @@
import type { ExternalAgentConfig } from "../../../../infrastructure/ai/types";
import {
type ManagedAgentKey,
getExternalAgentSdkBackend,
isPathLikeCommand,
} from "../../../../infrastructure/ai/managedAgents";
import type { AgentPathInfo } from "./types";
import { AGENT_DEFAULTS, isCursorAvailableForMode } from "./types";
import { buildCodebuddyEnv } from "./codebuddyConfigEnv";
/** A saved, enabled harness can remain preferred while its version probe fails. */
export function getUnavailablePreferredHarness(
agents: ExternalAgentConfig[],
defaultAgentId: string,
): ExternalAgentConfig | undefined {
return agents.find((agent) =>
agent.id === defaultAgentId &&
Object.keys(AGENT_DEFAULTS).some((key) => agent.id === `discovered_${key}`) &&
agent.enabled && agent.available === false &&
agent.commandSource !== "auto" && isPathLikeCommand(agent.command) &&
Boolean(getExternalAgentSdkBackend(agent)));
}
function getAutoManagedAgentStoredPath(
agents: ExternalAgentConfig[],
agentKey: ManagedAgentKey,
@@ -34,9 +48,17 @@ export function buildManagedAgentState(
const managedId = `discovered_${agentKey}`;
const managedAgents = prevAgents.filter((agent) => agent.id === managedId);
const otherAgents = prevAgents.filter((agent) => agent.id !== managedId);
const existingManaged = managedAgents[0];
const savedManualPath = commandSource === "manual" && existingManaged?.commandSource !== "auto"
&& isPathLikeCommand(existingManaged?.command);
if (!pathInfo?.available || !pathInfo.path) {
const existingManaged = managedAgents.find((agent) => agent.id === managedId);
if (savedManualPath && existingManaged) {
return {
agents: prevAgents.map((agent) => agent.id === managedId ? { ...agent, available: false } : agent),
defaultAgentId,
};
}
if (agentKey === "cursor" && (existingManaged?.apiKey || existingManaged?.cursorAuthMode === "cli-login")) {
const defaults = AGENT_DEFAULTS[agentKey];
const {
@@ -97,7 +119,6 @@ export function buildManagedAgentState(
};
}
const existingManaged = managedAgents.find((agent) => agent.id === managedId);
const {
acpCommand: _legacyCommand,
acpArgs: _legacyArgs,
@@ -139,7 +160,9 @@ export function buildManagedAgentState(
available: cursorModeAvailable,
// Do not force-disable when only the current auth mode is temporarily
// unavailable (user may switch modes). Send paths already require available.
enabled: managedAgents.length === 0
enabled: savedManualPath && existingManaged
? existingManaged.enabled
: managedAgents.length === 0
|| (agentKey === "codebuddy" && existingManaged && !isPathLikeCommand(existingManaged.command))
? true
: managedAgents.some((agent) => agent.enabled) || managedAgents.every((agent) => agent.available === false),
+10 -6
View File
@@ -139,6 +139,8 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
// panel setTransfersState for every tick — that re-rendered the whole SFTP
// tree and pegged the renderer during large copies.
const task = useSftpTransferTask(propsTask.id, propsTask);
const pauseFailed = task.status === 'pausing' && !!task.pauseUnavailableReason;
const isPausing = task.status === 'pausing' && !pauseFailed;
// Same progress model as the global transfer center (done · found for folders).
const isDirParent = isDirectoryParentTask(task);
@@ -196,7 +198,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
? (fileCountDisplay
? `${t('sftp.transferCenter.phase.scanning')} · ${fileCountDisplay}`
: t('sftp.transferCenter.phase.scanning'))
: task.status === 'pausing'
: isPausing
? pausingLabel
: isDirParent
? (fileCountDisplay
@@ -227,7 +229,9 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
const statusIcon = isResuming
? <Loader2 size={12} className="animate-spin text-primary" />
: task.status === 'pausing'
: pauseFailed
? <Pause size={12} className="text-amber-500" />
: isPausing
? <Loader2 size={12} className="animate-spin text-amber-500" />
: task.status === 'transferring'
? <Loader2 size={12} className="animate-spin text-primary" />
@@ -290,7 +294,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
// Surface hard pause misses (e.g. "cannot be paused yet") so the panel
// pause button never looks dead when the backend refuses.
const showPauseUnavailable = !!task.pauseUnavailableReason
&& (task.status === 'transferring' || task.status === 'queued' || task.status === 'pending');
&& (pauseFailed || task.status === 'transferring' || task.status === 'queued' || task.status === 'pending');
const showWarning = task.status === 'completed' && !!task.warning;
const hasFooterContent = showTransferSizeCalculation || showFailedError || showPauseUnavailable || showWarning || childWarningCount > 0;
const retryActionLabel = t('sftp.transfers.retryAction');
@@ -352,7 +356,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
</Button>
</IconButtonWithTooltip>
)}
{task.status === 'transferring' && task.resumable !== false && onPause && !isResuming && (
{(task.status === 'transferring' || pauseFailed) && task.resumable !== false && onPause && !isResuming && (
<IconButtonWithTooltip label={pauseActionLabel}>
<Button
type="button"
@@ -367,7 +371,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
</Button>
</IconButtonWithTooltip>
)}
{task.status === 'pausing' && (
{isPausing && (
<IconButtonWithTooltip label={pausingLabel}>
<Button
type="button"
@@ -397,7 +401,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
</Button>
</IconButtonWithTooltip>
)}
{(task.status === 'paused' || task.status === 'interrupted') && onResume && !isResuming && (
{(task.status === 'paused' || task.status === 'interrupted' || (pauseFailed && task.resumable !== false)) && onResume && !isResuming && (
<IconButtonWithTooltip label={resumeActionLabel}>
<Button
type="button"
@@ -75,6 +75,9 @@ test('list hook preserves local copy/move routing, remote HTML drag, selection a
await act(async () => root.render(React.createElement(Harness, { local: false })));
await act(async () => right.handlePaneDrop(event()));
assert.equal(actions.at(-1)?.kind, 'copy');
actions.length = 0;
await act(async () => left.handleEntryDrop(entries[2], event()));
assert.deepEqual(actions, [{ kind: 'move', args: [['/files/b.txt'], '/files/folder'] }], 'same-pane remote drag stays a move');
} finally {
await act(async () => root.unmount());
clearLocalFileDrag();
@@ -2,9 +2,11 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import React from 'react';
import { JSDOM } from 'jsdom';
import { createRoot } from 'react-dom/client';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
import { I18nProvider } from '../../application/i18n/I18nProvider';
import { TerminalComposeBar } from './TerminalComposeBar';
import { TerminalContextMenu } from './TerminalContextMenu';
import { TooltipProvider } from '../ui/tooltip';
import { getComposeBarHistory, pruneComposeBarHistory, recordComposeBarHistory } from '../../application/state/composeBarHistoryStore';
import { terminalReconnectRegistry } from '../../application/state/terminalReconnectRegistry';
@@ -303,3 +305,54 @@ test('compose send target toggle shows all vs active without looking like broadc
assert.equal(stillPulsing.length, 0);
await act(async () => { root.unmount(); });
});
test('compose right-click never pastes into the terminal behind it', async (t) => {
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', { url: 'http://localhost' });
const globals = ['window', 'document', 'localStorage', 'Element', 'HTMLElement', 'Node'] as const;
const originals = globals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)] as const);
for (const name of globals) {
Object.defineProperty(globalThis, name, { configurable: true, value: dom.window[name] });
}
const rootElement = dom.window.document.querySelector('#root')!;
const root = createRoot(rootElement);
t.after(async () => {
await act(async () => root.unmount());
dom.window.close();
for (const [name, descriptor] of originals) {
if (descriptor) Object.defineProperty(globalThis, name, descriptor);
else Reflect.deleteProperty(globalThis, name);
}
});
let pasteCount = 0;
const render = (broadcast: boolean) => (
<I18nProvider locale="en"><TooltipProvider>
<TerminalContextMenu sessionId="right-click-test" status="connected" rightClickBehavior="paste" onPaste={() => { pasteCount++; }}>
<div>
<div data-terminal-cell />
<TerminalComposeBar sessionId="right-click-test" isBroadcastEnabled={broadcast} onSend={() => true} onClose={() => {}} />
</div>
</TerminalContextMenu>
</TooltipProvider></I18nProvider>
);
const rightClick = async (target: string) => {
const element = rootElement.querySelector(target);
assert.ok(element, target);
await act(async () => {
element.dispatchEvent(new dom.window.MouseEvent('contextmenu', { bubbles: true, cancelable: true, button: 2 }));
});
};
await act(async () => root.render(render(false)));
await rightClick('textarea');
assert.equal(pasteCount, 0, 'the solo composer must not paste into the PTY');
await rightClick('[data-terminal-cell]');
assert.equal(pasteCount, 1, 'ordinary terminal right-click paste still works');
await act(async () => root.render(render(true)));
await rightClick('textarea');
assert.equal(pasteCount, 1, 'broadcast compose opens only its own menu');
assert.ok(rootElement.querySelector('[data-compose-broadcast-menu]'));
await rightClick('[data-compose-broadcast-menu]');
assert.equal(pasteCount, 1, 'right-click on the compose menu must not paste into the PTY');
});
+3 -1
View File
@@ -360,9 +360,11 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
const sendToAll = composeSendToAll ?? Boolean(isBroadcastEnabled);
const handleBroadcastContextMenu = useCallback((event: React.MouseEvent) => {
// A solo composer is inside the terminal's context-menu trigger, but this
// gesture must never run a terminal action (such as paste into the PTY).
event.stopPropagation();
if (!isBroadcastEnabled && !sendToAll) return;
event.preventDefault();
event.stopPropagation();
setBroadcastMenuAnchor({
x: event.clientX,
y: event.clientY,
@@ -110,6 +110,7 @@ import {
createTerminalLigatureController,
terminalFontLigaturesEnabled,
} from "./terminalFontLigatures";
import { createPaneBidiJoiner, findRightToLeftRuns } from "./terminalBidiJoiner";
import { createWebglRendererController } from "./webglRendererController";
import { getSharedWebglContextBudget } from "./webglContextBudget";
import {
@@ -1074,6 +1075,22 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
term.loadAddon(unicodeGraphemes);
term.unicode.activeVersion = '15-graphemes';
// Draw Arabic, Persian and Hebrew runs in display order with joined letters.
// Display only: the buffer, selection and copy keep the logical text.
term.registerCharacterJoiner(performanceConfig.useWebGLAddon
? createPaneBidiJoiner(
() => webglController.getAddon() !== null,
() => {
if (runtimeDisposed) return;
// The pinned WebGL addon allocates a maximum-size atlas page for a
// wide joined glyph. Prevent attach/recovery again for just this pane.
webglController.dispose();
logger.info("[XTerm] Using DOM renderer for right-to-left text in this pane");
repaintTerminal();
},
)
: findRightToLeftRuns);
trackRenderer();
const appLevelActions = getAppLevelActions();
@@ -2601,6 +2618,18 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
}
}
// Claim Shift+Insert as clipboard paste before Kitty/Win32 or xterm can
// encode it as an Insert key, while preserving user shortcut precedence.
if (
e.key === "Insert" && e.shiftKey
&& !e.ctrlKey && !e.altKey && !e.metaKey
) {
e.preventDefault();
e.stopPropagation();
void ctx.terminalContextActionsRef?.current?.onPaste?.();
return false;
}
// Sogou/macOS CJK punctuation: keydown still reports ASCII "," while the
// full-width "," arrives on insertText. Returning false (without
// preventDefault) stops xterm/Kitty from sending the half-width key so the
@@ -2776,15 +2805,6 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
};
return true;
}
// xterm leaves Shift+Insert to the browser's native paste handler. Fan out
// the clipboard data from onData instead of encoding an Insert key for
// peers or treating the paste as that key's pending legacy data (#4142).
if (
e.key === "Insert" && e.shiftKey
&& !e.ctrlKey && !e.altKey && !e.metaKey
) {
return true;
}
if (!shouldDeferKittyKeyEvent(normalizedKittyEvent)) {
const identity = kittyKeyIdentity(e);
if (
@@ -65,3 +65,24 @@ test('disabled or mouse-owned gestures retain the full original event sequence',
dispose();
dom.window.close();
});
test('right-click in the compose bar is never captured or replayed as terminal paste', (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
const dom = new JSDOM('<div id="root"><div data-section="terminal-compose-bar"><textarea></textarea></div></div>');
const root = dom.window.document.querySelector<HTMLElement>('#root')!;
const compose = root.querySelector('textarea')!;
const dispose = installRightClickLongPress(root, () => true);
const seen: EventTarget[] = [];
root.addEventListener('contextmenu', (event) => seen.push(event.target!));
const fire = (type: string) => compose.dispatchEvent(new dom.window.MouseEvent(type, {
bubbles: true, cancelable: true, button: 2, buttons: type === 'mouseup' ? 0 : 2,
}));
fire('mousedown');
fire('contextmenu');
t.mock.timers.tick(RIGHT_CLICK_LONG_PRESS_MS);
fire('mouseup');
assert.deepEqual(seen, [compose], 'only the original composer event should be delivered');
dispose();
dom.window.close();
});
@@ -37,7 +37,7 @@ export function installRightClickLongPress(
suppressContextMenu = false;
if (event.button !== 2 || event.shiftKey || event.ctrlKey || event.altKey || event.metaKey
|| !canStart()
|| (event.target as Element | null)?.closest('[data-terminal-history-preview]')) return;
|| (event.target as Element | null)?.closest('[data-terminal-history-preview], [data-section="terminal-compose-bar"]')) return;
press = event;
suppressContextMenu = true;
timer = setTimeout(() => {
@@ -0,0 +1,128 @@
import assert from "node:assert/strict";
import test from "node:test";
import { createPaneBidiJoiner, findRightToLeftRuns, mightContainRightToLeft } from "./terminalBidiJoiner";
const slice = (text: string, ranges: [number, number][]) =>
ranges.map(([start, end]) => text.slice(start, end));
test("pure left-to-right text is left alone", () => {
assert.deepEqual(findRightToLeftRuns("ls -la /var/log 2>&1 | grep error"), []);
assert.deepEqual(findRightToLeftRuns("10.0.0.138 (eth0) 100%"), []);
assert.deepEqual(findRightToLeftRuns(""), []);
});
test("the cheap detection gate rejects the ASCII and unrelated astral characters", () => {
assert.equal(mightContainRightToLeft(String.raw`update DEPLOY 0 2 3 \uD802`), false);
assert.equal(mightContainRightToLeft("shell 🛠️ 👍"), false);
assert.equal(mightContainRightToLeft("𞤀𞤤"), true);
});
test("supplementary RTL stays whole and returns xterm UTF-16 offsets", () => {
const adlam = "𞤀𞤤";
const text = `🛠 ${adlam} x`;
assert.deepEqual(findRightToLeftRuns(text), [[3, 7]]);
assert.deepEqual(findRightToLeftRuns(`${adlam} 123`), [[0, 8]]);
});
test("Persian prose is one run so the browser can order and join it", () => {
const text = "سلام دنیا";
assert.deepEqual(findRightToLeftRuns(text), [[0, text.length]]);
});
test("Arabic prose keeps its interior spaces and drops trailing ones", () => {
const text = "مرحبا بالعالم ";
assert.deepEqual(slice(text, findRightToLeftRuns(text)), ["مرحبا بالعالم"]);
});
test("a Persian word typed after a shell command is its own run", () => {
const text = 'echo "سلام"';
assert.deepEqual(slice(text, findRightToLeftRuns(text)), ["سلام"]);
});
test("numbers inside Persian text stay in the run", () => {
const text = "قیمت 100 تومان";
assert.deepEqual(findRightToLeftRuns(text), [[0, text.length]]);
});
test("an IP address after Arabic text belongs to the Arabic run", () => {
const text = "العنوان 10.0.0.138";
assert.deepEqual(findRightToLeftRuns(text), [[0, text.length]]);
});
test("Persian digits inside Persian text stay in the run", () => {
const text = "تعداد ۵۰ فایل";
assert.deepEqual(findRightToLeftRuns(text), [[0, text.length]]);
});
test("mixed Persian and English splits at the English words", () => {
const text = "فایل config.yaml پیدا نشد";
assert.deepEqual(slice(text, findRightToLeftRuns(text)), ["فایل", "پیدا نشد"]);
});
test("English with a Persian phrase in the middle only joins the phrase", () => {
const text = "Error: فایل پیدا نشد (code 2)";
assert.deepEqual(slice(text, findRightToLeftRuns(text)), ["فایل پیدا نشد"]);
});
test("brackets around RTL text inside an RTL run are kept with it", () => {
const text = "مثال (نص) هنا";
assert.deepEqual(findRightToLeftRuns(text), [[0, text.length]]);
});
test("Hebrew is handled like Arabic", () => {
const text = "ls שלום עולם";
assert.deepEqual(slice(text, findRightToLeftRuns(text)), ["שלום עולם"]);
});
test("a single right-to-left character is not worth joining", () => {
assert.deepEqual(findRightToLeftRuns("a ب c"), []);
});
test("ranges are sorted and do not overlap", () => {
const text = "الف abc باء def جيم";
const ranges = findRightToLeftRuns(text);
assert.deepEqual(slice(text, ranges), ["الف", "باء", "جيم"]);
for (let i = 1; i < ranges.length; i++) {
assert.ok(ranges[i][0] >= ranges[i - 1][1]);
}
});
test("ASCII output never requests a DOM-only renderer", async () => {
let switches = 0;
const join = createPaneBidiJoiner(() => true, () => { switches++; });
assert.deepEqual(join("192.0.2.1: ready"), []);
assert.deepEqual(join("100 lines of output"), []);
await Promise.resolve();
assert.equal(switches, 0);
});
test("RTL joins are withheld from WebGL until the pane switches once to DOM", async () => {
let webgl = true;
let switches = 0;
const join = createPaneBidiJoiner(() => webgl, () => {
switches++;
webgl = false;
});
const short = "سلام دنیا";
const long = "این یک جمله فارسی معمولی برای بررسی خوانایی متن در یک پنجره عریض است";
assert.deepEqual(join(short), []);
assert.deepEqual(join(long), []);
assert.equal(switches, 0);
await Promise.resolve();
assert.equal(switches, 1);
assert.deepEqual(join(short), [[0, short.length]]);
assert.deepEqual(join(long), [[0, long.length]]);
await Promise.resolve();
assert.equal(switches, 1);
});
test("RTL received before deferred WebGL activation keeps the pane on DOM", async () => {
let switches = 0;
const text = "سلام";
const join = createPaneBidiJoiner(() => false, () => { switches++; });
assert.deepEqual(join(text), [[0, text.length]]);
await Promise.resolve();
assert.equal(switches, 1);
});
@@ -0,0 +1,91 @@
import bidiFactory from "bidi-js";
import rtlCharacterPattern from "../../../lib/terminalRtlCharacter.json";
/**
* Display-only right-to-left support for xterm.js (issue #4261).
*
* xterm.js draws every cell on its own and in buffer (logical) order, so
* Arabic, Persian and Hebrew words come out reversed, and Arabic letters are
* drawn in their isolated forms. xterm.js has no bidi support of its own
* (xtermjs/xterm.js#701).
*
* The DOM renderer draws joined ranges as one string, allowing the browser to
* reorder and shape Arabic letters and mirror brackets. The WebGL addon also
* supports joiners, but long joined RTL runs can exhaust its glyph texture,
* so a pane that needs RTL shaping stays on DOM. The buffer is never changed, so selection, copy, search
* and cursor positions keep working on the logical text. xterm.js also draws
* a range cell by cell again while the cursor is inside it or a selection
* only partly covers it, so editing an RTL word shows the logical cells.
*
* This joiner returns the parts of a line that the Unicode Bidirectional
* Algorithm puts at a right-to-left (or number) embedding level when the
* paragraph direction is left-to-right, which is the default for terminals
* (https://terminal-wg.pages.freedesktop.org/bidi/). Runs separated by
* left-to-right text therefore keep their left-to-right order, and lines are
* not right-aligned.
*/
// RTL scripts and directional controls in the BMP and supplementary planes.
// The Unicode flag makes the supplementary bounds code points, not UTF-16
// lead surrogates (which would also match unrelated non-RTL characters).
const RTL_CHARACTER = new RegExp(rtlCharacterPattern, "u");
const SURROGATE_PAIR = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
// bidi-js 1.0.3 looks up string[i] rather than a full code point. Project
// astral characters to BMP characters of the same bidi class for this
// calculation only. Two copies retain the original UTF-16 offsets expected
// by xterm; the actual glyphs (and terminal buffer) are never replaced.
const BIDI_CLASS_PROXY: Readonly<Record<string, string>> = {
L: "a", R: "א", AL: "ا", EN: "0", AN: "٠", NSM: "\u0301",
ON: "!", BN: "\u00ad", ET: "$", CS: ",", ES: "+",
};
let bidi: ReturnType<typeof bidiFactory> | null = null;
export function mightContainRightToLeft(text: string): boolean {
return RTL_CHARACTER.test(text);
}
export function findRightToLeftRuns(text: string): [number, number][] {
if (!mightContainRightToLeft(text)) return [];
bidi ??= bidiFactory();
const classifier = bidi;
const projected = text.replace(SURROGATE_PAIR, (character) =>
(BIDI_CLASS_PROXY[classifier.getBidiCharTypeName(character)] ?? "!").repeat(2),
);
const { levels } = classifier.getEmbeddingLevels(projected, "ltr");
const ranges: [number, number][] = [];
let start = -1;
for (let i = 0; i <= text.length; i++) {
const inRun = i < text.length && levels[i] > 0;
if (inRun && start < 0) {
start = i;
} else if (!inRun && start >= 0) {
// A single cell looks the same joined or not.
if (i - start > 1) ranges.push([start, i]);
start = -1;
}
}
return ranges;
}
/** Keep wide RTL glyphs out of the WebGL atlas, without changing other panes. */
export function createPaneBidiJoiner(
isWebglActive: () => boolean,
stayOnDom: () => void,
): typeof findRightToLeftRuns {
let requestedDom = false;
return (text) => {
const ranges = findRightToLeftRuns(text);
if (ranges.length === 0) return ranges;
if (!requestedDom) {
requestedDom = true;
// Do not dispose the current renderer from inside its render callback.
queueMicrotask(stayOnDom);
}
return isWebglActive() ? [] : ranges;
};
}
@@ -7,7 +7,7 @@ import { buildSync } from "esbuild";
import { JSDOM } from "jsdom";
import ts from "typescript";
test("native Shift+Insert broadcasts clipboard bytes once without an Insert key", async () => {
test("Shift+Insert uses onPaste and broadcasts clipboard bytes once across keyboard modes", async () => {
const root = fileURLToPath(new URL("../../..", import.meta.url));
const layer = readFileSync(new URL("../../TerminalLayer.tsx", import.meta.url), "utf8");
const start = layer.indexOf(" const handleBroadcastInput = useCallback(");
@@ -21,6 +21,8 @@ test("native Shift+Insert broadcasts clipboard bytes once without an Insert key"
contents: `
export { createXTermRuntime } from "./components/terminal/runtime/createXTermRuntime";
export { DEFAULT_TERMINAL_SETTINGS } from "./domain/models/terminal";
export { DEFAULT_KEY_BINDINGS } from "./domain/models/keyBindings";
export { pasteTextIntoTerminal } from "./components/terminal/runtime/terminalUserPaste";
export { resolveTerminalBroadcastTargetIds } from "./domain/terminalBroadcast";
export { dispatchKittyKeyboardBroadcastInput } from "./components/terminal/runtime/kittyKeyboardBroadcast";
export * from "./components/terminal/runtime/terminalPacedBroadcast";
@@ -50,7 +52,8 @@ test("native Shift+Insert broadcasts clipboard bytes once without an Insert key"
`);
dom.window.eval(bundle);
const results = await dom.window.eval(`(async () => {
const {createXTermRuntime, DEFAULT_TERMINAL_SETTINGS, resolveTerminalBroadcastTargetIds,
const {createXTermRuntime, DEFAULT_TERMINAL_SETTINGS, DEFAULT_KEY_BINDINGS,
pasteTextIntoTerminal, resolveTerminalBroadcastTargetIds,
dispatchKittyKeyboardBroadcastInput, markTerminalBroadcastUserInput,
captureTerminalBroadcastInput, isTerminalBroadcastInputCurrent} = runtimeTest;
const ref = current => ({current});
@@ -60,71 +63,123 @@ test("native Shift+Insert broadcasts clipboard bytes once without an Insert key"
const canUseDirectSessionWriteFallback = () => true;
const isTerminalSensitiveInputActive = () => false;
const wires = new Map();
const pasteCalls = new Map();
const terminalBackend = {
writeToSession:(id,data)=>wires.get(id).push(data), resizeSession(){}, openExternalAvailable:false,
};
${dispatcher}
const make = (id, kittyKeyboardProtocolEnabled) => {
const make = (id, kittyKeyboardProtocolEnabled, options = {}) => {
const container = document.createElement('div'); document.body.appendChild(container);
wires.set(id, []);
pasteCalls.set(id, 0);
const terminalContextActionsRef = ref({});
const host = {id,label:id,hostname:'localhost',protocol:'ssh',sshInputCompatibility:false};
return createXTermRuntime({
const runtime = createXTermRuntime({
container, host, getHost:()=>host, sessionId:id, sessionRef:ref(id), statusRef:ref('connected'),
fontFamilyId:'jetbrains-mono',resolvedFontFamily:'monospace',fontSize:14,
terminalTheme:{colors:{background:'#111111',foreground:'#eeeeee',cursor:'#ffffff',selection:'#444444'}},
terminalSettingsRef:ref({...DEFAULT_TERMINAL_SETTINGS,rendererType:'dom',fontLigatures:false,cursorBlink:false}),
terminalBackend,hotkeySchemeRef:ref('disabled'),keyBindingsRef:ref([]),onHotkeyActionRef:ref(undefined),
terminalBackend,hotkeySchemeRef:ref('pc'),
keyBindingsRef:ref(options.bindings ?? DEFAULT_KEY_BINDINGS),onHotkeyActionRef:ref(undefined),
terminalContextActionsRef, snippetsRef:ref(options.snippets ?? []),
onSnippetShortkeyRef:ref(options.onSnippet),
isBroadcastEnabledRef:ref(true),onBroadcastInputRef:ref(handleBroadcastInput),
commandBufferRef:ref(''),requestSearchFocus(){},kittyKeyboardProtocolEnabled,
commandBufferRef:ref(''),requestSearchFocus:options.onSearch ?? (()=>{}),kittyKeyboardProtocolEnabled,
});
terminalContextActionsRef.current.onPaste = async () => {
pasteCalls.set(id, pasteCalls.get(id) + 1);
if (options.delayed) await new Promise(resolve=>setTimeout(resolve,10));
pasteTextIntoTerminal(runtime.term, 'clipboard', {scrollOnPaste:false});
};
return runtime;
};
const results = [];
for (const bracketed of [false,true]) {
for (const delayed of [true,false]) {
for (const peerKitty of [false,true]) {
const source = make('source', false), peer = make('peer', peerKitty);
try {
sessionsRef.current = ['source','peer'].map(id=>({id,protocol:'ssh',workspaceId:'workspace'}));
if (peerKitty) await new Promise(resolve=>peer.term.write('\\x1b[>8u',resolve));
if (bracketed) await new Promise(resolve=>source.term.write('\\x1b[?2004h',resolve));
const key = new KeyboardEvent('keydown', {
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
});
source.term.textarea.dispatchEvent(key);
const beforePaste = [...wires.get('peer')];
if (delayed) await new Promise(resolve=>setTimeout(resolve,10));
// Supply the native clipboard event which Chromium emits for this chord.
const paste = new Event('paste', {bubbles:true,cancelable:true});
Object.defineProperty(paste,'clipboardData',{value:{getData:()=> 'clipboard'}});
source.term.textarea.dispatchEvent(paste);
source.term.textarea.dispatchEvent(new KeyboardEvent('keyup', {
bubbles:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
}));
results.push({bracketed,delayed,peerKitty,beforePaste,
prevented:key.defaultPrevented,source:[...wires.get('source')],peer:[...wires.get('peer')]});
// Ordinary Insert still uses the physical-key broadcast path.
if (!peerKitty) {
wires.get('source').length=0; wires.get('peer').length=0;
source.term.textarea.dispatchEvent(new KeyboardEvent('keydown', {
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,
const modes = [
{name:'legacy',kitty:false,setup:''},
{name:'native-kitty',kitty:false,setup:'\\x1b[>1u'},
{name:'native-kitty-all-keys',kitty:false,setup:'\\x1b[>8u'},
{name:'netcatty-kitty',kitty:true,setup:'\\x1b[>1u'},
{name:'win32',kitty:false,setup:'\\x1b[?9001h'},
];
for (const mode of modes) {
for (const bracketed of [false,true]) {
for (const delayed of [true,false]) {
for (const peerKitty of [false,true]) {
const source = make('source', mode.kitty, {delayed}), peer = make('peer', peerKitty);
try {
sessionsRef.current = ['source','peer'].map(id=>({id,protocol:'ssh',workspaceId:'workspace'}));
if (mode.setup) await new Promise(resolve=>source.term.write(mode.setup,resolve));
if (peerKitty) await new Promise(resolve=>peer.term.write('\\x1b[>8u',resolve));
if (bracketed) await new Promise(resolve=>source.term.write('\\x1b[?2004h',resolve));
const key = new KeyboardEvent('keydown', {
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
});
source.term.textarea.dispatchEvent(key);
if (delayed) await new Promise(resolve=>setTimeout(resolve,20));
source.term.textarea.dispatchEvent(new KeyboardEvent('keyup', {
bubbles:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
}));
results.push({plainInsert:true,source:[...wires.get('source')],peer:[...wires.get('peer')]});
}
} finally { source.dispose(); peer.dispose(); }
results.push({mode:mode.name,bracketed,delayed,peerKitty,pasteCalls:pasteCalls.get('source'),
prevented:key.defaultPrevented,source:[...wires.get('source')],peer:[...wires.get('peer')]});
// Ordinary Insert still uses the physical-key broadcast path.
if (!peerKitty && mode.name !== 'win32') {
wires.get('source').length=0; wires.get('peer').length=0;
source.term.textarea.dispatchEvent(new KeyboardEvent('keydown', {
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,
}));
results.push({plainInsert:true,mode:mode.name,pasteCalls:pasteCalls.get('source'),
source:[...wires.get('source')],peer:[...wires.get('peer')]});
}
wires.get('source').length=0; wires.get('peer').length=0;
const pasteShortcut = new KeyboardEvent('keydown', {
bubbles:true,cancelable:true,key:'V',code:'KeyV',keyCode:86,ctrlKey:true,shiftKey:true,
});
source.term.textarea.dispatchEvent(pasteShortcut);
if (delayed) await new Promise(resolve=>setTimeout(resolve,20));
source.term.textarea.dispatchEvent(new KeyboardEvent('keyup', {
bubbles:true,key:'V',code:'KeyV',keyCode:86,ctrlKey:true,shiftKey:true,
}));
results.push({configuredPaste:true,mode:mode.name,bracketed,pasteCalls:pasteCalls.get('source'),
prevented:pasteShortcut.defaultPrevented,source:[...wires.get('source')],peer:[...wires.get('peer')]});
} finally { source.dispose(); peer.dispose(); }
}
}
}
}
for (const shortcut of ['binding','snippet']) {
let searchCalls = 0, snippetCalls = 0;
const source = make('source', true, shortcut === 'binding'
? {onSearch:()=>searchCalls++,bindings:DEFAULT_KEY_BINDINGS.map(binding=>binding.action === 'searchTerminal'
? {...binding,pc:'Shift + Insert'} : binding)}
: {snippets:[{id:'snippet',shortkey:'Shift + Insert'}],onSnippet:()=>snippetCalls++});
try {
await new Promise(resolve=>source.term.write('\\x1b[>1u',resolve));
source.term.textarea.dispatchEvent(new KeyboardEvent('keydown', {
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
}));
results.push({shortcut,pasteCalls:pasteCalls.get('source'),snippetCalls,searchCalls,
source:[...wires.get('source')]});
} finally { source.dispose(); }
}
return JSON.stringify(results);
})()`);
for (const result of JSON.parse(results)) {
if (result.plainInsert) {
assert.equal(result.pasteCalls, 1);
assert.deepEqual(result.source, ["\x1b[2~"]);
assert.deepEqual(result.peer, ["\x1b[2~"]);
continue;
}
if (result.shortcut) {
assert.equal(result.pasteCalls, 0, result.shortcut);
assert.equal(result.snippetCalls, result.shortcut === 'snippet' ? 1 : 0);
assert.equal(result.searchCalls, result.shortcut === 'binding' ? 1 : 0);
assert.deepEqual(result.source, []);
continue;
}
const label = JSON.stringify(result);
assert.deepEqual(result.beforePaste, [], label);
assert.equal(result.prevented, false, "native paste must remain enabled: " + label);
assert.equal(result.pasteCalls, result.configuredPaste ? 2 : 1, label);
assert.equal(result.prevented, true, label);
const expected = result.bracketed ? "\x1b[200~clipboard\x1b[201~" : "clipboard";
assert.deepEqual(result.source, [expected], label);
assert.deepEqual(result.peer, [expected], label);
@@ -89,6 +89,15 @@ test("a visible pane past the cap releases the least recently seen hidden pane",
assert.equal(budget.getActiveCount(), 3);
});
test("new visible panes are refused when visible holders fill the cap", () => {
const { budget } = setup(2);
const members = ["a", "b", "c", "d"].map((name) => new FakeMember(name));
assert.deepEqual(members.map((member) => budget.tryAcquire(member)), [true, true, false, false]);
assert.equal(budget.tryAcquire(members[0]), true, "an existing holder keeps its slot");
assert.equal(budget.getActiveCount(), 2);
assert.deepEqual(members.map((member) => member.releases), [0, 0, 0, 0]);
});
test("recently hidden panes are released only once they stay hidden long enough", () => {
const { clock, budget } = setup(2);
const [a, b] = ["a", "b"].map((name) => new FakeMember(name));
@@ -101,6 +110,8 @@ test("recently hidden panes are released only once they stay hidden long enough"
budget.tryAcquire(new FakeMember("shown"));
assert.equal(a.releases, 0, "a quick tab flip must not lose the renderer");
assert.equal(budget.getActiveCount(), 3);
assert.equal(budget.tryAcquire(new FakeMember("overflow")), false);
assert.equal(budget.getActiveCount(), 3, "one hidden holder allows only one extra context");
clock.advance(2_999);
assert.equal(a.releases, 0);
@@ -110,26 +121,33 @@ test("recently hidden panes are released only once they stay hidden long enough"
assert.equal(clock.pendingTimers, 0);
});
test("a pane hidden after the budget went over is released once eligible", () => {
test("a pane hidden after a grace overshoot is released once eligible", () => {
const { clock, budget } = setup(2);
const [a, b, c] = ["a", "b", "c"].map((name) => new FakeMember(name));
budget.tryAcquire(a);
budget.tryAcquire(b);
budget.tryAcquire(c);
assert.equal(budget.getActiveCount(), 3, "three visible panes all keep WebGL");
assert.equal(budget.tryAcquire(c), false);
assert.equal(budget.getActiveCount(), 2);
assert.equal(clock.pendingTimers, 0);
a.hiddenSince = clock.now();
budget.noteHidden(a);
assert.equal(budget.tryAcquire(c), true);
assert.equal(budget.getActiveCount(), 3, "recently hidden holders allow a grace overshoot");
a.hiddenSince = null;
b.hiddenSince = clock.now();
budget.noteHidden(b);
clock.advance(3_000);
assert.equal(b.releases, 1);
assert.equal(a.releases, 0, "a holder shown again keeps its renderer");
assert.equal(budget.getActiveCount(), 2);
});
test("a hidden pane cannot take a context once the budget is full", () => {
const { budget } = setup(2);
budget.tryAcquire(new FakeMember("a"));
const { clock, budget } = setup(2);
const a = new FakeMember("a");
budget.tryAcquire(a);
budget.tryAcquire(new FakeMember("b"));
const hidden = new FakeMember("hidden");
@@ -138,7 +156,13 @@ test("a hidden pane cannot take a context once the budget is full", () => {
assert.equal(budget.getActiveCount(), 2);
hidden.hiddenSince = null;
assert.equal(budget.tryAcquire(hidden), true, "it gets one as soon as it is shown");
assert.equal(budget.tryAcquire(hidden), false, "visible holders still fill the cap");
a.hiddenSince = clock.now();
budget.noteHidden(a);
clock.advance(3_000);
assert.equal(budget.tryAcquire(hidden), true, "a shown pane can replace an eligible hidden holder");
assert.equal(a.releases, 1);
assert.equal(budget.getActiveCount(), 2);
});
test("released and forgotten panes free their slot", () => {
@@ -10,8 +10,9 @@
*
* The budget stays below the browser limit by releasing the renderers of panes
* that have been hidden for a while, least recently seen first. Visible panes
* are never released and always get a context. A released pane builds a new
* renderer when it is shown again. Below the cap nothing changes.
* are never released, but new ones stay on DOM when visible holders fill the
* cap. Recently hidden holders may temporarily exceed the cap during tab flips.
* A released pane can rebuild when shown if the budget permits.
*/
export const MAX_ACTIVE_WEBGL_CONTEXTS = 12;
@@ -31,8 +32,8 @@ export interface WebglContextBudgetMember {
export interface WebglContextBudget {
/**
* Reserve a context for a member about to create its renderer. Visible
* members always get one; hidden members only while the budget has room.
* Reserve a context if the budget has room. Visible members may replace
* hidden holders, allowing a temporary overshoot until their grace expires.
*/
tryAcquire(member: WebglContextBudgetMember): boolean;
/** Give the slot back once the member's renderer is gone. Idempotent. */
@@ -102,7 +103,11 @@ export function createWebglContextBudget(
return {
tryAcquire(member) {
if (active.has(member)) return true;
if (member.getHiddenSince() !== null && active.size >= maxActive) return false;
if (active.size >= maxActive) {
if (member.getHiddenSince() !== null) return false;
const visibleCount = [...active].filter((holder) => holder.getHiddenSince() === null).length;
if (visibleCount >= maxActive) return false;
}
active.add(member);
releaseOverflow();
return true;
@@ -186,20 +186,93 @@ test("panes past the budget give up WebGL after staying hidden, and get it back
assert.equal(budget.getActiveCount(), 2);
});
test("simultaneous visible ensures stay within the context budget", () => {
const { budget, createPane } = setup();
const panes = Array.from({ length: 13 }, () => createPane());
for (const pane of panes) pane.controller.ensure();
assert.deepEqual(panes.map((pane) => pane.loaded), [...Array(12).fill(true), false]);
assert.equal(panes[12].addons.length, 0);
assert.equal(budget.getActiveCount(), 12);
});
test("visible context loss recovers at the cap, including with a refused visible pane", () => {
for (const withOverflow of [false, true]) {
const { clock, budget, createPane } = setup(2);
const panes = [createPane(), createPane()];
for (const pane of panes) pane.controller.ensure();
const overflow = withOverflow ? createPane() : null;
overflow?.controller.ensure();
assert.equal(overflow?.addons.length ?? 0, 0);
assert.equal(budget.getActiveCount(), 2);
panes[0].addons[0].loseContext();
assert.equal(budget.getActiveCount(), 1);
clock.advance(49);
assert.equal(panes[0].loaded, false);
clock.advance(1);
assert.equal(panes[0].loaded, true);
assert.equal(panes[0].addons.length, 2);
assert.equal(panes[1].addons.length, 1);
overflow?.controller.ensure();
assert.equal(overflow?.addons.length ?? 0, 0);
assert.equal(budget.getActiveCount(), 2);
assert.equal(clock.pendingTimers, 0);
assert.ok(panes.every((pane) => !pane.warnings.some((warning) => warning.includes("staying on DOM renderer"))));
}
});
test("visible loss stays on DOM if another visible pane takes the freed slot before recovery", () => {
const { clock, budget, createPane } = setup(2);
const panes = [createPane(), createPane(), createPane()];
for (const pane of panes) pane.controller.ensure();
assert.equal(panes[2].loaded, false);
panes[0].addons[0].loseContext();
panes[2].controller.ensure();
assert.equal(panes[2].loaded, true);
clock.advance(50);
assert.equal(panes[0].loaded, false);
assert.deepEqual(panes.map((pane) => pane.addons.length), [1, 1, 1]);
assert.equal(budget.getActiveCount(), 2);
assert.equal(clock.pendingTimers, 0);
assert.ok(panes.every((pane) => !pane.warnings.some((warning) => warning.includes("staying on DOM renderer"))));
});
test("a hidden pane mounted past the budget keeps the DOM renderer until shown", () => {
const { budget, createPane } = setup(1);
createPane().controller.ensure();
const { clock, budget, createPane } = setup(1);
const occupant = createPane();
occupant.controller.ensure();
const hidden = createPane(false);
hidden.controller.ensure();
assert.equal(hidden.addons.length, 0);
assert.equal(budget.getActiveCount(), 1);
occupant.setVisible(false);
clock.advance(3_000);
hidden.reveal();
assert.equal(hidden.loaded, true);
assert.equal(occupant.loaded, false);
assert.equal(budget.getActiveCount(), 1);
});
test("a pane on screen is never refused or released, even if a sync was missed", () => {
test("revealing a hidden pane is refused while visible holders fill the budget", () => {
const { budget, createPane } = setup(1);
const occupant = createPane();
occupant.controller.ensure();
const hidden = createPane(false);
hidden.controller.ensure();
hidden.reveal();
assert.equal(hidden.loaded, false);
assert.equal(hidden.addons.length, 0);
assert.equal(occupant.loaded, true);
assert.equal(budget.getActiveCount(), 1);
});
test("a holder on screen is never released, even if a sync was missed", () => {
const { clock, budget, createPane } = setup(1);
const visible = createPane();
visible.controller.ensure();
@@ -210,12 +283,37 @@ test("a pane on screen is never refused or released, even if a sync was missed",
createPane().controller.ensure();
clock.advance(10_000);
assert.equal(visible.loaded, true);
assert.equal(budget.getActiveCount(), 2);
assert.equal(budget.getActiveCount(), 1);
const late = createPane(false);
late.setVisibleWithoutSync(true);
late.controller.ensure();
assert.equal(late.loaded, true);
assert.equal(late.loaded, false);
assert.equal(late.addons.length, 0);
assert.equal(budget.getActiveCount(), 1);
});
test("grace overflow never releases a holder shown again without a visibility sync", () => {
const { clock, budget, createPane } = setup(1);
const holder = createPane();
holder.controller.ensure();
holder.setVisible(false);
const front = createPane();
front.controller.ensure();
assert.equal(budget.getActiveCount(), 2);
holder.setVisibleWithoutSync(true);
clock.advance(3_000);
assert.equal(holder.loaded, true);
assert.equal(front.loaded, true);
assert.equal(holder.addons[0].disposeCalls, 0);
front.addons[0].loseContext();
clock.advance(50);
assert.equal(front.loaded, false, "recovery cannot exceed a cap already filled by visible holders");
assert.equal(front.addons.length, 1);
assert.equal(budget.getActiveCount(), 1);
assert.equal(clock.pendingTimers, 0);
});
test("suspend, dispose and failed loads return the budget slot", () => {
@@ -65,7 +65,7 @@ export function createWebglRendererController<TAddon extends WebglRendererAddon>
// isVisible() is the source of truth; hiddenSince only remembers when the
// pane was last seen. Re-reading it at every decision keeps a pane that is
// on screen from being refused or released even if a sync was missed.
// on screen from being released even if a sync was missed.
const readVisibility = () => {
if (!options.isVisible) return;
if (options.isVisible()) hiddenSince = null;
@@ -94,7 +94,7 @@ export function createWebglRendererController<TAddon extends WebglRendererAddon>
const ensure = () => {
if (loaded || circuitBroken || disposed || !options.enabled) return;
// A hidden pane past the budget keeps the DOM renderer until it is shown.
// Panes past the budget keep the DOM renderer until a slot is available.
if (budget && !budget.tryAcquire(budgetMember)) return;
let nextAddon: TAddon | null = null;
try {
+3 -3
View File
@@ -938,9 +938,9 @@ export function useTerminalEffects(ctx: TerminalEffectsContext) {
return;
}
// A boot that never reached "connected" has nothing worth capturing, and
// the teardown below awaits terminal drain plus serialization before it
// closes anything. Cancel the pending backend boot after giving an immediate
// Never-connected logs are captured at explicit session close, including
// empty buffers. Runtime cleanup alone must not end an open log.
// Cancel the pending backend boot after giving an immediate
// remount a chance to replace this generation, instead of letting it
// finish against a pane that is already gone. Attached popups never own
// the backend session (skip closeSession) but still sync-dispose xterm.
@@ -374,3 +374,14 @@ test('side panel close button stays visible at every panel width', () => {
assert.match(closeSlice, /className="h-7 w-7 shrink-0 rounded-md p-0 hover:bg-transparent"/);
assert.doesNotMatch(closeSlice, /\bhidden\b|max-(sm|md|lg|xl):/);
});
test('magnified side-panel chrome thickens the accent stroke on low-DPR displays', () => {
const source = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8');
const overlay = source.slice(
source.indexOf('data-section="pane-magnification-overlay"'),
source.indexOf('data-section="pane-magnification-content"'),
);
assert.match(overlay, /overflow-hidden rounded-md border bg-background shadow-2xl/);
assert.match(overlay, /borderColor: sidePanelTheme\.accent,/);
assert.match(overlay, /resolveMagnifiedChromeBorderWidth\(/);
});
@@ -64,7 +64,7 @@ import { PersistentSidePanelPortal, SidePanelMountedContent } from './terminalLa
import { usePluginTerminalSidebar } from '../../application/state/usePluginTerminalSidebar';
import { PluginTerminalSidebarPageHost } from '../plugins/PluginTerminalSidebar';
import { PluginContributionIcon } from '../plugins/PluginContributionIcon';
import { getPaneMagnificationShortcutLabel } from '../../domain/paneMagnification';
import { getPaneMagnificationShortcutLabel, resolveMagnifiedChromeBorderWidth } from '../../domain/paneMagnification';
const MemoizedSidePanelMountedContent = memo(
SidePanelMountedContent,
@@ -1545,6 +1545,9 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
className="absolute inset-3 flex flex-col overflow-hidden rounded-md border bg-background shadow-2xl animate-in fade-in zoom-in-95 duration-150"
style={{
borderColor: sidePanelTheme.accent,
borderWidth: resolveMagnifiedChromeBorderWidth(
typeof window === 'undefined' ? 1 : (window.devicePixelRatio || 1),
),
backgroundColor: sidePanelTheme.termBg,
color: sidePanelTheme.termFg,
}}
@@ -52,6 +52,7 @@ import type { ResolvedAppearance, TerminalAppearanceHostScope } from '../../doma
import type { TerminalSidePanelAutoOpenTab } from '../../domain/terminalSidePanelAutoOpen';
import type { SidePanelTool } from '../../domain/sidePanelLayout';
import {
resolveMagnifiedChromeBorderWidth,
resolvePaneMagnificationStyle,
type PaneMagnificationController,
type PaneMagnificationTarget,
@@ -1439,10 +1440,12 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
observer.observe(surface);
return () => observer.disconnect();
}, [isMagnified]);
const magnifiedDevicePixelRatio = typeof window === 'undefined' ? 1 : (window.devicePixelRatio || 1);
const style: React.CSSProperties = resolvePaneMagnificationStyle(
layoutStyle,
isMagnified && !!magnifiedSurfaceBounds,
magnifiedSurfaceBounds,
magnifiedDevicePixelRatio,
);
useLayoutEffect(() => {
@@ -1605,6 +1608,9 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
style={{
...style,
borderColor: isMagnified && magnifiedSurfaceBounds ? sessionAppearanceTheme.colors.cursor : undefined,
borderWidth: isMagnified && magnifiedSurfaceBounds
? resolveMagnifiedChromeBorderWidth(magnifiedDevicePixelRatio)
: undefined,
}}
tabIndex={-1}
onClick={handlePaneClick}
@@ -15,6 +15,14 @@ test("magnified terminal panes use the resolved terminal accent for border chrom
assert.match(paneSource, /isMagnified && magnifiedSurfaceBounds && "overflow-hidden rounded-md border shadow-2xl /);
assert.match(paneSource, /borderColor: isMagnified && magnifiedSurfaceBounds \? sessionAppearanceTheme\.colors\.cursor : undefined/);
assert.match(paneSource, /borderWidth: isMagnified && magnifiedSurfaceBounds/);
assert.match(paneSource, /resolveMagnifiedChromeBorderWidth\(magnifiedDevicePixelRatio\)/);
});
test("magnified terminal panes snap overlay bounds to the device-pixel grid", () => {
const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8");
assert.match(source, /resolvePaneMagnificationStyle\(\s*layoutStyle,\s*isMagnified && !!magnifiedSurfaceBounds,\s*magnifiedSurfaceBounds,\s*magnifiedDevicePixelRatio,\s*\)/);
assert.match(source, /const magnifiedDevicePixelRatio = typeof window === 'undefined' \? 1 : \(window\.devicePixelRatio \|\| 1\)/);
});
test("terminal keyboard focus updates the pane selected for magnification", () => {
@@ -33,17 +33,17 @@
<text x="85" y="85.0" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="end">8K</text>
<text x="43" y="271.5" fill="#e6edf3" font-size="17" font-family="Handlee, cursive" font-weight="bold" transform="rotate(-90, 43, 271.5)">GitHub Stars</text>
<text x="90.0" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Jan 2026</text>
<text x="214.5" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Mar 2026</text>
<text x="347.8" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">May 2026</text>
<text x="481.0" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Jul 2026</text>
<text x="616.5" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Sep 2026</text>
<text x="749.7" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Nov 2026</text>
<text x="211.8" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Mar 2026</text>
<text x="342.1" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">May 2026</text>
<text x="472.4" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Jul 2026</text>
<text x="604.8" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Sep 2026</text>
<text x="735.1" y="488" fill="#e6edf3" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Nov 2026</text>
<text x="50%" y="525" fill="#e6edf3" font-size="17" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Date</text>
<line x1="90" y1="80" x2="90" y2="463" stroke="#30363d" stroke-width="2.5" filter="url(#xkcdify)"/>
<line x1="90" y1="463" x2="765" y2="463" stroke="#30363d" stroke-width="2.5" filter="url(#xkcdify)"/>
<path d="M 90.0,462.3 C 90.4,462.3 91.8,462.0 92.2,461.9 C 92.9,461.8 93.6,461.7 94.4,461.5 C 95.1,461.4 95.8,461.2 96.6,461.1 C 97.3,461.0 98.0,461.1 98.7,461.0 C 99.5,461.0 100.2,461.0 100.9,460.9 C 101.7,460.9 102.4,460.8 103.1,460.8 C 103.8,460.7 104.2,460.7 105.3,460.7 C 106.4,460.6 108.6,460.6 109.7,460.5 C 110.8,460.5 111.1,460.4 111.8,460.4 C 112.6,460.4 113.3,460.4 114.0,460.4 C 114.8,460.4 115.5,460.3 116.2,460.3 C 116.9,460.3 117.7,460.3 118.4,460.3 C 119.1,460.2 119.9,460.2 120.6,460.1 C 121.3,460.1 122.0,460.1 122.8,459.9 C 123.5,459.8 124.2,459.6 125.0,459.3 C 125.7,459.0 126.4,458.3 127.1,458.1 C 127.9,457.8 128.6,458.0 129.3,457.9 C 130.0,457.9 130.8,457.9 131.5,457.8 C 132.2,457.8 132.6,457.8 133.7,457.7 C 134.8,457.7 136.6,457.7 138.1,457.7 C 139.5,457.7 141.3,457.6 142.4,457.6 C 143.5,457.6 143.9,457.5 144.6,457.5 C 145.3,457.5 146.1,457.4 146.8,457.4 C 147.5,457.4 148.3,457.3 149.0,457.3 C 149.7,457.3 150.4,457.3 151.2,457.3 C 151.9,457.2 152.3,457.2 153.3,457.2 C 154.4,457.2 155.9,457.1 157.7,457.1 C 159.5,457.1 162.5,457.1 164.3,457.1 C 166.1,457.0 166.5,457.1 168.6,457.0 C 170.8,457.0 175.6,456.9 177.4,456.8 C 179.2,456.8 178.5,456.8 179.6,456.8 C 180.7,456.8 182.1,456.8 183.9,456.7 C 185.8,456.7 186.8,456.7 190.5,456.6 C 194.1,456.6 202.9,456.5 205.8,456.5 C 208.7,456.5 207.2,456.5 208.0,456.4 C 208.7,456.4 209.1,457.0 210.1,456.4 C 211.2,455.8 213.4,455.3 214.5,452.9 C 215.6,450.4 216.0,443.6 216.7,441.5 C 217.4,439.4 218.2,440.6 218.9,440.3 C 219.6,439.9 220.3,439.7 221.1,439.5 C 221.8,439.3 222.5,439.1 223.3,439.0 C 224.0,438.8 224.7,438.8 225.4,438.7 C 226.2,438.6 226.9,438.5 227.6,438.4 C 228.3,438.4 229.1,438.5 229.8,438.4 C 230.5,438.3 231.3,438.1 232.0,438.1 C 232.7,438.0 233.4,438.0 234.2,437.9 C 234.9,437.8 235.6,437.5 236.4,437.4 C 237.1,437.3 237.8,437.3 238.5,437.2 C 239.3,437.2 239.6,437.0 240.7,436.9 C 241.8,436.8 244.0,436.8 245.1,436.8 C 246.2,436.7 246.6,436.7 247.3,436.6 C 248.0,436.6 248.7,436.6 249.5,436.5 C 250.2,436.4 250.9,436.2 251.7,436.0 C 252.4,435.9 253.1,436.5 253.8,435.7 C 254.6,434.9 255.3,432.1 256.0,431.2 C 256.7,430.3 257.5,430.4 258.2,430.3 C 258.9,430.1 259.7,430.3 260.4,430.2 C 261.1,430.1 261.8,429.8 262.6,429.5 C 263.3,429.3 264.0,429.1 264.8,428.7 C 265.5,428.2 266.2,427.4 266.9,426.9 C 267.7,426.4 268.4,425.9 269.1,425.5 C 269.9,425.1 270.6,424.8 271.3,424.6 C 272.0,424.4 272.8,424.3 273.5,424.2 C 274.2,424.1 275.0,424.1 275.7,424.0 C 276.4,423.9 277.1,423.7 277.9,423.6 C 278.6,423.5 279.3,423.6 280.0,423.5 C 280.8,423.5 281.5,423.4 282.2,423.3 C 283.0,423.2 283.7,423.2 284.4,422.9 C 285.1,422.5 285.9,421.6 286.6,421.2 C 287.3,420.7 288.1,420.6 288.8,420.2 C 289.5,419.9 290.2,420.6 291.0,419.2 C 291.7,417.8 292.4,413.6 293.2,412.0 C 293.9,410.4 294.6,410.1 295.3,409.4 C 296.1,408.7 296.8,408.3 297.5,407.8 C 298.3,407.4 299.0,406.9 299.7,406.6 C 300.4,406.2 301.2,405.9 301.9,405.6 C 302.6,405.4 303.3,405.4 304.1,405.2 C 304.8,405.0 305.5,404.8 306.3,404.5 C 307.0,404.2 307.7,403.8 308.4,403.6 C 309.2,403.4 309.9,403.4 310.6,403.2 C 311.4,402.9 312.1,402.5 312.8,402.2 C 313.5,402.0 314.3,401.7 315.0,401.5 C 315.7,401.3 316.5,401.1 317.2,401.0 C 317.9,400.9 318.6,400.8 319.4,400.7 C 320.1,400.6 320.8,400.4 321.6,400.3 C 322.3,400.1 323.0,400.0 323.7,399.8 C 324.5,399.6 325.2,399.5 325.9,399.2 C 326.7,398.9 327.4,398.4 328.1,398.1 C 328.8,397.9 329.6,397.8 330.3,397.7 C 331.0,397.5 331.7,397.4 332.5,397.3 C 333.2,397.2 333.9,397.1 334.7,397.0 C 335.4,396.9 336.1,396.8 336.8,396.7 C 337.6,396.7 338.3,396.7 339.0,396.6 C 339.8,396.5 340.5,396.3 341.2,396.1 C 341.9,395.8 342.7,395.4 343.4,395.1 C 344.1,394.8 344.9,394.5 345.6,394.3 C 346.3,394.1 347.0,394.1 347.8,394.0 C 348.5,393.8 349.2,393.8 350.0,393.6 C 350.7,393.4 351.4,392.9 352.1,392.7 C 352.9,392.5 353.6,392.6 354.3,392.5 C 355.0,392.4 355.8,392.2 356.5,392.0 C 357.2,391.8 358.0,391.7 358.7,391.5 C 359.4,391.4 360.1,391.2 360.9,391.0 C 361.6,390.8 362.3,390.8 363.1,390.6 C 363.8,390.4 364.5,390.1 365.2,389.8 C 366.0,389.6 366.7,389.5 367.4,389.3 C 368.2,389.1 368.9,388.8 369.6,388.6 C 370.3,388.4 371.1,388.1 371.8,387.9 C 372.5,387.7 373.3,387.6 374.0,387.3 C 374.7,386.9 375.4,386.1 376.2,385.8 C 376.9,385.5 377.6,385.4 378.3,385.3 C 379.1,385.2 379.8,385.2 380.5,385.1 C 381.3,385.0 382.0,384.9 382.7,384.8 C 383.4,384.7 384.2,384.8 384.9,384.5 C 385.6,384.2 386.4,383.3 387.1,382.9 C 387.8,382.5 388.5,382.6 389.3,382.4 C 390.0,382.2 390.7,381.7 391.5,381.6 C 392.2,381.4 392.9,381.5 393.6,381.3 C 394.4,381.1 395.1,380.7 395.8,380.5 C 396.6,380.3 397.3,380.4 398.0,380.3 C 398.7,380.2 399.5,380.2 400.2,380.0 C 400.9,379.8 401.7,379.6 402.4,379.1 C 403.1,378.7 403.8,377.8 404.6,377.3 C 405.3,376.8 406.0,376.6 406.7,376.3 C 407.5,376.0 408.2,375.9 408.9,375.2 C 409.7,374.6 410.4,373.2 411.1,372.5 C 411.8,371.8 412.6,371.5 413.3,371.0 C 414.0,370.6 414.8,370.6 415.5,369.9 C 416.2,369.3 416.9,367.9 417.7,367.2 C 418.4,366.6 419.1,366.5 419.9,366.2 C 420.6,365.8 421.3,365.6 422.0,365.1 C 422.8,36Line truncated
<path d="M 90.0,462.3 C 90.4,462.3 91.8,462.0 92.2,461.9 C 92.9,461.8 93.6,461.7 94.4,461.5 C 95.1,461.4 95.8,461.2 96.6,461.1 C 97.3,461.0 98.0,461.1 98.7,461.0 C 99.5,461.0 100.2,461.0 100.9,460.9 C 101.7,460.9 102.4,460.8 103.1,460.8 C 103.8,460.7 104.2,460.7 105.3,460.7 C 106.4,460.6 108.6,460.6 109.7,460.5 C 110.8,460.5 111.1,460.4 111.8,460.4 C 112.6,460.4 113.3,460.4 114.0,460.4 C 114.8,460.4 115.5,460.3 116.2,460.3 C 116.9,460.3 117.7,460.3 118.4,460.3 C 119.1,460.2 119.9,460.2 120.6,460.1 C 121.3,460.1 122.0,460.1 122.8,459.9 C 123.5,459.8 124.2,459.6 125.0,459.3 C 125.7,459.0 126.4,458.3 127.1,458.1 C 127.9,457.8 128.6,458.0 129.3,457.9 C 130.0,457.9 130.8,457.9 131.5,457.8 C 132.2,457.8 132.6,457.8 133.7,457.7 C 134.8,457.7 136.6,457.7 138.1,457.7 C 139.5,457.7 141.3,457.6 142.4,457.6 C 143.5,457.6 143.9,457.5 144.6,457.5 C 145.3,457.5 146.1,457.4 146.8,457.4 C 147.5,457.4 148.3,457.3 149.0,457.3 C 149.7,457.3 150.4,457.3 151.2,457.3 C 151.9,457.2 152.3,457.2 153.3,457.2 C 154.4,457.2 155.9,457.1 157.7,457.1 C 159.5,457.1 162.5,457.1 164.3,457.1 C 166.1,457.0 166.5,457.1 168.6,457.0 C 170.8,457.0 175.6,456.9 177.4,456.8 C 179.2,456.8 178.5,456.8 179.6,456.8 C 180.7,456.8 182.1,456.8 183.9,456.7 C 185.8,456.7 186.8,456.7 190.5,456.6 C 194.1,456.6 202.9,456.5 205.8,456.5 C 208.7,456.5 207.2,456.5 208.0,456.4 C 208.7,456.4 209.1,457.0 210.1,456.4 C 211.2,455.8 213.4,455.3 214.5,452.9 C 215.6,450.4 216.0,443.6 216.7,441.5 C 217.4,439.4 218.2,440.6 218.9,440.3 C 219.6,439.9 220.3,439.7 221.1,439.5 C 221.8,439.3 222.5,439.1 223.3,439.0 C 224.0,438.8 224.7,438.8 225.4,438.7 C 226.2,438.6 226.9,438.5 227.6,438.4 C 228.3,438.4 229.1,438.5 229.8,438.4 C 230.5,438.3 231.3,438.1 232.0,438.1 C 232.7,438.0 233.4,438.0 234.2,437.9 C 234.9,437.8 235.6,437.5 236.4,437.4 C 237.1,437.3 237.8,437.3 238.5,437.2 C 239.3,437.2 239.6,437.0 240.7,436.9 C 241.8,436.8 244.0,436.8 245.1,436.8 C 246.2,436.7 246.6,436.7 247.3,436.6 C 248.0,436.6 248.7,436.6 249.5,436.5 C 250.2,436.4 250.9,436.2 251.7,436.0 C 252.4,435.9 253.1,436.5 253.8,435.7 C 254.6,434.9 255.3,432.1 256.0,431.2 C 256.7,430.3 257.5,430.4 258.2,430.3 C 258.9,430.1 259.7,430.3 260.4,430.2 C 261.1,430.1 261.8,429.8 262.6,429.5 C 263.3,429.3 264.0,429.1 264.8,428.7 C 265.5,428.2 266.2,427.4 266.9,426.9 C 267.7,426.4 268.4,425.9 269.1,425.5 C 269.9,425.1 270.6,424.8 271.3,424.6 C 272.0,424.4 272.8,424.3 273.5,424.2 C 274.2,424.1 275.0,424.1 275.7,424.0 C 276.4,423.9 277.1,423.7 277.9,423.6 C 278.6,423.5 279.3,423.6 280.0,423.5 C 280.8,423.5 281.5,423.4 282.2,423.3 C 283.0,423.2 283.7,423.2 284.4,422.9 C 285.1,422.5 285.9,421.6 286.6,421.2 C 287.3,420.7 288.1,420.6 288.8,420.2 C 289.5,419.9 290.2,420.6 291.0,419.2 C 291.7,417.8 292.4,413.6 293.2,412.0 C 293.9,410.4 294.6,410.1 295.3,409.4 C 296.1,408.7 296.8,408.3 297.5,407.8 C 298.3,407.4 299.0,406.9 299.7,406.6 C 300.4,406.2 301.2,405.9 301.9,405.6 C 302.6,405.4 303.3,405.4 304.1,405.2 C 304.8,405.0 305.5,404.8 306.3,404.5 C 307.0,404.2 307.7,403.8 308.4,403.6 C 309.2,403.4 309.9,403.4 310.6,403.2 C 311.4,402.9 312.1,402.5 312.8,402.2 C 313.5,402.0 314.3,401.7 315.0,401.5 C 315.7,401.3 316.5,401.1 317.2,401.0 C 317.9,400.9 318.6,400.8 319.4,400.7 C 320.1,400.6 320.8,400.4 321.6,400.3 C 322.3,400.1 323.0,400.0 323.7,399.8 C 324.5,399.6 325.2,399.5 325.9,399.2 C 326.7,398.9 327.4,398.4 328.1,398.1 C 328.8,397.9 329.6,397.8 330.3,397.7 C 331.0,397.5 331.7,397.4 332.5,397.3 C 333.2,397.2 333.9,397.1 334.7,397.0 C 335.4,396.9 336.1,396.8 336.8,396.7 C 337.6,396.7 338.3,396.7 339.0,396.6 C 339.8,396.5 340.5,396.3 341.2,396.1 C 341.9,395.8 342.7,395.4 343.4,395.1 C 344.1,394.8 344.9,394.5 345.6,394.3 C 346.3,394.1 347.0,394.1 347.8,394.0 C 348.5,393.8 349.2,393.8 350.0,393.6 C 350.7,393.4 351.4,392.9 352.1,392.7 C 352.9,392.5 353.6,392.6 354.3,392.5 C 355.0,392.4 355.8,392.2 356.5,392.0 C 357.2,391.8 358.0,391.7 358.7,391.5 C 359.4,391.4 360.1,391.2 360.9,391.0 C 361.6,390.8 362.3,390.8 363.1,390.6 C 363.8,390.4 364.5,390.1 365.2,389.8 C 366.0,389.6 366.7,389.5 367.4,389.3 C 368.2,389.1 368.9,388.8 369.6,388.6 C 370.3,388.4 371.1,388.1 371.8,387.9 C 372.5,387.7 373.3,387.6 374.0,387.3 C 374.7,386.9 375.4,386.1 376.2,385.8 C 376.9,385.5 377.6,385.4 378.3,385.3 C 379.1,385.2 379.8,385.2 380.5,385.1 C 381.3,385.0 382.0,384.9 382.7,384.8 C 383.4,384.7 384.2,384.8 384.9,384.5 C 385.6,384.2 386.4,383.3 387.1,382.9 C 387.8,382.5 388.5,382.6 389.3,382.4 C 390.0,382.2 390.7,381.7 391.5,381.6 C 392.2,381.4 392.9,381.5 393.6,381.3 C 394.4,381.1 395.1,380.7 395.8,380.5 C 396.6,380.3 397.3,380.4 398.0,380.3 C 398.7,380.2 399.5,380.2 400.2,380.0 C 400.9,379.8 401.7,379.6 402.4,379.1 C 403.1,378.7 403.8,377.8 404.6,377.3 C 405.3,376.8 406.0,376.6 406.7,376.3 C 407.5,376.0 408.2,375.9 408.9,375.2 C 409.7,374.6 410.4,373.2 411.1,372.5 C 411.8,371.8 412.6,371.5 413.3,371.0 C 414.0,370.6 414.8,370.6 415.5,369.9 C 416.2,369.3 416.9,367.9 417.7,367.2 C 418.4,366.6 419.1,366.5 419.9,366.2 C 420.6,365.8 421.3,365.6 422.0,365.1 C 422.8,36Line truncated
<circle cx="765.0" cy="119.4" r="5" fill="#dd4528" stroke="#0d1117" stroke-width="2" filter="url(#xkcdify)"/>
<text x="753.0" y="77.0" fill="#dd4528" font-size="18" font-family="Handlee, cursive" font-weight="bold" text-anchor="end">7176</text>
<path d="M 90.0,462.3 C 90.4,462.3 91.8,462.0 92.1,461.9 C 92.8,461.8 93.6,461.7 94.3,461.5 C 95.0,461.4 95.7,461.2 96.4,461.1 C 97.1,461.0 97.8,461.1 98.5,461.0 C 99.3,461.0 100.0,461.0 100.7,460.9 C 101.4,460.9 102.1,460.8 102.8,460.8 C 103.5,460.7 103.9,460.7 105.0,460.7 C 106.0,460.6 108.2,460.6 109.2,460.5 C 110.3,460.5 110.6,460.4 111.4,460.4 C 112.1,460.4 112.8,460.4 113.5,460.4 C 114.2,460.4 114.9,460.3 115.6,460.3 C 116.3,460.3 117.1,460.3 117.8,460.3 C 118.5,460.2 119.2,460.2 119.9,460.1 C 120.6,460.1 121.3,460.1 122.0,459.9 C 122.8,459.8 123.5,459.6 124.2,459.3 C 124.9,459.0 125.6,458.3 126.3,458.1 C 127.0,457.8 127.7,458.0 128.4,457.9 C 129.2,457.9 129.9,457.9 130.6,457.8 C 131.3,457.8 131.7,457.8 132.7,457.7 C 133.8,457.7 135.6,457.7 137.0,457.7 C 138.4,457.7 140.2,457.6 141.3,457.6 C 142.3,457.6 142.7,457.5 143.4,457.5 C 144.1,457.5 144.8,457.4 145.5,457.4 C 146.2,457.4 147.0,457.3 147.7,457.3 C 148.4,457.3 149.1,457.3 149.8,457.3 C 150.5,457.2 150.9,457.2 151.9,457.2 C 153.0,457.2 154.4,457.1 156.2,457.1 C 158.0,457.1 160.8,457.1 162.6,457.1 C 164.4,457.0 164.8,457.1 166.9,457.0 C 169.0,457.0 173.7,456.9 175.4,456.8 C 177.2,456.8 176.5,456.8 177.6,456.8 C 178.6,456.8 180.1,456.8 181.9,456.7 C 183.6,456.7 184.7,456.7 188.3,456.6 C 191.8,456.6 200.4,456.5 203.2,456.5 C 206.1,456.5 204.6,456.5 205.3,456.4 C 206.1,456.4 206.4,457.0 207.5,456.4 C 208.6,455.8 210.7,455.3 211.8,452.9 C 212.8,450.4 213.2,443.7 213.9,441.6 C 214.6,439.6 215.3,440.7 216.0,440.4 C 216.7,440.1 217.5,439.9 218.2,439.6 C 218.9,439.4 219.6,439.2 220.3,439.1 C 221.0,439.0 221.7,439.0 222.4,438.9 C 223.1,438.8 223.9,438.6 224.6,438.6 C 225.3,438.5 226.0,438.6 226.7,438.5 C 227.4,438.5 228.1,438.3 228.8,438.2 C 229.6,438.1 230.3,438.2 231.0,438.1 C 231.7,437.9 232.4,437.6 233.1,437.5 C 233.8,437.4 234.5,437.5 235.3,437.4 C 236.0,437.3 236.3,437.1 237.4,437.1 C 238.5,437.0 240.6,437.0 241.7,436.9 C 242.7,436.9 243.1,436.8 243.8,436.8 C 244.5,436.7 245.2,436.7 245.9,436.6 C 246.6,436.5 247.4,436.3 248.1,436.2 C 248.8,436.1 249.5,436.7 250.2,435.9 C 250.9,435.0 251.6,432.3 252.3,431.4 C 253.1,430.4 253.8,430.6 254.5,430.4 C 255.2,430.2 255.9,430.5 256.6,430.3 C 257.3,430.2 258.0,429.9 258.8,429.7 C 259.5,429.4 260.2,429.3 260.9,428.8 C 261.6,428.4 262.3,427.6 263.0,427.0 C 263.7,426.5 264.4,426.0 265.2,425.7 C 265.9,425.3 266.6,425.0 267.3,424.7 C 268.0,424.5 268.7,424.4 269.4,424.3 C 270.1,424.2 270.9,424.2 271.6,424.1 C 272.3,424.0 273.0,423.8 273.7,423.7 C 274.4,423.7 275.1,423.7 275.8,423.6 C 276.6,423.6 277.3,423.6 278.0,423.5 C 278.7,423.4 279.4,423.4 280.1,423.0 C 280.8,422.7 281.5,421.7 282.2,421.3 C 283.0,420.9 283.7,420.7 284.4,420.4 C 285.1,420.1 285.8,420.7 286.5,419.3 C 287.2,418.0 287.9,413.8 288.7,412.2 C 289.4,410.5 290.1,410.3 290.8,409.6 C 291.5,408.9 292.2,408.5 292.9,408.0 C 293.6,407.5 294.4,407.1 295.1,406.7 C 295.8,406.3 296.5,406.0 297.2,405.8 C 297.9,405.6 298.6,405.5 299.3,405.3 C 300.0,405.1 300.8,404.9 301.5,404.6 C 302.2,404.4 302.9,404.0 303.6,403.7 C 304.3,403.5 305.0,403.5 305.7,403.3 C 306.5,403.1 307.2,402.7 307.9,402.4 C 308.6,402.1 309.3,401.9 310.0,401.7 C 310.7,401.5 311.4,401.3 312.2,401.1 C 312.9,401.0 313.6,401.0 314.3,400.9 C 315.0,400.7 315.7,400.6 316.4,400.4 C 317.1,400.3 317.8,400.1 318.6,399.9 C 319.3,399.8 320.0,399.6 320.7,399.3 C 321.4,399.0 322.1,398.5 322.8,398.3 C 323.5,398.0 324.3,397.9 325.0,397.8 C 325.7,397.7 326.4,397.6 327.1,397.5 C 327.8,397.4 328.5,397.3 329.2,397.2 C 330.0,397.1 330.7,397.0 331.4,396.9 C 332.1,396.8 332.8,396.9 333.5,396.7 C 334.2,396.6 334.9,396.5 335.6,396.2 C 336.4,396.0 337.1,395.6 337.8,395.3 C 338.5,395.0 339.2,394.6 339.9,394.4 C 340.6,394.3 341.3,394.2 342.1,394.1 C 342.8,394.0 343.5,393.9 344.2,393.7 C 344.9,393.5 345.6,393.0 346.3,392.9 C 347.0,392.7 347.8,392.7 348.5,392.6 C 349.2,392.5 349.9,392.3 350.6,392.1 C 351.3,392.0 352.0,391.8 352.7,391.7 C 353.4,391.5 354.2,391.3 354.9,391.1 C 355.6,391.0 356.3,390.9 357.0,390.7 C 357.7,390.5 358.4,390.2 359.1,390.0 C 359.9,389.8 360.6,389.7 361.3,389.5 C 362.0,389.3 362.7,389.0 363.4,388.7 C 364.1,388.5 364.8,388.3 365.6,388.0 C 366.3,387.8 367.0,387.8 367.7,387.4 C 368.4,387.1 369.1,386.2 369.8,385.9 C 370.5,385.6 371.2,385.6 372.0,385.4 C 372.7,385.3 373.4,385.3 374.1,385.3 C 374.8,385.2 375.5,385.0 376.2,384.9 C 376.9,384.8 377.7,385.0 378.4,384.7 C 379.1,384.4 379.8,383.4 380.5,383.0 C 381.2,382.7 381.9,382.7 382.6,382.5 C 383.4,382.3 384.1,381.9 384.8,381.7 C 385.5,381.5 386.2,381.6 386.9,381.5 C 387.6,381.3 388.3,380.8 389.1,380.7 C 389.8,380.5 390.5,380.5 391.2,380.4 C 391.9,380.3 392.6,380.4 393.3,380.2 C 394.0,380.0 394.7,379.8 395.5,379.3 C 396.2,378.9 396.9,378.0 397.6,377.5 C 398.3,377.0 399.0,376.8 399.7,376.5 C 400.4,376.2 401.2,376.1 401.9,375.5 C 402.6,374.8 403.3,373.4 404.0,372.7 C 404.7,371.9 405.4,371.6 406.1,371.2 C 406.9,370.8 407.6,370.8 408.3,370.1 C 409.0,369.5 409.7,368.1 410.4,367.4 C 411.1,366.8 411.8,366.7 412.5,366.4 C 413.3,366.0 414.0,365.7 414.7,365.3 C 415.4,36Line truncated
<path d="M 90.0,462.3 C 90.4,462.3 91.8,462.0 92.1,461.9 C 92.8,461.8 93.6,461.7 94.3,461.5 C 95.0,461.4 95.7,461.2 96.4,461.1 C 97.1,461.0 97.8,461.1 98.5,461.0 C 99.3,461.0 100.0,461.0 100.7,460.9 C 101.4,460.9 102.1,460.8 102.8,460.8 C 103.5,460.7 103.9,460.7 105.0,460.7 C 106.0,460.6 108.2,460.6 109.2,460.5 C 110.3,460.5 110.6,460.4 111.4,460.4 C 112.1,460.4 112.8,460.4 113.5,460.4 C 114.2,460.4 114.9,460.3 115.6,460.3 C 116.3,460.3 117.1,460.3 117.8,460.3 C 118.5,460.2 119.2,460.2 119.9,460.1 C 120.6,460.1 121.3,460.1 122.0,459.9 C 122.8,459.8 123.5,459.6 124.2,459.3 C 124.9,459.0 125.6,458.3 126.3,458.1 C 127.0,457.8 127.7,458.0 128.4,457.9 C 129.2,457.9 129.9,457.9 130.6,457.8 C 131.3,457.8 131.7,457.8 132.7,457.7 C 133.8,457.7 135.6,457.7 137.0,457.7 C 138.4,457.7 140.2,457.6 141.3,457.6 C 142.3,457.6 142.7,457.5 143.4,457.5 C 144.1,457.5 144.8,457.4 145.5,457.4 C 146.2,457.4 147.0,457.3 147.7,457.3 C 148.4,457.3 149.1,457.3 149.8,457.3 C 150.5,457.2 150.9,457.2 151.9,457.2 C 153.0,457.2 154.4,457.1 156.2,457.1 C 158.0,457.1 160.8,457.1 162.6,457.1 C 164.4,457.0 164.8,457.1 166.9,457.0 C 169.0,457.0 173.7,456.9 175.4,456.8 C 177.2,456.8 176.5,456.8 177.6,456.8 C 178.6,456.8 180.1,456.8 181.9,456.7 C 183.6,456.7 184.7,456.7 188.3,456.6 C 191.8,456.6 200.4,456.5 203.2,456.5 C 206.1,456.5 204.6,456.5 205.3,456.4 C 206.1,456.4 206.4,457.0 207.5,456.4 C 208.6,455.8 210.7,455.3 211.8,452.9 C 212.8,450.4 213.2,443.7 213.9,441.6 C 214.6,439.6 215.3,440.7 216.0,440.4 C 216.7,440.1 217.5,439.9 218.2,439.6 C 218.9,439.4 219.6,439.2 220.3,439.1 C 221.0,439.0 221.7,439.0 222.4,438.9 C 223.1,438.8 223.9,438.6 224.6,438.6 C 225.3,438.5 226.0,438.6 226.7,438.5 C 227.4,438.5 228.1,438.3 228.8,438.2 C 229.6,438.1 230.3,438.2 231.0,438.1 C 231.7,437.9 232.4,437.6 233.1,437.5 C 233.8,437.4 234.5,437.5 235.3,437.4 C 236.0,437.3 236.3,437.1 237.4,437.1 C 238.5,437.0 240.6,437.0 241.7,436.9 C 242.7,436.9 243.1,436.8 243.8,436.8 C 244.5,436.7 245.2,436.7 245.9,436.6 C 246.6,436.5 247.4,436.3 248.1,436.2 C 248.8,436.1 249.5,436.7 250.2,435.9 C 250.9,435.0 251.6,432.3 252.3,431.4 C 253.1,430.4 253.8,430.6 254.5,430.4 C 255.2,430.2 255.9,430.5 256.6,430.3 C 257.3,430.2 258.0,429.9 258.8,429.7 C 259.5,429.4 260.2,429.3 260.9,428.8 C 261.6,428.4 262.3,427.6 263.0,427.0 C 263.7,426.5 264.4,426.0 265.2,425.7 C 265.9,425.3 266.6,425.0 267.3,424.7 C 268.0,424.5 268.7,424.4 269.4,424.3 C 270.1,424.2 270.9,424.2 271.6,424.1 C 272.3,424.0 273.0,423.8 273.7,423.7 C 274.4,423.7 275.1,423.7 275.8,423.6 C 276.6,423.6 277.3,423.6 278.0,423.5 C 278.7,423.4 279.4,423.4 280.1,423.0 C 280.8,422.7 281.5,421.7 282.2,421.3 C 283.0,420.9 283.7,420.7 284.4,420.4 C 285.1,420.1 285.8,420.7 286.5,419.3 C 287.2,418.0 287.9,413.8 288.7,412.2 C 289.4,410.5 290.1,410.3 290.8,409.6 C 291.5,408.9 292.2,408.5 292.9,408.0 C 293.6,407.5 294.4,407.1 295.1,406.7 C 295.8,406.3 296.5,406.0 297.2,405.8 C 297.9,405.6 298.6,405.5 299.3,405.3 C 300.0,405.1 300.8,404.9 301.5,404.6 C 302.2,404.4 302.9,404.0 303.6,403.7 C 304.3,403.5 305.0,403.5 305.7,403.3 C 306.5,403.1 307.2,402.7 307.9,402.4 C 308.6,402.1 309.3,401.9 310.0,401.7 C 310.7,401.5 311.4,401.3 312.2,401.1 C 312.9,401.0 313.6,401.0 314.3,400.9 C 315.0,400.7 315.7,400.6 316.4,400.4 C 317.1,400.3 317.8,400.1 318.6,399.9 C 319.3,399.8 320.0,399.6 320.7,399.3 C 321.4,399.0 322.1,398.5 322.8,398.3 C 323.5,398.0 324.3,397.9 325.0,397.8 C 325.7,397.7 326.4,397.6 327.1,397.5 C 327.8,397.4 328.5,397.3 329.2,397.2 C 330.0,397.1 330.7,397.0 331.4,396.9 C 332.1,396.8 332.8,396.9 333.5,396.7 C 334.2,396.6 334.9,396.5 335.6,396.2 C 336.4,396.0 337.1,395.6 337.8,395.3 C 338.5,395.0 339.2,394.6 339.9,394.4 C 340.6,394.3 341.3,394.2 342.1,394.1 C 342.8,394.0 343.5,393.9 344.2,393.7 C 344.9,393.5 345.6,393.0 346.3,392.9 C 347.0,392.7 347.8,392.7 348.5,392.6 C 349.2,392.5 349.9,392.3 350.6,392.1 C 351.3,392.0 352.0,391.8 352.7,391.7 C 353.4,391.5 354.2,391.3 354.9,391.1 C 355.6,391.0 356.3,390.9 357.0,390.7 C 357.7,390.5 358.4,390.2 359.1,390.0 C 359.9,389.8 360.6,389.7 361.3,389.5 C 362.0,389.3 362.7,389.0 363.4,388.7 C 364.1,388.5 364.8,388.3 365.6,388.0 C 366.3,387.8 367.0,387.8 367.7,387.4 C 368.4,387.1 369.1,386.2 369.8,385.9 C 370.5,385.6 371.2,385.6 372.0,385.4 C 372.7,385.3 373.4,385.3 374.1,385.3 C 374.8,385.2 375.5,385.0 376.2,384.9 C 376.9,384.8 377.7,385.0 378.4,384.7 C 379.1,384.4 379.8,383.4 380.5,383.0 C 381.2,382.7 381.9,382.7 382.6,382.5 C 383.4,382.3 384.1,381.9 384.8,381.7 C 385.5,381.5 386.2,381.6 386.9,381.5 C 387.6,381.3 388.3,380.8 389.1,380.7 C 389.8,380.5 390.5,380.5 391.2,380.4 C 391.9,380.3 392.6,380.4 393.3,380.2 C 394.0,380.0 394.7,379.8 395.5,379.3 C 396.2,378.9 396.9,378.0 397.6,377.5 C 398.3,377.0 399.0,376.8 399.7,376.5 C 400.4,376.2 401.2,376.1 401.9,375.5 C 402.6,374.8 403.3,373.4 404.0,372.7 C 404.7,371.9 405.4,371.6 406.1,371.2 C 406.9,370.8 407.6,370.8 408.3,370.1 C 409.0,369.5 409.7,368.1 410.4,367.4 C 411.1,366.8 411.8,366.7 412.5,366.4 C 413.3,366.0 414.0,365.7 414.7,365.3 C 415.4,36Line truncated
<circle cx="765.0" cy="108.4" r="5" fill="#dd4528" stroke="#0d1117" stroke-width="2" filter="url(#xkcdify)"/>
<text x="753.0" y="77.0" fill="#dd4528" font-size="18" font-family="Handlee, cursive" font-weight="bold" text-anchor="end">7406</text>
<a href="https://github.com/carsteneu/mystarhistory" target="_blank" rel="noopener"><text x="763" y="527" font-size="13" font-family="Handlee, cursive" fill="#fff" text-anchor="end">Made with carsteneu/mystarhistory</text></a>
</svg>

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 38 KiB

@@ -33,17 +33,17 @@
<text x="85" y="85.0" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="end">8K</text>
<text x="43" y="271.5" fill="#000" font-size="17" font-family="Handlee, cursive" font-weight="bold" transform="rotate(-90, 43, 271.5)">GitHub Stars</text>
<text x="90.0" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Jan 2026</text>
<text x="214.5" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Mar 2026</text>
<text x="347.8" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">May 2026</text>
<text x="481.0" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Jul 2026</text>
<text x="616.5" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Sep 2026</text>
<text x="749.7" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Nov 2026</text>
<text x="211.8" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Mar 2026</text>
<text x="342.1" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">May 2026</text>
<text x="472.4" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Jul 2026</text>
<text x="604.8" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Sep 2026</text>
<text x="735.1" y="488" fill="#000" font-size="16" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Nov 2026</text>
<text x="50%" y="525" fill="#000" font-size="17" font-family="Handlee, cursive" font-weight="bold" text-anchor="middle">Date</text>
<line x1="90" y1="80" x2="90" y2="463" stroke="#222" stroke-width="2.5" filter="url(#xkcdify)"/>
<line x1="90" y1="463" x2="765" y2="463" stroke="#222" stroke-width="2.5" filter="url(#xkcdify)"/>
<path d="M 90.0,462.3 C 90.4,462.3 91.8,462.0 92.2,461.9 C 92.9,461.8 93.6,461.7 94.4,461.5 C 95.1,461.4 95.8,461.2 96.6,461.1 C 97.3,461.0 98.0,461.1 98.7,461.0 C 99.5,461.0 100.2,461.0 100.9,460.9 C 101.7,460.9 102.4,460.8 103.1,460.8 C 103.8,460.7 104.2,460.7 105.3,460.7 C 106.4,460.6 108.6,460.6 109.7,460.5 C 110.8,460.5 111.1,460.4 111.8,460.4 C 112.6,460.4 113.3,460.4 114.0,460.4 C 114.8,460.4 115.5,460.3 116.2,460.3 C 116.9,460.3 117.7,460.3 118.4,460.3 C 119.1,460.2 119.9,460.2 120.6,460.1 C 121.3,460.1 122.0,460.1 122.8,459.9 C 123.5,459.8 124.2,459.6 125.0,459.3 C 125.7,459.0 126.4,458.3 127.1,458.1 C 127.9,457.8 128.6,458.0 129.3,457.9 C 130.0,457.9 130.8,457.9 131.5,457.8 C 132.2,457.8 132.6,457.8 133.7,457.7 C 134.8,457.7 136.6,457.7 138.1,457.7 C 139.5,457.7 141.3,457.6 142.4,457.6 C 143.5,457.6 143.9,457.5 144.6,457.5 C 145.3,457.5 146.1,457.4 146.8,457.4 C 147.5,457.4 148.3,457.3 149.0,457.3 C 149.7,457.3 150.4,457.3 151.2,457.3 C 151.9,457.2 152.3,457.2 153.3,457.2 C 154.4,457.2 155.9,457.1 157.7,457.1 C 159.5,457.1 162.5,457.1 164.3,457.1 C 166.1,457.0 166.5,457.1 168.6,457.0 C 170.8,457.0 175.6,456.9 177.4,456.8 C 179.2,456.8 178.5,456.8 179.6,456.8 C 180.7,456.8 182.1,456.8 183.9,456.7 C 185.8,456.7 186.8,456.7 190.5,456.6 C 194.1,456.6 202.9,456.5 205.8,456.5 C 208.7,456.5 207.2,456.5 208.0,456.4 C 208.7,456.4 209.1,457.0 210.1,456.4 C 211.2,455.8 213.4,455.3 214.5,452.9 C 215.6,450.4 216.0,443.6 216.7,441.5 C 217.4,439.4 218.2,440.6 218.9,440.3 C 219.6,439.9 220.3,439.7 221.1,439.5 C 221.8,439.3 222.5,439.1 223.3,439.0 C 224.0,438.8 224.7,438.8 225.4,438.7 C 226.2,438.6 226.9,438.5 227.6,438.4 C 228.3,438.4 229.1,438.5 229.8,438.4 C 230.5,438.3 231.3,438.1 232.0,438.1 C 232.7,438.0 233.4,438.0 234.2,437.9 C 234.9,437.8 235.6,437.5 236.4,437.4 C 237.1,437.3 237.8,437.3 238.5,437.2 C 239.3,437.2 239.6,437.0 240.7,436.9 C 241.8,436.8 244.0,436.8 245.1,436.8 C 246.2,436.7 246.6,436.7 247.3,436.6 C 248.0,436.6 248.7,436.6 249.5,436.5 C 250.2,436.4 250.9,436.2 251.7,436.0 C 252.4,435.9 253.1,436.5 253.8,435.7 C 254.6,434.9 255.3,432.1 256.0,431.2 C 256.7,430.3 257.5,430.4 258.2,430.3 C 258.9,430.1 259.7,430.3 260.4,430.2 C 261.1,430.1 261.8,429.8 262.6,429.5 C 263.3,429.3 264.0,429.1 264.8,428.7 C 265.5,428.2 266.2,427.4 266.9,426.9 C 267.7,426.4 268.4,425.9 269.1,425.5 C 269.9,425.1 270.6,424.8 271.3,424.6 C 272.0,424.4 272.8,424.3 273.5,424.2 C 274.2,424.1 275.0,424.1 275.7,424.0 C 276.4,423.9 277.1,423.7 277.9,423.6 C 278.6,423.5 279.3,423.6 280.0,423.5 C 280.8,423.5 281.5,423.4 282.2,423.3 C 283.0,423.2 283.7,423.2 284.4,422.9 C 285.1,422.5 285.9,421.6 286.6,421.2 C 287.3,420.7 288.1,420.6 288.8,420.2 C 289.5,419.9 290.2,420.6 291.0,419.2 C 291.7,417.8 292.4,413.6 293.2,412.0 C 293.9,410.4 294.6,410.1 295.3,409.4 C 296.1,408.7 296.8,408.3 297.5,407.8 C 298.3,407.4 299.0,406.9 299.7,406.6 C 300.4,406.2 301.2,405.9 301.9,405.6 C 302.6,405.4 303.3,405.4 304.1,405.2 C 304.8,405.0 305.5,404.8 306.3,404.5 C 307.0,404.2 307.7,403.8 308.4,403.6 C 309.2,403.4 309.9,403.4 310.6,403.2 C 311.4,402.9 312.1,402.5 312.8,402.2 C 313.5,402.0 314.3,401.7 315.0,401.5 C 315.7,401.3 316.5,401.1 317.2,401.0 C 317.9,400.9 318.6,400.8 319.4,400.7 C 320.1,400.6 320.8,400.4 321.6,400.3 C 322.3,400.1 323.0,400.0 323.7,399.8 C 324.5,399.6 325.2,399.5 325.9,399.2 C 326.7,398.9 327.4,398.4 328.1,398.1 C 328.8,397.9 329.6,397.8 330.3,397.7 C 331.0,397.5 331.7,397.4 332.5,397.3 C 333.2,397.2 333.9,397.1 334.7,397.0 C 335.4,396.9 336.1,396.8 336.8,396.7 C 337.6,396.7 338.3,396.7 339.0,396.6 C 339.8,396.5 340.5,396.3 341.2,396.1 C 341.9,395.8 342.7,395.4 343.4,395.1 C 344.1,394.8 344.9,394.5 345.6,394.3 C 346.3,394.1 347.0,394.1 347.8,394.0 C 348.5,393.8 349.2,393.8 350.0,393.6 C 350.7,393.4 351.4,392.9 352.1,392.7 C 352.9,392.5 353.6,392.6 354.3,392.5 C 355.0,392.4 355.8,392.2 356.5,392.0 C 357.2,391.8 358.0,391.7 358.7,391.5 C 359.4,391.4 360.1,391.2 360.9,391.0 C 361.6,390.8 362.3,390.8 363.1,390.6 C 363.8,390.4 364.5,390.1 365.2,389.8 C 366.0,389.6 366.7,389.5 367.4,389.3 C 368.2,389.1 368.9,388.8 369.6,388.6 C 370.3,388.4 371.1,388.1 371.8,387.9 C 372.5,387.7 373.3,387.6 374.0,387.3 C 374.7,386.9 375.4,386.1 376.2,385.8 C 376.9,385.5 377.6,385.4 378.3,385.3 C 379.1,385.2 379.8,385.2 380.5,385.1 C 381.3,385.0 382.0,384.9 382.7,384.8 C 383.4,384.7 384.2,384.8 384.9,384.5 C 385.6,384.2 386.4,383.3 387.1,382.9 C 387.8,382.5 388.5,382.6 389.3,382.4 C 390.0,382.2 390.7,381.7 391.5,381.6 C 392.2,381.4 392.9,381.5 393.6,381.3 C 394.4,381.1 395.1,380.7 395.8,380.5 C 396.6,380.3 397.3,380.4 398.0,380.3 C 398.7,380.2 399.5,380.2 400.2,380.0 C 400.9,379.8 401.7,379.6 402.4,379.1 C 403.1,378.7 403.8,377.8 404.6,377.3 C 405.3,376.8 406.0,376.6 406.7,376.3 C 407.5,376.0 408.2,375.9 408.9,375.2 C 409.7,374.6 410.4,373.2 411.1,372.5 C 411.8,371.8 412.6,371.5 413.3,371.0 C 414.0,370.6 414.8,370.6 415.5,369.9 C 416.2,369.3 416.9,367.9 417.7,367.2 C 418.4,366.6 419.1,366.5 419.9,366.2 C 420.6,365.8 421.3,365.6 422.0,365.1 C 422.8,36Line truncated
<path d="M 90.0,462.3 C 90.4,462.3 91.8,462.0 92.2,461.9 C 92.9,461.8 93.6,461.7 94.4,461.5 C 95.1,461.4 95.8,461.2 96.6,461.1 C 97.3,461.0 98.0,461.1 98.7,461.0 C 99.5,461.0 100.2,461.0 100.9,460.9 C 101.7,460.9 102.4,460.8 103.1,460.8 C 103.8,460.7 104.2,460.7 105.3,460.7 C 106.4,460.6 108.6,460.6 109.7,460.5 C 110.8,460.5 111.1,460.4 111.8,460.4 C 112.6,460.4 113.3,460.4 114.0,460.4 C 114.8,460.4 115.5,460.3 116.2,460.3 C 116.9,460.3 117.7,460.3 118.4,460.3 C 119.1,460.2 119.9,460.2 120.6,460.1 C 121.3,460.1 122.0,460.1 122.8,459.9 C 123.5,459.8 124.2,459.6 125.0,459.3 C 125.7,459.0 126.4,458.3 127.1,458.1 C 127.9,457.8 128.6,458.0 129.3,457.9 C 130.0,457.9 130.8,457.9 131.5,457.8 C 132.2,457.8 132.6,457.8 133.7,457.7 C 134.8,457.7 136.6,457.7 138.1,457.7 C 139.5,457.7 141.3,457.6 142.4,457.6 C 143.5,457.6 143.9,457.5 144.6,457.5 C 145.3,457.5 146.1,457.4 146.8,457.4 C 147.5,457.4 148.3,457.3 149.0,457.3 C 149.7,457.3 150.4,457.3 151.2,457.3 C 151.9,457.2 152.3,457.2 153.3,457.2 C 154.4,457.2 155.9,457.1 157.7,457.1 C 159.5,457.1 162.5,457.1 164.3,457.1 C 166.1,457.0 166.5,457.1 168.6,457.0 C 170.8,457.0 175.6,456.9 177.4,456.8 C 179.2,456.8 178.5,456.8 179.6,456.8 C 180.7,456.8 182.1,456.8 183.9,456.7 C 185.8,456.7 186.8,456.7 190.5,456.6 C 194.1,456.6 202.9,456.5 205.8,456.5 C 208.7,456.5 207.2,456.5 208.0,456.4 C 208.7,456.4 209.1,457.0 210.1,456.4 C 211.2,455.8 213.4,455.3 214.5,452.9 C 215.6,450.4 216.0,443.6 216.7,441.5 C 217.4,439.4 218.2,440.6 218.9,440.3 C 219.6,439.9 220.3,439.7 221.1,439.5 C 221.8,439.3 222.5,439.1 223.3,439.0 C 224.0,438.8 224.7,438.8 225.4,438.7 C 226.2,438.6 226.9,438.5 227.6,438.4 C 228.3,438.4 229.1,438.5 229.8,438.4 C 230.5,438.3 231.3,438.1 232.0,438.1 C 232.7,438.0 233.4,438.0 234.2,437.9 C 234.9,437.8 235.6,437.5 236.4,437.4 C 237.1,437.3 237.8,437.3 238.5,437.2 C 239.3,437.2 239.6,437.0 240.7,436.9 C 241.8,436.8 244.0,436.8 245.1,436.8 C 246.2,436.7 246.6,436.7 247.3,436.6 C 248.0,436.6 248.7,436.6 249.5,436.5 C 250.2,436.4 250.9,436.2 251.7,436.0 C 252.4,435.9 253.1,436.5 253.8,435.7 C 254.6,434.9 255.3,432.1 256.0,431.2 C 256.7,430.3 257.5,430.4 258.2,430.3 C 258.9,430.1 259.7,430.3 260.4,430.2 C 261.1,430.1 261.8,429.8 262.6,429.5 C 263.3,429.3 264.0,429.1 264.8,428.7 C 265.5,428.2 266.2,427.4 266.9,426.9 C 267.7,426.4 268.4,425.9 269.1,425.5 C 269.9,425.1 270.6,424.8 271.3,424.6 C 272.0,424.4 272.8,424.3 273.5,424.2 C 274.2,424.1 275.0,424.1 275.7,424.0 C 276.4,423.9 277.1,423.7 277.9,423.6 C 278.6,423.5 279.3,423.6 280.0,423.5 C 280.8,423.5 281.5,423.4 282.2,423.3 C 283.0,423.2 283.7,423.2 284.4,422.9 C 285.1,422.5 285.9,421.6 286.6,421.2 C 287.3,420.7 288.1,420.6 288.8,420.2 C 289.5,419.9 290.2,420.6 291.0,419.2 C 291.7,417.8 292.4,413.6 293.2,412.0 C 293.9,410.4 294.6,410.1 295.3,409.4 C 296.1,408.7 296.8,408.3 297.5,407.8 C 298.3,407.4 299.0,406.9 299.7,406.6 C 300.4,406.2 301.2,405.9 301.9,405.6 C 302.6,405.4 303.3,405.4 304.1,405.2 C 304.8,405.0 305.5,404.8 306.3,404.5 C 307.0,404.2 307.7,403.8 308.4,403.6 C 309.2,403.4 309.9,403.4 310.6,403.2 C 311.4,402.9 312.1,402.5 312.8,402.2 C 313.5,402.0 314.3,401.7 315.0,401.5 C 315.7,401.3 316.5,401.1 317.2,401.0 C 317.9,400.9 318.6,400.8 319.4,400.7 C 320.1,400.6 320.8,400.4 321.6,400.3 C 322.3,400.1 323.0,400.0 323.7,399.8 C 324.5,399.6 325.2,399.5 325.9,399.2 C 326.7,398.9 327.4,398.4 328.1,398.1 C 328.8,397.9 329.6,397.8 330.3,397.7 C 331.0,397.5 331.7,397.4 332.5,397.3 C 333.2,397.2 333.9,397.1 334.7,397.0 C 335.4,396.9 336.1,396.8 336.8,396.7 C 337.6,396.7 338.3,396.7 339.0,396.6 C 339.8,396.5 340.5,396.3 341.2,396.1 C 341.9,395.8 342.7,395.4 343.4,395.1 C 344.1,394.8 344.9,394.5 345.6,394.3 C 346.3,394.1 347.0,394.1 347.8,394.0 C 348.5,393.8 349.2,393.8 350.0,393.6 C 350.7,393.4 351.4,392.9 352.1,392.7 C 352.9,392.5 353.6,392.6 354.3,392.5 C 355.0,392.4 355.8,392.2 356.5,392.0 C 357.2,391.8 358.0,391.7 358.7,391.5 C 359.4,391.4 360.1,391.2 360.9,391.0 C 361.6,390.8 362.3,390.8 363.1,390.6 C 363.8,390.4 364.5,390.1 365.2,389.8 C 366.0,389.6 366.7,389.5 367.4,389.3 C 368.2,389.1 368.9,388.8 369.6,388.6 C 370.3,388.4 371.1,388.1 371.8,387.9 C 372.5,387.7 373.3,387.6 374.0,387.3 C 374.7,386.9 375.4,386.1 376.2,385.8 C 376.9,385.5 377.6,385.4 378.3,385.3 C 379.1,385.2 379.8,385.2 380.5,385.1 C 381.3,385.0 382.0,384.9 382.7,384.8 C 383.4,384.7 384.2,384.8 384.9,384.5 C 385.6,384.2 386.4,383.3 387.1,382.9 C 387.8,382.5 388.5,382.6 389.3,382.4 C 390.0,382.2 390.7,381.7 391.5,381.6 C 392.2,381.4 392.9,381.5 393.6,381.3 C 394.4,381.1 395.1,380.7 395.8,380.5 C 396.6,380.3 397.3,380.4 398.0,380.3 C 398.7,380.2 399.5,380.2 400.2,380.0 C 400.9,379.8 401.7,379.6 402.4,379.1 C 403.1,378.7 403.8,377.8 404.6,377.3 C 405.3,376.8 406.0,376.6 406.7,376.3 C 407.5,376.0 408.2,375.9 408.9,375.2 C 409.7,374.6 410.4,373.2 411.1,372.5 C 411.8,371.8 412.6,371.5 413.3,371.0 C 414.0,370.6 414.8,370.6 415.5,369.9 C 416.2,369.3 416.9,367.9 417.7,367.2 C 418.4,366.6 419.1,366.5 419.9,366.2 C 420.6,365.8 421.3,365.6 422.0,365.1 C 422.8,36Line truncated
<circle cx="765.0" cy="119.4" r="5" fill="#dd4528" stroke="#fff" stroke-width="2" filter="url(#xkcdify)"/>
<text x="753.0" y="77.0" fill="#dd4528" font-size="18" font-family="Handlee, cursive" font-weight="bold" text-anchor="end">7176</text>
<path d="M 90.0,462.3 C 90.4,462.3 91.8,462.0 92.1,461.9 C 92.8,461.8 93.6,461.7 94.3,461.5 C 95.0,461.4 95.7,461.2 96.4,461.1 C 97.1,461.0 97.8,461.1 98.5,461.0 C 99.3,461.0 100.0,461.0 100.7,460.9 C 101.4,460.9 102.1,460.8 102.8,460.8 C 103.5,460.7 103.9,460.7 105.0,460.7 C 106.0,460.6 108.2,460.6 109.2,460.5 C 110.3,460.5 110.6,460.4 111.4,460.4 C 112.1,460.4 112.8,460.4 113.5,460.4 C 114.2,460.4 114.9,460.3 115.6,460.3 C 116.3,460.3 117.1,460.3 117.8,460.3 C 118.5,460.2 119.2,460.2 119.9,460.1 C 120.6,460.1 121.3,460.1 122.0,459.9 C 122.8,459.8 123.5,459.6 124.2,459.3 C 124.9,459.0 125.6,458.3 126.3,458.1 C 127.0,457.8 127.7,458.0 128.4,457.9 C 129.2,457.9 129.9,457.9 130.6,457.8 C 131.3,457.8 131.7,457.8 132.7,457.7 C 133.8,457.7 135.6,457.7 137.0,457.7 C 138.4,457.7 140.2,457.6 141.3,457.6 C 142.3,457.6 142.7,457.5 143.4,457.5 C 144.1,457.5 144.8,457.4 145.5,457.4 C 146.2,457.4 147.0,457.3 147.7,457.3 C 148.4,457.3 149.1,457.3 149.8,457.3 C 150.5,457.2 150.9,457.2 151.9,457.2 C 153.0,457.2 154.4,457.1 156.2,457.1 C 158.0,457.1 160.8,457.1 162.6,457.1 C 164.4,457.0 164.8,457.1 166.9,457.0 C 169.0,457.0 173.7,456.9 175.4,456.8 C 177.2,456.8 176.5,456.8 177.6,456.8 C 178.6,456.8 180.1,456.8 181.9,456.7 C 183.6,456.7 184.7,456.7 188.3,456.6 C 191.8,456.6 200.4,456.5 203.2,456.5 C 206.1,456.5 204.6,456.5 205.3,456.4 C 206.1,456.4 206.4,457.0 207.5,456.4 C 208.6,455.8 210.7,455.3 211.8,452.9 C 212.8,450.4 213.2,443.7 213.9,441.6 C 214.6,439.6 215.3,440.7 216.0,440.4 C 216.7,440.1 217.5,439.9 218.2,439.6 C 218.9,439.4 219.6,439.2 220.3,439.1 C 221.0,439.0 221.7,439.0 222.4,438.9 C 223.1,438.8 223.9,438.6 224.6,438.6 C 225.3,438.5 226.0,438.6 226.7,438.5 C 227.4,438.5 228.1,438.3 228.8,438.2 C 229.6,438.1 230.3,438.2 231.0,438.1 C 231.7,437.9 232.4,437.6 233.1,437.5 C 233.8,437.4 234.5,437.5 235.3,437.4 C 236.0,437.3 236.3,437.1 237.4,437.1 C 238.5,437.0 240.6,437.0 241.7,436.9 C 242.7,436.9 243.1,436.8 243.8,436.8 C 244.5,436.7 245.2,436.7 245.9,436.6 C 246.6,436.5 247.4,436.3 248.1,436.2 C 248.8,436.1 249.5,436.7 250.2,435.9 C 250.9,435.0 251.6,432.3 252.3,431.4 C 253.1,430.4 253.8,430.6 254.5,430.4 C 255.2,430.2 255.9,430.5 256.6,430.3 C 257.3,430.2 258.0,429.9 258.8,429.7 C 259.5,429.4 260.2,429.3 260.9,428.8 C 261.6,428.4 262.3,427.6 263.0,427.0 C 263.7,426.5 264.4,426.0 265.2,425.7 C 265.9,425.3 266.6,425.0 267.3,424.7 C 268.0,424.5 268.7,424.4 269.4,424.3 C 270.1,424.2 270.9,424.2 271.6,424.1 C 272.3,424.0 273.0,423.8 273.7,423.7 C 274.4,423.7 275.1,423.7 275.8,423.6 C 276.6,423.6 277.3,423.6 278.0,423.5 C 278.7,423.4 279.4,423.4 280.1,423.0 C 280.8,422.7 281.5,421.7 282.2,421.3 C 283.0,420.9 283.7,420.7 284.4,420.4 C 285.1,420.1 285.8,420.7 286.5,419.3 C 287.2,418.0 287.9,413.8 288.7,412.2 C 289.4,410.5 290.1,410.3 290.8,409.6 C 291.5,408.9 292.2,408.5 292.9,408.0 C 293.6,407.5 294.4,407.1 295.1,406.7 C 295.8,406.3 296.5,406.0 297.2,405.8 C 297.9,405.6 298.6,405.5 299.3,405.3 C 300.0,405.1 300.8,404.9 301.5,404.6 C 302.2,404.4 302.9,404.0 303.6,403.7 C 304.3,403.5 305.0,403.5 305.7,403.3 C 306.5,403.1 307.2,402.7 307.9,402.4 C 308.6,402.1 309.3,401.9 310.0,401.7 C 310.7,401.5 311.4,401.3 312.2,401.1 C 312.9,401.0 313.6,401.0 314.3,400.9 C 315.0,400.7 315.7,400.6 316.4,400.4 C 317.1,400.3 317.8,400.1 318.6,399.9 C 319.3,399.8 320.0,399.6 320.7,399.3 C 321.4,399.0 322.1,398.5 322.8,398.3 C 323.5,398.0 324.3,397.9 325.0,397.8 C 325.7,397.7 326.4,397.6 327.1,397.5 C 327.8,397.4 328.5,397.3 329.2,397.2 C 330.0,397.1 330.7,397.0 331.4,396.9 C 332.1,396.8 332.8,396.9 333.5,396.7 C 334.2,396.6 334.9,396.5 335.6,396.2 C 336.4,396.0 337.1,395.6 337.8,395.3 C 338.5,395.0 339.2,394.6 339.9,394.4 C 340.6,394.3 341.3,394.2 342.1,394.1 C 342.8,394.0 343.5,393.9 344.2,393.7 C 344.9,393.5 345.6,393.0 346.3,392.9 C 347.0,392.7 347.8,392.7 348.5,392.6 C 349.2,392.5 349.9,392.3 350.6,392.1 C 351.3,392.0 352.0,391.8 352.7,391.7 C 353.4,391.5 354.2,391.3 354.9,391.1 C 355.6,391.0 356.3,390.9 357.0,390.7 C 357.7,390.5 358.4,390.2 359.1,390.0 C 359.9,389.8 360.6,389.7 361.3,389.5 C 362.0,389.3 362.7,389.0 363.4,388.7 C 364.1,388.5 364.8,388.3 365.6,388.0 C 366.3,387.8 367.0,387.8 367.7,387.4 C 368.4,387.1 369.1,386.2 369.8,385.9 C 370.5,385.6 371.2,385.6 372.0,385.4 C 372.7,385.3 373.4,385.3 374.1,385.3 C 374.8,385.2 375.5,385.0 376.2,384.9 C 376.9,384.8 377.7,385.0 378.4,384.7 C 379.1,384.4 379.8,383.4 380.5,383.0 C 381.2,382.7 381.9,382.7 382.6,382.5 C 383.4,382.3 384.1,381.9 384.8,381.7 C 385.5,381.5 386.2,381.6 386.9,381.5 C 387.6,381.3 388.3,380.8 389.1,380.7 C 389.8,380.5 390.5,380.5 391.2,380.4 C 391.9,380.3 392.6,380.4 393.3,380.2 C 394.0,380.0 394.7,379.8 395.5,379.3 C 396.2,378.9 396.9,378.0 397.6,377.5 C 398.3,377.0 399.0,376.8 399.7,376.5 C 400.4,376.2 401.2,376.1 401.9,375.5 C 402.6,374.8 403.3,373.4 404.0,372.7 C 404.7,371.9 405.4,371.6 406.1,371.2 C 406.9,370.8 407.6,370.8 408.3,370.1 C 409.0,369.5 409.7,368.1 410.4,367.4 C 411.1,366.8 411.8,366.7 412.5,366.4 C 413.3,366.0 414.0,365.7 414.7,365.3 C 415.4,36Line truncated
<path d="M 90.0,462.3 C 90.4,462.3 91.8,462.0 92.1,461.9 C 92.8,461.8 93.6,461.7 94.3,461.5 C 95.0,461.4 95.7,461.2 96.4,461.1 C 97.1,461.0 97.8,461.1 98.5,461.0 C 99.3,461.0 100.0,461.0 100.7,460.9 C 101.4,460.9 102.1,460.8 102.8,460.8 C 103.5,460.7 103.9,460.7 105.0,460.7 C 106.0,460.6 108.2,460.6 109.2,460.5 C 110.3,460.5 110.6,460.4 111.4,460.4 C 112.1,460.4 112.8,460.4 113.5,460.4 C 114.2,460.4 114.9,460.3 115.6,460.3 C 116.3,460.3 117.1,460.3 117.8,460.3 C 118.5,460.2 119.2,460.2 119.9,460.1 C 120.6,460.1 121.3,460.1 122.0,459.9 C 122.8,459.8 123.5,459.6 124.2,459.3 C 124.9,459.0 125.6,458.3 126.3,458.1 C 127.0,457.8 127.7,458.0 128.4,457.9 C 129.2,457.9 129.9,457.9 130.6,457.8 C 131.3,457.8 131.7,457.8 132.7,457.7 C 133.8,457.7 135.6,457.7 137.0,457.7 C 138.4,457.7 140.2,457.6 141.3,457.6 C 142.3,457.6 142.7,457.5 143.4,457.5 C 144.1,457.5 144.8,457.4 145.5,457.4 C 146.2,457.4 147.0,457.3 147.7,457.3 C 148.4,457.3 149.1,457.3 149.8,457.3 C 150.5,457.2 150.9,457.2 151.9,457.2 C 153.0,457.2 154.4,457.1 156.2,457.1 C 158.0,457.1 160.8,457.1 162.6,457.1 C 164.4,457.0 164.8,457.1 166.9,457.0 C 169.0,457.0 173.7,456.9 175.4,456.8 C 177.2,456.8 176.5,456.8 177.6,456.8 C 178.6,456.8 180.1,456.8 181.9,456.7 C 183.6,456.7 184.7,456.7 188.3,456.6 C 191.8,456.6 200.4,456.5 203.2,456.5 C 206.1,456.5 204.6,456.5 205.3,456.4 C 206.1,456.4 206.4,457.0 207.5,456.4 C 208.6,455.8 210.7,455.3 211.8,452.9 C 212.8,450.4 213.2,443.7 213.9,441.6 C 214.6,439.6 215.3,440.7 216.0,440.4 C 216.7,440.1 217.5,439.9 218.2,439.6 C 218.9,439.4 219.6,439.2 220.3,439.1 C 221.0,439.0 221.7,439.0 222.4,438.9 C 223.1,438.8 223.9,438.6 224.6,438.6 C 225.3,438.5 226.0,438.6 226.7,438.5 C 227.4,438.5 228.1,438.3 228.8,438.2 C 229.6,438.1 230.3,438.2 231.0,438.1 C 231.7,437.9 232.4,437.6 233.1,437.5 C 233.8,437.4 234.5,437.5 235.3,437.4 C 236.0,437.3 236.3,437.1 237.4,437.1 C 238.5,437.0 240.6,437.0 241.7,436.9 C 242.7,436.9 243.1,436.8 243.8,436.8 C 244.5,436.7 245.2,436.7 245.9,436.6 C 246.6,436.5 247.4,436.3 248.1,436.2 C 248.8,436.1 249.5,436.7 250.2,435.9 C 250.9,435.0 251.6,432.3 252.3,431.4 C 253.1,430.4 253.8,430.6 254.5,430.4 C 255.2,430.2 255.9,430.5 256.6,430.3 C 257.3,430.2 258.0,429.9 258.8,429.7 C 259.5,429.4 260.2,429.3 260.9,428.8 C 261.6,428.4 262.3,427.6 263.0,427.0 C 263.7,426.5 264.4,426.0 265.2,425.7 C 265.9,425.3 266.6,425.0 267.3,424.7 C 268.0,424.5 268.7,424.4 269.4,424.3 C 270.1,424.2 270.9,424.2 271.6,424.1 C 272.3,424.0 273.0,423.8 273.7,423.7 C 274.4,423.7 275.1,423.7 275.8,423.6 C 276.6,423.6 277.3,423.6 278.0,423.5 C 278.7,423.4 279.4,423.4 280.1,423.0 C 280.8,422.7 281.5,421.7 282.2,421.3 C 283.0,420.9 283.7,420.7 284.4,420.4 C 285.1,420.1 285.8,420.7 286.5,419.3 C 287.2,418.0 287.9,413.8 288.7,412.2 C 289.4,410.5 290.1,410.3 290.8,409.6 C 291.5,408.9 292.2,408.5 292.9,408.0 C 293.6,407.5 294.4,407.1 295.1,406.7 C 295.8,406.3 296.5,406.0 297.2,405.8 C 297.9,405.6 298.6,405.5 299.3,405.3 C 300.0,405.1 300.8,404.9 301.5,404.6 C 302.2,404.4 302.9,404.0 303.6,403.7 C 304.3,403.5 305.0,403.5 305.7,403.3 C 306.5,403.1 307.2,402.7 307.9,402.4 C 308.6,402.1 309.3,401.9 310.0,401.7 C 310.7,401.5 311.4,401.3 312.2,401.1 C 312.9,401.0 313.6,401.0 314.3,400.9 C 315.0,400.7 315.7,400.6 316.4,400.4 C 317.1,400.3 317.8,400.1 318.6,399.9 C 319.3,399.8 320.0,399.6 320.7,399.3 C 321.4,399.0 322.1,398.5 322.8,398.3 C 323.5,398.0 324.3,397.9 325.0,397.8 C 325.7,397.7 326.4,397.6 327.1,397.5 C 327.8,397.4 328.5,397.3 329.2,397.2 C 330.0,397.1 330.7,397.0 331.4,396.9 C 332.1,396.8 332.8,396.9 333.5,396.7 C 334.2,396.6 334.9,396.5 335.6,396.2 C 336.4,396.0 337.1,395.6 337.8,395.3 C 338.5,395.0 339.2,394.6 339.9,394.4 C 340.6,394.3 341.3,394.2 342.1,394.1 C 342.8,394.0 343.5,393.9 344.2,393.7 C 344.9,393.5 345.6,393.0 346.3,392.9 C 347.0,392.7 347.8,392.7 348.5,392.6 C 349.2,392.5 349.9,392.3 350.6,392.1 C 351.3,392.0 352.0,391.8 352.7,391.7 C 353.4,391.5 354.2,391.3 354.9,391.1 C 355.6,391.0 356.3,390.9 357.0,390.7 C 357.7,390.5 358.4,390.2 359.1,390.0 C 359.9,389.8 360.6,389.7 361.3,389.5 C 362.0,389.3 362.7,389.0 363.4,388.7 C 364.1,388.5 364.8,388.3 365.6,388.0 C 366.3,387.8 367.0,387.8 367.7,387.4 C 368.4,387.1 369.1,386.2 369.8,385.9 C 370.5,385.6 371.2,385.6 372.0,385.4 C 372.7,385.3 373.4,385.3 374.1,385.3 C 374.8,385.2 375.5,385.0 376.2,384.9 C 376.9,384.8 377.7,385.0 378.4,384.7 C 379.1,384.4 379.8,383.4 380.5,383.0 C 381.2,382.7 381.9,382.7 382.6,382.5 C 383.4,382.3 384.1,381.9 384.8,381.7 C 385.5,381.5 386.2,381.6 386.9,381.5 C 387.6,381.3 388.3,380.8 389.1,380.7 C 389.8,380.5 390.5,380.5 391.2,380.4 C 391.9,380.3 392.6,380.4 393.3,380.2 C 394.0,380.0 394.7,379.8 395.5,379.3 C 396.2,378.9 396.9,378.0 397.6,377.5 C 398.3,377.0 399.0,376.8 399.7,376.5 C 400.4,376.2 401.2,376.1 401.9,375.5 C 402.6,374.8 403.3,373.4 404.0,372.7 C 404.7,371.9 405.4,371.6 406.1,371.2 C 406.9,370.8 407.6,370.8 408.3,370.1 C 409.0,369.5 409.7,368.1 410.4,367.4 C 411.1,366.8 411.8,366.7 412.5,366.4 C 413.3,366.0 414.0,365.7 414.7,365.3 C 415.4,36Line truncated
<circle cx="765.0" cy="108.4" r="5" fill="#dd4528" stroke="#fff" stroke-width="2" filter="url(#xkcdify)"/>
<text x="753.0" y="77.0" fill="#dd4528" font-size="18" font-family="Handlee, cursive" font-weight="bold" text-anchor="end">7406</text>
<a href="https://github.com/carsteneu/mystarhistory" target="_blank" rel="noopener"><text x="763" y="527" font-size="13" font-family="Handlee, cursive" fill="#000" text-anchor="end">Made with carsteneu/mystarhistory</text></a>
</svg>

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 38 KiB

+28
View File
@@ -1,5 +1,6 @@
import assert from "node:assert/strict";
import { createRequire } from "node:module";
import { isIP } from "node:net";
import test from "node:test";
import {
@@ -9,11 +10,38 @@ import {
buildCodexHttpToml,
buildExternalMcpHttpUrl,
buildGenericHttpMcpJson,
isExternalMcpHttpIpAddress,
} from "./externalMcpHttp.ts";
const require = createRequire(import.meta.url);
const security = require("../electron/bridges/externalMcp/httpSecurity.cjs");
test("HTTP IP validation accepts valid literals and agrees with the runtime", () => {
const valid = [
"::1", "::", "0.0.0.0", "127.0.0.1", "255.255.255.255",
"1:2:3:4:5:6:7:8", "fe80::1", "2001:db8::1", "::ffff:127.0.0.1",
"1:2:3:4:5:6:127.0.0.1", "FE80::ABCD", "fe80::1%eth0",
];
for (const address of valid) {
assert.equal(isExternalMcpHttpIpAddress(address), true, address);
assert.equal(isExternalMcpHttpIpAddress(address), isIP(address) !== 0, address);
}
});
test("HTTP IP validation rejects malformed literals and agrees with the runtime", () => {
const invalid = [
"1::2::3", ":", "1:2:3:4:5:6:7:8:9", "1:::2", ":::", "12345::", "g::1",
"127.000.0.1", "", " ", "\t\n", "127.0.0", "256.0.0.1", "-1.0.0.1",
"1:2:3:4:5:6:7", "1:2:3:4:5:6:7:8::", ":1:2:3:4:5:6:7", "1:2:3:4:5:6:7:",
"::ffff:127.000.0.1", "::ffff:256.0.0.1", "1:2:3:4:5:127.0.0.1",
"1:2:3:4:5:6::127.0.0.1", "[::1]", "localhost", "fe80::1%", "fe80::1%a%b",
];
for (const address of invalid) {
assert.equal(isExternalMcpHttpIpAddress(address), false, JSON.stringify(address));
assert.equal(isExternalMcpHttpIpAddress(address), isIP(address) !== 0, JSON.stringify(address));
}
});
test("HTTP client URL stays on loopback unless a specific listen address is set", () => {
assert.equal(DEFAULT_EXTERNAL_MCP_HTTP_PORT, security.DEFAULT_EXTERNAL_MCP_HTTP_PORT);
assert.equal(
+29
View File
@@ -3,6 +3,35 @@ export const DEFAULT_EXTERNAL_MCP_HTTP_PORT = 47391;
export const DEFAULT_EXTERNAL_MCP_HTTP_HOST = "127.0.0.1";
export const EXTERNAL_MCP_HTTP_PATH = "/mcp";
function isIpv4Address(value: string): boolean {
const parts = value.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
return parts !== null && parts.slice(1).every(
(part) => Number(part) <= 255 && String(Number(part)) === part,
);
}
export function isExternalMcpHttpIpAddress(value: string): boolean {
if (isIpv4Address(value)) return true;
const [literal, zone, ...extraZones] = value.split("%");
if (extraZones.length || (zone !== undefined && !/^[0-9a-zA-Z.:-]+$/.test(zone))) return false;
if (!literal.includes(":")) return false;
let address = literal;
if (address.includes(".")) {
const lastColon = address.lastIndexOf(":");
if (!isIpv4Address(address.slice(lastColon + 1))) return false;
// An embedded IPv4 tail occupies two IPv6 groups.
address = `${address.slice(0, lastColon + 1)}0:0`;
}
const halves = address.split("::");
if (halves.length > 2) return false;
const groups = halves.flatMap((half) => half ? half.split(":") : []);
if (!groups.every((group) => /^[0-9a-fA-F]{1,4}$/.test(group))) return false;
return halves.length === 2 ? groups.length < 8 : groups.length === 8;
}
function formatHostForUrl(host: string): string {
if (host.includes(":") && !host.startsWith("[")) return `[${host}]`;
return host;
+49
View File
@@ -7,7 +7,9 @@ import {
isPaneMagnificationSelectionValid,
resolvePaneMagnificationCandidate,
resolvePaneMagnificationStyle,
resolveMagnifiedChromeBorderWidth,
resolveTwoPaneMagnificationStyle,
snapCssRectToDevicePixels,
type PaneMagnificationController,
} from './paneMagnification.ts';
@@ -90,6 +92,53 @@ test('magnification overlays the original layout without changing its rect', ()
});
});
test('magnified chrome uses a 2px accent stroke only below 1.5 device pixels', () => {
assert.equal(resolveMagnifiedChromeBorderWidth(1), 2);
assert.equal(resolveMagnifiedChromeBorderWidth(1.2), 2);
assert.equal(resolveMagnifiedChromeBorderWidth(1.49), 2);
assert.equal(resolveMagnifiedChromeBorderWidth(1.5), 1);
assert.equal(resolveMagnifiedChromeBorderWidth(2), 1);
assert.equal(resolveMagnifiedChromeBorderWidth(0), 1);
});
test('magnified surface bounds snap to the device-pixel grid after the 12px inset', () => {
const original = { left: '0px', top: '0px', width: '100px', height: '100px' };
// Integer CSS pixels at 1x stay unchanged (existing contract).
assert.deepEqual(resolvePaneMagnificationStyle(original, true, {
left: 120,
top: 80,
width: 1400,
height: 900,
}, 1), {
position: 'fixed',
left: '132px',
top: '92px',
width: '1376px',
height: '876px',
zIndex: 50,
});
// 120.4+12=132.4 at 2x -> 264.8 rounds to 265 -> 132.5
// right: 120.4+1400-12=1508.4 at 2x -> 3016.8 rounds to 3017 -> 1508.5
const snapped = resolvePaneMagnificationStyle(original, true, {
left: 120.4,
top: 80.4,
width: 1400,
height: 900,
}, 2);
assert.deepEqual(snapped, {
position: 'fixed',
left: '132.5px',
top: '92.5px',
width: '1376px',
height: '876px',
zIndex: 50,
});
const rect = snapCssRectToDevicePixels(10.2, 20.2, 110.2, 80.2, 2);
assert.deepEqual(rect, { left: 10, top: 20, width: 100, height: 60 });
});
test('two-pane magnification keeps the dormant pane geometry unchanged', () => {
assert.deepEqual(resolveTwoPaneMagnificationStyle('left', true, true), {
left: '12px', top: '12px', width: 'calc(100% - 24px)', height: 'calc(100% - 24px)', zIndex: 50,
+37 -4
View File
@@ -92,19 +92,52 @@ export function getPaneMagnificationShortcutLabel(
return (hotkeyScheme === 'mac' ? binding?.mac : binding?.pc)?.replace(/ \+ /g, '+') ?? '';
}
export function resolveMagnifiedChromeBorderWidth(devicePixelRatio = 1): number {
return devicePixelRatio > 0 && devicePixelRatio < 1.5 ? 2 : 1;
}
export function snapCssRectToDevicePixels(
left: number,
top: number,
right: number,
bottom: number,
devicePixelRatio = 1,
): { left: number; top: number; width: number; height: number } {
const dpr = devicePixelRatio > 0 ? devicePixelRatio : 1;
const snap = (value: number) => Math.round(value * dpr) / dpr;
const snappedLeft = snap(left);
const snappedTop = snap(top);
const snappedRight = snap(right);
const snappedBottom = snap(bottom);
return {
left: snappedLeft,
top: snappedTop,
width: Math.max(0, snappedRight - snappedLeft),
height: Math.max(0, snappedBottom - snappedTop),
};
}
export function resolvePaneMagnificationStyle(
original: React.CSSProperties,
magnified: boolean,
surfaceBounds?: { left: number; top: number; width: number; height: number } | null,
devicePixelRatio = 1,
): React.CSSProperties {
if (!magnified) return original;
if (surfaceBounds) {
const snapped = snapCssRectToDevicePixels(
surfaceBounds.left + 12,
surfaceBounds.top + 12,
surfaceBounds.left + surfaceBounds.width - 12,
surfaceBounds.top + surfaceBounds.height - 12,
devicePixelRatio,
);
return {
position: 'fixed',
left: `${surfaceBounds.left + 12}px`,
top: `${surfaceBounds.top + 12}px`,
width: `${Math.max(0, surfaceBounds.width - 24)}px`,
height: `${Math.max(0, surfaceBounds.height - 24)}px`,
left: `${snapped.left}px`,
top: `${snapped.top}px`,
width: `${snapped.width}px`,
height: `${snapped.height}px`,
zIndex: 50,
};
}
+136
View File
@@ -64,6 +64,41 @@ test("settings search catalog has unique ids", () => {
assert.equal(new Set(ids).size, ids.length);
});
test("newly indexed gated settings retain visible parent destinations in search", () => {
const fallbacks = {
"terminal-hibernate-hidden-tabs-delay": "terminal-hibernate-hidden-tabs",
"terminal-hibernate-skip-alt-screen": "terminal-hibernate-hidden-tabs",
"terminal-hibernate-keep-renderer-count": "terminal-hibernate-hidden-tabs",
"terminal-hibernate-replay-chunk-bytes": "terminal-hibernate-hidden-tabs",
"terminal-hibernate-prefer-wasm-serialize": "terminal-hibernate-hidden-tabs",
"terminal-inline-images-kitty": "terminal-inline-images-enabled",
"terminal-inline-images-sixel": "terminal-inline-images-enabled",
"terminal-inline-images-iip": "terminal-inline-images-enabled",
"terminal-inline-images-storage-limit": "terminal-inline-images-enabled",
"terminal-inline-images-max-megapixels": "terminal-inline-images-enabled",
"terminal-inline-images-sequence-limit": "terminal-inline-images-enabled",
"terminal-host-info-bar-title-mode": "terminal-host-info-bar-show",
"terminal-server-stats-refresh-interval": "terminal-server-stats-show",
"ai-web-search-api-key": "ai-web-search-provider",
"system-network-proxy-url": "system-network-proxy-mode",
"system-network-proxy-bypass": "system-network-proxy-mode",
"system-app-lock-timeout": "system-app-lock",
};
const hits = filterSettingsSearchCatalog("", (key) => en[key] ?? key, { limit: 500 });
for (const [id, fallbackId] of Object.entries(fallbacks)) {
const entry = hits.find((hit) => hit.entry.id === id)?.entry;
assert.ok(entry, id);
assert.equal(entry.fallbackAnchorId, fallbackId, id);
const parent = SETTINGS_SEARCH_CATALOG.find((candidate) => candidate.id === fallbackId);
assert.ok(parent, fallbackId);
assert.equal(parent.tab, entry.tab, id);
assert.equal(parent.aiSubTab, entry.aiSubTab, id);
assert.equal(parent.fallbackAnchorId, undefined, fallbackId);
}
// The local start-directory row is always mounted in this UI.
assert.equal(hits.find((hit) => hit.entry.id === "terminal-local-shell-start-dir")?.entry.fallbackAnchorId, undefined);
});
test("filterSettingsSearchCatalog matches English labels", () => {
const hits = filterSettingsSearchCatalog("copy on select", tEn);
assert.ok(hits.some((hit) => hit.entry.id === "terminal-copy-on-select"));
@@ -125,6 +160,107 @@ test("settings search finds App Lock from the zh-CN locale", () => {
assert.ok(hits.some((hit) => hit.entry.id === "system-app-lock"));
});
test("settings search finds folder compression from the real locales", () => {
const tZhReal = (key: string) => zhCN[key] ?? key;
const tEnReal = (key: string) => en[key] ?? key;
for (const [t, queries] of [
[tZhReal, ["压缩", "普通传输"]],
[tEnReal, ["compress", "tar"]],
] as const) {
for (const query of queries) {
const hits = filterSettingsSearchCatalog(query, t);
assert.ok(hits.some((hit) => hit.entry.id === "sftp-compressed-upload"), query);
}
}
});
test("settings search finds skip unchanged files from the real locales", () => {
const tZhReal = (key: string) => zhCN[key] ?? key;
const tEnReal = (key: string) => en[key] ?? key;
for (const [t, queries] of [
[tZhReal, ["跳过未改文件", "修改时间"]],
[tEnReal, ["skip unchanged", "rsync"]],
] as const) {
for (const query of queries) {
const hits = filterSettingsSearchCatalog(query, t);
assert.ok(hits.some((hit) => hit.entry.id === "sftp-skip-unchanged"), query);
}
}
});
test("settings search finds SSH connection keep-alive from the real locales", () => {
const tZhReal = (key: string) => zhCN[key] ?? key;
const tEnReal = (key: string) => en[key] ?? key;
for (const [t, queries] of [
[tZhReal, ["保活时间", "重新认证"]],
[tEnReal, ["keep-alive", "re-authentication"]],
] as const) {
for (const query of queries) {
const hits = filterSettingsSearchCatalog(query, t);
assert.ok(hits.some((hit) => hit.entry.id === "sftp-transport-idle-ttl"), query);
}
}
});
test("settings search finds note typography from the real locales", () => {
const tZhReal = (key: string) => zhCN[key] ?? key;
const tEnReal = (key: string) => en[key] ?? key;
for (const [id, zhQuery, enQuery] of [
["appearance-vault-notes-font", "代码字体", "code font"],
["appearance-vault-notes-font-size", "笔记字号", "note font size"],
["appearance-vault-notes-code-font-size", "代码字号", "code font size"],
] as const) {
for (const [t, query] of [[tZhReal, zhQuery], [tEnReal, enQuery]] as const) {
const hit = filterSettingsSearchCatalog(query, t).find((hit) => hit.entry.id === id);
assert.ok(hit, `${query} should find ${id}`);
assert.equal(hit.entry.tab, "appearance");
}
}
});
test("settings search finds session log options from the real locales", () => {
const tZhReal = (key: string) => zhCN[key] ?? key;
const tEnReal = (key: string) => en[key] ?? key;
for (const [id, t, queries] of [
["system-session-logs-directory", tZhReal, ["保存目录"]],
["system-session-logs-directory", tEnReal, ["save directory"]],
["system-session-logs-format", tZhReal, ["日志格式"]],
["system-session-logs-format", tEnReal, ["log format"]],
["system-session-logs-timestamps", tZhReal, ["时间戳"]],
["system-session-logs-timestamps", tEnReal, ["timestamp", "Add timestamps"]],
] as const) {
for (const query of queries) {
const hit = filterSettingsSearchCatalog(query, t).find((hit) => hit.entry.id === id);
assert.ok(hit, `${query} should find ${id}`);
assert.equal(hit.entry.tab, "system");
assert.equal(hit.entry.sectionKey, "settings.sessionLogs.title");
}
}
});
test("later-added settings retain their tab and sub-tab destinations", () => {
const tZhReal = (key: string) => zhCN[key] ?? key;
const tEnReal = (key: string) => en[key] ?? key;
for (const [id, tab, subTab, labelKey] of [
["terminal-font-ligatures", "terminal", undefined, "settings.terminal.font.ligatures"],
["terminal-local-shell-side-panel-auto-open", "terminal", undefined, "settings.terminal.localShellSidePanel.autoOpen"],
["terminal-system-manager-process-refresh-interval", "terminal", undefined, "settings.terminal.systemManager.processRefreshInterval"],
["ai-chat-history-message-cap", "ai", "tools", "ai.chatHistory.messageCap"],
["ai-web-search-max-results", "ai", "search", "ai.webSearch.maxResults"],
["ai-safety-max-iterations", "ai", "safety", "ai.safety.maxIterations"],
["sync-ai-sessions", "sync", "status", "cloudSync.aiSessions.title"],
["system-network-proxy-url", "system", undefined, "settings.system.networkProxy.url"],
] as const) {
for (const t of [tZhReal, tEnReal]) {
assert.notEqual(t(labelKey), labelKey);
const hit = filterSettingsSearchCatalog(t(labelKey), t).find((hit) => hit.entry.id === id);
assert.ok(hit, `${t(labelKey)} should find ${id}`);
assert.equal(hit.entry.tab, tab);
assert.equal(hit.entry.aiSubTab ?? hit.entry.syncSubTab, subTab);
}
}
});
test("settings search finds temporary network device mode", () => {
const tEnReal = (key: string) => en[key] ?? key;
const tZhTW = (key: string) => zhTW[key] ?? key;
+2 -2
View File
@@ -24,7 +24,7 @@ function collectSourceFiles(root: string): string[] {
return out;
}
test("every settings search catalog id is wired as an anchor in components", () => {
test("every settings search catalog id and fallback is wired as an anchor in components", () => {
const roots = [
join(process.cwd(), "components"),
];
@@ -32,7 +32,7 @@ test("every settings search catalog id is wired as an anchor in components", ()
const haystack = sources.map((file) => readFileSync(file, "utf8")).join("\n");
const missing = SETTINGS_SEARCH_CATALOG
.map((entry) => entry.id)
.flatMap((entry) => [entry.id, ...(entry.fallbackAnchorId ? [entry.fallbackAnchorId] : [])])
.filter((id) => {
const asProp = `anchorId="${id}"`;
const asPropSingle = `anchorId='${id}'`;
+462
View File
@@ -36,6 +36,11 @@ export type SettingsPlatform = "mac" | "win" | "linux";
export type SettingsSearchEntry = {
/** Stable id; also used as `data-settings-anchor` on the target element. */
id: string;
/**
* Already-mounted parent to highlight when a prerequisite setting is off and
* this entry's own anchor is not in the DOM.
*/
fallbackAnchorId?: string;
tab: SettingsTabId;
/** Nested AI settings tab when `tab === "ai"`. */
aiSubTab?: AISettingsSubTabId;
@@ -214,6 +219,27 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
descriptionKey: "settings.vault.autoImportSystemKnownHostsDesc",
sectionKey: "settings.vault.title",
},
{
id: "appearance-vault-notes-font",
tab: "appearance",
labelKey: "settings.vault.notesFont",
descriptionKey: "settings.vault.notesFontDesc",
sectionKey: "settings.vault.title",
},
{
id: "appearance-vault-notes-font-size",
tab: "appearance",
labelKey: "settings.vault.notesFontSize",
descriptionKey: "settings.vault.notesFontSizeDesc",
sectionKey: "settings.vault.title",
},
{
id: "appearance-vault-notes-code-font-size",
tab: "appearance",
labelKey: "settings.vault.notesCodeFontSize",
descriptionKey: "settings.vault.notesCodeFontSizeDesc",
sectionKey: "settings.vault.title",
},
{
id: "appearance-custom-css",
tab: "appearance",
@@ -273,6 +299,13 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
descriptionKey: "settings.terminal.font.smoothing.desc",
sectionKey: "settings.terminal.section.font",
},
{
id: "terminal-font-ligatures",
tab: "terminal",
labelKey: "settings.terminal.font.ligatures",
descriptionKey: "settings.terminal.font.ligatures.desc",
sectionKey: "settings.terminal.section.font",
},
{
id: "terminal-font-line-padding",
tab: "terminal",
@@ -366,6 +399,20 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
descriptionKey: "settings.terminal.behavior.rightClick.desc",
sectionKey: "settings.terminal.section.behavior",
},
{
id: "terminal-right-click-long-press-menu",
tab: "terminal",
labelKey: "settings.terminal.behavior.rightClick.longPressMenu",
descriptionKey: "settings.terminal.behavior.rightClick.longPressMenu.desc",
sectionKey: "settings.terminal.section.behavior",
},
{
id: "terminal-right-click-fullscreen-menu",
tab: "terminal",
labelKey: "settings.terminal.behavior.rightClick.fullscreenMenu",
descriptionKey: "settings.terminal.behavior.rightClick.fullscreenMenu.desc",
sectionKey: "settings.terminal.section.behavior",
},
{
id: "terminal-copy-on-select",
tab: "terminal",
@@ -415,6 +462,13 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
descriptionKey: "settings.terminal.behavior.confirmMultilinePaste.desc",
sectionKey: "settings.terminal.section.behavior",
},
{
id: "terminal-confirm-multiline-paste-min-lines",
tab: "terminal",
labelKey: "settings.terminal.behavior.confirmMultilinePasteMinLines",
descriptionKey: "settings.terminal.behavior.confirmMultilinePasteMinLines.desc",
sectionKey: "settings.terminal.section.behavior",
},
{
id: "terminal-shift-enter-newline",
tab: "terminal",
@@ -422,6 +476,13 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
descriptionKey: "settings.terminal.behavior.shiftEnterNewline.desc",
sectionKey: "settings.terminal.section.behavior",
},
{
id: "terminal-shift-enter-newline-text",
tab: "terminal",
labelKey: "settings.terminal.behavior.shiftEnterNewlineText",
descriptionKey: "settings.terminal.behavior.shiftEnterNewlineText.desc",
sectionKey: "settings.terminal.section.behavior",
},
{
id: "terminal-shift-enter-force-text",
tab: "terminal",
@@ -443,6 +504,20 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
descriptionKey: "settings.terminal.behavior.clearWipesScrollback.desc",
sectionKey: "settings.terminal.section.behavior",
},
{
id: "terminal-preserve-selection-on-input",
tab: "terminal",
labelKey: "settings.terminal.behavior.preserveSelectionOnInput",
descriptionKey: "settings.terminal.behavior.preserveSelectionOnInput.desc",
sectionKey: "settings.terminal.section.behavior",
},
{
id: "terminal-force-prompt-new-line",
tab: "terminal",
labelKey: "settings.terminal.behavior.forcePromptNewLine",
descriptionKey: "settings.terminal.behavior.forcePromptNewLine.desc",
sectionKey: "settings.terminal.section.behavior",
},
{
id: "terminal-tab-double-click",
tab: "terminal",
@@ -472,6 +547,55 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
descriptionKey: "settings.terminal.behavior.osc52Clipboard.desc",
sectionKey: "settings.terminal.section.behavior",
},
{
id: "terminal-scroll-on-input",
tab: "terminal",
labelKey: "settings.terminal.behavior.scrollOnInput",
descriptionKey: "settings.terminal.behavior.scrollOnInput.desc",
sectionKey: "settings.terminal.section.behavior",
},
{
id: "terminal-scroll-on-output",
tab: "terminal",
labelKey: "settings.terminal.behavior.scrollOnOutput",
descriptionKey: "settings.terminal.behavior.scrollOnOutput.desc",
sectionKey: "settings.terminal.section.behavior",
},
{
id: "terminal-scroll-on-key-press",
tab: "terminal",
labelKey: "settings.terminal.behavior.scrollOnKeyPress",
descriptionKey: "settings.terminal.behavior.scrollOnKeyPress.desc",
sectionKey: "settings.terminal.section.behavior",
},
{
id: "terminal-scroll-on-paste",
tab: "terminal",
labelKey: "settings.terminal.behavior.scrollOnPaste",
descriptionKey: "settings.terminal.behavior.scrollOnPaste.desc",
sectionKey: "settings.terminal.section.behavior",
},
{
id: "terminal-smooth-scrolling",
tab: "terminal",
labelKey: "settings.terminal.behavior.smoothScrolling",
descriptionKey: "settings.terminal.behavior.smoothScrolling.desc",
sectionKey: "settings.terminal.section.behavior",
},
{
id: "terminal-link-browser",
tab: "terminal",
labelKey: "settings.terminal.behavior.linkBrowser",
descriptionKey: "settings.terminal.behavior.linkBrowser.desc",
sectionKey: "settings.terminal.section.behavior",
},
{
id: "terminal-link-modifier",
tab: "terminal",
labelKey: "settings.terminal.behavior.linkModifier",
descriptionKey: "settings.terminal.behavior.linkModifier.desc",
sectionKey: "settings.terminal.section.behavior",
},
{
id: "terminal-scrollback-rows",
tab: "terminal",
@@ -493,6 +617,27 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
descriptionKey: "settings.terminal.sidePanel.autoOpen.desc",
sectionKey: "settings.terminal.section.sidePanel",
},
{
id: "terminal-side-panel-auto-open-pane",
tab: "terminal",
labelKey: "settings.terminal.sidePanel.autoOpenPane",
descriptionKey: "settings.terminal.sidePanel.autoOpenPane.desc",
sectionKey: "settings.terminal.section.sidePanel",
},
{
id: "terminal-local-shell-side-panel-auto-open",
tab: "terminal",
labelKey: "settings.terminal.localShellSidePanel.autoOpen",
descriptionKey: "settings.terminal.localShellSidePanel.autoOpen.desc",
sectionKey: "settings.terminal.section.localShellSidePanel",
},
{
id: "terminal-local-shell-side-panel-auto-open-pane",
tab: "terminal",
labelKey: "settings.terminal.localShellSidePanel.autoOpenPane",
descriptionKey: "settings.terminal.localShellSidePanel.autoOpenPane.desc",
sectionKey: "settings.terminal.section.localShellSidePanel",
},
{
id: "terminal-keyword-highlight",
tab: "terminal",
@@ -507,6 +652,13 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
descriptionKey: "settings.terminal.localShell.shell.desc",
sectionKey: "settings.terminal.section.localShell",
},
{
id: "terminal-local-shell-start-dir",
tab: "terminal",
labelKey: "settings.terminal.localShell.startDir",
descriptionKey: "settings.terminal.localShell.startDir.desc",
sectionKey: "settings.terminal.section.localShell",
},
{
id: "terminal-default-proxy",
tab: "terminal",
@@ -552,6 +704,13 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
descriptionKey: "settings.terminal.connection.keepaliveInterval.desc",
sectionKey: "settings.terminal.section.connection",
},
{
id: "terminal-keepalive-count-max",
tab: "terminal",
labelKey: "settings.terminal.connection.keepaliveCountMax",
descriptionKey: "settings.terminal.connection.keepaliveCountMax.desc",
sectionKey: "settings.terminal.section.connection",
},
{
id: "terminal-x11-display",
tab: "terminal",
@@ -560,6 +719,21 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
sectionKey: "settings.terminal.section.connection",
keywords: ["x11", "display"],
},
{
id: "terminal-host-info-bar-show",
tab: "terminal",
labelKey: "settings.terminal.hostInfoBar.show",
descriptionKey: "settings.terminal.hostInfoBar.show.desc",
sectionKey: "settings.terminal.section.serverStats",
},
{
id: "terminal-host-info-bar-title-mode",
fallbackAnchorId: "terminal-host-info-bar-show",
tab: "terminal",
labelKey: "settings.terminal.hostInfoBar.titleMode",
descriptionKey: "settings.terminal.hostInfoBar.titleMode.desc",
sectionKey: "settings.terminal.section.serverStats",
},
{
id: "terminal-server-stats-show",
tab: "terminal",
@@ -567,6 +741,42 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
descriptionKey: "settings.terminal.serverStats.show.desc",
sectionKey: "settings.terminal.section.serverStats",
},
{
id: "terminal-server-stats-refresh-interval",
fallbackAnchorId: "terminal-server-stats-show",
tab: "terminal",
labelKey: "settings.terminal.serverStats.refreshInterval",
descriptionKey: "settings.terminal.serverStats.refreshInterval.desc",
sectionKey: "settings.terminal.section.serverStats",
},
{
id: "terminal-system-manager-process-refresh-interval",
tab: "terminal",
labelKey: "settings.terminal.systemManager.processRefreshInterval",
descriptionKey: "settings.terminal.systemManager.processRefreshInterval.desc",
sectionKey: "settings.terminal.section.systemManager",
},
{
id: "terminal-system-manager-tmux-refresh-interval",
tab: "terminal",
labelKey: "settings.terminal.systemManager.tmuxRefreshInterval",
descriptionKey: "settings.terminal.systemManager.tmuxRefreshInterval.desc",
sectionKey: "settings.terminal.section.systemManager",
},
{
id: "terminal-system-manager-docker-list-refresh-interval",
tab: "terminal",
labelKey: "settings.terminal.systemManager.dockerListRefreshInterval",
descriptionKey: "settings.terminal.systemManager.dockerListRefreshInterval.desc",
sectionKey: "settings.terminal.section.systemManager",
},
{
id: "terminal-system-manager-docker-stats-refresh-interval",
tab: "terminal",
labelKey: "settings.terminal.systemManager.dockerStatsRefreshInterval",
descriptionKey: "settings.terminal.systemManager.dockerStatsRefreshInterval.desc",
sectionKey: "settings.terminal.section.systemManager",
},
{
id: "terminal-renderer",
tab: "terminal",
@@ -575,6 +785,53 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
sectionKey: "settings.terminal.section.rendering",
keywords: ["webgl", "canvas"],
},
{
id: "terminal-hibernate-hidden-tabs",
tab: "terminal",
labelKey: "settings.terminal.rendering.hibernateHiddenTabs",
descriptionKey: "settings.terminal.rendering.hibernateHiddenTabs.desc",
sectionKey: "settings.terminal.section.rendering",
},
{
id: "terminal-hibernate-hidden-tabs-delay",
fallbackAnchorId: "terminal-hibernate-hidden-tabs",
tab: "terminal",
labelKey: "settings.terminal.rendering.hibernateHiddenTabsDelay",
descriptionKey: "settings.terminal.rendering.hibernateHiddenTabsDelay.desc",
sectionKey: "settings.terminal.section.rendering",
},
{
id: "terminal-hibernate-skip-alt-screen",
fallbackAnchorId: "terminal-hibernate-hidden-tabs",
tab: "terminal",
labelKey: "settings.terminal.rendering.hibernateSkipAltScreen",
descriptionKey: "settings.terminal.rendering.hibernateSkipAltScreen.desc",
sectionKey: "settings.terminal.section.rendering",
},
{
id: "terminal-hibernate-keep-renderer-count",
fallbackAnchorId: "terminal-hibernate-hidden-tabs",
tab: "terminal",
labelKey: "settings.terminal.rendering.hibernateKeepRendererCount",
descriptionKey: "settings.terminal.rendering.hibernateKeepRendererCount.desc",
sectionKey: "settings.terminal.section.rendering",
},
{
id: "terminal-hibernate-replay-chunk-bytes",
fallbackAnchorId: "terminal-hibernate-hidden-tabs",
tab: "terminal",
labelKey: "settings.terminal.rendering.hibernateReplayChunkBytes",
descriptionKey: "settings.terminal.rendering.hibernateReplayChunkBytes.desc",
sectionKey: "settings.terminal.section.rendering",
},
{
id: "terminal-hibernate-prefer-wasm-serialize",
fallbackAnchorId: "terminal-hibernate-hidden-tabs",
tab: "terminal",
labelKey: "settings.terminal.rendering.hibernatePreferWasmSerialize",
descriptionKey: "settings.terminal.rendering.hibernatePreferWasmSerialize.desc",
sectionKey: "settings.terminal.section.rendering",
},
{
id: "terminal-inline-images-enabled",
tab: "terminal",
@@ -583,6 +840,54 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
sectionKey: "settings.terminal.section.inlineImages",
keywords: ["sixel", "kitty", "iip"],
},
{
id: "terminal-inline-images-kitty",
fallbackAnchorId: "terminal-inline-images-enabled",
tab: "terminal",
labelKey: "settings.terminal.inlineImages.kitty",
descriptionKey: "settings.terminal.inlineImages.kitty.desc",
sectionKey: "settings.terminal.section.inlineImages",
},
{
id: "terminal-inline-images-sixel",
fallbackAnchorId: "terminal-inline-images-enabled",
tab: "terminal",
labelKey: "settings.terminal.inlineImages.sixel",
descriptionKey: "settings.terminal.inlineImages.sixel.desc",
sectionKey: "settings.terminal.section.inlineImages",
},
{
id: "terminal-inline-images-iip",
fallbackAnchorId: "terminal-inline-images-enabled",
tab: "terminal",
labelKey: "settings.terminal.inlineImages.iip",
descriptionKey: "settings.terminal.inlineImages.iip.desc",
sectionKey: "settings.terminal.section.inlineImages",
},
{
id: "terminal-inline-images-storage-limit",
fallbackAnchorId: "terminal-inline-images-enabled",
tab: "terminal",
labelKey: "settings.terminal.inlineImages.storageLimit",
descriptionKey: "settings.terminal.inlineImages.storageLimit.desc",
sectionKey: "settings.terminal.section.inlineImages",
},
{
id: "terminal-inline-images-max-megapixels",
fallbackAnchorId: "terminal-inline-images-enabled",
tab: "terminal",
labelKey: "settings.terminal.inlineImages.maxMegapixels",
descriptionKey: "settings.terminal.inlineImages.maxMegapixels.desc",
sectionKey: "settings.terminal.section.inlineImages",
},
{
id: "terminal-inline-images-sequence-limit",
fallbackAnchorId: "terminal-inline-images-enabled",
tab: "terminal",
labelKey: "settings.terminal.inlineImages.sequenceLimit",
descriptionKey: "settings.terminal.inlineImages.sequenceLimit.desc",
sectionKey: "settings.terminal.section.inlineImages",
},
{
id: "terminal-workspace-focus-style",
tab: "terminal",
@@ -598,6 +903,27 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
sectionKey: "settings.terminal.section.autocomplete",
keywords: ["completion", "补全"],
},
{
id: "terminal-autocomplete-ghost-text",
tab: "terminal",
labelKey: "settings.terminal.autocomplete.ghostText",
descriptionKey: "settings.terminal.autocomplete.ghostText.desc",
sectionKey: "settings.terminal.section.autocomplete",
},
{
id: "terminal-autocomplete-popup-menu",
tab: "terminal",
labelKey: "settings.terminal.autocomplete.popupMenu",
descriptionKey: "settings.terminal.autocomplete.popupMenu.desc",
sectionKey: "settings.terminal.section.autocomplete",
},
{
id: "terminal-autocomplete-history-scope",
tab: "terminal",
labelKey: "settings.terminal.autocomplete.historyScope",
descriptionKey: "settings.terminal.autocomplete.historyScope.desc",
sectionKey: "settings.terminal.section.autocomplete",
},
{
id: "terminal-password-prompt-assist",
tab: "terminal",
@@ -671,6 +997,13 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
descriptionKey: "settings.sftp.autoSync.enableDesc",
sectionKey: "settings.sftp.autoSync",
},
{
id: "sftp-compressed-upload",
tab: "file-associations",
labelKey: "settings.sftp.compressedUpload.enable",
descriptionKey: "settings.sftp.compressedUpload.enableDesc",
sectionKey: "settings.sftp.compressedUpload",
},
{
id: "sftp-follow-terminal-cwd",
tab: "file-associations",
@@ -691,6 +1024,20 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
labelKey: "settings.sftp.transferConcurrency",
descriptionKey: "settings.sftp.transferConcurrency.desc",
},
{
id: "sftp-skip-unchanged",
tab: "file-associations",
labelKey: "settings.sftp.skipUnchanged.enable",
descriptionKey: "settings.sftp.skipUnchanged.enableDesc",
sectionKey: "settings.sftp.transferConcurrency",
},
{
id: "sftp-transport-idle-ttl",
tab: "file-associations",
labelKey: "settings.ssh.transportIdleTtl",
descriptionKey: "settings.ssh.transportIdleTtl.desc",
sectionKey: "settings.sftp.transferConcurrency",
},
{
id: "sftp-default-opener",
tab: "file-associations",
@@ -758,6 +1105,13 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
labelKey: "ai.defaultAgent",
descriptionKey: "ai.defaultAgent.description",
},
{
id: "ai-privacy",
tab: "ai",
aiSubTab: "tools",
labelKey: "ai.privacy.title",
descriptionKey: "ai.privacy.description",
},
{
id: "ai-chat-shortcuts-selection",
tab: "ai",
@@ -798,6 +1152,29 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
sectionKey: "ai.externalMcp.title",
keywords: ["notification", "approval", "dock"],
},
{
id: "ai-chat-history-message-cap",
tab: "ai",
aiSubTab: "tools",
labelKey: "ai.chatHistory.messageCap",
descriptionKey: "ai.chatHistory.messageCap.description",
sectionKey: "ai.chatHistory.title",
},
{
id: "ai-external-mcp-behavior",
tab: "ai",
aiSubTab: "tools",
labelKey: "ai.toolSettings.behavior",
sectionKey: "ai.externalMcp.title",
},
{
id: "ai-external-mcp-client-configuration",
tab: "ai",
aiSubTab: "tools",
labelKey: "ai.externalMcp.clientConfiguration",
descriptionKey: "ai.externalMcp.clientConfiguration.description",
sectionKey: "ai.externalMcp.title",
},
{
id: "ai-user-skills",
tab: "ai",
@@ -829,6 +1206,31 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
descriptionKey: "ai.webSearch.provider.description",
sectionKey: "ai.webSearch.title",
},
{
id: "ai-web-search-api-key",
fallbackAnchorId: "ai-web-search-provider",
tab: "ai",
aiSubTab: "search",
labelKey: "ai.webSearch.apiKey",
descriptionKey: "ai.webSearch.apiKey.description",
sectionKey: "ai.webSearch.title",
},
{
id: "ai-web-search-api-host",
tab: "ai",
aiSubTab: "search",
labelKey: "ai.webSearch.apiHost",
descriptionKey: "ai.webSearch.apiHost.description",
sectionKey: "ai.webSearch.title",
},
{
id: "ai-web-search-max-results",
tab: "ai",
aiSubTab: "search",
labelKey: "ai.webSearch.maxResults",
descriptionKey: "ai.webSearch.maxResults.description",
sectionKey: "ai.webSearch.title",
},
{
id: "ai-safety-permission-mode",
tab: "ai",
@@ -855,6 +1257,14 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
sectionKey: "ai.safety.title",
keywords: ["response", "request", "idle", "timeout", "响应", "请求", "超时"],
},
{
id: "ai-safety-max-iterations",
tab: "ai",
aiSubTab: "safety",
labelKey: "ai.safety.maxIterations",
descriptionKey: "ai.safety.maxIterations.description",
sectionKey: "ai.safety.title",
},
{
id: "ai-safety-blocklist",
tab: "ai",
@@ -894,6 +1304,13 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
labelKey: "cloudSync.strategy.title",
descriptionKey: "cloudSync.strategy.desc",
},
{
id: "sync-ai-sessions",
tab: "sync",
syncSubTab: "status",
labelKey: "cloudSync.aiSessions.title",
descriptionKey: "cloudSync.aiSessions.desc",
},
{
id: "sync-local-backups",
tab: "sync",
@@ -941,6 +1358,22 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
sectionKey: "settings.system.networkProxy.title",
keywords: ["proxy", "http", "代理"],
},
{
id: "system-network-proxy-url",
fallbackAnchorId: "system-network-proxy-mode",
tab: "system",
labelKey: "settings.system.networkProxy.url",
descriptionKey: "settings.system.networkProxy.url.desc",
sectionKey: "settings.system.networkProxy.title",
},
{
id: "system-network-proxy-bypass",
fallbackAnchorId: "system-network-proxy-mode",
tab: "system",
labelKey: "settings.system.networkProxy.bypass",
descriptionKey: "settings.system.networkProxy.bypass.desc",
sectionKey: "settings.system.networkProxy.title",
},
{
id: "system-app-lock",
tab: "system",
@@ -948,6 +1381,14 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
descriptionKey: "settings.appLock.description",
keywords: ["app lock", "applock", "lock", "应用锁", "锁屏", "idle", "timeout", "无操作"],
},
{
id: "system-app-lock-timeout",
fallbackAnchorId: "system-app-lock",
tab: "system",
labelKey: "settings.appLock.timeout",
descriptionKey: "settings.appLock.timeoutDesc",
sectionKey: "settings.appLock.title",
},
{
id: "system-credentials",
tab: "system",
@@ -996,6 +1437,27 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
descriptionKey: "settings.sessionLogs.enableAutoSaveDesc",
sectionKey: "settings.sessionLogs.title",
},
{
id: "system-session-logs-directory",
tab: "system",
labelKey: "settings.sessionLogs.directory",
descriptionKey: "settings.sessionLogs.directoryHint",
sectionKey: "settings.sessionLogs.title",
},
{
id: "system-session-logs-format",
tab: "system",
labelKey: "settings.sessionLogs.format",
descriptionKey: "settings.sessionLogs.formatDesc",
sectionKey: "settings.sessionLogs.title",
},
{
id: "system-session-logs-timestamps",
tab: "system",
labelKey: "settings.sessionLogs.timestamps",
descriptionKey: "settings.sessionLogs.timestampsDesc",
sectionKey: "settings.sessionLogs.title",
},
{
id: "system-ssh-deep-link",
tab: "system",
+13
View File
@@ -0,0 +1,13 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import type { TransferTask } from './models';
import { getGlobalTransferBatchEligibility, listGloballyPausableTransferIds } from './sftpTransferActions';
test('a partially failed folder pause can be retried or explicitly resumed', () => {
const task = { id: 'folder', status: 'pausing', isDirectory: true, resumable: true,
pauseUnavailableReason: 'This transfer cannot be paused yet' } as TransferTask;
assert.equal(getGlobalTransferBatchEligibility([task]).pausableCount, 1);
assert.equal(getGlobalTransferBatchEligibility([task]).resumableCount, 1);
assert.deepEqual(listGloballyPausableTransferIds([task]), ['folder']);
assert.equal(getGlobalTransferBatchEligibility([{ ...task, pauseUnavailableReason: undefined }]).pausableCount, 0);
});
+2 -1
View File
@@ -5,7 +5,8 @@ export function getGlobalTransferBatchEligibility(tasks: readonly TransferTask[]
return {
cancellableCount: listGloballyCancellableTransferIds(tasks).length,
pausableCount: topLevel.filter((task) => (
["pending", "queued", "transferring"].includes(task.status)
(["pending", "queued", "transferring"].includes(task.status)
|| (task.status === "pausing" && !!task.pauseUnavailableReason))
&& task.resumable !== false
&& !(task.ownerId === "dedicated-resume" && task.reconnectRequired)
)).length,
+20
View File
@@ -0,0 +1,20 @@
const fs = require("node:fs");
const path = require("node:path");
function configureAppProfile(app, devServerUrl) {
const unpackaged = !app.isPackaged;
const isDev = unpackaged && Boolean(devServerUrl);
if (unpackaged) {
// Keep the existing development profile path for both Vite and dist.
app.setName("Netcatty Dev");
const devProfile = path.join(app.getPath("userData"), "dev");
fs.mkdirSync(devProfile, { recursive: true });
app.setPath("userData", devProfile);
// Chromium's Local Storage, IndexedDB and other session state must
// follow the profile even if Electron has already resolved sessionData.
app.setPath("sessionData", devProfile);
}
return { isDev, effectiveDevServerUrl: isDev ? devServerUrl : undefined };
}
module.exports = { configureAppProfile };
+51
View File
@@ -0,0 +1,51 @@
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 { configureAppProfile } = require("./appProfile.cjs");
function fakeApp(t, isPackaged) {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-profile-"));
t.after(() => fs.rmSync(tmp, { recursive: true, force: true }));
const production = path.join(tmp, "netcatty");
const paths = { userData: production, sessionData: production };
const app = {
isPackaged,
name: "Netcatty",
setName(name) { this.name = name; },
getPath(name) { return paths[name]; },
setPath(name, value) {
assert.ok(fs.statSync(value).isDirectory());
paths[name] = value;
},
};
return { app, paths, production };
}
test("unpackaged dist launches isolate both application and Chromium state", (t) => {
const { app, paths, production } = fakeApp(t, false);
assert.deepEqual(configureAppProfile(app, undefined), {
isDev: false, effectiveDevServerUrl: undefined,
});
const dev = path.join(production, "dev");
assert.deepEqual(paths, { userData: dev, sessionData: dev });
assert.equal(app.name, "Netcatty Dev");
});
test("Vite launches keep the development profile and URL", (t) => {
const { app, paths, production } = fakeApp(t, false);
const url = "http://localhost:5173";
assert.deepEqual(configureAppProfile(app, url), { isDev: true, effectiveDevServerUrl: url });
const dev = path.join(production, "dev");
assert.deepEqual(paths, { userData: dev, sessionData: dev });
});
test("packaged launches keep their data paths and ignore a Vite URL", (t) => {
const { app, paths, production } = fakeApp(t, true);
assert.deepEqual(configureAppProfile(app, "http://localhost:5173"), {
isDev: false, effectiveDevServerUrl: undefined,
});
assert.deepEqual(paths, { userData: production, sessionData: production });
assert.equal(app.name, "Netcatty");
});
+37 -6
View File
@@ -27,6 +27,7 @@ const {
stripAnsi,
} = require("./ptyExecHelpers.cjs");
const { extractTrailingIdlePrompt } = require("./shellUtils.cjs");
const { READINESS_UNKNOWN, SHELL_READINESS_UNKNOWN_MESSAGE } = require("./shellReadinessState.cjs");
const { getSessionSnapshot } = require("../terminalInterruptDiagnostics.cjs");
const { createJobStartupDiag } = require("./jobStartupDiagnostics.cjs");
@@ -70,6 +71,7 @@ function startPtyJob(ptyStream, command, options) {
sessionId = null,
diagnosticsSession = null,
getReadyPrompt,
classifyReadiness,
beforeInput,
promptWaitTimeoutMs = 30000,
typedInput = false,
@@ -85,6 +87,30 @@ function startPtyJob(ptyStream, command, options) {
let readinessFailureCode = null;
let waitingForInputGuard = typeof beforeInput === "function";
// #4195: an empty prompt at the bounded wait deadline is resolved into a
// PROVEN-busy hard block (unchanged) or an honest, actionable `unknown`.
// A missing/ambiguous classifier always fails closed to busy, so #4110's
// false-ready guards and legacy callers without classifyReadiness keep the
// exact SHELL_NOT_READY behavior. `unknown` NEVER sends the queued command.
function resolveUnreadyOutcome() {
if (typeof classifyReadiness !== "function") return "busy";
try {
return classifyReadiness() === "unknown" ? "unknown" : "busy";
} catch {
return "busy";
}
}
function finishUnready(busyMessage) {
if (resolveUnreadyOutcome() === "unknown") {
readinessFailureCode = READINESS_UNKNOWN;
finish("", -1, SHELL_READINESS_UNKNOWN_MESSAGE);
} else {
readinessFailureCode = "SHELL_NOT_READY";
finish("", -1, busyMessage);
}
}
const marker = `__NCMCP_${Date.now().toString(36)}_${crypto.randomBytes(16).toString('hex')}__`;
let resolvedShellKind = resolveEffectiveShellKind(shellKind, expectedPrompt, {
loginShellHint,
@@ -203,10 +229,12 @@ function startPtyJob(ptyStream, command, options) {
wallTimeoutId = setTimeout(() => {
if (finished) return;
if (waitingForPrompt || waitingForInputGuard) {
readinessFailureCode = waitingForPrompt ? "SHELL_NOT_READY" : "EXECUTION_NOT_AUTHORIZED";
finish("", -1, waitingForPrompt
? "Shell prompt is not ready; no command was sent"
: "Execution authorization timed out; no command was sent");
if (waitingForPrompt) {
finishUnready("Shell prompt is not ready; no command was sent");
} else {
readinessFailureCode = "EXECUTION_NOT_AUTHORIZED";
finish("", -1, "Execution authorization timed out; no command was sent");
}
return;
}
if (pendingEnd) {
@@ -1017,8 +1045,10 @@ function startPtyJob(ptyStream, command, options) {
return;
}
if (Date.now() >= deadline) {
readinessFailureCode = "SHELL_NOT_READY";
finish("", -1, "Shell prompt is not ready (startup, busy program, pending input, or unrecognized prompt); no command was sent");
// Same bounded 30s budget, unchanged. Only the *verdict* differs:
// proven-busy stays a hard block; an unrecognized prompt on a live
// shell becomes an honest, non-terminal, actionable `unknown`.
finishUnready("Shell prompt is not ready (startup, busy program, pending input, or unrecognized prompt); no command was sent");
return;
}
readinessTimer = setTimeout(checkReady, Math.min(50, deadline - Date.now()));
@@ -1062,6 +1092,7 @@ function startPtyJob(ptyStream, command, options) {
* @param {AbortSignal} [options.abortSignal] - AbortSignal to cancel execution
* @param {string} [options.expectedPrompt] - Last observed idle prompt for exact fallback matching
* @param {() => string} [options.getReadyPrompt] - Read current prompt; wait without writing until non-empty
* @param {() => "busy"|"unknown"} [options.classifyReadiness] - At the bounded wait deadline, classify an empty prompt as PROVEN busy (hard SHELL_NOT_READY) or an honest actionable `unknown` (SHELL_READINESS_UNKNOWN). Absent/ambiguous ⇒ busy (fail closed). Never sends the command for `unknown`.
* @param {function} [options.beforeInput] - Revalidate authorization before the first PTY byte (may return a promise)
* @param {number} [options.promptWaitTimeoutMs=30000] - Bounded pre-input wait (maximum 30 seconds)
* @param {boolean} [options.typedInput=false] - Emit synthetic command echo before execution
@@ -281,6 +281,26 @@ test('wall deadline during authorization reports authorization failure rather th
assert.deepEqual(pty.writes, []);
});
test('idle Enter-PSSession remoting prompt allows the command to be sent', async () => {
const pty = new TestPty();
const session = { _promptTrackTail: '', lastIdlePrompt: '' };
const prompt = '[192.168.1.10]: PS C:\\Users\\Administrator\\Documents> ';
trackSessionIdlePrompt(session, `PowerShell 7\r\n${prompt}`);
assert.equal(readyPrompt(session), prompt);
const result = await startPtyJob(pty, 'Write-Output ok', {
shellKind: 'powershell',
getReadyPrompt: () => readyPrompt(session),
promptWaitTimeoutMs: 200,
timeoutMs: 1000,
typedInput: true,
}).resultPromise;
assert.equal(result.ok, true);
assert.equal(result.stdout, 'OK');
assert.equal(pty.writes.length, 1);
assert.match(pty.writes[0], /\$__NCMCP_/);
});
test('idle PowerShell whose raw tail was CSI-erased still receives the command', async (t) => {
t.mock.timers.enable({ apis: ['Date', 'setTimeout'] });
const pty = new TestPty();
@@ -0,0 +1,280 @@
"use strict";
const test = require("node:test");
const assert = require("node:assert/strict");
const { EventEmitter } = require("node:events");
const { startPtyJob } = require("./ptyExec.cjs");
const {
trackSessionIdlePrompt,
getFreshIdlePrompt,
getVisibleIdlePrompt,
} = require("./shellUtils.cjs");
const {
READINESS_UNKNOWN,
SHELL_READINESS_UNKNOWN_MESSAGE,
classifyShellReadiness,
} = require("./shellReadinessState.cjs");
const {
formatTerminalExecuteMcpResponse,
} = require("../../capabilities/codegen/mcpToolRegistry.cjs");
const { MODEL_DESCRIPTION_HINTS } = require("../../capabilities/schemas/toolInputs.cjs");
function readyPrompt(session) {
return getFreshIdlePrompt(session) || getVisibleIdlePrompt(session);
}
function makeSession(extra = {}) {
return { _promptTrackTail: "", lastIdlePrompt: "", ...extra };
}
// Records every byte written to the PTY; echoes a completion marker so a
// genuinely-executed command resolves ok:true (same seam as
// ptyExec.readiness.test.cjs).
class TestPty extends EventEmitter {
writes = [];
write(data) {
this.writes.push(String(data));
const marker = String(data).match(/(__NCMCP_[a-z0-9]+_[0-9a-f]+__)/i)?.[1];
if (marker) queueMicrotask(() => this.emit("data", `${marker}_S\nOK\n${marker}_E:0\n`));
}
}
const UNKNOWN_PROMPT = "Last login: Mon\r\nstarship-custom-prompt─❯ ";
const SHORT_BUDGET = { promptWaitTimeoutMs: 30, timeoutMs: 2000 };
// ---------------------------------------------------------------------------
// classifier unit: PROVEN busy stays hard, whitelist miss on a live shell is
// an honest unknown. These are the #4110 false-ready guards we must not weaken.
// ---------------------------------------------------------------------------
test("classifyShellReadiness: proven-busy OSC 133 / pending-input / task / transport stay busy", () => {
assert.equal(classifyShellReadiness(makeSession({ osc133Ready: false })), "busy"); // C/D
assert.equal(classifyShellReadiness(makeSession({ _osc133PromptRedrawPending: true })), "busy");
assert.equal(classifyShellReadiness(makeSession({ _osc133PromptContinued: true })), "busy");
assert.equal(classifyShellReadiness(makeSession({ osc133Ready: true, _osc133PromptLine: 3 })), "busy"); // B cursor deviation
assert.equal(classifyShellReadiness(makeSession({ waitingForInput: true })), "busy");
assert.equal(classifyShellReadiness(makeSession({ busy: true })), "busy");
assert.equal(classifyShellReadiness(makeSession({ status: "disconnected" })), "busy");
assert.equal(classifyShellReadiness(makeSession(), { taskInFlight: true }), "busy");
assert.equal(classifyShellReadiness(makeSession(), { transportAlive: false }), "busy");
assert.equal(classifyShellReadiness(null), "busy"); // fail closed
});
test("classifyShellReadiness: unrecognized prompt on a live shell is unknown (not ready, not busy)", () => {
const session = makeSession();
trackSessionIdlePrompt(session, UNKNOWN_PROMPT);
assert.equal(readyPrompt(session), ""); // genuine whitelist miss
assert.equal(classifyShellReadiness(session), "unknown");
// A-only marker with no C/D and no B confirmation is still unknown (no busy evidence).
assert.equal(classifyShellReadiness(makeSession({ osc133Ready: true, _osc133PromptLine: null })), "unknown");
});
test("classifyShellReadiness: credential prompts remain hard busy (#4195)", () => {
for (const line of ["Password:", "[sudo] password for alice: ", "Enter passphrase for key '/root/.ssh/id_rsa': ", "PIN: ", "Sorry, try again."]) {
const session = makeSession({ _promptTrackTail: line });
assert.equal(readyPrompt(session), "", line);
assert.equal(classifyShellReadiness(session), "busy", line);
}
});
// ---------------------------------------------------------------------------
// gating trichotomy end-to-end — EVERY case asserts PTY bytes written.
// ---------------------------------------------------------------------------
test("ready (whitelist match) → command sent, unchanged", async () => {
const pty = new TestPty();
const prompt = "user@host:~$ ";
const result = await startPtyJob(pty, "echo OK", {
shellKind: "posix",
getReadyPrompt: () => prompt,
classifyReadiness: () => "unknown", // never consulted when a prompt is recognized
...SHORT_BUDGET,
}).resultPromise;
assert.equal(result.ok, true);
assert.equal(pty.writes.length, 1);
});
test("ready (OSC 133 A with empty input) → command sent, unchanged (#4110)", async () => {
const pty = new TestPty();
const session = makeSession();
trackSessionIdlePrompt(session, "\x1b]133;A\x07\x1b[38;5;39m~/src\x1b[0m \x1b[38;5;213m❯\x1b[0m ");
assert.equal(readyPrompt(session), "~/src ❯ ");
const result = await startPtyJob(pty, "echo OK", {
shellKind: "posix",
getReadyPrompt: () => readyPrompt(session),
classifyReadiness: () => classifyShellReadiness(session),
...SHORT_BUDGET,
}).resultPromise;
assert.equal(result.ok, true);
assert.equal(pty.writes.length, 1);
});
test("PROVEN busy (OSC 133 C/D) → hard SHELL_NOT_READY, ZERO bytes written (#4110 guard)", async () => {
const pty = new TestPty();
const session = makeSession();
trackSessionIdlePrompt(session, "\x1b]133;A\x07PS C:\\Users\\alice> ");
assert.equal(readyPrompt(session), "PS C:\\Users\\alice> ");
trackSessionIdlePrompt(session, "\x1b]133;C\x07build running...\r\nPS C:\\Users\\alice> ");
assert.equal(readyPrompt(session), "");
assert.equal(classifyShellReadiness(session), "busy");
const result = await startPtyJob(pty, "echo OK", {
shellKind: "powershell",
getReadyPrompt: () => readyPrompt(session),
classifyReadiness: () => classifyShellReadiness(session),
...SHORT_BUDGET,
}).resultPromise;
assert.equal(result.code, "SHELL_NOT_READY");
assert.deepEqual(pty.writes, []);
});
test("PROVEN busy (pending-input / our task / disconnected) → hard block, ZERO bytes written", async () => {
for (const extra of [
{ _osc133PromptContinued: true },
{ _osc133PromptRedrawPending: true },
{ waitingForInput: true },
{ busy: true },
{ status: "disconnected" },
]) {
const pty = new TestPty();
const session = makeSession(extra);
trackSessionIdlePrompt(session, UNKNOWN_PROMPT);
assert.equal(readyPrompt(session), "");
const result = await startPtyJob(pty, "echo OK", {
shellKind: "posix",
getReadyPrompt: () => readyPrompt(session),
classifyReadiness: () => classifyShellReadiness(session),
...SHORT_BUDGET,
}).resultPromise;
assert.equal(result.code, "SHELL_NOT_READY", JSON.stringify(extra));
assert.deepEqual(pty.writes, [], JSON.stringify(extra));
}
});
test("unknown (unrecognized prompt, live shell, no busy evidence): command NOT sent, actionable NON-fatal result", async () => {
const pty = new TestPty();
const session = makeSession();
trackSessionIdlePrompt(session, UNKNOWN_PROMPT);
assert.equal(readyPrompt(session), "");
assert.equal(classifyShellReadiness(session), "unknown");
const result = await startPtyJob(pty, "echo OK", {
shellKind: "posix",
getReadyPrompt: () => readyPrompt(session),
classifyReadiness: () => classifyShellReadiness(session),
...SHORT_BUDGET,
}).resultPromise;
assert.equal(result.code, READINESS_UNKNOWN);
assert.equal(result.ok, false); // NOT a lie of success
assert.equal(result.error, SHELL_READINESS_UNKNOWN_MESSAGE);
assert.match(result.error, /connection is alive/i);
assert.match(result.error, /could not be recognized/i);
assert.match(result.error, /NOT sent/i);
assert.match(result.error, /read-only/i);
assert.match(result.error, /get_environment|terminal_read_context/);
assert.deepEqual(pty.writes, []); // no blind typing
});
test("unknown keeps the same bounded wait (no early send, no early verdict)", async () => {
const pty = new TestPty();
let prompt = "";
const job = startPtyJob(pty, "echo OK", {
shellKind: "posix",
getReadyPrompt: () => prompt,
classifyReadiness: () => "unknown",
promptWaitTimeoutMs: 80,
timeoutMs: 2000,
});
await new Promise((resolve) => setTimeout(resolve, 20));
assert.deepEqual(pty.writes, []); // still waiting at the bounded budget
const result = await job.resultPromise;
assert.equal(result.code, READINESS_UNKNOWN);
assert.deepEqual(pty.writes, []);
});
test("unknown is recoverable: a recognized prompt (user pressed Enter) lets the next exec succeed", async () => {
const pty = new TestPty();
let prompt = "";
const first = await startPtyJob(pty, "echo OK", {
shellKind: "posix",
getReadyPrompt: () => prompt,
classifyReadiness: () => "unknown",
...SHORT_BUDGET,
}).resultPromise;
assert.equal(first.code, READINESS_UNKNOWN);
assert.deepEqual(pty.writes, []); // first exec never bricked the session
prompt = "user@host:~$ ";
const second = await startPtyJob(pty, "echo OK", {
shellKind: "posix",
getReadyPrompt: () => prompt,
classifyReadiness: () => "unknown",
...SHORT_BUDGET,
}).resultPromise;
assert.equal(second.ok, true);
assert.equal(pty.writes.length, 1);
});
test("Password: remains hard not-ready, ZERO bytes written (#4195 correct behavior)", async () => {
const pty = new TestPty();
const session = makeSession();
trackSessionIdlePrompt(session, "Password:");
assert.equal(readyPrompt(session), "");
assert.equal(classifyShellReadiness(session), "busy");
const result = await startPtyJob(pty, "echo OK", {
shellKind: "posix",
getReadyPrompt: () => readyPrompt(session),
classifyReadiness: () => classifyShellReadiness(session),
...SHORT_BUDGET,
}).resultPromise;
assert.equal(result.code, "SHELL_NOT_READY");
assert.deepEqual(pty.writes, []);
});
test("legacy callers without classifyReadiness keep the exact hard SHELL_NOT_READY block", async () => {
const pty = new TestPty();
const result = await startPtyJob(pty, "echo OK", {
getReadyPrompt: () => "",
...SHORT_BUDGET,
}).resultPromise;
assert.equal(result.code, "SHELL_NOT_READY");
assert.deepEqual(pty.writes, []);
});
test("a throwing / ambiguous classifier fails closed to busy (never a false ready)", async () => {
const pty = new TestPty();
const result = await startPtyJob(pty, "echo OK", {
getReadyPrompt: () => "",
classifyReadiness: () => { throw new Error("inspection blew up"); },
...SHORT_BUDGET,
}).resultPromise;
assert.equal(result.code, "SHELL_NOT_READY");
assert.deepEqual(pty.writes, []);
});
// ---------------------------------------------------------------------------
// agent-visible surfaces: MCP tool result + tool description.
// ---------------------------------------------------------------------------
test("MCP terminal_execute surfaces unknown as a NON-fatal, actionable result (not isError)", () => {
const unknownResult = {
ok: false,
error: SHELL_READINESS_UNKNOWN_MESSAGE,
code: READINESS_UNKNOWN,
exitCode: -1,
stdout: "",
stderr: "",
};
const formatted = formatTerminalExecuteMcpResponse(unknownResult);
assert.notEqual(formatted.isError, true); // THE fix: agent does not see a terminal error
assert.match(formatted.content[0].text, /read-only/i);
assert.match(formatted.content[0].text, /NOT sent/i);
assert.match(formatted.content[0].text, /get_environment|terminal_read_context/);
// Control: a proven-busy verdict is still a hard error.
const busy = formatTerminalExecuteMcpResponse({ ...unknownResult, code: "SHELL_NOT_READY", error: "Shell prompt is not ready; no command was sent" });
assert.equal(busy.isError, true);
});
test("terminal_execute tool description documents the unknown outcome and the read-only/confirm path", () => {
const description = MODEL_DESCRIPTION_HINTS["terminal.execute"] || "";
assert.match(description, /SHELL_READINESS_UNKNOWN/);
assert.match(description, /NOT sent/);
assert.match(description, /read-only/);
assert.match(description, /get_environment|terminal_read_context/);
assert.match(description, /ask the user to confirm/);
});
+106
View File
@@ -0,0 +1,106 @@
"use strict";
/**
* First-class shell readiness classification for the pre-input gate in
* startPtyJob. This composes #4110's OSC 133 marker authority and #4195's
* asymmetric-harm thesis: a whitelist miss on a live shell must be an
* actionable `unknown`, never a terminal SHELL_NOT_READY — but anything
* PROVEN busy (or a credential prompt waiting for the user's secret) must
* stay a hard block. It mirrors #3935's honesty rule: `unknown` is NOT a lie
* of success and is never claimed as ready.
*
* This module only READS session state. It never writes to a PTY, never
* injects OSC markers, and never widens tool scope. It lives outside
* shellUtils.cjs (the prompt whitelist) on purpose so the gating consumer
* evolves independently of positive-signal additions such as #4197.
*/
const { stripAnsi } = require("./shellUtils.cjs");
/** Distinct, non-terminal code emitted when the gate cannot prove busy. */
const READINESS_UNKNOWN = "SHELL_READINESS_UNKNOWN";
/**
* Honest, actionable result text. Surfaced verbatim as the exec result
* `error` and as the MCP/Catty tool-result text. It must never claim ready.
* (a) connection alive + no busy signal, (b) prompt unrecognized,
* (c) command NOT sent / no blind typing, (d) the viable read-only path.
*/
const SHELL_READINESS_UNKNOWN_MESSAGE = [
"Shell readiness unknown (SHELL_READINESS_UNKNOWN): the terminal connection is",
"alive and no busy, pending-input, or credential-prompt signal was observed, but",
"the prompt could not be recognized (custom theme, colored/starship/root prompt,",
"or continuation). The command was NOT sent — never blind-type into a possible",
"password prompt, editor, or half-typed command. This is a recoverable,",
"non-terminal state, not a failed command. Read-only next steps: call",
"get_environment or terminal_read_context to inspect the visible buffer, re-check",
"readiness after the user presses Enter or a recognized prompt appears, reuse",
"another idle session, or ask the user to confirm the prompt before retrying.",
"Retrying once the prompt is recognized is safe.",
].join(" ");
// Known credential/passphrase prompts. #4195: `Password:` (and friends) are
// PROVEN "waiting for secret input" states and MUST remain hard not-ready.
// This is a conservative block-list (hardening only): a miss falls through to
// `unknown`, which still never types.
const BLOCKING_INPUT_PATTERNS = [
/^(?:\[sudo\]\s*|enter\s+|please\s+enter\s+)?(?:password|passphrase|pin)(?:\s+for\s+[^:]+)?\s*:?\s*$/i,
/^sorry,\s*try\s+again\.?\s*$/i,
];
function lastVisibleLine(session) {
const tail = typeof session?._promptTrackTail === "string" ? session._promptTrackTail : "";
if (!tail) return "";
const lines = stripAnsi(tail).split(/[\r\n]/);
for (let i = lines.length - 1; i >= 0; i -= 1) {
const line = lines[i].trim();
if (line) return line;
}
return "";
}
/**
* Classify a session whose getReadyPrompt() just returned empty (i.e. no
* whitelist match and no OSC 133 A-with-empty-input ready signal).
*
* Returns:
* "busy" — PROVEN busy → keep the hard SHELL_NOT_READY block unchanged.
* "unknown" — connection alive, no proven-busy evidence, prompt not
* recognized → actionable, non-terminal outcome.
*
* Anything ambiguous (missing session, thrown helper, unknown context) fails
* CLOSED to "busy", so #4110's false-ready guards are never weakened.
*/
function classifyShellReadiness(session, context = {}) {
if (!session) return "busy";
const { taskInFlight = false, transportAlive = true } = context || {};
// Our own tracked task in flight / a dead transport are proven busy and are
// also hard-blocked at the exec call sites (reserveSessionExecution,
// writability check) and by the PTY close/error handlers.
if (taskInFlight || !transportAlive) return "busy";
// #4110: an OSC 133 C/D marker establishes a running command/output
// lifecycle. shellUtils.cjs:321 sets osc133Ready=false; getFreshIdlePrompt
// (:377) and getVisibleIdlePrompt (:406) both return "" for that state.
if (session.osc133Ready === false) return "busy";
// #4110 pending-input guards (shellUtils.cjs:265-275): redraw latch,
// continuation/PS2, and B-marker cursor deviation. An empty prompt while
// osc133Ready===true with a B-marked line means matchesOsc133EmptyPrompt
// rejected it → the user typed into the prompt line.
if (session._osc133PromptRedrawPending) return "busy";
if (session._osc133PromptContinued) return "busy";
if (session.osc133Ready === true && session._osc133PromptLine != null) return "busy";
// Explicit busy / waiting-for-input session state (#3935 recovery model:
// sessionRecoveryService.cjs:55-56, 101-102).
if (session.waitingForInput === true || session.busy === true) return "busy";
if (session.status === "disconnected" || session.status === "stopped") return "busy";
// Credential prompt waiting for the user's secret (#4195).
const line = lastVisibleLine(session);
if (line && BLOCKING_INPUT_PATTERNS.some((pattern) => pattern.test(line))) return "busy";
// Connection alive, no proven-busy evidence, prompt not recognized.
return "unknown";
}
module.exports = {
READINESS_UNKNOWN,
SHELL_READINESS_UNKNOWN_MESSAGE,
classifyShellReadiness,
};
+9 -3
View File
@@ -50,11 +50,12 @@ function formatSyntheticEcho(command) {
}
// Default PowerShell prompt (e.g. `PS C:\Users\alice>`, `PS>`,
// `PS /home/alice>`). Anchored so command output that merely starts with
// `PS` (e.g. `PSO>`) doesn't match. The `\S` after `\s+` rejects literal
// `PS /home/alice>`), with optional Enter-PSSession / remoting `[host]: `
// and debug `[DBG]: ` prefixes. Anchored so command output that merely
// starts with `PS` (e.g. `PSO>`) doesn't match. The `\S` after `\s+` rejects literal
// `"PS >"` (which the default prompt never emits) so a script that prints
// such a line can't trick prompt-driven shell-kind selection.
const POWERSHELL_PROMPT_PATTERN = /^PS(?:\s+\S.*)?>$/;
const POWERSHELL_PROMPT_PATTERN = /^(?:\[[^\]\r\n]+\]: )*PS(?:\s+\S.*)?>$/;
// Default cmd.exe prompt (e.g. `C:\>`, `C:\Users\alice>`, `D:\data>`).
// Drive letter + optional path + `>`. Rejects `C: >` (space before `>`) and
@@ -69,6 +70,10 @@ const CMD_PROMPT_PATTERN = /^[A-Za-z]:(?:\\[^<>"|]*)?>$/;
// the final `]` before `$`/`#` is the delimiter.
const POSIX_PROMPT_PATTERN = /^(?:[^\s@]+@[^\s:]+(?::[^\n\r]*)?|\[[^\s@\]]+@[^\s\]:]+(?:\s+[^\n\r]+)?\])[#$]$/;
// Bracket PS1 without @host, with bash `\t` time: `[\u \t \w]$` -> `[root 12:04:23 ~]$` (#4276).
// Require HH:MM:SS so loose `[word]$` output cannot count as idle.
const BRACKET_TIME_POSIX_PROMPT_PATTERN = /^\[[^\s@\]]+\s+\d{2}:\d{2}:\d{2}(?:\s+[^\n\r\]]+)?\][#$]$/;
// Space-separated bash PS1 `\u@\h \w $ ` renders as `user@host ~ $`.
// macOS ships zsh with `%n@%m %1~ %#`, which renders as
// `user@host ~ %` / `user@host My Project %`; privileged shells end in `#`.
@@ -136,6 +141,7 @@ function isDefaultPosixPromptLine(line) {
const withoutEnvPrefix = normalized.replace(/^\([^()\n\r]+\)\s+/, "");
return (
POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) ||
BRACKET_TIME_POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) ||
PAREN_POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) ||
ALPINE_PROMPT_PATTERN.test(withoutEnvPrefix) ||
ZSH_PROMPT_PATTERN.test(withoutEnvPrefix) ||
+79
View File
@@ -112,6 +112,46 @@ test("isDefaultPowerShellPromptLine matches default shapes and rejects look-alik
assert.equal(isDefaultPowerShellPromptLine(null), false);
});
test("PowerShell prompt helpers recognize remoting and debug prefixes", () => {
for (const prompt of [
"[192.168.1.10]: PS C:\\Users\\Administrator\\Documents>",
"[SERVER01]: PS C:\\>",
"[host.example.com]: PS C:\\Windows\\System32>",
"[fe80::1]: PS C:\\>",
"[DBG]: PS C:\\Users\\alice>",
"[SERVER01]: [DBG]: PS C:\\>",
]) {
assert.equal(isDefaultPowerShellPromptLine(prompt), true, prompt);
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${prompt}`), prompt, prompt);
}
});
test("PowerShell prompt helpers reject malformed remoting prefixes and look-alikes", () => {
for (const line of [
"[host] PS C:\\>",
"prefix [host]: PS C:\\>",
"[]: PS C:\\>",
"[ho]st]: PS C:\\>",
"[ho\rst]: PS C:\\>",
"[ho\nst]: PS C:\\>",
"[host]:PS C:\\>",
"[host]: PS >",
"PS >",
"PSO>",
"ZIPS>",
"",
null,
]) {
assert.equal(isDefaultPowerShellPromptLine(line), false, String(line));
assert.equal(extractTrailingIdlePrompt(line), "", String(line));
}
});
test("extractTrailingIdlePrompt preserves trailing space on a remoting prompt", () => {
const prompt = "[192.168.1.10]: PS C:\\Users\\Administrator\\Documents> ";
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${prompt}`), prompt);
});
test("extracts a trailing cmd.exe idle prompt", () => {
// Windows OpenSSH default shell is cmd.exe; without capturing `C:\...>`
// AI exec cannot select the cmd wrapper when shellKind is still unset.
@@ -152,6 +192,30 @@ test("isDefaultPosixPromptLine matches classic user@host prompts", () => {
assert.equal(isDefaultPosixPromptLine(""), false);
});
test("recognizes bracketed time prompts without a hostname and preserves trailing space", () => {
for (const prompt of [
"[root 12:04:23 ~]$",
"[root 12:04:23 ~]$ ",
"[alice 00:00:00 /var/log]# ",
"[alice-admin 23:59:59 ~/src]$ ",
]) {
assert.equal(isDefaultPosixPromptLine(prompt), true, prompt);
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${prompt}`), prompt, prompt);
}
});
test("bracketed time prompt recognition rejects pending input and prompts without time", () => {
for (const line of [
"[root 12:04:23 ~]$ hostname",
"[root 12:04:23 ~]$ echo $",
"[root ~]$",
"[word]$",
]) {
assert.equal(isDefaultPosixPromptLine(line), false, line);
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${line}`), "", line);
}
});
test("recognizes space-separated Bash idle prompts and preserves trailing whitespace", () => {
for (const prompt of [
"root@VM-Q7L4M8P2 ~ $",
@@ -448,6 +512,13 @@ test("extracts a trailing RHEL-family bracketed idle prompt", () => {
assert.equal(extractTrailingIdlePrompt("welcome\r\nroot@host ~#"), "");
});
test("extractTrailingIdlePrompt recognizes an ANSI-colored bracketed time prompt", () => {
assert.equal(
extractTrailingIdlePrompt("welcome\r\n[\x1b[1;34mroot \x1b[1;36m12:04:23 \x1b[1;32m~\x1b[0m]$ "),
"[root 12:04:23 ~]$ ",
);
});
test("extractTrailingIdlePrompt recognizes a two-line user@host then bare $/# PS1", () => {
// export PS1="\u@\h: \w\n$ " paints the host line, then a lone "$ ".
// The cached prompt must keep both lines so a lone "$" cannot satisfy endsWith.
@@ -1193,6 +1264,14 @@ test("trackSessionIdlePrompt and getFreshIdlePrompt accept an Oracle/RHEL bracke
assert.equal(getFreshIdlePrompt(bracketedPath), "[user@host My [Project]]$ ");
});
test("trackSessionIdlePrompt and getFreshIdlePrompt accept a bracketed time prompt", () => {
const session = {};
const prompt = "[root 12:04:23 ~]$ ";
assert.equal(trackSessionIdlePrompt(session, `Last login...\r\n${prompt}`), prompt);
assert.equal(session.lastIdlePrompt, prompt);
assert.equal(getFreshIdlePrompt(session), prompt);
});
test("visible idle prompt survives a PSReadLine erase that leaves the raw tail dirty", () => {
// PSReadLine echoes the pending-input clear prefix (`ggd2147483647d` / `i`),
// then homes the cursor and erases those keys with CSI. stripAnsi drops the
@@ -4,6 +4,7 @@
// (based in electron/bridges/). Requiring here keeps the path unambiguous.
const { emitTerminalSessionData } = require("../emitTerminalSessionData.cjs");
const { formatSyntheticEcho, getVisibleIdlePrompt } = require("../ai/shellUtils.cjs");
const { classifyShellReadiness } = require("../ai/shellReadinessState.cjs");
const { clearSessionFlowState } = require("../terminalFlowAck.cjs");
const { remoteDisallowsExecChannelProbe, sessionDisallowsExtraSshChannel, ensureSessionShellKindForExec } = require("../ai/sessionShellKind.cjs");
const defaultAiPrivacyService = require("../../shared/aiPrivacyService.cjs");
@@ -227,6 +228,7 @@ function registerCattyExecHandlers(ctx) {
expectedPrompt: getFreshIdlePrompt(session),
getReadyPrompt: typeof session._promptTrackTail === "string"
? () => getFreshIdlePrompt(session) || getVisibleIdlePrompt(session) : undefined,
classifyReadiness: () => classifyShellReadiness(session),
typedInput: true,
echoCommand: (rawCommand) => {
const contents = electronModule?.webContents?.fromId?.(session.webContentsId);
@@ -254,19 +254,25 @@ function buildCodebuddyQueryOptions({
elicitation, canUseTool,
}) {
const builtinTools = codebuddyBuiltinTools(toolIntegrationMode);
const mcpMode = builtinTools.length === 0;
const mcpServers = toSdkMcpServers(injectedMcpServers);
if (mcpMode) {
// These are only the app-managed servers. Show their tools directly without
// enabling the CLI’s general-purpose discovery tools.
for (const server of Object.values(mcpServers)) {
if (server.type !== "sdk") server.defer_loading = false;
}
}
const options = {
cwd,
includePartialMessages: true,
permissionMode: "bypassPermissions",
allowDangerouslySkipPermissions: true,
extraArgs: { "dangerously-skip-permissions": null },
mcpServers: toSdkMcpServers(injectedMcpServers),
mcpServers,
...(mcpMode ? { strictMcpConfig: true } : {}),
// Keep unrelated CLI built-ins disabled by default, including future tools.
tools: builtinTools,
// `tools` is the built-in tool whitelist. In mcp mode it is [], so CodeBuddy
// built-ins stay disabled while injected Netcatty MCP tools remain visible.
// Do not mirror that empty list into allowedTools: the SDK treats
// allowedTools as an auto-approval list, and allowedTools: [] prevents MCP
// tool calls from running under bypassPermissions.
disallowedTools: [...UI_DISALLOWED_TOOLS],
// Keep the SDK isolated from user/project settings so local hooks, plugins,
// or extra MCP servers cannot expand Netcatty's controlled tool boundary.
@@ -60,14 +60,38 @@ test("buildCodebuddyQueryOptions wires SDK options in isolated mode", () => {
assert.equal(opts.abortController, ac);
assert.equal(opts.resume, "sess-1");
assert.deepEqual(opts.tools, []);
// allowedTools must stay unset in mcp mode: tools:[] disables built-ins, while
// allowedTools:[] would prevent injected Netcatty MCP tools from running.
assert.ok(!("allowedTools" in opts));
assert.equal(opts.strictMcpConfig, true);
assert.equal(opts.mcpServers["netcatty-remote-hosts"].defer_loading, false);
assert.ok(opts.disallowedTools.includes("AskUserQuestion"));
assert.equal(opts.mcpServers["netcatty-remote-hosts"].type, "stdio");
assert.deepEqual(opts.mcpServers["netcatty-remote-hosts"].env, { NETCATTY_MCP_PORT: "1" });
});
test("mcp and default mode allow only the app-managed MCP configuration", () => {
for (const toolIntegrationMode of ["mcp", undefined]) {
const opts = buildCodebuddyQueryOptions({
toolIntegrationMode,
injectedMcpServers: [{ name: "netcatty", command: "/abs/electron" }],
});
assert.deepEqual(opts.tools, []);
assert.ok(!("allowedTools" in opts));
assert.deepEqual(opts.settingSources, []);
assert.equal(opts.strictMcpConfig, true);
assert.equal(opts.mcpServers.netcatty.command, "/abs/electron");
assert.equal(opts.mcpServers.netcatty.defer_loading, false);
}
});
test("skills mode keeps the Bash whitelist and UI exclusions", () => {
const opts = buildCodebuddyQueryOptions({ toolIntegrationMode: "skills" });
assert.deepEqual(opts.tools, ["Bash"]);
assert.deepEqual(opts.disallowedTools, ["AskUserQuestion"]);
assert.ok(!opts.disallowedTools.includes("Bash"));
assert.ok(!("allowedTools" in opts));
});
test("built-in tools are mode-aware", () => {
assert.deepEqual(codebuddyBuiltinTools("mcp"), []);
assert.deepEqual(codebuddyBuiltinTools(undefined), []);
Loaded 100 of 162 files, more files were not shown because too many files have changed in this diff. Show more