Compare commits

...
Author SHA1 Message Date
Radwan Selo a64029bc0b fix(dev): build plugin workspace packages before starting dev server (#4674)
@netcatty/plugin-contract resolves to packages/plugin-contract/dist, which
is not committed. On a fresh clone Vite failed with 'Failed to resolve entry
for package @netcatty/plugin-contract'. Build the plugin runtime deps as
part of npm run dev.
2026-12-03 23:30:34 +08:00
陈大猫 b5815c3064 feat(settings): measure local AI history on demand (#4678) 2026-12-03 19:10:43 +08:00
陈大猫 1f91fd54f1 fix(sync): preserve recovery history when saving or migrating a baseline (#4677)
* fix(sync): commit each baseline and its recovery history atomically

* fix(sync): preserve competing writes during lazy migration
2026-12-03 19:10:39 +08:00
陈大猫andGOUKI9999 2f76061ec8 fix(sync): require a recovery checkpoint before applying vault data (#4676)
Extract the two pre-apply checks and their regressions from #4605.

Co-authored-by: GOUKI9999 <gouki9999@Hotmail.com>
2026-12-03 19:10:36 +08:00
Joseph Hauand陈奇 dd9f6e862a feat(terminal): switch Git branches from the compose bar (#4625)
* feat(terminal): switch Git branches from the compose bar

* docs(terminal): organize compose bar and chip documentation

* fix(terminal): bind macOS prompt matching to the session directory

* fix(terminal): switch branches only in the selected worktree

* fix(terminal): preserve the boundary of colon-only prompts

* fix(terminal): bound macOS prompt matching before shell edits

* test(terminal): supply macOS prompt helpers to the paste runtime fixture

---------

Co-authored-by: 陈奇 <16399091+binaricat@users.noreply.github.com>
2026-12-03 19:10:32 +08:00
GOUKI9999and陈奇 f688a17f14 feat(ai): add Antigravity CLI (agy) ACP agent support (Beta) and reorder agent cards (#4664)
* feat(ai): add Antigravity CLI (agy) ACP agent support and reorder agent cards

* chore(i18n): label Antigravity CLI (agy) ACP integration as Beta with risk notice

* fix(ai): address Codex review findings in Antigravity ACP driver

* fix(ai): preserve Antigravity state and honor native approval decisions

* fix(ai): stop Antigravity process groups and report failed tools

* fix(ai): keep Antigravity outside the plugin backend contract

* fix(ai): decode ACP content blocks for Antigravity tool output

---------

Co-authored-by: 陈奇 <16399091+binaricat@users.noreply.github.com>
2026-12-03 19:10:27 +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
205 changed files with 9283 additions and 1278 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.
+29
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',
@@ -305,6 +308,16 @@ export const enAiMessages: Messages = {
'ai.opencode.v2.mcpSkipped': 'OpenCode 2 could not attach an MCP tool. The chat will continue without it.',
// AI MiMo Code (Xiaomi MiMo Code CLI — OpenCode fork)
'ai.agy.title': 'Antigravity CLI (Beta)',
'ai.agy.description': "Experimental Beta: Google's Antigravity coding agent CLI connected via the official Agent Client Protocol (agy acp --stdio). Feature coverage is still limited and not yet thoroughly tested — use at your own risk. Sign in with agy in your terminal, then select it as an external coding agent.",
'ai.agy.detecting': 'Detecting...',
'ai.agy.detected': 'Detected',
'ai.agy.notFound': 'Not found',
'ai.agy.path': 'Path:',
'ai.agy.notFoundHint': 'Could not find agy in PATH. Install Antigravity CLI or specify the executable path below.',
'ai.agy.customPathPlaceholder': 'e.g. /usr/local/bin/agy',
'ai.agy.check': 'Check',
'ai.agy.resetPath': 'Reset',
'ai.mimo.title': 'MiMo Code',
'ai.mimo.description': "Xiaomi's MiMo Code CLI, an OpenCode fork. Install it and configure providers in its own config, then select it as an external coding agent.",
'ai.mimo.detecting': 'Detecting...',
@@ -328,6 +341,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 +650,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 +714,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',
+6
View File
@@ -4,6 +4,12 @@ export const enTerminalMessages: Messages = {
'terminal.directory.open': 'Current directory: {path}. Change directory',
'terminal.gitBranch.current': 'Git branch: {{value}}',
'terminal.gitBranch.detached': 'Detached HEAD: {{value}}',
'terminal.gitBranch.search': 'Search local branches...',
'terminal.gitBranch.branches': 'Local branches',
'terminal.gitBranch.loading': 'Reading branches...',
'terminal.gitBranch.empty': 'No local branches yet',
'terminal.gitBranch.noMatches': 'No matching branches',
'terminal.gitBranch.unavailable': 'Could not read branches for this session.',
'terminal.directory.unknown': 'Directory unknown',
'terminal.directory.search': 'Search child directories...',
'terminal.directory.directories': 'Directories',
+29
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',
@@ -305,6 +308,16 @@ export const esAiMessages: Messages = {
'ai.opencode.v2.mcpSkipped': 'OpenCode 2 no pudo adjuntar una herramienta MCP. El chat continuará sin ella.',
// AI MiMo Code (CLI de Xiaomi MiMo Code — fork de OpenCode)
'ai.agy.title': 'Antigravity CLI (Beta)',
'ai.agy.description': 'Beta experimental: CLI del agente de codificación Antigravity de Google conectado mediante el Agent Client Protocol oficial (agy acp --stdio). El soporte aún es limitado y no ha sido probado a fondo; úsalo bajo tu propia responsabilidad. Inicia sesión con agy en tu terminal y selecciónalo como agente externo.',
'ai.agy.detecting': 'Detectando...',
'ai.agy.detected': 'Detectado',
'ai.agy.notFound': 'No encontrado',
'ai.agy.path': 'Ruta:',
'ai.agy.notFoundHint': 'No se pudo encontrar agy en el PATH. Instala Antigravity CLI o especifica la ruta del ejecutable a continuación.',
'ai.agy.customPathPlaceholder': 'p. ej. /usr/local/bin/agy',
'ai.agy.check': 'Verificar',
'ai.agy.resetPath': 'Restablecer',
'ai.mimo.title': 'MiMo Code',
'ai.mimo.description': 'CLI de MiMo Code de Xiaomi, un fork de OpenCode. Instálalo y configura los proveedores en su propia configuración, luego selecciónalo como agente de codificación externo.',
'ai.mimo.detecting': 'Detectando...',
@@ -328,6 +341,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 +650,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 +714,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',
+6
View File
@@ -4,6 +4,12 @@ export const esTerminalMessages: Messages = {
'terminal.directory.open': 'Directorio actual: {path}. Cambiar directorio',
'terminal.gitBranch.current': 'Rama de Git: {{value}}',
'terminal.gitBranch.detached': 'HEAD separado: {{value}}',
'terminal.gitBranch.search': 'Buscar ramas locales...',
'terminal.gitBranch.branches': 'Ramas locales',
'terminal.gitBranch.loading': 'Leyendo ramas...',
'terminal.gitBranch.empty': 'Aún no hay ramas locales',
'terminal.gitBranch.noMatches': 'No hay ramas coincidentes',
'terminal.gitBranch.unavailable': 'No se pudieron leer las ramas de esta sesión.',
'terminal.directory.unknown': 'Directorio desconocido',
'terminal.directory.search': 'Buscar subdirectorios...',
'terminal.directory.directories': 'Directorios',
+29
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.',
@@ -323,6 +329,16 @@ export const ruAiMessages: Messages = {
'ai.opencode.v2.mcpSkipped': 'OpenCode 2 не смог подключить инструмент MCP. Чат продолжится без него.',
// MiMo Code
'ai.agy.title': 'Antigravity CLI (Beta)',
'ai.agy.description': 'Экспериментальная бета-версия: CLI агента Google Antigravity через официальный протокол ACP (agy acp --stdio). Поддержка пока ограничена и не прошла полноценного тестирования — используйте на свой страх и риск. Выполните вход через agy в терминале и выберите его как внешнего агента.',
'ai.agy.detecting': 'Поиск…',
'ai.agy.detected': 'Найден',
'ai.agy.notFound': 'Не найден',
'ai.agy.path': 'Путь:',
'ai.agy.notFoundHint': 'Не удалось найти agy в PATH. Установите Antigravity CLI или укажите путь к исполняемому файлу ниже.',
'ai.agy.customPathPlaceholder': 'например, /usr/local/bin/agy',
'ai.agy.check': 'Проверить',
'ai.agy.resetPath': 'Сбросить',
'ai.mimo.title': 'MiMo Code',
'ai.mimo.description': 'MiMo Code от Xiaomi — форк OpenCode с интерфейсом командной строки. Установите его и настройте провайдеров в его конфигурации, затем выберите MiMo Code как внешнего агента для программирования.',
'ai.mimo.detecting': 'Поиск…',
@@ -633,6 +649,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 +713,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': 'Навигация',
+6
View File
@@ -4,6 +4,12 @@ export const ruTerminalMessages: Messages = {
'terminal.directory.open': 'Текущий каталог: {path}. Сменить каталог',
'terminal.gitBranch.current': 'Ветка Git: {{value}}',
'terminal.gitBranch.detached': 'Отсоединённый HEAD: {{value}}',
'terminal.gitBranch.search': 'Поиск локальных веток...',
'terminal.gitBranch.branches': 'Локальные ветки',
'terminal.gitBranch.loading': 'Чтение веток...',
'terminal.gitBranch.empty': 'Локальных веток пока нет',
'terminal.gitBranch.noMatches': 'Ветки не найдены',
'terminal.gitBranch.unavailable': 'Не удалось прочитать ветки для этого сеанса.',
'terminal.directory.unknown': 'Каталог неизвестен',
'terminal.directory.search': 'Поиск подкаталогов...',
'terminal.directory.directories': 'Каталоги',
@@ -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`);
}
}
}
});
+29
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': '输入其他答案',
@@ -305,6 +308,16 @@ export const zhCNAiMessages: Messages = {
'ai.opencode.v2.mcpSkipped': 'OpenCode 2 无法接入 MCP 工具,对话会继续,但没有该工具。',
// AI MiMo Code(小米 MiMo Code CLI,OpenCode 分支)
'ai.agy.title': 'Antigravity CLI(Beta)',
'ai.agy.description': 'Beta 测试中:通过官方 Agent Client Protocol(agy acp --stdio)接入 Google Antigravity CLI。当前支持程度有限且未经充分测试,使用请自担风险。请在终端完成 agy 登录后再作为外部编程 Agent 使用。',
'ai.agy.detecting': '检测中...',
'ai.agy.detected': '已检测到',
'ai.agy.notFound': '未找到',
'ai.agy.path': '路径:',
'ai.agy.notFoundHint': '在 PATH 中未找到 agy。请安装 Antigravity CLI 或在下方指定可执行文件路径。',
'ai.agy.customPathPlaceholder': '例如 /usr/local/bin/agy',
'ai.agy.check': '检查',
'ai.agy.resetPath': '重置',
'ai.mimo.title': 'MiMo Code',
'ai.mimo.description': '小米 MiMo Code CLI(OpenCode 分支)。安装后在它自己的配置里配置 provider 和密钥,检测到后即可作为外部编程 Agent 使用。',
'ai.mimo.detecting': '检测中...',
@@ -328,6 +341,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 +650,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 +714,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': '条消息',
@@ -4,6 +4,12 @@ export const zhCNTerminalMessages: Messages = {
'terminal.directory.open': '当前目录:{path}。更改目录',
'terminal.gitBranch.current': 'Git 分支:{{value}}',
'terminal.gitBranch.detached': '分离的 HEAD:{{value}}',
'terminal.gitBranch.search': '搜索本地分支…',
'terminal.gitBranch.branches': '本地分支',
'terminal.gitBranch.loading': '正在读取分支…',
'terminal.gitBranch.empty': '还没有本地分支',
'terminal.gitBranch.noMatches': '没有匹配的分支',
'terminal.gitBranch.unavailable': '无法读取此会话的分支。',
'terminal.directory.unknown': '目录未知',
'terminal.directory.search': '搜索当前目录下的文件夹…',
'terminal.directory.directories': '目录',
@@ -574,6 +580,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 +609,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': '导航',
+29
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': '輸入其他答案',
@@ -305,6 +308,16 @@ export const zhTWAiMessages: Messages = {
'ai.opencode.v2.mcpSkipped': 'OpenCode 2 無法掛接 MCP 工具,對話會繼續,但沒有該工具。',
// AI MiMo Code(小米 MiMo Code CLI,OpenCode 分支)
'ai.agy.title': 'Antigravity CLI(Beta)',
'ai.agy.description': 'Beta 測試中:透過官方 Agent Client Protocol(agy acp --stdio)接入 Google Antigravity CLI。目前支援程度有限且未經充分測試,使用請自負風險。請在終端完成 agy 登入後再作為外部程式設計 Agent 使用。',
'ai.agy.detecting': '偵測中...',
'ai.agy.detected': '已偵測到',
'ai.agy.notFound': '未找到',
'ai.agy.path': '路徑:',
'ai.agy.notFoundHint': '在 PATH 中未找到 agy。請安裝 Antigravity CLI 或在下方指定執行檔路徑。',
'ai.agy.customPathPlaceholder': '例如 /usr/local/bin/agy',
'ai.agy.check': '檢查',
'ai.agy.resetPath': '重設',
'ai.mimo.title': 'MiMo Code',
'ai.mimo.description': '小米 MiMo Code CLI(OpenCode 分支)。安裝後在它自己的設定裡設定 provider 和金鑰,偵測到後即可作為外部程式設計 Agent 使用。',
'ai.mimo.detecting': '偵測中...',
@@ -328,6 +341,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 +649,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 +713,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': '則訊息',
@@ -4,6 +4,12 @@ export const zhTWTerminalMessages: Messages = {
'terminal.directory.open': '目前目錄:{path}。變更目錄',
'terminal.gitBranch.current': 'Git 分支:{{value}}',
'terminal.gitBranch.detached': '分離的 HEAD:{{value}}',
'terminal.gitBranch.search': '搜尋本機分支…',
'terminal.gitBranch.branches': '本機分支',
'terminal.gitBranch.loading': '正在讀取分支…',
'terminal.gitBranch.empty': '還沒有本機分支',
'terminal.gitBranch.noMatches': '沒有符合的分支',
'terminal.gitBranch.unavailable': '無法讀取此工作階段的分支。',
'terminal.directory.unknown': '目錄未知',
'terminal.directory.search': '搜尋目前目錄下的資料夾…',
'terminal.directory.directories': '目錄',
@@ -574,6 +580,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 +609,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': '導航',
+38
View File
@@ -79,6 +79,44 @@ test('prepared apply callback runs after the snapshot with sentinel protection',
assert.equal(readInterruptedVaultApply(), null);
});
test('protected sync does not apply anything if storage cannot persist its interruption marker', async (t) => {
const storage = globalThis.localStorage;
const originalSetItem = storage.setItem;
t.after(() => { storage.setItem = originalSetItem; });
storage.setItem = () => { throw new DOMException('No storage space', 'QuotaExceededError'); };
let applied = false;
await assert.rejects(() => applyProtectedSyncPayload({
buildPreApplyPayload: emptyPayload,
applyPayload: () => { applied = true; },
translateProtectiveBackupFailure: (message) => message,
}), /interruption marker/);
assert.equal(applied, false);
assert.equal(readInterruptedVaultApply(), null);
});
test('protected sync rejects a missing backup even when the backup bridge resolves', async (t) => {
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
t.after(() => {
if (previousWindow) Object.defineProperty(globalThis, 'window', previousWindow);
else Reflect.deleteProperty(globalThis, 'window');
});
Object.defineProperty(globalThis, 'window', { configurable: true, value: {
netcatty: { createVaultBackup: async () => ({ backup: null }) },
} });
let applied = false;
await assert.rejects(() => applyProtectedSyncPayload({
buildPreApplyPayload: () => ({ ...emptyPayload(), settings: { theme: 'light' } }),
applyPayload: () => { applied = true; },
translateProtectiveBackupFailure: (message) => message,
}), /no recoverable backup/);
assert.equal(applied, false);
assert.equal(readInterruptedVaultApply(), null);
});
for (const localRestore of [false, true]) {
for (const encryptionFails of [false, true]) {
test(`protected header preparation (${localRestore ? 'restore' : 'sync'}, ${encryptionFails ? 'failure' : 'success'})`, async () => {
+9 -11
View File
@@ -241,7 +241,10 @@ export async function createRequiredProtectiveLocalVaultBackup(
reason: 'before_restore',
maxCount: getLocalVaultBackupMaxCount(),
});
return result?.backup ?? null;
if (!result?.backup?.id) {
throw new Error('Vault backup service returned no recoverable backup');
}
return result.backup;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new ProtectiveBackupUnavailableError(message);
@@ -381,16 +384,11 @@ export function clearInterruptedVaultApply(): void {
}
function writeApplyInProgressSentinel(record: VaultApplyInProgressRecord): void {
try {
localStorageAdapter.writeString(
STORAGE_KEY_VAULT_APPLY_IN_PROGRESS,
JSON.stringify(record),
);
} catch (error) {
// Sentinel write is best-effort: a failure here means a later crash
// won't be detected, but does NOT compromise the apply itself.
// Log so a systematic storage outage is diagnosable.
console.warn('[localVaultBackups] Failed to set apply-in-progress sentinel:', error);
if (!localStorageAdapter.writeString(
STORAGE_KEY_VAULT_APPLY_IN_PROGRESS,
JSON.stringify(record),
)) {
throw new Error('Cannot persist the sync interruption marker; local data was not changed');
}
}
@@ -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');
@@ -5,6 +5,8 @@ import { terminalCwdStore } from './terminalCwdStore';
import type { TerminalDirectoryIO } from '../../infrastructure/services/terminalDirectory';
import { directoryChangeCommand, COMPLETE_DIRECTORY_CAPABILITIES } from '../../domain/directoryPicker';
import { gitSwitchCommand } from '../../domain/terminalGitHead';
function setup(overrides: Partial<TerminalDirectoryIO> = {}) {
let cwd = '/old'; let ready = true; let current = true;
const writes: string[] = [];
@@ -269,3 +271,40 @@ for (const cancellation of ['abort', 'dispose'] as const) {
await assert.rejects(controller.change('/next', abort.signal, () => {}), { code: 'unavailable' });
});
}
test('local command submission rechecks cwd and prompt readiness before writing', async t => {
const sessionId = 'local-command';
const writes: string[] = [];
let ready = true;
let finishCwd!: (cwd: string) => void;
const controller = createTerminalDirectoryController({
sessionId, localPosixSessionId: 'local-pty', isCurrent: () => true, isReady: () => ready,
io: { cwd: () => new Promise(resolve => { finishCwd = resolve; }), list: async () => ({ entries: [], home: null }),
realpath: async value => value, write: data => { writes.push(data); } },
publish() {},
});
terminalCwdStore.setCwd(sessionId, '/repo', 'osc7');
t.after(() => { controller.dispose(); terminalCwdStore.setCwd(sessionId, null); });
const command = gitSwitchCommand("/repo", "topic/it's-$special");
assert.ok(command);
const send = (signal = new AbortController().signal) => controller.sendLocalCommand(command, '/repo', signal);
const moved = send();
finishCwd('/other');
await assert.rejects(moved, { code: 'unavailable' });
const busy = send();
ready = false;
finishCwd('/repo');
await assert.rejects(busy, { code: 'busy' });
ready = true;
const request = new AbortController();
const cancelled = send(request.signal);
request.abort();
finishCwd('/repo');
await assert.rejects(cancelled, { code: 'unavailable' });
assert.deepEqual(writes, []);
const sent = send();
finishCwd('/repo');
await sent;
assert.deepEqual(writes, [command + '\r']);
});
@@ -185,11 +185,35 @@ export function createTerminalDirectoryController(options: {
check(signal);
} finally { confirmationFinished = true; changing = false; }
}
async function sendLocalCommand(command: string, expectedCwd: string, signal: AbortSignal) {
ready();
check(signal);
if (!options.localPosixSessionId || getConfirmedCwd() !== expectedCwd) throw new DirectoryPickerError('unavailable');
if (changing) throw new DirectoryPickerError('busy');
changing = true;
try {
const revision = terminalCwdStore.getSessionRevision(options.sessionId);
const liveCwd = await bounded(options.io.cwd(), signal);
if (!same(liveCwd, expectedCwd)) {
const [livePath, expectedPath] = await bounded(Promise.all([
options.io.realpath(liveCwd, signal), options.io.realpath(expectedCwd, signal),
]), signal);
if (!same(livePath, expectedPath)) throw new DirectoryPickerError('unavailable');
}
check(signal);
ready();
if (getConfirmedCwd() !== expectedCwd || terminalCwdStore.getSessionRevision(options.sessionId) !== revision) {
throw new DirectoryPickerError('unavailable');
}
options.io.write(command + '\r');
} finally { changing = false; }
}
return {
target,
localPosixSessionId: options.localPosixSessionId,
capabilities,
getConfirmedCwd,
sendLocalCommand,
subscribeCwd(listener: () => void) {
const unsubscribe = terminalCwdStore.subscribe(listener);
cwdListeners.add(listener);
+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 };
}
@@ -27,8 +27,8 @@ test('Git chip follows confirmed cwd and ignores an old worktree result', async
const unregister = registerTerminalDirectory(id, controller);
const stopObserving = observeTerminalDirectory(id);
let root!: ReactTestRenderer;
let head: ReturnType<typeof useComposeGitBranch>;
function Harness() { head = useComposeGitBranch(id); return null; }
let head: ReturnType<typeof useComposeGitBranch>['head'];
function Harness() { head = useComposeGitBranch(id).head; return null; }
const waitForCalls = async (count: number) => {
for (let i = 0; calls.length < count && i < 100; i++) await new Promise(resolve => setTimeout(resolve, 10));
assert.equal(calls.length, count);
+35 -4
View File
@@ -1,5 +1,6 @@
import { useEffect, useState, useSyncExternalStore } from 'react';
import type { TerminalGitHead } from '../../domain/terminalGitHead';
import { DirectoryPickerError } from '../../domain/directoryPicker';
import { useEffect, useMemo, useState, useSyncExternalStore } from 'react';
import { gitSwitchCommand, type TerminalGitHead } from '../../domain/terminalGitHead';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
import { getTerminalDirectory, subscribeTerminalDirectories, subscribeTerminalDirectoryRefresh } from './terminalDirectoryRegistry';
import type { TerminalDirectoryController } from './terminalDirectoryController';
@@ -8,7 +9,7 @@ const noCwd = () => null;
const noSubscription = () => () => {};
const REFRESH_DELAY_MS = 150;
export function useComposeGitBranch(sessionId: string): TerminalGitHead | null {
export function useComposeGitBranch(sessionId: string) {
const controller = useSyncExternalStore(subscribeTerminalDirectories, () => getTerminalDirectory(sessionId), () => null);
const backendId = controller?.localPosixSessionId;
const cwd = useSyncExternalStore(
@@ -18,6 +19,11 @@ export function useComposeGitBranch(sessionId: string): TerminalGitHead | null {
);
const [result, setResult] = useState<{ controller: TerminalDirectoryController; cwd: string; head: TerminalGitHead | null } | null>(null);
const scope = useMemo(() => controller && backendId && cwd ? { controller, backendId, cwd, sessionId } : null,
[backendId, controller, cwd, sessionId]);
const isCurrent = () => scope !== null && getTerminalDirectory(sessionId) === scope.controller
&& scope.controller.getConfirmedCwd() === scope.cwd;
useEffect(() => {
const bridge = netcattyBridge.get();
if (!controller || !backendId || !cwd || !bridge?.readLocalSessionGitHead) return;
@@ -63,5 +69,30 @@ export function useComposeGitBranch(sessionId: string): TerminalGitHead | null {
};
}, [backendId, controller, cwd, sessionId]);
return result?.controller === controller && result.cwd === cwd ? result.head : null;
const head = result?.controller === controller && result.cwd === cwd ? result.head : null;
const bridge = netcattyBridge.get();
return {
head,
scope,
canSwitch: Boolean(bridge?.listLocalSessionGitBranches),
async list(worktreeRoot: string) {
try {
if (scope && isCurrent()) {
const next = await bridge?.listLocalSessionGitBranches?.(scope.backendId, scope.cwd, worktreeRoot);
if (isCurrent() && next) return next;
}
} catch { /* The menu displays the unavailable state. */ }
return { kind: 'unavailable' } as const;
},
async switchBranch(worktreeRoot: string, name: string, signal: AbortSignal): Promise<'sent' | 'busy' | 'unavailable'> {
const command = gitSwitchCommand(worktreeRoot, name);
if (!command || !scope || !isCurrent()) return 'unavailable';
try {
await scope.controller.sendLocalCommand(command, scope.cwd, signal);
return 'sent';
} catch (error) {
return error instanceof DirectoryPickerError && error.code === 'busy' ? 'busy' : 'unavailable';
}
},
};
}
+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. */
+1
View File
@@ -400,6 +400,7 @@ export function shouldLoadSdkRuntimeModels(agent?: ExternalAgentConfig): boolean
return sdkBackend === 'codex'
|| sdkBackend === 'claude'
|| sdkBackend === 'copilot'
|| sdkBackend === 'agy'
|| sdkBackend === 'cursor'
|| sdkBackend === 'codebuddy'
|| sdkBackend === 'opencode'
+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,
);
});
+10 -4
View File
@@ -1,7 +1,7 @@
import { terminalCwdStore } from '../application/state/terminalCwdStore';
import { useTerminalExternalEditor } from '../application/state/useTerminalExternalEditor';
import { useTerminalDirectorySession } from '../application/state/useTerminalDirectorySession';
import { refreshObservedTerminalDirectory, scheduleObservedTerminalDirectoryRefresh } from '../application/state/terminalDirectoryRegistry';
import { getTerminalDirectory, refreshObservedTerminalDirectory, scheduleObservedTerminalDirectoryRefresh } from '../application/state/terminalDirectoryRegistry';
import { publishTerminalSelectionTarget } from "../infrastructure/plugins/terminalSelectionRegistry";
import { usePluginTerminalSelection } from "../application/state/usePluginTerminalSelection";
import { clearTerminalBroadcastUserInput, markTerminalBroadcastUserInput } from "./terminal/runtime/terminalPacedBroadcast";
@@ -640,12 +640,18 @@ const TerminalComponent: React.FC<TerminalProps> = ({
const onTerminalDataCaptureRef = useRef(onTerminalDataCapture);
const onSessionExitRef = useRef(onSessionExit);
const commandBufferRef = useRef<string>("");
const detectCommandPrompt = useCallback((term: XTerm) => {
const directory = getTerminalDirectory(sessionId);
const macShellCwd = directory?.localPosixSessionId && detectLocalOs(navigator.platform) === "macos"
? directory.getConfirmedCwd() : null;
return detectPrompt(term, macShellCwd);
}, [sessionId]);
useEffect(() => registerTerminalCommandInjectionReadyReader(
sessionId,
(options) => {
const term = termRef.current;
if (!term) return false;
const prompt = detectPrompt(term);
const prompt = detectCommandPrompt(term);
const readiness = {
sensitiveInputActive: passwordPromptActiveRef.current,
hasLiveTerminal: true,
@@ -662,7 +668,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
() => {
const term = termRef.current;
if (!term) return null;
const prompt = detectPrompt(term);
const prompt = detectCommandPrompt(term);
if (!prompt.isAtPrompt) return null;
return {
promptText: prompt.promptText,
@@ -670,7 +676,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
pendingTypedInput: commandBufferRef.current,
};
},
), [sessionId]);
), [sessionId, detectCommandPrompt]);
const promptLineBreakStateRef = useRef<PromptLineBreakState>(createPromptLineBreakState());
const [hasMouseTracking, setHasMouseTracking] = useState(false);
const mouseTrackingRef = useRef(false);
+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 }) {
+92 -82
View File
@@ -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";
@@ -251,10 +252,11 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
codex: string;
claude: string;
copilot: string;
agy: string;
cursor: string;
codebuddy: string;
opencode: string;
grok: string;
codebuddy: string;
mimo: string;
} | null>(null);
if (!initialManagedPathsRef.current) {
@@ -305,6 +307,12 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
const [copilotCustomPath, setCopilotCustomPath] = useState(() => initialManagedPathsRef.current?.copilot ?? "");
const [isResolvingCopilot, setIsResolvingCopilot] = useState(false);
const [agyPathInfo, setAgyPathInfo] = useState<AgentPathInfo | null>(
() => getSavedManagedAgentPathInfo(externalAgents, "agy"),
);
const [agyCustomPath, setAgyCustomPath] = useState(() => initialManagedPathsRef.current?.agy ?? "");
const [isResolvingAgy, setIsResolvingAgy] = useState(false);
const [cursorPathInfo, setCursorPathInfo] = useState<AgentPathInfo | null>(
() => getSavedManagedAgentPathInfo(externalAgents, "cursor"),
);
@@ -384,34 +392,27 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
return () => {
mountedRef.current = false;
codexRequestIdRef.current += 1;
for (const key of ["codex", "claude", "copilot", "cursor", "codebuddy", "opencode", "grok", "mimo"] as ManagedAgentKey[]) {
for (const key of ["codex", "claude", "copilot", "agy", "cursor", "opencode", "grok", "codebuddy", "mimo"] as ManagedAgentKey[]) {
agentPathRequestIds[key] = (agentPathRequestIds[key] ?? 0) + 1;
}
};
}, []);
const setManagedAgentPathInfo = useCallback((key: ManagedAgentKey, result: AgentPathInfo | null) => {
const setters = {
agy: setAgyPathInfo, claude: setClaudePathInfo, codebuddy: setCodebuddyPathInfo,
codex: setCodexPathInfo, copilot: setCopilotPathInfo, cursor: setCursorPathInfo,
grok: setGrokPathInfo, mimo: setMimoPathInfo, opencode: setOpencodePathInfo,
};
setters[key](result);
}, []);
const applyResolvedAgentPath = useCallback((
agentKey: ManagedAgentKey,
result: AgentPathInfo | null,
commandSource: "manual" | "auto" = "auto",
) => {
const setInfo = agentKey === "codex"
? setCodexPathInfo
: agentKey === "claude"
? setClaudePathInfo
: agentKey === "copilot"
? setCopilotPathInfo
: agentKey === "cursor"
? setCursorPathInfo
: agentKey === "codebuddy"
? setCodebuddyPathInfo
: agentKey === "opencode"
? setOpencodePathInfo
: agentKey === "grok"
? setGrokPathInfo
: setMimoPathInfo;
setInfo(result);
setManagedAgentPathInfo(agentKey, result);
const savedPaths = initialManagedPathsRef.current;
if (savedPaths && (commandSource === "auto" || (result?.available && result.path))) {
savedPaths[agentKey] = commandSource === "manual" ? result?.path ?? "" : "";
@@ -429,7 +430,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
if (nextDefaultId !== null) {
setDefaultAgentId(nextDefaultId);
}
}, [setDefaultAgentId, setExternalAgents]);
}, [setDefaultAgentId, setExternalAgents, setManagedAgentPathInfo]);
const resolveAgentPath = useCallback(async (
agentKey: ManagedAgentKey,
@@ -450,15 +451,17 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
? setIsResolvingClaude
: agentKey === "copilot"
? setIsResolvingCopilot
: agentKey === "cursor"
? setIsResolvingCursor
: agentKey === "codebuddy"
? setIsResolvingCodebuddy
: agentKey === "opencode"
? setIsResolvingOpencode
: agentKey === "grok"
? setIsResolvingGrok
: setIsResolvingMimo;
: agentKey === "agy"
? setIsResolvingAgy
: agentKey === "cursor"
? setIsResolvingCursor
: agentKey === "codebuddy"
? setIsResolvingCodebuddy
: agentKey === "opencode"
? setIsResolvingOpencode
: agentKey === "grok"
? setIsResolvingGrok
: setIsResolvingMimo;
setResolving(true);
const requestId = (agentPathRequestIdRef.current[agentKey] ?? 0) + 1;
@@ -487,22 +490,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
&& !result?.available
&& !options.recheckSavedPath
) {
const setInfo = agentKey === "codex"
? setCodexPathInfo
: agentKey === "claude"
? setClaudePathInfo
: agentKey === "copilot"
? setCopilotPathInfo
: agentKey === "cursor"
? setCursorPathInfo
: agentKey === "codebuddy"
? setCodebuddyPathInfo
: agentKey === "opencode"
? setOpencodePathInfo
: agentKey === "grok"
? setGrokPathInfo
: setMimoPathInfo;
setInfo(result);
setManagedAgentPathInfo(agentKey, result);
return result;
}
applyResolvedAgentPath(agentKey, result, options?.commandSource ?? "auto");
@@ -516,7 +504,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
setResolving(false);
}
}
}, [applyResolvedAgentPath, cursorApiKeyEncrypted]);
}, [applyResolvedAgentPath, cursorApiKeyEncrypted, setManagedAgentPathInfo]);
useEffect(() => {
if (activeSubTab !== "agents") return;
@@ -531,16 +519,17 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
{ key: "codex", delayMs: 160, path: initialPaths?.codex ?? "" },
{ key: "claude", delayMs: 440, path: initialPaths?.claude ?? "" },
{ key: "copilot", delayMs: 720, path: initialPaths?.copilot ?? "" },
{ key: "agy", delayMs: 960, path: initialPaths?.agy ?? "" },
{
key: "cursor",
delayMs: 1000,
delayMs: 1200,
path: initialPaths?.cursor ?? "",
options: { apiKeyPresent: Boolean(cursorApiKeyEncrypted) },
},
{ key: "codebuddy", delayMs: 1280, path: initialPaths?.codebuddy ?? "" },
{ key: "opencode", delayMs: 1560, path: initialPaths?.opencode ?? "" },
{ key: "grok", delayMs: 1840, path: initialPaths?.grok ?? "" },
{ key: "mimo", delayMs: 2120, path: initialPaths?.mimo ?? "" },
{ key: "opencode", delayMs: 1440, path: initialPaths?.opencode ?? "" },
{ key: "grok", delayMs: 1680, path: initialPaths?.grok ?? "" },
{ key: "codebuddy", delayMs: 1920, path: initialPaths?.codebuddy ?? "" },
{ key: "mimo", delayMs: 2160, path: initialPaths?.mimo ?? "" },
];
const cancelTasks = tasks
.filter((task) => !autoResolvedAgentStateRef.current[task.key])
@@ -809,15 +798,17 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
? claudeCustomPath
: agentKey === "copilot"
? copilotCustomPath
: agentKey === "codebuddy"
? codebuddyCustomPath
: agentKey === "opencode"
? opencodeCustomPath
: agentKey === "grok"
? grokCustomPath
: agentKey === "mimo"
? mimoCustomPath
: "";
: agentKey === "agy"
? agyCustomPath
: agentKey === "codebuddy"
? codebuddyCustomPath
: agentKey === "opencode"
? opencodeCustomPath
: agentKey === "grok"
? grokCustomPath
: agentKey === "mimo"
? mimoCustomPath
: "";
const result = await resolveAgentPath(agentKey, customPath, {
refreshShellEnv: true,
commandSource: customPath.trim() ? "manual" : "auto",
@@ -829,7 +820,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
codexPath: result?.path || customPath.trim() || undefined,
});
}
}, [claudeCustomPath, codexCustomPath, copilotCustomPath, codebuddyCustomPath, opencodeCustomPath, grokCustomPath, mimoCustomPath, resolveAgentPath, refreshCodexIntegration]);
}, [claudeCustomPath, codexCustomPath, copilotCustomPath, agyCustomPath, codebuddyCustomPath, opencodeCustomPath, grokCustomPath, mimoCustomPath, resolveAgentPath, refreshCodexIntegration]);
const handleResetCustomPath = useCallback(async (agentKey: ManagedAgentKey) => {
if (agentKey === "codex") {
@@ -838,6 +829,8 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
setClaudeCustomPath("");
} else if (agentKey === "copilot") {
setCopilotCustomPath("");
} else if (agentKey === "agy") {
setAgyCustomPath("");
} else if (agentKey === "codebuddy") {
setCodebuddyCustomPath("");
} else if (agentKey === "opencode") {
@@ -1206,6 +1199,22 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
/>
</SettingsSection>
<SettingsSection
anchorId="ai-agy"
title={t('ai.agy.title')}
leading={<AgentIconBadge agent={{ id: "agy", icon: "google", name: "Antigravity CLI" }} variant="plain" className="h-5 w-5 text-muted-foreground/90" />}
>
<CopilotCliCard
pathInfo={agyPathInfo}
isResolvingPath={isResolvingAgy}
customPath={agyCustomPath}
onCustomPathChange={setAgyCustomPath}
onRecheckPath={() => void handleCheckCustomPath("agy")}
onResetPath={() => void handleResetCustomPath("agy")}
i18nPrefix="ai.agy"
/>
</SettingsSection>
<SettingsSection
anchorId="ai-cursor"
title={t('ai.cursor.title')}
@@ -1222,27 +1231,6 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
/>
</SettingsSection>
<SettingsSection
anchorId="ai-codebuddy"
title={t('ai.codebuddy.title')}
leading={<AgentIconBadge agent={{ id: "codebuddy", icon: "codebuddy", name: "CodeBuddy Code" }} variant="plain" className="h-5 w-5 text-muted-foreground/90" />}
>
<CodebuddyCard
pathInfo={codebuddyPathInfo}
isResolvingPath={isResolvingCodebuddy}
customPath={codebuddyCustomPath}
onCustomPathChange={setCodebuddyCustomPath}
onRecheckPath={() => void handleCheckCustomPath("codebuddy")}
onResetPath={() => void handleResetCustomPath("codebuddy")}
internetEnv={codebuddyInternetEnv}
onInternetEnvChange={(v) => updateCodebuddyEnv(v, codebuddyEnvText)}
envText={codebuddyEnvText}
onEnvTextChange={(v) => updateCodebuddyEnv(codebuddyInternetEnv, v)}
advancedOptions={codebuddyAdvancedOptions}
onAdvancedOptionsChange={updateCodebuddyAdvancedOptions}
/>
</SettingsSection>
<SettingsSection
title={t('ai.opencode.title')}
leading={<AgentIconBadge agent={{ id: "opencode", icon: "opencode", name: "OpenCode" }} variant="plain" className="h-5 w-5 text-muted-foreground/90" />}
@@ -1279,6 +1267,27 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
/>
</SettingsSection>
<SettingsSection
anchorId="ai-codebuddy"
title={t('ai.codebuddy.title')}
leading={<AgentIconBadge agent={{ id: "codebuddy", icon: "codebuddy", name: "CodeBuddy Code" }} variant="plain" className="h-5 w-5 text-muted-foreground/90" />}
>
<CodebuddyCard
pathInfo={codebuddyPathInfo}
isResolvingPath={isResolvingCodebuddy}
customPath={codebuddyCustomPath}
onCustomPathChange={setCodebuddyCustomPath}
onRecheckPath={() => void handleCheckCustomPath("codebuddy")}
onResetPath={() => void handleResetCustomPath("codebuddy")}
internetEnv={codebuddyInternetEnv}
onInternetEnvChange={(v) => updateCodebuddyEnv(v, codebuddyEnvText)}
envText={codebuddyEnvText}
onEnvTextChange={(v) => updateCodebuddyEnv(codebuddyInternetEnv, v)}
advancedOptions={codebuddyAdvancedOptions}
onAdvancedOptionsChange={updateCodebuddyAdvancedOptions}
/>
</SettingsSection>
<SettingsSection
title={t('ai.mimo.title')}
leading={<AgentIconBadge agent={{ id: "mimo", icon: "mimo", name: "MiMo Code" }} variant="plain" className="h-5 w-5 text-muted-foreground/90" />}
@@ -1383,6 +1392,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>
);
}
@@ -14,7 +14,7 @@ export const CopilotCliCard: React.FC<{
onCustomPathChange: (path: string) => void;
onRecheckPath: () => void;
onResetPath?: () => void;
i18nPrefix?: "ai.copilot" | "ai.cursor" | "ai.opencode" | "ai.grok" | "ai.mimo";
i18nPrefix?: "ai.copilot" | "ai.agy" | "ai.cursor" | "ai.opencode" | "ai.grok" | "ai.mimo";
allowEmptyCheck?: boolean;
showCustomPathInput?: boolean;
/** Grok only: ACP (default) vs headless streaming-json. */
@@ -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",
};
@@ -256,10 +256,11 @@ export function getInitialManagedAgentPaths(agents: ExternalAgentConfig[]) {
codex: getAutoManagedAgentStoredPath(agents, "codex") ?? "",
claude: getAutoManagedAgentStoredPath(agents, "claude") ?? "",
copilot: getAutoManagedAgentStoredPath(agents, "copilot") ?? "",
agy: getAutoManagedAgentStoredPath(agents, "agy") ?? "",
cursor: getAutoManagedAgentStoredPath(agents, "cursor") ?? "",
codebuddy: getAutoManagedAgentStoredPath(agents, "codebuddy") ?? "",
opencode: getAutoManagedAgentStoredPath(agents, "opencode") ?? "",
grok: getAutoManagedAgentStoredPath(agents, "grok") ?? "",
codebuddy: getAutoManagedAgentStoredPath(agents, "codebuddy") ?? "",
mimo: getAutoManagedAgentStoredPath(agents, "mimo") ?? "",
};
}
+6
View File
@@ -242,6 +242,12 @@ export const AGENT_DEFAULTS: Record<string, Omit<ExternalAgentConfig, "id" | "co
icon: "grok",
sdkBackend: "grok",
},
agy: {
name: "Antigravity CLI",
args: [],
icon: "google",
sdkBackend: "agy",
},
mimo: {
name: "MiMo Code",
args: [],
+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;
+175 -14
View File
@@ -1,25 +1,186 @@
import { GitBranch } from 'lucide-react';
import { defaultRangeExtractor, useVirtualizer } from '@tanstack/react-virtual';
import { Check, ChevronDown, GitBranch, LoaderCircle } from 'lucide-react';
import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
import { useI18n } from '../../application/i18n/I18nProvider';
import { useComposeGitBranch } from '../../application/state/useComposeGitBranch';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import type { ComposeBarTheme } from './TerminalComposeBar';
export function ComposeGitBranchChip({ sessionId, theme }: { sessionId: string; theme: ComposeBarTheme }) {
type Menu = {
scope: ReturnType<typeof useComposeGitBranch>['scope'];
root: string;
branches: readonly string[];
status: 'loading' | 'ready' | 'sending' | 'busy' | 'unavailable';
};
const chipClass = 'flex h-6 min-w-0 max-w-[min(180px,35%)] shrink items-center gap-1.5 rounded border px-2 font-mono text-[11px]';
const branchRowHeight = 32;
const branchViewportHeight = branchRowHeight * 7;
export function ComposeGitBranchChip({ sessionId, theme, onReturnFocus }: {
sessionId: string; theme: ComposeBarTheme; onReturnFocus: () => void;
}) {
const { t } = useI18n();
const head = useComposeGitBranch(sessionId);
const model = useComposeGitBranch(sessionId);
const [menu, setMenu] = useState<Menu | null>(null);
const [query, setQuery] = useState('');
const [active, setActive] = useState<number | null>(null);
const search = useRef<HTMLInputElement>(null);
const viewport = useRef<HTMLDivElement>(null);
const outside = useRef(false);
const composing = useRef(false);
const submission = useRef<AbortController | null>(null);
useEffect(() => () => submission.current?.abort(), [model.scope]);
const listId = useId();
const head = model.head;
const current = menu && menu.scope === model.scope && menu.root === head?.worktreeRoot ? menu : null;
const branches = current?.branches;
const searchText = query.trim().toLowerCase();
const filtered = useMemo(() => {
if (!branches) return [];
return searchText ? branches.filter(name => name.toLowerCase().includes(searchText)) : branches;
}, [branches, searchText]);
const selected = active ?? (filtered.length ? 0 : -1);
const virtualizer = useVirtualizer({
count: filtered.length,
getScrollElement: () => viewport.current,
estimateSize: () => branchRowHeight,
overscan: 4,
rangeExtractor: useCallback(range => {
const visible = defaultRangeExtractor(range);
// Keep the combobox's active descendant mounted when scrolling by mouse.
return selected < 0 || visible.includes(selected) ? visible : [...visible, selected].sort((a, b) => a - b);
}, [selected]),
});
if (!head) return null;
const text = head.kind === 'branch' ? head.name : head.hash;
const label = t(head.kind === 'branch' ? 'terminal.gitBranch.current' : 'terminal.gitBranch.detached', { value: text });
const chipStyle = { backgroundColor: theme.chipBg, borderColor: theme.borderColor, color: theme.resolvedFg };
const chipContent = <><GitBranch size={12} className="shrink-0" aria-hidden="true" />
<span className="truncate" dir="auto">{text}</span></>;
if (!model.canSwitch) {
return <div data-compose-git-branch role="group" aria-label={label} title={label} className={chipClass} style={chipStyle}>{chipContent}</div>;
}
const currentBranch = head.kind === 'branch' ? head.name : null;
const canSelect = current?.status === 'ready' || current?.status === 'busy';
function closeMenu() {
submission.current?.abort();
setMenu(null);
}
async function openMenu() {
if (!head) return;
outside.current = false;
composing.current = false;
setQuery('');
setActive(null);
const pending: Menu = { scope: model.scope, root: head.worktreeRoot, branches: [], status: 'loading' };
setMenu(pending);
const result = await model.list(head.worktreeRoot);
setMenu(value => value !== pending ? value : result.kind === 'branches'
? { ...pending, status: 'ready', branches: result.branches }
: { ...pending, status: result.kind });
}
async function choose(name: string) {
if (!current || !canSelect || submission.current) return;
const request = new AbortController();
submission.current = request;
const pending: Menu = { ...current, status: 'sending' };
setMenu(pending);
try {
const result = await model.switchBranch(current.root, name, request.signal);
if (!request.signal.aborted) {
setMenu(value => value !== pending ? value : result === 'sent' ? null : { ...pending, status: result });
}
} finally {
submission.current = null;
}
}
return (
<div
data-compose-git-branch
role="group"
aria-label={label}
title={label}
className="flex h-6 min-w-0 max-w-[min(180px,35%)] shrink items-center gap-1.5 overflow-hidden rounded border px-2 font-mono text-[11px]"
style={{ backgroundColor: theme.chipBg, borderColor: theme.borderColor, color: theme.resolvedFg }}
>
<GitBranch size={12} className="shrink-0" aria-hidden="true" />
<span className="truncate" dir="auto">{text}</span>
</div>
<Popover open={current !== null} onOpenChange={value => { if (value) void openMenu(); else closeMenu(); }}>
<PopoverTrigger asChild>
<button type="button" data-compose-git-branch title={label} aria-label={label}
className={`${chipClass} focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2`}
style={chipStyle}
onMouseEnter={event => { event.currentTarget.style.backgroundColor = theme.chipHoverBg; }}
onMouseLeave={event => { event.currentTarget.style.backgroundColor = theme.chipBg; }}>
{chipContent}<ChevronDown size={10} className="shrink-0 opacity-60" aria-hidden="true" />
</button>
</PopoverTrigger>
<PopoverContent side="top" align="start" sideOffset={6}
className="w-[360px] max-w-[calc(100vw-16px)] overflow-hidden p-0"
style={{ backgroundColor: theme.resolvedBg, borderColor: theme.borderColor, color: theme.resolvedFg }}
onOpenAutoFocus={event => { event.preventDefault(); search.current?.focus(); }}
onInteractOutside={() => { outside.current = true; }}
onCloseAutoFocus={event => { event.preventDefault(); if (!outside.current) onReturnFocus(); }}
onContextMenu={event => event.stopPropagation()}
onKeyDown={event => {
event.stopPropagation();
if (event.target !== search.current || composing.current || event.nativeEvent.isComposing) return;
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault();
if (!filtered.length) return;
const next = Math.max(0, Math.min(filtered.length - 1, selected + (event.key === 'ArrowDown' ? 1 : -1)));
setActive(next);
virtualizer.scrollToIndex(next, { align: 'auto' });
} else if (event.key === 'Enter') {
event.preventDefault();
if (filtered[selected]) void choose(filtered[selected]);
}
}}>
<div className="border-b px-3 py-2" style={{ borderColor: theme.borderColor }}>
<input ref={search} value={query} onChange={event => {
setQuery(event.target.value);
setActive(null);
if (viewport.current) viewport.current.scrollTop = 0;
}}
role="combobox" aria-autocomplete="list" aria-expanded="true" aria-controls={listId}
aria-activedescendant={filtered[selected] ? `${listId}-${selected}` : undefined}
aria-label={t('terminal.gitBranch.search')} placeholder={t('terminal.gitBranch.search')}
className="w-full bg-transparent text-xs outline-none placeholder:opacity-60"
onCompositionStart={() => { composing.current = true; }}
onCompositionEnd={() => { composing.current = false; }} />
</div>
<div ref={viewport} id={listId} role="listbox" aria-label={t('terminal.gitBranch.branches')}
className="overflow-y-auto overscroll-contain" style={{ maxHeight: branchViewportHeight }}
aria-busy={current?.status === 'loading' || current?.status === 'sending'}>
<div role="presentation" style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
{virtualizer.getVirtualItems().map(({ index, start, size }) => {
const name = filtered[index];
return (
<div key={name} id={`${listId}-${index}`} role="option" aria-selected={name === currentBranch}
aria-posinset={index + 1} aria-setsize={filtered.length} aria-disabled={!canSelect} title={name}
className="absolute inset-x-0 flex items-center gap-2 px-3 py-1 font-mono text-xs"
style={{ top: start, height: size, backgroundColor: index === selected ? theme.chipHoverBg : undefined, cursor: canSelect ? 'pointer' : undefined }}
onPointerMove={() => setActive(index)} onMouseDown={event => event.preventDefault()}
onClick={() => { void choose(name); }}>
<span className="w-3 shrink-0" aria-hidden="true">{name === currentBranch && <Check size={12} />}</span>
<span className="min-w-0 truncate" dir="auto">{name}</span>
</div>
);
})}
</div>
</div>
{current?.status === 'loading' ? (
<p className="flex items-center gap-2 px-3 py-2 text-xs" role="status">
<LoaderCircle size={12} className="animate-spin" aria-hidden="true" />
{t('terminal.gitBranch.loading')}
</p>
) : current?.status === 'busy' || current?.status === 'unavailable' ? (
<div className="max-h-32 overflow-y-auto px-3 py-2 text-xs" role="alert">
{t(current.status === 'busy' ? 'terminal.directory.busy' : 'terminal.gitBranch.unavailable')}
</div>
) : canSelect && !filtered.length && (
<p className="px-3 py-2 text-xs" role="status" style={{ color: theme.mutedFg }}>
{t(query.trim() ? 'terminal.gitBranch.noMatches' : 'terminal.gitBranch.empty')}
</p>
)}
</PopoverContent>
</Popover>
);
}
+53 -1
View File
@@ -1,7 +1,7 @@
import test from "node:test";
import assert from "node:assert/strict";
import { detectPrompt, getAlignedPrompt, isProgramInputPromptText } from "./autocomplete/promptDetector.ts";
import { detectPrompt, noteMacShellPromptEdit, getAlignedPrompt, isProgramInputPromptText } from "./autocomplete/promptDetector.ts";
import { resolveAutocompleteQueryInput } from "./autocomplete/terminalAutocompletePrompt.ts";
import { getSnippetSuggestions } from "./autocomplete/snippetCompleter.ts";
import { stringCellWidth } from "./autocomplete/terminalStringCellWidth.ts";
@@ -59,6 +59,58 @@ function createWrappedFakeTerm(rows: string[], cursorY: number, cursorX: number,
};
}
test('recognizes the macOS Bash and sh login prompt without swallowing typed input', () => {
for (const [prompt, cwd] of [
['MacBook-Pro:~ tester$ ', '/Users/tester'], ['MacBook-Pro:work tree tester$ ', '/src/work tree'],
['MacBook-Pro:logical alias tester$ ', '/Users/tester/physical repo'],
['MacBook-Pro:/ root# ', '/'], ['MacBook-Pro:C# repo tester$ ', '/src/C# repo'],
['MacBook-Pro:$ prices root# ', '/src/$ prices'],
]) {
for (const input of ['', 'echo hi > output', 'echo value # comment', 'echo tester$ more', 'echo root# more']) {
const text = prompt + input;
const detected = detectPrompt(createPaddedFakeTerm(text, stringCellWidth(text)) as never, cwd);
assert.equal(detected.promptText, prompt);
assert.equal(detected.userInput, input);
assert.equal(isIdleShellReadyForCommandInjection({
hasLiveTerminal: true,
alternateScreenActive: false,
isAtPrompt: detected.isAtPrompt,
userInputLength: detected.userInput.length,
}), input === '');
}
}
});
test('a host prompt preserves recalled input even when the command ends with a prompt marker', () => {
for (const prompt of ['host:~/repo$ ', 'host:repo$ ', 'host: ']) {
const input = 'echo value$';
const text = prompt + input;
const term = createPaddedFakeTerm(text, stringCellWidth(text)) as never;
for (const cwd of [undefined, '/src/repo']) {
const detected = detectPrompt(term, cwd);
assert.equal(detected.promptText, prompt);
assert.equal(detected.userInput, input);
}
}
});
test('macOS history recall cannot extend the prompt beyond its pre-edit cursor', () => {
for (const recalled of ['echo value$', 'echo value$ ', 'repo tester$ ']) {
const prompt = 'host:';
const screen = createPaddedFakeTerm(prompt, prompt.length);
noteMacShellPromptEdit(screen as never, '\x1b[A');
const edited = prompt + recalled;
screen.buffer.active = createPaddedFakeTerm(edited, edited.length).buffer.active;
const detected = detectPrompt(screen as never, '/src/repo');
assert.equal(detected.isAtPrompt && !detected.userInput.length, false);
// A new command line can have a different prompt after changing directory.
noteMacShellPromptEdit(screen as never, '\r');
const next = 'MacBook-Pro:logical alias tester$ ';
screen.buffer.active = createPaddedFakeTerm(next, next.length).buffer.active;
assert.equal(detectPrompt(screen as never, '/src/repo').promptText, next);
}
});
test('long native Windows paths remain empty shell prompts for directory navigation', () => {
const prompts = [
String.raw`PS C:\Users\tester\git\Netcatty-directory-picker> `,
+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,
+1 -1
View File
@@ -825,7 +825,7 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
theme={theme}
onReturnFocus={handleReturnFocus}
/>
<ComposeGitBranchChip key={`git-${sessionId}`} sessionId={sessionId} theme={theme} />
<ComposeGitBranchChip key={`git-${sessionId}`} sessionId={sessionId} theme={theme} onReturnFocus={handleReturnFocus} />
{pinnedSnippets.length > 0 && (
<span
aria-hidden="true"
@@ -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
@@ -582,10 +582,23 @@ function alignThemedDecorationWithPartialEcho(
return null;
}
// History recall can replace the shell buffer without updating the typed-command
// buffer. Record where editing began before the shell echoes the first key.
const macPromptLengthsBeforeEdit = new WeakMap<XTerm, number>();
export function noteMacShellPromptEdit(term: XTerm, data: string): void {
if (data === "\r" || data === "\n" || data === "\x03") {
macPromptLengthsBeforeEdit.delete(term);
} else if (!macPromptLengthsBeforeEdit.has(term)) {
const prefix = getWrappedCursorPrefix(term) ?? getCursorLinePrefix(term);
macPromptLengthsBeforeEdit.set(term, prefix?.length ?? 0);
}
}
/**
* Detect whether the terminal cursor is at a shell prompt and extract the current user input.
*/
export function detectPrompt(term: XTerm): PromptDetectionResult {
export function detectPrompt(term: XTerm, macShellCwd?: string | null): PromptDetectionResult {
const buffer = term.buffer.active;
const cursorY = buffer.cursorY + buffer.baseY;
const cursorX = buffer.cursorX;
@@ -628,7 +641,7 @@ export function detectPrompt(term: XTerm): PromptDetectionResult {
const promptScanText = afterCursor.trim().length > 0
? lineText
: cursorLinePrefix;
const promptEnd = findPromptBoundary(promptScanText);
const promptEnd = findPromptBoundary(promptScanText, macShellCwd, macPromptLengthsBeforeEdit.get(term));
// Colon read-prompts (`Email: `) stay out of shell prompt detection. Autocomplete
// opts in later via alignTypedInputFromCursorPrefix.
if (promptEnd >= 0 && !isProgramInputPromptText(lineText.substring(0, promptEnd))) {
@@ -660,7 +673,7 @@ export function detectPrompt(term: XTerm): PromptDetectionResult {
if (promptLine) {
const promptLineText = promptLine.translateToString(false);
if (isSensitiveTerminalChallenge(promptLineText) || isNonPromptLine(promptLineText)) return NO_PROMPT;
const pEnd = findPromptBoundary(promptLineText);
const pEnd = findPromptBoundary(promptLineText, macShellCwd, macPromptLengthsBeforeEdit.get(term));
if (pEnd >= 0 && !isProgramInputPromptText(promptLineText.substring(0, pEnd))) {
const promptText = promptLineText.substring(0, pEnd);
// Concatenate all rows from promptRow to cursorY to get full input
@@ -863,9 +876,28 @@ function isSpacedPromptSegment(lineText: string, boundary: number): boolean {
* Avoids false positives: $VAR, $(...), ${...} are not prompt endings.
* Returns the character index where user input begins, or -1 if no prompt detected.
*/
function findPromptBoundary(lineText: string): number {
function findPromptBoundary(lineText: string, macShellCwd?: string | null, beforeEdit = Infinity): number {
const windowsBoundary = findWindowsPathPromptBoundary(lineText);
if (windowsBoundary >= 0) return windowsBoundary;
// macOS /etc/bashrc prints hostname:basename username$. Match the verified
// directory literally so a recalled command cannot become part of the prompt.
if (macShellCwd) {
// A colon followed by whitespace already ends a host-only prompt.
const hostPrefix = /^[\w.-]+:(?=\S)/.exec(lineText)?.[0];
if (hostPrefix) {
const rest = lineText.slice(hostPrefix.length);
const basename = macShellCwd.split('/').at(-1) || '/';
// Bash can show a logical symlink name while the local process reports a
// physical cwd. A plain alias cannot contain an earlier prompt marker.
const alias = /^[\p{L}\p{N}._~ -]+?(?= [\w.-]+[$#] )/u.exec(rest)?.[0];
const directory = rest.startsWith(basename + ' ') ? basename : alias;
if (directory && rest.startsWith(directory + ' ')) {
const offset = hostPrefix.length + directory.length + 1;
const userSuffix = /^[\w.-]+[$#] /.exec(lineText.slice(offset));
if (userSuffix && offset + userSuffix[0].length <= beforeEdit) return offset + userSuffix[0].length;
}
}
}
// Scan for prompt boundary. Take the LAST candidate.
// For ambiguous chars like >, limit scan to first 60% to avoid matching redirections.
// For unambiguous prompt chars ($, #), scan the full line since they're rarely
@@ -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);
}
});
@@ -6,6 +6,7 @@ import {
} from "../../../domain/externalEditor";
import type { SensitiveInputActiveRef } from "../autocomplete/terminalAutocompletePrompt";
import { clearTerminalBroadcastUserInput, captureTerminalBroadcastInput, isTerminalBroadcastInputCurrent, markTerminalBroadcastUserInput, type TerminalPacedBroadcast } from "./terminalPacedBroadcast";
import { noteMacShellPromptEdit } from "../autocomplete/promptDetector";
import { stringCellWidth } from "../autocomplete/terminalStringCellWidth";
import type { TerminalBroadcastInputOptions } from "../terminalHelpers";
import { FitAddon } from "@xterm/addon-fit";
@@ -1541,6 +1542,9 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
&& !isPrintableInput(logicalData) && !isTerminalReportSequence(logicalData)) {
commandBufferRevision += 1;
}
if (logicalData && ctx.host.protocol === "local" && isMacPlatform() && !isTerminalReportSequence(logicalData)) {
noteMacShellPromptEdit(term, logicalData);
}
if (!options?.lineDelayMs && logicalData !== null && !isTerminalReportSequence(logicalData)) {
markTerminalBroadcastUserInput(ctx.sessionId);
}
@@ -1936,6 +1940,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 +2056,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 +2761,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;
}
@@ -30,7 +30,7 @@ const helpers = await Promise.all([
"./terminalBackspaceInput.ts", "./terminalPerCharacterInput.ts",
"./terminalSudoAutofill.ts", "./terminalCommandExecution.ts",
"./terminalPacedBroadcast.ts", "./terminalInterruptInputState.ts", "./serialLocalEcho.ts", "../autocomplete/terminalStringCellWidth.ts",
"./shiftEnterText.ts", "./serialLineInput.ts", "./telnetLocalEcho.ts",
"./shiftEnterText.ts", "./serialLineInput.ts", "./telnetLocalEcho.ts", "../autocomplete/promptDetector.ts",
].map(path => import(new URL(path, import.meta.url).href)));
for (const [protocol, lineMode, sensitive] of [
@@ -127,7 +127,8 @@ for (const [protocol, lineMode, sensitive] of [
? { isWrapped: false, translateToString: () => liveLine } : undefined } },
};
const env = {
usePerCharacterInput: true,
usePerCharacterInput: true,
isMacPlatform: () => true,
...Object.assign({}, ...helpers), ...userPaste, ctx, term, crypto, isPluginHostProtocol: () => false, logger: { warn() {} },
netcattyBridge: { get: () => ({ onTerminalPasteWrite: (listener: typeof receiptListener) => { receiptListener = listener; return () => { receiptListener = undefined; }; } }) },
suppressNextTerminalDataBroadcast: false, handlingKittyBroadcast: false,
@@ -343,6 +344,7 @@ test("bypassed sensitive line paste keeps the paced fan-out with sourceSensitive
};
const env = {
usePerCharacterInput: true,
isMacPlatform: () => true,
...Object.assign({}, ...helpers), ...userPaste, ctx, term, crypto, isPluginHostProtocol: () => false, logger: { warn() {} },
netcattyBridge: { get: () => ({ onTerminalPasteWrite: (listener: typeof receiptListener) => { receiptListener = listener; return () => { receiptListener = undefined; }; } }) },
suppressNextTerminalDataBroadcast: false, handlingKittyBroadcast: false,
@@ -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),
Loaded 100 of 205 files, more files were not shown because too many files have changed in this diff. Show more