mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-12-05 17:51:19 +00:00
Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b079d593f7 | ||
|
|
569b05e7fa | ||
|
|
180a1427be | ||
|
|
5c4c7e3fa8 | ||
|
|
1c41aad9ff | ||
|
|
516314f8ef | ||
|
|
43dd7a43b3 | ||
|
|
0a389e760e | ||
|
|
897c3e23e6 | ||
|
|
12531fbcc5 | ||
|
|
a64029bc0b | ||
|
|
b5815c3064 | ||
|
|
1f91fd54f1 | ||
|
|
2f76061ec8 | ||
|
|
dd9f6e862a | ||
|
|
f688a17f14 | ||
|
|
e6d3047d0a | ||
|
|
f50c18e5c7 | ||
|
|
33b4bd1a43 | ||
|
|
31458b00a4 | ||
|
|
f68570d942 | ||
|
|
9474601fdf | ||
|
|
4cef084e99 | ||
|
|
58eeefb4c1 | ||
|
|
6f8211481c | ||
|
|
6458dbe039 | ||
|
|
6e0eacc6ae | ||
|
|
73ee6c0f31 | ||
|
|
905aed61ad | ||
|
|
13d05b0ea4 | ||
|
|
1045737c68 | ||
|
|
909d3e5ed2 | ||
|
|
cb7e49c409 | ||
|
|
02be8a2e0a |
No files matched your search
@@ -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}>
|
||||
|
||||
@@ -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
|
||||
@@ -164,6 +166,7 @@ If you regularly work with a fleet of servers, Netcatty is built for speed and f
|
||||
- **Fast search** — locate hosts and groups quickly
|
||||
|
||||
### 🖥️ Terminal Workspaces
|
||||
- Right-click a standalone terminal tab and choose **Convert to Workspace** to keep your running shell as the first pane.
|
||||
- **Split panes** — horizontal and vertical splits for multi-tasking
|
||||
- **Session management** — run multiple connections side-by-side
|
||||
- **Save current screen** — right-click a terminal to save the visible final text, without replaying keystrokes or overwritten output; scroll first to save an earlier screen.
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -274,7 +274,7 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
const {
|
||||
addShellHistoryEntry, clearAllCommandHistory, removeShellHistoryEntry, addSessionToWorkspace, addToWorkspaceDialog, appendHostToWorkspace, appendLocalTerminalToWorkspace, moveWorkspacePane,
|
||||
clearAndRemoveSource, clearAndRemoveSources, closeLogView, closeSession, closeTabsBatch, closeWorkspace, commitPluginImporterData, commitVaultImportTransaction, commitVaultGroupMutation, copySessionToNewWindowWithCurrentShell, moveSessionToNewWindow, copySessionWithCurrentShell, duplicateSessionWithCurrentShell, copyWorkspaceWithCurrentShell,
|
||||
convertKnownHostToHost, createWorkspaceFromSessions, createWorkspaceFromTargets, createWorkspaceWithHosts,
|
||||
convertKnownHostToHost, convertSessionToWorkspace, createWorkspaceFromSessions, createWorkspaceFromTargets, createWorkspaceWithHosts,
|
||||
customGroups, currentTerminalTheme, deepLinkHostDraft, draggingSessionId, effectiveKnownHosts, editorTabs, editorWordWrap, emptyVaultConflict,
|
||||
followAppTerminalTheme,
|
||||
groupConfigs, handleAddKnownHost, handleConnectSerial, handleConnectToHost, handleConnectRemoteDesktop, handleOpenSystemRemoteDesktop, handleCreateLocalTerminal, handleDefaultTerminalThemeChange, handleDeleteHost,
|
||||
@@ -569,6 +569,7 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
tabDoubleClickBehavior={terminalSettings.tabDoubleClickBehavior}
|
||||
onCopySessionToNewWindow={copySessionToNewWindowWithCurrentShell}
|
||||
onMoveSessionToNewWindow={moveSessionToNewWindow}
|
||||
onConvertSessionToWorkspace={convertSessionToWorkspace}
|
||||
onEditHost={handleEditHostFromOverlay}
|
||||
onRenameWorkspace={startWorkspaceRename}
|
||||
onCopyWorkspace={copyWorkspaceWithCurrentShell}
|
||||
|
||||
@@ -131,6 +131,7 @@ export function ChromeHost() {
|
||||
sessionRenameTarget: session.sessionRenameTarget,
|
||||
setActiveTabId: sessionActions?.setActiveTabId,
|
||||
startSessionRename: sessionActions?.startSessionRename,
|
||||
convertSessionToWorkspace: sessionActions?.convertSessionToWorkspace,
|
||||
renameSessionInline: sessionActions?.renameSessionInline,
|
||||
startWorkspaceRename: sessionActions?.startWorkspaceRename,
|
||||
submitSessionRename: sessionActions?.submitSessionRename,
|
||||
|
||||
@@ -59,6 +59,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
|
||||
clearSessionFontSizeOverride,
|
||||
createWorkspaceWithHosts,
|
||||
createWorkspaceFromSessions,
|
||||
convertSessionToWorkspace,
|
||||
addSessionToWorkspace,
|
||||
moveWorkspacePane,
|
||||
appendHostToWorkspace,
|
||||
@@ -148,6 +149,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
|
||||
clearSessionFontSizeOverride,
|
||||
createWorkspaceWithHosts,
|
||||
createWorkspaceFromSessions,
|
||||
convertSessionToWorkspace,
|
||||
addSessionToWorkspace,
|
||||
moveWorkspacePane,
|
||||
appendHostToWorkspace,
|
||||
@@ -197,6 +199,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
|
||||
createSerialSession,
|
||||
createSessionFromCloneSource,
|
||||
createWorkspaceFromSessions,
|
||||
convertSessionToWorkspace,
|
||||
createWorkspaceFromTargets,
|
||||
createWorkspaceWithHosts,
|
||||
getOrderedWorkTabs,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const enAiMessages: Messages = {
|
||||
'ai.grok.chooseModeAndSend': 'Choose Grok mode and send…',
|
||||
'ai.chat.iterationLimitReached': 'Tool-loop limit ({limit} iterations) reached. You can continue in this chat. Running terminal jobs are not stopped.',
|
||||
'ai.chat.continue': 'Continue',
|
||||
'ai.chat.attachmentContentUnavailable': 'Content not available on this device',
|
||||
@@ -117,6 +118,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 +309,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 +342,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 +651,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 +715,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',
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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',
|
||||
@@ -707,6 +713,7 @@ export const enTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': 'Duplicate Session',
|
||||
'tabs.copyTabToNewWindow': 'Copy Tab to New Window',
|
||||
'tabs.copyTabToNewWindowFailed': 'Failed to open tab in a new window',
|
||||
'tabs.convertToWorkspace': 'Convert to Workspace',
|
||||
'tabs.moveTabToNewWindow': 'Move Tab to New Window',
|
||||
'tabs.moveTabToNewWindowFailed': 'Failed to move tab to a new window',
|
||||
'tabs.closeOthers': 'Close Others',
|
||||
|
||||
@@ -882,7 +882,7 @@ export const enVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent.socket': 'Agent Socket',
|
||||
'hostDetails.systemSshAgent.socket.desc': 'Leave empty to use SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': 'Only Use Configured Keys',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Do not try unrelated keys currently loaded in the agent',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Match agent keys to public keys configured for this host. To use agent keys without a local public key, choose Automatic authentication and leave this off.',
|
||||
'hostDetails.systemSshAgent.notRunning': 'System SSH agent is unavailable',
|
||||
'hostDetails.systemSshAgent.notRunningHint': 'Start or unlock your SSH agent, or provide its socket path above.',
|
||||
'hostDetails.keys.search': 'Search keys...',
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const esAiMessages: Messages = {
|
||||
'ai.grok.chooseModeAndSend': 'Elegir el modo de Grok y enviar…',
|
||||
'ai.chat.iterationLimitReached': 'Se alcanzó el límite del bucle de herramientas ({limit} iteraciones). Puedes continuar en este chat. Las tareas de terminal en ejecución no se detienen.',
|
||||
'ai.chat.continue': 'Continuar',
|
||||
'ai.chat.attachmentContentUnavailable': 'Contenido no disponible en este dispositivo',
|
||||
@@ -117,6 +118,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 +309,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 +342,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 +651,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 +715,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',
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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',
|
||||
@@ -709,6 +715,7 @@ export const esTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': 'Duplicar sesión',
|
||||
'tabs.copyTabToNewWindow': 'Copiar pestaña a una nueva ventana',
|
||||
'tabs.copyTabToNewWindowFailed': 'No se pudo abrir la pestaña en una nueva ventana',
|
||||
'tabs.convertToWorkspace': 'Convertir en espacio de trabajo',
|
||||
'tabs.moveTabToNewWindow': 'Mover pestaña a una nueva ventana',
|
||||
'tabs.moveTabToNewWindowFailed': 'No se pudo mover la pestaña a una nueva ventana',
|
||||
'tabs.closeOthers': 'Cerrar las demás',
|
||||
|
||||
@@ -878,7 +878,7 @@ export const esVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent.socket': 'Socket del agente',
|
||||
'hostDetails.systemSshAgent.socket.desc': 'Déjalo vacío para usar SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': 'Usar solo las claves configuradas',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'No intentar con claves no relacionadas actualmente cargadas en el agente',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Usa las claves del agente que coincidan con las claves públicas configuradas para este host. Para usar el agente sin una clave pública local, elige la autenticación automática y desactiva esta opción.',
|
||||
'hostDetails.systemSshAgent.notRunning': 'El agente SSH del sistema no está disponible',
|
||||
'hostDetails.systemSshAgent.notRunningHint': 'Inicia o desbloquea tu agente SSH, o proporciona la ruta de su socket arriba.',
|
||||
'hostDetails.keys.search': 'Buscar claves...',
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const ruAiMessages: Messages = {
|
||||
'ai.grok.chooseModeAndSend': 'Выбрать режим Grok и отправить…',
|
||||
'ai.chat.iterationLimitReached': 'Достигнут лимит цикла инструментов ({limit} итераций). Можно продолжить в этом чате. Запущенные задачи терминала не останавливаются.',
|
||||
'ai.chat.continue': 'Продолжить',
|
||||
'ai.chat.attachmentContentUnavailable': 'Содержимое недоступно на этом устройстве',
|
||||
@@ -117,6 +118,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 +300,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 +330,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 +650,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 +714,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': 'сообщений',
|
||||
|
||||
@@ -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': 'Навигация',
|
||||
|
||||
@@ -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': 'Каталоги',
|
||||
@@ -722,6 +728,7 @@ export const ruTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': 'Дублировать сессию',
|
||||
'tabs.copyTabToNewWindow': 'Копировать вкладку в новое окно',
|
||||
'tabs.copyTabToNewWindowFailed': 'Не удалось открыть вкладку в новом окне',
|
||||
'tabs.convertToWorkspace': 'Преобразовать в рабочую область',
|
||||
'tabs.moveTabToNewWindow': 'Переместить вкладку в новое окно',
|
||||
'tabs.moveTabToNewWindowFailed': 'Не удалось переместить вкладку в новое окно',
|
||||
'tabs.closeOthers': 'Закрыть остальные',
|
||||
|
||||
@@ -924,7 +924,7 @@ export const ruVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent.socket': 'Сокет агента',
|
||||
'hostDetails.systemSshAgent.socket.desc': 'Оставьте пустым, чтобы использовать SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': 'Только настроенные ключи',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Не пробовать другие ключи, загруженные в агент',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Использовать ключи агента, соответствующие открытым ключам этого хоста. Чтобы использовать агент без локального открытого ключа, выберите автоматическую аутентификацию и отключите эту настройку.',
|
||||
'hostDetails.systemSshAgent.notRunning': 'Системный SSH-агент недоступен',
|
||||
'hostDetails.systemSshAgent.notRunningHint': 'Запустите или разблокируйте SSH-агент либо укажите путь к его сокету выше.',
|
||||
'hostDetails.keys.search': 'Поиск ключей...',
|
||||
|
||||
@@ -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`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const zhCNAiMessages: Messages = {
|
||||
'ai.grok.chooseModeAndSend': '选择 Grok 模式并发送…',
|
||||
'ai.chat.iterationLimitReached': '已达到工具循环上限({limit} 次迭代)。你可以在此对话中继续,正在运行的终端任务不会停止。',
|
||||
'ai.chat.continue': '继续',
|
||||
'ai.chat.attachmentContentUnavailable': '附件内容未保留在此设备',
|
||||
@@ -117,6 +118,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 +309,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 +342,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 +651,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 +715,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': '导航',
|
||||
@@ -805,6 +817,7 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': '复制会话',
|
||||
'tabs.copyTabToNewWindow': '复制标签页到新窗口',
|
||||
'tabs.copyTabToNewWindowFailed': '无法在新窗口打开标签页',
|
||||
'tabs.convertToWorkspace': '转为工作区',
|
||||
'tabs.moveTabToNewWindow': '移动标签页到新窗口',
|
||||
'tabs.moveTabToNewWindowFailed': '无法将标签页移动到新窗口',
|
||||
'tabs.closeOthers': '关闭其他标签',
|
||||
|
||||
@@ -309,7 +309,7 @@ export const zhCNVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent.socket': '代理地址',
|
||||
'hostDetails.systemSshAgent.socket.desc': '留空时使用 SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': '仅使用已配置的密钥',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': '不尝试代理中其他无关密钥',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': '只尝试与此主机已配置公钥匹配的代理密钥。如需使用代理中的密钥且本地没有公钥,请将认证方式设为“自动选择”,并关闭此选项。',
|
||||
'hostDetails.systemSshAgent.notRunning': '系统 SSH 密钥服务不可用',
|
||||
'hostDetails.systemSshAgent.notRunningHint': '请启动或解锁密钥服务,或者在上方填写它的地址。',
|
||||
'hostDetails.keys.search': '搜索密钥…',
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const zhTWAiMessages: Messages = {
|
||||
'ai.grok.chooseModeAndSend': '選擇 Grok 模式並傳送…',
|
||||
'ai.chat.iterationLimitReached': '已達到工具迴圈上限({limit} 次迭代)。你可以在此對話中繼續,正在執行的終端工作不會停止。',
|
||||
'ai.chat.continue': '繼續',
|
||||
'ai.chat.attachmentContentUnavailable': '附件內容未保留在此裝置',
|
||||
@@ -117,6 +118,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 +309,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 +342,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 +650,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 +714,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': '導航',
|
||||
@@ -805,6 +817,7 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': '複製工作階段',
|
||||
'tabs.copyTabToNewWindow': '複製分頁到新視窗',
|
||||
'tabs.copyTabToNewWindowFailed': '無法在新視窗開啟分頁',
|
||||
'tabs.convertToWorkspace': '轉為工作區',
|
||||
'tabs.moveTabToNewWindow': '移動分頁到新視窗',
|
||||
'tabs.moveTabToNewWindowFailed': '無法將分頁移動到新視窗',
|
||||
'tabs.closeOthers': '關閉其他分頁',
|
||||
|
||||
@@ -309,7 +309,7 @@ export const zhTWVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent.socket': '代理位址',
|
||||
'hostDetails.systemSshAgent.socket.desc': '留空時使用 SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': '僅使用已設定的金鑰',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': '不嘗試代理中其他無關金鑰',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': '僅嘗試與此主機已設定公鑰相符的代理程式金鑰。若要使用代理程式中的金鑰且本機沒有公鑰,請將驗證方式設為「自動選擇」並關閉此選項。',
|
||||
'hostDetails.systemSshAgent.notRunning': '系統 SSH 金鑰服務無法使用',
|
||||
'hostDetails.systemSshAgent.notRunningHint': '請啟動或解鎖金鑰服務,或在上方填寫其位址。',
|
||||
'hostDetails.keys.search': '搜尋金鑰…',
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -90,6 +90,7 @@ test('session actions register and unregister', () => {
|
||||
clearSessionFontSizeOverride: noop,
|
||||
createWorkspaceWithHosts: noop,
|
||||
createWorkspaceFromSessions: noop,
|
||||
convertSessionToWorkspace: noop,
|
||||
addSessionToWorkspace: noop,
|
||||
appendHostToWorkspace: noop,
|
||||
appendHostToWorkspaceConfirmed: noop,
|
||||
|
||||
@@ -57,6 +57,7 @@ export type SessionSnapshotActions = Pick<
|
||||
| 'clearSessionFontSizeOverride'
|
||||
| 'createWorkspaceWithHosts'
|
||||
| 'createWorkspaceFromSessions'
|
||||
| 'convertSessionToWorkspace'
|
||||
| 'addSessionToWorkspace'
|
||||
| 'moveWorkspacePane'
|
||||
| 'appendHostToWorkspace'
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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()));
|
||||
}
|
||||
|
||||
@@ -139,6 +139,7 @@ export interface SendToExternalContext {
|
||||
defaultTargetSession?: DefaultTargetSessionHint;
|
||||
providers: ProviderConfig[];
|
||||
selectedAgentModel?: string;
|
||||
chooseGrokMode?: boolean;
|
||||
toolIntegrationMode: AIToolIntegrationMode;
|
||||
selectedUserSkillSlugs?: string[];
|
||||
permissionMode: AIPermissionMode;
|
||||
|
||||
@@ -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
@@ -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);
|
||||
|
||||
@@ -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';
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -68,9 +68,15 @@ export function usePluginManager() {
|
||||
if (!bridge.uninstallPlugin) throw new Error('Plugin management unavailable');
|
||||
const source = clearSource ? await bridge.getPluginSourceBinding?.(id) : null;
|
||||
await bridge.uninstallPlugin(id);
|
||||
if (clearSource && source) {
|
||||
if (!bridge.resetPluginSource) throw new Error('Private source reset unavailable');
|
||||
await bridge.resetPluginSource(id, source.id);
|
||||
try {
|
||||
if (clearSource && source) {
|
||||
if (!bridge.resetPluginSource) throw new Error('Private source reset unavailable');
|
||||
await bridge.resetPluginSource(id, source.id);
|
||||
}
|
||||
} finally {
|
||||
if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function') {
|
||||
window.dispatchEvent(new Event('netcatty:plugin-packages-changed'));
|
||||
}
|
||||
}
|
||||
}, true),
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useEffect, useMemo, useRef } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
import { activeTabStore, useIsVaultActive } from './activeTabStore';
|
||||
import { collectPluginVaultPages, PLUGIN_VAULT_PAGE_PREFIX, resolvePluginVaultPage } from './pluginVaultPages';
|
||||
import { usePluginContributions } from './usePluginContributions';
|
||||
@@ -6,6 +7,18 @@ import { OPEN_PLUGIN_VIEW_EVENT, type OpenPluginViewDetail } from './usePluginVi
|
||||
|
||||
const CONTEXT = Object.freeze({ 'netcatty.surface': 'vault-page' });
|
||||
|
||||
function areStringArraysEqual(
|
||||
left: readonly string[] | undefined,
|
||||
right: readonly string[] | undefined,
|
||||
): boolean {
|
||||
if (left === right) return true;
|
||||
if (!left || !right || left.length !== right.length) return false;
|
||||
for (let i = 0; i < left.length; i += 1) {
|
||||
if (left[i] !== right[i]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function usePluginVaultPages({ locale, section, select }: {
|
||||
locale: string;
|
||||
section: string;
|
||||
@@ -18,6 +31,41 @@ export function usePluginVaultPages({ locale, section, select }: {
|
||||
useEffect(() => () => { if (focusFrame.current !== null) cancelAnimationFrame(focusFrame.current); }, []);
|
||||
const contributions = usePluginContributions({ locale, context: CONTEXT });
|
||||
const pages = useMemo(() => collectPluginVaultPages(contributions.snapshot.plugins), [contributions.snapshot.plugins]);
|
||||
const [installedPluginIds, setInstalledPluginIds] = useState<readonly string[] | undefined>(undefined);
|
||||
useEffect(() => {
|
||||
const bridge = typeof window === 'undefined' ? undefined : netcattyBridge.get();
|
||||
if (!contributions.available || !bridge?.listPlugins) {
|
||||
setInstalledPluginIds((current) => (current === undefined ? current : undefined));
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
let generation = 0;
|
||||
const loadInstalled = () => {
|
||||
const requestId = ++generation;
|
||||
void bridge.listPlugins!()
|
||||
.then((plugins) => {
|
||||
if (cancelled || requestId !== generation) return;
|
||||
const next = Array.from(
|
||||
new Set(
|
||||
plugins
|
||||
.map((plugin) => plugin.id)
|
||||
.filter((id): id is string => typeof id === 'string' && id.length > 0),
|
||||
),
|
||||
).sort();
|
||||
setInstalledPluginIds((current) => (areStringArraysEqual(current, next) ? current : next));
|
||||
})
|
||||
.catch(() => {
|
||||
if (cancelled || requestId !== generation) return;
|
||||
setInstalledPluginIds((current) => (current === undefined ? current : undefined));
|
||||
});
|
||||
};
|
||||
loadInstalled();
|
||||
window.addEventListener('netcatty:plugin-packages-changed', loadInstalled);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.removeEventListener('netcatty:plugin-packages-changed', loadInstalled);
|
||||
};
|
||||
}, [contributions.available, contributions.snapshot]);
|
||||
const selected = resolvePluginVaultPage(pages, section);
|
||||
const fallback = useCallback(() => {
|
||||
select('hosts');
|
||||
@@ -43,5 +91,5 @@ export function usePluginVaultPages({ locale, section, select }: {
|
||||
window.addEventListener(OPEN_PLUGIN_VIEW_EVENT, open);
|
||||
return () => window.removeEventListener(OPEN_PLUGIN_VIEW_EVENT, open);
|
||||
}, [pages, select]);
|
||||
return { pages, selected, active, select, fallback, contributions, context: CONTEXT };
|
||||
return { pages, selected, active, select, fallback, contributions, installedPluginIds, context: CONTEXT };
|
||||
}
|
||||
@@ -57,6 +57,40 @@ async function mountSessionState(t: test.TestContext) {
|
||||
return () => latestState;
|
||||
}
|
||||
|
||||
test('converting a standalone tab keeps the live session, tab position and focus', async (t) => {
|
||||
const getState = await mountSessionState(t);
|
||||
let first = '';
|
||||
let target = '';
|
||||
let last = '';
|
||||
await act(async () => {
|
||||
first = getState().createLocalTerminal();
|
||||
target = getState().createLocalTerminal({ shellName: 'Build shell' });
|
||||
last = getState().createLocalTerminal();
|
||||
});
|
||||
await act(async () => { getState().updateSessionStatus(target, 'connected'); });
|
||||
const before = getState().sessions;
|
||||
await act(async () => {
|
||||
getState().convertSessionToWorkspace(target);
|
||||
getState().convertSessionToWorkspace(target);
|
||||
});
|
||||
assert.equal(getState().workspaces.length, 1);
|
||||
const [workspace] = getState().workspaces;
|
||||
assert.equal(workspace.root.type, 'pane');
|
||||
assert.equal(workspace.root.sessionId, target);
|
||||
assert.equal(workspace.focusedSessionId, target);
|
||||
assert.deepEqual(getState().sessions, before.map(session =>
|
||||
session.id === target ? { ...session, workspaceId: workspace.id } : session));
|
||||
assert.deepEqual(getState().orderedTabs, [first, workspace.id, last]);
|
||||
assert.equal(activeTabStore.getActiveTabId(), workspace.id);
|
||||
|
||||
// A reordered editor tab must keep its place alongside terminal tabs.
|
||||
const editor = 'editor:test';
|
||||
await act(async () => { getState().reorderTabs(editor, last, 'before', [editor]); });
|
||||
await act(async () => { getState().convertSessionToWorkspace(last); });
|
||||
const secondWorkspace = getState().workspaces[1];
|
||||
assert.deepEqual(getState().getOrderedWorkTabs([editor]), [first, workspace.id, editor, secondWorkspace.id]);
|
||||
});
|
||||
|
||||
test('useSessionState issue #4249 scenario 1: repeated close focuses C -> B -> A -> vault', async (t) => {
|
||||
const getState = await mountSessionState(t);
|
||||
|
||||
|
||||
@@ -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,
|
||||
@@ -1502,6 +1503,30 @@ export const useSessionState = ({
|
||||
});
|
||||
}, [setActiveTabId]);
|
||||
|
||||
const convertSessionToWorkspace = useCallback((sessionId: string) => {
|
||||
const standaloneIds = orphanSessionsRef.current.map(session => session.id);
|
||||
const workspace = createWorkspaceFromSessionIds([sessionId], {
|
||||
title: DEFAULT_WORKSPACE_TITLE,
|
||||
autoTitle: true,
|
||||
viewMode: 'focus',
|
||||
});
|
||||
|
||||
setSessions(prev => {
|
||||
const source = prev.find(session => session.id === sessionId);
|
||||
if (!source || source.workspaceId || source.hiddenFromTabs) return prev;
|
||||
|
||||
setWorkspaces(current => addWorkspaceIfMissing(current, workspace));
|
||||
setTabOrder(current => {
|
||||
if (current.includes(workspace.id)) return current;
|
||||
// Unreordered terminal tabs may only have an implicit position.
|
||||
const order = current.includes(sessionId) ? current : [...new Set([...current, ...standaloneIds])];
|
||||
return order.map(id => id === sessionId ? workspace.id : id);
|
||||
});
|
||||
setActiveTabId(workspace.id);
|
||||
return prev.map(session => session === source ? { ...session, workspaceId: workspace.id } : session);
|
||||
});
|
||||
}, [setActiveTabId]);
|
||||
|
||||
// Copy a session - creates a new session with the same host connection
|
||||
const copySession = useCallback((sessionId: string, options?: {
|
||||
localShellType?: TerminalSession['shellType'];
|
||||
@@ -1793,6 +1818,7 @@ export const useSessionState = ({
|
||||
createWorkspaceWithHosts,
|
||||
createWorkspaceFromTargets,
|
||||
createWorkspaceFromSessions,
|
||||
convertSessionToWorkspace,
|
||||
addSessionToWorkspace,
|
||||
moveWorkspacePane,
|
||||
removeSessionFromWorkspace,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -6,6 +6,8 @@ const DB_PLUGIN = 'plugin-vault:com.binaricat.netcatty-database.main' as const;
|
||||
const MONITOR_PLUGIN = 'plugin-vault:com.binaricat.netcatty-monitor.main' as const;
|
||||
const OFFICIAL_DB_PLUGIN = 'plugin-vault:com.binaricat.netcatty-database.workbench' as const;
|
||||
const OFFICIAL_MONITOR_PLUGIN = 'plugin-vault:com.binaricat.netcatty-monitor.workbench' as const;
|
||||
const DB_PLUGIN_ID = 'com.binaricat.netcatty-database';
|
||||
const MONITOR_PLUGIN_ID = 'com.binaricat.netcatty-monitor';
|
||||
|
||||
test('useVaultNavConfig persists order & visibility, survives cold-start loading, prunes uninstalled plugins, and resets cleanly', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost' });
|
||||
@@ -31,11 +33,17 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
|
||||
|
||||
let model!: ReturnType<typeof useVaultNavConfig>;
|
||||
let activePluginIds: (typeof DB_PLUGIN | typeof MONITOR_PLUGIN)[] = [DB_PLUGIN, MONITOR_PLUGIN];
|
||||
let installedPluginIds: string[] | undefined = [DB_PLUGIN_ID, MONITOR_PLUGIN_ID];
|
||||
let pluginsLoading = false;
|
||||
let pluginsAvailable = true;
|
||||
|
||||
function Fixture() {
|
||||
model = useVaultNavConfig({ activePluginIds, pluginsLoading, pluginsAvailable });
|
||||
model = useVaultNavConfig({
|
||||
activePluginIds,
|
||||
pluginsLoading,
|
||||
pluginsAvailable,
|
||||
installedPluginIds,
|
||||
});
|
||||
return <div />;
|
||||
}
|
||||
|
||||
@@ -85,6 +93,7 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
|
||||
});
|
||||
const coldRoot = createRoot(document.getElementById('root')!);
|
||||
activePluginIds = [];
|
||||
installedPluginIds = undefined;
|
||||
pluginsLoading = true;
|
||||
pluginsAvailable = false;
|
||||
await act(async () => {
|
||||
@@ -96,6 +105,7 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
|
||||
|
||||
// Plugins finish loading, but DB_PLUGIN was uninstalled.
|
||||
activePluginIds = [MONITOR_PLUGIN];
|
||||
installedPluginIds = [MONITOR_PLUGIN_ID];
|
||||
pluginsLoading = false;
|
||||
pluginsAvailable = true;
|
||||
await act(async () => {
|
||||
@@ -249,3 +259,334 @@ test('useVaultNavConfig preserves saved plugin order when settled with pluginsAv
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('useVaultNavConfig preserves custom plugin order across in-place plugin update gap and prunes only after uninstall', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost' });
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const key of ['window', 'document', 'navigator', 'localStorage', 'StorageEvent', 'CustomEvent', 'Event']) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window],
|
||||
});
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: true,
|
||||
});
|
||||
|
||||
const { default: React, act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { useVaultNavConfig } = await import('./useVaultNavConfig');
|
||||
const { STORAGE_KEY_VAULT_NAV_CONFIG } = await import('../../infrastructure/config/storageKeys');
|
||||
|
||||
let model!: ReturnType<typeof useVaultNavConfig>;
|
||||
let activePluginIds: (typeof OFFICIAL_DB_PLUGIN | typeof OFFICIAL_MONITOR_PLUGIN)[] = [
|
||||
OFFICIAL_DB_PLUGIN,
|
||||
OFFICIAL_MONITOR_PLUGIN,
|
||||
];
|
||||
let installedPluginIds: string[] = [DB_PLUGIN_ID, MONITOR_PLUGIN_ID];
|
||||
let pluginOwnerByNavId: Record<string, string> = {
|
||||
[OFFICIAL_DB_PLUGIN]: DB_PLUGIN_ID,
|
||||
[OFFICIAL_MONITOR_PLUGIN]: MONITOR_PLUGIN_ID,
|
||||
};
|
||||
let pluginsLoading = false;
|
||||
let pluginsAvailable = true;
|
||||
|
||||
function Fixture() {
|
||||
model = useVaultNavConfig({
|
||||
activePluginIds,
|
||||
pluginsLoading,
|
||||
pluginsAvailable,
|
||||
installedPluginIds,
|
||||
pluginOwnerByNavId,
|
||||
});
|
||||
return <div />;
|
||||
}
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
const render = async () => {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<Fixture />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
try {
|
||||
await render();
|
||||
|
||||
await act(async () => {
|
||||
model.reorder(OFFICIAL_DB_PLUGIN, 'hosts', 'after');
|
||||
model.setVisible('logs', false);
|
||||
});
|
||||
assert.equal(model.visibleIds[1], OFFICIAL_DB_PLUGIN);
|
||||
assert.equal(model.config.order[1], OFFICIAL_DB_PLUGIN);
|
||||
|
||||
// Mid-update gap: beforeActivate disables the plugin while it remains installed.
|
||||
activePluginIds = [OFFICIAL_MONITOR_PLUGIN];
|
||||
pluginOwnerByNavId = { [OFFICIAL_MONITOR_PLUGIN]: MONITOR_PLUGIN_ID };
|
||||
pluginsLoading = false;
|
||||
pluginsAvailable = true;
|
||||
await render();
|
||||
|
||||
assert.equal(model.visibleIds.includes(OFFICIAL_DB_PLUGIN), false);
|
||||
assert.equal(model.config.order[1], OFFICIAL_DB_PLUGIN);
|
||||
const persistedDuringGap = JSON.parse(
|
||||
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
|
||||
);
|
||||
assert.equal(persistedDuringGap.order[1], OFFICIAL_DB_PLUGIN);
|
||||
assert.deepEqual(persistedDuringGap.hidden, ['logs']);
|
||||
|
||||
// Updated version re-enables and returns the same workbench nav key.
|
||||
activePluginIds = [OFFICIAL_DB_PLUGIN, OFFICIAL_MONITOR_PLUGIN];
|
||||
pluginOwnerByNavId = {
|
||||
[OFFICIAL_DB_PLUGIN]: DB_PLUGIN_ID,
|
||||
[OFFICIAL_MONITOR_PLUGIN]: MONITOR_PLUGIN_ID,
|
||||
};
|
||||
await render();
|
||||
|
||||
assert.equal(model.visibleIds[1], OFFICIAL_DB_PLUGIN);
|
||||
assert.equal(model.config.order[1], OFFICIAL_DB_PLUGIN);
|
||||
assert.equal(model.isHidden('logs'), true);
|
||||
const persistedAfterUpdate = JSON.parse(
|
||||
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
|
||||
);
|
||||
assert.equal(persistedAfterUpdate.order[1], OFFICIAL_DB_PLUGIN);
|
||||
|
||||
// True uninstall removes the plugin from installedPluginIds and prunes its nav slot.
|
||||
activePluginIds = [OFFICIAL_MONITOR_PLUGIN];
|
||||
installedPluginIds = [MONITOR_PLUGIN_ID];
|
||||
pluginOwnerByNavId = { [OFFICIAL_MONITOR_PLUGIN]: MONITOR_PLUGIN_ID };
|
||||
await render();
|
||||
|
||||
assert.equal(model.config.order.includes(OFFICIAL_DB_PLUGIN), false);
|
||||
const persistedAfterUninstall = JSON.parse(
|
||||
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
|
||||
);
|
||||
assert.equal(persistedAfterUninstall.order.includes(OFFICIAL_DB_PLUGIN), false);
|
||||
assert.deepEqual(persistedAfterUninstall.hidden, ['logs']);
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
} finally {
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('usePluginVaultPages + useVaultNavConfig preserve custom order across simulated 0.3.5 -> 0.3.6 update', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost' });
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const key of ['window', 'document', 'navigator', 'localStorage', 'StorageEvent', 'CustomEvent', 'Event']) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window],
|
||||
});
|
||||
}
|
||||
for (const [key, value] of Object.entries({
|
||||
requestAnimationFrame: (cb: FrameRequestCallback) => setTimeout(() => cb(Date.now()), 0),
|
||||
cancelAnimationFrame: (id: number) => clearTimeout(id),
|
||||
IS_REACT_ACT_ENVIRONMENT: true,
|
||||
})) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
}
|
||||
|
||||
const dbEntry = (version: string) => ({
|
||||
id: DB_PLUGIN_ID,
|
||||
version,
|
||||
displayName: 'Database',
|
||||
commands: [],
|
||||
keybindings: [],
|
||||
menus: [],
|
||||
settings: [],
|
||||
views: [
|
||||
{ id: `${DB_PLUGIN_ID}.workbench`, title: 'Database', location: 'vault-page', visible: true },
|
||||
],
|
||||
});
|
||||
const monitorEntry = {
|
||||
id: MONITOR_PLUGIN_ID,
|
||||
version: '1.0.0',
|
||||
displayName: 'Monitor',
|
||||
commands: [],
|
||||
keybindings: [],
|
||||
menus: [],
|
||||
settings: [],
|
||||
views: [
|
||||
{ id: `${MONITOR_PLUGIN_ID}.workbench`, title: 'Monitor', location: 'vault-page', visible: true },
|
||||
],
|
||||
};
|
||||
|
||||
let snapshot = { locale: 'en', plugins: [dbEntry('0.3.5'), monitorEntry] };
|
||||
let installed = [
|
||||
{ id: DB_PLUGIN_ID, enabled: true, activeVersion: '0.3.5' },
|
||||
{ id: MONITOR_PLUGIN_ID, enabled: true, activeVersion: '1.0.0' },
|
||||
];
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
Object.assign(dom.window, {
|
||||
netcatty: {
|
||||
async getPluginRuntimeStatus() { return { available: true }; },
|
||||
async getPluginContributions() { return { ...snapshot, plugins: [...snapshot.plugins] }; },
|
||||
async listPlugins() { return [...installed]; },
|
||||
onPluginContributionsChanged(cb: () => void) {
|
||||
listeners.add(cb);
|
||||
return () => { listeners.delete(cb); };
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const { default: React, act, useMemo, useState } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { usePluginVaultPages } = await import('./usePluginVaultPages');
|
||||
const { useVaultNavConfig } = await import('./useVaultNavConfig');
|
||||
const { STORAGE_KEY_VAULT_NAV_CONFIG } = await import('../../infrastructure/config/storageKeys');
|
||||
|
||||
let nav!: ReturnType<typeof useVaultNavConfig>;
|
||||
|
||||
function Fixture() {
|
||||
const [section, setSection] = useState<'hosts' | `plugin-vault:${string}`>('hosts');
|
||||
const pluginVault = usePluginVaultPages({ locale: 'en', section, select: setSection });
|
||||
const activePluginIds = useMemo(
|
||||
() => pluginVault.pages.map((page) => page.key),
|
||||
[pluginVault.pages],
|
||||
);
|
||||
const pluginOwnerByNavId = useMemo(
|
||||
() => Object.fromEntries(pluginVault.pages.map((page) => [page.key, page.pluginId])),
|
||||
[pluginVault.pages],
|
||||
);
|
||||
nav = useVaultNavConfig({
|
||||
activePluginIds,
|
||||
pluginsLoading: pluginVault.contributions.loading,
|
||||
pluginsAvailable: pluginVault.contributions.available,
|
||||
installedPluginIds: pluginVault.installedPluginIds,
|
||||
pluginOwnerByNavId,
|
||||
});
|
||||
return <div />;
|
||||
}
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 25));
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<Fixture />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
await settle();
|
||||
});
|
||||
assert.ok(nav.visibleIds.includes(OFFICIAL_DB_PLUGIN));
|
||||
assert.ok(nav.visibleIds.includes(OFFICIAL_MONITOR_PLUGIN));
|
||||
|
||||
await act(async () => {
|
||||
nav.reorder(OFFICIAL_DB_PLUGIN, 'hosts', 'after');
|
||||
await settle();
|
||||
});
|
||||
assert.equal(nav.visibleIds[1], OFFICIAL_DB_PLUGIN);
|
||||
|
||||
// beforeActivate disables Database 0.3.5 (still installed) and emits contributions-changed.
|
||||
snapshot = { locale: 'en', plugins: [monitorEntry] };
|
||||
installed = [
|
||||
{ id: DB_PLUGIN_ID, enabled: false, activeVersion: '0.3.5' },
|
||||
{ id: MONITOR_PLUGIN_ID, enabled: true, activeVersion: '1.0.0' },
|
||||
];
|
||||
await act(async () => {
|
||||
for (const listener of listeners) listener();
|
||||
await settle();
|
||||
});
|
||||
|
||||
assert.equal(nav.visibleIds.includes(OFFICIAL_DB_PLUGIN), false);
|
||||
assert.equal(nav.config.order[1], OFFICIAL_DB_PLUGIN);
|
||||
const persistedMidUpdate = JSON.parse(
|
||||
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
|
||||
);
|
||||
assert.equal(persistedMidUpdate.order[1], OFFICIAL_DB_PLUGIN);
|
||||
|
||||
// Database 0.3.6 activates and emits contributions-changed.
|
||||
snapshot = { locale: 'en', plugins: [dbEntry('0.3.6'), monitorEntry] };
|
||||
installed = [
|
||||
{ id: DB_PLUGIN_ID, enabled: true, activeVersion: '0.3.6' },
|
||||
{ id: MONITOR_PLUGIN_ID, enabled: true, activeVersion: '1.0.0' },
|
||||
];
|
||||
await act(async () => {
|
||||
for (const listener of listeners) listener();
|
||||
await settle();
|
||||
});
|
||||
|
||||
assert.equal(nav.visibleIds[1], OFFICIAL_DB_PLUGIN);
|
||||
assert.equal(nav.config.order[1], OFFICIAL_DB_PLUGIN);
|
||||
|
||||
// Hide Database, then simulate uninstall where plugin-disabled arrives before package removal
|
||||
// followed by post-uninstall contributions-changed once listPlugins no longer contains it.
|
||||
await act(async () => {
|
||||
nav.setVisible(OFFICIAL_DB_PLUGIN, false);
|
||||
await settle();
|
||||
});
|
||||
assert.equal(nav.isHidden(OFFICIAL_DB_PLUGIN), true);
|
||||
|
||||
snapshot = { locale: 'en', plugins: [monitorEntry] };
|
||||
installed = [
|
||||
{ id: DB_PLUGIN_ID, enabled: false, activeVersion: '0.3.6' },
|
||||
{ id: MONITOR_PLUGIN_ID, enabled: true, activeVersion: '1.0.0' },
|
||||
];
|
||||
await act(async () => {
|
||||
for (const listener of listeners) listener();
|
||||
await settle();
|
||||
});
|
||||
assert.equal(nav.config.order[1], OFFICIAL_DB_PLUGIN);
|
||||
assert.equal(nav.config.hidden.includes(OFFICIAL_DB_PLUGIN), true);
|
||||
|
||||
// Post-uninstall refresh (from onPluginUninstalled) sees DB removed and prunes slot + hidden flag.
|
||||
installed = [
|
||||
{ id: MONITOR_PLUGIN_ID, enabled: true, activeVersion: '1.0.0' },
|
||||
];
|
||||
await act(async () => {
|
||||
for (const listener of listeners) listener();
|
||||
await settle();
|
||||
});
|
||||
assert.equal(nav.config.order.includes(OFFICIAL_DB_PLUGIN), false);
|
||||
assert.equal(nav.config.hidden.includes(OFFICIAL_DB_PLUGIN), false);
|
||||
const persistedAfterUninstall = JSON.parse(
|
||||
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
|
||||
);
|
||||
assert.equal(persistedAfterUninstall.order.includes(OFFICIAL_DB_PLUGIN), false);
|
||||
assert.equal(persistedAfterUninstall.hidden.includes(OFFICIAL_DB_PLUGIN), false);
|
||||
|
||||
// Reinstalling in the same session restores the page visible by default at the end.
|
||||
snapshot = { locale: 'en', plugins: [dbEntry('0.3.6'), monitorEntry] };
|
||||
installed = [
|
||||
{ id: DB_PLUGIN_ID, enabled: true, activeVersion: '0.3.6' },
|
||||
{ id: MONITOR_PLUGIN_ID, enabled: true, activeVersion: '1.0.0' },
|
||||
];
|
||||
await act(async () => {
|
||||
for (const listener of listeners) listener();
|
||||
await settle();
|
||||
});
|
||||
assert.equal(nav.visibleIds.includes(OFFICIAL_DB_PLUGIN), true);
|
||||
assert.equal(nav.isHidden(OFFICIAL_DB_PLUGIN), false);
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
} finally {
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
getManageableVaultNavIds,
|
||||
getVisibleVaultNavIds,
|
||||
isCustomVaultNavConfig,
|
||||
isPluginVaultNavId,
|
||||
moveVaultNavItem,
|
||||
normalizeVaultNavConfig,
|
||||
reconcileVaultNavConfig,
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
setVaultNavItemVisibility,
|
||||
toggleVaultNavItemVisibility,
|
||||
type PluginVaultNavId,
|
||||
type ReconcileVaultNavOptions,
|
||||
type VaultNavConfig,
|
||||
type VaultNavDropPosition,
|
||||
type VaultNavItemId,
|
||||
@@ -30,6 +32,17 @@ export interface UseVaultNavConfigOptions {
|
||||
pluginsLoading?: boolean;
|
||||
/** Pass true once plugin contributions are available from the plugin runtime. */
|
||||
pluginsAvailable?: boolean;
|
||||
/**
|
||||
* Installed plugin package IDs (including disabled/updating plugins).
|
||||
* When omitted, saved plugin-vault:* entries are preserved rather than pruned
|
||||
* solely because they are absent from `activePluginIds`.
|
||||
*/
|
||||
installedPluginIds?: readonly string[];
|
||||
/**
|
||||
* Optional nav-key to owning plugin package ID map for currently active pages.
|
||||
* Cached across renders so a vanished page can still be attributed to its plugin.
|
||||
*/
|
||||
pluginOwnerByNavId?: Readonly<Record<string, string>>;
|
||||
}
|
||||
|
||||
export interface UseVaultNavConfigResult {
|
||||
@@ -57,11 +70,11 @@ export interface UseVaultNavConfigResult {
|
||||
|
||||
function readStoredVaultNavConfig(
|
||||
activePluginIds: readonly PluginVaultNavId[],
|
||||
pruneMissingPlugins: boolean,
|
||||
options: ReconcileVaultNavOptions,
|
||||
): VaultNavConfig {
|
||||
try {
|
||||
const raw = localStorageAdapter.read(STORAGE_KEY_VAULT_NAV_CONFIG);
|
||||
return normalizeVaultNavConfig(raw, activePluginIds, { pruneMissingPlugins });
|
||||
return normalizeVaultNavConfig(raw, activePluginIds, options);
|
||||
} catch {
|
||||
return resetVaultNavConfig(activePluginIds);
|
||||
}
|
||||
@@ -79,16 +92,36 @@ export function useVaultNavConfig({
|
||||
activePluginIds,
|
||||
pluginsLoading = false,
|
||||
pluginsAvailable = false,
|
||||
installedPluginIds,
|
||||
pluginOwnerByNavId,
|
||||
}: UseVaultNavConfigOptions): UseVaultNavConfigResult {
|
||||
const pluginKey = activePluginIds.join('\0');
|
||||
const stablePluginIds = useMemo<PluginVaultNavId[]>(
|
||||
() => (pluginKey ? (pluginKey.split('\0') as PluginVaultNavId[]) : []),
|
||||
[pluginKey],
|
||||
);
|
||||
const pruneMissingPlugins = !pluginsLoading && pluginsAvailable;
|
||||
const installedKey = installedPluginIds ? installedPluginIds.join('\0') : null;
|
||||
const stableInstalledPluginIds = useMemo<readonly string[] | undefined>(
|
||||
() => (installedKey === null ? undefined : installedKey ? installedKey.split('\0') : []),
|
||||
[installedKey],
|
||||
);
|
||||
const pluginOwnerCacheRef = useRef<Map<PluginVaultNavId, string>>(new Map());
|
||||
if (pluginOwnerByNavId) {
|
||||
for (const [navId, ownerId] of Object.entries(pluginOwnerByNavId)) {
|
||||
if (isPluginVaultNavId(navId) && ownerId) {
|
||||
pluginOwnerCacheRef.current.set(navId, ownerId);
|
||||
}
|
||||
}
|
||||
}
|
||||
const pruneMissingPlugins =
|
||||
!pluginsLoading && pluginsAvailable && stableInstalledPluginIds !== undefined;
|
||||
|
||||
const [config, setConfig] = useState<VaultNavConfig>(() =>
|
||||
readStoredVaultNavConfig(stablePluginIds, pruneMissingPlugins),
|
||||
readStoredVaultNavConfig(stablePluginIds, {
|
||||
pruneMissingPlugins,
|
||||
installedPluginIds: stableInstalledPluginIds,
|
||||
pluginOwnerByNavId: pluginOwnerCacheRef.current,
|
||||
}),
|
||||
);
|
||||
const configRef = useRef<VaultNavConfig>(config);
|
||||
configRef.current = config;
|
||||
@@ -100,6 +133,8 @@ export function useVaultNavConfig({
|
||||
const current = configRef.current;
|
||||
const reconciled = reconcileVaultNavConfig(current, stablePluginIds, {
|
||||
pruneMissingPlugins,
|
||||
installedPluginIds: stableInstalledPluginIds,
|
||||
pluginOwnerByNavId: pluginOwnerCacheRef.current,
|
||||
});
|
||||
if (!areVaultNavConfigsEqual(current, reconciled)) {
|
||||
configRef.current = reconciled;
|
||||
@@ -120,7 +155,7 @@ export function useVaultNavConfig({
|
||||
// Ignore storage read errors.
|
||||
}
|
||||
}
|
||||
}, [pruneMissingPlugins, stablePluginIds]);
|
||||
}, [pruneMissingPlugins, stableInstalledPluginIds, stablePluginIds]);
|
||||
|
||||
// Cross-window and adapter sync.
|
||||
useEffect(() => {
|
||||
@@ -134,7 +169,11 @@ export function useVaultNavConfig({
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const next = readStoredVaultNavConfig(stablePluginIds, pruneMissingPlugins);
|
||||
const next = readStoredVaultNavConfig(stablePluginIds, {
|
||||
pruneMissingPlugins,
|
||||
installedPluginIds: stableInstalledPluginIds,
|
||||
pluginOwnerByNavId: pluginOwnerCacheRef.current,
|
||||
});
|
||||
if (!areVaultNavConfigsEqual(configRef.current, next)) {
|
||||
configRef.current = next;
|
||||
setConfig(next);
|
||||
@@ -146,7 +185,7 @@ export function useVaultNavConfig({
|
||||
window.removeEventListener('storage', sync);
|
||||
window.removeEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, sync);
|
||||
};
|
||||
}, [pruneMissingPlugins, stablePluginIds]);
|
||||
}, [pruneMissingPlugins, stableInstalledPluginIds, stablePluginIds]);
|
||||
|
||||
const commit = useCallback((next: VaultNavConfig): VaultNavConfig => {
|
||||
if (areVaultNavConfigsEqual(configRef.current, next)) {
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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[];
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -62,6 +62,7 @@ interface AIChatPanelContentProps {
|
||||
inputValueRevision?: number;
|
||||
setInputValue: (value: string) => void;
|
||||
handleSend: (textOverride?: string) => void;
|
||||
onSendWithGrokMode?: (text: string) => void;
|
||||
handleSendQuickPrompt?: (promptText: string) => void;
|
||||
handleCompact: () => void;
|
||||
/** Rename a chat by id (history drawer edit affordance). Panel action, never agent content. */
|
||||
@@ -176,6 +177,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
setInputValue,
|
||||
handleSend,
|
||||
handleSendQuickPrompt,
|
||||
onSendWithGrokMode,
|
||||
handleCompact,
|
||||
onRenameSession,
|
||||
onRenameActiveChat,
|
||||
@@ -574,6 +576,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
onChange={setInputValue}
|
||||
onSend={handleSend}
|
||||
onSendQuickPrompt={handleSendQuickPrompt}
|
||||
onSendWithGrokMode={onSendWithGrokMode}
|
||||
onCompact={handleCompact}
|
||||
onRenameSession={onRenameActiveChat}
|
||||
onListChats={onListChats}
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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]);
|
||||
@@ -1737,7 +1739,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
|
||||
const handleSend = useCallback(async (
|
||||
textOverride?: string,
|
||||
options?: { includeDraftAttachments?: boolean },
|
||||
options?: { includeDraftAttachments?: boolean; chooseGrokMode?: boolean },
|
||||
) => {
|
||||
const draft = currentDraftRef.current;
|
||||
const currentPanelView = panelViewRef.current;
|
||||
@@ -1962,6 +1964,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
scopeType,
|
||||
scopeTargetId,
|
||||
existingSessionId: existingExternalSessionId,
|
||||
chooseGrokMode: options?.chooseGrokMode,
|
||||
updateExternalSessionId: updateSessionExternalSessionId,
|
||||
historyMessages: buildExternalAgentHistoryMessagesForBridge(currentSession?.messages ?? [], existingExternalSessionId),
|
||||
terminalSessions,
|
||||
@@ -2127,7 +2130,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 +2166,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') {
|
||||
@@ -2182,6 +2190,10 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
return registerGrantPersister((rule) => { addGrant(rule); });
|
||||
}, [addGrant]);
|
||||
|
||||
const handleSendWithGrokMode = useCallback((text: string) => {
|
||||
void handleSend(text, { includeDraftAttachments: true, chooseGrokMode: true });
|
||||
}, [handleSend]);
|
||||
|
||||
const handleSendQuickPrompt = useCallback((promptText: string) => {
|
||||
void handleSend(promptText, { includeDraftAttachments: true });
|
||||
}, [handleSend]);
|
||||
@@ -2437,9 +2449,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 +2558,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 +2581,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
handleManagerDelete,
|
||||
handleManagerDeleteMany,
|
||||
handleManagerRegenerateTitle,
|
||||
handleManagerRegenerateTitles,
|
||||
handleManagerExport,
|
||||
onFocusAIScopeTarget,
|
||||
]);
|
||||
@@ -2586,6 +2659,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
setInputValue={setInputValue}
|
||||
handleSend={handleSend}
|
||||
handleSendQuickPrompt={handleSendQuickPrompt}
|
||||
onSendWithGrokMode={getExternalAgentSdkBackend(currentAgentConfig ?? undefined) === 'grok' && currentAgentConfig?.grokRuntime !== 'streaming-json' ? handleSendWithGrokMode : undefined}
|
||||
handleCompact={handleCompact}
|
||||
onRenameSession={handleRenameSession}
|
||||
onRenameActiveChat={handleRenameSlashCommand}
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
@@ -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
@@ -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}
|
||||
|
||||
@@ -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*\/>/);
|
||||
});
|
||||
@@ -383,8 +383,8 @@ const ConnectionLogsManager: React.FC<ConnectionLogsManagerProps> = ({
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors cursor-pointer",
|
||||
active
|
||||
? "bg-primary/12 text-primary border border-primary/25"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-secondary/60 border border-transparent",
|
||||
? "bg-primary/12 text-primary"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-secondary/60",
|
||||
)}
|
||||
>
|
||||
{item.icon}
|
||||
|
||||
@@ -624,13 +624,55 @@ const KnownHostsManager: React.FC<KnownHostsManagerProps> = ({
|
||||
return (
|
||||
<div className="h-full flex flex-col">
|
||||
<VaultPageHeader>
|
||||
<div className="flex-1 min-w-0 flex items-center gap-2">
|
||||
<div className="flex-1 min-w-0 flex flex-wrap items-center gap-2">
|
||||
<VaultHeaderSearch
|
||||
placeholder={t("knownHosts.search.placeholder")}
|
||||
className="flex-1 max-w-xs"
|
||||
className="flex-1 min-w-[160px] max-w-xs"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
<div
|
||||
role="tablist"
|
||||
aria-label={t("vault.nav.knownHosts")}
|
||||
className="inline-flex h-10 shrink-0 items-center rounded-md bg-secondary/70 p-1 gap-0.5"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeTab === "ssh"}
|
||||
data-known-hosts-tab="ssh"
|
||||
onClick={() => setActiveTab("ssh")}
|
||||
className={cn(
|
||||
"inline-flex h-full items-center gap-1.5 rounded-sm px-2.5 text-xs font-medium whitespace-nowrap transition-all cursor-pointer",
|
||||
activeTab === "ssh"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span>{t("knownHosts.tabs.ssh")}</span>
|
||||
<span className="rounded-full bg-secondary px-1.5 py-0 text-[10px] tabular-nums text-muted-foreground">
|
||||
{filteredHosts.length}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeTab === "certs"}
|
||||
data-known-hosts-tab="certs"
|
||||
onClick={() => setActiveTab("certs")}
|
||||
className={cn(
|
||||
"inline-flex h-full items-center gap-1.5 rounded-sm px-2.5 text-xs font-medium whitespace-nowrap transition-all cursor-pointer",
|
||||
activeTab === "certs"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span>{t("knownHosts.tabs.remoteDesktopCerts")}</span>
|
||||
<span className="rounded-full bg-secondary px-1.5 py-0 text-[10px] tabular-nums text-muted-foreground">
|
||||
{remoteCerts.length}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
{/* View Mode Toggle */}
|
||||
@@ -720,52 +762,6 @@ const KnownHostsManager: React.FC<KnownHostsManagerProps> = ({
|
||||
)}
|
||||
</VaultPageHeader>
|
||||
|
||||
{/* Segmented Tab Strip: SSH Host Keys | Remote Desktop Certificates */}
|
||||
<div className="px-4 py-2 border-b border-border/50 bg-background/60 shrink-0">
|
||||
<div
|
||||
role="tablist"
|
||||
aria-label={t("vault.nav.knownHosts")}
|
||||
className="inline-flex items-center rounded-lg bg-secondary/70 p-0.5 gap-0.5"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeTab === "ssh"}
|
||||
data-known-hosts-tab="ssh"
|
||||
onClick={() => setActiveTab("ssh")}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-all",
|
||||
activeTab === "ssh"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span>{t("knownHosts.tabs.ssh")}</span>
|
||||
<span className="rounded-full bg-secondary px-1.5 py-0 text-[10px] tabular-nums text-muted-foreground">
|
||||
{filteredHosts.length}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeTab === "certs"}
|
||||
data-known-hosts-tab="certs"
|
||||
onClick={() => setActiveTab("certs")}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-all",
|
||||
activeTab === "certs"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span>{t("knownHosts.tabs.remoteDesktopCerts")}</span>
|
||||
<span className="rounded-full bg-secondary px-1.5 py-0 text-[10px] tabular-nums text-muted-foreground">
|
||||
{remoteCerts.length}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<ScrollArea className="flex-1">
|
||||
{activeTab === "certs" ? (
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
|
||||
@@ -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
@@ -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);
|
||||
|
||||
@@ -191,6 +191,7 @@ interface TopTabsProps {
|
||||
onCopySession: (sessionId: string) => void;
|
||||
onDuplicateSession?: (sessionId: string) => void;
|
||||
onCopySessionToNewWindow: (sessionId: string) => void;
|
||||
onConvertSessionToWorkspace?: (sessionId: string) => void;
|
||||
onMoveSessionToNewWindow?: (sessionId: string) => void;
|
||||
onEditHost?: (host: Host) => void;
|
||||
onRenameWorkspace: (workspaceId: string) => void;
|
||||
@@ -249,6 +250,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
onDuplicateSession,
|
||||
onCopySessionToNewWindow,
|
||||
onMoveSessionToNewWindow,
|
||||
onConvertSessionToWorkspace,
|
||||
onEditHost,
|
||||
onRenameWorkspace,
|
||||
onCopyWorkspace,
|
||||
@@ -992,6 +994,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
onDuplicateSession={onDuplicateSession}
|
||||
onCopySessionToNewWindow={onCopySessionToNewWindow}
|
||||
onMoveSessionToNewWindow={onMoveSessionToNewWindow}
|
||||
onConvertSessionToWorkspace={onConvertSessionToWorkspace}
|
||||
onEditHost={onEditHost}
|
||||
renderBulkCloseItems={renderBulkCloseItems}
|
||||
dynamicTabTitleMode={dynamicTabTitleMode}
|
||||
@@ -1391,6 +1394,7 @@ export const topTabsAreEqual = (prev: TopTabsProps, next: TopTabsProps): boolean
|
||||
prev.onCopySession === next.onCopySession &&
|
||||
prev.onDuplicateSession === next.onDuplicateSession &&
|
||||
prev.onCopySessionToNewWindow === next.onCopySessionToNewWindow &&
|
||||
prev.onConvertSessionToWorkspace === next.onConvertSessionToWorkspace &&
|
||||
prev.onMoveSessionToNewWindow === next.onMoveSessionToNewWindow &&
|
||||
prev.onEditHost === next.onEditHost &&
|
||||
prev.onAppendHostToWorkspace === next.onAppendHostToWorkspace &&
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -391,10 +391,16 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
() => pluginVault.pages.map((page) => page.key),
|
||||
[pluginVault.pages],
|
||||
);
|
||||
const pluginOwnerByNavId = useMemo(
|
||||
() => Object.fromEntries(pluginVault.pages.map((page) => [page.key, page.pluginId])),
|
||||
[pluginVault.pages],
|
||||
);
|
||||
const vaultNavConfig = useVaultNavConfig({
|
||||
activePluginIds: activePluginNavIds,
|
||||
pluginsLoading: pluginVault.contributions.loading,
|
||||
pluginsAvailable: pluginVault.contributions.available,
|
||||
installedPluginIds: pluginVault.installedPluginIds,
|
||||
pluginOwnerByNavId,
|
||||
});
|
||||
const previousHiddenNavRef = useRef<ReadonlySet<VaultNavItemId>>(vaultNavConfig.hiddenSet);
|
||||
useEffect(() => {
|
||||
|
||||
@@ -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;/);
|
||||
});
|
||||
@@ -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';
|
||||
@@ -263,6 +263,7 @@ interface ChatInputProps {
|
||||
hosts?: Array<{ sessionId: string; hostname: string; label: string; connected: boolean; protocol?: string }>;
|
||||
/** Explicit signal that the active tab/scope is a VNC or RDP remote desktop. */
|
||||
isRemoteDesktopContext?: boolean;
|
||||
onSendWithGrokMode?: (text: string) => void;
|
||||
/** Optional handler invoked when a remote desktop quick prompt chip is clicked. */
|
||||
onSendQuickPrompt?: (promptText: string) => void;
|
||||
/** Force-show remote desktop quick prompt chips (auto-shown when a remote screen image is attached). */
|
||||
@@ -342,6 +343,7 @@ const ChatInput: React.FC<ChatInputProps> = ({
|
||||
hosts = [],
|
||||
isRemoteDesktopContext = false,
|
||||
onSendQuickPrompt,
|
||||
onSendWithGrokMode,
|
||||
showRemoteScreenQuickPrompts,
|
||||
notes = [],
|
||||
onMentionNote,
|
||||
@@ -556,7 +558,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 +580,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 +1425,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}
|
||||
@@ -1682,6 +1691,22 @@ const ChatInput: React.FC<ChatInputProps> = ({
|
||||
<span className="flex-1 text-foreground/85">{t('ai.chat.menuMentionHost')}</span>
|
||||
{hosts.length > 0 && <ChevronRight size={10} className="text-muted-foreground/50" />}
|
||||
</button>
|
||||
{onSendWithGrokMode && (
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
disabled={composerDisabled || isStreaming || (!hasTextStore.get() && !hasTerminalSelectionAttachment && !hasImageAttachment)}
|
||||
onClick={() => {
|
||||
const text = readComposerText();
|
||||
closeAllMenus();
|
||||
onSendWithGrokMode(text);
|
||||
}}
|
||||
className="w-full flex items-center gap-2.5 px-3 py-1.5 text-left text-[12px] hover:bg-muted/30 cursor-pointer whitespace-nowrap disabled:opacity-40"
|
||||
>
|
||||
<MessageSquare size={13} className="text-muted-foreground/60" />
|
||||
{t('ai.grok.chooseModeAndSend')}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
@@ -2019,6 +2044,7 @@ function chatInputPropsAreEqual(prev: ChatInputProps, next: ChatInputProps): boo
|
||||
&& prev.onRemoveFile === next.onRemoveFile
|
||||
&& prev.hosts === next.hosts
|
||||
&& prev.isRemoteDesktopContext === next.isRemoteDesktopContext
|
||||
&& prev.onSendWithGrokMode === next.onSendWithGrokMode
|
||||
&& prev.onSendQuickPrompt === next.onSendQuickPrompt
|
||||
&& prev.showRemoteScreenQuickPrompts === next.showRemoteScreenQuickPrompts
|
||||
&& prev.notes === next.notes
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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 = [
|
||||
|
||||
@@ -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"]);
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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(() => {
|
||||
|
||||
@@ -70,8 +70,13 @@ test('uninstall requires a visible confirmation, reports failures, and removes t
|
||||
await act(async () => { fail(new Error('Synthetic removal failed')); await settle(); });
|
||||
assert.match(confirmation()!.querySelector('[role="alert"]')!.textContent!, /Synthetic removal failed/);
|
||||
assert.equal(installed.length, 1);
|
||||
let packagesChangedEvents = 0;
|
||||
const onPackagesChanged = () => { packagesChangedEvents += 1; };
|
||||
dom.window.addEventListener('netcatty:plugin-packages-changed', onPackagesChanged);
|
||||
await act(async () => { button('Uninstall', confirmation()!).click(); await settle(); });
|
||||
await act(async () => { finish(); await settle(); });
|
||||
dom.window.removeEventListener('netcatty:plugin-packages-changed', onPackagesChanged);
|
||||
assert.equal(packagesChangedEvents, 1, 'successful uninstall dispatches plugin-packages-changed');
|
||||
assert.equal(confirmation(), null);
|
||||
assert.equal(installed.length, 0);
|
||||
assert.equal(document.querySelector('article'), null, 'the removed plugin no longer has an installed card or detail');
|
||||
|
||||
@@ -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: "agy", 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')}
|
||||
|
||||
@@ -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") ?? "",
|
||||
};
|
||||
}
|
||||
@@ -242,6 +242,12 @@ export const AGENT_DEFAULTS: Record<string, Omit<ExternalAgentConfig, "id" | "co
|
||||
icon: "grok",
|
||||
sdkBackend: "grok",
|
||||
},
|
||||
agy: {
|
||||
name: "Antigravity CLI",
|
||||
args: [],
|
||||
icon: "agy",
|
||||
sdkBackend: "agy",
|
||||
},
|
||||
mimo: {
|
||||
name: "MiMo Code",
|
||||
args: [],
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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> `,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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"
|
||||
|
||||
Loaded 100 of 221 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user