Compare commits

...
Author SHA1 Message Date
binaricat 69015c7cf2 feat(settings): measure local AI history on demand 2026-12-03 17:26:44 +08:00
e6d3047d0a fix(ai): 识别 Kali 两行提示符并清洗 zle 键盘模式转义序列 (#4637)
* fix(ai): recognize Kali two-line prompts and strip zle keypad escapes

Kali's default bash/zsh prompt (┌──(user㉿host)-[path] / └─$) was never
treated as idle, so AI and MCP terminal execution could not detect a
ready shell on Kali hosts.

- Match the Kali host line, including bash/zsh chroot and venv groups,
  paired only with a └─$/└─# marker line. Accept the optional zsh
  RPROMPT exit-code (⨯) and background-job (⚙) indicators.
- stripAnsi now also removes short escapes such as ESC = / ESC > emitted
  by zle after every prompt; previously the leftover "=" kept zsh prompts
  from ever matching.

Verified against bytes captured from a Kali 2026.2 host (zsh and bash)
and via External MCP on a local test build.

* fix(ai): classify nested Kali prompts as POSIX and strip control strings whole

- isPosixPrompt now also accepts the Kali two-line prompt, so a Windows
  OpenSSH session with a cmd/PowerShell login hint that enters Kali (e.g.
  via WSL) gets the POSIX wrapper instead of a Windows one.
- stripAnsi removes DCS/SOS/PM/APC strings as a unit; previously only the
  introducer and ST were dropped, leaving the payload as visible text that
  could pass as an idle prompt.

* fix(ai): end non-OSC control strings only at ST and keep the scan linear

DCS/SOS/PM/APC now require ST (BEL terminates only OSC), and the payload
match stops at the next ESC so a run of unterminated introducers no longer
makes stripAnsi quadratic on large PTY captures.

* fix(ai): restore Kali prompt readiness after erasing typed input

---------

Co-authored-by: rinchao0721 <214155009+rinchao0721@users.noreply.github.com>
Co-authored-by: 陈奇 <16399091+binaricat@users.noreply.github.com>
2026-12-03 16:55:56 +08:00
GOUKI9999andbinaricat f50c18e5c7 fix(ai): sync providers, honor UI language, preserve timestamps, and show feedback when regenerating chat titles (#4649)
* fix(ai): fix AI title regeneration provider sync, locale prompt, timestamp preservation, and UI feedback

* fix(ai): preserve queued renames and scoped conversation order

* fix(ai): isolate privacy sessions for repeated title generation

---------

Co-authored-by: binaricat <16399091+binaricat@users.noreply.github.com>
2026-12-03 16:55:52 +08:00
GOUKI9999andbinaricat 33b4bd1a43 fix(ai): prevent sent composer text from lingering due to async batching, blur race, and steer ref equality (#4647)
* fix(ai): fix React 18 batching in clearDraftForScope, blur resurrection, and steer clear

* fix(ai): preserve replacement drafts after late steer replies

---------

Co-authored-by: binaricat <16399091+binaricat@users.noreply.github.com>
2026-12-03 16:55:46 +08:00
Caijinglongand陈奇 31458b00a4 feat(shortcuts): allow adding secondary chords to a shortcut (#4658)
* feat(shortcuts): allow adding secondary chords to a shortcut

Each shortcut row only accepted one chord, so binding a second, easier chord meant overwriting the default one.

Settings > Shortcuts now offers an add button per row. Secondary chords are stored in the existing custom-binding record as `extra`, expanded into real bindings that carry `extraOf`, and matched by the same dispatcher. They render under their base row and can be re-recorded or removed individually. A secondary chord that a default already occupies disables that default, following the existing custom-binding conflict rule; resetting one scheme keeps the secondary chords.

* fix(shortcuts): honor secondary chords in editor close and SFTP paste

The editor's capture-phase close-tab handler and the SFTP native-paste eligibility check still read only the first binding for their action, so a secondary chord added in Settings matched the global dispatcher but did nothing in those paths. Both now scan every binding for the action.

* fix(shortcuts): show recording feedback and honor native close chords

---------

Co-authored-by: 陈奇 <16399091+binaricat@users.noreply.github.com>
2026-12-03 16:37:25 +08:00
陈大猫 f68570d942 fix(win): refresh existing desktop shortcut icon on NSIS update (#4672) (#4673)
Fixes #4672.

Regression from #4597: ensureDesktopShortcut previously skipped CreateShortCut when $newDesktopLink already existed, leaving existing desktop shortcuts stale with a blank icon after in-app NSIS updates. Always rewrite the existing .lnk from the newly installed $appExe when ensureDesktopShortcut runs, while preserving all caller gates so deleted or opted-out shortcuts are still not recreated.
2026-12-03 16:22:37 +08:00
GOUKI9999 9474601fdf feat(ai): show native Grok ACP questions in chat (#4651)
* feat(ai): show native Grok ACP questions in chat

* fix(ai): validate Grok answers before privacy masking

* refactor(ai): keep Grok question cleanup independently mergeable

* fix(i18n): complete Grok question translations
2026-12-03 16:20:26 +08:00
GOUKI9999 4cef084e99 fix(ai): route Grok ACP plan review to the user (#4650)
* fix(ai): route Grok ACP plan review to the user

* fix(ai): restore private plan text for Grok review

* fix(i18n): complete Grok plan review translations
2026-12-03 16:20:21 +08:00
Caijinglong 58eeefb4c1 fix(import): merge repeated ssh_config Host blocks for one alias (#4657)
OpenSSH applies every Host block whose pattern matches an alias and keeps the first obtained value, so one alias may be declared in several blocks (for example HostName/User in one block and IdentityFile in another). The importer created one host per block, so such a config produced a second host whose hostname was the alias itself with no username.

Managed dedupe only compares endpoints, so the alias copy survived next to the resolved host, and the config serializer omits HostName when the hostname equals the alias, so the split was written back and re-imported unchanged on every sync.

Accumulate options per literal pattern instead (first obtained wins, IdentityFile paths are unioned) and create one host per pattern.
2026-12-03 13:53:48 +08:00
Caijinglong 6f8211481c feat(ai): add DeepSeek as a web search provider (#4660) 2026-12-03 13:52:36 +08:00
陈大猫 6458dbe039 fix(mcp): redact tcpdump-style ip.port addresses in external MCP output (#4668)
Fixes #4665

Recognize a trailing dotted port (0-65535) after IPv4/IPv6 so tcpdump-style
addresses are masked while the port is preserved. Colon forms and hostname
suffixes are unchanged. Single-digit IPv4 ports still require a tcpdump-like
delimiter so identifiers such as 1.2.3.4.5 stay intact.
2026-12-03 13:49:17 +08:00
陈大猫 6e0eacc6ae fix(cloud-sync): persist sync base and snapshots in IndexedDB (#4663)
Fixes #4661

Persist encrypted sync baseline and snapshots in IndexedDB so large vaults are no longer blocked by localStorage quota (Unable to persist sync base).

CI: lint-and-test green, run 47032340860 attempt 3.
Real Electron smoke: PASS on tip 758bbec0ac (production saveSyncBase under localStorage pressure; reload/hash/Settings Sync/SSH verified).
Codex residual P2 concurrency races judged out of scope for this quota fix.
2026-12-03 12:44:16 +08:00
陈大猫 73ee6c0f31 fix(terminal): defer CJK punctuation keydowns for IME halfwidth remaps (#4655)
* fix(terminal): defer CJK punctuation keydowns for IME halfwidth remaps

Fixes #4653. macOS Pinyin halfwidth punctuation reports a fullwidth keydown before committing halfwidth insertText, the inverse of #2833. Defer non-ASCII punctuation and keep unchanged CJK glyphs on the literal/composition path rather than Kitty physical-key encoding.

Credit AiHyo for diagnosing the event sequence and root cause.

* fix(terminal): avoid control-character regex in IME punctuation deferral
2026-12-02 20:04:41 +08:00
陈大猫 905aed61ad fix(terminal): keep workspace sessions removed across queued updates (#4652) 2026-12-02 19:36:39 +08:00
GOUKI9999 13d05b0ea4 fix(cloud-sync): keep local backup AI/settings counts inline when width allows (#4645) 2026-12-02 17:16:44 +08:00
陈大猫 1045737c68 feat(terminal): add autocomplete setting to show or hide code snippets (#4641) 2026-12-02 17:16:00 +08:00
陈大猫 909d3e5ed2 fix(startup): open local terminal landing after lazy App mount (#4640) (#4646)
#4476 split App into a lazy chunk, so AppLockGate could send rendererReady
while Suspense still showed a fallback. The cold-start settled event then
fired before AppSideEffects subscribed, and the "open local terminal on
launch" landing never ran when tab restore was off.

Defer rendererReady until the lazy route reports it has mounted, and latch
the settled event in preload so late subscribers still receive it.
2026-12-02 17:00:35 +08:00
陈大猫 cb7e49c409 fix(terminal): prevent autocomplete crash from double-sending keys (#4539) (#4632) 2026-12-02 14:49:08 +08:00
Netcatty-Bot 02be8a2e0a Update Nix release metadata for v1.2.0 (#4631) 2026-12-02 13:38:39 +08:00
陈大猫 ca2cdcbd12 fix(terminal): show sudo password hint for bare Password: prompts (#4628) (#4629) 2026-12-02 12:20:18 +08:00
陈大猫 f7fed5fd6f fix(plugins): systematic reliability hardening across transports, streams, RPC lifecycle, and UI (#4630) 2026-12-02 12:17:21 +08:00
陈大猫 25aa27bbf8 fix(plugins): settle pending SSH dial coordination and isolate plugin exec transport (#4627) 2026-12-02 11:34:05 +08:00
Netcatty-Botandgithub-actions[bot] 7e44b774f8 Update Nix release metadata for v1.1.99 (#4623)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-12-02 09:36:35 +08:00
陈大猫 c5c7cfdae3 fix(ai): loop-strip stacked decorative prompt prefixes (#4620)
* fix(ai): loop-strip stacked decorative prompt prefixes

Related #4354

After a non-zero exit, p10k (and similar) may prefix a status glyph
such as ✘ before the existing theme decoration (⚡). Recognition only
stripped one 1-4 char decorative token, so the leftover ⚡ still missed
the idle-prompt matchers and MCP terminal_execute never sent the command.

* fix(ai): match decorative prefix candidates after each strip

Related #4354

isDefaultPosixPromptLine must try the original line and each
intermediate strip so a status glyph in front of an Oh My Zsh
➜ prompt does not drop the ➜ before matching.
2026-12-02 08:35:18 +08:00
陈大猫 62085cb3c2 fix(plugins): cancel stuck SSH exec dials before the plugin RPC deadline (#4622)
Plugin vault.execHostCommand could hit "Plugin request deadline exceeded"
when a pooled SSH reconnect used the interactive 20s/120s handshake
timeouts, and retries hitchhiked on the leftover pendingDial.

- Stop and drop a pending plugin dial when its last waiter cancels
- Pass tighter startPortForward connect/auth budgets (8s/8s) under an
  18s prepare+dial envelope, and map failures to "SSH connection timed out"
- Evict half-open or channel-open/RPC-deadline-failed pooled connections
2026-12-02 08:15:51 +08:00
158 changed files with 6885 additions and 820 deletions

No files matched your search

+8 -2
View File
@@ -25,6 +25,7 @@ import { SessionPublisher } from './application/app/publishers/SessionPublisher'
import { SettingsPublisher } from './application/app/publishers/SettingsPublisher';
import { VaultPublisher } from './application/app/publishers/VaultPublisher';
import { AppLockRuntimePublisher } from './application/app/publishers/AppLockRuntimePublisher';
import { useReportRendererReady } from './components/AppLockGate';
// Initialize fonts eagerly at app startup
initializeFonts();
@@ -61,8 +62,10 @@ function App() {
/**
* `AppLockGate` (index.tsx) owns `useSettingsState` / `useAppLockState` so the
* lock overlay can render before app children mount, and it owns the
* splash-removal + rendererReady signal (deep links must wait for unlock).
* lock overlay can render before app children mount, and owns splash removal
* plus the lock-gated `rendererReady` policy. This lazy route reports ready
* after `AppSideEffects` and bridge listeners have mounted so cold-start
* intents and deep links never race a suspended chunk.
* App forwards the gate's settings instance into SettingsPublisher so the
* runtime slot/context still publish a single settings runtime.
*/
@@ -78,6 +81,9 @@ function AppWithProviders({ settings, appLock }: { settings: SettingsState; appL
}, []);
useExternalMcpGrantPersister();
// Signal rendererReady after child effects (AppSideEffects) and bridge setup
// have registered in this commit's effect flush.
useReportRendererReady();
return (
<SettingsPublisher settings={settings}>
+2
View File
@@ -67,6 +67,8 @@
- 🔥 **Intelligent context awareness** — understands your server environment and provides tailored responses
- 🚀 **One-click complex operations** — set up clusters, deploy services, and more with simple instructions
To search the web with DeepSeek, open **Settings → AI → Web Search**, enable web search, select **DeepSeek**, and enter your DeepSeek API key. You can use it with your current chat model. [DeepSeek Search API and pricing](https://api-docs.deepseek.com/guides/search/)
### 🎬 AI in Action
#### 🔥 Single Host — Intelligent Server Diagnostics
+11 -11
View File
@@ -270,7 +270,7 @@ export function flushQueuedTrayPanelConnectHostsImpl(getCtx: AppContextGetter) {
}
export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: KeyboardEvent) {
const { HOTKEY_DEBUG, closeTabKeyStr, executeHotkeyAction, hotkeyScheme, keyBindings, matchesKeyBinding } = getCtx();
const { HOTKEY_DEBUG, executeHotkeyAction, hotkeyScheme, keyBindings, matchesKeyBinding } = getCtx();
{
if (
isTargetInsideRemoteDesktopCapture(e.target, e.composedPath?.bind(e))
@@ -280,8 +280,14 @@ export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: Keybo
}
const isMac = hotkeyScheme === 'mac';
// Secondary chords added in Settings share the action of their default
// binding, so every "is this action's shortcut?" check must scan all of them.
const matchesActionHotkey = (action: string): boolean => keyBindings.some((binding) => (
binding.action === action
&& matchesKeyBinding(e, isMac ? binding.mac : binding.pc, isMac)
));
const target = e.target as HTMLElement;
const isCloseTabHotkey = closeTabKeyStr ? matchesKeyBinding(e, closeTabKeyStr, isMac) : false;
const isCloseTabHotkey = matchesActionHotkey('closeTab');
const dialogHotkeyScope = target.closest?.('[data-hotkey-close-tab="true"]');
if (isCloseTabHotkey && dialogHotkeyScope) {
@@ -308,15 +314,9 @@ export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: Keybo
target instanceof HTMLElement &&
!!target.closest?.(".xterm, .xterm-helper-textarea, .xterm-screen, .xterm-viewport");
const quickSwitchBinding = keyBindings.find((binding) => binding.action === 'quickSwitch');
const quickSwitchKeyStr = quickSwitchBinding ? (isMac ? quickSwitchBinding.mac : quickSwitchBinding.pc) : null;
const isQuickSwitchHotkey = quickSwitchKeyStr ? matchesKeyBinding(e, quickSwitchKeyStr, isMac) : false;
const paneZoomBinding = keyBindings.find((binding) => binding.action === 'togglePaneZoom');
const paneZoomKeyStr = paneZoomBinding ? (isMac ? paneZoomBinding.mac : paneZoomBinding.pc) : null;
const isPaneZoomHotkey = paneZoomKeyStr ? matchesKeyBinding(e, paneZoomKeyStr, isMac) : false;
const hostTreeBinding = keyBindings.find((binding) => binding.action === 'toggleHostTree');
const hostTreeKeyStr = hostTreeBinding ? (isMac ? hostTreeBinding.mac : hostTreeBinding.pc) : null;
const isHostTreeHotkey = hostTreeKeyStr ? matchesKeyBinding(e, hostTreeKeyStr, isMac) : false;
const isQuickSwitchHotkey = matchesActionHotkey('quickSwitch');
const isPaneZoomHotkey = matchesActionHotkey('togglePaneZoom');
const isHostTreeHotkey = matchesActionHotkey('toggleHostTree');
if (
(isFormElement || isMonacoElement)
+4 -11
View File
@@ -66,7 +66,7 @@ import type { PaneMagnificationController } from '../../domain/paneMagnification
import { isPluginViewEditingTarget } from '../state/pluginKeybindings';
import { resolveCloseIntent } from '../state/resolveCloseIntent';
import { resolveSnippetsShortcutIntent } from '../state/resolveSnippetsShortcutIntent';
import { isPrimaryModifierWBinding, resolveWindowCommandCloseIntent } from '../state/windowCommandClose';
import { isNativeCloseTabBound, resolveWindowCommandCloseIntent } from '../state/windowCommandClose';
import type { SyncPayload } from '../../domain/sync';
import { prepareSyncPayloadApply, buildLocalVaultPayloadAsync, hasMeaningfulSyncData } from '../syncPayload';
import {
@@ -651,7 +651,7 @@ export function AppSideEffects() {
const _handleTrayTogglePortForward = useEffectEvent((ruleId: string, start: boolean) => { return handleTrayTogglePortForwardImpl(() => ({ hasRuntimeTunnel, hosts, identities, keys, knownHosts: effectiveKnownHosts, portForwardingRules, resolveEffectiveHost, ruleId, start, startTunnel, stopTunnel, t, terminalSettings, toast, undefined }), ruleId, start); });
const _handleTrayPanelConnect = useEffectEvent((hostId: string) => { return handleTrayPanelConnectImpl(() => ({ addConnectionLog, connectToHost, hostId, hosts, identities, keys, resolveEffectiveHost, resolveHostAuth, systemInfoRef, t, toast }), hostId); });
const _handleTrayPanelConnectRequest = useEffectEvent((hostId: string) => { return handleTrayPanelConnectRequestImpl(() => ({ connectNow: _handleTrayPanelConnect, hostId, isVaultInitialized, queueConnect: (queuedHostId: string) => setPendingTrayPanelConnectHostIds((prev) => [...prev, queuedHostId]) }), hostId); });
const _handleGlobalHotkeyKeyDown = useEffectEvent((e: KeyboardEvent) => { return handleGlobalHotkeyKeyDownImpl(() => ({ HOTKEY_DEBUG, closeTabKeyStr, e, executeHotkeyAction, hotkeyScheme, keyBindings, matchesKeyBinding }), e); });
const _handleGlobalHotkeyKeyDown = useEffectEvent((e: KeyboardEvent) => { return handleGlobalHotkeyKeyDownImpl(() => ({ HOTKEY_DEBUG, e, executeHotkeyAction, hotkeyScheme, keyBindings, matchesKeyBinding }), e); });
const _handleEscapeKeyDown = useEffectEvent((e: KeyboardEvent) => { return handleEscapeKeyDownImpl(() => ({ e, isQuickSwitcherOpen, setIsQuickSwitcherOpen }), e); });
// Vault hosts for tray / auto-start; terminalHosts (vault + ephemeral) only for
@@ -1082,13 +1082,6 @@ export function AppSideEffects() {
setSessionPoppedOut(sessionId, false);
}), [setSessionPoppedOut]);
const closeTabKeyStr = useMemo(() => {
if (hotkeyScheme === 'disabled') return null;
const closeTabBinding = keyBindings.find((binding) => binding.action === 'closeTab');
if (!closeTabBinding) return null;
return hotkeyScheme === 'mac' ? closeTabBinding.mac : closeTabBinding.pc;
}, [hotkeyScheme, keyBindings]);
const confirmIfBusyLocalTerminal = useCallback(
async (sessionIds: string[]): Promise<boolean> => { return confirmIfBusyLocalTerminalImpl(() => ({ netcattyBridge, sessionIds, sessions, t }), sessionIds); },
[sessions, t],
@@ -1228,7 +1221,7 @@ export function AppSideEffects() {
logViewIds: logViews.map((logView) => logView.id),
pluginViewTabIds: pluginViewTabs.map((tab) => tab.id),
hasOpenDialog: Boolean(topmostDialogClose),
closeTabShortcutEnabled: isPrimaryModifierWBinding(closeTabKeyStr, matchesKeyBinding, true),
closeTabShortcutEnabled: isNativeCloseTabBound(hotkeyScheme, keyBindings, true),
});
if (intent.kind === 'forwardShortcut') {
@@ -1261,7 +1254,7 @@ export function AppSideEffects() {
}
await netcattyBridge.get()?.windowClose?.();
}, [closeLogView, closeTabKeyStr, editorTabs, executeHotkeyAction, logViews, pluginViewTabs, sessions, workspaces]);
}, [closeLogView, editorTabs, executeHotkeyAction, hotkeyScheme, keyBindings, logViews, pluginViewTabs, sessions, workspaces]);
useEffect(() => {
// Cmd/Ctrl+W from the app menu arrives via IPC, not the keydown listener.
+19
View File
@@ -117,6 +117,9 @@ export const enAiMessages: Messages = {
'ai.codex.appServer.available': 'App Server is available for this Codex CLI.',
'ai.codex.appServer.modelCatalogWarning': 'The live Codex model catalog is unavailable. Using the built-in model list.',
'ai.codex.appServer.approval.allowSession': 'Allow for session',
'ai.planReview.title': 'Review implementation plan',
'ai.planReview.keepPlanning': 'Keep planning',
'ai.planReview.approveAndImplement': 'Approve and implement',
'ai.codex.appServer.userInput.title': 'Codex needs your input',
'ai.codex.appServer.userInput.description': 'Answer these questions to continue the current turn.',
'ai.codex.appServer.userInput.other': 'Enter another answer',
@@ -328,6 +331,9 @@ export const enAiMessages: Messages = {
'ai.grok.check': 'Check',
'ai.grok.resetPath': 'Reset',
'ai.grok.runtime.acp.title': 'Use Grok ACP (agent stdio)',
'ai.grok.userQuestion.title': 'Grok needs your input',
'ai.grok.userQuestion.description': 'Answers do not grant permissions. Do not include passwords or tokens.',
'ai.grok.userQuestion.submit': 'Send answers',
'ai.grok.runtime.acp.default': 'Default',
'ai.grok.runtime.acp.description':
'Talk to Grok over Agent Client Protocol (grok agent stdio). Injects Netcatty MCP on session/new. Turn off to use the original headless streaming-json CLI path.',
@@ -634,6 +640,12 @@ export const enAiMessages: Messages = {
'ai.chat.managerSelectedCount': '{n} selected',
'ai.chat.managerSelectRow': 'Select this chat',
'ai.chat.managerRegenerateTitle': 'Regenerate title with AI',
'ai.chat.managerRegenerateTitleUpdated': 'Chat title updated.',
'ai.chat.managerRegenerateTitleUnchanged': 'Chat title is already up to date.',
'ai.chat.managerRegenerateTitleNoModel': 'No AI provider/model is configured for title generation. Configure a provider or title model in AI Settings.',
'ai.chat.managerRegenerateTitleFailed': 'Failed to regenerate title: {error}',
'ai.chat.managerRegenerateTitleBatchDone': 'Updated {n} chat title(s).',
'ai.chat.managerRegenerateTitleBatchPartial': 'Updated {updated} title(s), {failed} failed.',
'ai.chat.managerExportOne': 'Export this chat',
'ai.chat.managerBadgeActive': 'Active',
'ai.chat.managerBadgeIdle': 'Idle',
@@ -692,6 +704,13 @@ export const enAiMessages: Messages = {
'ai.chatShortcuts.selectionAction': 'Show Add to Conversation when selecting terminal text',
'ai.chatShortcuts.selectionAction.description': 'Show a small AI button next to selected terminal text.',
'ai.chatHistory.title': 'Chat History',
'ai.chatHistory.storageUsage': 'Local chat history size',
'ai.chatHistory.storageUsage.description': 'Estimate the size of saved chat records as UTF-8 JSON.',
'ai.chatHistory.storageUsage.measure': 'Measure',
'ai.chatHistory.storageUsage.measuring': 'Measuring…',
'ai.chatHistory.storageUsage.result': 'Saved records · {count}. Estimated JSON size · {size}.',
'ai.chatHistory.storageUsage.partial': 'Records excluded from the size estimate · {count}.',
'ai.chatHistory.storageUsage.error': 'Could not read the local chat history. Try again.',
'ai.chatHistory.messageCap': 'Messages kept per chat',
'ai.chatHistory.messageCap.description': 'Maximum number of messages stored per chat (50–2000). Lowering it drops the oldest messages from storage on the next write. Larger values increase storage and cloud-sync size.',
'ai.chatHistory.messageCap.unit': 'messages',
+6
View File
@@ -1001,6 +1001,9 @@ Highlight the focused split pane:
'Choose whether autocomplete history suggestions come from the current host only, or from commands recorded on all hosts.',
'settings.terminal.autocomplete.historyScope.host': 'Current host',
'settings.terminal.autocomplete.historyScope.global': 'All hosts',
'settings.terminal.autocomplete.showSnippets': 'Show code snippets',
'settings.terminal.autocomplete.showSnippets.desc':
'Include matching code snippets in the autocomplete list. Turn this off if snippets crowd out command and history suggestions.',
// Settings > Terminal > Password prompt assist (sudo/su)
'settings.terminal.section.passwordPromptAssist': 'Password prompt assist',
@@ -1029,6 +1032,9 @@ Highlight the focused split pane:
'settings.shortcuts.recording': 'Press keys...',
'settings.shortcuts.none': 'None',
'settings.shortcuts.setDisabled': 'Set to disabled',
'settings.shortcuts.addExtra': 'Add shortcut',
'settings.shortcuts.additional': 'Additional shortcut',
'settings.shortcuts.removeExtra': 'Remove shortcut',
'settings.shortcuts.category.tabs': 'Tabs',
'settings.shortcuts.category.terminal': 'Terminal',
'settings.shortcuts.category.navigation': 'Navigation',
+19
View File
@@ -117,6 +117,9 @@ export const esAiMessages: Messages = {
'ai.codex.appServer.available': 'App Server está disponible para esta Codex CLI.',
'ai.codex.appServer.modelCatalogWarning': 'El catálogo de modelos de Codex en vivo no está disponible. Se usa la lista de modelos integrada.',
'ai.codex.appServer.approval.allowSession': 'Permitir por sesión',
'ai.planReview.title': 'Revisar el plan de implementación',
'ai.planReview.keepPlanning': 'Seguir planificando',
'ai.planReview.approveAndImplement': 'Aprobar e implementar',
'ai.codex.appServer.userInput.title': 'Codex necesita tu aporte',
'ai.codex.appServer.userInput.description': 'Responde estas preguntas para continuar el turno actual.',
'ai.codex.appServer.userInput.other': 'Ingresa otra respuesta',
@@ -328,6 +331,9 @@ export const esAiMessages: Messages = {
'ai.grok.check': 'Verificar',
'ai.grok.resetPath': 'Restablecer',
'ai.grok.runtime.acp.title': 'Usar Grok ACP (agente stdio)',
'ai.grok.userQuestion.title': 'Grok necesita tu respuesta',
'ai.grok.userQuestion.description': 'Las respuestas no conceden permisos. No incluyas contraseñas ni tokens.',
'ai.grok.userQuestion.submit': 'Enviar respuestas',
'ai.grok.runtime.acp.default': 'Predeterminado',
'ai.grok.runtime.acp.description':
'Habla con Grok mediante el Protocolo de Cliente de Agente (grok agent stdio). Inyecta el MCP de Netcatty en session/new. Apágalo para usar la ruta original de CLI headless con streaming-json.',
@@ -634,6 +640,12 @@ export const esAiMessages: Messages = {
'ai.chat.managerSelectedCount': '{n} seleccionados',
'ai.chat.managerSelectRow': 'Seleccionar este chat',
'ai.chat.managerRegenerateTitle': 'Regenerar título con IA',
'ai.chat.managerRegenerateTitleUpdated': 'Título del chat actualizado.',
'ai.chat.managerRegenerateTitleUnchanged': 'El título del chat ya está actualizado.',
'ai.chat.managerRegenerateTitleNoModel': 'No hay un proveedor o modelo de IA configurado para generar títulos. Configúralo en Ajustes de IA.',
'ai.chat.managerRegenerateTitleFailed': 'Error al regenerar el título: {error}',
'ai.chat.managerRegenerateTitleBatchDone': 'Se actualizaron {n} título(s) de chat.',
'ai.chat.managerRegenerateTitleBatchPartial': 'Se actualizaron {updated} título(s) y fallaron {failed}.',
'ai.chat.managerExportOne': 'Exportar este chat',
'ai.chat.managerBadgeActive': 'Activo',
'ai.chat.managerBadgeIdle': 'Inactivo',
@@ -692,6 +704,13 @@ export const esAiMessages: Messages = {
'ai.chatShortcuts.selectionAction': 'Mostrar "Agregar a la conversación" al seleccionar texto de la terminal',
'ai.chatShortcuts.selectionAction.description': 'Muestra un pequeño botón de IA junto al texto seleccionado de la terminal.',
'ai.chatHistory.title': 'Historial de chat',
'ai.chatHistory.storageUsage': 'Tamaño del historial de chats local',
'ai.chatHistory.storageUsage.description': 'Calcula el tamaño de los registros guardados como JSON UTF-8.',
'ai.chatHistory.storageUsage.measure': 'Calcular',
'ai.chatHistory.storageUsage.measuring': 'Calculando…',
'ai.chatHistory.storageUsage.result': 'Registros guardados · {count}. Tamaño estimado del JSON · {size}.',
'ai.chatHistory.storageUsage.partial': 'Registros excluidos del cálculo · {count}.',
'ai.chatHistory.storageUsage.error': 'No se pudo leer el historial de chats local. Vuelve a intentarlo.',
'ai.chatHistory.messageCap': 'Mensajes conservados por chat',
'ai.chatHistory.messageCap.description': 'Número máximo de mensajes almacenados por chat (50–2000). Al reducirlo, los mensajes más antiguos se descartan del almacenamiento en la siguiente escritura. Los valores más altos aumentan el almacenamiento y el tamaño de la sincronización en la nube.',
'ai.chatHistory.messageCap.unit': 'mensajes',
+6
View File
@@ -1001,6 +1001,9 @@ Resalta el panel dividido enfocado:
'Elige si las sugerencias de autocompletado del historial provienen solo del host actual o de los comandos registrados en todos los hosts.',
'settings.terminal.autocomplete.historyScope.host': 'Host actual',
'settings.terminal.autocomplete.historyScope.global': 'Todos los hosts',
'settings.terminal.autocomplete.showSnippets': 'Mostrar fragmentos de código',
'settings.terminal.autocomplete.showSnippets.desc':
'Incluye fragmentos de código coincidentes en la lista de autocompletado. Desactiva esta opción si los fragmentos desplazan las sugerencias de comandos e historial.',
// Settings > Terminal > Password prompt assist (sudo/su)
'settings.terminal.section.passwordPromptAssist': 'Asistencia para solicitud de contraseña',
@@ -1029,6 +1032,9 @@ Resalta el panel dividido enfocado:
'settings.shortcuts.recording': 'Presiona teclas...',
'settings.shortcuts.none': 'Ninguno',
'settings.shortcuts.setDisabled': 'Configurar como desactivado',
'settings.shortcuts.addExtra': 'Añadir atajo',
'settings.shortcuts.additional': 'Atajo adicional',
'settings.shortcuts.removeExtra': 'Eliminar atajo',
'settings.shortcuts.category.tabs': 'Pestañas',
'settings.shortcuts.category.terminal': 'Terminal',
'settings.shortcuts.category.navigation': 'Navegación',
+19
View File
@@ -117,6 +117,9 @@ export const ruAiMessages: Messages = {
'ai.codex.appServer.available': 'Эта версия Codex CLI поддерживает App Server.',
'ai.codex.appServer.modelCatalogWarning': 'Динамический каталог моделей Codex недоступен. Используется встроенный список моделей.',
'ai.codex.appServer.approval.allowSession': 'Разрешить для сеанса',
'ai.planReview.title': 'Проверить план реализации',
'ai.planReview.keepPlanning': 'Продолжить планирование',
'ai.planReview.approveAndImplement': 'Одобрить и приступить к реализации',
'ai.codex.appServer.userInput.title': 'Codex требуется ваш ответ',
'ai.codex.appServer.userInput.description': 'Ответьте на вопросы, чтобы продолжить текущую задачу.',
'ai.codex.appServer.userInput.other': 'Введите другой ответ',
@@ -296,6 +299,9 @@ export const ruAiMessages: Messages = {
'ai.grok.check': 'Проверить',
'ai.grok.resetPath': 'Сбросить',
'ai.grok.runtime.acp.title': 'Использовать Grok ACP (agent stdio)',
'ai.grok.userQuestion.title': 'Grok ждёт вашего ответа',
'ai.grok.userQuestion.description': 'Ответы не предоставляют разрешений. Не указывайте пароли и токены.',
'ai.grok.userQuestion.submit': 'Отправить ответы',
'ai.grok.runtime.acp.default': 'По умолчанию',
'ai.grok.runtime.acp.description':
'Подключение к Grok через Agent Client Protocol (grok agent stdio). Netcatty MCP внедряется в session/new. Выключите, чтобы использовать исходный headless streaming-json CLI.',
@@ -633,6 +639,12 @@ export const ruAiMessages: Messages = {
'ai.chat.managerSelectedCount': 'Выбрано: {n}',
'ai.chat.managerSelectRow': 'Выбрать этот чат',
'ai.chat.managerRegenerateTitle': 'Пересоздать заголовок через ИИ',
'ai.chat.managerRegenerateTitleUpdated': 'Заголовок чата обновлён.',
'ai.chat.managerRegenerateTitleUnchanged': 'Заголовок чата уже актуален.',
'ai.chat.managerRegenerateTitleNoModel': 'Не настроен провайдер/модель ИИ для генерации заголовков. Настройте модель в настройках ИИ.',
'ai.chat.managerRegenerateTitleFailed': 'Не удалось пересоздать заголовок: {error}',
'ai.chat.managerRegenerateTitleBatchDone': 'Обновлено заголовков: {n}.',
'ai.chat.managerRegenerateTitleBatchPartial': 'Обновлено {updated}, ошибок: {failed}.',
'ai.chat.managerExportOne': 'Экспортировать этот чат',
'ai.chat.managerBadgeActive': 'Активен',
'ai.chat.managerBadgeIdle': 'Простой',
@@ -691,6 +703,13 @@ export const ruAiMessages: Messages = {
'ai.chatShortcuts.selectionAction': 'Показывать «Добавить в чат» при выделении в терминале',
'ai.chatShortcuts.selectionAction.description': 'Показывать небольшую кнопку ИИ рядом с выделенным текстом терминала.',
'ai.chatHistory.title': 'История чата',
'ai.chatHistory.storageUsage': 'Размер локальной истории чатов',
'ai.chatHistory.storageUsage.description': 'Оценивает размер сохранённых записей чатов в формате JSON (UTF-8).',
'ai.chatHistory.storageUsage.measure': 'Рассчитать',
'ai.chatHistory.storageUsage.measuring': 'Расчёт…',
'ai.chatHistory.storageUsage.result': 'Сохранено записей — {count}. Примерный размер JSON — {size}.',
'ai.chatHistory.storageUsage.partial': 'Записей, исключённых из расчёта размера, — {count}.',
'ai.chatHistory.storageUsage.error': 'Не удалось прочитать локальную историю чатов. Повторите попытку.',
'ai.chatHistory.messageCap': 'Сообщений, сохраняемых в чате',
'ai.chatHistory.messageCap.description': 'Максимальное число сообщений, хранимых для одного чата (50–2000). При уменьшении самые старые сообщения удаляются из хранилища при следующей записи. Большие значения увеличивают объём хранилища и синхронизации с облаком.',
'ai.chatHistory.messageCap.unit': 'сообщений',
+6
View File
@@ -986,6 +986,9 @@ export const ruCoreMessages: Messages = {
'Выберите, брать ли подсказки истории автодополнения только с текущего хоста или со всех хостов.',
'settings.terminal.autocomplete.historyScope.host': 'Текущий хост',
'settings.terminal.autocomplete.historyScope.global': 'Все хосты',
'settings.terminal.autocomplete.showSnippets': 'Показывать сниппеты',
'settings.terminal.autocomplete.showSnippets.desc':
'Включать подходящие сниппеты в список автодополнения. Отключите, если сниппеты вытесняют подсказки команд и истории.',
// Settings > Terminal > Password prompt assist (sudo/su)
'settings.terminal.section.passwordPromptAssist': 'Подсказки пароля',
@@ -1014,6 +1017,9 @@ export const ruCoreMessages: Messages = {
'settings.shortcuts.recording': 'Нажмите клавиши...',
'settings.shortcuts.none': 'Нет',
'settings.shortcuts.setDisabled': 'Отключить',
'settings.shortcuts.addExtra': 'Добавить сочетание',
'settings.shortcuts.additional': 'Дополнительное сочетание',
'settings.shortcuts.removeExtra': 'Удалить сочетание',
'settings.shortcuts.category.tabs': 'Вкладки',
'settings.shortcuts.category.terminal': 'Терминал',
'settings.shortcuts.category.navigation': 'Навигация',
@@ -304,3 +304,20 @@ test("localized settings include SFTP tree folder double-click labels across all
}
}
});
test("localized settings include autocomplete show code snippets labels across all locales", () => {
const keys = [
"settings.terminal.autocomplete.showSnippets",
"settings.terminal.autocomplete.showSnippets.desc",
];
for (const locale of ALL_SETTINGS_LOCALES) {
const missing = keys.filter((key) => !locale.messages[key]);
assert.deepEqual(missing, [], `${locale.name} is missing autocomplete showSnippets labels`);
if (locale.name !== "en") {
for (const key of keys) {
assert.notEqual(locale.messages[key], en[key], `${locale.name}: ${key} should be translated`);
}
}
}
});
+19
View File
@@ -117,6 +117,9 @@ export const zhCNAiMessages: Messages = {
'ai.codex.appServer.available': '当前 Codex CLI 支持 App Server。',
'ai.codex.appServer.modelCatalogWarning': 'Codex 动态模型目录暂不可用,当前将使用内置模型列表。',
'ai.codex.appServer.approval.allowSession': '本会话允许',
'ai.planReview.title': '审核实施方案',
'ai.planReview.keepPlanning': '继续规划',
'ai.planReview.approveAndImplement': '批准并实施',
'ai.codex.appServer.userInput.title': 'Codex 需要你的输入',
'ai.codex.appServer.userInput.description': '回答以下问题以继续当前任务。',
'ai.codex.appServer.userInput.other': '输入其他答案',
@@ -328,6 +331,9 @@ export const zhCNAiMessages: Messages = {
'ai.grok.check': '检查',
'ai.grok.resetPath': '重置',
'ai.grok.runtime.acp.title': '使用 Grok ACP(agent stdio)',
'ai.grok.userQuestion.title': 'Grok 正在等待你的回答',
'ai.grok.userQuestion.description': '回答不会改变权限。请勿填写密码或令牌。',
'ai.grok.userQuestion.submit': '发送回答',
'ai.grok.runtime.acp.default': '默认',
'ai.grok.runtime.acp.description':
'通过 Agent Client Protocol(grok agent stdio)接入 Grok。在 session/new 注入 Netcatty MCP。关闭后使用原始 headless streaming-json CLI 路径。',
@@ -634,6 +640,12 @@ export const zhCNAiMessages: Messages = {
'ai.chat.managerSelectedCount': '已选 {n} 个',
'ai.chat.managerSelectRow': '选择此会话',
'ai.chat.managerRegenerateTitle': '用 AI 重新生成标题',
'ai.chat.managerRegenerateTitleUpdated': '会话标题已更新。',
'ai.chat.managerRegenerateTitleUnchanged': '会话标题已是最新。',
'ai.chat.managerRegenerateTitleNoModel': '未配置用于生成标题的 AI 模型,请在 AI 设置中配置提供商或标题模型。',
'ai.chat.managerRegenerateTitleFailed': '重新生成标题失败:{error}',
'ai.chat.managerRegenerateTitleBatchDone': '已更新 {n} 个会话标题。',
'ai.chat.managerRegenerateTitleBatchPartial': '已更新 {updated} 个标题,{failed} 个失败。',
'ai.chat.managerExportOne': '导出此会话',
'ai.chat.managerBadgeActive': '使用中',
'ai.chat.managerBadgeIdle': '空闲',
@@ -692,6 +704,13 @@ export const zhCNAiMessages: Messages = {
'ai.chatShortcuts.selectionAction': '选中终端内容时显示“添加到对话”',
'ai.chatShortcuts.selectionAction.description': '在终端里选中文本后显示 AI 快捷按钮。',
'ai.chatHistory.title': '聊天历史',
'ai.chatHistory.storageUsage': '本地聊天历史大小',
'ai.chatHistory.storageUsage.description': '按 UTF-8 JSON 估算已保存的聊天记录大小。',
'ai.chatHistory.storageUsage.measure': '估算',
'ai.chatHistory.storageUsage.measuring': '正在估算…',
'ai.chatHistory.storageUsage.result': '已保存 {count} 条记录,JSON 大小约为 {size}。',
'ai.chatHistory.storageUsage.partial': '其中 {count} 条记录未计入大小估算。',
'ai.chatHistory.storageUsage.error': '无法读取本地聊天历史,请重试。',
'ai.chatHistory.messageCap': '每个会话保留的消息数',
'ai.chatHistory.messageCap.description': '每个会话最多存储的消息条数(50–2000)。调低后会在下一次写入时从存储中丢弃最旧的消息。数值越大,存储占用和云同步体积也越大。',
'ai.chatHistory.messageCap.unit': '条消息',
@@ -574,6 +574,9 @@ export const zhCNTerminalMessages: Messages = {
'选择自动补全的历史建议来自当前主机,还是所有主机上执行过的命令。',
'settings.terminal.autocomplete.historyScope.host': '当前主机',
'settings.terminal.autocomplete.historyScope.global': '全部主机',
'settings.terminal.autocomplete.showSnippets': '显示代码片段',
'settings.terminal.autocomplete.showSnippets.desc':
'在补全列表中显示匹配的代码片段。若片段较多、排在列表前面,可关闭此项。',
'settings.terminal.section.passwordPromptAssist': '密码提示辅助',
'settings.terminal.passwordPromptAssist.mode': '辅助模式',
'settings.terminal.passwordPromptAssist.mode.desc':
@@ -600,6 +603,9 @@ export const zhCNTerminalMessages: Messages = {
'settings.shortcuts.recording': '请按键...',
'settings.shortcuts.none': '无',
'settings.shortcuts.setDisabled': '设为禁用',
'settings.shortcuts.addExtra': '添加快捷键',
'settings.shortcuts.additional': '附加快捷键',
'settings.shortcuts.removeExtra': '移除快捷键',
'settings.shortcuts.category.tabs': '标签页',
'settings.shortcuts.category.terminal': '终端',
'settings.shortcuts.category.navigation': '导航',
+19
View File
@@ -117,6 +117,9 @@ export const zhTWAiMessages: Messages = {
'ai.codex.appServer.available': '目前 Codex CLI 支援 App Server。',
'ai.codex.appServer.modelCatalogWarning': 'Codex 動態模型目錄暫時無法使用,目前將使用內建模型清單。',
'ai.codex.appServer.approval.allowSession': '本工作階段允許',
'ai.planReview.title': '審核實作方案',
'ai.planReview.keepPlanning': '繼續規劃',
'ai.planReview.approveAndImplement': '批准並實作',
'ai.codex.appServer.userInput.title': 'Codex 需要你的輸入',
'ai.codex.appServer.userInput.description': '回答以下問題以繼續目前任務。',
'ai.codex.appServer.userInput.other': '輸入其他答案',
@@ -328,6 +331,9 @@ export const zhTWAiMessages: Messages = {
'ai.grok.check': '檢查',
'ai.grok.resetPath': '重設',
'ai.grok.runtime.acp.title': '使用 Grok ACP(agent stdio)',
'ai.grok.userQuestion.title': 'Grok 正在等待你的回答',
'ai.grok.userQuestion.description': '回答不會變更權限。請勿填寫密碼或權杖。',
'ai.grok.userQuestion.submit': '傳送回答',
'ai.grok.runtime.acp.default': '預設',
'ai.grok.runtime.acp.description':
'透過 Agent Client Protocol(grok agent stdio)接入 Grok。在 session/new 注入 Netcatty MCP。關閉後使用原始 headless streaming-json CLI 路徑。',
@@ -633,6 +639,12 @@ export const zhTWAiMessages: Messages = {
'ai.chat.managerSelectedCount': '已選 {n} 個',
'ai.chat.managerSelectRow': '選擇此工作階段',
'ai.chat.managerRegenerateTitle': '用 AI 重新產生標題',
'ai.chat.managerRegenerateTitleUpdated': '會話標題已更新。',
'ai.chat.managerRegenerateTitleUnchanged': '會話標題已是最新。',
'ai.chat.managerRegenerateTitleNoModel': '未設定用於產生標題的 AI 模型,請在 AI 設定中設定供應商或標題模型。',
'ai.chat.managerRegenerateTitleFailed': '重新產生標題失敗:{error}',
'ai.chat.managerRegenerateTitleBatchDone': '已更新 {n} 個會話標題。',
'ai.chat.managerRegenerateTitleBatchPartial': '已更新 {updated} 個標題,{failed} 個失敗。',
'ai.chat.managerExportOne': '匯出此會話',
'ai.chat.managerBadgeActive': '使用中',
'ai.chat.managerBadgeIdle': '閒置',
@@ -691,6 +703,13 @@ export const zhTWAiMessages: Messages = {
'ai.chatShortcuts.selectionAction': '選取終端內容時顯示「新增到對話」',
'ai.chatShortcuts.selectionAction.description': '在終端裡選取文字後顯示 AI 快捷按鈕。',
'ai.chatHistory.title': '聊天歷史',
'ai.chatHistory.storageUsage': '本機聊天記錄大小',
'ai.chatHistory.storageUsage.description': '以 UTF-8 JSON 估算已儲存的聊天記錄大小。',
'ai.chatHistory.storageUsage.measure': '估算',
'ai.chatHistory.storageUsage.measuring': '正在估算…',
'ai.chatHistory.storageUsage.result': '已儲存 {count} 筆記錄,JSON 大小約為 {size}。',
'ai.chatHistory.storageUsage.partial': '其中 {count} 筆記錄未計入大小估算。',
'ai.chatHistory.storageUsage.error': '無法讀取本機聊天記錄,請再試一次。',
'ai.chatHistory.messageCap': '每個會話保留的訊息數',
'ai.chatHistory.messageCap.description': '每個會話最多儲存的訊息數(50–2000)。調低後會在下一次寫入時從儲存中捨棄最舊的訊息。數值越大,儲存空間與雲端同步體積也越大。',
'ai.chatHistory.messageCap.unit': '則訊息',
@@ -574,6 +574,9 @@ export const zhTWTerminalMessages: Messages = {
'選擇自動補全的歷史建議來自目前主機,還是所有主機上執行過的指令。',
'settings.terminal.autocomplete.historyScope.host': '目前主機',
'settings.terminal.autocomplete.historyScope.global': '全部主機',
'settings.terminal.autocomplete.showSnippets': '顯示程式碼片段',
'settings.terminal.autocomplete.showSnippets.desc':
'在補全列表中顯示符合的程式碼片段。若片段較多、排在列表前面,可關閉此項。',
'settings.terminal.section.passwordPromptAssist': '密碼提示輔助',
'settings.terminal.passwordPromptAssist.mode': '輔助模式',
'settings.terminal.passwordPromptAssist.mode.desc':
@@ -600,6 +603,9 @@ export const zhTWTerminalMessages: Messages = {
'settings.shortcuts.recording': '請按鍵...',
'settings.shortcuts.none': '無',
'settings.shortcuts.setDisabled': '設為停用',
'settings.shortcuts.addExtra': '新增快速鍵',
'settings.shortcuts.additional': '附加快速鍵',
'settings.shortcuts.removeExtra': '移除快速鍵',
'settings.shortcuts.category.tabs': '分頁',
'settings.shortcuts.category.terminal': '終端',
'settings.shortcuts.category.navigation': '導航',
@@ -15,6 +15,7 @@ import {
idbPutSessions,
isIndexedDbAvailable,
loadOrMigrateAiSessions,
measureAiSessionStorageUsage,
mirrorActiveSessionMapToIdb,
openAiSessionsIdb,
readActiveSessionMapFromIdb,
@@ -57,6 +58,27 @@ test('module wrapper roundtrips sessions through the object stores', async () =>
}
});
test('usage reads UTF-8 JSON sizes without changing unreadable or healthy records', async () => {
const idb = installFakeIndexedDb();
try {
const signal = new AbortController().signal;
assert.deepEqual(await measureAiSessionStorageUsage(signal), { recordCount: 0, jsonBytes: 0, unmeasuredCount: 0 });
const db = await openAiSessionsIdb();
const session = { ...makeSession('old-chat', 1), title: '旧聊天 🐈' };
const bad = { ...makeSession('cycle', 2), data: {} };
bad.data = bad;
await idbPutSessions(db, [session, bad]);
assert.deepEqual(await measureAiSessionStorageUsage(signal), {
recordCount: 2, jsonBytes: Buffer.byteLength(JSON.stringify(session)), unmeasuredCount: 1,
});
assert.deepEqual(idb.db.opCounts.get('sessions'), { put: 2, delete: 0 });
await assert.rejects(measureAiSessionStorageUsage(AbortSignal.abort()), { name: 'AbortError' });
} finally {
idb.restore();
resetAiSessionsIdbForTests();
}
});
test('meta store roundtrips schema and active-map records', async () => {
const idb = installFakeIndexedDb();
try {
+41
View File
@@ -108,6 +108,47 @@ export async function idbGetAllSessions(db?: IDBDatabase): Promise<AISession[]>
return Array.isArray(result) ? result : [];
}
export interface AiSessionStorageUsage {
recordCount: number;
jsonBytes: number;
unmeasuredCount: number;
}
/** Size of the JSON payloads in a consistent read-only snapshot of local history. */
export async function measureAiSessionStorageUsage(signal: AbortSignal): Promise<AiSessionStorageUsage> {
signal.throwIfAborted();
const db = await openAiSessionsIdb();
signal.throwIfAborted();
const tx = db.transaction(AI_SESSIONS_IDB_SESSION_STORE, 'readonly');
const request = tx.objectStore(AI_SESSIONS_IDB_SESSION_STORE).openCursor();
const usage = { recordCount: 0, jsonBytes: 0, unmeasuredCount: 0 };
const encoder = new TextEncoder();
return new Promise((resolve, reject) => {
tx.onabort = () => reject(tx.error ?? new Error('History scan aborted'));
request.onerror = () => reject(request.error);
request.onsuccess = () => {
if (signal.aborted) {
reject(signal.reason);
return;
}
const cursor = request.result;
if (!cursor) {
resolve(usage);
return;
}
usage.recordCount++;
try {
usage.jsonBytes += encoder.encode(JSON.stringify(cursor.value)).byteLength;
} catch {
// Structured clone also accepts cycles and BigInts, which JSON cannot represent.
usage.unmeasuredCount++;
}
cursor.continue();
};
});
}
export async function idbPutSessions(db: IDBDatabase, sessions: AISession[]): Promise<void> {
if (sessions.length === 0) return;
const transaction = db.transaction(AI_SESSIONS_IDB_SESSION_STORE, 'readwrite');
+19 -1
View File
@@ -1,7 +1,7 @@
/**
* Minimal in-memory IndexedDB stub covering the exact subset used by
* `aiSessionIdbStorage.ts`: open + upgrade (createObjectStore), readonly
* getAll/get, readwrite put/delete/clear, and meta-store records. Not a
* getAll/get/openCursor, readwrite put/delete/clear, and meta-store records. Not a
* general-purpose IDB implementation — extend deliberately if the wrapper
* grows new usage.
*/
@@ -70,6 +70,24 @@ export class FakeObjectStore {
return new FakeRequest(this.records.get(String(key)));
}
openCursor() {
const entries = this.records.values();
type Cursor = { value: unknown; continue: () => void };
const next = (): Cursor | null => {
const entry = entries.next();
if (entry.done) return null;
return {
value: entry.value,
continue: () => queueMicrotask(() => {
request.result = next();
request.onsuccess?.(request);
}),
};
};
const request: FakeRequest<Cursor | null> = new FakeRequest(next());
return request;
}
getAll(): FakeRequest<unknown[]> {
return new FakeRequest(Array.from(this.records.values()));
}
@@ -343,3 +343,23 @@ test('autoTitleSession respects autoLlmTitle=false and removeProvider clears dan
await cleanup();
}
});
test('a queued regeneration preserves a title renamed before its request starts', async () => {
const session = untitledSession();
let calls = 0;
const { capture, cleanup } = await setupHook({
sessions: [session],
providers: [providerA],
activeProviderId: providerA.id,
generateSessionTitle: async () => { calls += 1; return 'Generated'; },
});
try {
await act(async () => { capture.ai!.updateSessionTitle(session.id, 'Manual'); });
const result = await capture.ai!.regenerateSessionTitle(session.id, session.title);
assert.deepEqual(result, { status: 'unchanged', title: 'Manual' });
assert.equal(calls, 0);
assert.equal(capture.sessions[0].title, 'Manual');
} finally {
await cleanup();
}
});
@@ -128,3 +128,64 @@ test('restored workspace enters a blank draft when New Chat is clicked', async (
container.remove();
dom.window.close();
});
test('async clearDraftForScope propagates draft removal to sibling useAIState subscribers', async () => {
const dom = new JSDOM('<!doctype html><html><body></body></html>', {
url: 'http://localhost',
});
Object.defineProperty(globalThis, 'window', { configurable: true, value: dom.window });
Object.defineProperty(globalThis, 'document', { configurable: true, value: dom.window.document });
Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: dom.window.localStorage });
Object.defineProperty(globalThis, 'CustomEvent', { configurable: true, value: dom.window.CustomEvent });
Object.defineProperty(globalThis, 'Event', { configurable: true, value: dom.window.Event });
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, value: true });
let writer: ReturnType<typeof useAIState> | null = null;
let readerDraftText: string | undefined;
function Writer() {
writer = useAIState();
return null;
}
function Reader() {
useAIState();
const state = useAISessionsStore();
readerDraftText = state.draftsByScope[SCOPE_KEY]?.text;
return <span data-draft={readerDraftText ?? ''} />;
}
const container = document.createElement('div');
document.body.appendChild(container);
const root = createRoot(container);
await act(async () => {
root.render(
<>
<Writer />
<Reader />
</>,
);
});
await act(async () => {
writer!.updateDraft(SCOPE_KEY, 'catty', () => ({
text: 'sent message',
agentId: 'catty',
attachments: [],
selectedUserSkillSlugs: [],
updatedAt: Date.now(),
}));
});
await act(async () => {
await Promise.resolve();
writer!.clearDraftForScope(SCOPE_KEY);
});
assert.equal(readerDraftText, undefined);
assert.equal(container.querySelector('span')?.dataset.draft, '');
await act(async () => root.unmount());
container.remove();
dom.window.close();
});
+125 -93
View File
@@ -10,6 +10,7 @@ import {
STORAGE_KEY_AI_AGENT_PROVIDER_MAP,
STORAGE_KEY_AI_AGENT_THINKING_MAP,
STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS,
STORAGE_KEY_UI_LANGUAGE,
} from '../../infrastructure/config/storageKeys';
import type {
AIDraft,
@@ -18,6 +19,7 @@ import type {
HostAIPermission,
ChatMessage,
AISessionScope,
ProviderConfig,
} from '../../infrastructure/ai/types';
import {
activateDraftView,
@@ -106,6 +108,27 @@ import {
} from '../../domain/aiSessionTitle';
import type { generateSessionLlmTitle as GenerateSessionLlmTitleFn } from '../../infrastructure/ai/sessionTitleGeneration';
export type RegenerateSessionTitleResult =
| { status: 'updated'; title: string }
| { status: 'unchanged'; title: string }
| { status: 'busy' }
| { status: 'no-model' }
| { status: 'empty' }
| { status: 'error'; error: string };
function readConfiguredUiLanguage(): string | undefined {
try {
const stored = localStorageAdapter.readString(STORAGE_KEY_UI_LANGUAGE);
if (stored && stored.trim()) return stored.trim();
} catch {
// Ignore storage read errors.
}
if (typeof navigator !== 'undefined' && typeof navigator.language === 'string' && navigator.language.trim()) {
return navigator.language.trim();
}
return undefined;
}
export interface UseAIStateOptions {
/** Optional test injection for one-shot LLM title generation. */
generateSessionTitle?: typeof GenerateSessionLlmTitleFn;
@@ -1010,6 +1033,13 @@ export function useAIState(options?: UseAIStateOptions) {
: (text ? [{ role: 'user' as const, content: text }] : []);
if (sourceMessages.length === 0) return;
const bridge = getAIBridge() as {
aiSyncProviders?: (providers: ProviderConfig[]) => Promise<unknown>;
} | undefined;
if (bridge?.aiSyncProviders && providersRef.current.length > 0) {
await bridge.aiSyncProviders(providersRef.current);
}
const generateTitle = generateSessionTitleRef.current
?? (await import('../../infrastructure/ai/sessionTitleGeneration')).generateSessionLlmTitle;
@@ -1019,6 +1049,7 @@ export function useAIState(options?: UseAIStateOptions) {
config: resolvedTitleConfig,
chatSessionId: sessionId,
signal: requestController.signal,
language: readConfiguredUiLanguage(),
},
);
@@ -1062,11 +1093,18 @@ export function useAIState(options?: UseAIStateOptions) {
* (session-history management: no placeholder gate). The old title is the
* expected value, so a user rename during generation still wins.
*/
const regenerateSessionTitle = useCallback(async (sessionId: string): Promise<void> => {
if (!sessionId || titleAbortControllersRef.current.has(sessionId)) return;
const regenerateSessionTitle = useCallback(async (sessionId: string, expectedTitle?: string): Promise<RegenerateSessionTitleResult> => {
if (!sessionId || titleAbortControllersRef.current.has(sessionId)) {
return { status: 'busy' };
}
const snapshot = latestAISessionsSnapshot ?? sessionsRef.current;
const session = snapshot.find((s) => s.id === sessionId);
if (!session || session.messages.length === 0) return;
if (!session || session.messages.length === 0) {
return { status: 'empty' };
}
if (expectedTitle !== undefined && session.title !== expectedTitle) {
return { status: 'unchanged', title: session.title };
}
const resolvedTitleConfig = resolveEffectiveTitleModelConfig({
titleModel: titleModelRef.current,
providers: providersRef.current,
@@ -1075,10 +1113,19 @@ export function useAIState(options?: UseAIStateOptions) {
agentProviderMap: agentProviderMapRef.current,
agentModelMap: agentModelMapRef.current,
});
if (!resolvedTitleConfig) return;
if (!resolvedTitleConfig) {
return { status: 'no-model' };
}
const controller = new AbortController();
titleAbortControllersRef.current.set(sessionId, controller);
let capturedError: unknown = null;
try {
const bridge = getAIBridge() as {
aiSyncProviders?: (providers: ProviderConfig[]) => Promise<unknown>;
} | undefined;
if (bridge?.aiSyncProviders && providersRef.current.length > 0) {
await bridge.aiSyncProviders(providersRef.current);
}
const generateTitle = generateSessionTitleRef.current
?? (await import('../../infrastructure/ai/sessionTitleGeneration')).generateSessionLlmTitle;
const generated = await generateTitle(
@@ -1088,9 +1135,22 @@ export function useAIState(options?: UseAIStateOptions) {
chatSessionId: sessionId,
signal: controller.signal,
fallbackOnFailure: false,
language: readConfiguredUiLanguage(),
onError: (err) => { capturedError = err; },
},
);
if (controller.signal.aborted || !generated || generated === session.title) return;
if (controller.signal.aborted) {
return { status: 'error', error: 'Aborted' };
}
if (!generated) {
const message = capturedError instanceof Error
? capturedError.message
: (capturedError ? String(capturedError) : 'Model returned an empty title');
return { status: 'error', error: message };
}
if (generated === session.title) {
return { status: 'unchanged', title: generated };
}
const previousTitle = session.title;
const commit = (sessions: AISession[]) => {
const result = applySessionTitleIfCurrent(sessions, sessionId, generated, previousTitle);
@@ -1105,8 +1165,10 @@ export function useAIState(options?: UseAIStateOptions) {
emitAIStateChanged(STORAGE_KEY_AI_SESSIONS);
void result;
}
} catch {
// Title generation never throws; keep the existing title on failure.
return { status: 'updated', title: generated };
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return { status: 'error', error: message };
} finally {
if (titleAbortControllersRef.current.get(sessionId) === controller) {
titleAbortControllersRef.current.delete(sessionId);
@@ -1337,20 +1399,12 @@ export function useAIState(options?: UseAIStateOptions) {
}, [persistSessions]);
const ensureDraftForScope = useCallback((scopeKey: string, agentId: string): void => {
let nextDraftsByScope: DraftsByScope | null = null;
let textOnly = false;
setDraftsByScopeRaw((prev) => {
const next = ensureDraftForScopeState(prev, scopeKey, agentId);
if (next === prev) return prev;
nextDraftsByScope = next;
textOnly = draftsByScopeEqualIgnoringAllComposerText(prev, next);
return next;
});
if (!nextDraftsByScope) return;
setLatestAIDraftsByScopeSnapshot(nextDraftsByScope);
const prev = latestAIDraftsByScopeSnapshot;
const next = ensureDraftForScopeState(prev, scopeKey, agentId);
if (next === prev) return;
const textOnly = draftsByScopeEqualIgnoringAllComposerText(prev, next);
setLatestAIDraftsByScopeSnapshot(next);
setDraftsByScopeRaw(next);
if (textOnly) return;
bumpDraftMutationVersion(scopeKey);
emitAIStateChanged(AI_STATE_CHANGED_DRAFTS_BY_SCOPE);
@@ -1361,31 +1415,24 @@ export function useAIState(options?: UseAIStateOptions) {
fallbackAgentId: string,
updater: (draft: AIDraft) => AIDraft,
): void => {
let nextDraftsByScope: DraftsByScope | null = null;
let textOnly = false;
setDraftsByScopeRaw((prev) => {
const next = updateDraftForScope(
prev,
scopeKey,
fallbackAgentId,
(draft) => {
const updated = updater(draft);
if (updated === draft) return draft;
return {
...updated,
updatedAt: Date.now(),
};
},
);
if (next === prev) return prev;
nextDraftsByScope = next;
textOnly = draftsByScopeEqualIgnoringAllComposerText(prev, next);
return next;
});
if (!nextDraftsByScope) return;
setLatestAIDraftsByScopeSnapshot(nextDraftsByScope);
const prev = latestAIDraftsByScopeSnapshot;
const next = updateDraftForScope(
prev,
scopeKey,
fallbackAgentId,
(draft) => {
const updated = updater(draft);
if (updated === draft) return draft;
return {
...updated,
updatedAt: Date.now(),
};
},
);
if (next === prev) return;
const textOnly = draftsByScopeEqualIgnoringAllComposerText(prev, next);
setLatestAIDraftsByScopeSnapshot(next);
setDraftsByScopeRaw(next);
if (textOnly) return;
bumpDraftMutationVersion(scopeKey);
emitAIStateChanged(AI_STATE_CHANGED_DRAFTS_BY_SCOPE);
@@ -1395,32 +1442,25 @@ export function useAIState(options?: UseAIStateOptions) {
scopeKey: string,
updater: (draft: AIDraft) => AIDraft,
): void => {
let nextDraftsByScope: DraftsByScope | null = null;
let textOnly = false;
const prev = latestAIDraftsByScopeSnapshot;
const currentDraft = prev[scopeKey];
if (!currentDraft) return;
setDraftsByScopeRaw((prev) => {
const currentDraft = prev[scopeKey];
if (!currentDraft) return prev;
const updated = updater(currentDraft);
const nextDraft = updated === currentDraft
? currentDraft
: {
...updated,
updatedAt: Date.now(),
};
if (nextDraft === currentDraft) return prev;
const next = {
...prev,
[scopeKey]: nextDraft,
const updated = updater(currentDraft);
const nextDraft = updated === currentDraft
? currentDraft
: {
...updated,
updatedAt: Date.now(),
};
nextDraftsByScope = next;
textOnly = draftsByScopeEqualIgnoringAllComposerText(prev, next);
return next;
});
if (!nextDraftsByScope) return;
setLatestAIDraftsByScopeSnapshot(nextDraftsByScope);
if (nextDraft === currentDraft) return;
const next: DraftsByScope = {
...prev,
[scopeKey]: nextDraft,
};
const textOnly = draftsByScopeEqualIgnoringAllComposerText(prev, next);
setLatestAIDraftsByScopeSnapshot(next);
setDraftsByScopeRaw(next);
if (textOnly) return;
bumpDraftMutationVersion(scopeKey);
emitAIStateChanged(AI_STATE_CHANGED_DRAFTS_BY_SCOPE);
@@ -1455,38 +1495,30 @@ export function useAIState(options?: UseAIStateOptions) {
}, [setPanelViewByScope]);
const clearDraftForScope = useCallback((scopeKey: string) => {
const currentPanelViewByScope = panelViewByScope;
let nextDraftsByScope: DraftsByScope | null = null;
let nextPanelViewByScope: PanelViewByScope | null = null;
let draftsChanged = false;
let panelViewChanged = false;
setDraftsByScopeRaw((prevDraftsByScope) => {
const next = clearScopeDraftState(
prevDraftsByScope,
currentPanelViewByScope,
scopeKey,
);
draftsChanged = next.draftsByScope !== prevDraftsByScope;
panelViewChanged = next.panelViewByScope !== currentPanelViewByScope;
nextDraftsByScope = next.draftsByScope;
nextPanelViewByScope = next.panelViewByScope;
return draftsChanged ? next.draftsByScope : prevDraftsByScope;
});
const prevDraftsByScope = latestAIDraftsByScopeSnapshot;
const currentPanelViewByScope = latestAIPanelViewByScopeSnapshot ?? panelViewByScope;
const next = clearScopeDraftState(
prevDraftsByScope,
currentPanelViewByScope,
scopeKey,
);
const draftsChanged = next.draftsByScope !== prevDraftsByScope;
const panelViewChanged = next.panelViewByScope !== currentPanelViewByScope;
if (!draftsChanged && !panelViewChanged) return;
bumpDraftMutationVersion(scopeKey);
bumpDraftUploadGeneration(scopeKey);
if (draftsChanged && nextDraftsByScope) {
setLatestAIDraftsByScopeSnapshot(nextDraftsByScope);
if (draftsChanged) {
setLatestAIDraftsByScopeSnapshot(next.draftsByScope);
setDraftsByScopeRaw(next.draftsByScope);
emitAIStateChanged(AI_STATE_CHANGED_DRAFTS_BY_SCOPE);
}
if (panelViewChanged && nextPanelViewByScope) {
setLatestAIPanelViewByScopeSnapshot(nextPanelViewByScope);
setPanelViewByScopeRaw(nextPanelViewByScope);
if (panelViewChanged) {
setLatestAIPanelViewByScopeSnapshot(next.panelViewByScope);
setPanelViewByScopeRaw(next.panelViewByScope);
emitAIStateChanged(AI_STATE_CHANGED_PANEL_VIEW_BY_SCOPE);
}
}, [panelViewByScope]);
@@ -0,0 +1,29 @@
import { useEffect, useRef, useState } from 'react';
import { measureAiSessionStorageUsage, type AiSessionStorageUsage } from './aiSessionIdbStorage';
type Measurement =
| { status: 'idle' | 'loading' | 'error' }
| { status: 'ready'; usage: AiSessionStorageUsage };
export function useAiSessionStorageUsage() {
const [measurement, setMeasurement] = useState<Measurement>({ status: 'idle' });
const active = useRef<AbortController | null>(null);
useEffect(() => () => active.current?.abort(), []);
async function measure() {
if (active.current) return;
const controller = new AbortController();
active.current = controller;
setMeasurement({ status: 'loading' });
try {
const usage = await measureAiSessionStorageUsage(controller.signal);
if (!controller.signal.aborted) setMeasurement({ status: 'ready', usage });
} catch {
if (!controller.signal.aborted) setMeasurement({ status: 'error' });
} finally {
active.current = null;
}
}
return { measurement, measure };
}
+24 -12
View File
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
import { useAppLockChrome } from './appRuntimeBridge';
import { resolvePluginViewWindowScope } from './pluginViewScopes';
import { pluginViewSessions, type PluginViewSnapshot } from './pluginViewSession';
import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
@@ -7,15 +8,17 @@ import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
const initial = (): PluginViewSnapshot => ({ tree: { children: [] }, css: '', loading: true, error: false, settled: true });
export function useHostDrawnPluginView({ viewId, version, slot, active, context, subscribeHidden, unavailable }: {
viewId: string; version: string; slot: string; active: boolean; context: Record<string, unknown>;
subscribeHidden(listener: () => void): () => void; unavailable(): void;
subscribeHidden(listener: (hidden?: boolean) => void): () => void; unavailable(): void;
}) {
const { locked } = useAppLockChrome();
const effectiveActive = active && !locked;
const contextKey = JSON.stringify(context);
const key = JSON.stringify([viewId, version, slot, contextKey]);
const scopeId = typeof window !== 'undefined'
? resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` })
: '';
const sessionKey = scopeId ? JSON.stringify([scopeId, key]) : '';
const cachedSession = active && sessionKey ? pluginViewSessions.peek(sessionKey) : null;
const cachedSession = effectiveActive && sessionKey ? pluginViewSessions.peek(sessionKey) : null;
const [state, setState] = useState<{
key: string;
snapshot: PluginViewSnapshot;
@@ -29,7 +32,7 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
const unavailableRef = useRef(unavailable); unavailableRef.current = unavailable;
const sessionRef = useRef<{ key: string; image(path: string): Promise<string>; send(event: HostDrawnViewEvent): void } | null>(null);
useEffect(() => {
if (!active) {
if (!effectiveActive) {
setHidden(false);
return;
}
@@ -38,22 +41,31 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
const resolvedScopeId = resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` });
try {
const session = pluginViewSessions.acquire(JSON.stringify([resolvedScopeId, key]), bridge, { viewId, scopeId: resolvedScopeId, context: JSON.parse(contextKey) });
sessionRef.current = { key, send: session.send, image: session.image };
const activeHandle = { key, send: session.send, image: session.image };
sessionRef.current = activeHandle;
const update = () => {
const snapshot = session.getSnapshot();
if (snapshot.error) sessionRef.current = null;
setState({ key, snapshot, image: session.image });
};
const stop = session.subscribe(update); update(); setHidden(false);
const stopHidden = subscribeHidden(() => { sessionRef.current = null; setHidden(true); });
const stopHidden = subscribeHidden((nextHidden = true) => {
if (nextHidden) {
sessionRef.current = null;
setHidden(true);
} else {
if (!session.getSnapshot().error) sessionRef.current = activeHandle;
setHidden(false);
}
});
return () => { sessionRef.current = null; stopHidden(); stop(); session.release(); };
} catch { unavailableRef.current(); }
}, [active, contextKey, key, slot, subscribeHidden, viewId]);
}, [effectiveActive, contextKey, key, slot, subscribeHidden, viewId]);
const fallbackLoadImage = useCallback((path: string) => {
const session = sessionRef.current;
return active && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable'));
}, [active, key]);
const hasCurrentState = active
return effectiveActive && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable'));
}, [effectiveActive, key]);
const hasCurrentState = effectiveActive
&& state.key === key
&& (cachedSession !== null ? state.image === cachedSession.image : state.snapshot.error);
const resolvedSnapshot = hasCurrentState
@@ -65,9 +77,9 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
? state.image
: (cachedSession?.image ?? fallbackLoadImage);
const sendEvent = useCallback((event: HostDrawnViewEvent) => {
const session = sessionRef.current; if (active && session?.key === key) session.send(event);
}, [active, key]);
const session = sessionRef.current; if (effectiveActive && session?.key === key) session.send(event);
}, [effectiveActive, key]);
// A newly selected plugin must never receive values from the previous tree,
// even during the render before effect cleanup and the next activation.
return { ...resolvedSnapshot, visible: active && !hidden, loadImage, sendEvent };
return { ...resolvedSnapshot, visible: effectiveActive && !hidden, loadImage, sendEvent };
}
+40 -10
View File
@@ -73,15 +73,31 @@ export function usePluginHostActions() {
if (entry.prompt.request.kind === 'vault.requestHostDraft' && vault.managedSources !== entry.managedSources) throw new Error('Managed sources changed during draft review');
}, [getVault]);
const clearReview = useCallback((entry: Review) => {
if (current.current !== entry) return;
current.current = null;
responding.current = false;
setReview(null);
setRemember(false);
setBusy(false);
setError(false);
}, []);
const fail = useCallback(async (entry: Review) => {
if (current.current !== entry) return;
setError(true);
try {
await netcattyBridge.get()?.respondPluginInteraction?.({
const accepted = await netcattyBridge.get()?.respondPluginInteraction?.({
requestId: entry.prompt.requestId, actionToken: entry.completionToken ?? entry.prompt.actionToken, action: 'fail',
});
} catch { /* A stopped runtime or closed window already invalidates it. */ }
}, []);
if (accepted === false) {
clearReview(entry);
}
} catch {
// A stopped runtime, closed window, or already-settled prompt will never send { closed: true }.
clearReview(entry);
}
}, [clearReview]);
const execute = useCallback(async (entry: Review) => {
const bridge = netcattyBridge.get();
@@ -140,7 +156,8 @@ export function usePluginHostActions() {
entry.claimed = true;
assertCurrent(entry);
await openHostSession(entry.host);
await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
const completed = await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
if (completed === false) clearReview(entry);
return;
}
let action: PluginHostAction;
@@ -161,9 +178,16 @@ export function usePluginHostActions() {
},
connect: openHostSession,
});
await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
const completed = await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
if (completed === false) clearReview(entry);
} catch { await fail(entry); }
}, [assertCurrent, fail, getVault]);
finally {
if (current.current === entry) {
responding.current = false;
setBusy(false);
}
}
}, [assertCurrent, clearReview, fail, getVault]);
useEffect(() => {
const bridge = netcattyBridge.get();
@@ -282,7 +306,7 @@ export function usePluginHostActions() {
if (!entry || responding.current || (action === 'cancel' && entry.claimed)) return;
responding.current = true; setBusy(true); setError(false);
try {
assertCurrent(entry);
if (action !== 'cancel') assertCurrent(entry);
const request = entry.prompt.request;
const selected = request.kind === 'vault.selectHosts' && action === 'submit' ? selectedIds.map((id) => {
const revision = entry.candidateRevisions.get(id);
@@ -296,18 +320,24 @@ export function usePluginHostActions() {
|| request.kind === 'network.stream.tlsConfirm'
);
const effectiveRemember = rememberOverride ?? remember;
await netcattyBridge.require().respondPluginInteraction?.({
const accepted = await netcattyBridge.require().respondPluginInteraction?.({
requestId: entry.prompt.requestId, actionToken: entry.prompt.actionToken, action,
...(selected === undefined ? {} : { resources: selected }),
...(draft === undefined ? {} : { draft }),
...(request.kind === 'vault.requestConnect' && action === 'submit' ? { scriptsRun: entry.scriptsRun } : {}),
...(includeRemember && effectiveRemember ? { remember: true } : {}),
});
} catch { await fail(entry); }
if (accepted === false) {
clearReview(entry);
}
} catch {
if (action === 'cancel') clearReview(entry);
else await fail(entry);
}
finally {
if (current.current === entry && entry.prompt.phase === 'request') { responding.current = false; setBusy(false); }
}
}, [assertCurrent, fail, remember, selectedIds]);
}, [assertCurrent, clearReview, fail, remember, selectedIds]);
return { review, selectedIds, setSelectedIds, remember, setRemember, busy, error, respond };
}
@@ -19,7 +19,7 @@ export function usePluginHostInteractions() {
if (current.current?.requestId !== event.requestId) return;
current.current = null; setPrompt(null);
} else {
if (event.request.kind.startsWith('vault.') || event.request.kind === 'network.stream.connectViaHost') return;
if (event.request.kind.startsWith('vault.') || event.request.kind.startsWith('network.stream.')) return;
current.current = event as UiPrompt;
if (event.request.kind === 'terminal.selection.read' && event.phase === 'request') {
setPrompt(null);
+7 -2
View File
@@ -149,7 +149,12 @@ export function usePluginViewLifecycle({
}, [contributions.loading, contributions.snapshot.plugins]);
useEffect(() => {
if (!requested || activeView?.view.location !== 'tab') return;
if (!requested || viewContributions.loading) return;
if (!resolvedActiveView) {
setRequested(null);
return;
}
if (activeView?.view.location !== 'tab') return;
pluginViewTabStore.open({
pluginId: activeView.plugin.id,
pluginName: activeView.plugin.displayName,
@@ -159,7 +164,7 @@ export function usePluginViewLifecycle({
context: requested.context,
});
setRequested(null);
}, [activeView, requested]);
}, [activeView, requested, resolvedActiveView, viewContributions.loading]);
useEffect(() => {
const stop = pluginViewTabStore.onDidClose(({ tab }) => closePluginViewSessionIfLoaded(tab.viewId));
+3 -2
View File
@@ -766,13 +766,14 @@ export const useSessionState = ({
const preferredTabId = activeTabStore.getPreviousActiveTabId();
const tabOrderSnapshot = tabOrderRef.current;
const sessionsSnapshot = sessionsRef.current;
// Queue removal outside the workspace updater so React retains it when
// lower-priority session updates are rebased after this close.
setSessions(prevSessions => prevSessions.filter(s => s.workspaceId !== workspaceId));
setTabOrder(prevTabOrder => prevTabOrder.filter(id => id !== workspaceId));
setWorkspaces(prevWorkspaces => {
const remainingWorkspaces = prevWorkspaces.filter(w => w.id !== workspaceId);
const remainingSessions = sessionsSnapshot.filter(s => s.workspaceId !== workspaceId);
setSessions(prevSessions => prevSessions.filter(s => s.workspaceId !== workspaceId));
const nextActiveTabId = resolveActiveTabAfterCloseWorkspace({
currentActiveTabId: activeTabStore.getActiveTabId(),
closedWorkspaceId: workspaceId,
@@ -0,0 +1,96 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import React, { useEffect } from 'react';
import { createRoot } from 'react-dom/client';
import { flushSync } from 'react-dom';
import { JSDOM } from 'jsdom';
import { activeTabStore } from './activeTabStore';
import { useSessionState } from './useSessionState';
import type { Host } from '../../domain/models';
const settle = (ms = 20) => new Promise<void>(resolve => setTimeout(resolve, ms));
test('workspace Close does not restore removed panes when a queued session update is rebased', async () => {
const dom = new JSDOM('<div id="root"></div>', { url: 'http://localhost' });
const previous = new Map<string, PropertyDescriptor | undefined>();
for (const [key, value] of Object.entries({
window: dom.window, document: dom.window.document,
localStorage: dom.window.localStorage, CustomEvent: dom.window.CustomEvent,
Event: dom.window.Event,
})) {
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, value });
}
const root = createRoot(document.getElementById('root')!);
let state!: ReturnType<typeof useSessionState>;
let closingId = '';
const mounts = new Map<string, number>();
function Pane({ id }: { id: string }) {
useEffect(() => { mounts.set(id, (mounts.get(id) ?? 0) + 1); }, [id]);
return null;
}
function Probe() {
state = useSessionState({ persistSessionRestore: false });
return <>
<button onClick={() => state.closeWorkspace(closingId)}>Close</button>
{state.sessions.map(s => <Pane key={s.id} id={s.id} />)}
</>;
}
async function connect(name: string, count: number) {
const hosts = Array.from({ length: count }, (_, i) => ({
id: `${name}-${i}`, label: `${name}-${i}`, hostname: 'host.test',
username: 'alice', protocol: 'ssh',
} as Host));
flushSync(() => state.createWorkspaceWithHosts(name, hosts));
await settle();
const workspace = state.workspaces.at(-1)!;
flushSync(() => {
for (const s of state.sessions.filter(s => s.workspaceId === workspace.id)) {
state.updateSessionStatus(s.id, 'connected');
}
});
await settle();
return workspace;
}
async function close(id: string, queueCwd = false) {
closingId = id;
// A cwd observation without pendingInitialCwd queues a no-op update at
// default priority. The discrete Close runs first; React later rebases
// that queue. Wrapping this preparation in act would hide the schedule.
const session = state.sessions.find(s => s.workspaceId === id)!;
if (queueCwd) state.updateSessionRestoreCwd(session.id, '/home/alice');
document.querySelector('button')!.click();
await settle(100);
assert(!state.workspaces.some(w => w.id === id));
assert(!state.sessions.some(s => s.workspaceId === id), 'closed workspace sessions must stay removed after queued updates settle');
}
try {
activeTabStore.setActiveTabId('vault', { recordPrevious: false });
flushSync(() => root.render(<Probe />));
const left = await connect('left', 2);
const target = await connect('target', 6);
const targetIds = state.sessions.filter(s => s.workspaceId === target.id).map(s => s.id);
// Keep the target mounted while other connected workspaces are used.
for (let i = 0; i < 3; i++) await close((await connect(`warm-${i}`, 2)).id);
const right = await connect('right', 2);
await close(right.id);
await close(left.id);
assert.deepEqual(state.sessions.map(s => s.id), targetIds);
assert(state.sessions.every(s => s.status === 'connected'));
assert.equal(activeTabStore.getActiveTabId(), target.id);
await close(target.id, true);
assert.equal(state.sessions.length, 0);
assert.equal(state.workspaces.length, 0);
assert.equal(activeTabStore.getActiveTabId(), 'vault');
assert([...mounts.values()].every(count => count === 1), 'Close must not remount any closed pane');
} finally {
flushSync(() => root.unmount());
activeTabStore.setActiveTabId('vault', { recordPrevious: false });
await settle();
dom.window.close();
for (const [key, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
}
});
+21
View File
@@ -99,14 +99,17 @@ import {
} from '../../infrastructure/config/storageKeys';
import { resolveDefaultUiLocale, resolveSupportedLocale } from '../../infrastructure/config/i18n';
import {
addCustomKeyBindingExtra,
areCustomKeyBindingsEqual,
nextCustomKeyBindingsSyncVersion,
parseCustomKeyBindingsStorageRecord,
removeCustomKeyBindingExtra,
resetCustomKeyBinding,
resolveKeyBindings,
serializeCustomKeyBindingsStorageRecord,
shouldApplyIncomingCustomKeyBindingsRecord,
updateCustomKeyBinding as updateCustomKeyBindingRecord,
updateCustomKeyBindingExtra,
} from '../../domain/customKeyBindings';
import { resolveGlobalTerminalAppearance, idleThemeUserIntent } from '../../domain/terminalAppearanceRuntime';
import { DEFAULT_FONT_SIZE, TERMINAL_FONT_AUTO } from '../../infrastructure/config/fonts';
@@ -2131,6 +2134,21 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
setCustomKeyBindings(prev => resetCustomKeyBinding(prev, bindingId, scheme));
}, [setCustomKeyBindings]);
// Add a secondary chord that triggers the same action as the default binding
const addKeyBindingExtra = useCallback((bindingId: string, scheme: 'mac' | 'pc', newKey: string) => {
setCustomKeyBindings(prev => addCustomKeyBindingExtra(prev, bindingId, scheme, newKey));
}, [setCustomKeyBindings]);
// Re-record an existing secondary chord
const updateKeyBindingExtra = useCallback((bindingId: string, index: number, scheme: 'mac' | 'pc', newKey: string) => {
setCustomKeyBindings(prev => updateCustomKeyBindingExtra(prev, bindingId, index, scheme, newKey));
}, [setCustomKeyBindings]);
// Remove a secondary chord
const removeKeyBindingExtra = useCallback((bindingId: string, index: number) => {
setCustomKeyBindings(prev => removeCustomKeyBindingExtra(prev, bindingId, index));
}, [setCustomKeyBindings]);
// Reset all key bindings to defaults
const resetAllKeyBindings = useCallback(() => {
setCustomKeyBindings({});
@@ -2370,6 +2388,9 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
keyBindings,
customKeyBindings,
updateKeyBinding,
updateKeyBindingExtra,
addKeyBindingExtra,
removeKeyBindingExtra,
resetKeyBinding,
resetAllKeyBindings,
isHotkeyRecording,
+10 -1
View File
@@ -2,7 +2,7 @@ import test from "node:test";
import assert from "node:assert/strict";
import { matchesKeyBinding } from "../../domain/models.ts";
import { isPrimaryModifierWBinding, resolveWindowCommandCloseIntent } from "./windowCommandClose.ts";
import { isNativeCloseTabBound, isPrimaryModifierWBinding, resolveWindowCommandCloseIntent } from "./windowCommandClose.ts";
test("primary-modifier W only belongs to the matching close-tab binding", () => {
assert.equal(isPrimaryModifierWBinding("⌘ + W", matchesKeyBinding, true), true);
@@ -176,3 +176,12 @@ test("Cmd+W closes the window when nothing else is active", () => {
{ kind: "closeWindow" },
);
});
test("native close matches a secondary Command-W for the active Close Tab action", () => {
const primary = { id: "close-tab", action: "closeTab", label: "Close", category: "tabs" as const, mac: "F9", pc: "F9" };
const secondary = { ...primary, id: "close-tab::extra-0", mac: "⌘ + W", pc: "Disabled" };
assert.equal(isNativeCloseTabBound("mac", [primary, secondary], true), true);
assert.equal(isNativeCloseTabBound("pc", [primary, secondary], true), false);
assert.equal(isNativeCloseTabBound("disabled", [primary, secondary], true), false);
assert.equal(isNativeCloseTabBound("mac", [primary, { ...secondary, action: "quickSwitch" }], true), false);
});
+12
View File
@@ -1,3 +1,5 @@
import { matchesKeyBinding, type HotkeyScheme, type KeyBinding } from '../../domain/models/keyBindings';
export type WindowCommandCloseIntent =
| { kind: 'forwardShortcut' }
| { kind: 'closeDialog' }
@@ -25,6 +27,16 @@ export function isPrimaryModifierWBinding(
);
}
export function isNativeCloseTabBound(
scheme: HotkeyScheme,
bindings: readonly KeyBinding[],
isMac: boolean,
): boolean {
return scheme !== 'disabled' && bindings.some((binding) =>
binding.action === 'closeTab' && isPrimaryModifierWBinding(binding[scheme], matchesKeyBinding, isMac)
);
}
interface ResolveWindowCommandCloseIntentInput {
activeTabId: string | null;
editorTabIds: string[];
+1 -1
View File
@@ -309,7 +309,7 @@ const SYNCABLE_TERMINAL_KEYS = [
'inlineImagesEnabled', 'inlineImageKittyEnabled', 'inlineImageSixelEnabled', 'inlineImageIipEnabled',
'autocompleteEnabled', 'autocompleteGhostText', 'autocompletePopupMenu',
'autocompleteDebounceMs', 'autocompleteMinChars', 'autocompleteMaxSuggestions',
'autocompleteHistoryScope',
'autocompleteHistoryScope', 'autocompleteShowSnippets',
] as const;
export const SYNCABLE_SETTING_STORAGE_KEYS = [
+8 -7
View File
@@ -160,14 +160,15 @@
${andIf} ${FileExists} "$oldDesktopLink"
Rename "$oldDesktopLink" "$newDesktopLink"
WinShell::UninstShortcut "$oldDesktopLink"
WinShell::SetLnkAUMI "$newDesktopLink" "${APP_ID}"
System::Call 'Shell32::SHChangeNotify(i 0x8000000, i 0, i 0, i 0)'
${elseIfNot} ${FileExists} "$newDesktopLink"
CreateShortCut "$newDesktopLink" "$appExe" "" "$appExe" 0 "" "" "${APP_DESCRIPTION}"
ClearErrors
WinShell::SetLnkAUMI "$newDesktopLink" "${APP_ID}"
System::Call 'Shell32::SHChangeNotify(i 0x8000000, i 0, i 0, i 0)'
${endif}
; #4672: Always rewrite the .lnk from the newly installed $appExe so in-app
; updates do not leave an existing desktop shortcut with a stale/blank icon.
CreateShortCut "$newDesktopLink" "$appExe" "" "$appExe" 0 "" "" "${APP_DESCRIPTION}"
ClearErrors
WinShell::SetLnkAUMI "$newDesktopLink" "${APP_ID}"
System::Call 'Shell32::SHChangeNotify(i 0x00002000, i 0x0005, w "$newDesktopLink", i 0)'
System::Call 'Shell32::SHChangeNotify(i 0x8000000, i 0, i 0, i 0)'
!macroend
!macro removeDesktopShortcut
+2 -1
View File
@@ -9,6 +9,7 @@ import { Input } from './ui/input';
import { ScrollArea } from './ui/scroll-area';
import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip';
import { SESSION_HISTORY_ROW_CLASSNAMES } from './ai/sessionHistoryLayout';
import { getSessionLastMessageAt } from './ai/globalSessionManagerRows';
import { GlobalSessionSelectionContext } from './ai/sessionHistorySelectionContext';
import { useSessionHistorySearch } from '../application/state/useSessionHistorySearch';
@@ -295,7 +296,7 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
)}
{displayedSessions.map((session) => {
const isActive = session.id === activeSessionId;
const time = new Date(session.updatedAt);
const time = new Date(getSessionLastMessageAt(session));
const timeStr = formatRelativeTime(time, t);
return (
+74 -6
View File
@@ -840,7 +840,9 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
setComposerValueRevision((rev) => rev + 1);
}, []);
const draftGenerationRef = useRef(0);
const clearScopeDraft = useCallback((options?: { keepPendingText?: boolean }) => {
draftGenerationRef.current += 1;
if (!options?.keepPendingText) discardPendingComposerText();
clearDraftForScope(scopeKey);
}, [clearDraftForScope, discardPendingComposerText, scopeKey]);
@@ -2127,7 +2129,9 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
if (!sessionId || !draft || steeringSessionId || !canSteerCurrentTurn) return;
if (!validateNoteMentions(draft.attachments)) return;
const trimmed = draft.text.trim();
const submittedText = draft.text;
const draftGeneration = draftGenerationRef.current;
const trimmed = submittedText.trim();
const attachments = draft.attachments.map((file) => ({
base64Data: file.base64Data,
mediaType: file.mediaType,
@@ -2161,7 +2165,10 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
attachedImages: modelAttachments,
});
if (result.status === 'accepted') {
if (currentDraftRef.current === draft) clearScopeDraft();
if (draftGenerationRef.current !== draftGeneration || activeSessionRef.current?.id !== sessionId) return;
const pending = pendingComposerTextRef.current;
const keepPendingText = pending != null && pending !== submittedText;
clearScopeDraft({ keepPendingText });
return;
}
if (result.status !== 'cancelled') {
@@ -2437,9 +2444,68 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
// Regeneration lives in useAIState so it can reuse the maintainer's
// title-model resolution and atomic title-write helpers.
const handleManagerRegenerateTitle = useCallback((sessionId: string) => {
void regenerateSessionTitle?.(sessionId);
}, [regenerateSessionTitle]);
const handleManagerRegenerateTitle = useCallback(async (sessionId: string) => {
if (!regenerateSessionTitle) return;
const result = await regenerateSessionTitle(sessionId);
if (!result) return;
if (result.status === 'updated') {
toast.success(t('ai.chat.managerRegenerateTitleUpdated'));
} else if (result.status === 'unchanged') {
toast.info(t('ai.chat.managerRegenerateTitleUnchanged'));
} else if (result.status === 'no-model') {
toast.warning(t('ai.chat.managerRegenerateTitleNoModel'));
} else if (result.status === 'error') {
toast.error(t('ai.chat.managerRegenerateTitleFailed').replace('{error}', result.error));
}
}, [regenerateSessionTitle, t]);
const handleManagerRegenerateTitles = useCallback(async (sessionIds: string[]) => {
if (!regenerateSessionTitle || sessionIds.length === 0) return;
let updated = 0;
let unchanged = 0;
let noModel = 0;
let failed = 0;
let lastError = '';
const expectedTitles = new Map(sessionsRef.current.map(session => [session.id, session.title]));
const concurrency = 2;
let cursor = 0;
const workers = Array.from({ length: Math.min(concurrency, sessionIds.length) }, async () => {
while (cursor < sessionIds.length) {
const currentId = sessionIds[cursor];
cursor += 1;
const expectedTitle = expectedTitles.get(currentId);
if (expectedTitle === undefined) continue;
const result = await regenerateSessionTitle(currentId, expectedTitle);
if (!result) continue;
if (result.status === 'updated') updated += 1;
else if (result.status === 'unchanged') unchanged += 1;
else if (result.status === 'no-model') noModel += 1;
else if (result.status === 'error') {
failed += 1;
lastError = result.error;
}
}
});
await Promise.all(workers);
if (noModel === sessionIds.length) {
toast.warning(t('ai.chat.managerRegenerateTitleNoModel'));
return;
}
if (updated > 0 && failed === 0) {
toast.success(t('ai.chat.managerRegenerateTitleBatchDone').replace('{n}', String(updated)));
} else if (updated > 0 && failed > 0) {
toast.warning(
t('ai.chat.managerRegenerateTitleBatchPartial')
.replace('{updated}', String(updated))
.replace('{failed}', String(failed)),
);
} else if (failed > 0) {
toast.error(t('ai.chat.managerRegenerateTitleFailed').replace('{error}', lastError || 'Unknown error'));
} else if (unchanged > 0) {
toast.info(t('ai.chat.managerRegenerateTitleUnchanged'));
}
}, [regenerateSessionTitle, t]);
const handleManagerDeleteMany = useCallback(async (sessionIds: string[]) => {
for (const sessionId of sessionIds) {
@@ -2487,7 +2553,8 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
onRename={handleRenameSession}
onDelete={(sessionId) => { void handleManagerDelete(sessionId); }}
onDeleteMany={(ids) => { void handleManagerDeleteMany(ids); }}
onRegenerateTitle={(sessionId) => { void handleManagerRegenerateTitle(sessionId); }}
onRegenerateTitle={(sessionId) => handleManagerRegenerateTitle(sessionId)}
onRegenerateTitles={(ids) => handleManagerRegenerateTitles(ids)}
onExport={handleManagerExport}
/>
)
@@ -2509,6 +2576,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
handleManagerDelete,
handleManagerDeleteMany,
handleManagerRegenerateTitle,
handleManagerRegenerateTitles,
handleManagerExport,
onFocusAIScopeTarget,
]);
+2 -1
View File
@@ -13,6 +13,7 @@ import type {
import type { AIQuickMessage } from '../infrastructure/ai/quickMessages';
import type { ExecutorContext } from '../infrastructure/ai/cattyAgent/executor';
import type { Host, Snippet, VaultNote } from '../types';
import type { RegenerateSessionTitleResult } from '../application/state/useAIState';
// -------------------------------------------------------------------
// Props
@@ -46,7 +47,7 @@ export interface AIChatSidePanelProps {
updateSessionTitle: (sessionId: string, title: string) => void;
autoTitleSession?: (sessionId: string, text: string, signal?: AbortSignal) => void | Promise<void>;
/** Explicitly regenerate an existing chat title with the configured LLM. */
regenerateSessionTitle?: (sessionId: string) => void | Promise<void>;
regenerateSessionTitle?: (sessionId: string, expectedTitle?: string) => void | Promise<RegenerateSessionTitleResult | void>;
/** Issue #4015 R2: rebind a dangling chat to this panel's scope (panel action, never agent content). */
rebindSessionScope?: (sessionId: string, scope: { type: 'terminal' | 'workspace'; targetId: string; hostIds?: string[] }) => void;
/** Manual durability escape hatch: export the store to a JSON file (returns the path, '' when fixed-path). With `sessionIds`, exports only those chats. */
+283 -1
View File
@@ -4,7 +4,7 @@ import React from "react";
import { useAppLockBridge } from "../application/state/useAppLockBridge.ts";
import { useAppLockState } from "../application/state/useAppLockState.ts";
import { createAppLockGate } from "./AppLockGate.tsx";
import { ReportRendererReady, createAppLockGate } from "./AppLockGate.tsx";
import { APP_LOCK_AUTO_PROMPT_DELAY_MS } from "./AppLockOverlay.tsx";
import { createAppLockBridgeHarness } from "./test-support/createAppLockBridgeHarness.ts";
import {
@@ -1024,3 +1024,285 @@ test("reopen resync does not unlock a gate when runtime is still locked", async
dom.cleanup();
}
});
test("rendererReady waits for lazy route mount and runs after child effects", async () => {
const dom = installDomEnvironment();
const renderer = await createDomRenderer(dom.document);
const events: string[] = [];
const bridgeHarness = createAppLockBridgeHarness({
runtimeState: {
initialized: true,
locked: false,
reason: null,
version: 1,
lastLockedAt: null,
lastUnlockedAt: 1_000,
lastActivityAt: 1_000,
},
});
const baseBridge = bridgeHarness.bridge;
const wrappedBridge: NetcattyBridge = {
...baseBridge,
rendererReady: () => {
events.push("rendererReady");
baseBridge.rendererReady?.();
},
};
const useIsolatedAppLockBridge: typeof useAppLockBridge = () => {
const bridge = useAppLockBridge();
return {
...bridge,
notifyRendererReady: () => {
dom.window.netcatty?.rendererReady?.();
},
};
};
const AppLockGate = createAppLockGate({
useSettingsState: () => ({
uiLanguage: "en",
appLockSettings: {
enabled: false,
timeoutMinutes: 15,
passwordVerifier: null,
},
}) as ReturnType<typeof import("../application/state/useSettingsState.ts").useSettingsState>,
useAppLockState,
useAppLockBridge: useIsolatedAppLockBridge,
});
let resolveLazy!: (mod: { default: React.FC }) => void;
const LazyRoute = React.lazy(
() =>
new Promise<{ default: React.FC }>((resolve) => {
resolveLazy = resolve;
}),
);
const ChildSubscriber: React.FC = () => {
React.useEffect(() => {
events.push("childSubscribed");
}, []);
return React.createElement("div", { id: "lazy-route-content" }, "Mounted");
};
const previousWindowNetcatty = dom.window.netcatty;
dom.window.netcatty = wrappedBridge;
try {
await renderer.render(
React.createElement(AppLockGate, {
notifyRendererReady: true,
children: () =>
React.createElement(
React.Suspense,
{ fallback: React.createElement("div", { id: "lazy-fallback" }, "Loading") },
React.createElement(LazyRoute),
),
}),
);
await flushEffects();
await flushEffects();
// Gate allowed children, but LazyRoute is still suspended -> must NOT signal ready.
assert.equal(dom.document.getElementById("lazy-fallback")?.textContent, "Loading");
assert.equal(bridgeHarness.getRendererReadyCallCount(), 0);
assert.deepEqual(events, []);
await runWithAct(async () => {
resolveLazy({
default: () =>
React.createElement(
React.Fragment,
null,
React.createElement(ChildSubscriber),
React.createElement(ReportRendererReady),
),
});
});
await flushEffects();
await flushEffects();
assert.equal(dom.document.getElementById("lazy-route-content")?.textContent, "Mounted");
assert.equal(bridgeHarness.getRendererReadyCallCount(), 1);
assert.deepEqual(events, ["childSubscribed", "rendererReady"]);
} finally {
dom.window.netcatty = previousWindowNetcatty;
await renderer.unmount();
dom.cleanup();
}
});
test("startup-locked gate withholds rendererReady until unlock and lazy route mount", async () => {
const dom = installDomEnvironment();
const renderer = await createDomRenderer(dom.document);
const bridgeHarness = createAppLockBridgeHarness({
runtimeState: {
initialized: true,
locked: true,
reason: "startup",
version: 1,
lastLockedAt: 1_000,
lastUnlockedAt: null,
lastActivityAt: 1_000,
},
});
const useIsolatedAppLockBridge: typeof useAppLockBridge = () => {
const bridge = useAppLockBridge();
return {
...bridge,
notifyRendererReady: () => {
dom.window.netcatty?.rendererReady?.();
},
};
};
const AppLockGate = createAppLockGate({
useSettingsState: () => ({
uiLanguage: "en",
appLockSettings: {
enabled: true,
timeoutMinutes: 15,
passwordVerifier: {
version: 1,
algorithm: "PBKDF2-SHA256",
iterations: 210000,
salt: "AAAAAAAAAAAAAAAAAAAAAA==",
hash: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
},
},
}) as ReturnType<typeof import("../application/state/useSettingsState.ts").useSettingsState>,
useAppLockState,
useAppLockBridge: useIsolatedAppLockBridge,
});
let resolveLazy!: (mod: { default: React.FC }) => void;
const LazyRoute = React.lazy(
() =>
new Promise<{ default: React.FC }>((resolve) => {
resolveLazy = resolve;
}),
);
const previousWindowNetcatty = dom.window.netcatty;
dom.window.netcatty = bridgeHarness.bridge;
try {
await renderer.render(
React.createElement(AppLockGate, {
notifyRendererReady: true,
children: () =>
React.createElement(
React.Suspense,
{ fallback: React.createElement("div", { id: "locked-lazy-fallback" }, "Loading") },
React.createElement(LazyRoute),
),
}),
);
await flushEffects();
await flushEffects();
// Locked first paint: children withheld, must not notify.
assert.equal(dom.document.getElementById("locked-lazy-fallback"), null);
assert.equal(bridgeHarness.getRendererReadyCallCount(), 0);
// Unlock: children allowed, but LazyRoute still suspended -> still must not notify.
await runWithAct(async () => {
bridgeHarness.setRuntimeState({
locked: false,
reason: null,
lastUnlockedAt: 2_000,
lastActivityAt: 2_000,
});
});
await flushEffects();
await flushEffects();
assert.equal(dom.document.getElementById("locked-lazy-fallback")?.textContent, "Loading");
assert.equal(bridgeHarness.getRendererReadyCallCount(), 0);
// Resolve lazy chunk -> mounts real page and reports ready once.
await runWithAct(async () => {
resolveLazy({
default: () =>
React.createElement(
React.Fragment,
null,
React.createElement("div", { id: "locked-lazy-mounted" }, "Ready"),
React.createElement(ReportRendererReady),
),
});
});
await flushEffects();
await flushEffects();
assert.equal(dom.document.getElementById("locked-lazy-mounted")?.textContent, "Ready");
assert.equal(bridgeHarness.getRendererReadyCallCount(), 1);
} finally {
dom.window.netcatty = previousWindowNetcatty;
await renderer.unmount();
dom.cleanup();
}
});
test("notifyRendererReady=false suppresses ReportRendererReady signals", async () => {
const dom = installDomEnvironment();
const renderer = await createDomRenderer(dom.document);
const bridgeHarness = createAppLockBridgeHarness({
runtimeState: {
initialized: true,
locked: false,
reason: null,
version: 1,
lastLockedAt: null,
lastUnlockedAt: 1_000,
lastActivityAt: 1_000,
},
});
const useIsolatedAppLockBridge: typeof useAppLockBridge = () => {
const bridge = useAppLockBridge();
return {
...bridge,
notifyRendererReady: () => {
dom.window.netcatty?.rendererReady?.();
},
};
};
const AppLockGate = createAppLockGate({
useSettingsState: () => ({
uiLanguage: "en",
appLockSettings: {
enabled: false,
timeoutMinutes: 15,
passwordVerifier: null,
},
}) as ReturnType<typeof import("../application/state/useSettingsState.ts").useSettingsState>,
useAppLockState,
useAppLockBridge: useIsolatedAppLockBridge,
});
const previousWindowNetcatty = dom.window.netcatty;
dom.window.netcatty = bridgeHarness.bridge;
try {
await renderer.render(
React.createElement(AppLockGate, {
notifyRendererReady: false,
children: () =>
React.createElement(
React.Fragment,
null,
React.createElement("div", { id: "opt-out-content" }, "OptOut"),
React.createElement(ReportRendererReady),
),
}),
);
await flushEffects();
await flushEffects();
assert.equal(dom.document.getElementById("opt-out-content")?.textContent, "OptOut");
assert.equal(bridgeHarness.getRendererReadyCallCount(), 0);
} finally {
dom.window.netcatty = previousWindowNetcatty;
await renderer.unmount();
dom.cleanup();
}
});
+39
View File
@@ -5,6 +5,7 @@ import {
shouldDeferExternalActionWhileAppLocked,
shouldNotifyAppLockGateRendererReady,
shouldRenderAppLockGateChildren,
shouldReportAppLockGateRendererReady,
} from "./AppLockGate.tsx";
test("shouldRenderAppLockGateChildren withholds startup-locked route children until unlock", () => {
@@ -140,6 +141,44 @@ test("shouldNotifyAppLockGateRendererReady waits until locked children can mount
);
});
test("shouldReportAppLockGateRendererReady requires gate permission and mounted content", () => {
// Gate allowing children (e.g. Suspense fallback) is not sufficient.
assert.equal(
shouldReportAppLockGateRendererReady({
notifyRendererReady: true,
renderChildren: true,
contentMounted: false,
}),
false,
);
// Locked first paint must not notify even if contentMounted were true.
assert.equal(
shouldReportAppLockGateRendererReady({
notifyRendererReady: true,
renderChildren: false,
contentMounted: true,
}),
false,
);
// Routes that opt out (terminal-popup / editor-window) must not notify.
assert.equal(
shouldReportAppLockGateRendererReady({
notifyRendererReady: false,
renderChildren: true,
contentMounted: true,
}),
false,
);
assert.equal(
shouldReportAppLockGateRendererReady({
notifyRendererReady: true,
renderChildren: true,
contentMounted: true,
}),
true,
);
});
test("shouldDeferExternalActionWhileAppLocked queues actions only while locked", () => {
assert.equal(shouldDeferExternalActionWhileAppLocked({ locked: true }), true);
assert.equal(shouldDeferExternalActionWhileAppLocked({ locked: false }), false);
+74 -22
View File
@@ -1,4 +1,4 @@
import React, { useEffect, useRef, useState } from 'react';
import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react';
import { I18nProvider } from '../application/i18n/I18nProvider';
import { useAppLockBridge } from '../application/state/useAppLockBridge';
@@ -67,6 +67,33 @@ export function shouldNotifyAppLockGateRendererReady(input: {
return input.notifyRendererReady && input.renderChildren;
}
/**
* Lazy route chunks suspend after AppLockGate allows children to render.
* Only emit rendererReady once the gate permits it and the lazy route's real
* content has mounted (so AppSideEffects / IPC listeners are registered).
*/
export function shouldReportAppLockGateRendererReady(input: {
notifyRendererReady: boolean;
renderChildren: boolean;
contentMounted: boolean;
}): boolean {
return shouldNotifyAppLockGateRendererReady(input) && input.contentMounted;
}
const RendererReadyContext = createContext<(() => void) | null>(null);
export function useReportRendererReady(): void {
const reportRendererReady = useContext(RendererReadyContext);
useEffect(() => {
reportRendererReady?.();
}, [reportRendererReady]);
}
export const ReportRendererReady: React.FC = () => {
useReportRendererReady();
return null;
};
/** Queue external actions (e.g. ssh:// deep links) while the app lock is held. */
export function shouldDeferExternalActionWhileAppLocked(input: {
locked: boolean;
@@ -88,6 +115,8 @@ export function createAppLockGate(deps: AppLockGateDeps): React.FC<AppLockGatePr
onAppLockReopen,
} = deps.useAppLockBridge();
const hasRenderedChildrenRef = useRef(false);
const contentMountedRef = useRef(false);
const hasNotifiedRendererReadyRef = useRef(false);
const [reopenSignal, setReopenSignal] = useState(0);
const renderChildren = shouldRenderAppLockGateChildren({
initialized: appLock.initialized,
@@ -99,10 +128,31 @@ export function createAppLockGate(deps: AppLockGateDeps): React.FC<AppLockGatePr
if (renderChildren) {
hasRenderedChildrenRef.current = true;
}
const shouldNotifyRendererReady = shouldNotifyAppLockGateRendererReady({
notifyRendererReady,
renderChildren,
});
const emitRendererReadyIfAllowed = useCallback(() => {
if (hasNotifiedRendererReadyRef.current) return;
if (
!shouldReportAppLockGateRendererReady({
notifyRendererReady,
renderChildren,
contentMounted: contentMountedRef.current,
})
) {
return;
}
hasNotifiedRendererReadyRef.current = true;
try {
performance.mark('netcatty:renderer:ready');
notifyAppLockRendererReady();
} catch {
// ignore
}
}, [notifyAppLockRendererReady, notifyRendererReady, renderChildren]);
const reportRendererReady = useCallback(() => {
contentMountedRef.current = true;
emitRendererReadyIfAllowed();
}, [emitRendererReadyIfAllowed]);
useEffect(() => {
try {
@@ -111,14 +161,14 @@ export function createAppLockGate(deps: AppLockGateDeps): React.FC<AppLockGatePr
splash.classList.add('fade-out');
setTimeout(() => splash.remove(), 200);
}
if (shouldNotifyRendererReady) {
performance.mark('netcatty:renderer:ready');
notifyAppLockRendererReady();
}
} catch {
// ignore
}
}, [notifyAppLockRendererReady, shouldNotifyRendererReady]);
}, []);
useEffect(() => {
emitRendererReadyIfAllowed();
}, [emitRendererReadyIfAllowed]);
useEffect(() => {
const unsubscribe = onAppLockReopen(() => {
@@ -149,18 +199,20 @@ export function createAppLockGate(deps: AppLockGateDeps): React.FC<AppLockGatePr
<I18nProvider locale={settings.uiLanguage}>
<ToastProvider>
<TooltipProvider delayDuration={300}>
{renderChildren ? (
<div
// React 19 supports the HTML inert attribute; when true, the
// subtree is non-interactive and removed from sequential focus.
inert={lockedBackground ? true : undefined}
aria-hidden={lockedBackground || undefined}
className={lockedBackground ? 'h-full pointer-events-none' : 'h-full'}
data-app-lock-background={lockedBackground ? 'locked' : 'unlocked'}
>
{children({ settings, appLock })}
</div>
) : null}
<RendererReadyContext.Provider value={reportRendererReady}>
{renderChildren ? (
<div
// React 19 supports the HTML inert attribute; when true, the
// subtree is non-interactive and removed from sequential focus.
inert={lockedBackground ? true : undefined}
aria-hidden={lockedBackground || undefined}
className={lockedBackground ? 'h-full pointer-events-none' : 'h-full'}
data-app-lock-background={lockedBackground ? 'locked' : 'unlocked'}
>
{children({ settings, appLock })}
</div>
) : null}
</RendererReadyContext.Provider>
<AppLockOverlay
locked={appLock.locked}
reason={appLock.lockReason}
+10
View File
@@ -31,3 +31,13 @@ test("terminal popups wait for app-lock initialization before starting a termina
/allowTerminalStart=\{appLock\.initialized\s*&&\s*!appLock\.locked\}/,
);
});
test("lazy routes gated by AppLockGate report rendererReady after mounting", () => {
const appSource = readComponentSource("../App.tsx");
const settingsPage = readComponentSource("./SettingsPage.tsx");
const trayPanel = readComponentSource("./TrayPanel.tsx");
assert.match(appSource, /\buseReportRendererReady\s*\(\)/);
assert.match(settingsPage, /<ReportRendererReady\s*\/>/);
assert.match(trayPanel, /<ReportRendererReady\s*\/>/);
});
+8 -15
View File
@@ -14,7 +14,7 @@ import { useWindowControls } from "../application/state/useWindowControls";
import { useUpdateCheck } from "../application/state/useUpdateCheck";
import { I18nProvider, useI18n } from "../application/i18n/I18nProvider";
import { sanitizePortForwardingRulesForSync } from "../application/syncPayload";
import type { AppLockGateRenderContext } from "./AppLockGate";
import { ReportRendererReady, type AppLockGateRenderContext } from "./AppLockGate";
import { toast } from "./ui/toast";
import { SettingsTabContent } from "./settings/settings-ui";
import { SettingsFocusProvider, useSettingsFocus } from "./settings/SettingsFocusContext";
@@ -28,8 +28,7 @@ import { setupMcpApprovalBridge } from "../infrastructure/ai/shared/approvalGate
import { usePluginContributions } from "../application/state/usePluginContributions";
import { PluginContributionHost } from "./plugins/PluginContributionHost";
import { PluginPermissionHost } from "./plugins/PluginPermissionHost";
import { matchesKeyBinding } from "../domain/models";
import { isPrimaryModifierWBinding } from "../application/state/windowCommandClose";
import { isNativeCloseTabBound } from "../application/state/windowCommandClose";
import { getSettingsWindowClassName } from "./settings/settingsWindowChrome";
const LazySettingsApplicationTab = lazy(() => import("./SettingsApplicationTab"));
@@ -341,7 +340,7 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
const pluginThemeTokens = useMemo(() => selectPluginThemeTokens(committedAppThemeStyle as Record<string, unknown>), [committedAppThemeStyle]);
const { t } = useI18n();
const { request, clearFocus, openSearch } = useSettingsFocus();
const { notifyRendererReady, closeSettingsWindow, onWindowCommandCloseRequested } = useWindowControls();
const { closeSettingsWindow, onWindowCommandCloseRequested } = useWindowControls();
const { updateState, checkNow, installUpdate, openReleasePage, startDownload, isUpdateDemoMode } = useUpdateCheck({
autoUpdateEnabled: settings.autoUpdateEnabled,
// Install blocked by unsaved editors in the main window — surface a toast
@@ -351,17 +350,7 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
const [activeTab, setActiveTab] = useState("application");
const [mountedTabs, setMountedTabs] = useState(() => new Set(["application"]));
const { available: pluginRuntimeAvailable } = usePluginContributions();
const closeTabKeyStr = useMemo(() => {
if (settings.hotkeyScheme === "disabled") return null;
const binding = settings.keyBindings.find((item) => item.action === "closeTab");
if (!binding) return null;
return settings.hotkeyScheme === "mac" ? binding.mac : binding.pc;
}, [settings.hotkeyScheme, settings.keyBindings]);
const nativeCommandWClosesSettings = isPrimaryModifierWBinding(closeTabKeyStr, matchesKeyBinding, true);
useEffect(() => {
notifyRendererReady();
}, [notifyRendererReady]);
const nativeCommandWClosesSettings = isNativeCloseTabBound(settings.hotkeyScheme, settings.keyBindings, true);
useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
@@ -648,6 +637,9 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
setDisableTerminalFontZoom={settings.setDisableTerminalFontZoom}
keyBindings={settings.keyBindings}
updateKeyBinding={settings.updateKeyBinding}
addKeyBindingExtra={settings.addKeyBindingExtra}
updateKeyBindingExtra={settings.updateKeyBindingExtra}
removeKeyBindingExtra={settings.removeKeyBindingExtra}
resetKeyBinding={settings.resetKeyBinding}
resetAllKeyBindings={settings.resetAllKeyBindings}
setIsHotkeyRecording={settings.setIsHotkeyRecording}
@@ -757,6 +749,7 @@ export default function SettingsPage({
<I18nProvider locale={settings.uiLanguage}>
<SettingsFocusProvider>
<SettingsPageContent settings={settings} appLock={appLock} />
<ReportRendererReady />
</SettingsFocusProvider>
</I18nProvider>
);
+7
View File
@@ -251,4 +251,11 @@ test("native clipboard paste follows SFTP paste shortcut availability", () => {
]),
true,
);
assert.equal(
isSftpNativeClipboardPasteEnabled("pc", [
{ id: "sftp-paste", action: "sftpPaste", label: "Paste", mac: "⌘ + V", pc: "F9", category: "sftp" },
{ id: "sftp-paste::extra-0", action: "sftpPaste", label: "Paste", mac: "Disabled", pc: "Ctrl + V", category: "sftp", extraOf: "sftp-paste" },
]),
true,
);
});
+2 -1
View File
@@ -16,7 +16,7 @@ import { getEffectiveKnownHosts } from "../infrastructure/syncHelpers";
import { PortForwardHostKeyTrayPrompt } from "./port-forwarding";
import { X, Maximize2, ChevronRight, ChevronDown, Power } from "lucide-react";
import { AppLogo } from "./AppLogo";
import type { AppLockGateRenderContext } from "./AppLockGate";
import { ReportRendererReady, type AppLockGateRenderContext } from "./AppLockGate";
const StatusDot: React.FC<{ status: "success" | "warning" | "error" | "neutral"; spinning?: boolean }> = ({
status,
@@ -505,6 +505,7 @@ const TrayPanel: React.FC<{ settings: SettingsState }> = ({ settings }) => {
return (
<I18nProvider locale={settings.uiLanguage}>
<TrayPanelContent />
<ReportRendererReady />
</I18nProvider>
);
};
+4 -1
View File
@@ -82,7 +82,7 @@ test('first keystrokes stay local so IME and Chromium spellcheck cannot stall th
assert.match(source, /autoCapitalize="off"/);
assert.match(source, /nativeEvent\.isComposing/);
assert.match(source, /onCompositionEnd=/);
assert.match(source, /onBlur=\{\(\) => commitComposerText\(readComposerText\(\)\)\}/);
assert.match(source, /onBlur=\{syncUncommittedComposerText\}/);
assert.match(source, /onChangeRef\.current\(textareaRef\.current\?\.value \?\? composerTextRef\.current\)/);
assert.doesNotMatch(source, /onSend\(\);\s*commitComposerText\(''\);/);
assert.match(source, /defaultValue=\{value\}/);
@@ -425,4 +425,7 @@ test('valueRevision clears the uncontrolled textarea even when value stays empty
assert.match(sidePanelSource, /setComposerValueRevision\(\(rev\) => rev \+ 1\)/);
assert.match(sidePanelSource, /inputValueRevision=\{composerValueRevision\}/);
assert.match(contentSource, /valueRevision=\{inputValueRevision\}/);
assert.match(chatInputSource, /useLayoutEffect\(\(\) => \{\s*const revisionChanged = valueRevision !== lastValueRevisionRef\.current/);
assert.match(chatInputSource, /onBlur=\{syncUncommittedComposerText\}/);
assert.match(sidePanelSource, /const keepPendingText = pending != null && pending !== submittedText;/);
});
+12 -5
View File
@@ -43,7 +43,7 @@ import {
type UserSkillSlashOption,
} from '../../infrastructure/ai/quickMessages';
import { SlashCommandPicker } from './SlashCommandPicker';
import React, { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
import { useI18n } from '../../application/i18n/I18nProvider';
import { createPortal } from 'react-dom';
import type { FormEvent } from 'react';
@@ -556,7 +556,7 @@ const ChatInput: React.FC<ChatInputProps> = ({
), []);
const lastValueRevisionRef = useRef(valueRevision);
useEffect(() => {
useLayoutEffect(() => {
const revisionChanged = valueRevision !== lastValueRevisionRef.current;
lastValueRevisionRef.current = valueRevision;
if (!revisionChanged && value === pushedParentTextRef.current) return;
@@ -578,13 +578,20 @@ const ChatInput: React.FC<ChatInputProps> = ({
onChange(next);
}, [onChange, syncHasComposerText]);
const syncUncommittedComposerText = useCallback(() => {
const current = readComposerText();
if (current !== pushedParentTextRef.current) {
commitComposerText(current);
}
}, [commitComposerText, readComposerText]);
const parkedRef = useRef(parked);
useEffect(() => {
const becameParked = parked && !parkedRef.current;
parkedRef.current = parked;
if (!becameParked) return;
commitComposerText(readComposerText());
}, [commitComposerText, parked, readComposerText]);
syncUncommittedComposerText();
}, [parked, syncUncommittedComposerText]);
const onChangeRef = useRef(onChange);
onChangeRef.current = onChange;
@@ -1416,7 +1423,7 @@ const ChatInput: React.FC<ChatInputProps> = ({
setAiComposerComposing(false);
handleInputChange(e.currentTarget.value);
}}
onBlur={() => commitComposerText(readComposerText())}
onBlur={syncUncommittedComposerText}
onKeyDown={handleTextareaKeyDown}
placeholder={placeholder || (isStreaming && canSteer ? t('ai.codex.steer.placeholder') : defaultPlaceholder)}
disabled={composerDisabled}
+54 -1
View File
@@ -7,7 +7,7 @@ import { act, create, type ReactTestRenderer } from "react-test-renderer";
import { I18nProvider } from "../../application/i18n/I18nProvider.tsx";
import type { ChatMessage } from "../../infrastructure/ai/types.ts";
import type { ApprovalRequest } from "../../infrastructure/ai/shared/approvalGate.ts";
import { setupMcpApprovalBridge, type ApprovalRequest } from "../../infrastructure/ai/shared/approvalGate.ts";
import ChatMessageList, {
buildCodexApprovalRenderPlan,
pruneResolvedApprovals,
@@ -629,6 +629,59 @@ test("Codex approval render plan preserves every approval for the same item", ()
);
});
test("plan review shows the complete plan only in its chat and approves once", async t => {
const previousWindow = globalThis.window;
const actGlobal = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
const previousActEnvironment = actGlobal.IS_REACT_ACT_ENVIRONMENT;
type WireReview = { approvalId: string; chatSessionId: string; toolName: string;
args: { plan: string }; interactionKind: 'plan-review'; allowSession: false };
let receive!: (review: WireReview) => void;
let clear!: (event: { approvalIds: string[] }) => void;
const responses: unknown[][] = [];
globalThis.window = {
setTimeout, clearTimeout,
netcatty: {
onMcpApprovalRequest: (cb: typeof receive) => { receive = cb; return () => {}; },
onMcpApprovalCleared: (cb: typeof clear) => { clear = cb; return () => {}; },
respondMcpApproval: async (...args: unknown[]) => {
responses.push(args); return { ok: true, accepted: true };
},
},
} as unknown as Window & typeof globalThis;
actGlobal.IS_REACT_ACT_ENVIRONMENT = true;
const unsubscribe = setupMcpApprovalBridge();
t.after(() => {
clear({ approvalIds: ['mcp_approval_review_1', 'mcp_approval_review_2'] });
unsubscribe();
globalThis.window = previousWindow;
actGlobal.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
});
let renderer!: ReactTestRenderer;
await act(async () => {
renderer = create(
<I18nProvider locale="en"><TooltipProvider>
<ChatMessageList messages={[makeMessage(1)]} activeSessionId="chat-1" isStreaming />
</TooltipProvider></I18nProvider>,
);
for (const index of [1, 2]) receive({
approvalId: `mcp_approval_review_${index}`, chatSessionId: `chat-${index}`,
toolName: 'Grok plan review', args: { plan: `# Proposed steps ${index}\nNo changes yet` },
interactionKind: 'plan-review', allowSession: false,
});
});
const [card, ...otherCards] = renderer.root.findAllByType('section')
.filter(node => node.props['aria-label'] === 'Review implementation plan');
assert.ok(card);
assert.equal(otherCards.length, 0);
assert.match(JSON.stringify(card.findByProps({ tabIndex: 0 }).children), /Proposed steps 1/);
const buttons = card.findAllByType('button');
assert.deepEqual(buttons.map(button => button.children.join('')), ['Keep planning', 'Approve and implement']);
assert.deepEqual(responses, []);
await act(async () => { buttons[1].props.onClick(); });
assert.deepEqual(responses, [['mcp_approval_review_1', true, 'once']]);
await act(async () => { renderer.unmount(); });
});
test('fork is offered only for safe completed replies and hidden while streaming', () => {
const messages: ChatMessage[] = [
{ id: 'u', role: 'user', content: 'hello', timestamp: 1 },
+24 -1
View File
@@ -12,6 +12,7 @@ import { useI18n } from '../../application/i18n/I18nProvider';
import type { AISessionContextCompaction, ChatMessage, ToolCall as AgentToolCall } from '../../infrastructure/ai/types';
import { getForkableMessageIds } from '../../domain/aiSessionFork';
import { Dialog, DialogContent, DialogTitle } from '../ui/dialog';
import { Button } from '../ui/button';
import {
Conversation,
ConversationContent,
@@ -946,6 +947,7 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
{!hideToolCalls && Array.from(pendingApprovals.entries())
.filter(([id, req]) => {
if (!id.startsWith('mcp_approval_')) return false;
if (req.interactionKind === 'plan-review') return false;
// External MCP approvals render in ExternalMcpApprovalsHost so they
// remain visible even when the Catty AI panel is closed.
if (req.chatSessionId === '__external_mcp__') return false;
@@ -977,6 +979,26 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
);
})}
{Array.from(pendingApprovals.entries())
.filter(([, request]) => request.interactionKind === 'plan-review'
&& activeSessionId && request.chatSessionId === activeSessionId)
.map(([id, request]) => (
<section key={id} aria-label={t('ai.planReview.title')} className="min-w-0 space-y-2 rounded-md border border-border bg-card p-3">
<h3 className="text-xs font-semibold">{t('ai.planReview.title')}</h3>
<div tabIndex={0} className="max-h-64 overflow-auto whitespace-pre-wrap break-words rounded-sm bg-muted/50 p-2 text-xs leading-relaxed focus-visible:outline focus-visible:outline-ring">
{typeof request.args.plan === 'string' ? request.args.plan : null}
</div>
<div className="flex flex-wrap justify-end gap-2">
<Button type="button" size="sm" variant="outline" onClick={() => handleReject(id)}>
{t('ai.planReview.keepPlanning')}
</Button>
<Button type="button" size="sm" onClick={() => handleApproveOnce(id)}>
{t('ai.planReview.approveAndImplement')}
</Button>
</div>
</section>
))}
{!hideToolCalls && standaloneCodexApprovals
.map(({ approvalId, request }) => (
<React.Profiler key={approvalId} {...getAIPanelProfilerProps('AIChatPanel.ToolCall.Approval')}>
@@ -1013,7 +1035,8 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
/>
))}
{(Array.from(pendingCodebuddyElicitations.values()) as CodebuddyElicitation[])
.filter((elicitation) => !activeSessionId || elicitation.chatSessionId === activeSessionId)
.filter((elicitation) => elicitation.chatSessionId === activeSessionId
|| (!activeSessionId && elicitation.request.source !== 'grok'))
.map((elicitation) => (
<CodebuddyElicitationCard
key={`${elicitation.elicitationId}:${elicitation.requestInstanceId ?? 0}`}
@@ -51,6 +51,50 @@ test('CodebuddyElicitationCard renders MCP form fields and response actions', ()
assert.doesNotMatch(markup, /role="alert"/);
});
test('the same form displays Grok questions without an action approval', () => {
const markup = renderToStaticMarkup(
<I18nProvider locale="en"><CodebuddyElicitationCard
elicitation={{ elicitationId: 'grok-1', chatSessionId: 'chat-1', request: {
source: 'grok', requestedSchema: {
type: 'object', required: ['q0'], properties: {
q0: { type: 'string', title: 'Which color?', oneOf: [{ const: '0', title: 'Blue' }] },
},
},
} }}
onRespond={async () => {}}
/></I18nProvider>,
);
assert.match(markup, /Grok needs your input/);
assert.match(markup, /Which color\?/);
assert.match(markup, /<option value="variant:0">Blue<\/option>/);
assert.match(markup, /Send answers/);
assert.doesNotMatch(markup, /Decline|Approve|CodeBuddy needs/);
});
test('Grok text questions keep submission disabled for whitespace and cleared answers', async () => {
let renderer!: ReactTestRenderer;
await act(async () => { renderer = create(
<I18nProvider locale="en"><CodebuddyElicitationCard
elicitation={{ elicitationId: 'grok-text', chatSessionId: 'chat-1', request: {
source: 'grok', requestedSchema: { type: 'object', required: ['q0'],
properties: { q0: { type: 'string', title: 'Note', minLength: 1, maxLength: 2000 } } },
} }}
onRespond={async () => {}}
/></I18nProvider>,
); });
const submit = () => renderer.root.findAllByType('button').find(button => button.children.includes('Send answers'))!;
const change = async (value: string) => act(async () => {
renderer.root.findByType('input').props.onChange({ target: { value } });
});
await change('valid');
assert.equal(submit().props.disabled, false);
await change(' \t ');
assert.equal(submit().props.disabled, true);
await change('');
assert.equal(submit().props.disabled, true);
await act(async () => renderer.unmount());
});
test('CodebuddyElicitationCard renders constraint errors and blocks submission', () => {
const markup = renderToStaticMarkup(
<I18nProvider locale="en">
+14 -7
View File
@@ -56,7 +56,12 @@ export const CodebuddyElicitationCard: React.FC<{
const [touchedFields, setTouchedFields] = useState<Set<string>>(() => new Set());
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState('');
const validationIssues = validateCodebuddyElicitationValues(fields, values);
const isGrokQuestion = elicitation.request.source === 'grok';
const formValues = isGrokQuestion
? Object.fromEntries(Object.entries(values).map(([id, value]) =>
[id, typeof value === 'string' ? value.trim() : value]))
: values;
const validationIssues = validateCodebuddyElicitationValues(fields, formValues);
const validationByField = new Map(
validationIssues.map((validationIssue) => [validationIssue.fieldId, validationIssue]),
);
@@ -91,9 +96,11 @@ export const CodebuddyElicitationCard: React.FC<{
<div className="flex items-start gap-2">
<MessageCircleQuestion size={16} className="mt-0.5 shrink-0 text-blue-500" />
<div className="min-w-0">
<div className="text-sm font-medium">{t('ai.codebuddy.elicitation.title')}</div>
<div className="text-sm font-medium">{t(isGrokQuestion
? 'ai.grok.userQuestion.title' : 'ai.codebuddy.elicitation.title')}</div>
<div className="text-xs text-muted-foreground leading-5">
{elicitation.request.message || t('ai.codebuddy.elicitation.description')}
{elicitation.request.message || t(isGrokQuestion
? 'ai.grok.userQuestion.description' : 'ai.codebuddy.elicitation.description')}
</div>
</div>
</div>
@@ -249,23 +256,23 @@ export const CodebuddyElicitationCard: React.FC<{
>
{t('common.cancel')}
</Button>
<Button
{!isGrokQuestion && <Button
variant="outline"
size="sm"
disabled={submitting}
onClick={() => void respond('decline')}
>
{t('ai.codebuddy.elicitation.decline')}
</Button>
</Button>}
<Button
size="sm"
disabled={submitting || !complete}
onClick={() => void respond(
'accept',
buildCodebuddyElicitationContent(values, fields),
buildCodebuddyElicitationContent(formValues, fields),
)}
>
{t('ai.codebuddy.elicitation.accept')}
{t(isGrokQuestion ? 'ai.grok.userQuestion.submit' : 'ai.codebuddy.elicitation.accept')}
</Button>
</div>
</div>
+61 -10
View File
@@ -59,7 +59,9 @@ interface GlobalAIChatSessionManagerProps {
onDelete: (sessionId: string) => void;
onDeleteMany?: (sessionIds: string[]) => void;
/** Re-run LLM title generation for an existing chat (no placeholder gate). */
onRegenerateTitle?: (sessionId: string) => void;
onRegenerateTitle?: (sessionId: string) => void | Promise<unknown>;
/** Batch re-run LLM title generation for multiple selected chats. */
onRegenerateTitles?: (sessionIds: string[]) => void | Promise<unknown>;
onExport: (sessionId: string) => void;
/** Optional controlled selection mode; falls back to SessionHistoryDrawer context. */
selectionMode?: boolean;
@@ -87,6 +89,7 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
onDelete,
onDeleteMany,
onRegenerateTitle,
onRegenerateTitles,
onExport,
selectionMode: controlledSelectionMode,
onSelectionModeChange,
@@ -103,6 +106,7 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
const [renamingSessionId, setRenamingSessionId] = useState<string | null>(null);
const [uncontrolledSelectionMode, setUncontrolledSelectionMode] = useState(false);
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const [regeneratingIds, setRegeneratingIds] = useState<Set<string>>(new Set());
const [renameDraft, setRenameDraft] = useState('');
const renameInputRef = useRef<HTMLInputElement>(null);
@@ -243,9 +247,43 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
else ids.forEach((id) => onDelete(id));
exitSelectionMode();
};
const runSingleRegenerate = useCallback((sessionId: string) => {
if (!onRegenerateTitle) return;
setRegeneratingIds((prev) => {
const next = new Set(prev);
next.add(sessionId);
return next;
});
void Promise.resolve(onRegenerateTitle(sessionId)).finally(() => {
setRegeneratingIds((prev) => {
if (!prev.has(sessionId)) return prev;
const next = new Set(prev);
next.delete(sessionId);
return next;
});
});
}, [onRegenerateTitle]);
const commitBulkRegenerate = () => {
if (!onRegenerateTitle || activeSelectedIds.size === 0) return;
activeSelectedIds.forEach((id) => onRegenerateTitle(id));
if ((!onRegenerateTitles && !onRegenerateTitle) || activeSelectedIds.size === 0) return;
const ids = [...activeSelectedIds];
setRegeneratingIds((prev) => {
const next = new Set(prev);
ids.forEach((id) => next.add(id));
return next;
});
const clearIds = () => {
setRegeneratingIds((prev) => {
const next = new Set(prev);
ids.forEach((id) => next.delete(id));
return next;
});
};
if (onRegenerateTitles) {
void Promise.resolve(onRegenerateTitles(ids)).finally(clearIds);
return;
}
void Promise.all(ids.map((id) => Promise.resolve(onRegenerateTitle!(id)))).finally(clearIds);
};
const getOtherMoveTargets = (session: AISession) =>
@@ -350,14 +388,17 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
{t('ai.chat.managerSelectedCount', { n: String(activeSelectedIds.size) })}
</span>
<div className="ml-auto flex items-center gap-1">
{onRegenerateTitle && (
{(onRegenerateTitles || onRegenerateTitle) && (
<button
type="button"
disabled={activeSelectedIds.size === 0}
disabled={activeSelectedIds.size === 0 || [...activeSelectedIds].some((id) => regeneratingIds.has(id))}
onClick={commitBulkRegenerate}
className="flex items-center gap-1 rounded px-2 py-1 text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 whitespace-nowrap cursor-pointer"
>
<RefreshCw size={12} />
<RefreshCw
size={12}
className={[...activeSelectedIds].some((id) => regeneratingIds.has(id)) ? 'animate-spin' : undefined}
/>
{t('ai.chat.managerRegenerateTitle')}
</button>
)}
@@ -529,8 +570,11 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
</div>
</div>
<div className={SESSION_HISTORY_ROW_CLASSNAMES.meta}>
{regeneratingIds.has(row.session.id) && (
<RefreshCw size={11} className="animate-spin text-muted-foreground/70 shrink-0" />
)}
<span className={SESSION_HISTORY_ROW_CLASSNAMES.time}>
{formatRelativeTime(new Date(row.session.updatedAt), t)}
{formatRelativeTime(new Date(row.lastMessageAt), t)}
</span>
{!selectionMode && (
<Dropdown
@@ -571,14 +615,21 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
{onRegenerateTitle && (
<button
type="button"
disabled={regeneratingIds.has(row.session.id)}
onClick={(e) => {
e.stopPropagation();
setOpenMenuSessionId(null);
onRegenerateTitle(row.session.id);
runSingleRegenerate(row.session.id);
}}
className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground/85 hover:bg-muted cursor-pointer"
className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground/85 hover:bg-muted disabled:opacity-40 cursor-pointer"
>
<RefreshCw size={12} className="shrink-0 text-muted-foreground" />
<RefreshCw
size={12}
className={cn(
'shrink-0 text-muted-foreground',
regeneratingIds.has(row.session.id) && 'animate-spin',
)}
/>
<span>{t('ai.chat.managerRegenerateTitle')}</span>
</button>
)}
@@ -199,6 +199,30 @@ test("workspace member and hidden terminal active pointers are not treated as ju
assert.equal(byId.get("s-hidden-active")!.scopeState, "idle");
});
test("renaming an older chat (bumping updatedAt) keeps its lastMessageAt and sort order", () => {
const input = baseInput();
input.sessions = [
baseSession({
id: "older-renamed",
title: "AI Renamed Older Chat",
createdAt: 1_000,
updatedAt: 999_999,
messages: [{ id: "m1", role: "user", timestamp: 2_000, content: "old question" }],
}),
baseSession({
id: "newer-chat",
title: "Newer Chat",
createdAt: 5_000,
updatedAt: 6_000,
messages: [{ id: "m2", role: "user", timestamp: 6_000, content: "recent question" }],
}),
] as AISession[];
const rows = buildGlobalManagerRows(input);
assert.deepEqual(rows.map((row) => row.session.id), ["newer-chat", "older-renamed"]);
assert.equal(rows[0].lastMessageAt, 6_000);
assert.equal(rows[1].lastMessageAt, 2_000);
});
test("rows sort by updatedAt descending and carry agent labels + counts", () => {
const input = baseInput();
input.sessions = [
+21 -2
View File
@@ -60,6 +60,8 @@ export interface GlobalManagerRow {
*/
canActivate: boolean;
messageCount: number;
/** Timestamp of the last user/assistant message (falls back to createdAt/updatedAt). */
lastMessageAt: number;
}
export interface BuildGlobalManagerRowsInput {
@@ -92,6 +94,21 @@ function resolveHistoricalHostLabel(
return `${names[0]}, ${names[1]} +${names.length - 2}`;
}
export function getSessionLastMessageAt(session: AISession): number {
for (let index = session.messages.length - 1; index >= 0; index--) {
const message = session.messages[index];
if (
(message.role === 'user' || message.role === 'assistant')
&& Number.isFinite(message.timestamp)
) {
return message.timestamp;
}
}
return Number.isFinite(session.createdAt) && session.createdAt > 0
? session.createdAt
: session.updatedAt;
}
export function buildGlobalManagerRows(input: BuildGlobalManagerRowsInput): GlobalManagerRow[] {
const {
sessions,
@@ -212,10 +229,12 @@ export function buildGlobalManagerRows(input: BuildGlobalManagerRowsInput): Glob
activeElsewhereTarget,
canActivate: Boolean(isCurrentView || currentScopeTargetId || isActiveElsewhere),
messageCount: session.messages.length,
lastMessageAt: getSessionLastMessageAt(session),
} satisfies GlobalManagerRow;
})
// Newest first; the filter helpers preserve this order.
.sort((a, b) => b.session.updatedAt - a.session.updatedAt);
// Newest conversation first; renaming updates `updatedAt` for sync but must
// not reorder rows or turn old chats into "just now".
.sort((a, b) => b.lastMessageAt - a.lastMessageAt);
}
export interface GlobalManagerFilter {
@@ -298,3 +298,11 @@ test("implicit workspace auto-resume excludes other-workspace rank-1 chats after
"chat-member",
);
});
test("renaming an older chat preserves its position within a scope", () => {
const scope = { type: "terminal", targetId: "term-1" } as const;
const renamed = { ...createSession("older", scope, 1), updatedAt: 3 };
const recent = createSession("recent", scope, 2);
const history = getScopedHistorySessions([renamed, recent], "terminal", "term-1", [], new Set());
assert.deepEqual(history.map(session => session.id), ["recent", "older"]);
});
+2 -1
View File
@@ -1,4 +1,5 @@
import type { AISession } from '../../infrastructure/ai/types';
import { getSessionLastMessageAt } from './globalSessionManagerRows';
import { getSessionScopeMatchRank } from './sessionScopeMatch';
type HistoryCacheKey = string;
@@ -78,7 +79,7 @@ export function getScopedHistorySessions(
),
}))
.filter(({ matchRank }) => matchRank > 0)
.sort((a, b) => b.matchRank - a.matchRank || b.session.updatedAt - a.session.updatedAt)
.sort((a, b) => b.matchRank - a.matchRank || getSessionLastMessageAt(b.session) - getSessionLastMessageAt(a.session))
.map(({ session }) => session);
scopeCache.set(cacheKey, result);
@@ -337,22 +337,27 @@ export const LocalBackupsPanel: React.FC<LocalBackupsPanelProps> = ({
</>
)}
</div>
<div className="text-xs text-muted-foreground mt-1">
{t('cloudSync.localBackups.counts', {
hosts: String(backup.preview.hostCount),
keys: String(backup.preview.keyCount),
snippets: String(backup.preview.snippetCount),
notes: String(backup.preview.noteCount ?? 0),
})}
</div>
{(backup.preview.aiSessionCount || backup.preview.settingCount) ? (
<div className="text-xs text-muted-foreground mt-0.5">
{t('cloudSync.localBackups.aiCounts', {
sessions: String(backup.preview.aiSessionCount ?? 0),
settings: String(backup.preview.settingCount ?? 0),
<div className="text-xs text-muted-foreground mt-1 flex flex-wrap items-center gap-x-1.5">
<span>
{t('cloudSync.localBackups.counts', {
hosts: String(backup.preview.hostCount),
keys: String(backup.preview.keyCount),
snippets: String(backup.preview.snippetCount),
notes: String(backup.preview.noteCount ?? 0),
})}
</div>
) : null}
</span>
{(backup.preview.aiSessionCount || backup.preview.settingCount) ? (
<>
<span aria-hidden="true">·</span>
<span>
{t('cloudSync.localBackups.aiCounts', {
sessions: String(backup.preview.aiSessionCount ?? 0),
settings: String(backup.preview.settingCount ?? 0),
})}
</span>
</>
) : null}
</div>
</div>
{restoreAllowed && (
<Button
@@ -443,22 +448,27 @@ export const LocalBackupsPanel: React.FC<LocalBackupsPanelProps> = ({
</>
)}
</div>
<div className="text-muted-foreground">
{t('cloudSync.localBackups.counts', {
hosts: String(pendingRestoreBackup.preview.hostCount),
keys: String(pendingRestoreBackup.preview.keyCount),
snippets: String(pendingRestoreBackup.preview.snippetCount),
notes: String(pendingRestoreBackup.preview.noteCount ?? 0),
})}
</div>
{(pendingRestoreBackup.preview.aiSessionCount || pendingRestoreBackup.preview.settingCount) ? (
<div className="text-muted-foreground mt-0.5">
{t('cloudSync.localBackups.aiCounts', {
sessions: String(pendingRestoreBackup.preview.aiSessionCount ?? 0),
settings: String(pendingRestoreBackup.preview.settingCount ?? 0),
<div className="text-muted-foreground flex flex-wrap items-center gap-x-1.5">
<span>
{t('cloudSync.localBackups.counts', {
hosts: String(pendingRestoreBackup.preview.hostCount),
keys: String(pendingRestoreBackup.preview.keyCount),
snippets: String(pendingRestoreBackup.preview.snippetCount),
notes: String(pendingRestoreBackup.preview.noteCount ?? 0),
})}
</div>
) : null}
</span>
{(pendingRestoreBackup.preview.aiSessionCount || pendingRestoreBackup.preview.settingCount) ? (
<>
<span aria-hidden="true">·</span>
<span>
{t('cloudSync.localBackups.aiCounts', {
sessions: String(pendingRestoreBackup.preview.aiSessionCount ?? 0),
settings: String(pendingRestoreBackup.preview.settingCount ?? 0),
})}
</span>
</>
) : null}
</div>
</div>
)}
<DialogFooter className="gap-2 sm:gap-0">
@@ -72,4 +72,12 @@ test("Monaco Cmd+W follows the current close-tab binding", () => {
closeTabBinding: { ...closeTabBinding, mac: "⌘ + E" },
isMac: true,
}), false);
assert.equal(isTextEditorCommandWEnabled({
hotkeyScheme: "mac",
closeTabBindings: [
{ ...closeTabBinding, mac: "⌘ + E" },
{ ...closeTabBinding, id: "close-tab::extra-0", mac: "⌘ + W", extraOf: "close-tab" },
],
isMac: true,
}), true);
});
+17 -11
View File
@@ -188,18 +188,22 @@ export function getTextEditorContentStats(content: string): { lineCount: number;
export function isTextEditorCommandWEnabled({
hotkeyScheme,
closeTabBinding,
closeTabBindings,
isMac,
}: {
hotkeyScheme: HotkeyScheme;
closeTabBinding?: KeyBinding;
/** Every close-tab binding, including secondary chords added in Settings. */
closeTabBindings?: readonly KeyBinding[];
isMac: boolean;
}): boolean {
if (hotkeyScheme === 'disabled' || !closeTabBinding) return false;
return isPrimaryModifierWBinding(
hotkeyScheme === 'mac' ? closeTabBinding.mac : closeTabBinding.pc,
if (hotkeyScheme === 'disabled') return false;
const bindings = closeTabBindings ?? (closeTabBinding ? [closeTabBinding] : []);
return bindings.some((binding) => isPrimaryModifierWBinding(
hotkeyScheme === 'mac' ? binding.mac : binding.pc,
matchesKeyBinding,
isMac,
);
));
}
export const TextEditorPromoteButton: React.FC<{
@@ -265,13 +269,13 @@ const TextEditorPaneInner: React.FC<TextEditorPaneProps> = ({
const handlePasteRef = useRef<() => Promise<void>>(() => Promise.resolve());
const readClipboardTextRef = useRef<() => Promise<string | null>>(() => Promise.resolve(null));
const closeTabBinding = useMemo(
() => keyBindings.find((binding) => binding.action === 'closeTab'),
const closeTabBindings = useMemo(
() => keyBindings.filter((binding) => binding.action === 'closeTab'),
[keyBindings],
);
closeTabCommandWEnabledRef.current = isTextEditorCommandWEnabled({
hotkeyScheme,
closeTabBinding,
closeTabBindings,
isMac: isMacPlatform,
});
@@ -430,17 +434,19 @@ const TextEditorPaneInner: React.FC<TextEditorPaneProps> = ({
// so Cmd/Ctrl+W works even when focus is inside Monaco (which otherwise
// swallows the event). Requires an `onRequestClose` prop from the parent.
const handleDialogKeyDownCapture = useCallback((e: React.KeyboardEvent<HTMLDivElement>) => {
if (hotkeyScheme === 'disabled' || !closeTabBinding || !onRequestClose) return;
if (hotkeyScheme === 'disabled' || closeTabBindings.length === 0 || !onRequestClose) return;
const isMac = hotkeyScheme === 'mac';
const keyStr = isMac ? closeTabBinding.mac : closeTabBinding.pc;
if (!matchesKeyBinding(e.nativeEvent, keyStr, isMac)) return;
const matchesCloseTab = closeTabBindings.some((binding) => (
matchesKeyBinding(e.nativeEvent, isMac ? binding.mac : binding.pc, isMac)
));
if (!matchesCloseTab) return;
e.preventDefault();
e.stopPropagation();
e.nativeEvent.stopPropagation();
onRequestClose();
}, [closeTabBinding, hotkeyScheme, onRequestClose]);
}, [closeTabBindings, hotkeyScheme, onRequestClose]);
// Trigger search dialog
const handleSearch = useCallback(() => {
+6 -3
View File
@@ -58,9 +58,12 @@ export function PluginTerminalSidebarPageHost({ page, tabId, sessionId, getSessi
showHeader?: boolean;
}) {
const { t } = useI18n();
const subscribeHidden = useMemo(() => (hide: () => void) => {
const stopTab = activeTabStore.subscribeSync((id) => { if (id !== tabId) hide(); });
const stopSession = subscribeSidePanelLiveSnapshot(true, () => { if (getSession() !== sessionId) hide(); });
const subscribeHidden = useMemo(() => (onVisibilityChange: (hidden?: boolean) => void) => {
const sync = (tab = activeTabStore.getActiveTabId()) => {
onVisibilityChange(tab !== tabId || getSession() !== sessionId);
};
const stopTab = activeTabStore.subscribeSync((id) => sync(id));
const stopSession = subscribeSidePanelLiveSnapshot(true, () => sync());
return () => { stopTab(); stopSession(); };
}, [getSession, sessionId, tabId]);
return <section className="flex h-full min-h-0 flex-col overflow-hidden" aria-label={`${page.title} — ${page.pluginName}`} data-plugin-terminal-sidebar>
+2 -1
View File
@@ -15,7 +15,8 @@ import { LazyPluginHostDrawnPage, prewarmPluginView } from './LazyPluginHostDraw
import { PluginVaultAISidebar } from './PluginVaultAISidebar';
type VaultPages = ReturnType<typeof usePluginVaultPages>;
const subscribeHidden = (hide: () => void) => activeTabStore.subscribeSync((id) => { if (id !== 'vault') hide(); });
const subscribeHidden = (onVisibilityChange: (hidden?: boolean) => void) =>
activeTabStore.subscribeSync((id) => { onVisibilityChange(id !== 'vault'); });
let nextPluginPromptId = 1;
export function PluginVaultNavigation({ model, collapsed }: { model: VaultPages; collapsed: boolean }) {
@@ -63,6 +63,7 @@ import {
} from "../../../domain/aiSessionMessageCap";
import { WebSearchSettings } from "./ai/WebSearchSettings";
import { QuickMessagesSettings } from "./ai/QuickMessagesSettings";
import { ChatHistoryStorageUsage } from "./ai/ChatHistoryStorageUsage";
import { TitleModelPicker } from "./ai/TitleModelPicker";
import type { AIQuickMessage } from "../../../infrastructure/ai/quickMessages";
import { encryptField } from "../../../infrastructure/persistence/secureFieldAdapter";
@@ -1383,6 +1384,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
<span className="text-xs text-muted-foreground">{t('ai.chatHistory.messageCap.unit')}</span>
</div>
</SettingRow>
<ChatHistoryStorageUsage />
<SettingRow
anchorId="ai-chat-history-auto-llm-title"
label={t('ai.chatHistory.autoLlmTitle')}
+150 -55
View File
@@ -1,5 +1,5 @@
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { Ban, RotateCcw } from "lucide-react";
import { Ban, Plus, RotateCcw, X } from "lucide-react";
import type { HotkeyScheme, KeyBinding } from "../../../domain/models";
import { keyEventToString } from "../../../domain/models";
import { useI18n } from "../../../application/i18n/I18nProvider";
@@ -19,6 +19,9 @@ export default function SettingsShortcutsTab(props: {
setDisableTerminalFontZoom: (enabled: boolean) => void;
keyBindings: KeyBinding[];
updateKeyBinding?: (bindingId: string, scheme: "mac" | "pc", newKey: string) => void;
addKeyBindingExtra?: (bindingId: string, scheme: "mac" | "pc", newKey: string) => void;
updateKeyBindingExtra?: (bindingId: string, index: number, scheme: "mac" | "pc", newKey: string) => void;
removeKeyBindingExtra?: (bindingId: string, index: number) => void;
resetKeyBinding?: (bindingId: string, scheme?: "mac" | "pc") => void;
resetAllKeyBindings: () => void;
setIsHotkeyRecording?: (isRecording: boolean) => void;
@@ -34,6 +37,9 @@ export default function SettingsShortcutsTab(props: {
setDisableTerminalFontZoom,
keyBindings,
updateKeyBinding,
addKeyBindingExtra,
updateKeyBindingExtra,
removeKeyBindingExtra,
resetKeyBinding,
resetAllKeyBindings,
setIsHotkeyRecording,
@@ -42,10 +48,13 @@ export default function SettingsShortcutsTab(props: {
const [recordingBindingId, setRecordingBindingId] = useState<string | null>(null);
const [recordingScheme, setRecordingScheme] = useState<"mac" | "pc" | null>(null);
// index -1 records a new secondary chord, >= 0 re-records an existing one
const [recordingExtra, setRecordingExtra] = useState<{ bindingId: string; index: number } | null>(null);
const cancelRecording = useCallback(() => {
setRecordingBindingId(null);
setRecordingScheme(null);
setRecordingExtra(null);
}, []);
const getSpecialSuffix = useCallback(
@@ -60,6 +69,28 @@ export default function SettingsShortcutsTab(props: {
[keyBindings, hotkeyScheme],
);
const commitShortcut = useCallback((keyString: string) => {
if (!recordingBindingId || !recordingScheme) return;
if (recordingExtra && recordingExtra.bindingId === recordingBindingId) {
if (recordingExtra.index < 0) {
addKeyBindingExtra?.(recordingBindingId, recordingScheme, keyString);
} else {
updateKeyBindingExtra?.(recordingBindingId, recordingExtra.index, recordingScheme, keyString);
}
} else {
updateKeyBinding?.(recordingBindingId, recordingScheme, keyString);
}
cancelRecording();
}, [
addKeyBindingExtra,
cancelRecording,
recordingBindingId,
recordingExtra,
recordingScheme,
updateKeyBinding,
updateKeyBindingExtra,
]);
useEffect(() => {
if (!recordingBindingId || !recordingScheme) return;
@@ -99,15 +130,13 @@ export default function SettingsShortcutsTab(props: {
return;
}
updateKeyBinding?.(recordingBindingId, recordingScheme, fullKeyString);
cancelRecording();
commitShortcut(fullKeyString);
return;
}
if (["Meta", "Control", "Alt", "Shift"].includes(e.key)) return;
const keyString = keyEventToString(e, recordingScheme === "mac");
updateKeyBinding?.(recordingBindingId, recordingScheme, keyString);
cancelRecording();
commitShortcut(keyString);
};
const handleKeyUp = (e: KeyboardEvent) => {
@@ -117,8 +146,7 @@ export default function SettingsShortcutsTab(props: {
e.stopPropagation();
// Wait for release so a modifier-only editor can capture Ctrl+Alt, etc.
if (e.metaKey || e.ctrlKey || e.altKey || e.shiftKey) return;
updateKeyBinding?.(recordingBindingId, recordingScheme, pendingModifierBinding);
cancelRecording();
commitShortcut(pendingModifierBinding);
};
const handleClick = () => {
@@ -137,7 +165,7 @@ export default function SettingsShortcutsTab(props: {
window.removeEventListener("keyup", handleKeyUp, true);
window.removeEventListener("click", handleClick, true);
};
}, [recordingBindingId, recordingScheme, updateKeyBinding, cancelRecording, getSpecialSuffix]);
}, [recordingBindingId, recordingScheme, commitShortcut, cancelRecording, getSpecialSuffix]);
useEffect(() => {
const isRecording = Boolean(recordingBindingId && recordingScheme);
@@ -220,7 +248,7 @@ export default function SettingsShortcutsTab(props: {
</div>
{categories.map((category) => {
const categoryBindings = keyBindings.filter((kb) => kb.category === category);
const categoryBindings = keyBindings.filter((kb) => kb.category === category && !kb.extraOf);
if (categoryBindings.length === 0) return null;
return (
<div key={category}>
@@ -241,23 +269,52 @@ export default function SettingsShortcutsTab(props: {
? currentKey.replace(specialSuffix!, "").trim().replace(/\+\s*$/, "").trim()
: null;
const isRecordingThis = recordingBindingId === binding.id;
const scheme = hotkeyScheme === "mac" ? "mac" : "pc";
const extras = keyBindings
.filter((kb) => kb.extraOf === binding.id)
.map((kb) => ({ binding: kb, index: Number(kb.id.split("::extra-")[1]) }));
const isRecordingThis = recordingBindingId === binding.id && !recordingExtra;
return (
<div key={binding.id} className="flex items-center justify-between px-4 py-2">
<span className="text-sm">{t(`settings.shortcuts.binding.${binding.id}`) !== `settings.shortcuts.binding.${binding.id}` ? t(`settings.shortcuts.binding.${binding.id}`) : binding.label}</span>
<div className="flex items-center gap-2">
{isSpecialBinding ? (
<div className="flex items-center gap-1">
<div key={binding.id}>
<div className="flex items-center justify-between px-4 py-2">
<span className="text-sm">{t(`settings.shortcuts.binding.${binding.id}`) !== `settings.shortcuts.binding.${binding.id}` ? t(`settings.shortcuts.binding.${binding.id}`) : binding.label}</span>
<div className="flex items-center gap-2">
{isSpecialBinding ? (
<div className="flex items-center gap-1">
<button
onClick={(e) => {
e.stopPropagation();
setRecordingExtra(null);
setRecordingBindingId(binding.id);
setRecordingScheme(scheme);
}}
className={cn(
"px-2 py-1 text-xs font-mono rounded border transition-colors min-w-[60px] text-center",
isRecordingThis
? "border-primary bg-primary/10 animate-pulse"
: "border-border hover:border-primary/50",
)}
>
{isRecordingThis
? t("settings.shortcuts.recording")
: modifierPrefix || t("settings.shortcuts.none")}
</button>
<span className="text-xs text-muted-foreground">+</span>
<span className="px-2 py-1 text-xs font-mono rounded border border-border bg-muted/30 text-muted-foreground">
{specialSuffix}
</span>
</div>
) : (
<button
onClick={(e) => {
e.stopPropagation();
setRecordingExtra(null);
setRecordingBindingId(binding.id);
setRecordingScheme(scheme);
}}
className={cn(
"px-2 py-1 text-xs font-mono rounded border transition-colors min-w-[60px] text-center",
"px-2 py-1 text-xs font-mono rounded border transition-colors min-w-[80px] text-center",
isRecordingThis
? "border-primary bg-primary/10 animate-pulse"
: "border-border hover:border-primary/50",
@@ -265,51 +322,89 @@ export default function SettingsShortcutsTab(props: {
>
{isRecordingThis
? t("settings.shortcuts.recording")
: modifierPrefix || t("settings.shortcuts.none")}
: currentKey === "Disabled"
? t("settings.shortcuts.scheme.disabled")
: currentKey || t("settings.shortcuts.scheme.disabled")}
</button>
<span className="text-xs text-muted-foreground">+</span>
<span className="px-2 py-1 text-xs font-mono rounded border border-border bg-muted/30 text-muted-foreground">
{specialSuffix}
</span>
</div>
) : (
)}
{!isSpecialBinding && (
<button
onClick={() => updateKeyBinding?.(binding.id, scheme, "Disabled")}
className="p-1 hover:bg-muted rounded"
aria-label={t("settings.shortcuts.setDisabled")}
>
<Ban size={12} />
</button>
)}
{!isSpecialBinding && (
<button
onClick={(e) => {
e.stopPropagation();
setRecordingExtra({ bindingId: binding.id, index: -1 });
setRecordingBindingId(binding.id);
setRecordingScheme(scheme);
}}
className="p-1 hover:bg-muted rounded"
aria-label={t("settings.shortcuts.addExtra")}
title={t("settings.shortcuts.addExtra")}
>
{recordingExtra?.bindingId === binding.id && recordingExtra.index === -1
? <span role="status" className="px-1 text-xs font-mono text-primary">{t("settings.shortcuts.recording")}</span>
: <Plus size={12} />}
</button>
)}
<button
onClick={(e) => {
e.stopPropagation();
setRecordingBindingId(binding.id);
setRecordingScheme(scheme);
}}
className={cn(
"px-2 py-1 text-xs font-mono rounded border transition-colors min-w-[80px] text-center",
isRecordingThis
? "border-primary bg-primary/10 animate-pulse"
: "border-border hover:border-primary/50",
)}
>
{isRecordingThis
? t("settings.shortcuts.recording")
: currentKey === "Disabled"
? t("settings.shortcuts.scheme.disabled")
: currentKey || t("settings.shortcuts.scheme.disabled")}
</button>
)}
{!isSpecialBinding && (
<button
onClick={() => updateKeyBinding?.(binding.id, scheme, "Disabled")}
onClick={() => resetKeyBinding?.(binding.id, scheme)}
className="p-1 hover:bg-muted rounded"
aria-label={t("settings.shortcuts.setDisabled")}
aria-label={t("settings.shortcuts.resetToDefault")}
>
<Ban size={12} />
<RotateCcw size={12} />
</button>
)}
<button
onClick={() => resetKeyBinding?.(binding.id, scheme)}
className="p-1 hover:bg-muted rounded"
aria-label={t("settings.shortcuts.resetToDefault")}
>
<RotateCcw size={12} />
</button>
</div>
</div>
{extras.map(({ binding: extraBinding, index }) => {
const extraKey = hotkeyScheme === "mac" ? extraBinding.mac : extraBinding.pc;
const isRecordingExtra = recordingBindingId === binding.id
&& recordingExtra?.bindingId === binding.id
&& recordingExtra.index === index;
return (
<div key={extraBinding.id} className="flex items-center justify-between bg-muted/20 px-4 py-2">
<span className="pl-4 text-xs text-muted-foreground">
{t("settings.shortcuts.additional")}
</span>
<div className="flex items-center gap-2">
<button
onClick={(e) => {
e.stopPropagation();
setRecordingExtra({ bindingId: binding.id, index });
setRecordingBindingId(binding.id);
setRecordingScheme(scheme);
}}
className={cn(
"px-2 py-1 text-xs font-mono rounded border transition-colors min-w-[80px] text-center",
isRecordingExtra
? "border-primary bg-primary/10 animate-pulse"
: "border-border hover:border-primary/50",
)}
>
{isRecordingExtra
? t("settings.shortcuts.recording")
: extraKey === "Disabled" || !extraKey
? t("settings.shortcuts.none")
: extraKey}
</button>
<button
onClick={() => removeKeyBindingExtra?.(binding.id, index)}
className="p-1 hover:bg-muted rounded"
aria-label={t("settings.shortcuts.removeExtra")}
title={t("settings.shortcuts.removeExtra")}
>
<X size={12} />
</button>
</div>
</div>
);
})}
</div>
);
})}
@@ -1603,6 +1603,17 @@ function SettingsTerminalTab(props: {
disabled={!terminalSettings.autocompleteEnabled}
/>
</SettingRow>
<SettingRow
anchorId="terminal-autocomplete-show-snippets"
label={t("settings.terminal.autocomplete.showSnippets")}
description={t("settings.terminal.autocomplete.showSnippets.desc")}
>
<Toggle
checked={terminalSettings.autocompleteShowSnippets !== false}
onChange={(v) => updateTerminalSetting("autocompleteShowSnippets", v)}
disabled={!terminalSettings.autocompleteEnabled}
/>
</SettingRow>
</div>
<SectionHeader title={t("settings.terminal.section.passwordPromptAssist")} />
@@ -0,0 +1,42 @@
import React from 'react';
import { useI18n } from '../../../../application/i18n/I18nProvider';
import { useAiSessionStorageUsage } from '../../../../application/state/useAiSessionStorageUsage';
import { Button } from '../../../ui/button';
import { SettingRow } from '../../settings-ui';
function formatSize(bytes: number, locale: string) {
const units = ['byte', 'kilobyte', 'megabyte', 'gigabyte', 'terabyte'];
const unitIndex = bytes > 0 ? Math.min(units.length - 1, Math.floor(Math.log10(bytes) / 3)) : 0;
return new Intl.NumberFormat(locale, {
style: 'unit', unit: units[unitIndex], unitDisplay: 'short', maximumFractionDigits: 1,
}).format(bytes / 1000 ** unitIndex);
}
export function ChatHistoryStorageUsage() {
const { t, resolvedLocale } = useI18n();
const { measurement, measure } = useAiSessionStorageUsage();
let description = t('ai.chatHistory.storageUsage.description');
if (measurement.status === 'error') description = t('ai.chatHistory.storageUsage.error');
if (measurement.status === 'ready') {
const { recordCount, jsonBytes, unmeasuredCount } = measurement.usage;
description = t('ai.chatHistory.storageUsage.result', {
count: recordCount.toLocaleString(resolvedLocale),
size: formatSize(jsonBytes, resolvedLocale),
});
if (unmeasuredCount) {
description += ' ' + t('ai.chatHistory.storageUsage.partial', {
count: unmeasuredCount.toLocaleString(resolvedLocale),
});
}
}
return (
<SettingRow anchorId="ai-chat-history-storage-usage"
label={t('ai.chatHistory.storageUsage')}
description={<span role="status">{description}</span>}
>
<Button size="sm" variant="outline" disabled={measurement.status === 'loading'} onClick={measure}>
{measurement.status === 'loading' ? t('ai.chatHistory.storageUsage.measuring') : t('ai.chatHistory.storageUsage.measure')}
</Button>
</SettingRow>
);
}
@@ -10,6 +10,7 @@ const SEARCH_ICON_PATHS: Record<WebSearchProviderId, string> = {
tavily: "/ai/search/tavily.svg",
exa: "/ai/search/exa.png",
bocha: "/ai/search/bocha.webp",
deepseek: "/ai/providers/deepseek.svg",
zhipu: "/ai/search/zhipu.png",
searxng: "/ai/search/searxng.svg",
};
+7 -4
View File
@@ -97,12 +97,15 @@ export function isSftpNativeClipboardPasteEnabled(
keyBindings: KeyBinding[],
): boolean {
if (hotkeyScheme === "disabled") return false;
const pasteBinding = keyBindings.find((binding) => (
// A secondary paste chord added in Settings can be the native one even when
// the primary chord is not, so every binding for the action has to count.
const pasteBindings = keyBindings.filter((binding) => (
binding.category === "sftp" && binding.action === "sftpPaste"
));
if (!pasteBinding) return false;
const key = hotkeyScheme === "mac" ? pasteBinding.mac : pasteBinding.pc;
return shouldLetNativePasteEventHandleSftpPaste("sftpPaste", key);
return pasteBindings.some((binding) => shouldLetNativePasteEventHandleSftpPaste(
"sftpPaste",
hotkeyScheme === "mac" ? binding.mac : binding.pc,
));
}
export interface SftpClipboardUploadRequest {
@@ -617,9 +617,11 @@ export const useSftpKeyboardShortcuts = ({
if (hotkeyScheme !== "disabled") {
const isMac = hotkeyScheme === "mac";
const searchBinding = keyBindings.find((binding) => binding.action === "searchTerminal");
const searchKey = searchBinding ? (isMac ? searchBinding.mac : searchBinding.pc) : null;
if (searchKey && matchesKeyBinding(e, searchKey, isMac)) {
const matchesSearchHotkey = keyBindings.some((binding) => (
binding.action === "searchTerminal"
&& matchesKeyBinding(e, isMac ? binding.mac : binding.pc, isMac)
));
if (matchesSearchHotkey) {
const { pane } = getFocusedPane();
if (!pane?.connection) return;
+2 -1
View File
@@ -129,13 +129,14 @@ export function TerminalAutocomplete({
hostGroup,
cwdSource: options.cwdSource,
snippets: options.snippets,
showSnippets: options.showSnippets ?? settings?.showSnippets,
maximum: options.maxResults ?? 15,
historyScope: options.historyScope ?? settings?.historyScope,
signal: options.signal,
onLatePathSuggestions: options.onLatePathSuggestions,
locale: resolvedLocale,
});
}, [allowHostStyleGreaterThanPrompt, hostGroup, hostId, hostOs, isPluginCompletionProviderAvailable, protocol, resolvedLocale, sensitiveInputActiveRef, sessionId, settings?.historyScope, status, workspaceId]);
}, [allowHostStyleGreaterThanPrompt, hostGroup, hostId, hostOs, isPluginCompletionProviderAvailable, protocol, resolvedLocale, sensitiveInputActiveRef, sessionId, settings?.historyScope, settings?.showSnippets, status, workspaceId]);
const autocomplete = useTerminalAutocomplete({
termRef,
containerRef,
@@ -210,6 +210,8 @@ export async function getCompletions(
cwdSource?: AutocompleteCwdSource;
/** Custom snippets to surface at the command position */
snippets?: Snippet[];
/** Whether to include matching snippets in completions (default: true). */
showSnippets?: boolean;
/** Which history pool to query (default: current host only). */
historyScope?: AutocompleteHistoryScope;
/**
@@ -376,7 +378,7 @@ export async function getCompletions(
// Push without the early seen-text skip: snippets score above history, so if
// a snippet's label collides with an existing history entry's text, the
// score-sort + final dedup below keeps the snippet (the higher-scored one).
if (options.snippets && options.snippets.length > 0) {
if (options.showSnippets !== false && options.snippets && options.snippets.length > 0) {
const atCommandPosition = ctx.wordIndex === 0;
const argumentNeedle = normalizeHistoryPathPrefix(ctx.currentWord);
const snippetArgumentMatch = !atCommandPosition
@@ -10,6 +10,7 @@ type TerminalAutocompleteSettingFields = {
autocompleteMinChars?: number;
autocompleteMaxSuggestions?: number;
autocompleteHistoryScope?: AutocompleteHistoryScope;
autocompleteShowSnippets?: boolean;
shiftEnterNewlineEnabled?: boolean;
};
@@ -36,6 +37,7 @@ export function resolveTerminalAutocompleteSettings(input: {
minChars: terminalSettings?.autocompleteMinChars ?? 1,
maxSuggestions: terminalSettings?.autocompleteMaxSuggestions ?? 50,
historyScope: terminalSettings?.autocompleteHistoryScope ?? "host",
showSnippets: terminalSettings?.autocompleteShowSnippets !== false,
shiftEnterNewlineEnabled: terminalSettings?.shiftEnterNewlineEnabled ?? true,
};
}
@@ -58,6 +60,7 @@ export function resolveTerminalAutocompleteSettings(input: {
minChars: terminalSettings.autocompleteMinChars ?? 1,
maxSuggestions: terminalSettings.autocompleteMaxSuggestions ?? 50,
historyScope: terminalSettings.autocompleteHistoryScope ?? "host",
showSnippets: terminalSettings.autocompleteShowSnippets !== false,
shiftEnterNewlineEnabled: terminalSettings.shiftEnterNewlineEnabled ?? true,
};
}
@@ -159,3 +159,16 @@ test('terminal completion adapter preserves built-in snippet metadata on duplica
assert.equal(duplicate?.snippet, snippet);
assert.equal(results.filter((item) => item.text === 'deploy').length, 1);
});
test('terminal completion adapter skips built-in snippets when showSnippets is false', async () => {
const snippet = { id: 'deploy', label: 'deploy', command: 'kubectl apply -f .' };
const results = await provideTerminalCompletions(null, {
input: 'dep',
session: { sessionId: 'session-1', protocol: 'ssh', status: 'connected' },
hostOs: 'linux',
snippets: [snippet],
showSnippets: false,
maximum: 8,
});
assert.equal(results.some((item) => item.source === 'snippet'), false);
});
@@ -17,6 +17,8 @@ export interface TerminalCompletionProviderRequest {
hostOs: 'linux' | 'windows' | 'macos';
cwdSource?: AutocompleteCwdSource;
snippets?: Snippet[];
/** Whether to include matching snippets in built-in completions (default: true). */
showSnippets?: boolean;
maximum: number;
/** Which history pool built-in suggestions draw from. */
historyScope?: AutocompleteHistoryScope;
@@ -73,7 +75,8 @@ export async function provideTerminalCompletions(
protocol: request.session.protocol,
cwd: request.session.cwd,
cwdSource: request.cwdSource,
snippets: request.snippets,
snippets: request.showSnippets === false ? undefined : request.snippets,
showSnippets: request.showSnippets,
historyScope: request.historyScope,
onLatePathSuggestions: request.onLatePathSuggestions,
locale: request.locale,
@@ -68,6 +68,8 @@ export interface AutocompleteSettings {
shiftEnterNewlineEnabled: boolean;
/** Which history pool suggestions draw from (current host vs all hosts). */
historyScope: "host" | "global";
/** Whether matching code snippets are included in autocomplete suggestions. */
showSnippets: boolean;
}
export const DEFAULT_AUTOCOMPLETE_SETTINGS: AutocompleteSettings = {
@@ -82,6 +84,7 @@ export const DEFAULT_AUTOCOMPLETE_SETTINGS: AutocompleteSettings = {
fastTypingThresholdMs: 40,
shiftEnterNewlineEnabled: true,
historyScope: "host",
showSnippets: true,
};
/** Max time to poll for shell echo after a pre-echo debounce cycle (#2813). */
@@ -302,6 +305,7 @@ export function useTerminalAutocomplete(
const settings: AutocompleteSettings = {
...rawSettings,
showGhostText: rawSettings.showPopupMenu ? false : rawSettings.showGhostText,
showSnippets: rawSettings.showSnippets !== false,
livePreview: shouldWriteAutocompleteLivePreview(rawSettings.livePreview, isNetworkDevice),
};
@@ -487,6 +491,16 @@ export function useTerminalAutocomplete(
);
}, []);
// Drop visible snippet suggestions if the user turns showSnippets off mid-session.
useEffect(() => {
if (
!settings.showSnippets
&& stateRef.current.suggestions.some((suggestion) => suggestion.source === "snippet")
) {
clearState();
}
}, [settings.showSnippets, clearState]);
/**
* Reconcile the visible popup with the newly edited input synchronously.
* The full provider refresh remains debounced, but rows from the previous
@@ -1165,7 +1179,8 @@ export function useTerminalAutocomplete(
skipPathCompletion: isNetworkDeviceRef.current,
cwd: cwdResolution.cwd,
cwdSource: cwdResolution.source,
snippets: snippetsRef.current,
snippets: settingsRef.current.showSnippets ? snippetsRef.current : undefined,
showSnippets: settingsRef.current.showSnippets,
promptText: prompt.promptText,
allowExternalProviders,
signal: completionController.signal,
@@ -1188,6 +1203,9 @@ export function useTerminalAutocomplete(
if (completionAbortRef.current === completionController) completionAbortRef.current = null;
}
if (completionController.signal.aborted) return;
if (!settingsRef.current.showSnippets) {
completions = completions.filter((completion) => completion.source !== "snippet");
}
if (!settingsRef.current.allowLineReplacement) {
completions = completions.filter((completion) =>
completion.source !== "snippet" && completion.text.startsWith(input),
@@ -0,0 +1,115 @@
import test from "node:test";
import assert from "node:assert/strict";
import { JSDOM } from "jsdom";
import type { Terminal as XTerm } from "@xterm/xterm";
import { GhostTextAddon } from "./GhostTextAddon.ts";
import { getXTermCellDimensions, invalidateCellDimensionCache } from "./xtermUtils.ts";
import {
keepImeCommittedTextThroughModifierKeyDowns,
keepLateImeTextInsert,
} from "../runtime/imeModifierKeyDownSeenGuard.ts";
test("autocomplete on a disposed renderer does not double-send a key (#4539)", async () => {
const dom = new JSDOM("<!doctype html><html><body></body></html>", {
url: "http://localhost/",
pretendToBeVisual: true,
});
const win = dom.window;
win.matchMedia = () => ({
matches: false, media: "", onchange: null,
addEventListener() {}, removeEventListener() {},
addListener() {}, removeListener() {}, dispatchEvent: () => false,
});
win.HTMLCanvasElement.prototype.getContext = () => ({
font: "10px monospace", measureText: () => ({ width: 8 }),
}) as unknown as CanvasRenderingContext2D;
const globals = {
window: win, document: win.document, HTMLElement: win.HTMLElement,
HTMLTextAreaElement: win.HTMLTextAreaElement, Node: win.Node,
Element: win.Element, getComputedStyle: win.getComputedStyle.bind(win),
};
const previousGlobals = Object.fromEntries(
Object.keys(globals).map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]),
);
Object.assign(globalThis, globals);
const errors: unknown[] = [];
win.addEventListener("error", (event) => {
errors.push(event.error);
event.preventDefault();
});
let oldTerm: XTerm | undefined;
let liveTerm: XTerm | undefined;
const ghost = new GhostTextAddon();
try {
const imported = await import("@xterm/xterm");
const Terminal = (imported as { default?: { Terminal: typeof imported.Terminal } }).default?.Terminal
?? imported.Terminal;
const openTerminal = () => {
const parent = win.document.createElement("div");
win.document.body.appendChild(parent);
const term = new Terminal({ cols: 80, rows: 24, cursorBlink: false });
keepImeCommittedTextThroughModifierKeyDowns(term);
keepLateImeTextInsert(term);
term.open(parent);
return term;
};
oldTerm = openTerminal();
ghost.activate(oldTerm);
// Runtime replacement leaves the separately activated autocomplete addon
// holding the old terminal, whose RenderService still exists after dispose.
oldTerm.dispose();
liveTerm = openTerminal();
const sent: string[] = [];
liveTerm.onData((data) => {
// Match createXTermRuntime: write first, then notify autocomplete.
sent.push(data);
ghost.applyKeystroke(data);
});
const textarea = liveTerm.textarea!;
const cancelled: boolean[] = [];
const typeKey = (key: string) => {
const keyCode = key.toUpperCase().charCodeAt(0);
const keydown = new win.KeyboardEvent("keydown", {
key, code: `Key${key.toUpperCase()}`, keyCode,
bubbles: true, cancelable: true,
});
textarea.dispatchEvent(keydown);
cancelled.push(keydown.defaultPrevented);
// JSDOM does not perform native keyboard default actions. Deliver the
// browser's keypress/input sequence only when keydown was not cancelled.
if (!keydown.defaultPrevented) {
textarea.dispatchEvent(new win.KeyboardEvent("keypress", {
key, charCode: key.charCodeAt(0), keyCode: key.charCodeAt(0),
bubbles: true, cancelable: true,
}));
for (const type of ["beforeinput", "input"]) {
textarea.dispatchEvent(new win.InputEvent(type, {
data: key, inputType: "insertText", composed: true, bubbles: true,
}));
}
}
textarea.dispatchEvent(new win.KeyboardEvent("keyup", { key, keyCode, bubbles: true }));
};
typeKey("a");
// The first suggestion arrives asynchronously, as in the reporter's trace.
await Promise.resolve().then(() => ghost.show("apt update -y", "a")).catch((error) => errors.push(error));
typeKey("p");
typeKey("t");
assert.equal(sent.join(""), "apt", "one PTY write per physical key");
assert.deepEqual(cancelled, [true, true, true]);
assert.deepEqual(errors, []);
// With no cached size, the absent renderer also reaches the DOM fallback.
invalidateCellDimensionCache();
assert.deepEqual(getXTermCellDimensions(oldTerm), { width: 8, height: 16 });
} finally {
ghost.dispose();
liveTerm?.dispose();
oldTerm?.dispose();
dom.window.close();
invalidateCellDimensionCache();
for (const [key, descriptor] of Object.entries(previousGlobals)) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
}
});
+10 -2
View File
@@ -33,9 +33,17 @@ function getTermId(term: XTerm): number {
export function getXTermCellDimensions(term: XTerm): CellDimensions {
// Try xterm core renderer API (fast path)
const coreAccess = term as XTerm & {
_core?: { _renderService?: { dimensions?: { css?: { cell?: CellDimensions } } } };
_core?: { _renderService?: {
hasRenderer?: () => boolean;
dimensions?: { css?: { cell?: CellDimensions } };
} };
};
const coreDims = coreAccess._core?._renderService?.dimensions?.css?.cell;
const renderService = coreAccess._core?._renderService;
// The dimensions getter dereferences its renderer even after disposal.
// Avoid throwing through onData before xterm can prevent the key's default.
const coreDims = renderService?.hasRenderer?.() === false
? undefined
: renderService?.dimensions?.css?.cell;
if (coreDims && coreDims.width > 0 && coreDims.height > 0) {
// Update cache while we have a good value
const id = getTermId(term);
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import { getCompletions } from "./autocomplete/completionEngine";
import { DEFAULT_AUTOCOMPLETE_SETTINGS } from "./autocomplete/useTerminalAutocomplete";
import { clearHistory, recordCommand } from "../../application/state/commandHistoryStore";
import { getPinyinCacheStatsForTests, resetPinyinCacheForTests } from "../../domain/searchMatcher";
import type { Snippet } from "../../domain/models";
@@ -115,3 +116,83 @@ test("ASCII argument completion retains compact query prefixes", async () => {
const result = await getCompletions("git pull foo_bar", { snippets, skipPathCompletion: true });
assert.equal(result.find((suggestion) => suggestion.source === "snippet")?.snippet?.id, "compact");
});
test("getCompletions excludes snippet suggestions when showSnippets is false or snippets are omitted", async () => {
const chineseSnippet: Snippet = { id: "zh", label: "部署服务", command: "kubectl apply -f ." };
const dockerSnippet: Snippet = { id: "doc", label: "docker-deploy", command: "docker compose up -d" };
const library: Snippet[] = [deploySnippet, chineseSnippet, dockerSnippet];
// Baseline: when enabled, English and pinyin queries both surface snippet matches.
const enabledEn = await getCompletions("dep", { snippets: library, showSnippets: true });
assert.ok(enabledEn.some((suggestion) => suggestion.source === "snippet"));
const enabledPinyin = await getCompletions("bushu", { snippets: library, showSnippets: true });
assert.ok(enabledPinyin.some((suggestion) => suggestion.source === "snippet" && suggestion.snippet?.id === "zh"));
const enabledArg = await getCompletions("git pull dep", { snippets: library, showSnippets: true });
assert.ok(enabledArg.some((suggestion) => suggestion.source === "snippet"));
// Disabled via showSnippets: false — no snippet matches at command or argument positions,
// including English and pinyin queries, even though the snippet library is present.
for (const input of ["dep", "bushu", "git pull dep"]) {
const disabled = await getCompletions(input, {
snippets: library,
showSnippets: false,
skipPathCompletion: true,
});
assert.equal(
disabled.some((suggestion) => suggestion.source === "snippet"),
false,
`expected no snippet suggestions for ${JSON.stringify(input)} when showSnippets is false`,
);
}
// History suggestions still appear when snippets are hidden, while snippets are excluded.
const hostId = "host-snippet-toggle-test";
const previousLocalStorage = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
const store = new Map<string, string>();
Object.defineProperty(globalThis, "localStorage", {
configurable: true,
value: {
clear: () => store.clear(),
getItem: (key: string) => (store.has(key) ? store.get(key)! : null),
setItem: (key: string, value: string) => { store.set(key, String(value)); },
removeItem: (key: string) => { store.delete(key); },
},
});
try {
clearHistory(hostId);
recordCommand("docker ps -a", hostId, "linux");
const dockerWithSnippets = await getCompletions("doc", {
hostId,
snippets: library,
showSnippets: true,
skipPathCompletion: true,
});
assert.equal(dockerWithSnippets[0]?.source, "snippet");
assert.ok(
dockerWithSnippets.some((suggestion) => suggestion.source === "history" && suggestion.text === "docker ps -a"),
);
const dockerWithoutSnippets = await getCompletions("doc", {
hostId,
snippets: library,
showSnippets: false,
skipPathCompletion: true,
});
assert.equal(dockerWithoutSnippets.some((suggestion) => suggestion.source === "snippet"), false);
assert.equal(dockerWithoutSnippets[0]?.source, "history");
assert.equal(dockerWithoutSnippets[0]?.text, "docker ps -a");
} finally {
clearHistory(hostId);
if (previousLocalStorage) {
Object.defineProperty(globalThis, "localStorage", previousLocalStorage);
} else {
delete (globalThis as Record<string, unknown>).localStorage;
}
}
// Disabled by omitting snippets (how useTerminalAutocomplete gates the option).
for (const snippets of [undefined, [] as Snippet[]]) {
const omitted = await getCompletions("dep", { snippets, skipPathCompletion: true });
assert.equal(omitted.some((suggestion) => suggestion.source === "snippet"), false);
}
});
@@ -1936,6 +1936,8 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
// Unchanged ASCII must keep the Kitty press/release path. Composition
// encoding under report-all emits unidentified CSI 0 u (or associated
// text without a physical key), so ordinary punctuation breaks in TUIs.
// Unchanged CJK glyphs use the literal/composition path below so Kitty
// cannot turn the physical key back into ASCII (#4653).
if (
isUnchangedDeferredImeTextInput(deferredKey, text) &&
deferredKittyEvent &&
@@ -2050,8 +2052,8 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
const armImeTextInputDeferral = (event: KeyboardEvent) => {
clearImeTextInputDeferral();
clearBroadcastLegacyDataPending();
// Wait for insertText (full-width) before keyup; keyup/blur flushes ASCII
// when the IME did not remap the key (English punctuation mode).
// Wait for insertText before keyup; keyup/blur flushes the original glyph
// when the IME did not remap the key.
imeTextInputDeferredKey = event.key;
// Keep the physical key even when the source is not in Kitty mode so
// broadcast targets can still receive paired key events.
@@ -2755,10 +2757,10 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
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
// input listener can commit the real glyph (#2833).
// Sogou/macOS reports ASCII "," before insertText commits "," (#2833);
// macOS Pinyin halfwidth mode reports the inverse (#4653). Returning false
// (without preventDefault) stops xterm/Kitty from sending the keydown glyph
// so the input listener can commit the real glyph.
if (shouldDeferKeyDownForImeTextInput(e)) {
armImeTextInputDeferral(e);
return false;
@@ -43,27 +43,32 @@ test("shouldDeferKeyDownForImeTextInput defers bare ASCII punctuation keydowns",
);
});
test("shouldDeferKeyDownForImeTextInput defers bare CJK punctuation keydowns", () => {
for (const key of [",", "。", ";", "?", "、", ":", "!", "「", "」"]) {
assert.equal(shouldDeferKeyDownForImeTextInput({ type: "keydown", key }), true, key);
}
});
test("shouldDeferKeyDownForImeTextInput leaves non-punctuation keys alone", () => {
for (const key of ["a", "Z", "0", " ", "Enter", "ArrowLeft", "中", "A", "1", " ", ",,"]) {
assert.equal(shouldDeferKeyDownForImeTextInput({ type: "keydown", key }), false, key);
}
});
test("shouldDeferKeyDownForImeTextInput leaves composition and modified keys alone", () => {
assert.equal(
shouldDeferKeyDownForImeTextInput({ type: "keydown", key: ",", keyCode: 229 }),
false,
);
assert.equal(
shouldDeferKeyDownForImeTextInput({ type: "keydown", key: ",", isComposing: true }),
false,
);
assert.equal(
shouldDeferKeyDownForImeTextInput({ type: "keydown", key: ",", ctrlKey: true }),
false,
);
assert.equal(
shouldDeferKeyDownForImeTextInput({ type: "keydown", key: "a", keyCode: 65 }),
false,
);
assert.equal(
shouldDeferKeyDownForImeTextInput({ type: "keypress", key: "," }),
false,
);
for (const key of [",", ","]) {
for (const event of [
{ type: "keydown", key, keyCode: 229 },
{ type: "keydown", key, isComposing: true },
{ type: "keydown", key, ctrlKey: true },
{ type: "keydown", key, altKey: true },
{ type: "keydown", key, metaKey: true },
{ type: "keypress", key },
{ type: "keyup", key },
]) {
assert.equal(shouldDeferKeyDownForImeTextInput(event), false, JSON.stringify(event));
}
}
});
test("shouldBlockKeyPressForImeTextInput only while a deferral is armed", () => {
@@ -391,9 +396,22 @@ test("shouldCommitDeferredImeTextInput accepts insertText payloads while deferre
);
});
test("isUnchangedDeferredImeTextInput detects English punctuation flush", () => {
test("macOS Pinyin halfwidth insertText can commit after a fullwidth keydown (#4653)", () => {
let deferredKey: string | null = null;
const keydown = { type: "keydown", key: ",", code: "Comma", keyCode: 188 };
if (shouldDeferKeyDownForImeTextInput(keydown)) deferredKey = keydown.key;
assert.equal(deferredKey, ",");
assert.equal(
shouldCommitDeferredImeTextInput(deferredKey, { inputType: "insertText", data: "," }),
true,
);
});
test("isUnchangedDeferredImeTextInput detects only ASCII punctuation flush", () => {
assert.equal(isUnchangedDeferredImeTextInput(",", ","), true);
assert.equal(isUnchangedDeferredImeTextInput(",", ","), false);
assert.equal(isUnchangedDeferredImeTextInput(",", ","), false);
assert.equal(isUnchangedDeferredImeTextInput(",", ","), false);
assert.equal(isUnchangedDeferredImeTextInput(null, ","), false);
});
@@ -4,9 +4,11 @@
* an `input`/`insertText` event. xterm.js sends the keydown character and then
* drops the input event because `_keyDownSeen` is set — so the PTY receives
* "," instead of ",".
* macOS Pinyin halfwidth mode does the inverse: keydown reports "," but
* insertText commits "," (#4653).
*
* Defer those keydowns to the following insertText. If no remap arrives before
* keyup/blur, the original ASCII key is flushed. Composition (keyCode 229 /
* keyup/blur, the original key is flushed. Composition (keyCode 229 /
* isComposing) stays on xterm's CompositionHelper path.
*
* The deferral must never outlive the keystroke it was armed for: Windows IMEs
@@ -32,6 +34,9 @@ export type ImeTextInputEvent = Pick<InputEvent, "data" | "inputType">;
/** Printable ASCII punctuation IMEs commonly remap to full-width forms. */
const ASCII_PUNCTUATION_RE = /^[\x21-\x2f\x3a-\x40\x5b-\x60\x7b-\x7e]$/;
/** Single Unicode punctuation glyphs, including CJK and full-width forms. */
const UNICODE_PUNCTUATION_RE = /^\p{P}$/u;
export function isAsciiPunctuationKey(key: string): boolean {
return ASCII_PUNCTUATION_RE.test(key);
}
@@ -42,7 +47,8 @@ export function shouldDeferKeyDownForImeTextInput(
if (event.type !== undefined && event.type !== "keydown") return false;
if (event.isComposing === true || event.keyCode === 229) return false;
if (event.altKey || event.ctrlKey || event.metaKey) return false;
return isAsciiPunctuationKey(event.key);
return isAsciiPunctuationKey(event.key) ||
(event.key.charCodeAt(0) > 0x7f && UNICODE_PUNCTUATION_RE.test(event.key));
}
/** Key releases that carry no keystroke of their own. */
@@ -186,5 +192,5 @@ export function isUnchangedDeferredImeTextInput(
deferredKey: string | null | undefined,
text: string,
): boolean {
return deferredKey != null && text === deferredKey;
return deferredKey != null && isAsciiPunctuationKey(deferredKey) && text === deferredKey;
}
@@ -257,19 +257,79 @@ test("does not arm when the hint cannot be shown (overlay unavailable)", () => {
assert.deepEqual(writes, []);
});
test("a bare Password prompt does not hint until a su command is submitted", () => {
test("a bare Password prompt does not hint until a su or sudo command is submitted", () => {
const { autofill, hints } = make();
autofill.handleOutput("Password: ");
assert.deepEqual(hints, []);
// sudo-armed bare Password: is too generic (mysql/ssh); su-armed is expected
// macOS / Synology sudo uses the same bare prompt as su (#4628).
autofill.armForCommand("sudo whoami");
autofill.handleOutput("Password: ");
assert.deepEqual(hints, []);
assert.deepEqual(hints, [true]);
autofill.armForCommand("su -");
autofill.handleOutput("Password: ");
assert.deepEqual(hints, [true]);
assert.deepEqual(hints, [true, false, true]);
});
for (const command of ["sudo ping 192.168.30.4", "sudo su"]) {
for (const prompt of ["Password:", "密码:"]) {
test(`${command} shows only the host-password hint for ${prompt} (#4628)`, () => {
const hints: boolean[] = [];
const writes: string[] = [];
const autofill = createSudoPasswordAutofill({
mode: "picker",
password: "host-secret",
candidates: [{ id: "other", label: "Other", password: "other-secret" }],
write: (data) => writes.push(data),
onHint: (active) => {
hints.push(active);
return true;
},
onPicker: () => assert.fail("sudo must not open the full keychain picker"),
});
autofill.armForCommand(command);
autofill.handleOutput(prompt);
assert.deepEqual(hints, [true]);
assert.deepEqual(writes, []);
assert.equal(autofill.isPromptPending(), true);
assert.equal(autofill.isPickerPending(), false);
autofill.confirmFill();
assert.deepEqual(writes, ["host-secret\n"]);
});
}
}
test("sudo arms still reject child and remote password prompts (#4628)", () => {
for (const prompt of ["Enter password:", "Password for user postgres:", "user@host's password:"]) {
const { autofill, hints, writes } = make();
autofill.armForCommand("sudo su");
autofill.handleOutput(prompt);
assert.deepEqual(hints, [], prompt);
assert.equal(autofill.isPromptPending(), false, prompt);
autofill.confirmFill();
assert.deepEqual(writes, [], prompt);
}
});
for (const { output, retry } of [
{ output: "\r\nPassword:", retry: false },
{ output: "\r\nSorry, try again.\r\nPassword:", retry: true },
{ output: "\r\n[sudo] password for alice:", retry: true },
]) {
test(`sudo bare prompt after confirmFill requires auth retry evidence: ${JSON.stringify(output)} (#4628)`, () => {
const { autofill, hints, writes } = make();
autofill.armForCommand("sudo su");
autofill.handleOutput("Password:");
assert.equal(autofill.isPromptPending(), true);
autofill.confirmFill();
assert.deepEqual(writes, ["secret\n"]);
autofill.handleOutput(output);
assert.equal(autofill.isPromptPending(), retry);
assert.deepEqual(hints, retry ? [true, false, true] : [true, false]);
autofill.confirmFill();
assert.deepEqual(writes, retry ? ["secret\n", "secret\n"] : ["secret\n"]);
});
}
test("an explicit [sudo] prompt hints without a recorded sudo command", () => {
// The [sudo] tag is sudo-specific, so we hint even when arming didn't fire —
// manual typing's recordedCommand is flaky (#1281/#1284), and the hint only
@@ -350,9 +350,10 @@ export const createSudoPasswordAutofill = (_options: {
if (!armActive) return false;
// su always prompts with a bare Password: line (not Enter password / DB).
if (armedKind === "su") return isSuBarePasswordPrompt(line);
// sudo: only sudo-scoped prompts, never generic "Enter password:" from
// child programs when sudo credentials are already cached.
if (armedKind === "sudo") return isSudoScopedBarePasswordPrompt(line);
// macOS / Synology / BSD sudo uses the same short bare Password: as su (#4628).
if (armedKind === "sudo") {
return isSudoScopedBarePasswordPrompt(line) || isSuBarePasswordPrompt(line);
}
return false;
};
@@ -442,8 +443,8 @@ export const createSudoPasswordAutofill = (_options: {
dismissedWhileArmed = false;
armedKind = null;
}
// Explicit "[sudo] …" always; su arm accepts bare Password:; sudo arm only
// accepts sudo-scoped bare prompts (not generic Enter password from mysql).
// Explicit "[sudo] …" always; su/sudo arms accept short bare Password:;
// sudo also accepts scoped prompts (not generic Enter password from mysql).
const isPrompt = isArmedPromptLine(lastLine, armActive);
if (pending) {
// The prompt moved on: a new line arrived and the latest line is no
@@ -30,6 +30,7 @@ function createContext(input: string) {
fastTypingThresholdMs: 40,
shiftEnterNewlineEnabled: true,
historyScope: "host",
showSnippets: true,
};
const context = {
settingsRef: ref(settings),
@@ -28,6 +28,7 @@ test("keeps autocomplete enabled for shell-like terminal protocols", () => {
minChars: 2,
maxSuggestions: 6,
historyScope: "global",
showSnippets: true,
shiftEnterNewlineEnabled: false,
},
);
@@ -57,6 +58,7 @@ test("keeps network-device autocomplete popup but disables live preview (#1193)"
minChars: 1,
maxSuggestions: 8,
historyScope: "host",
showSnippets: true,
shiftEnterNewlineEnabled: true,
},
);
@@ -109,6 +111,7 @@ test("keeps serial autocomplete available but disables input-line preview and re
minChars: 1,
maxSuggestions: 8,
historyScope: "host",
showSnippets: true,
livePreview: false,
allowLineReplacement: false,
shiftEnterNewlineEnabled: true,
@@ -154,3 +157,33 @@ test('unknown systems do not rewrite the command line while retaining suggestion
assert.equal(settings?.allowLineReplacement, false);
}
});
test("defaults showSnippets to true and preserves explicit false across protocols", () => {
assert.equal(
resolveTerminalAutocompleteSettings({
protocol: "ssh",
terminalSettings: { autocompleteEnabled: true },
})?.showSnippets,
true,
);
assert.equal(
resolveTerminalAutocompleteSettings({
protocol: "ssh",
terminalSettings: { autocompleteShowSnippets: false },
})?.showSnippets,
false,
);
assert.equal(
resolveTerminalAutocompleteSettings({
protocol: "serial",
terminalSettings: { autocompleteShowSnippets: false },
})?.showSnippets,
false,
);
assert.equal(
resolveTerminalAutocompleteSettings({
protocol: "serial",
})?.showSnippets,
true,
);
});
@@ -99,3 +99,17 @@ test("clearing command history restores the live-preview baseline (#3632)", () =
);
});
test("useTerminalAutocomplete excludes snippets when showSnippets is false", () => {
const source = readFileSync(
fileURLToPath(new URL("./autocomplete/useTerminalAutocomplete.ts", import.meta.url)),
"utf8",
);
assert.match(source, /showSnippets: true,/);
assert.match(source, /snippets: settingsRef\.current\.showSnippets \? snippetsRef\.current : undefined,/);
assert.match(source, /showSnippets: settingsRef\.current\.showSnippets,/);
assert.match(
source,
/if \(!settingsRef\.current\.showSnippets\) \{\s*completions = completions\.filter\(\(completion\) => completion\.source !== "snippet"\);/,
);
});
@@ -0,0 +1,40 @@
# Runtime user questions
Use a runtime's native question callback when one is available. Keep its
protocol mapping in the driver; share the application form and its lifecycle.
An answer provides context, not permission. It does not change Auto, Confirm,
or Observer. Never turn a question into tool approval or collect credentials
through the question card.
## Integration points
For an in-app SDK turn, the registry can pass `requestUserForm(form, signal)`
into a driver. The form uses the existing SDK elicitation create/complete events
and the existing renderer form. The broker generates the response ID and
accepts a single answer from the originating renderer. It clears the form on
cancel, timeout, or turn teardown; delegated turns do not receive this hook.
Timeout and cancellation do not fabricate an answer. The existing SDK answer
privacy handling applies to renderer replies.
Grok ACP uses this hook for `_x.ai/ask_user_question`. The adapter checks the
ACP session, presents bounded text or offered choices, and maps answers back
to Grok's native `accepted` or `cancelled` response. Observer can answer a question
without obtaining write permission. Grok's rich previews and special Plan
interview actions are out of scope for this adapter.
## Compatibility snapshot
| Runtime | Native path and Netcatty status |
| --- | --- |
| Grok ACP | Native question request wired through the shared SDK form. Streaming-JSON is not changed. |
| Codex App Server | Already wired in Netcatty: `item/tool/requestUserInput` is separately routed, answered and tested. A future renderer consolidation can reuse the form without changing the Codex protocol. |
| Codex SDK | Do not assume App Server support applies to the SDK path. No equivalent reverse request is wired here. |
| Claude Agent SDK | Native `AskUserQuestion` input and SDK tool callbacks exist. Netcatty currently disallows this tool in the Claude UI driver; a separate adapter must own its answer path before removing the block. |
| CodeBuddy | Existing SDK MCP elicitation is already wired to this form. That does not enable its separate native `AskUserQuestion` tool. |
| GitHub Copilot SDK | SDK offers `onUserInputRequest` for `ask_user`; the current driver does not register it. A separate adapter is needed. |
| Cursor CLI, OpenCode, MiMo | This change does not wire or verify a native question path. Inspect the specific runtime before advertising support. |
No public MCP capability or configuration is added. A future optional
MCP question tool should require an identified, live chat and opt-in, expose
only bounded non-secret inputs, and apply rate/cancellation limits. A Skill can
guide when to ask, but does not grant permissions or implement a reply channel.
+65
View File
@@ -0,0 +1,65 @@
# In-app agent interactions
Some agent runtimes need a decision from the user before they can continue.
For example, Grok submits its implementation plan for review through its
`_x.ai/exit_plan_mode` ACP request. Approving the plan is not the same as
granting another tool permission.
## First integration: Grok plan review
- The Grok ACP adapter validates the runtime session and maps the specific
reverse request to a chat-scoped `plan-review` interaction. The existing
main-process approval bridge and renderer approval store handle delivery,
response correlation, and cancellation.
- **Approve and implement** grants only this plan review. **Keep planning**
declines the review without granting permission to implement. There is no
persistent or session-wide grant. A running turn can be stopped normally;
a timeout or missing review channel never approves the plan.
- Generic tool auto-approval does not answer this request. Observer and
delegated turns cannot approve implementation through this path.
- Unsupported reverse requests return an explicit method-not-found error.
The adapter never guesses an answer or converts a different request into a
successful permission grant.
The bridge and interaction discriminator are internal extension points, not
public MCP or plugin APIs. A new runtime should map only requests it
recognizes, preserve the runtime's decision semantics, and use the existing
chat/turn lifecycle rather than opening a second approval channel.
Today the Grok driver calls
`requestApprovalFromRenderer(label, { plan }, chatSessionId, context)`
with `interactionKind: "plan-review"`, `requireFreshApproval: true`, and the
turn's abort signal in `context`. A literal `true` maps to Grok's
`approved` outcome; a negative or unavailable decision maps to `cancelled`
while the turn is still live. A terminated turn cannot receive a late approval.
This boolean interface is suitable for a decision, not for answers with values.
## Follow-up design (not implemented)
Add a second concrete runtime integration first, such as a structured user
question with typed choices. Share the request envelope and lifecycle across
runtimes, but keep separate response types for questions, plan reviews, tool
approvals, and authentication. Approval IDs should be host-owned, bound to
the originating agent session and turn, and settled once. A reply from a
stale turn or a different chat must not be accepted.
Keep interaction policy separate from action permission:
- **Auto:** keep approving eligible tool actions as before; still ask the user
when an explicitly supported runtime request requires a human decision.
- **Confirm:** keep normal action approvals and also present required runtime
interactions. A plan approval does not replace any required action approval.
- **Observer:** allow informational questions if enabled, but do not approve
implementation or grant write permissions.
If an unattended run cannot obtain a required answer, report that it could
not continue. Do not silently approve or try to override a runtime restriction.
A per-agent preference for optional questions can be considered separately from
required runtime interactions.
An MCP capability could later let supported agents without a native interaction
protocol ask a structured, chat-scoped question, subject to capability
advertising, session validation, and rate limits. Start with a bounded
question, not a generic authorization endpoint. A Skill can tell an agent when
to invoke the capability, but cannot implement the UI, suspend execution, or
grant permissions on its own.
+74
View File
@@ -2,14 +2,17 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import {
addCustomKeyBindingExtra,
areCustomKeyBindingsEqual,
nextCustomKeyBindingsSyncVersion,
parseCustomKeyBindingsStorageRecord,
removeCustomKeyBindingExtra,
resetCustomKeyBinding,
resolveKeyBindings,
serializeCustomKeyBindingsStorageRecord,
shouldApplyIncomingCustomKeyBindingsRecord,
updateCustomKeyBinding,
updateCustomKeyBindingExtra,
} from './customKeyBindings.ts';
import { DEFAULT_KEY_BINDINGS, keyStringToKeyboardEvent } from './models/keyBindings.ts';
import { checkAppShortcut } from '../application/state/useGlobalHotkeys.ts';
@@ -258,3 +261,74 @@ test('resetting the last side removes the binding entry entirely', () => {
assert.deepEqual(next, {});
});
test('secondary chord resolves to the same action as its base binding', () => {
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
'open-local': { extra: [{ pc: 'Ctrl + Shift + E' }] },
});
assert.equal(shortcut('Ctrl + Shift + E', bindings), 'openLocal');
assert.equal(shortcut('\u2318 + L', bindings, true), 'openLocal');
const extra = bindings.find(binding => binding.extraOf === 'open-local');
assert.equal(extra?.id, 'open-local::extra-0');
assert.equal(extra?.mac, 'Disabled');
});
test('a secondary chord evicts the default that already occupies it', () => {
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
'open-local': { extra: [{ pc: 'Ctrl + Shift + T' }] },
});
assert.equal(bindings.find(binding => binding.id === 'reopen-closed-tab')?.pc, 'Disabled');
assert.equal(shortcut('Ctrl + Shift + T', bindings), 'openLocal');
assert.equal(shortcut('\u2318 + Shift + T', bindings, true), 'reopenClosedTab');
});
test('adding, re-recording, and removing a secondary chord', () => {
let custom = addCustomKeyBindingExtra({}, 'open-local', 'mac', '\u2318 + Shift + E');
assert.deepEqual(custom, { 'open-local': { extra: [{ mac: '\u2318 + Shift + E' }] } });
custom = addCustomKeyBindingExtra(custom, 'open-local', 'pc', 'Ctrl + Shift + E');
assert.deepEqual(custom['open-local'].extra, [
{ mac: '\u2318 + Shift + E' },
{ pc: 'Ctrl + Shift + E' },
]);
custom = updateCustomKeyBindingExtra(custom, 'open-local', 1, 'pc', 'Ctrl + Shift + R');
assert.deepEqual(custom['open-local'].extra?.[1], { pc: 'Ctrl + Shift + R' });
custom = removeCustomKeyBindingExtra(custom, 'open-local', 0);
assert.deepEqual(custom['open-local'].extra, [{ pc: 'Ctrl + Shift + R' }]);
});
test('resetting one scheme keeps the secondary chords', () => {
const custom = addCustomKeyBindingExtra(
{ 'open-local': { mac: '\u2318 + Shift + E' } },
'open-local',
'pc',
'Ctrl + Shift + E',
);
const reset = resetCustomKeyBinding(custom, 'open-local', 'mac');
assert.deepEqual(reset['open-local'], { extra: [{ pc: 'Ctrl + Shift + E' }] });
});
test('removing the last secondary chord leaves the base override intact', () => {
const custom = addCustomKeyBindingExtra(
{ 'open-local': { pc: 'Ctrl + L' } },
'open-local',
'mac',
'\u2318 + Shift + E',
);
const reset = removeCustomKeyBindingExtra(custom, 'open-local', 0);
assert.deepEqual(reset['open-local'], { pc: 'Ctrl + L', extra: undefined });
});
test('removing the only secondary chord drops the now-empty override', () => {
const custom = addCustomKeyBindingExtra({}, 'open-local', 'pc', 'Ctrl + Shift + E');
const reset = removeCustomKeyBindingExtra(custom, 'open-local', 0);
assert.deepEqual(reset, {});
});
+89 -2
View File
@@ -1,4 +1,32 @@
import { CustomKeyBindings, KeyBinding } from './models';
import { CustomKeyBindings, KeyBinding, KeyBindingExtra } from './models';
/**
* Expand user-added secondary chords into real bindings so the dispatcher can
* match them like any default shortcut. `extraOf` keeps them out of the
* one-row-per-action settings list.
*/
const expandExtraKeyBindings = (
bindings: readonly KeyBinding[],
customKeyBindings: CustomKeyBindings,
): KeyBinding[] => {
const expanded: KeyBinding[] = [];
for (const binding of bindings) {
expanded.push(binding);
(customKeyBindings[binding.id]?.extra ?? []).forEach((extra, index) => {
const mac = extra.mac ?? 'Disabled';
const pc = extra.pc ?? 'Disabled';
if (mac === 'Disabled' && pc === 'Disabled') return;
expanded.push({
...binding,
id: `${binding.id}::extra-${index}`,
mac,
pc,
extraOf: binding.id,
});
});
}
return expanded;
};
export const resolveKeyBindings = (
defaults: readonly KeyBinding[],
@@ -20,6 +48,12 @@ export const resolveKeyBindings = (
if (customKeyBindings[binding.id]?.[scheme] != null && binding[scheme] !== 'Disabled') {
customChords[binding.category === 'sftp' ? 'sftp' : 'app'].add(binding[scheme]);
}
for (const extra of customKeyBindings[binding.id]?.extra ?? []) {
const chord = extra[scheme];
if (chord && chord !== 'Disabled') {
customChords[binding.category === 'sftp' ? 'sftp' : 'app'].add(chord);
}
}
}
// SFTP has its own input context; all other categories share the app-level handler.
@@ -32,7 +66,7 @@ export const resolveKeyBindings = (
));
}
return merged;
return expandExtraKeyBindings(merged, customKeyBindings);
};
const SYNC_VERSION_FIELD = '__netcattySyncVersion';
@@ -166,3 +200,56 @@ export const resetCustomKeyBinding = (
[bindingId]: nextBinding,
};
};
const writeExtras = (
bindings: CustomKeyBindings,
bindingId: string,
extra: KeyBindingExtra[],
): CustomKeyBindings => {
const existing = bindings[bindingId] ?? {};
const next = { ...existing, extra: extra.length > 0 ? extra : undefined };
if (next.mac == null && next.pc == null && !next.extra) {
const { [bindingId]: _removed, ...rest } = bindings;
return rest;
}
return {
...bindings,
[bindingId]: next,
};
};
/** Append a secondary chord to a binding without touching its primary chord. */
export const addCustomKeyBindingExtra = (
bindings: CustomKeyBindings,
bindingId: string,
scheme: 'mac' | 'pc',
newKey: string,
): CustomKeyBindings => {
const extra = [...(bindings[bindingId]?.extra ?? [])];
extra.push({ [scheme]: newKey } as KeyBindingExtra);
return writeExtras(bindings, bindingId, extra);
};
export const updateCustomKeyBindingExtra = (
bindings: CustomKeyBindings,
bindingId: string,
index: number,
scheme: 'mac' | 'pc',
newKey: string,
): CustomKeyBindings => {
const extra = [...(bindings[bindingId]?.extra ?? [])];
if (index < 0 || index >= extra.length) return bindings;
extra[index] = { ...extra[index], [scheme]: newKey };
return writeExtras(bindings, bindingId, extra);
};
export const removeCustomKeyBindingExtra = (
bindings: CustomKeyBindings,
bindingId: string,
index: number,
): CustomKeyBindings => {
const extra = [...(bindings[bindingId]?.extra ?? [])];
if (index < 0 || index >= extra.length) return bindings;
extra.splice(index, 1);
return writeExtras(bindings, bindingId, extra);
};
+33 -1
View File
@@ -8,10 +8,26 @@ export interface KeyBinding {
mac: string; // e.g., '⌘+1', '⌘+⌥+arrows'
pc: string; // e.g., 'Ctrl+1', 'Ctrl+Alt+arrows'
category: 'tabs' | 'terminal' | 'navigation' | 'app' | 'sftp';
/**
* Set on a user-added secondary shortcut. The entry shares its action with
* the default binding whose id this holds, so it never renders as its own row.
*/
extraOf?: string;
}
/** One user-added secondary shortcut for a default binding. */
export interface KeyBindingExtra {
mac?: string;
pc?: string;
}
// User's custom key bindings - only stores overrides from defaults
export type CustomKeyBindings = Record<string, { mac?: string; pc?: string }>;
export type CustomKeyBindings = Record<string, {
mac?: string;
pc?: string;
/** Additional chords that trigger the same action as the default binding. */
extra?: KeyBindingExtra[];
}>;
// Parse a key string like "⌘ + Shift + K" or "Ctrl + Alt + T" into normalized form
export const parseKeyCombo = (keyStr: string): { modifiers: string[]; key: string } | null => {
@@ -236,6 +252,22 @@ export const matchesKeyBinding = (e: KeyboardEvent, keyStr: string, isMac: boole
return eventKey.toLowerCase() === parsedKey.toLowerCase();
};
/** Every binding that triggers `action`, including user-added secondary chords. */
export const findBindingsForAction = (
bindings: readonly KeyBinding[],
action: string,
): KeyBinding[] => bindings.filter((binding) => binding.action === action);
/** True when any binding of `action` matches the event. */
export const matchesActionKeyBinding = (
e: KeyboardEvent,
bindings: readonly KeyBinding[],
action: string,
isMac: boolean,
): boolean => findBindingsForAction(bindings, action).some((binding) => (
matchesKeyBinding(e, isMac ? binding.mac : binding.pc, isMac)
));
export const DEFAULT_KEY_BINDINGS: KeyBinding[] = [
// Tab Management
{ id: 'switch-tab-1-9', action: 'switchToTab', label: 'Switch to Tab [1...9]', mac: '⌘ + [1...9]', pc: 'Ctrl + [1...9]', category: 'tabs' },
+4
View File
@@ -269,6 +269,8 @@ export interface TerminalSettings {
autocompleteMaxSuggestions: number; // Maximum suggestions in popup menu
/** Scope for history-backed autocomplete suggestions (host vs all hosts). */
autocompleteHistoryScope: AutocompleteHistoryScope;
/** Include matching code snippets in terminal autocomplete suggestions. */
autocompleteShowSnippets: boolean;
/**
* Assist for sudo/su password prompts: off, quick Enter-to-paste (hint),
@@ -480,6 +482,7 @@ export const normalizeTerminalSettings = (
autocompleteHistoryScope: isAutocompleteHistoryScope(settings?.autocompleteHistoryScope)
? settings.autocompleteHistoryScope
: DEFAULT_TERMINAL_SETTINGS.autocompleteHistoryScope,
autocompleteShowSnippets: settings?.autocompleteShowSnippets !== false,
oscNotifications: isOscNotificationMode(settings?.oscNotifications)
? settings.oscNotifications
: DEFAULT_TERMINAL_SETTINGS.oscNotifications,
@@ -663,6 +666,7 @@ const DEFAULT_TERMINAL_SETTINGS: TerminalSettings = {
autocompleteMinChars: 1, // Start suggesting after 1 character
autocompleteMaxSuggestions: 50, // Show up to 50 suggestions (popup scrolls)
autocompleteHistoryScope: 'host', // Per-host history suggestions by default (#2595)
autocompleteShowSnippets: true, // Include matching code snippets in autocomplete by default
passwordPromptAssist: 'hint', // Historical sudo confirm-to-fill; picker is opt-in (#2156)
};
+20
View File
@@ -247,6 +247,7 @@ test("later-added settings retain their tab and sub-tab destinations", () => {
["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-chat-history-storage-usage", "ai", "tools", "ai.chatHistory.storageUsage"],
["ai-chat-history-auto-llm-title", "ai", "tools", "ai.chatHistory.autoLlmTitle"],
["ai-chat-history-title-model", "ai", "tools", "ai.chatHistory.titleModel"],
["ai-web-search-max-results", "ai", "search", "ai.webSearch.maxResults"],
@@ -359,3 +360,22 @@ test("settings search finds the SFTP tree view folder double-click option from t
}
}
});
test("settings search finds the autocomplete show code snippets toggle across locales", () => {
const tZhReal = (key: string) => zhCN[key] ?? key;
const tTwReal = (key: string) => zhTW[key] ?? key;
const tEnReal = (key: string) => en[key] ?? key;
for (const [t, queries] of [
[tZhReal, ["显示代码片段", "代码片段", "补全"]],
[tTwReal, ["顯示程式碼片段", "程式碼片段"]],
[tEnReal, ["show code snippets", "snippet", "snippets"]],
] as const) {
for (const query of queries) {
const hit = filterSettingsSearchCatalog(query, t).find(
(hit) => hit.entry.id === "terminal-autocomplete-show-snippets",
);
assert.ok(hit, `${query} should find terminal-autocomplete-show-snippets`);
assert.equal(hit.entry.tab, "terminal");
}
}
});
+17 -1
View File
@@ -931,6 +931,14 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
descriptionKey: "settings.terminal.autocomplete.historyScope.desc",
sectionKey: "settings.terminal.section.autocomplete",
},
{
id: "terminal-autocomplete-show-snippets",
tab: "terminal",
labelKey: "settings.terminal.autocomplete.showSnippets",
descriptionKey: "settings.terminal.autocomplete.showSnippets.desc",
sectionKey: "settings.terminal.section.autocomplete",
keywords: ["snippet", "snippets", "code snippets", "代码片段", "程式碼片段", "补全", "補全"],
},
{
id: "terminal-password-prompt-assist",
tab: "terminal",
@@ -1236,6 +1244,14 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
descriptionKey: "ai.chatHistory.messageCap.description",
sectionKey: "ai.chatHistory.title",
},
{
id: "ai-chat-history-storage-usage",
tab: "ai",
aiSubTab: "tools",
labelKey: "ai.chatHistory.storageUsage",
descriptionKey: "ai.chatHistory.storageUsage.description",
sectionKey: "ai.chatHistory.title",
},
{
id: "ai-chat-history-auto-llm-title",
tab: "ai",
@@ -1291,7 +1307,7 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
labelKey: "ai.webSearch.enable",
descriptionKey: "ai.webSearch.enable.description",
sectionKey: "ai.webSearch.title",
keywords: ["tavily", "brave", "web search"],
keywords: ["tavily", "brave", "deepseek", "web search"],
},
{
id: "ai-web-search-provider",
+25
View File
@@ -106,6 +106,31 @@ test("normalizeTerminalSettings falls back for unsupported autocomplete history
);
});
test("normalizeTerminalSettings defaults autocompleteShowSnippets to true", () => {
assert.equal(normalizeTerminalSettings().autocompleteShowSnippets, true);
assert.equal(normalizeTerminalSettings({}).autocompleteShowSnippets, true);
});
test("normalizeTerminalSettings preserves explicit autocompleteShowSnippets values", () => {
assert.equal(
normalizeTerminalSettings({ autocompleteShowSnippets: false }).autocompleteShowSnippets,
false,
);
assert.equal(
normalizeTerminalSettings({ autocompleteShowSnippets: true }).autocompleteShowSnippets,
true,
);
});
test("normalizeTerminalSettings normalizes missing or non-boolean autocompleteShowSnippets to true", () => {
for (const invalid of [undefined, null, "false", 0, {}]) {
assert.equal(
normalizeTerminalSettings({ autocompleteShowSnippets: invalid as never }).autocompleteShowSnippets,
true,
);
}
});
test("normalizeTerminalSettings enables Shift+Enter newline by default", () => {
const settings = normalizeTerminalSettings();
+20
View File
@@ -116,6 +116,26 @@ test("ssh_config import maps ForwardX11 no to disabled host X11 forwarding", ()
assert.equal(result.hosts[0].x11Forwarding, false);
});
test("ssh_config import merges an alias declared in several Host blocks", () => {
const result = importVaultHostsFromText("ssh_config", [
"Host hd-edu-web1",
" HostName 10.147.28.11",
" User root",
"",
"Host hd-edu-web1",
" IdentityFile ~/.ssh/id_rsa",
" IdentitiesOnly yes",
].join("\n"));
assert.equal(result.hosts.length, 1);
const [host] = result.hosts;
assert.equal(host.label, "hd-edu-web1");
assert.equal(host.hostname, "10.147.28.11");
assert.equal(host.username, "root");
assert.deepEqual(host.identityFilePaths, ["~/.ssh/id_rsa"]);
assert.equal(host.identitiesOnly, true);
});
test("ssh_config import enables agent login for the macOS Keychain pattern", () => {
const result = importVaultHostsFromText("ssh_config", [
"Host aws-sg",
+96 -55
View File
@@ -1105,70 +1105,111 @@ const importFromSshConfig = (text: string): VaultImportResult => {
const makeHostKey = (hostname: string, port?: number) =>
`${hostname.toLowerCase()}:${port ?? 22}`;
for (const block of blocks) {
const patterns = block.patterns.filter((p) => p && !isWildcardPattern(p));
if (patterns.length === 0) continue;
// OpenSSH applies every Host block whose pattern matches an alias and keeps
// the first obtained value, so one alias may be declared in several blocks
// (for example HostName/User in one block and IdentityFile in another).
// Resolve options per literal pattern; treating every block as its own host
// imported such an alias twice, and the second copy kept the alias itself as
// its hostname with no username.
const orderedPatterns: string[] = [];
const blockByPattern = new Map<string, Block>();
const inheritOption = <K extends keyof Block>(target: Block, source: Block, key: K) => {
if (target[key] === undefined && source[key] !== undefined) target[key] = source[key];
};
for (const pat of patterns) {
parsed++;
const hostname = block.hostname ?? pat;
if (!looksLikeHostnameToken(hostname)) {
skipped++;
issues.push({
level: "warning",
message: `ssh_config: skipped host "${pat}" (invalid hostname).`,
for (const block of blocks) {
for (const pattern of block.patterns) {
if (!pattern || isWildcardPattern(pattern)) continue;
const merged = blockByPattern.get(pattern);
if (!merged) {
blockByPattern.set(pattern, {
...block,
patterns: [pattern],
identityFiles: block.identityFiles ? [...block.identityFiles] : undefined,
});
orderedPatterns.push(pattern);
continue;
}
inheritOption(merged, block, "hostname");
inheritOption(merged, block, "username");
inheritOption(merged, block, "port");
inheritOption(merged, block, "proxyJump");
inheritOption(merged, block, "identityAgent");
inheritOption(merged, block, "identitiesOnly");
inheritOption(merged, block, "addKeysToAgent");
inheritOption(merged, block, "useKeychain");
inheritOption(merged, block, "forwardX11");
if (block.identityFiles?.length) {
const seen = new Set(merged.identityFiles ?? []);
for (const identityFile of block.identityFiles) {
if (seen.has(identityFile)) continue;
seen.add(identityFile);
(merged.identityFiles ??= []).push(identityFile);
}
}
}
}
const host = createHost({
label: pat,
hostname,
username: block.username,
port: block.port,
protocol: "ssh",
for (const pattern of orderedPatterns) {
const block = blockByPattern.get(pattern)!;
parsed++;
const hostname = block.hostname ?? pattern;
if (!looksLikeHostnameToken(hostname)) {
skipped++;
issues.push({
level: "warning",
message: `ssh_config: skipped host "${pattern}" (invalid hostname).`,
});
continue;
}
// Attach IdentityFile paths if present
if (block.identityFiles && block.identityFiles.length > 0) {
host.identityFilePaths = [...block.identityFiles];
}
if (block.identityAgent !== undefined) {
host.identityAgent = block.identityAgent;
}
if (block.identitiesOnly !== undefined) {
host.identitiesOnly = block.identitiesOnly;
}
if (block.addKeysToAgent !== undefined) {
host.addKeysToAgent = block.addKeysToAgent;
}
if (block.useKeychain !== undefined) {
host.useKeychain = block.useKeychain;
}
const identityAgentEnabled = block.identityAgent !== undefined
&& block.identityAgent.toLowerCase() !== "none";
const identityAgentDisabled = block.identityAgent?.toLowerCase() === "none";
// The #2119 macOS pattern relies on AddKeysToAgent + UseKeychain without
// declaring IdentityAgent. Treat that pair as an agent-backed login so
// the bridge can ask Apple's ssh-add to load the configured IdentityFile.
// AddKeysToAgent alone still keeps direct-key semantics on other setups.
const macKeychainAgentEnabled = hasMacKeychainAgentDirectives(block);
if (!identityAgentDisabled && (identityAgentEnabled || macKeychainAgentEnabled)) {
host.useSshAgent = true;
} else if (identityAgentDisabled) {
host.useSshAgent = false;
}
if (block.forwardX11 !== undefined) {
host.x11Forwarding = block.forwardX11;
}
const host = createHost({
label: pattern,
hostname,
username: block.username,
port: block.port,
protocol: "ssh",
});
parsedHosts.push(host);
// Attach IdentityFile paths if present
if (block.identityFiles && block.identityFiles.length > 0) {
host.identityFilePaths = [...block.identityFiles];
}
if (block.identityAgent !== undefined) {
host.identityAgent = block.identityAgent;
}
if (block.identitiesOnly !== undefined) {
host.identitiesOnly = block.identitiesOnly;
}
if (block.addKeysToAgent !== undefined) {
host.addKeysToAgent = block.addKeysToAgent;
}
if (block.useKeychain !== undefined) {
host.useKeychain = block.useKeychain;
}
const identityAgentEnabled = block.identityAgent !== undefined
&& block.identityAgent.toLowerCase() !== "none";
const identityAgentDisabled = block.identityAgent?.toLowerCase() === "none";
// The #2119 macOS pattern relies on AddKeysToAgent + UseKeychain without
// declaring IdentityAgent. Treat that pair as an agent-backed login so
// the bridge can ask Apple's ssh-add to load the configured IdentityFile.
// AddKeysToAgent alone still keeps direct-key semantics on other setups.
const macKeychainAgentEnabled = hasMacKeychainAgentDirectives(block);
if (!identityAgentDisabled && (identityAgentEnabled || macKeychainAgentEnabled)) {
host.useSshAgent = true;
} else if (identityAgentDisabled) {
host.useSshAgent = false;
}
if (block.forwardX11 !== undefined) {
host.x11Forwarding = block.forwardX11;
}
// Store ProxyJump using hostname key (survives deduplication)
if (block.proxyJump && block.proxyJump.toLowerCase() !== "none") {
const hostKey = makeHostKey(hostname, block.port);
hostProxyJumpMap.set(hostKey, block.proxyJump);
}
parsedHosts.push(host);
// Store ProxyJump using hostname key (survives deduplication)
if (block.proxyJump && block.proxyJump.toLowerCase() !== "none") {
const hostKey = makeHostKey(hostname, block.port);
hostProxyJumpMap.set(hostKey, block.proxyJump);
}
}
+13
View File
@@ -403,6 +403,19 @@ test("loginShellHint selects fish/posix/powershell/cmd without pinning confirmed
resolveEffectiveShellKind(undefined, "alice@wsl:/mnt/c$", { loginShellHint: "cmd" }),
"posix",
);
// Nested Kali two-line prompt: the last line alone is a bare `└─$`.
assert.equal(
resolveEffectiveShellKind(undefined, "┌──(kali㉿kali)-[~]\n\n└─$ ", { loginShellHint: "cmd" }),
"posix",
);
assert.equal(
resolveEffectiveShellKind(undefined, "┌──(root㉿kali)-[/tmp]\n\n└─# 1 ⨯", { loginShellHint: "powershell" }),
"posix",
);
assert.equal(
resolveEffectiveShellKind(undefined, "random output\n└─$ ", { loginShellHint: "cmd" }),
"cmd",
);
// Confirmed shellKind is never overridden by a login hint.
assert.equal(
resolveEffectiveShellKind("posix", "user@host:~$", { loginShellHint: "fish" }),
+2 -1
View File
@@ -7,6 +7,7 @@ const {
isDefaultPowerShellPromptLine,
isDefaultCmdPromptLine,
isDefaultPosixPromptLine,
isKaliTwoLinePrompt,
} = require("./shellUtils.cjs");
const { renderCursorBoundScreenText } = require("../terminalLogSanitizer.cjs");
const { classifyLocalShellType } = require("../../../lib/localShell.cjs");
@@ -206,7 +207,7 @@ function isPosixPrompt(prompt) {
.split("\n")
.pop()
.replace(/\s+$/, "");
return isDefaultPosixPromptLine(lastLine);
return isDefaultPosixPromptLine(lastLine) || isKaliTwoLinePrompt(prompt);
}
// Prompt-driven override is intentionally narrow: only flip to PowerShell
+78 -17
View File
@@ -17,6 +17,15 @@ const {
const ANSI_ESCAPE_REGEX = /\u001B\[[0-?]*[ -/]*[@-~]/g;
const ANSI_OSC_REGEX = /\u001B\][^\u0007]*?(?:\u0007|\u001B\\)/g;
// DCS/SOS/PM/APC strings are removed whole so their payload never reads as
// visible text. Only ST ends them (BEL is OSC-only), and the payload stops at
// the next ESC so runs of unterminated introducers stay linear; an
// unterminated one keeps its ESC like an incomplete OSC.
const ANSI_CONTROL_STRING_REGEX = /\u001B[PX^_][^\u001B]*\u001B\\/g;
// Non-CSI/OSC escapes: zle paints `ESC =` (keypad mode) right after the prompt;
// also `ESC 7`/`ESC 8`, `ESC M`, and charset designators like `ESC ( B`.
// `[`, `]` and the control-string introducers `P X ^ _` stay excluded.
const ANSI_SHORT_ESCAPE_REGEX = /\u001B(?:[ -/]+[0-~]|[0-OQ-WYZ\\`-~])/g;
const URL_CANDIDATE_REGEX = /https?:\/\/[^\s]+/g;
const WINDOWS_RUNNABLE_EXTENSIONS = [".exe", ".cmd", ".bat", ".com"];
const MAX_PROMPT_TRACK_TAIL = 4096;
@@ -38,7 +47,11 @@ function execFileAsync(command, args, options) {
// ── ANSI stripping ──
function stripAnsi(input) {
return String(input || "").replace(ANSI_OSC_REGEX, "").replace(ANSI_ESCAPE_REGEX, "");
return String(input || "")
.replace(ANSI_OSC_REGEX, "")
.replace(ANSI_CONTROL_STRING_REGEX, "")
.replace(ANSI_ESCAPE_REGEX, "")
.replace(ANSI_SHORT_ESCAPE_REGEX, "");
}
// ── Synthetic command echo ──
@@ -107,6 +120,31 @@ const POSIX_PROMPT_HOST_LINE_PATTERN = /^[^\s@]+@[^\s:]+(?::[^\n\r]*)?$/;
// a bare `$`/`#` still does not match.
const OH_MY_ZSH_YS_HOST_LINE_PATTERN = /^#\s+[^\s@]+\s+@\s+[^\s]+(?:\s+[^\n\r]+)?$/;
// Kali Linux default two-line bash/zsh prompt:
// ┌──(root㉿kali)-[~]
// └─#
// Also handles non-root `└─$` and ASCII `@`. Chroot/venv groups precede the
// user group: zsh joins them with `─`, bash with `──` (chroot) or nothing (venv).
const KALI_PROMPT_HOST_LINE_PATTERN =
/^┌──(?:\([^()\r\n]+\)─{0,2})*\([^\s@㉿()]+[@㉿][^\s()]+\)-\[[^\r\n]+\]$/;
// Kali's zsh RPROMPT appends ` <code> ⨯` after a failed command and
// ` <jobs> ⚙` with background jobs; anything else is pending input.
const KALI_PROMPT_MARKER_LINE_PATTERN = /^└─[$#](?:\s+\d+\s+[⨯⚙])*$/;
// Shell-kind resolution only sees the last line, which for Kali is a bare
// `└─$`; check the paired host line so nested Kali (e.g. WSL) reads as POSIX.
function isKaliTwoLinePrompt(prompt) {
const lines = stripAnsi(String(prompt || ""))
.replace(/\r/g, "\n")
.split("\n")
.map((line) => line.replace(/\s+$/, ""))
.filter(Boolean);
let index = lines.length - 1;
if (index < 1 || !KALI_PROMPT_MARKER_LINE_PATTERN.test(lines[index])) return false;
while (index >= 0 && KALI_PROMPT_MARKER_LINE_PATTERN.test(lines[index])) index -= 1;
return index >= 0 && KALI_PROMPT_HOST_LINE_PATTERN.test(lines[index]);
}
// Alpine's default ash PS1 omits the username: `\h:\w\$ ` -> `localhost:~# `.
// Require a hostname and a home/absolute path, excluding prompt delimiters
// within the path so partially entered commands do not count as idle prompts.
@@ -174,7 +212,7 @@ function isDefaultCmdPromptLine(line) {
}
function stripLeadingDecorativeToken(line) {
// Optional short decorative token, stripped only for recognition (#4354).
// Optional short decorative tokens, stripped only for recognition (#4354).
return line.replace(/^\s*[^\s\w\p{L}\p{N}@:#$\\\/>\[\]().]{1,4}\s+/u, "");
}
@@ -183,9 +221,11 @@ function isDefaultPosixPromptLine(line) {
// Optional virtualenv / conda / BT-panel style env name prefix: "(name) "
// before the shell prompt. Recognition only; callers still return the full
// prompt line so suffix matching sees the visible prefix (#3947).
const withoutEnvPrefix = normalized.replace(/^\([^()\n\r]+\)\s+/, "");
return [withoutEnvPrefix, stripLeadingDecorativeToken(withoutEnvPrefix)].some(
(prompt) => (
let prompt = normalized.replace(/^\([^()\n\r]+\)\s+/, "");
// Check each candidate before stripping again: a glyph such as the
// robbyrussell arrow may be part of the prompt itself (#4354).
while (true) {
if (
POSIX_PROMPT_PATTERN.test(prompt) ||
BRACKET_TIME_POSIX_PROMPT_PATTERN.test(prompt) ||
BRACKET_PATH_POSIX_PROMPT_PATTERN.test(prompt) ||
@@ -196,8 +236,11 @@ function isDefaultPosixPromptLine(line) {
POWERLEVEL10K_PROMPT_PATTERN.test(prompt) ||
POWERLINE_PROMPT_PATTERN.test(prompt) ||
OH_MY_ZSH_ROBBYRUSSELL_PROMPT_PATTERN.test(prompt)
),
);
) return true;
const stripped = stripLeadingDecorativeToken(prompt);
if (stripped === prompt) return false;
prompt = stripped;
}
}
function extractTrailingIdlePrompt(output) {
@@ -241,14 +284,21 @@ function extractTrailingIdlePrompt(output) {
// getFreshIdlePrompt uses the same normalize, and hasExpectedPromptSuffix
// compares this CR-as-LF form against live PTY bytes. A lone `$`/`#` must
// not satisfy endsWith; the previous non-empty line has to be a recognized
// host line (classic `user@host[:path]` or Oh My Zsh `ys`).
if (rightTrimmed === "$" || rightTrimmed === "#") {
// host line (classic `user@host[:path]`, Oh My Zsh `ys`, or Kali `┌──(...)`
// paired only with a Kali `└─$`/`└─#` marker).
const isBareMarker = rightTrimmed === "$" || rightTrimmed === "#";
const isKaliMarker = KALI_PROMPT_MARKER_LINE_PATTERN.test(rightTrimmed);
if (isBareMarker || isKaliMarker) {
let hostIndex = lines.length - 1;
while (hostIndex >= 0) {
const candidate = lines[hostIndex].replace(/\s+$/, "");
// Some Prompts redraw the same bare marker multiple times with CR + EL.
// Those intermediate marker lines are still part of the idle prompt.
if (candidate === "" || candidate === rightTrimmed) {
if (
candidate === ""
|| candidate === rightTrimmed
|| (isKaliMarker && KALI_PROMPT_MARKER_LINE_PATTERN.test(candidate))
) {
hostIndex -= 1;
} else {
break;
@@ -259,11 +309,14 @@ function extractTrailingIdlePrompt(output) {
// Same optional "(name) " env prefix as isDefaultPosixPromptLine (#3947).
// Recognition only; the returned prompt keeps the visible prefix.
const previousHostLine = previousRightTrimmed.replace(/^\([^()\n\r]+\)\s+/, "");
if (
POSIX_PROMPT_HOST_LINE_PATTERN.test(previousHostLine)
|| OH_MY_ZSH_YS_HOST_LINE_PATTERN.test(previousHostLine)
|| extractTerminalPromptHostname(`${previousRightTrimmed}\n${rightTrimmed}`)
) {
const matched = isKaliMarker
? KALI_PROMPT_HOST_LINE_PATTERN.test(previousHostLine)
: (
POSIX_PROMPT_HOST_LINE_PATTERN.test(previousHostLine)
|| OH_MY_ZSH_YS_HOST_LINE_PATTERN.test(previousHostLine)
|| extractTerminalPromptHostname(`${previousRightTrimmed}\n${rightTrimmed}`)
);
if (matched) {
return `${lines.slice(hostIndex).join("\n")}\n${lastLine}${trailingLineBreaks}`;
}
}
@@ -495,8 +548,9 @@ function getVisibleIdlePrompt(session) {
if (session.osc133Ready === false) return "";
if (!matchesOsc133EmptyPrompt(session, view)) return "";
const { terminalCursorLine } = require("../terminalLogSanitizer.cjs");
const cursorLine = terminalCursorLine(tail, view);
const { terminalCursorLine, renderCursorBoundScreenText } = require("../terminalLogSanitizer.cjs");
const visibleTail = tail.replace(ANSI_CONTROL_STRING_REGEX, "");
const cursorLine = terminalCursorLine(visibleTail, view);
const rightTrimmed = cursorLine.replace(/\s+$/, "");
if (!rightTrimmed) return "";
if (session.osc133Ready === true && session._osc133PromptLine != null) {
@@ -504,6 +558,12 @@ function getVisibleIdlePrompt(session) {
// and lack of continuation are checked above before bypassing shape checks.
return /\s$/.test(cursorLine) ? `${rightTrimmed} ` : rightTrimmed;
}
if (KALI_PROMPT_MARKER_LINE_PATTERN.test(rightTrimmed)) {
// After readline or zle erases input, verify the host and marker on the
// current screen together. The bare marker alone cannot establish readiness.
const screen = renderCursorBoundScreenText(visibleTail, view);
return screen ? extractTrailingIdlePrompt(screen.trimmedAboveText) : "";
}
if (
!isDefaultPowerShellPromptLine(rightTrimmed)
&& !isDefaultPosixPromptLine(rightTrimmed)
@@ -1461,6 +1521,7 @@ module.exports = {
isDefaultPowerShellPromptLine,
isDefaultCmdPromptLine,
isDefaultPosixPromptLine,
isKaliTwoLinePrompt,
trackSessionIdlePrompt,
getSessionReadinessGeneration,
bumpSessionReadinessGeneration,
+185
View File
@@ -518,10 +518,41 @@ test("isDefaultPosixPromptLine matches short decorative prefixes and keeps the f
}
});
test("stacked decorative prefixes preserve the full extracted and tracked prompt", () => {
for (const prompt of [
...["\u2718", "\u2714", "\u2717", "\u2713"].flatMap(status => [
`${status} \u26A1 root@testhost:~# `,
`${status} \u26A1 root@testhost:~#`,
`${status} \u26A1 root@testhost \uE0B0 ~ \uE0B0 `,
`(venv) ${status} \u26A1 user@host:~# `,
`${status} \u279C netcatty`,
`${status} \u279C netcatty `,
`${status} \u279C ~ git:(main) \u2717`,
`(venv) ${status} \u279C netcatty git:(main) \u2713 `,
]),
"\u2718 \u2714 \u26A1 root@testhost:~# ",
"\u2718 \u2714 \u279C netcatty ",
]) {
assert.equal(isDefaultPosixPromptLine(prompt), true, prompt);
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${prompt}`), prompt, prompt);
const session = {};
trackSessionIdlePrompt(session, `welcome\r\n${prompt}`);
assert.equal(session.lastIdlePrompt, prompt, prompt);
assert.equal(getFreshIdlePrompt(session), prompt, prompt);
}
});
test("decorative prefix recognition rejects pending input and non-decorative prefixes", () => {
for (const line of [
"\u26A1 root@testhost:~# echo hi",
" \u26A1 root@testhost \uE0B0 ~ \uE0B0 ls",
"\u2718 \u26A1 root@testhost:~# echo hi",
"\u2718 \u26A1 root@testhost \uE0B0 ~ \uE0B0 ls",
...["\u2718", "\u2714", "\u2717", "\u2713"].flatMap(status => [
`${status} \u279C netcatty ls`,
`(venv) ${status} \u279C netcatty git:(main) \u2713 ls`,
]),
"\u2718 \u2714 \u279C netcatty ls",
"OK root@testhost:~# ",
"yes root@testhost:~# ",
"git:(main) root@testhost:~# ",
@@ -1939,3 +1970,157 @@ test("macOS root pattern rejects cmd drive-letter prompts with pending input (#4
assert.equal(isDefaultPosixPromptLine("Password:"), false);
assert.equal(extractTrailingIdlePrompt("welcome\r\nPassword:"), "");
});
test("extractTrailingIdlePrompt recognizes Kali Linux default two-line prompts", () => {
const rootPrompt = "┌──(root㉿kali)-[~]\r\n└─# ";
assert.equal(
extractTrailingIdlePrompt(`Last login: Tue Dec 1\r\n${rootPrompt}`),
"┌──(root㉿kali)-[~]\n\n└─# ",
);
const userPrompt = "┌──(kali㉿kali)-[~/projects]\r\n└─$ ";
assert.equal(
extractTrailingIdlePrompt(`ready\r\n${userPrompt}`),
"┌──(kali㉿kali)-[~/projects]\n\n└─$ ",
);
const venvPrompt = "┌──(venv)─(root@kali)-[/etc/ssh]\r\n└─# ";
assert.equal(
extractTrailingIdlePrompt(`ok\r\n${venvPrompt}`),
"┌──(venv)─(root@kali)-[/etc/ssh]\n\n└─# ",
);
// Pending input on the second line or bare marker without Kali host line must stay rejected.
assert.equal(extractTrailingIdlePrompt("┌──(root㉿kali)-[~]\r\n└─# nmap -V"), "");
assert.equal(extractTrailingIdlePrompt("some random output\r\n└─# "), "");
assert.equal(extractTrailingIdlePrompt("└─$ "), "");
});
test("extractTrailingIdlePrompt accepts Kali chroot/venv prefixes from bash and zsh", () => {
const prompts = [
"┌──(venv)(kali㉿kali)-[~]\r\n└─$ ",
"┌──(chroot)──(kali㉿kali)-[~]\r\n└─$ ",
"┌──(chroot)─(venv)─(kali㉿kali)-[~]\r\n└─$ ",
];
for (const prompt of prompts) {
assert.equal(
extractTrailingIdlePrompt(`ok\r\n${prompt}`),
`${prompt.replace("\r\n", "\n\n")}`,
);
}
assert.equal(extractTrailingIdlePrompt("┌──(venv) (kali㉿kali)-[~]\r\n└─$ "), "");
assert.equal(extractTrailingIdlePrompt("┌──(kali kali)-[~]\r\n└─$ "), "");
});
test("extractTrailingIdlePrompt accepts Kali zsh RPROMPT exit-code and job indicators", () => {
const failed = "┌──(kali㉿kali)-[~]\r\n└─$ \x1b[60C 1 \x1b[1m⨯\x1b[0m\x1b[64D";
assert.equal(
extractTrailingIdlePrompt(`false\r\n${failed}`),
"┌──(kali㉿kali)-[~]\n\n└─$ 1 ⨯",
);
const failedWithJobs = "┌──(root㉿kali)-[/tmp]\r\n└─# 130 ⨯ 1 ⚙";
assert.equal(
extractTrailingIdlePrompt(`^C\r\n${failedWithJobs}`),
"┌──(root㉿kali)-[/tmp]\n\n└─# 130 ⨯ 1 ⚙",
);
// zsh may return the cursor with CR after painting RPROMPT.
const crReturn = "┌──(kali㉿kali)-[~]\r\n└─$ 1 ⨯\r\x1b[4C";
assert.equal(
extractTrailingIdlePrompt(crReturn),
"┌──(kali㉿kali)-[~]\n\n└─$ 1 ⨯\n",
);
assert.equal(extractTrailingIdlePrompt("┌──(kali㉿kali)-[~]\r\n└─$ ls 1 ⨯"), "");
assert.equal(extractTrailingIdlePrompt("┌──(kali㉿kali)-[~]\r\n└─$ oops ⨯"), "");
assert.equal(extractTrailingIdlePrompt("random output\r\n└─$ 1 ⨯"), "");
});
test("stripAnsi removes short ESC sequences but keeps incomplete CSI/OSC introducers", () => {
assert.equal(stripAnsi("a\x1b=b\x1b>c"), "abc");
assert.equal(stripAnsi("\x1b7saved\x1b8"), "saved");
assert.equal(stripAnsi("\x1b(Btext\x1b)0"), "text");
assert.equal(stripAnsi("line\x1bMup"), "lineup");
assert.equal(stripAnsi("tail\x1b["), "tail\x1b[");
assert.equal(stripAnsi("tail\x1b]0;title"), "tail\x1b]0;title");
});
test("stripAnsi removes DCS/SOS/PM/APC strings whole so payloads never look like prompts", () => {
assert.equal(stripAnsi("out\x1bPuser@host:~$ \x1b\\"), "out");
assert.equal(stripAnsi("a\x1bXsos\x1b\\b\x1b^pm\x1b\\c\x1b_apc\x1b\\d"), "abcd");
// BEL does not end a DCS: the payload after it must not leak as a prompt.
assert.equal(stripAnsi("x\x1bPdata\x07user@host:~$ \x1b\\"), "x");
assert.equal(extractTrailingIdlePrompt("vim\r\n\x1bPdata\x07user@host:~$ \x1b\\"), "");
assert.equal(stripAnsi("tail\x1bPunterminated"), "tail\x1bPunterminated");
assert.equal(extractTrailingIdlePrompt("vim\r\n\x1bPuser@host:~$ \x1b\\"), "");
});
test("stripAnsi stays linear on many unterminated control-string introducers", () => {
const input = "\x1bP".repeat(200000);
const started = Date.now();
stripAnsi(input);
assert.ok(Date.now() - started < 1000, "stripAnsi should not be quadratic");
});
// Bytes captured from Kali 2026.2 zsh over SSH (xterm-256color, 120 cols).
const KALI_ZSH_PROMPT_BYTES =
"\x1b[1m\x1b[7m%\x1b[27m\x1b[1m\x1b[0m" + " ".repeat(119) + "\r \r"
+ "\x1b]0;root@kali: ~\x07\r\n\r\x1b[0m\x1b[27m\x1b[24m\x1b[J"
+ "\x1b[34m┌──(\x1b[1m\x1b[34m\x1b[31mroot㉿kali\x1b[0m\x1b[31m\x1b[34m)-[\x1b[1m\x1b[34m\x1b[39m~\x1b[0m\x1b[34m]\r\n"
+ "└─\x1b[1m\x1b[34m\x1b[31m#\x1b[0m\x1b[31m\x1b[39m \x1b[K";
const KALI_ZLE_KEYPAD_ON = "\x1b[?1h\x1b=\x1b[?2004h";
test("real Kali zsh prompt bytes are idle, including zle keypad-mode escapes", () => {
const session = {};
trackSessionIdlePrompt(session, `false\r\n\x1b[?1l\x1b>\x1b[?2004l\r\r\n${KALI_ZSH_PROMPT_BYTES}${KALI_ZLE_KEYPAD_ON}`);
assert.equal(stripAnsi(getFreshIdlePrompt(session)).split("\n").pop(), "└─# ");
const failed = `${KALI_ZSH_PROMPT_BYTES}\x1b[111C 1 \x1b[31m\x1b[1m\x1b[31m⨯\x1b[0m\x1b[31m\x1b[39m\x1b[115D${KALI_ZLE_KEYPAD_ON}`;
const failedSession = {};
trackSessionIdlePrompt(failedSession, failed);
assert.equal(stripAnsi(getFreshIdlePrompt(failedSession)).split("\n").pop(), "└─# 1 ⨯");
const pending = `${KALI_ZSH_PROMPT_BYTES}${KALI_ZLE_KEYPAD_ON}l\bls\b\b\x1b[36ml\x1b[36ms\x1b[39m`;
assert.equal(extractTrailingIdlePrompt(pending), "");
});
test("real Kali bash prompt bytes with a readline redraw are idle", () => {
const bytes = "\x1b[?2004h\x1b]0;root@kali: ~\x07\x1b[;94m┌──(\x1b[1;31mroot㉿kali\x1b[;94m)-[\x1b[0;1m~\x1b[;94m]\r\r\n"
+ "\x1b[;94m└─\x1b[1;31m#\x1b[0m \r\x1b[;94m└─\x1b[1;31m#\x1b[0m ";
const session = {};
trackSessionIdlePrompt(session, `false\r\n\x1b[?2004l\r\r\n${bytes}`);
assert.equal(stripAnsi(getFreshIdlePrompt(session)).split("\n").pop(), "└─# ");
});
test("trackSessionIdlePrompt keeps Kali prompts ready after a failed command", () => {
const session = {};
const prompt = "┌──(kali㉿kali)-[~]\r\n└─$ \x1b[60C 1 ⨯\x1b[64D";
trackSessionIdlePrompt(session, `\r\nfalse\r\n${prompt}`);
assert.equal(getFreshIdlePrompt(session), "┌──(kali㉿kali)-[~]\n\n└─$ 1 ⨯");
});
test("trackSessionIdlePrompt and getFreshIdlePrompt accept Kali Linux two-line prompts", () => {
const session = {};
const prompt = "┌──(root㉿kali)-[~]\r\n└─# ";
trackSessionIdlePrompt(session, `Last login: Tue Dec 1\r\n${prompt}`);
assert.equal(getFreshIdlePrompt(session), "┌──(root㉿kali)-[~]\n\n└─# ");
trackSessionIdlePrompt(session, "\r\nnmap -V\r\nNmap version 7.99\r\n");
assert.equal(getFreshIdlePrompt(session), "");
});
test("Kali visible readiness recovers after bash and zsh erase the last character", () => {
for (const erase of ["\b\x1b[K", "\b \b"]) {
const session = {};
const hostLine = "┌──(kali㉿kali)-[~]";
trackSessionIdlePrompt(session, hostLine + "\r\n└─$ ");
trackSessionIdlePrompt(session, "a");
assert.equal(getVisibleIdlePrompt(session), "");
trackSessionIdlePrompt(session, erase);
assert.equal(getVisibleIdlePrompt(session), hostLine + "\n└─$ ");
}
assert.equal(getVisibleIdlePrompt({ _promptTrackTail: "text\r\n└─$ a\b\x1b[K" }), "");
assert.equal(getVisibleIdlePrompt({ _promptTrackTail: "busy\r\n\x1bPuser@host:~$ \x1b\\" }), "");
});
@@ -199,6 +199,7 @@ function registerProviderHandlers(ctx) {
"api.tavily.com",
"api.exa.ai",
"api.bochaai.com",
"api.deepseek.com",
"open.bigmodel.cn",
]);
// Dynamically populated from configured provider baseURLs
@@ -0,0 +1,46 @@
"use strict";
const { randomUUID } = require("node:crypto");
const { MCP_APPROVAL_TIMEOUT_MS } = require("../../../shared/approvalConstants.cjs");
// Reuse the SDK elicitation transport, but keep typed form replies separate
// from the approval gate. A form reply grants no action permission.
function createAgentFormBroker() {
const pending = new Map();
return {
get: (id) => pending.get(id),
request(request, { sender, chatSessionId, signal, emitter, validateContent }) {
if (!Number.isInteger(sender?.id) || !chatSessionId || sender.isDestroyed?.() || signal?.aborted) return;
const elicitationId = `agent-form:${randomUUID()}`;
return new Promise((resolve) => {
const finish = (value) => {
if (!pending.delete(elicitationId)) return;
clearTimeout(timer);
signal?.removeEventListener("abort", onAbort);
try {
emitter.emitEvent({ type: "elicitation-complete", notification: { elicitationId } });
} catch { /* Renderer may have closed. */ }
resolve(value);
};
const onAbort = () => finish(undefined);
const timer = setTimeout(onAbort, MCP_APPROVAL_TIMEOUT_MS);
pending.set(elicitationId, { sender, chatSessionId, finish, validateContent });
signal?.addEventListener("abort", onAbort, { once: true });
try {
emitter.emitEvent({ type: "elicitation-create", elicitationId, request });
} catch {
onAbort();
}
});
},
respond(id, sender, action, content) {
const entry = pending.get(id);
if (!entry || entry.sender.id !== sender?.id) return false;
if (!["accept", "decline", "cancel"].includes(action)) return false;
entry.finish(action === "accept" ? content : undefined);
return true;
},
};
}
module.exports = { createAgentFormBroker };
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff. Show more