mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-12-04 00:10:49 +00:00
Compare commits
61
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
69015c7cf2 | ||
|
|
e6d3047d0a | ||
|
|
f50c18e5c7 | ||
|
|
33b4bd1a43 | ||
|
|
31458b00a4 | ||
|
|
f68570d942 | ||
|
|
9474601fdf | ||
|
|
4cef084e99 | ||
|
|
58eeefb4c1 | ||
|
|
6f8211481c | ||
|
|
6458dbe039 | ||
|
|
6e0eacc6ae | ||
|
|
73ee6c0f31 | ||
|
|
905aed61ad | ||
|
|
13d05b0ea4 | ||
|
|
1045737c68 | ||
|
|
909d3e5ed2 | ||
|
|
cb7e49c409 | ||
|
|
02be8a2e0a | ||
|
|
ca2cdcbd12 | ||
|
|
f7fed5fd6f | ||
|
|
25aa27bbf8 | ||
|
|
7e44b774f8 | ||
|
|
c5c7cfdae3 | ||
|
|
62085cb3c2 | ||
|
|
960cc05219 | ||
|
|
7ad4a7daf5 | ||
|
|
469cecb963 | ||
|
|
3c7b19a208 | ||
|
|
782a59d246 | ||
|
|
6a950e1eed | ||
|
|
a6eaaed9ef | ||
|
|
6d2132f7fa | ||
|
|
f5afbaaf90 | ||
|
|
329d2b631c | ||
|
|
ea5521cae8 | ||
|
|
ae1fff28ae | ||
|
|
902c7b33c4 | ||
|
|
57b8ac53e3 | ||
|
|
b0e11af042 | ||
|
|
1851ee39b9 | ||
|
|
a01e58ac77 | ||
|
|
2b766abe6b | ||
|
|
4b65002a78 | ||
|
|
520b434866 | ||
|
|
7cdb07e9ed | ||
|
|
1b15e9773f | ||
|
|
ac1f779323 | ||
|
|
9d579c10ff | ||
|
|
c3cd4850ab | ||
|
|
74a304952b | ||
|
|
db30429344 | ||
|
|
b9d58c2825 | ||
|
|
12a49604d1 | ||
|
|
a06ebcc467 | ||
|
|
4686a945fc | ||
|
|
4b05b03776 | ||
|
|
5d5c5b0940 | ||
|
|
549f58c653 | ||
|
|
3a913b8fc2 | ||
|
|
8cae6c5784 |
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
|
||||
|
||||
@@ -1137,3 +1137,159 @@ test('executeHotkeyActionImpl reopenClosedTab calls reopenLastClosedTab and reco
|
||||
assert.equal(logs[1].username, 'dev');
|
||||
assert.equal(logs[1].protocol, 'local');
|
||||
});
|
||||
|
||||
for (const scheme of ['pc', 'mac'] as const) {
|
||||
test(`addSessionToWorkspace shortcut ${scheme}: opens append dialog and consumes event only when a workspace is active`, () => {
|
||||
const target = new FakeHTMLElement();
|
||||
|
||||
for (const scenario of [
|
||||
{ name: 'active workspace', activeTabId: 'workspace-1', expectConsume: true },
|
||||
{ name: 'standalone terminal', activeTabId: 'session-1', expectConsume: false },
|
||||
{ name: 'vault tab', activeTabId: 'vault', expectConsume: false },
|
||||
{ name: 'sftp tab', activeTabId: 'sftp', expectConsume: false },
|
||||
{ name: 'editor tab', activeTabId: 'editor:file-1', expectConsume: false },
|
||||
{ name: 'log view tab', activeTabId: 'log-1', expectConsume: false },
|
||||
{ name: 'plugin view tab', activeTabId: 'plugin-view:demo:main', expectConsume: false },
|
||||
]) {
|
||||
const dialogCalls: unknown[] = [];
|
||||
let prevented = 0;
|
||||
let stopped = 0;
|
||||
const event = {
|
||||
key: 'n',
|
||||
code: 'KeyN',
|
||||
ctrlKey: scheme === 'pc',
|
||||
metaKey: scheme === 'mac',
|
||||
altKey: false,
|
||||
shiftKey: false,
|
||||
target,
|
||||
composedPath: () => [target],
|
||||
preventDefault: () => { prevented += 1; },
|
||||
stopPropagation: () => { stopped += 1; },
|
||||
} as unknown as KeyboardEvent;
|
||||
|
||||
const actionCtx = {
|
||||
activeTabStore: { getActiveTabId: () => scenario.activeTabId },
|
||||
editorTabs: [{ id: 'file-1' }],
|
||||
orderedTabs: ['session-1', 'workspace-1'],
|
||||
sessions: [{ id: 'session-1' }, { id: 's-ws', workspaceId: 'workspace-1' }],
|
||||
settings: { showSftpTab: true, shellOnlyTabNumberShortcuts: false },
|
||||
setAddToWorkspaceDialog: (value: unknown) => { dialogCalls.push(value); },
|
||||
toEditorTabId: (id: string) => `editor:${id}`,
|
||||
workspaces: [{ id: 'workspace-1', title: 'Workspace 1' }],
|
||||
};
|
||||
|
||||
handleGlobalHotkeyKeyDownImpl(
|
||||
() => ({
|
||||
HOTKEY_DEBUG: false,
|
||||
closeTabKeyStr: '',
|
||||
hotkeyScheme: scheme,
|
||||
keyBindings: DEFAULT_KEY_BINDINGS,
|
||||
matchesKeyBinding,
|
||||
executeHotkeyAction: (action: string, ev: KeyboardEvent) =>
|
||||
executeHotkeyActionImpl(() => actionCtx, action, ev),
|
||||
}),
|
||||
event,
|
||||
);
|
||||
|
||||
assert.deepEqual(
|
||||
dialogCalls,
|
||||
scenario.expectConsume ? [{ mode: 'append', workspaceId: 'workspace-1' }] : [],
|
||||
`${scheme} / ${scenario.name}: dialog calls`,
|
||||
);
|
||||
assert.equal(
|
||||
prevented,
|
||||
scenario.expectConsume ? 1 : 0,
|
||||
`${scheme} / ${scenario.name}: preventDefault count`,
|
||||
);
|
||||
assert.equal(
|
||||
stopped,
|
||||
scenario.expectConsume ? 1 : 0,
|
||||
`${scheme} / ${scenario.name}: stopPropagation count`,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('addSessionToWorkspace shortcut stays out of form inputs and Monaco even while a workspace is active', () => {
|
||||
for (const [label, target] of [
|
||||
['input', new FakeInputHTMLElement()],
|
||||
['monaco', new FakeMonacoHTMLElement()],
|
||||
] as const) {
|
||||
const dialogCalls: unknown[] = [];
|
||||
let prevented = 0;
|
||||
let stopped = 0;
|
||||
const event = {
|
||||
key: 'n',
|
||||
code: 'KeyN',
|
||||
ctrlKey: true,
|
||||
metaKey: false,
|
||||
altKey: false,
|
||||
shiftKey: false,
|
||||
target,
|
||||
composedPath: () => [target],
|
||||
preventDefault: () => { prevented += 1; },
|
||||
stopPropagation: () => { stopped += 1; },
|
||||
} as unknown as KeyboardEvent;
|
||||
|
||||
handleGlobalHotkeyKeyDownImpl(
|
||||
() => ({
|
||||
HOTKEY_DEBUG: false,
|
||||
closeTabKeyStr: '',
|
||||
hotkeyScheme: 'pc',
|
||||
keyBindings: DEFAULT_KEY_BINDINGS,
|
||||
matchesKeyBinding,
|
||||
executeHotkeyAction: (action: string, ev: KeyboardEvent) =>
|
||||
executeHotkeyActionImpl(() => ({
|
||||
activeTabStore: { getActiveTabId: () => 'workspace-1' },
|
||||
editorTabs: [],
|
||||
orderedTabs: ['workspace-1'],
|
||||
sessions: [],
|
||||
settings: {},
|
||||
setAddToWorkspaceDialog: (value: unknown) => { dialogCalls.push(value); },
|
||||
toEditorTabId: (id: string) => `editor:${id}`,
|
||||
workspaces: [{ id: 'workspace-1', title: 'Workspace 1' }],
|
||||
}), action, ev),
|
||||
}),
|
||||
event,
|
||||
);
|
||||
|
||||
assert.deepEqual(dialogCalls, [], `${label} should not open workspace dialog`);
|
||||
assert.equal(prevented, 0, `${label} should not preventDefault`);
|
||||
assert.equal(stopped, 0, `${label} should not stopPropagation`);
|
||||
}
|
||||
});
|
||||
|
||||
test('executeHotkeyActionImpl addSessionToWorkspace returns boolean availability defensively', () => {
|
||||
const dialogCalls: unknown[] = [];
|
||||
const makeCtx = (overrides: Record<string, unknown> = {}) => ({
|
||||
activeTabStore: { getActiveTabId: () => 'workspace-1' },
|
||||
editorTabs: [],
|
||||
orderedTabs: [],
|
||||
sessions: [],
|
||||
settings: {},
|
||||
setAddToWorkspaceDialog: (value: unknown) => { dialogCalls.push(value); },
|
||||
toEditorTabId: (id: string) => `editor:${id}`,
|
||||
workspaces: [{ id: 'workspace-1', title: 'Workspace 1' }],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
assert.equal(
|
||||
executeHotkeyActionImpl(() => makeCtx({ workspaces: undefined }), 'addSessionToWorkspace', {} as KeyboardEvent),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
executeHotkeyActionImpl(() => makeCtx({ setAddToWorkspaceDialog: undefined }), 'addSessionToWorkspace', {} as KeyboardEvent),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
executeHotkeyActionImpl(() => makeCtx({ activeTabStore: { getActiveTabId: () => 'session-1' } }), 'addSessionToWorkspace', {} as KeyboardEvent),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(dialogCalls, []);
|
||||
|
||||
assert.equal(
|
||||
executeHotkeyActionImpl(() => makeCtx(), 'addSessionToWorkspace', {} as KeyboardEvent),
|
||||
true,
|
||||
);
|
||||
assert.deepEqual(dialogCalls, [{ mode: 'append', workspaceId: 'workspace-1' }]);
|
||||
});
|
||||
@@ -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)
|
||||
@@ -394,8 +394,13 @@ export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: Keybo
|
||||
|
||||
// An unavailable action must leave the chord to the terminal.
|
||||
// Broadcast keeps Ctrl/Cmd+B for tmux; the host list keeps Ctrl/Cmd+Shift+B
|
||||
// when the sidebar cannot show. Dispatch once before consuming it.
|
||||
if (binding.action === 'broadcast' || binding.action === 'toggleHostTree') {
|
||||
// when the sidebar cannot show; addSessionToWorkspace keeps Ctrl/Cmd+N
|
||||
// when no workspace tab is active. Dispatch once before consuming it.
|
||||
if (
|
||||
binding.action === 'broadcast'
|
||||
|| binding.action === 'toggleHostTree'
|
||||
|| binding.action === 'addSessionToWorkspace'
|
||||
) {
|
||||
if (executeHotkeyAction(binding.action, e) === true) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
@@ -1218,6 +1223,17 @@ export function executeHotkeyActionImpl(getCtx: AppContextGetter, action: string
|
||||
// button, but without having to open QS first.
|
||||
setAddToWorkspaceDialog({ mode: 'create' });
|
||||
break;
|
||||
case 'addSessionToWorkspace': {
|
||||
// Open the same append-mode picker the workspace tab context menu
|
||||
// uses, targeting the currently active workspace. A standalone tab
|
||||
// (or vault/settings) has no workspace to append into, so return false
|
||||
// to leave the chord for the active surface or terminal.
|
||||
const currentId = activeTabStore.getActiveTabId();
|
||||
const activeWs = (workspaces ?? []).find((w) => w.id === currentId);
|
||||
if (!activeWs || typeof setAddToWorkspaceDialog !== 'function') return false;
|
||||
setAddToWorkspaceDialog({ mode: 'append', workspaceId: activeWs.id });
|
||||
return true;
|
||||
}
|
||||
case 'portForwarding':
|
||||
// Navigate to vault and open port forwarding section
|
||||
setActiveTabId('vault');
|
||||
|
||||
@@ -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.
|
||||
@@ -1847,6 +1840,7 @@ export function AppSideEffects() {
|
||||
hostname: result.target.hostname,
|
||||
port: result.target.port,
|
||||
username: result.target.username || undefined,
|
||||
...(result.target.password ? { password: result.target.password } : {}),
|
||||
domain: result.target.domain || undefined,
|
||||
label: result.target.label,
|
||||
rdpContent: result.target.rawRdpFileContent,
|
||||
|
||||
@@ -572,6 +572,7 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
onEditHost={handleEditHostFromOverlay}
|
||||
onRenameWorkspace={startWorkspaceRename}
|
||||
onCopyWorkspace={copyWorkspaceWithCurrentShell}
|
||||
onRequestAddToWorkspace={handleRequestAddToWorkspace}
|
||||
onCloseWorkspace={closeWorkspace}
|
||||
onCloseLogView={closeLogView}
|
||||
onCloseTabsBatch={closeTabsBatch}
|
||||
|
||||
@@ -117,6 +117,9 @@ export const enAiMessages: Messages = {
|
||||
'ai.codex.appServer.available': 'App Server is available for this Codex CLI.',
|
||||
'ai.codex.appServer.modelCatalogWarning': 'The live Codex model catalog is unavailable. Using the built-in model list.',
|
||||
'ai.codex.appServer.approval.allowSession': 'Allow for session',
|
||||
'ai.planReview.title': 'Review implementation plan',
|
||||
'ai.planReview.keepPlanning': 'Keep planning',
|
||||
'ai.planReview.approveAndImplement': 'Approve and implement',
|
||||
'ai.codex.appServer.userInput.title': 'Codex needs your input',
|
||||
'ai.codex.appServer.userInput.description': 'Answer these questions to continue the current turn.',
|
||||
'ai.codex.appServer.userInput.other': 'Enter another answer',
|
||||
@@ -328,6 +331,9 @@ export const enAiMessages: Messages = {
|
||||
'ai.grok.check': 'Check',
|
||||
'ai.grok.resetPath': 'Reset',
|
||||
'ai.grok.runtime.acp.title': 'Use Grok ACP (agent stdio)',
|
||||
'ai.grok.userQuestion.title': 'Grok needs your input',
|
||||
'ai.grok.userQuestion.description': 'Answers do not grant permissions. Do not include passwords or tokens.',
|
||||
'ai.grok.userQuestion.submit': 'Send answers',
|
||||
'ai.grok.runtime.acp.default': 'Default',
|
||||
'ai.grok.runtime.acp.description':
|
||||
'Talk to Grok over Agent Client Protocol (grok agent stdio). Injects Netcatty MCP on session/new. Turn off to use the original headless streaming-json CLI path.',
|
||||
@@ -629,12 +635,25 @@ export const enAiMessages: Messages = {
|
||||
'ai.chat.managerRebindPick': 'Choose a terminal or workspace…',
|
||||
'ai.chat.managerRebindHere': 'Current panel',
|
||||
'ai.chat.managerRebindDone': 'Moved "{title}" to {target}.',
|
||||
'ai.chat.managerToggleSelection': 'Select chats',
|
||||
'ai.chat.managerSelectAll': 'Select all',
|
||||
'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',
|
||||
'ai.chat.managerMessagesCount': '{n} messages',
|
||||
'ai.chat.managerDeleteTitle': 'Delete this chat?',
|
||||
'ai.chat.managerDeleteMessage': '"{title}" and its messages will be removed from every panel. This cannot be undone.',
|
||||
'ai.chat.managerBulkDeleteTitle': 'Delete {n} chats?',
|
||||
'ai.chat.managerBulkDeleteMessage': '{n} selected chats and their messages will be removed from every panel. This cannot be undone.',
|
||||
'ai.chat.justNow': 'Just now',
|
||||
'ai.chat.minutesAgo': '{n}m ago',
|
||||
'ai.chat.hoursAgo': '{n}h ago',
|
||||
@@ -685,9 +704,25 @@ 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',
|
||||
'ai.chatHistory.autoLlmTitle': 'Auto-generate chat titles',
|
||||
'ai.chatHistory.autoLlmTitle.description': 'Use a small one-shot LLM call to write a short title after the first message. Falls back to the first line if unavailable. Local setting only.',
|
||||
'ai.chatHistory.titleModel': 'Title model',
|
||||
'ai.chatHistory.titleModel.description': 'Provider and model used to generate chat titles. Pick a small, cheap model. Defaults to the current Catty model.',
|
||||
'ai.chatHistory.titleModel.none': 'No enabled provider available.',
|
||||
'ai.chatHistory.titleModel.useCurrentCatty': 'Use current Catty model',
|
||||
'ai.chatHistory.titleModel.unavailable': 'Unavailable',
|
||||
'ai.chatHistory.titleModel.providerPlaceholder': 'Select provider',
|
||||
'ai.chatHistory.titleModel.modelPlaceholder': 'Select model',
|
||||
|
||||
// AI Error
|
||||
'ai.codex.bridgeError': 'Codex main-process handlers are not loaded yet. Fully restart Netcatty, or restart the Electron dev process, then try again.',
|
||||
|
||||
@@ -431,6 +431,8 @@ export const enCoreMessages: Messages = {
|
||||
'settings.vault.showSftpTab': 'Show SFTP tab',
|
||||
'settings.vault.showSftpTabDesc': 'Display the standalone SFTP view in the top tab bar. When hidden, use the in-session SFTP side panel instead.',
|
||||
'settings.vault.showHostTreeSidebar': 'Show host list sidebar',
|
||||
'settings.vault.removeTopTabsDragArea': 'Remove the top window-drag area',
|
||||
'settings.vault.removeTopTabsDragAreaDesc': 'When enabled, remove the draggable space above the tabs so the top edge is available for clicks.',
|
||||
'settings.vault.showHostTreeSidebarDesc': 'Display the host list sidebar and its top-bar toggle on terminal and editor tabs.',
|
||||
'settings.vault.autoImportSystemKnownHosts': 'Auto-import system known_hosts',
|
||||
'settings.vault.autoImportSystemKnownHostsDesc': 'When Vault loads, silently import entries from the OpenSSH known_hosts file. Turn this off to keep Netcatty known hosts separate; Scan System still imports on demand.',
|
||||
@@ -999,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',
|
||||
@@ -1027,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',
|
||||
@@ -1061,6 +1069,7 @@ Highlight the focused split pane:
|
||||
'settings.shortcuts.binding.command-palette': 'Open Command Palette',
|
||||
'settings.shortcuts.binding.quick-switch': 'Quick Switch',
|
||||
'settings.shortcuts.binding.new-workspace': 'New Workspace',
|
||||
'settings.shortcuts.binding.add-session-to-workspace': 'Add Session to Workspace',
|
||||
'settings.shortcuts.binding.snippets': 'Open Snippets',
|
||||
'settings.shortcuts.binding.broadcast': 'Switch the Broadcast Mode',
|
||||
'settings.shortcuts.binding.toggle-side-panel': 'Toggle Side Panel',
|
||||
@@ -1330,6 +1339,8 @@ Highlight the focused split pane:
|
||||
"plugins.sidebar.selectTerminal": "Select an open terminal first.",
|
||||
"plugins.sidebar.loading": "Loading extension page…",
|
||||
"plugins.vault.loading": "Loading plugin page…",
|
||||
"plugins.vault.viewError": "The plugin page failed to render.",
|
||||
"plugins.vault.retry": "Retry",
|
||||
"plugins.interaction.title": "Plugin request",
|
||||
"plugins.interaction.openUrlTitle": "Open external link?",
|
||||
"plugins.interaction.openUrlNote": "This plugin wants to open the following HTTPS URL in your default browser:",
|
||||
@@ -1496,5 +1507,41 @@ Highlight the focused split pane:
|
||||
'plugins.hostActions.managedUnsupported': 'Managed SSH config changes require the Vault host editor.',
|
||||
'plugins.hostActions.failed': 'The request expired, was revoked, or the host changed. Select the host again.',
|
||||
'plugins.hostActions.selectionLimit': 'Select up to 50 current hosts.',
|
||||
'settings.externalEditor.title': 'External Remote Editor',
|
||||
'settings.externalEditor.desc': 'Open remote SSH projects and files directly in local editors such as Zed, VS Code, or Cursor.',
|
||||
'settings.externalEditor.preferredEditor': 'Preferred editor',
|
||||
'settings.externalEditor.preferredEditor.desc': 'Default local editor used for SFTP context menu actions and terminal open requests.',
|
||||
'settings.externalEditor.executablePath': 'Editor executable',
|
||||
'settings.externalEditor.executablePath.desc': 'Leave empty to auto-detect, or choose the local binary manually.',
|
||||
'settings.externalEditor.executablePath.placeholder': 'Auto-detect executable path',
|
||||
'settings.externalEditor.status.configured': 'Custom path',
|
||||
'settings.externalEditor.status.detected': 'Auto-detected',
|
||||
'settings.externalEditor.status.notFound': 'Not detected',
|
||||
'settings.externalEditor.browse': 'Browse…',
|
||||
'settings.externalEditor.resetPath': 'Reset to auto-detect',
|
||||
'settings.externalEditor.redetect': 'Re-detect installed editors',
|
||||
'settings.externalEditor.customArgs': 'Custom arguments',
|
||||
'settings.externalEditor.customArgs.desc': 'Space-separated arguments (placeholders: {sshUri}, {sshTarget}, {remotePath}, {encodedPath}, {kind}).',
|
||||
'settings.externalEditor.connectionMode': 'SSH connection mode',
|
||||
'settings.externalEditor.connectionMode.desc': 'Netcatty SSH Bridge reuses your active authenticated session without exposing vault keys or host lists.',
|
||||
'settings.externalEditor.connectionMode.bridge': 'Netcatty SSH Bridge (*.netcatty)',
|
||||
'settings.externalEditor.connectionMode.direct': 'Direct OpenSSH (user@host:port)',
|
||||
'settings.externalEditor.sshBridge.title': 'OpenSSH *.netcatty bridge rule',
|
||||
'settings.externalEditor.sshBridge.desc': 'Adds a single static Host *.netcatty block to your OpenSSH config without writing any hostnames, keys, or passwords.',
|
||||
'settings.externalEditor.sshBridge.install': 'Install bridge rule',
|
||||
'settings.externalEditor.sshBridge.reinstall': 'Reinstall rule',
|
||||
'settings.externalEditor.sshBridge.update': 'Update rule',
|
||||
'settings.externalEditor.sshBridge.remove': 'Remove rule',
|
||||
'settings.externalEditor.terminalRequests': 'Allow terminal open requests (OSC 7337)',
|
||||
'settings.externalEditor.terminalRequests.desc': 'Let remote shells open paths in your configured local editor via commands like `zed .`.',
|
||||
'settings.externalEditor.autoSetup': 'Enable remote editor commands for Netcatty sessions',
|
||||
'settings.externalEditor.autoSetup.desc': 'Install `zed` / `ncedit` helpers into ~/.netcatty/bin and activate them in PATH for this Netcatty terminal session only, without modifying ~/.bashrc or ~/.zshrc (can also be toggled per host).',
|
||||
'settings.externalEditor.defaultTrust': 'Default host trust',
|
||||
'settings.externalEditor.defaultTrust.desc': 'Permission policy when an unrecognized remote host requests opening a local editor.',
|
||||
'settings.externalEditor.trust.ask': 'Ask every time',
|
||||
'settings.externalEditor.trust.allow': 'Always allow',
|
||||
'settings.externalEditor.trust.deny': 'Always deny',
|
||||
'settings.externalEditor.trustedHosts.host': 'Host',
|
||||
'settings.externalEditor.trustedHosts.policy': 'Policy',
|
||||
|
||||
};
|
||||
@@ -2,6 +2,8 @@ import type { Messages } from '../types';
|
||||
|
||||
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.directory.unknown': 'Directory unknown',
|
||||
'terminal.directory.search': 'Search child directories...',
|
||||
'terminal.directory.directories': 'Directories',
|
||||
@@ -16,6 +18,7 @@ export const enTerminalMessages: Messages = {
|
||||
'terminal.directory.cmdIntegrationUnavailable': 'Waiting for a directory report from the original Command Prompt session.',
|
||||
'terminal.directory.gitBashIntegrationUnavailable': 'Waiting for an accessible directory from the original Git Bash session.',
|
||||
'terminal.directory.wslIntegrationUnavailable': 'Waiting for an idle Bash session in the selected WSL distribution.',
|
||||
'terminal.directory.cygwinIntegrationUnavailable': 'Waiting for Cygwin Bash to return to an idle prompt.',
|
||||
'terminal.directory.nonFilesystem': 'The current PowerShell location is not a filesystem directory.',
|
||||
'terminal.directory.busy': 'Wait for an empty shell prompt.',
|
||||
'terminal.directory.readFailed': 'Could not read this directory. Try refreshing.',
|
||||
@@ -469,6 +472,7 @@ export const enTerminalMessages: Messages = {
|
||||
'cloudSync.localBackups.reason.beforeRestore': 'Before restore',
|
||||
'cloudSync.localBackups.versionChange': '{from} -> {to}',
|
||||
'cloudSync.localBackups.counts': '{hosts} hosts, {keys} keys, {snippets} snippets, {notes} notes',
|
||||
'cloudSync.localBackups.aiCounts': '{sessions} AI chats, {settings} settings',
|
||||
'cloudSync.localBackups.restore': 'Restore',
|
||||
'cloudSync.localBackups.restoreSuccess': 'Local backup restored.',
|
||||
'cloudSync.localBackups.restoreFailedTitle': 'Restore failed',
|
||||
@@ -619,6 +623,10 @@ export const enTerminalMessages: Messages = {
|
||||
'keychain.export.scriptPlaceholder': 'Export script...',
|
||||
'keychain.export.missingCredentials':
|
||||
'Host has no saved password or key. Please add password credentials to the host first.',
|
||||
'keychain.export.missingPublicKey':
|
||||
'This key has no public key. Open Edit, paste the public key, then try Export and Attach again.',
|
||||
'keychain.export.missingPublicKeyNote':
|
||||
'This key has no public key. Paste it in the key editor before exporting.',
|
||||
'keychain.export.successTitle': 'Export Successful',
|
||||
'keychain.export.successMessage': 'Public key exported and attached to {host}',
|
||||
'keychain.export.failedTitle': 'Export Failed',
|
||||
@@ -695,6 +703,7 @@ export const enTerminalMessages: Messages = {
|
||||
'tabs.logPrefix': 'Log:',
|
||||
'tabs.logLocal': 'Local',
|
||||
'tabs.copyTab': 'Copy Tab',
|
||||
'tabs.addSessionToWorkspace': 'Add Session to Workspace',
|
||||
'tabs.duplicateSession': 'Duplicate Session',
|
||||
'tabs.copyTabToNewWindow': 'Copy Tab to New Window',
|
||||
'tabs.copyTabToNewWindowFailed': 'Failed to open tab in a new window',
|
||||
@@ -988,4 +997,12 @@ export const enTerminalMessages: Messages = {
|
||||
'terminal.browser.allScopeHint': 'Show in every host’s browser.',
|
||||
'terminal.browser.downloadLocation': 'Saved to your Downloads folder',
|
||||
'terminal.browser.saveAs': 'Save as…',
|
||||
'terminal.externalEditor.opened': 'Opened {path} in {editor}',
|
||||
'terminal.externalEditor.failed': 'Failed to open in {editor}',
|
||||
'terminal.externalEditor.prompt.title': 'Open in {editor}?',
|
||||
'terminal.externalEditor.prompt.desc': 'Remote host {host} requested opening this remote path in {editor}:',
|
||||
'terminal.externalEditor.prompt.deny': 'Deny',
|
||||
'terminal.externalEditor.prompt.allowOnce': 'Allow Once',
|
||||
'terminal.externalEditor.prompt.alwaysTrust': 'Always Trust Host',
|
||||
'terminal.externalEditor.autoSetupConfigured': 'Remote editor commands configured ({editor})',
|
||||
};
|
||||
@@ -1463,5 +1463,8 @@ export const enVaultMessages: Messages = {
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmDesc': 'This will permanently delete {count} recorded .webm file(s) from this device.',
|
||||
'settings.remoteDesktopRecordings.clearResult': 'Removed {count} recording file(s).',
|
||||
'settings.remoteDesktopRecordings.hint': 'Recordings are stored locally on this device and never synced to the cloud. Bookmarked logs are protected from automatic cleanup.',
|
||||
'sftp.context.openInExternalEditor': 'Open in {editor}',
|
||||
'hostDetails.externalEditorShellIntegration': 'Enable external editor commands in this session',
|
||||
'hostDetails.externalEditorShellIntegration.desc': 'Expose `zed` / `ncedit` via ~/.netcatty/bin for this Netcatty terminal session only (including tmux) without modifying ~/.bashrc or ~/.zshrc.',
|
||||
|
||||
};
|
||||
@@ -117,6 +117,9 @@ export const esAiMessages: Messages = {
|
||||
'ai.codex.appServer.available': 'App Server está disponible para esta Codex CLI.',
|
||||
'ai.codex.appServer.modelCatalogWarning': 'El catálogo de modelos de Codex en vivo no está disponible. Se usa la lista de modelos integrada.',
|
||||
'ai.codex.appServer.approval.allowSession': 'Permitir por sesión',
|
||||
'ai.planReview.title': 'Revisar el plan de implementación',
|
||||
'ai.planReview.keepPlanning': 'Seguir planificando',
|
||||
'ai.planReview.approveAndImplement': 'Aprobar e implementar',
|
||||
'ai.codex.appServer.userInput.title': 'Codex necesita tu aporte',
|
||||
'ai.codex.appServer.userInput.description': 'Responde estas preguntas para continuar el turno actual.',
|
||||
'ai.codex.appServer.userInput.other': 'Ingresa otra respuesta',
|
||||
@@ -328,6 +331,9 @@ export const esAiMessages: Messages = {
|
||||
'ai.grok.check': 'Verificar',
|
||||
'ai.grok.resetPath': 'Restablecer',
|
||||
'ai.grok.runtime.acp.title': 'Usar Grok ACP (agente stdio)',
|
||||
'ai.grok.userQuestion.title': 'Grok necesita tu respuesta',
|
||||
'ai.grok.userQuestion.description': 'Las respuestas no conceden permisos. No incluyas contraseñas ni tokens.',
|
||||
'ai.grok.userQuestion.submit': 'Enviar respuestas',
|
||||
'ai.grok.runtime.acp.default': 'Predeterminado',
|
||||
'ai.grok.runtime.acp.description':
|
||||
'Habla con Grok mediante el Protocolo de Cliente de Agente (grok agent stdio). Inyecta el MCP de Netcatty en session/new. Apágalo para usar la ruta original de CLI headless con streaming-json.',
|
||||
@@ -629,12 +635,25 @@ export const esAiMessages: Messages = {
|
||||
'ai.chat.managerRebindPick': 'Elegir terminal o espacio de trabajo…',
|
||||
'ai.chat.managerRebindHere': 'Panel actual',
|
||||
'ai.chat.managerRebindDone': 'Se movió «{title}» a {target}.',
|
||||
'ai.chat.managerToggleSelection': 'Seleccionar chats',
|
||||
'ai.chat.managerSelectAll': 'Seleccionar todo',
|
||||
'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',
|
||||
'ai.chat.managerMessagesCount': '{n} mensajes',
|
||||
'ai.chat.managerDeleteTitle': '¿Eliminar este chat?',
|
||||
'ai.chat.managerDeleteMessage': '«{title}» y sus mensajes se eliminarán de todos los paneles. Esta acción no se puede deshacer.',
|
||||
'ai.chat.managerBulkDeleteTitle': '¿Eliminar {n} chats?',
|
||||
'ai.chat.managerBulkDeleteMessage': 'Los {n} chats seleccionados y sus mensajes se eliminarán de todos los paneles. Esta acción no se puede deshacer.',
|
||||
'ai.chat.justNow': 'Ahora mismo',
|
||||
'ai.chat.minutesAgo': 'hace {n} min',
|
||||
'ai.chat.hoursAgo': 'hace {n} h',
|
||||
@@ -685,9 +704,25 @@ 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',
|
||||
'ai.chatHistory.autoLlmTitle': 'Generar títulos automáticamente',
|
||||
'ai.chatHistory.autoLlmTitle.description': 'Usa una breve llamada LLM para crear un título corto tras el primer mensaje. Si no está disponible, usa la primera línea. Ajuste solo local.',
|
||||
'ai.chatHistory.titleModel': 'Modelo de título',
|
||||
'ai.chatHistory.titleModel.description': 'Proveedor y modelo usados para generar títulos. Elige un modelo pequeño y económico. Por defecto usa el modelo actual de Catty.',
|
||||
'ai.chatHistory.titleModel.none': 'No hay proveedores habilitados.',
|
||||
'ai.chatHistory.titleModel.useCurrentCatty': 'Usar el modelo actual de Catty',
|
||||
'ai.chatHistory.titleModel.unavailable': 'No disponible',
|
||||
'ai.chatHistory.titleModel.providerPlaceholder': 'Seleccionar proveedor',
|
||||
'ai.chatHistory.titleModel.modelPlaceholder': 'Seleccionar modelo',
|
||||
|
||||
// AI Error
|
||||
'ai.codex.bridgeError': 'Los controladores del proceso principal de Codex aún no están cargados. Reinicia Netcatty por completo o reinicia el proceso de desarrollo de Electron y vuelve a intentarlo.',
|
||||
|
||||
@@ -431,6 +431,8 @@ export const esCoreMessages: Messages = {
|
||||
'settings.vault.showSftpTab': 'Mostrar pestaña SFTP',
|
||||
'settings.vault.showSftpTabDesc': 'Muestra la vista SFTP independiente en la barra de pestañas superior. Cuando está oculta, usa el panel lateral SFTP dentro de la sesión.',
|
||||
'settings.vault.showHostTreeSidebar': 'Mostrar barra lateral de lista de hosts',
|
||||
'settings.vault.removeTopTabsDragArea': 'Quitar el área superior para arrastrar la ventana',
|
||||
'settings.vault.removeTopTabsDragAreaDesc': 'Al activarla, quita el espacio de arrastre sobre las pestañas para poder hacer clic en el borde superior.',
|
||||
'settings.vault.showHostTreeSidebarDesc': 'Muestra la barra lateral de lista de hosts y su alternador en la barra superior en las pestañas de terminal y editor.',
|
||||
'settings.vault.autoImportSystemKnownHosts': 'Importar automáticamente known_hosts del sistema',
|
||||
'settings.vault.autoImportSystemKnownHostsDesc': 'Cuando se carga el Vault, importa en silencio las entradas del archivo known_hosts de OpenSSH. Desactívalo para mantener los hosts conocidos de Netcatty separados; Escanear sistema sigue importando a pedido.',
|
||||
@@ -999,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',
|
||||
@@ -1027,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',
|
||||
@@ -1062,6 +1070,7 @@ Resalta el panel dividido enfocado:
|
||||
'settings.shortcuts.binding.command-palette': 'Abrir paleta de comandos',
|
||||
'settings.shortcuts.binding.quick-switch': 'Cambio rápido',
|
||||
'settings.shortcuts.binding.new-workspace': 'Nuevo espacio de trabajo',
|
||||
'settings.shortcuts.binding.add-session-to-workspace': 'Añadir sesión al espacio de trabajo',
|
||||
'settings.shortcuts.binding.snippets': 'Abrir fragmentos',
|
||||
'settings.shortcuts.binding.broadcast': 'Alternar modo de transmisión',
|
||||
'settings.shortcuts.binding.toggle-opacity': 'Alternar la transparencia de la ventana',
|
||||
@@ -1330,6 +1339,8 @@ Resalta el panel dividido enfocado:
|
||||
"plugins.sidebar.selectTerminal": "Selecciona primero un terminal abierto.",
|
||||
"plugins.sidebar.loading": "Cargando página de extensión…",
|
||||
"plugins.vault.loading": "Cargando página del plugin…",
|
||||
"plugins.vault.viewError": "No se pudo renderizar la página del plugin.",
|
||||
"plugins.vault.retry": "Reintentar",
|
||||
"plugins.interaction.title": "Solicitud de complemento",
|
||||
"plugins.interaction.openUrlTitle": "¿Abrir enlace externo?",
|
||||
"plugins.interaction.openUrlNote": "Este complemento solicita abrir la siguiente URL HTTPS en tu navegador predeterminado:",
|
||||
@@ -1496,5 +1507,41 @@ Resalta el panel dividido enfocado:
|
||||
'plugins.hostActions.managedUnsupported': 'Los cambios de configuración SSH administrada requieren el editor de equipos de Vault.',
|
||||
'plugins.hostActions.failed': 'La solicitud caducó, se revocó o el equipo cambió. Selecciona el equipo de nuevo.',
|
||||
'plugins.hostActions.selectionLimit': 'Selecciona hasta 50 equipos actuales.',
|
||||
'settings.externalEditor.title': 'Editor remoto externo',
|
||||
'settings.externalEditor.desc': 'Abre proyectos y archivos SSH remotos directamente en editores locales como Zed, VS Code o Cursor.',
|
||||
'settings.externalEditor.preferredEditor': 'Editor preferido',
|
||||
'settings.externalEditor.preferredEditor.desc': 'Editor local predeterminado para el menú contextual de SFTP y las solicitudes desde el terminal.',
|
||||
'settings.externalEditor.executablePath': 'Ejecutable del editor',
|
||||
'settings.externalEditor.executablePath.desc': 'Déjalo vacío para detectarlo automáticamente o elige el binario local manualmente.',
|
||||
'settings.externalEditor.executablePath.placeholder': 'Detectar ruta del ejecutable automáticamente',
|
||||
'settings.externalEditor.status.configured': 'Ruta personalizada',
|
||||
'settings.externalEditor.status.detected': 'Detectado automáticamente',
|
||||
'settings.externalEditor.status.notFound': 'No detectado',
|
||||
'settings.externalEditor.browse': 'Examinar…',
|
||||
'settings.externalEditor.resetPath': 'Restablecer a detección automática',
|
||||
'settings.externalEditor.redetect': 'Volver a detectar editores instalados',
|
||||
'settings.externalEditor.customArgs': 'Argumentos personalizados',
|
||||
'settings.externalEditor.customArgs.desc': 'Argumentos separados por espacios (marcadores: {sshUri}, {sshTarget}, {remotePath}, {encodedPath}, {kind}).',
|
||||
'settings.externalEditor.connectionMode': 'Modo de conexión SSH',
|
||||
'settings.externalEditor.connectionMode.desc': 'El puente SSH de Netcatty reutiliza tu sesión autenticada activa sin exponer claves ni listas de equipos.',
|
||||
'settings.externalEditor.connectionMode.bridge': 'Puente SSH de Netcatty (*.netcatty)',
|
||||
'settings.externalEditor.connectionMode.direct': 'OpenSSH directo (usuario@host:puerto)',
|
||||
'settings.externalEditor.sshBridge.title': 'Regla OpenSSH *.netcatty',
|
||||
'settings.externalEditor.sshBridge.desc': 'Añade un único bloque estático Host *.netcatty a tu configuración de OpenSSH sin escribir nombres de equipo, claves ni contraseñas.',
|
||||
'settings.externalEditor.sshBridge.install': 'Instalar regla',
|
||||
'settings.externalEditor.sshBridge.reinstall': 'Reinstalar regla',
|
||||
'settings.externalEditor.sshBridge.update': 'Actualizar regla',
|
||||
'settings.externalEditor.sshBridge.remove': 'Eliminar regla',
|
||||
'settings.externalEditor.terminalRequests': 'Permitir solicitudes desde el terminal (OSC 7337)',
|
||||
'settings.externalEditor.terminalRequests.desc': 'Permite que las shells remotas abran rutas en tu editor local configurado mediante comandos como `zed .`.',
|
||||
'settings.externalEditor.autoSetup': 'Habilitar comandos de editor remoto en sesiones de Netcatty',
|
||||
'settings.externalEditor.autoSetup.desc': 'Instala helpers `zed` / `ncedit` en ~/.netcatty/bin y los activa en el PATH solo para esta sesión de Netcatty, sin modificar ~/.bashrc ni ~/.zshrc (también configurable por equipo).',
|
||||
'settings.externalEditor.defaultTrust': 'Confianza predeterminada del equipo',
|
||||
'settings.externalEditor.defaultTrust.desc': 'Política de permisos cuando un equipo remoto no reconocido solicita abrir un editor local.',
|
||||
'settings.externalEditor.trust.ask': 'Preguntar siempre',
|
||||
'settings.externalEditor.trust.allow': 'Permitir siempre',
|
||||
'settings.externalEditor.trust.deny': 'Denegar siempre',
|
||||
'settings.externalEditor.trustedHosts.host': 'Equipo',
|
||||
'settings.externalEditor.trustedHosts.policy': 'Política',
|
||||
|
||||
};
|
||||
@@ -2,6 +2,8 @@ import type { Messages } from '../types';
|
||||
|
||||
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.directory.unknown': 'Directorio desconocido',
|
||||
'terminal.directory.search': 'Buscar subdirectorios...',
|
||||
'terminal.directory.directories': 'Directorios',
|
||||
@@ -16,6 +18,7 @@ export const esTerminalMessages: Messages = {
|
||||
'terminal.directory.cmdIntegrationUnavailable': 'Esperando el directorio de la sesión original del símbolo del sistema.',
|
||||
'terminal.directory.gitBashIntegrationUnavailable': 'Esperando un directorio accesible de la sesión original de Git Bash.',
|
||||
'terminal.directory.wslIntegrationUnavailable': 'Esperando una sesión de Bash inactiva en la distribución WSL seleccionada.',
|
||||
'terminal.directory.cygwinIntegrationUnavailable': 'Esperando que Bash de Cygwin vuelva a un indicador inactivo.',
|
||||
'terminal.directory.nonFilesystem': 'La ubicación actual de PowerShell no es un directorio del sistema de archivos.',
|
||||
'terminal.directory.accessDenied': 'Permiso denegado al listar este directorio.',
|
||||
'terminal.directory.busy': 'Espera a que el prompt esté vacío.',
|
||||
@@ -469,6 +472,7 @@ export const esTerminalMessages: Messages = {
|
||||
'cloudSync.localBackups.reason.beforeRestore': 'Antes de la restauración',
|
||||
'cloudSync.localBackups.versionChange': '{from} -> {to}',
|
||||
'cloudSync.localBackups.counts': '{hosts} hosts, {keys} claves, {snippets} snippets, {notes} notas',
|
||||
'cloudSync.localBackups.aiCounts': '{sessions} chats de IA, {settings} ajustes',
|
||||
'cloudSync.localBackups.restore': 'Restaurar',
|
||||
'cloudSync.localBackups.restoreSuccess': 'Copia de seguridad local restaurada.',
|
||||
'cloudSync.localBackups.restoreFailedTitle': 'Falló la restauración',
|
||||
@@ -619,6 +623,10 @@ export const esTerminalMessages: Messages = {
|
||||
'keychain.export.scriptPlaceholder': 'Script de exportación...',
|
||||
'keychain.export.missingCredentials':
|
||||
'El host no tiene contraseña ni clave guardadas. Primero agrega credenciales de contraseña al host.',
|
||||
'keychain.export.missingPublicKey':
|
||||
'Esta clave no tiene clave pública. Ábrela en Editar, pega la clave pública y vuelve a intentar Exportar y adjuntar.',
|
||||
'keychain.export.missingPublicKeyNote':
|
||||
'Esta clave no tiene clave pública. Pégala en el editor de claves antes de exportar.',
|
||||
'keychain.export.successTitle': 'Exportación exitosa',
|
||||
'keychain.export.successMessage': 'Clave pública exportada y adjuntada a {host}',
|
||||
'keychain.export.failedTitle': 'Falló la exportación',
|
||||
@@ -697,6 +705,7 @@ export const esTerminalMessages: Messages = {
|
||||
'tabs.logPrefix': 'Registro:',
|
||||
'tabs.logLocal': 'Local',
|
||||
'tabs.copyTab': 'Copiar pestaña',
|
||||
'tabs.addSessionToWorkspace': 'Añadir sesión al espacio de trabajo',
|
||||
'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',
|
||||
@@ -990,4 +999,12 @@ export const esTerminalMessages: Messages = {
|
||||
'terminal.browser.allScopeHint': 'Mostrar en el navegador de todos los hosts.',
|
||||
'terminal.browser.downloadLocation': 'Guardado en la carpeta Descargas',
|
||||
'terminal.browser.saveAs': 'Guardar como…',
|
||||
'terminal.externalEditor.opened': 'Se abrió {path} en {editor}',
|
||||
'terminal.externalEditor.failed': 'No se pudo abrir en {editor}',
|
||||
'terminal.externalEditor.prompt.title': '¿Abrir en {editor}?',
|
||||
'terminal.externalEditor.prompt.desc': 'El equipo remoto {host} solicitó abrir esta ruta remota en {editor}:',
|
||||
'terminal.externalEditor.prompt.deny': 'Denegar',
|
||||
'terminal.externalEditor.prompt.allowOnce': 'Permitir una vez',
|
||||
'terminal.externalEditor.prompt.alwaysTrust': 'Confiar siempre en este equipo',
|
||||
'terminal.externalEditor.autoSetupConfigured': 'Comandos de editor remoto configurados ({editor})',
|
||||
};
|
||||
@@ -1463,5 +1463,8 @@ export const esVaultMessages: Messages = {
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmDesc': 'Se eliminarán permanentemente {count} archivo(s) .webm grabados en este dispositivo.',
|
||||
'settings.remoteDesktopRecordings.clearResult': 'Se eliminaron {count} archivo(s) de grabación.',
|
||||
'settings.remoteDesktopRecordings.hint': 'Las grabaciones se guardan solo localmente en este dispositivo y nunca se sincronizan en la nube. Los registros guardados están protegidos frente a la limpieza automática.',
|
||||
'sftp.context.openInExternalEditor': 'Abrir en {editor}',
|
||||
'hostDetails.externalEditorShellIntegration': 'Habilitar comandos de editor externo en esta sesión',
|
||||
'hostDetails.externalEditorShellIntegration.desc': 'Activa `zed` / `ncedit` desde ~/.netcatty/bin solo para esta sesión de terminal de Netcatty (incluido tmux), sin modificar ~/.bashrc ni ~/.zshrc.',
|
||||
|
||||
};
|
||||
@@ -228,3 +228,25 @@ test("AI tool output limit settings copy is localized across all five locales",
|
||||
assert.match(zhTW["ai.safety.toolOutputMaxChars.description"], /傳回/);
|
||||
assert.equal(zhTW["ai.safety.toolOutputMaxChars.description"].includes("返回"), false);
|
||||
});
|
||||
|
||||
test("LLM chat title settings copy is localized across all five locales", () => {
|
||||
const keys = [
|
||||
"ai.chatHistory.autoLlmTitle",
|
||||
"ai.chatHistory.autoLlmTitle.description",
|
||||
"ai.chatHistory.titleModel",
|
||||
"ai.chatHistory.titleModel.description",
|
||||
"ai.chatHistory.titleModel.none",
|
||||
"ai.chatHistory.titleModel.useCurrentCatty",
|
||||
"ai.chatHistory.titleModel.unavailable",
|
||||
"ai.chatHistory.titleModel.providerPlaceholder",
|
||||
"ai.chatHistory.titleModel.modelPlaceholder",
|
||||
] as const;
|
||||
for (const [locale, messages] of Object.entries(ALL_LOCALES)) {
|
||||
for (const key of keys) {
|
||||
assert.ok(messages[key]?.trim(), `${locale}: missing ${key}`);
|
||||
if (locale !== "en") {
|
||||
assert.notEqual(messages[key], en[key], `${locale}: ${key} should be translated`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -117,6 +117,9 @@ export const ruAiMessages: Messages = {
|
||||
'ai.codex.appServer.available': 'Эта версия Codex CLI поддерживает App Server.',
|
||||
'ai.codex.appServer.modelCatalogWarning': 'Динамический каталог моделей Codex недоступен. Используется встроенный список моделей.',
|
||||
'ai.codex.appServer.approval.allowSession': 'Разрешить для сеанса',
|
||||
'ai.planReview.title': 'Проверить план реализации',
|
||||
'ai.planReview.keepPlanning': 'Продолжить планирование',
|
||||
'ai.planReview.approveAndImplement': 'Одобрить и приступить к реализации',
|
||||
'ai.codex.appServer.userInput.title': 'Codex требуется ваш ответ',
|
||||
'ai.codex.appServer.userInput.description': 'Ответьте на вопросы, чтобы продолжить текущую задачу.',
|
||||
'ai.codex.appServer.userInput.other': 'Введите другой ответ',
|
||||
@@ -296,6 +299,9 @@ export const ruAiMessages: Messages = {
|
||||
'ai.grok.check': 'Проверить',
|
||||
'ai.grok.resetPath': 'Сбросить',
|
||||
'ai.grok.runtime.acp.title': 'Использовать Grok ACP (agent stdio)',
|
||||
'ai.grok.userQuestion.title': 'Grok ждёт вашего ответа',
|
||||
'ai.grok.userQuestion.description': 'Ответы не предоставляют разрешений. Не указывайте пароли и токены.',
|
||||
'ai.grok.userQuestion.submit': 'Отправить ответы',
|
||||
'ai.grok.runtime.acp.default': 'По умолчанию',
|
||||
'ai.grok.runtime.acp.description':
|
||||
'Подключение к Grok через Agent Client Protocol (grok agent stdio). Netcatty MCP внедряется в session/new. Выключите, чтобы использовать исходный headless streaming-json CLI.',
|
||||
@@ -628,12 +634,25 @@ export const ruAiMessages: Messages = {
|
||||
'ai.chat.managerRebindPick': 'Выберите терминал или рабочее пространство…',
|
||||
'ai.chat.managerRebindHere': 'Текущая панель',
|
||||
'ai.chat.managerRebindDone': 'Чат «{title}» перемещён в {target}.',
|
||||
'ai.chat.managerToggleSelection': 'Выбрать чаты',
|
||||
'ai.chat.managerSelectAll': 'Выбрать все',
|
||||
'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': 'Простой',
|
||||
'ai.chat.managerMessagesCount': '{n} сообщений',
|
||||
'ai.chat.managerDeleteTitle': 'Удалить этот чат?',
|
||||
'ai.chat.managerDeleteMessage': '«{title}» и его сообщения будут удалены из всех панелей. Это действие нельзя отменить.',
|
||||
'ai.chat.managerBulkDeleteTitle': 'Удалить выбранные чаты ({n})?',
|
||||
'ai.chat.managerBulkDeleteMessage': 'Выбранные чаты ({n}) и их сообщения будут удалены из всех панелей. Это действие нельзя отменить.',
|
||||
'ai.chat.justNow': 'Только что',
|
||||
'ai.chat.minutesAgo': '{n}м назад',
|
||||
'ai.chat.hoursAgo': '{n}ч назад',
|
||||
@@ -684,9 +703,25 @@ 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': 'сообщений',
|
||||
'ai.chatHistory.autoLlmTitle': 'Автосоздание заголовков чатов',
|
||||
'ai.chatHistory.autoLlmTitle.description': 'Короткий запрос к LLM создаёт заголовок после первого сообщения. Если недоступно, используется первая строка. Локальная настройка.',
|
||||
'ai.chatHistory.titleModel': 'Модель для заголовков',
|
||||
'ai.chatHistory.titleModel.description': 'Провайдер и модель для создания заголовков. Выберите небольшую недорогую модель. По умолчанию — текущая модель Catty.',
|
||||
'ai.chatHistory.titleModel.none': 'Нет включённых провайдеров.',
|
||||
'ai.chatHistory.titleModel.useCurrentCatty': 'Использовать текущую модель Catty',
|
||||
'ai.chatHistory.titleModel.unavailable': 'Недоступно',
|
||||
'ai.chatHistory.titleModel.providerPlaceholder': 'Выбрать провайдер',
|
||||
'ai.chatHistory.titleModel.modelPlaceholder': 'Выбрать модель',
|
||||
|
||||
// AI Error
|
||||
'ai.codex.bridgeError': 'Обработчики главного процесса Codex ещё не загружены. Полностью перезапустите Netcatty или dev-процесс Electron и попробуйте снова.',
|
||||
|
||||
@@ -430,6 +430,8 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.vault.showSftpTab': 'Показывать вкладку SFTP',
|
||||
'settings.vault.showSftpTabDesc': 'Показывать отдельный SFTP-вид в верхней панели вкладок. Если скрыто, используйте боковую панель SFTP внутри сессии.',
|
||||
'settings.vault.showHostTreeSidebar': 'Показывать боковую панель хостов',
|
||||
'settings.vault.removeTopTabsDragArea': 'Убрать верхнюю область перетаскивания окна',
|
||||
'settings.vault.removeTopTabsDragAreaDesc': 'При включении удаляется область перетаскивания над вкладками, чтобы по верхнему краю можно было нажимать.',
|
||||
'settings.vault.showHostTreeSidebarDesc': 'Показывать список хостов и кнопку в верхней панели для вкладок терминала и редактора.',
|
||||
'settings.vault.autoImportSystemKnownHosts': 'Автоимпорт системного known_hosts',
|
||||
'settings.vault.autoImportSystemKnownHostsDesc': 'При открытии хранилища тихо импортировать записи из OpenSSH known_hosts. Отключите, чтобы держать известные хосты Netcatty отдельно; кнопка «Сканировать систему» по-прежнему импортирует вручную.',
|
||||
@@ -984,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': 'Подсказки пароля',
|
||||
@@ -1012,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': 'Навигация',
|
||||
@@ -1046,6 +1054,7 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.shortcuts.binding.command-palette': 'Открыть палитру команд',
|
||||
'settings.shortcuts.binding.quick-switch': 'Быстрое переключение',
|
||||
'settings.shortcuts.binding.new-workspace': 'Новая рабочая область',
|
||||
'settings.shortcuts.binding.add-session-to-workspace': 'Добавить сессию в рабочую область',
|
||||
'settings.shortcuts.binding.snippets': 'Открыть сниппеты',
|
||||
'settings.shortcuts.binding.broadcast': 'Переключить режим трансляции',
|
||||
'settings.shortcuts.binding.toggle-opacity': 'Переключить прозрачность окна',
|
||||
@@ -1271,6 +1280,8 @@ export const ruCoreMessages: Messages = {
|
||||
"plugins.sidebar.selectTerminal": "Сначала выберите открытый терминал.",
|
||||
"plugins.sidebar.loading": "Загрузка страницы расширения…",
|
||||
"plugins.vault.loading": "Загрузка страницы плагина…",
|
||||
"plugins.vault.viewError": "Не удалось отобразить страницу плагина.",
|
||||
"plugins.vault.retry": "Повторить",
|
||||
"plugins.interaction.title": "Запрос плагина",
|
||||
"plugins.interaction.openUrlTitle": "Открыть внешнюю ссылку?",
|
||||
"plugins.interaction.openUrlNote": "Этот плагин запрашивает открытие следующего HTTPS-адреса в браузере по умолчанию:",
|
||||
@@ -1437,4 +1448,40 @@ export const ruCoreMessages: Messages = {
|
||||
'plugins.hostActions.managedUnsupported': 'Изменяйте управляемые настройки SSH в редакторе хостов Vault.',
|
||||
'plugins.hostActions.failed': 'Запрос истёк, был отозван или хост изменился. Выберите хост заново.',
|
||||
'plugins.hostActions.selectionLimit': 'Выберите не более 50 текущих хостов.',
|
||||
'settings.externalEditor.title': 'Внешний удалённый редактор',
|
||||
'settings.externalEditor.desc': 'Открывайте удалённые SSH-проекты и файлы напрямую в локальных редакторах, таких как Zed, VS Code или Cursor.',
|
||||
'settings.externalEditor.preferredEditor': 'Предпочитаемый редактор',
|
||||
'settings.externalEditor.preferredEditor.desc': 'Локальный редактор по умолчанию для контекстного меню SFTP и запросов из терминала.',
|
||||
'settings.externalEditor.executablePath': 'Исполняемый файл редактора',
|
||||
'settings.externalEditor.executablePath.desc': 'Оставьте пустым для автоопределения или выберите локальный файл вручную.',
|
||||
'settings.externalEditor.executablePath.placeholder': 'Автоопределение пути к файлу',
|
||||
'settings.externalEditor.status.configured': 'Указан вручную',
|
||||
'settings.externalEditor.status.detected': 'Определён автоматически',
|
||||
'settings.externalEditor.status.notFound': 'Не найден',
|
||||
'settings.externalEditor.browse': 'Обзор…',
|
||||
'settings.externalEditor.resetPath': 'Сбросить на автоопределение',
|
||||
'settings.externalEditor.redetect': 'Повторить поиск редакторов',
|
||||
'settings.externalEditor.customArgs': 'Пользовательские аргументы',
|
||||
'settings.externalEditor.customArgs.desc': 'Аргументы через пробел (подстановки: {sshUri}, {sshTarget}, {remotePath}, {encodedPath}, {kind}).',
|
||||
'settings.externalEditor.connectionMode': 'Режим SSH-подключения',
|
||||
'settings.externalEditor.connectionMode.desc': 'SSH-мост Netcatty переиспользует активную аутентифицированную сессию без раскрытия ключей или списка хостов.',
|
||||
'settings.externalEditor.connectionMode.bridge': 'SSH-мост Netcatty (*.netcatty)',
|
||||
'settings.externalEditor.connectionMode.direct': 'Прямой OpenSSH (user@host:port)',
|
||||
'settings.externalEditor.sshBridge.title': 'Правило OpenSSH *.netcatty',
|
||||
'settings.externalEditor.sshBridge.desc': 'Добавляет один статический блок Host *.netcatty в конфиг OpenSSH без записи хостов, ключей и паролей.',
|
||||
'settings.externalEditor.sshBridge.install': 'Установить правило',
|
||||
'settings.externalEditor.sshBridge.reinstall': 'Переустановить правило',
|
||||
'settings.externalEditor.sshBridge.update': 'Обновить правило',
|
||||
'settings.externalEditor.sshBridge.remove': 'Удалить правило',
|
||||
'settings.externalEditor.terminalRequests': 'Разрешить запросы из терминала (OSC 7337)',
|
||||
'settings.externalEditor.terminalRequests.desc': 'Позволяет удалённой оболочке открывать пути в локальном редакторе командами вроде `zed .`.',
|
||||
'settings.externalEditor.autoSetup': 'Включить команды редактора только в сессиях Netcatty',
|
||||
'settings.externalEditor.autoSetup.desc': 'Устанавливает утилиты `zed` / `ncedit` в ~/.netcatty/bin и добавляет их в PATH только для этой сессии Netcatty, не изменяя ~/.bashrc и ~/.zshrc (можно задать отдельно для хоста).',
|
||||
'settings.externalEditor.defaultTrust': 'Доверие хостам по умолчанию',
|
||||
'settings.externalEditor.defaultTrust.desc': 'Политика разрешений, когда неизвестный удалённый хост запрашивает открытие локального редактора.',
|
||||
'settings.externalEditor.trust.ask': 'Спрашивать каждый раз',
|
||||
'settings.externalEditor.trust.allow': 'Всегда разрешать',
|
||||
'settings.externalEditor.trust.deny': 'Всегда запрещать',
|
||||
'settings.externalEditor.trustedHosts.host': 'Хост',
|
||||
'settings.externalEditor.trustedHosts.policy': 'Политика',
|
||||
};
|
||||
@@ -2,6 +2,8 @@ import type { Messages } from '../types';
|
||||
|
||||
export const ruTerminalMessages: Messages = {
|
||||
'terminal.directory.open': 'Текущий каталог: {path}. Сменить каталог',
|
||||
'terminal.gitBranch.current': 'Ветка Git: {{value}}',
|
||||
'terminal.gitBranch.detached': 'Отсоединённый HEAD: {{value}}',
|
||||
'terminal.directory.unknown': 'Каталог неизвестен',
|
||||
'terminal.directory.search': 'Поиск подкаталогов...',
|
||||
'terminal.directory.directories': 'Каталоги',
|
||||
@@ -16,6 +18,7 @@ export const ruTerminalMessages: Messages = {
|
||||
'terminal.directory.cmdIntegrationUnavailable': 'Ожидание данных о каталоге от исходного сеанса командной строки.',
|
||||
'terminal.directory.gitBashIntegrationUnavailable': 'Ожидание доступного каталога исходного сеанса Git Bash.',
|
||||
'terminal.directory.wslIntegrationUnavailable': 'Ожидание готовности Bash в выбранном дистрибутиве WSL.',
|
||||
'terminal.directory.cygwinIntegrationUnavailable': 'Ожидание готовности Bash в Cygwin.',
|
||||
'terminal.directory.nonFilesystem': 'Текущее расположение PowerShell не является каталогом файловой системы.',
|
||||
'terminal.directory.accessDenied': 'Нет разрешения на просмотр содержимого этого каталога.',
|
||||
'terminal.directory.busy': 'Дождитесь пустой командной строки.',
|
||||
@@ -489,6 +492,7 @@ export const ruTerminalMessages: Messages = {
|
||||
'cloudSync.localBackups.reason.beforeRestore': 'Перед восстановлением',
|
||||
'cloudSync.localBackups.versionChange': '{from} -> {to}',
|
||||
'cloudSync.localBackups.counts': '{hosts} хостов, {keys} ключей, {snippets} сниппетов, {notes} заметок',
|
||||
'cloudSync.localBackups.aiCounts': '{sessions} чатов ИИ, {settings} настроек',
|
||||
'cloudSync.localBackups.restore': 'Восстановить',
|
||||
'cloudSync.localBackups.restoreSuccess': 'Локальная резервная копия восстановлена.',
|
||||
'cloudSync.localBackups.restoreFailedTitle': 'Ошибка восстановления',
|
||||
@@ -636,6 +640,8 @@ export const ruTerminalMessages: Messages = {
|
||||
'keychain.export.script': 'Скрипт *',
|
||||
'keychain.export.scriptPlaceholder': 'Скрипт экспорта...',
|
||||
'keychain.export.missingCredentials': 'У хоста нет сохранённого пароля или ключа. Сначала добавьте в хост учётные данные с паролем.',
|
||||
'keychain.export.missingPublicKey': 'У этого ключа нет публичного ключа. Откройте «Редактировать», вставьте публичный ключ и снова нажмите «Экспортировать и привязать».',
|
||||
'keychain.export.missingPublicKeyNote': 'У этого ключа нет публичного ключа. Вставьте его в редакторе ключа перед экспортом.',
|
||||
'keychain.export.successTitle': 'Экспорт выполнен успешно',
|
||||
'keychain.export.successMessage': 'Публичный ключ экспортирован и привязан к {host}',
|
||||
'keychain.export.failedTitle': 'Ошибка экспорта',
|
||||
@@ -712,6 +718,7 @@ export const ruTerminalMessages: Messages = {
|
||||
'tabs.logPrefix': 'Журнал:',
|
||||
'tabs.logLocal': 'Локальный',
|
||||
'tabs.copyTab': 'Копировать вкладку',
|
||||
'tabs.addSessionToWorkspace': 'Добавить сессию в эту рабочую область',
|
||||
'tabs.duplicateSession': 'Дублировать сессию',
|
||||
'tabs.copyTabToNewWindow': 'Копировать вкладку в новое окно',
|
||||
'tabs.copyTabToNewWindowFailed': 'Не удалось открыть вкладку в новом окне',
|
||||
@@ -1004,4 +1011,12 @@ export const ruTerminalMessages: Messages = {
|
||||
'terminal.browser.allScopeHint': 'В браузерах всех хостов.',
|
||||
'terminal.browser.downloadLocation': 'Файлы сохраняются в папку «Загрузки»',
|
||||
'terminal.browser.saveAs': 'Сохранить как…',
|
||||
'terminal.externalEditor.opened': 'Открыто {path} в {editor}',
|
||||
'terminal.externalEditor.failed': 'Не удалось открыть в {editor}',
|
||||
'terminal.externalEditor.prompt.title': 'Открыть в {editor}?',
|
||||
'terminal.externalEditor.prompt.desc': 'Удалённый хост {host} запросил открытие этого пути в {editor}:',
|
||||
'terminal.externalEditor.prompt.deny': 'Отклонить',
|
||||
'terminal.externalEditor.prompt.allowOnce': 'Разрешить один раз',
|
||||
'terminal.externalEditor.prompt.alwaysTrust': 'Всегда доверять хосту',
|
||||
'terminal.externalEditor.autoSetupConfigured': 'Команды удалённого редактора настроены ({editor})',
|
||||
};
|
||||
@@ -1482,5 +1482,8 @@ export const ruVaultMessages: Messages = {
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmDesc': 'С этого устройства будут безвозвратно удалены файлы .webm ({count}).',
|
||||
'settings.remoteDesktopRecordings.clearResult': 'Удалено файлов записей: {count}.',
|
||||
'settings.remoteDesktopRecordings.hint': 'Записи хранятся только локально на этом устройстве и не синхронизируются с облаком. Закреплённые журналы защищены от автоматической очистки.',
|
||||
'sftp.context.openInExternalEditor': 'Открыть в {editor}',
|
||||
'hostDetails.externalEditorShellIntegration': 'Включить команды внешнего редактора в этой сессии',
|
||||
'hostDetails.externalEditorShellIntegration.desc': 'Добавляет `zed` / `ncedit` из ~/.netcatty/bin в PATH только для этой сессии терминала Netcatty (включая tmux), не изменяя ~/.bashrc и ~/.zshrc.',
|
||||
|
||||
};
|
||||
@@ -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`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -117,6 +117,9 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.codex.appServer.available': '当前 Codex CLI 支持 App Server。',
|
||||
'ai.codex.appServer.modelCatalogWarning': 'Codex 动态模型目录暂不可用,当前将使用内置模型列表。',
|
||||
'ai.codex.appServer.approval.allowSession': '本会话允许',
|
||||
'ai.planReview.title': '审核实施方案',
|
||||
'ai.planReview.keepPlanning': '继续规划',
|
||||
'ai.planReview.approveAndImplement': '批准并实施',
|
||||
'ai.codex.appServer.userInput.title': 'Codex 需要你的输入',
|
||||
'ai.codex.appServer.userInput.description': '回答以下问题以继续当前任务。',
|
||||
'ai.codex.appServer.userInput.other': '输入其他答案',
|
||||
@@ -328,6 +331,9 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.grok.check': '检查',
|
||||
'ai.grok.resetPath': '重置',
|
||||
'ai.grok.runtime.acp.title': '使用 Grok ACP(agent stdio)',
|
||||
'ai.grok.userQuestion.title': 'Grok 正在等待你的回答',
|
||||
'ai.grok.userQuestion.description': '回答不会改变权限。请勿填写密码或令牌。',
|
||||
'ai.grok.userQuestion.submit': '发送回答',
|
||||
'ai.grok.runtime.acp.default': '默认',
|
||||
'ai.grok.runtime.acp.description':
|
||||
'通过 Agent Client Protocol(grok agent stdio)接入 Grok。在 session/new 注入 Netcatty MCP。关闭后使用原始 headless streaming-json CLI 路径。',
|
||||
@@ -629,12 +635,25 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.chat.managerRebindPick': '选择目标终端或工作区…',
|
||||
'ai.chat.managerRebindHere': '当前面板',
|
||||
'ai.chat.managerRebindDone': '已将“{title}”移动到 {target}。',
|
||||
'ai.chat.managerToggleSelection': '选择会话',
|
||||
'ai.chat.managerSelectAll': '全选',
|
||||
'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': '空闲',
|
||||
'ai.chat.managerMessagesCount': '{n} 条消息',
|
||||
'ai.chat.managerDeleteTitle': '删除此会话?',
|
||||
'ai.chat.managerDeleteMessage': '“{title}”及其消息将从所有面板中移除,且无法撤销。',
|
||||
'ai.chat.managerBulkDeleteTitle': '删除选中的 {n} 个会话?',
|
||||
'ai.chat.managerBulkDeleteMessage': '选中的 {n} 个会话及其消息将从所有面板中移除,且无法撤销。',
|
||||
'ai.chat.justNow': '刚刚',
|
||||
'ai.chat.minutesAgo': '{n}分钟前',
|
||||
'ai.chat.hoursAgo': '{n}小时前',
|
||||
@@ -685,9 +704,25 @@ 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': '条消息',
|
||||
'ai.chatHistory.autoLlmTitle': '自动生成会话标题',
|
||||
'ai.chatHistory.autoLlmTitle.description': '首条消息后用一次轻量 LLM 调用生成简短标题;不可用时回退为首句。仅本机生效。',
|
||||
'ai.chatHistory.titleModel': '标题模型',
|
||||
'ai.chatHistory.titleModel.description': '用于生成会话标题的 provider 和模型,建议选小巧便宜的模型。默认使用当前 Catty 模型。',
|
||||
'ai.chatHistory.titleModel.none': '没有可用的 provider。',
|
||||
'ai.chatHistory.titleModel.useCurrentCatty': '使用当前 Catty 模型',
|
||||
'ai.chatHistory.titleModel.unavailable': '不可用',
|
||||
'ai.chatHistory.titleModel.providerPlaceholder': '选择 provider',
|
||||
'ai.chatHistory.titleModel.modelPlaceholder': '选择模型',
|
||||
|
||||
// AI Error
|
||||
'ai.codex.bridgeError': 'Codex 主进程处理器尚未加载。请完全重启 Netcatty 或重启 Electron 开发进程,然后重试。',
|
||||
|
||||
@@ -438,6 +438,8 @@ export const zhCNCoreMessages: Messages = {
|
||||
'settings.vault.showSftpTab': '显示 SFTP 标签页',
|
||||
'settings.vault.showSftpTabDesc': '在顶部标签栏显示独立的 SFTP 视图。关闭后可改用会话内左侧的 SFTP 侧栏。',
|
||||
'settings.vault.showHostTreeSidebar': '显示主机列表侧栏',
|
||||
'settings.vault.removeTopTabsDragArea': '移除顶部窗口拖动区域',
|
||||
'settings.vault.removeTopTabsDragAreaDesc': '开启后移除标签页上方的拖动空白区域,让顶部可用于点击标签页和窗口按钮。',
|
||||
'settings.vault.showHostTreeSidebarDesc': '在终端和编辑器标签页显示主机列表侧栏及顶部开关。',
|
||||
'settings.vault.autoImportSystemKnownHosts': '自动导入系统 known_hosts',
|
||||
'settings.vault.autoImportSystemKnownHostsDesc': '打开主机库时静默导入 OpenSSH known_hosts 中的记录。关闭后,Netcatty 已知主机与系统信任库保持独立;仍可通过「扫描系统」手动导入。',
|
||||
@@ -1247,6 +1249,8 @@ Vaults 标签保持扁平,不使用这块背景。
|
||||
"plugins.sidebar.selectTerminal": "请先选择已打开的终端。",
|
||||
"plugins.sidebar.loading": "正在加载扩展页面…",
|
||||
"plugins.vault.loading": "正在加载插件页面…",
|
||||
"plugins.vault.viewError": "插件页面渲染失败。",
|
||||
"plugins.vault.retry": "重试",
|
||||
"plugins.interaction.title": "插件请求",
|
||||
"plugins.interaction.openUrlTitle": "打开外部链接?",
|
||||
"plugins.interaction.openUrlNote": "此插件请求在默认浏览器中打开以下 HTTPS 链接:",
|
||||
@@ -1413,5 +1417,41 @@ Vaults 标签保持扁平,不使用这块背景。
|
||||
'plugins.hostActions.managedUnsupported': '受管理的 SSH 配置变更需在 Vault 主机编辑器中完成。',
|
||||
'plugins.hostActions.failed': '请求已过期、被撤销或主机已改变。请重新选择主机。',
|
||||
'plugins.hostActions.selectionLimit': '最多选择 50 个当前主机。',
|
||||
'settings.externalEditor.title': '外部远程编辑器',
|
||||
'settings.externalEditor.desc': '直接在本地编辑器(如 Zed、VS Code 或 Cursor)中打开远程 SSH 项目和文件。',
|
||||
'settings.externalEditor.preferredEditor': '首选编辑器',
|
||||
'settings.externalEditor.preferredEditor.desc': 'SFTP 右键菜单和终端打开请求默认使用的本地编辑器。',
|
||||
'settings.externalEditor.executablePath': '编辑器可执行文件',
|
||||
'settings.externalEditor.executablePath.desc': '留空以自动检测,或手动选择本地程序路径。',
|
||||
'settings.externalEditor.executablePath.placeholder': '自动检测可执行文件路径',
|
||||
'settings.externalEditor.status.configured': '已自定义路径',
|
||||
'settings.externalEditor.status.detected': '已自动检测',
|
||||
'settings.externalEditor.status.notFound': '未检测到',
|
||||
'settings.externalEditor.browse': '浏览…',
|
||||
'settings.externalEditor.resetPath': '重置为自动检测',
|
||||
'settings.externalEditor.redetect': '重新检测已安装的编辑器',
|
||||
'settings.externalEditor.customArgs': '自定义参数',
|
||||
'settings.externalEditor.customArgs.desc': '以空格分隔的参数列表(支持占位符:{sshUri}、{sshTarget}、{remotePath}、{encodedPath}、{kind})。',
|
||||
'settings.externalEditor.connectionMode': 'SSH 连接模式',
|
||||
'settings.externalEditor.connectionMode.desc': 'Netcatty SSH 桥接会直接复用当前已认证会话,无需向磁盘导出私钥或主机列表。',
|
||||
'settings.externalEditor.connectionMode.bridge': 'Netcatty SSH 桥接 (*.netcatty)',
|
||||
'settings.externalEditor.connectionMode.direct': '直连 OpenSSH (user@host:port)',
|
||||
'settings.externalEditor.sshBridge.title': 'OpenSSH *.netcatty 桥接规则',
|
||||
'settings.externalEditor.sshBridge.desc': '仅在 OpenSSH 配置中写入单个静态 Host *.netcatty 规则块,不包含任何主机名、私钥或密码。',
|
||||
'settings.externalEditor.sshBridge.install': '安装桥接规则',
|
||||
'settings.externalEditor.sshBridge.reinstall': '重新安装规则',
|
||||
'settings.externalEditor.sshBridge.update': '更新规则',
|
||||
'settings.externalEditor.sshBridge.remove': '移除规则',
|
||||
'settings.externalEditor.terminalRequests': '允许终端发起打开请求 (OSC 7337)',
|
||||
'settings.externalEditor.terminalRequests.desc': '允许远程 Shell 通过 `zed .` 等命令在本地编辑器中打开远程路径。',
|
||||
'settings.externalEditor.autoSetup': '仅在 Netcatty 会话中启用远程编辑器命令',
|
||||
'settings.externalEditor.autoSetup.desc': '将 `zed` / `ncedit` 脚本安装到 ~/.netcatty/bin,并仅在当前 Netcatty 终端会话的 PATH 中生效,不修改 ~/.bashrc 或 ~/.zshrc(也可按主机单独开关)。',
|
||||
'settings.externalEditor.defaultTrust': '默认主机信任策略',
|
||||
'settings.externalEditor.defaultTrust.desc': '未单独配置信任规则的远程主机发起打开编辑器请求时的处理方式。',
|
||||
'settings.externalEditor.trust.ask': '每次询问',
|
||||
'settings.externalEditor.trust.allow': '始终允许',
|
||||
'settings.externalEditor.trust.deny': '始终拒绝',
|
||||
'settings.externalEditor.trustedHosts.host': '主机',
|
||||
'settings.externalEditor.trustedHosts.policy': '策略',
|
||||
|
||||
};
|
||||
@@ -2,6 +2,8 @@ import type { Messages } from '../types';
|
||||
|
||||
export const zhCNTerminalMessages: Messages = {
|
||||
'terminal.directory.open': '当前目录:{path}。更改目录',
|
||||
'terminal.gitBranch.current': 'Git 分支:{{value}}',
|
||||
'terminal.gitBranch.detached': '分离的 HEAD:{{value}}',
|
||||
'terminal.directory.unknown': '目录未知',
|
||||
'terminal.directory.search': '搜索当前目录下的文件夹…',
|
||||
'terminal.directory.directories': '目录',
|
||||
@@ -16,6 +18,7 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 会话报告当前目录。',
|
||||
'terminal.directory.gitBashIntegrationUnavailable': '正在等待原 Git Bash 会话中的可访问目录。',
|
||||
'terminal.directory.wslIntegrationUnavailable': '正在等待所选 WSL 发行版中的 Bash 返回空闲提示符。',
|
||||
'terminal.directory.cygwinIntegrationUnavailable': '正在等待 Cygwin Bash 返回空闲提示符。',
|
||||
'terminal.directory.nonFilesystem': '当前 PowerShell 位置不是文件系统目录。',
|
||||
'terminal.directory.accessDenied': '没有权限列出此目录。',
|
||||
'terminal.directory.busy': '请等待终端回到空命令提示符。',
|
||||
@@ -571,6 +574,9 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'选择自动补全的历史建议来自当前主机,还是所有主机上执行过的命令。',
|
||||
'settings.terminal.autocomplete.historyScope.host': '当前主机',
|
||||
'settings.terminal.autocomplete.historyScope.global': '全部主机',
|
||||
'settings.terminal.autocomplete.showSnippets': '显示代码片段',
|
||||
'settings.terminal.autocomplete.showSnippets.desc':
|
||||
'在补全列表中显示匹配的代码片段。若片段较多、排在列表前面,可关闭此项。',
|
||||
'settings.terminal.section.passwordPromptAssist': '密码提示辅助',
|
||||
'settings.terminal.passwordPromptAssist.mode': '辅助模式',
|
||||
'settings.terminal.passwordPromptAssist.mode.desc':
|
||||
@@ -597,6 +603,9 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'settings.shortcuts.recording': '请按键...',
|
||||
'settings.shortcuts.none': '无',
|
||||
'settings.shortcuts.setDisabled': '设为禁用',
|
||||
'settings.shortcuts.addExtra': '添加快捷键',
|
||||
'settings.shortcuts.additional': '附加快捷键',
|
||||
'settings.shortcuts.removeExtra': '移除快捷键',
|
||||
'settings.shortcuts.category.tabs': '标签页',
|
||||
'settings.shortcuts.category.terminal': '终端',
|
||||
'settings.shortcuts.category.navigation': '导航',
|
||||
@@ -630,6 +639,7 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'settings.shortcuts.binding.command-palette': '打开命令面板',
|
||||
'settings.shortcuts.binding.quick-switch': '快速切换',
|
||||
'settings.shortcuts.binding.new-workspace': '新建工作区',
|
||||
'settings.shortcuts.binding.add-session-to-workspace': '添加会话到工作区',
|
||||
'settings.shortcuts.binding.snippets': '打开代码片段',
|
||||
'settings.shortcuts.binding.broadcast': '切换广播模式',
|
||||
'settings.shortcuts.binding.toggle-opacity': '切换窗口透明度',
|
||||
@@ -719,6 +729,8 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'keychain.export.script': '脚本 *',
|
||||
'keychain.export.scriptPlaceholder': '导出脚本...',
|
||||
'keychain.export.missingCredentials': '主机未保存密码或密钥。请先为该主机添加密码凭据。',
|
||||
'keychain.export.missingPublicKey': '此密钥没有公钥。请先在编辑页粘贴公钥,然后再试「导出并绑定」。',
|
||||
'keychain.export.missingPublicKeyNote': '此密钥没有公钥。请先在密钥编辑页粘贴公钥,然后再导出。',
|
||||
'keychain.export.successTitle': '导出成功',
|
||||
'keychain.export.successMessage': '已导出公钥并绑定到 {host}',
|
||||
'keychain.export.failedTitle': '导出失败',
|
||||
@@ -795,6 +807,7 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'tabs.logPrefix': '日志:',
|
||||
'tabs.logLocal': '本地',
|
||||
'tabs.copyTab': '复制标签页',
|
||||
'tabs.addSessionToWorkspace': '在此工作区添加会话',
|
||||
'tabs.duplicateSession': '复制会话',
|
||||
'tabs.copyTabToNewWindow': '复制标签页到新窗口',
|
||||
'tabs.copyTabToNewWindowFailed': '无法在新窗口打开标签页',
|
||||
@@ -1088,4 +1101,12 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'terminal.browser.allScopeHint': '在每台主机的浏览器中显示。',
|
||||
'terminal.browser.downloadLocation': '文件保存在系统“下载”文件夹',
|
||||
'terminal.browser.saveAs': '另存为…',
|
||||
'terminal.externalEditor.opened': '已在 {editor} 中打开 {path}',
|
||||
'terminal.externalEditor.failed': '无法在 {editor} 中打开',
|
||||
'terminal.externalEditor.prompt.title': '在 {editor} 中打开?',
|
||||
'terminal.externalEditor.prompt.desc': '远程主机 {host} 请求在 {editor} 中打开以下远程路径:',
|
||||
'terminal.externalEditor.prompt.deny': '拒绝',
|
||||
'terminal.externalEditor.prompt.allowOnce': '仅允许本次',
|
||||
'terminal.externalEditor.prompt.alwaysTrust': '始终信任此主机',
|
||||
'terminal.externalEditor.autoSetupConfigured': '已配置远程编辑器命令 ({editor})',
|
||||
};
|
||||
@@ -848,6 +848,7 @@ export const zhCNVaultMessages: Messages = {
|
||||
'cloudSync.localBackups.reason.beforeRestore': '恢复前',
|
||||
'cloudSync.localBackups.versionChange': '{from} -> {to}',
|
||||
'cloudSync.localBackups.counts': '{hosts} 台主机,{keys} 个密钥,{snippets} 个代码片段,{notes} 条笔记',
|
||||
'cloudSync.localBackups.aiCounts': '{sessions} 个 AI 会话,{settings} 项设置',
|
||||
'cloudSync.localBackups.restore': '恢复',
|
||||
'cloudSync.localBackups.restoreSuccess': '已恢复本地备份。',
|
||||
'cloudSync.localBackups.restoreFailedTitle': '恢复失败',
|
||||
@@ -1427,5 +1428,8 @@ export const zhCNVaultMessages: Messages = {
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmDesc': '将从此设备永久删除 {count} 个 .webm 录屏文件。',
|
||||
'settings.remoteDesktopRecordings.clearResult': '已删除 {count} 个录屏文件。',
|
||||
'settings.remoteDesktopRecordings.hint': '录屏文件仅保存在本设备本地,绝不上传云同步;已收藏的连接日志录屏不会在自动清理中被删除。',
|
||||
'sftp.context.openInExternalEditor': '在 {editor} 中打开',
|
||||
'hostDetails.externalEditorShellIntegration': '在此会话中启用外部编辑器命令',
|
||||
'hostDetails.externalEditorShellIntegration.desc': '通过 ~/.netcatty/bin 仅在当前 Netcatty 终端会话中启用 `zed` / `ncedit`(支持 tmux),不修改 ~/.bashrc 或 ~/.zshrc。',
|
||||
|
||||
};
|
||||
@@ -117,6 +117,9 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.codex.appServer.available': '目前 Codex CLI 支援 App Server。',
|
||||
'ai.codex.appServer.modelCatalogWarning': 'Codex 動態模型目錄暫時無法使用,目前將使用內建模型清單。',
|
||||
'ai.codex.appServer.approval.allowSession': '本工作階段允許',
|
||||
'ai.planReview.title': '審核實作方案',
|
||||
'ai.planReview.keepPlanning': '繼續規劃',
|
||||
'ai.planReview.approveAndImplement': '批准並實作',
|
||||
'ai.codex.appServer.userInput.title': 'Codex 需要你的輸入',
|
||||
'ai.codex.appServer.userInput.description': '回答以下問題以繼續目前任務。',
|
||||
'ai.codex.appServer.userInput.other': '輸入其他答案',
|
||||
@@ -328,6 +331,9 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.grok.check': '檢查',
|
||||
'ai.grok.resetPath': '重設',
|
||||
'ai.grok.runtime.acp.title': '使用 Grok ACP(agent stdio)',
|
||||
'ai.grok.userQuestion.title': 'Grok 正在等待你的回答',
|
||||
'ai.grok.userQuestion.description': '回答不會變更權限。請勿填寫密碼或權杖。',
|
||||
'ai.grok.userQuestion.submit': '傳送回答',
|
||||
'ai.grok.runtime.acp.default': '預設',
|
||||
'ai.grok.runtime.acp.description':
|
||||
'透過 Agent Client Protocol(grok agent stdio)接入 Grok。在 session/new 注入 Netcatty MCP。關閉後使用原始 headless streaming-json CLI 路徑。',
|
||||
@@ -628,12 +634,25 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.chat.managerRebindPick': '選擇目標終端或工作區…',
|
||||
'ai.chat.managerRebindHere': '目前面板',
|
||||
'ai.chat.managerRebindDone': '已將「{title}」移動到 {target}。',
|
||||
'ai.chat.managerToggleSelection': '選擇工作階段',
|
||||
'ai.chat.managerSelectAll': '全選',
|
||||
'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': '閒置',
|
||||
'ai.chat.managerMessagesCount': '{n} 則訊息',
|
||||
'ai.chat.managerDeleteTitle': '刪除此會話?',
|
||||
'ai.chat.managerDeleteMessage': '「{title}」及其訊息將從所有面板中移除,且無法復原。',
|
||||
'ai.chat.managerBulkDeleteTitle': '刪除選取的 {n} 個工作階段?',
|
||||
'ai.chat.managerBulkDeleteMessage': '選取的 {n} 個工作階段及其訊息將從所有面板中移除,且無法復原。',
|
||||
'ai.chat.justNow': '剛剛',
|
||||
'ai.chat.minutesAgo': '{n}分鐘前',
|
||||
'ai.chat.hoursAgo': '{n}小時前',
|
||||
@@ -684,9 +703,25 @@ 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': '則訊息',
|
||||
'ai.chatHistory.autoLlmTitle': '自動產生工作階段標題',
|
||||
'ai.chatHistory.autoLlmTitle.description': '首則訊息後以一次輕量 LLM 呼叫產生簡短標題;不可用時退回首行。僅本機生效。',
|
||||
'ai.chatHistory.titleModel': '標題模型',
|
||||
'ai.chatHistory.titleModel.description': '用於產生工作階段標題的 provider 與模型,建議選擇輕巧便宜的模型。預設使用目前的 Catty 模型。',
|
||||
'ai.chatHistory.titleModel.none': '沒有可用的 provider。',
|
||||
'ai.chatHistory.titleModel.useCurrentCatty': '使用目前的 Catty 模型',
|
||||
'ai.chatHistory.titleModel.unavailable': '無法使用',
|
||||
'ai.chatHistory.titleModel.providerPlaceholder': '選擇 provider',
|
||||
'ai.chatHistory.titleModel.modelPlaceholder': '選擇模型',
|
||||
|
||||
// AI Error
|
||||
'ai.codex.bridgeError': 'Codex 主行程處理器尚未載入。請完全重新啟動 Netcatty 或重新啟動 Electron 開發行程,然後重試。',
|
||||
|
||||
@@ -438,6 +438,8 @@ export const zhTWCoreMessages: Messages = {
|
||||
'settings.vault.showSftpTab': '顯示 SFTP 分頁',
|
||||
'settings.vault.showSftpTabDesc': '在頂部分頁列顯示獨立的 SFTP 檢視。關閉後可改用工作階段內左側的 SFTP 側欄。',
|
||||
'settings.vault.showHostTreeSidebar': '顯示主機列表側欄',
|
||||
'settings.vault.removeTopTabsDragArea': '移除頂部視窗拖曳區域',
|
||||
'settings.vault.removeTopTabsDragAreaDesc': '開啟後移除分頁上方的拖曳空白區域,讓頂部可供點擊分頁與視窗按鈕。',
|
||||
'settings.vault.showHostTreeSidebarDesc': '在終端和編輯器分頁顯示主機列表側欄及頂部開關。',
|
||||
'settings.vault.autoImportSystemKnownHosts': '自動匯入系統 known_hosts',
|
||||
'settings.vault.autoImportSystemKnownHostsDesc': '開啟主機庫時靜默匯入 OpenSSH known_hosts 中的記錄。關閉後,Netcatty 已知主機與系統信任庫保持獨立;仍可透過「掃描系統」手動匯入。',
|
||||
@@ -1248,6 +1250,8 @@ Vaults 分頁維持扁平,不使用這塊背景。
|
||||
"plugins.sidebar.selectTerminal": "請先選擇已開啟的終端。",
|
||||
"plugins.sidebar.loading": "正在載入擴充功能頁面…",
|
||||
"plugins.vault.loading": "正在載入擴充功能頁面…",
|
||||
"plugins.vault.viewError": "擴充功能頁面無法顯示。",
|
||||
"plugins.vault.retry": "重試",
|
||||
"plugins.interaction.title": "外掛請求",
|
||||
"plugins.interaction.openUrlTitle": "開啟外部連結?",
|
||||
"plugins.interaction.openUrlNote": "此外掛請求在預設瀏覽器中開啟以下 HTTPS 連結:",
|
||||
@@ -1414,4 +1418,40 @@ Vaults 分頁維持扁平,不使用這塊背景。
|
||||
'plugins.hostActions.managedUnsupported': '受管理的 SSH 設定變更需在 Vault 主機編輯器中完成。',
|
||||
'plugins.hostActions.failed': '請求已過期、被撤銷或主機已變更。請重新選擇主機。',
|
||||
'plugins.hostActions.selectionLimit': '最多選擇 50 部目前的主機。',
|
||||
'settings.externalEditor.title': '外部遠端編輯器',
|
||||
'settings.externalEditor.desc': '直接在本機編輯器(如 Zed、VS Code 或 Cursor)中開啟遠端 SSH 專案與檔案。',
|
||||
'settings.externalEditor.preferredEditor': '偏好編輯器',
|
||||
'settings.externalEditor.preferredEditor.desc': 'SFTP 右鍵選單與終端機開啟請求預設使用的本機編輯器。',
|
||||
'settings.externalEditor.executablePath': '編輯器執行檔',
|
||||
'settings.externalEditor.executablePath.desc': '留空以自動偵測,或手動選擇本機程式路徑。',
|
||||
'settings.externalEditor.executablePath.placeholder': '自動偵測執行檔路徑',
|
||||
'settings.externalEditor.status.configured': '已自訂路徑',
|
||||
'settings.externalEditor.status.detected': '已自動偵測',
|
||||
'settings.externalEditor.status.notFound': '未偵測到',
|
||||
'settings.externalEditor.browse': '瀏覽…',
|
||||
'settings.externalEditor.resetPath': '重設為自動偵測',
|
||||
'settings.externalEditor.redetect': '重新偵測已安裝的編輯器',
|
||||
'settings.externalEditor.customArgs': '自訂參數',
|
||||
'settings.externalEditor.customArgs.desc': '以空白分隔的參數清單(支援預留位置:{sshUri}、{sshTarget}、{remotePath}、{encodedPath}、{kind})。',
|
||||
'settings.externalEditor.connectionMode': 'SSH 連線模式',
|
||||
'settings.externalEditor.connectionMode.desc': 'Netcatty SSH 橋接會直接重複使用目前已完成驗證的連線,無需將私鑰或主機清單匯出至磁碟。',
|
||||
'settings.externalEditor.connectionMode.bridge': 'Netcatty SSH 橋接 (*.netcatty)',
|
||||
'settings.externalEditor.connectionMode.direct': '直連 OpenSSH (user@host:port)',
|
||||
'settings.externalEditor.sshBridge.title': 'OpenSSH *.netcatty 橋接規則',
|
||||
'settings.externalEditor.sshBridge.desc': '僅在 OpenSSH 設定中寫入單一靜態 Host *.netcatty 規則區塊,不包含任何主機名稱、私鑰或密碼。',
|
||||
'settings.externalEditor.sshBridge.install': '安裝橋接規則',
|
||||
'settings.externalEditor.sshBridge.reinstall': '重新安裝規則',
|
||||
'settings.externalEditor.sshBridge.update': '更新規則',
|
||||
'settings.externalEditor.sshBridge.remove': '移除規則',
|
||||
'settings.externalEditor.terminalRequests': '允許終端機發起開啟請求 (OSC 7337)',
|
||||
'settings.externalEditor.terminalRequests.desc': '允許遠端 Shell 透過 `zed .` 等指令在本機編輯器中開啟遠端路徑。',
|
||||
'settings.externalEditor.autoSetup': '僅在 Netcatty 工作階段啟用遠端編輯器指令',
|
||||
'settings.externalEditor.autoSetup.desc': '將 `zed` / `ncedit` 指令稿安裝至 ~/.netcatty/bin,並僅於目前 Netcatty 終端機工作階段的 PATH 生效,不修改 ~/.bashrc 或 ~/.zshrc(亦可依主機個別切換)。',
|
||||
'settings.externalEditor.defaultTrust': '預設主機信任原則',
|
||||
'settings.externalEditor.defaultTrust.desc': '尚未單獨設定信任原則的遠端主機請求開啟編輯器時的處理方式。',
|
||||
'settings.externalEditor.trust.ask': '每次詢問',
|
||||
'settings.externalEditor.trust.allow': '一律允許',
|
||||
'settings.externalEditor.trust.deny': '一律拒絕',
|
||||
'settings.externalEditor.trustedHosts.host': '主機',
|
||||
'settings.externalEditor.trustedHosts.policy': '原則',
|
||||
};
|
||||
@@ -2,6 +2,8 @@ import type { Messages } from '../types';
|
||||
|
||||
export const zhTWTerminalMessages: Messages = {
|
||||
'terminal.directory.open': '目前目錄:{path}。變更目錄',
|
||||
'terminal.gitBranch.current': 'Git 分支:{{value}}',
|
||||
'terminal.gitBranch.detached': '分離的 HEAD:{{value}}',
|
||||
'terminal.directory.unknown': '目錄未知',
|
||||
'terminal.directory.search': '搜尋目前目錄下的資料夾…',
|
||||
'terminal.directory.directories': '目錄',
|
||||
@@ -16,6 +18,7 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 工作階段回報目前目錄。',
|
||||
'terminal.directory.gitBashIntegrationUnavailable': '正在等待原 Git Bash 工作階段中的可存取目錄。',
|
||||
'terminal.directory.wslIntegrationUnavailable': '正在等待所選 WSL 發行版本中的 Bash 返回閒置提示字元。',
|
||||
'terminal.directory.cygwinIntegrationUnavailable': '正在等待 Cygwin Bash 返回閒置提示字元。',
|
||||
'terminal.directory.nonFilesystem': '目前 PowerShell 位置不是檔案系統目錄。',
|
||||
'terminal.directory.accessDenied': '沒有權限列出此目錄。',
|
||||
'terminal.directory.busy': '請等待終端回到空白命令提示字元。',
|
||||
@@ -571,6 +574,9 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'選擇自動補全的歷史建議來自目前主機,還是所有主機上執行過的指令。',
|
||||
'settings.terminal.autocomplete.historyScope.host': '目前主機',
|
||||
'settings.terminal.autocomplete.historyScope.global': '全部主機',
|
||||
'settings.terminal.autocomplete.showSnippets': '顯示程式碼片段',
|
||||
'settings.terminal.autocomplete.showSnippets.desc':
|
||||
'在補全列表中顯示符合的程式碼片段。若片段較多、排在列表前面,可關閉此項。',
|
||||
'settings.terminal.section.passwordPromptAssist': '密碼提示輔助',
|
||||
'settings.terminal.passwordPromptAssist.mode': '輔助模式',
|
||||
'settings.terminal.passwordPromptAssist.mode.desc':
|
||||
@@ -597,6 +603,9 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'settings.shortcuts.recording': '請按鍵...',
|
||||
'settings.shortcuts.none': '無',
|
||||
'settings.shortcuts.setDisabled': '設為停用',
|
||||
'settings.shortcuts.addExtra': '新增快速鍵',
|
||||
'settings.shortcuts.additional': '附加快速鍵',
|
||||
'settings.shortcuts.removeExtra': '移除快速鍵',
|
||||
'settings.shortcuts.category.tabs': '分頁',
|
||||
'settings.shortcuts.category.terminal': '終端',
|
||||
'settings.shortcuts.category.navigation': '導航',
|
||||
@@ -630,6 +639,7 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'settings.shortcuts.binding.command-palette': '開啟指令面板',
|
||||
'settings.shortcuts.binding.quick-switch': '快速切換',
|
||||
'settings.shortcuts.binding.new-workspace': '新增工作區',
|
||||
'settings.shortcuts.binding.add-session-to-workspace': '新增工作階段至工作區',
|
||||
'settings.shortcuts.binding.snippets': '開啟程式碼片段',
|
||||
'settings.shortcuts.binding.broadcast': '切換廣播模式',
|
||||
'settings.shortcuts.binding.toggle-opacity': '切換視窗透明度',
|
||||
@@ -719,6 +729,8 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'keychain.export.script': '指令碼 *',
|
||||
'keychain.export.scriptPlaceholder': '匯出指令碼...',
|
||||
'keychain.export.missingCredentials': '主機未儲存密碼或金鑰。請先為該主機新增密碼憑證。',
|
||||
'keychain.export.missingPublicKey': '此金鑰沒有公鑰。請先在編輯頁貼上公鑰,然後再試「匯出並繫結」。',
|
||||
'keychain.export.missingPublicKeyNote': '此金鑰沒有公鑰。請先在金鑰編輯頁貼上公鑰,然後再匯出。',
|
||||
'keychain.export.successTitle': '匯出成功',
|
||||
'keychain.export.successMessage': '已匯出公鑰並繫結到 {host}',
|
||||
'keychain.export.failedTitle': '匯出失敗',
|
||||
@@ -795,6 +807,7 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'tabs.logPrefix': '日誌:',
|
||||
'tabs.logLocal': '本機',
|
||||
'tabs.copyTab': '複製分頁',
|
||||
'tabs.addSessionToWorkspace': '新增工作階段至此工作區',
|
||||
'tabs.duplicateSession': '複製工作階段',
|
||||
'tabs.copyTabToNewWindow': '複製分頁到新視窗',
|
||||
'tabs.copyTabToNewWindowFailed': '無法在新視窗開啟分頁',
|
||||
@@ -1088,4 +1101,12 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'terminal.browser.allScopeHint': '在每台主機的瀏覽器中顯示。',
|
||||
'terminal.browser.downloadLocation': '檔案儲存在系統「下載項目」資料夾',
|
||||
'terminal.browser.saveAs': '另存新檔…',
|
||||
'terminal.externalEditor.opened': '已在 {editor} 中開啟 {path}',
|
||||
'terminal.externalEditor.failed': '無法在 {editor} 中開啟',
|
||||
'terminal.externalEditor.prompt.title': '在 {editor} 中開啟?',
|
||||
'terminal.externalEditor.prompt.desc': '遠端主機 {host} 請求在 {editor} 中開啟以下遠端路徑:',
|
||||
'terminal.externalEditor.prompt.deny': '拒絕',
|
||||
'terminal.externalEditor.prompt.allowOnce': '僅允許這次',
|
||||
'terminal.externalEditor.prompt.alwaysTrust': '一律信任此主機',
|
||||
'terminal.externalEditor.autoSetupConfigured': '已設定遠端編輯器指令 ({editor})',
|
||||
};
|
||||
@@ -848,6 +848,7 @@ export const zhTWVaultMessages: Messages = {
|
||||
'cloudSync.localBackups.reason.beforeRestore': '恢復前',
|
||||
'cloudSync.localBackups.versionChange': '{from} -> {to}',
|
||||
'cloudSync.localBackups.counts': '{hosts} 台主機,{keys} 個金鑰,{snippets} 個程式碼片段,{notes} 條筆記',
|
||||
'cloudSync.localBackups.aiCounts': '{sessions} 個 AI 工作階段,{settings} 項設定',
|
||||
'cloudSync.localBackups.restore': '恢復',
|
||||
'cloudSync.localBackups.restoreSuccess': '已恢復本機備份。',
|
||||
'cloudSync.localBackups.restoreFailedTitle': '恢復失敗',
|
||||
@@ -1427,5 +1428,8 @@ export const zhTWVaultMessages: Messages = {
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmDesc': '將從此裝置永久刪除 {count} 個 .webm 錄影檔案。',
|
||||
'settings.remoteDesktopRecordings.clearResult': '已刪除 {count} 個錄影檔案。',
|
||||
'settings.remoteDesktopRecordings.hint': '錄影檔案僅儲存在本裝置本機,絕不上傳雲端同步;已收藏的連線日誌錄影不會在自動清理中被刪除。',
|
||||
'sftp.context.openInExternalEditor': '在 {editor} 中開啟',
|
||||
'hostDetails.externalEditorShellIntegration': '於此工作階段啟用外部編輯器指令',
|
||||
'hostDetails.externalEditorShellIntegration.desc': '透過 ~/.netcatty/bin 僅於目前 Netcatty 終端機工作階段啟用 `zed` / `ncedit`(支援 tmux),不修改 ~/.bashrc 或 ~/.zshrc。',
|
||||
|
||||
};
|
||||
@@ -57,6 +57,9 @@ export interface LocalVaultBackupPreview {
|
||||
noteCount: number;
|
||||
identityCount: number;
|
||||
portForwardingRuleCount: number;
|
||||
/** Optional so backups written before these counters existed still load. */
|
||||
aiSessionCount?: number;
|
||||
settingCount?: number;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -65,3 +65,409 @@ test('inserting a child into an existing void element fails the view', async ()
|
||||
assert.equal(tree.isFailed(), true);
|
||||
assert.deepEqual(tree.snapshot(), { children: [] });
|
||||
});
|
||||
|
||||
test('duplicate insert of an existing id applies as a move or replace and keeps follow-up updates in sync', async () => {
|
||||
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
|
||||
const tree = createPluginRemoteTree();
|
||||
tree.apply([[0, '~', { id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] }, 0]]);
|
||||
|
||||
// Inserting an existing id at a later sibling index replaces the existing node in place.
|
||||
const replaced = tree.apply([
|
||||
[3, 'a', 'class', 'stale'],
|
||||
[0, '~', { id: 'a', type: 1, element: 'span', attributes: { class: 'replaced' }, children: [] }, 1],
|
||||
]);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(replaced, {
|
||||
children: [{ id: 'a', type: 1, element: 'span', attributes: { class: 'replaced' }, children: [] }],
|
||||
});
|
||||
|
||||
// Follow-up mutations must apply against the replaced live node (desync gate).
|
||||
const afterFollowUp = tree.apply([
|
||||
[3, 'a', 'class', 'after-sort'],
|
||||
[0, '~', { id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'second' }] }, 1],
|
||||
]);
|
||||
assert.deepEqual(afterFollowUp, {
|
||||
children: [
|
||||
{ id: 'a', type: 1, element: 'span', attributes: { class: 'after-sort' }, children: [] },
|
||||
{ id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'second' }] },
|
||||
],
|
||||
});
|
||||
|
||||
// Moving an existing sibling forward adjusts the insert index after detaching the old slot.
|
||||
const movedForward = tree.apply([
|
||||
[0, '~', { id: 'a', type: 1, element: 'span', attributes: { class: 'moved-end' }, children: [] }, 2],
|
||||
]);
|
||||
assert.deepEqual(movedForward.children.map((node) => node.id), ['b', 'a']);
|
||||
assert.deepEqual(movedForward.children[1], { id: 'a', type: 1, element: 'span', attributes: { class: 'moved-end' }, children: [] });
|
||||
|
||||
// Moving an existing sibling backward preserves index 0 and keeps subsequent updates working.
|
||||
const movedBack = tree.apply([
|
||||
[0, '~', { id: 'a', type: 1, element: 'span', attributes: { class: 'moved-start' }, children: [] }, 0],
|
||||
]);
|
||||
assert.deepEqual(movedBack.children.map((node) => node.id), ['a', 'b']);
|
||||
const postMoveAttr = tree.apply([[2, 'b-text', 'updated-second'], [3, 'a', 'class', 'synced']]);
|
||||
assert.deepEqual(postMoveAttr, {
|
||||
children: [
|
||||
{ id: 'a', type: 1, element: 'span', attributes: { class: 'synced' }, children: [] },
|
||||
{ id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'updated-second' }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test('inserting a parent whose subtree re-includes an already-present child detaches the child and preserves later updates', async () => {
|
||||
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
|
||||
const tree = createPluginRemoteTree();
|
||||
tree.apply([
|
||||
[0, '~', {
|
||||
id: 'old-parent',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: {},
|
||||
children: [{
|
||||
id: 'cell-1',
|
||||
type: 1,
|
||||
element: 'span',
|
||||
attributes: { class: 'unsorted' },
|
||||
children: [{ id: 'cell-text', type: 3, data: 'alpha' }],
|
||||
}],
|
||||
}, 0],
|
||||
]);
|
||||
|
||||
// Parent insertion repeats already-attached descendant IDs without a preceding remove.
|
||||
const reparented = tree.apply([
|
||||
[0, '~', {
|
||||
id: 'new-parent',
|
||||
type: 1,
|
||||
element: 'section',
|
||||
attributes: {},
|
||||
children: [{
|
||||
id: 'cell-1',
|
||||
type: 1,
|
||||
element: 'span',
|
||||
attributes: { class: 'sorted-asc' },
|
||||
children: [{ id: 'cell-text', type: 3, data: 'alpha' }],
|
||||
}],
|
||||
}, 1],
|
||||
]);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(reparented, {
|
||||
children: [
|
||||
{ id: 'old-parent', type: 1, element: 'div', attributes: {}, children: [] },
|
||||
{
|
||||
id: 'new-parent',
|
||||
type: 1,
|
||||
element: 'section',
|
||||
attributes: {},
|
||||
children: [{
|
||||
id: 'cell-1',
|
||||
type: 1,
|
||||
element: 'span',
|
||||
attributes: { class: 'sorted-asc' },
|
||||
children: [{ id: 'cell-text', type: 3, data: 'alpha' }],
|
||||
}],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// A subsequent sort-like incremental update on the moved child applies cleanly.
|
||||
const secondSort = tree.apply([
|
||||
[3, 'cell-1', 'class', 'sorted-desc'],
|
||||
[2, 'cell-text', 'omega'],
|
||||
]);
|
||||
assert.deepEqual(secondSort.children[1], {
|
||||
id: 'new-parent',
|
||||
type: 1,
|
||||
element: 'section',
|
||||
attributes: {},
|
||||
children: [{
|
||||
id: 'cell-1',
|
||||
type: 1,
|
||||
element: 'span',
|
||||
attributes: { class: 'sorted-desc' },
|
||||
children: [{ id: 'cell-text', type: 3, data: 'omega' }],
|
||||
}],
|
||||
});
|
||||
|
||||
// Same-batch case: descendant inserted first, then a new parent serializing that descendant.
|
||||
const sameBatch = tree.apply([
|
||||
[0, 'old-parent', { id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'one' }] }, 0],
|
||||
[0, '~', {
|
||||
id: 'wrapper',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: {},
|
||||
children: [{ id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'one' }] }],
|
||||
}, 2],
|
||||
]);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(sameBatch.children[0], { id: 'old-parent', type: 1, element: 'div', attributes: {}, children: [] });
|
||||
assert.deepEqual(sameBatch.children[2], {
|
||||
id: 'wrapper',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: {},
|
||||
children: [{ id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'one' }] }],
|
||||
});
|
||||
const afterSameBatch = tree.apply([[2, 'child-2-text', 'two']]);
|
||||
assert.deepEqual(afterSameBatch.children[2], {
|
||||
id: 'wrapper',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: {},
|
||||
children: [{ id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'two' }] }],
|
||||
});
|
||||
});
|
||||
|
||||
test('unrecoverable self-nesting duplicate throws without failing the tree or corrupting later updates', async () => {
|
||||
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
|
||||
const tree = createPluginRemoteTree();
|
||||
tree.apply([[0, '~', { id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] }, 0]]);
|
||||
assert.throws(
|
||||
() => tree.apply([
|
||||
[3, 'a', 'class', 'rejected'],
|
||||
[0, 'a', { id: 'a', type: 1, element: 'span', attributes: {}, children: [] }, 0],
|
||||
]),
|
||||
/Duplicate view node/,
|
||||
);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(tree.snapshot(), {
|
||||
children: [{ id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] }],
|
||||
});
|
||||
const updated = tree.apply([[0, '~', { id: 'b', type: 3, data: 'second' }, 1]]);
|
||||
assert.deepEqual(updated, {
|
||||
children: [
|
||||
{ id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] },
|
||||
{ id: 'b', type: 3, data: 'second' },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test('a duplicate id combined with a forbidden mutation still hard-fails the view', async () => {
|
||||
const { createPluginRemoteTree, isDuplicatePluginViewNodeError, assertDuplicateOnlyPluginRemoteTree } = await import('./pluginRemoteTree');
|
||||
const tree = createPluginRemoteTree();
|
||||
tree.apply([[0, '~', { id: 'input', type: 1, element: 'input', attributes: { type: 'text' }, children: [] }, 0]]);
|
||||
// Mutation order matters for RemoteReceiver: the void-element child is applied first so the
|
||||
// projected tree actually contains both the policy violation and a later duplicate id.
|
||||
assert.throws(
|
||||
() => tree.apply([
|
||||
[0, 'input', { id: 'child', type: 3, data: 'invalid' }, 0],
|
||||
[0, '~', { id: 'input', type: 1, element: 'div', attributes: {}, children: [] }, 1],
|
||||
]),
|
||||
/Void view elements/,
|
||||
);
|
||||
assert.equal(tree.isFailed(), true);
|
||||
assert.deepEqual(tree.snapshot(), { children: [] });
|
||||
|
||||
// Even when the duplicate node appears earlier in root order than the void-element violation,
|
||||
// unique-id revalidation must still hard-fail instead of rewriting the batch.
|
||||
const duplicateFirstTree = createPluginRemoteTree();
|
||||
duplicateFirstTree.apply([[0, '~', { id: 'input', type: 1, element: 'input', attributes: { type: 'text' }, children: [] }, 0]]);
|
||||
assert.throws(
|
||||
() => duplicateFirstTree.apply([
|
||||
[0, 'input', { id: 'child', type: 3, data: 'invalid' }, 0],
|
||||
[0, '~', { id: 'input', type: 1, element: 'div', attributes: {}, children: [] }, 0],
|
||||
]),
|
||||
/Void view elements/,
|
||||
);
|
||||
assert.equal(duplicateFirstTree.isFailed(), true);
|
||||
assert.deepEqual(duplicateFirstTree.snapshot(), { children: [] });
|
||||
|
||||
// Defense in depth: if a projected tree already has both issues, unique-id revalidation
|
||||
// must still surface the void-element violation instead of treating it as recoverable.
|
||||
const mixed = {
|
||||
children: [
|
||||
{ id: 'input', type: 1 as const, element: 'input', attributes: { type: 'text' }, children: [{ id: 'child', type: 3 as const, data: 'invalid' }] },
|
||||
{ id: 'input', type: 1 as const, element: 'div', attributes: {}, children: [] },
|
||||
],
|
||||
};
|
||||
assert.equal(isDuplicatePluginViewNodeError(new TypeError('Duplicate view node')), true);
|
||||
assert.throws(() => assertDuplicateOnlyPluginRemoteTree(mixed), /Void view elements/);
|
||||
});
|
||||
|
||||
test('RemoteMutationObserver wrapping a sibling preserves kept siblings and follow-up text updates', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="remote"></div>', { url: 'http://localhost', pretendToBeVisual: true });
|
||||
const saved = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'MutationObserver', 'Event', 'MouseEvent']) {
|
||||
saved.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] });
|
||||
}
|
||||
const { RemoteMutationObserver } = await import('@remote-dom/core/elements');
|
||||
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
|
||||
const staged = createPluginRemoteTree();
|
||||
const batches: unknown[][][] = [];
|
||||
const observer = new RemoteMutationObserver({
|
||||
mutate(records) {
|
||||
const cloned = JSON.parse(JSON.stringify(records)) as unknown[][];
|
||||
batches.push(cloned);
|
||||
staged.apply(cloned);
|
||||
},
|
||||
call() { throw new Error('Host method calls are unavailable'); },
|
||||
});
|
||||
const container = document.getElementById('remote')!;
|
||||
observer.observe(container);
|
||||
const flush = () => new Promise((resolve) => setTimeout(resolve, 10));
|
||||
|
||||
try {
|
||||
const a = document.createElement('div');
|
||||
a.id = 'a';
|
||||
const aText = document.createTextNode('Alpha');
|
||||
a.appendChild(aText);
|
||||
|
||||
const b = document.createElement('div');
|
||||
b.id = 'b';
|
||||
b.appendChild(document.createTextNode('Beta'));
|
||||
|
||||
container.appendChild(a);
|
||||
container.appendChild(b);
|
||||
await flush();
|
||||
|
||||
assert.equal(staged.isFailed(), false);
|
||||
assert.equal(staged.snapshot().children.length, 2);
|
||||
|
||||
// Same-tick wrap: append wrapper and move b into it.
|
||||
const wrapper = document.createElement('section');
|
||||
wrapper.id = 'wrapper';
|
||||
container.appendChild(wrapper);
|
||||
wrapper.appendChild(b);
|
||||
await flush();
|
||||
|
||||
assert.equal(staged.isFailed(), false);
|
||||
const afterWrap = staged.snapshot();
|
||||
assert.deepEqual(
|
||||
afterWrap.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
|
||||
['a', 'wrapper'],
|
||||
);
|
||||
const [aNode, wrapperNode] = afterWrap.children;
|
||||
assert.ok(aNode && aNode.type === 1, 'Expected sibling a first in host tree');
|
||||
assert.ok(wrapperNode && wrapperNode.type === 1, 'Expected wrapper second in host tree');
|
||||
assert.equal(aNode.children[0]?.type === 3 ? aNode.children[0].data : null, 'Alpha');
|
||||
assert.deepEqual(
|
||||
wrapperNode.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
|
||||
['b'],
|
||||
);
|
||||
const bNode = wrapperNode.children[0];
|
||||
assert.ok(bNode && bNode.type === 1, 'Expected b inside wrapper');
|
||||
assert.equal(bNode.children[0]?.type === 3 ? bNode.children[0].data : null, 'Beta');
|
||||
|
||||
// Desync gate: a subsequent text update to a must apply cleanly.
|
||||
aText.data = 'Alpha updated';
|
||||
await flush();
|
||||
|
||||
assert.equal(staged.isFailed(), false);
|
||||
const afterText = staged.snapshot();
|
||||
assert.deepEqual(
|
||||
afterText.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
|
||||
['a', 'wrapper'],
|
||||
);
|
||||
const updatedANode = afterText.children[0];
|
||||
assert.ok(updatedANode && updatedANode.type === 1);
|
||||
assert.equal(updatedANode.children[0]?.type === 3 ? updatedANode.children[0].data : null, 'Alpha updated');
|
||||
|
||||
// Later turn: removing wrapper at index 1 must keep a and leave a updatable.
|
||||
wrapper.remove();
|
||||
await flush();
|
||||
|
||||
assert.equal(staged.isFailed(), false);
|
||||
const afterRemove = staged.snapshot();
|
||||
assert.deepEqual(
|
||||
afterRemove.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
|
||||
['a'],
|
||||
);
|
||||
aText.data = 'Alpha after remove';
|
||||
await flush();
|
||||
|
||||
assert.equal(staged.isFailed(), false);
|
||||
const afterRemoveText = staged.snapshot();
|
||||
const survivingANode = afterRemoveText.children[0];
|
||||
assert.ok(survivingANode && survivingANode.type === 1);
|
||||
assert.equal(survivingANode.children[0]?.type === 3 ? survivingANode.children[0].data : null, 'Alpha after remove');
|
||||
assert.ok(batches.length >= 5);
|
||||
} finally {
|
||||
observer.disconnect();
|
||||
for (const [key, value] of saved) {
|
||||
if (value) Object.defineProperty(globalThis, key, value);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('rewriteDuplicateInsertBatch skips matched detaches and remaps subsequent producer removals', async () => {
|
||||
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
|
||||
const tree = createPluginRemoteTree();
|
||||
tree.apply([
|
||||
[0, '~', { id: '0', type: 1, element: 'div', attributes: { id: 'a' }, children: [{ id: '1', type: 3, data: 'Alpha' }] }, 0],
|
||||
[0, '~', { id: '2', type: 1, element: 'div', attributes: { id: 'b' }, children: [{ id: '3', type: 3, data: 'Beta' }] }, 1],
|
||||
]);
|
||||
|
||||
// Exact mutation batch from RemoteMutationObserver when appending wrapper and moving b into it.
|
||||
const wrapped = tree.apply([
|
||||
[0, '~', {
|
||||
id: '4',
|
||||
type: 1,
|
||||
element: 'section',
|
||||
attributes: { id: 'wrapper' },
|
||||
children: [{ id: '2', type: 1, element: 'div', attributes: { id: 'b' }, children: [{ id: '3', type: 3, data: 'Beta' }] }],
|
||||
}, 0],
|
||||
[1, '~', 1],
|
||||
]);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(wrapped.children.map((node) => node.id), ['0', '4']);
|
||||
const wrapperNode = wrapped.children[1];
|
||||
assert.equal(wrapperNode.type, 1);
|
||||
if (wrapperNode.type === 1) {
|
||||
assert.deepEqual(wrapperNode.children.map((node) => node.id), ['2']);
|
||||
}
|
||||
|
||||
// Subsequent text update to a must still apply.
|
||||
const updated = tree.apply([[2, '1', 'Alpha updated']]);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(updated.children[0], {
|
||||
id: '0',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: { id: 'a' },
|
||||
children: [{ id: '1', type: 3, data: 'Alpha updated' }],
|
||||
});
|
||||
|
||||
// Later producer remove of wrapper at index 1 must remove wrapper and keep a alive.
|
||||
const afterRemove = tree.apply([[1, '~', 1]]);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(afterRemove.children.map((node) => node.id), ['0']);
|
||||
const afterRemoveUpdate = tree.apply([[2, '1', 'Alpha after remove']]);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(afterRemoveUpdate, {
|
||||
children: [{
|
||||
id: '0',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: { id: 'a' },
|
||||
children: [{ id: '1', type: 3, data: 'Alpha after remove' }],
|
||||
}],
|
||||
});
|
||||
|
||||
// Producer remove at a larger index after a rewrite detach at a smaller index remaps to the right sibling.
|
||||
const remapTree = createPluginRemoteTree();
|
||||
remapTree.apply([
|
||||
[0, '~', { id: 'a', type: 1, element: 'div', attributes: {}, children: [] }, 0],
|
||||
[0, '~', { id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'keep' }] }, 1],
|
||||
[0, '~', { id: 'c', type: 1, element: 'div', attributes: {}, children: [] }, 2],
|
||||
]);
|
||||
const remapped = remapTree.apply([
|
||||
[0, '~', { id: 'wrap', type: 1, element: 'section', attributes: {}, children: [{ id: 'a', type: 1, element: 'div', attributes: {}, children: [] }] }, 3],
|
||||
// Producer removes c (original index 2) while a (index 0) was already detached by the rewrite.
|
||||
[1, '~', 2],
|
||||
// Producer then removes a at original index 0 (already detached -> skipped).
|
||||
[1, '~', 0],
|
||||
]);
|
||||
assert.equal(remapTree.isFailed(), false);
|
||||
assert.deepEqual(remapped.children.map((node) => node.id), ['b', 'wrap']);
|
||||
const followUp = remapTree.apply([[2, 'b-text', 'still-alive']]);
|
||||
assert.deepEqual(followUp.children[0], {
|
||||
id: 'b',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: {},
|
||||
children: [{ id: 'b-text', type: 3, data: 'still-alive' }],
|
||||
});
|
||||
});
|
||||
@@ -12,6 +12,174 @@ export function isValidatedPluginRemoteTree(tree: unknown): boolean {
|
||||
return Boolean(tree && typeof tree === 'object' && validatedTrees.has(tree));
|
||||
}
|
||||
|
||||
export function isDuplicatePluginViewNodeError(error: unknown): error is TypeError {
|
||||
return error instanceof TypeError && error.message === 'Duplicate view node';
|
||||
}
|
||||
|
||||
function withUniqueViewIds(tree: WireTree): WireTree {
|
||||
let n = 0;
|
||||
const rewrite = (node: WireNode): WireNode => {
|
||||
const id = `n${n++}`;
|
||||
if (node.type === 3 || node.type === 8) return { id, type: node.type, data: node.data };
|
||||
return { id, type: 1, element: node.element, attributes: node.attributes, children: node.children.map(rewrite) };
|
||||
};
|
||||
return { children: tree.children.map(rewrite) };
|
||||
}
|
||||
|
||||
/** If a projected tree has duplicate IDs, still hard-fail when other policy violations exist. */
|
||||
export function assertDuplicateOnlyPluginRemoteTree(tree: WireTree): void {
|
||||
validatePluginRemoteTree(withUniqueViewIds(tree));
|
||||
}
|
||||
|
||||
type WorkingNode = {
|
||||
id: string;
|
||||
parentId: string | null;
|
||||
children: WorkingNode[];
|
||||
};
|
||||
|
||||
type RewriteDetach = {
|
||||
parentId: string;
|
||||
index: number;
|
||||
id: string;
|
||||
};
|
||||
|
||||
function collectSubtreeIds(node: WireNode, out: string[] = []): string[] {
|
||||
out.push(node.id);
|
||||
if (node.type === 1) {
|
||||
for (const child of node.children) collectSubtreeIds(child, out);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function buildWorkingNode(node: WireNode, parentId: string, nodes: Map<string, WorkingNode>): WorkingNode {
|
||||
const working: WorkingNode = { id: node.id, parentId, children: [] };
|
||||
nodes.set(node.id, working);
|
||||
if (node.type === 1) {
|
||||
for (const child of node.children) {
|
||||
working.children.push(buildWorkingNode(child, node.id, nodes));
|
||||
}
|
||||
}
|
||||
return working;
|
||||
}
|
||||
|
||||
function detachWorkingSubtree(node: WorkingNode, nodes: Map<string, WorkingNode>): void {
|
||||
nodes.delete(node.id);
|
||||
node.parentId = null;
|
||||
for (const child of node.children) detachWorkingSubtree(child, nodes);
|
||||
}
|
||||
|
||||
function hasAncestorInSet(startId: string, ids: Set<string>, nodes: Map<string, WorkingNode>): boolean {
|
||||
let cursor: string | null = startId;
|
||||
while (cursor !== null) {
|
||||
if (ids.has(cursor)) return true;
|
||||
cursor = nodes.get(cursor)?.parentId ?? null;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes a duplicate-only mutation batch so inserts referencing IDs already
|
||||
* attached in the tree first emit explicit removals from their previous parents.
|
||||
* Returns null if an insert would detach its own destination parent (cycle).
|
||||
*/
|
||||
function rewriteDuplicateInsertBatch(current: WireTree, batch: unknown[][]): unknown[][] | null {
|
||||
const root: WorkingNode = { id: '~', parentId: null, children: [] };
|
||||
const nodes = new Map<string, WorkingNode>([['~', root]]);
|
||||
for (const child of current.children) {
|
||||
root.children.push(buildWorkingNode(child, '~', nodes));
|
||||
}
|
||||
|
||||
const rewritten: unknown[][] = [];
|
||||
const rewriteDetaches: RewriteDetach[] = [];
|
||||
for (const record of batch) {
|
||||
const type = record[0];
|
||||
if (type === 0) {
|
||||
const parentId = record[1] as string;
|
||||
const node = record[2] as WireNode;
|
||||
let insertIndex = record[3] as number;
|
||||
const parent = nodes.get(parentId);
|
||||
if (!parent) {
|
||||
// Detached parent: RemoteReceiver drops this insert as a no-op.
|
||||
rewritten.push(record);
|
||||
continue;
|
||||
}
|
||||
|
||||
const subtreeIds = collectSubtreeIds(node);
|
||||
if (hasAncestorInSet(parentId, new Set(subtreeIds), nodes)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const existingId of subtreeIds) {
|
||||
const existing = nodes.get(existingId);
|
||||
if (!existing || existing.parentId === null) continue;
|
||||
const oldParent = nodes.get(existing.parentId);
|
||||
if (!oldParent) continue;
|
||||
const oldIndex = oldParent.children.indexOf(existing);
|
||||
if (oldIndex < 0) continue;
|
||||
|
||||
rewritten.push([1, oldParent.id, oldIndex]);
|
||||
rewriteDetaches.push({ parentId: oldParent.id, index: oldIndex, id: existing.id });
|
||||
oldParent.children.splice(oldIndex, 1);
|
||||
detachWorkingSubtree(existing, nodes);
|
||||
|
||||
if (oldParent.id === parentId) {
|
||||
if (oldIndex < insertIndex) {
|
||||
insertIndex -= 1;
|
||||
} else if (existing.id !== node.id && oldIndex > insertIndex) {
|
||||
insertIndex = oldIndex;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rewritten.push(insertIndex === record[3] ? record : [0, parentId, node, insertIndex]);
|
||||
const inserted = buildWorkingNode(node, parentId, nodes);
|
||||
if (insertIndex >= parent.children.length) {
|
||||
parent.children.push(inserted);
|
||||
} else {
|
||||
parent.children.splice(insertIndex, 0, inserted);
|
||||
}
|
||||
} else if (type === 1) {
|
||||
const parentId = record[1] as string;
|
||||
const removeIndex = record[2] as number;
|
||||
const exactMatchIndex = rewriteDetaches.findIndex(
|
||||
(detach) => detach.parentId === parentId && detach.index === removeIndex,
|
||||
);
|
||||
if (exactMatchIndex !== -1) {
|
||||
rewriteDetaches.splice(exactMatchIndex, 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
let smallerCount = 0;
|
||||
for (const detach of rewriteDetaches) {
|
||||
if (detach.parentId === parentId && detach.index < removeIndex) {
|
||||
smallerCount += 1;
|
||||
}
|
||||
}
|
||||
const remappedIndex = removeIndex - smallerCount;
|
||||
const parent = nodes.get(parentId);
|
||||
if (!parent) {
|
||||
if (smallerCount === 0) rewritten.push(record);
|
||||
continue;
|
||||
}
|
||||
if (remappedIndex < 0 || remappedIndex >= parent.children.length) {
|
||||
continue;
|
||||
}
|
||||
rewritten.push(remappedIndex === removeIndex ? record : [1, parentId, remappedIndex]);
|
||||
const [removed] = parent.children.splice(remappedIndex, 1);
|
||||
if (removed) detachWorkingSubtree(removed, nodes);
|
||||
for (const detach of rewriteDetaches) {
|
||||
if (detach.parentId === parentId && detach.index > removeIndex) {
|
||||
detach.index -= 1;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
rewritten.push(record);
|
||||
}
|
||||
}
|
||||
|
||||
return rewritten;
|
||||
}
|
||||
|
||||
/** Data-only staging area: untrusted changes are never applied directly to the host DOM. */
|
||||
export function createPluginRemoteTree() {
|
||||
const receiver = new RemoteReceiver();
|
||||
@@ -23,6 +191,16 @@ export function createPluginRemoteTree() {
|
||||
if (value.type === 3 || value.type === 8) return { id: value.id, type: value.type, data: value.data ?? '' };
|
||||
return { id: value.id, type: 1, element: value.element ?? '', attributes: Object.fromEntries(Object.entries(value.attributes ?? {}).filter(([, attribute]) => attribute !== null)), children: (value.children ?? []).map(project) };
|
||||
};
|
||||
const applyToScratch = (records: unknown[][]): WireTree => {
|
||||
const scratch = new RemoteReceiver();
|
||||
if (current.children.length > 0) {
|
||||
scratch.connection.mutate(
|
||||
current.children.map((child, index) => [0, '~', child, index]) as unknown as Parameters<typeof scratch.connection.mutate>[0],
|
||||
);
|
||||
}
|
||||
scratch.connection.mutate(records as unknown as Parameters<typeof scratch.connection.mutate>[0]);
|
||||
return { children: scratch.root.children.map(project) };
|
||||
};
|
||||
return {
|
||||
apply(input: unknown): WireTree {
|
||||
if (failed) throw new Error('Plugin view has been closed after an invalid update');
|
||||
@@ -31,16 +209,35 @@ export function createPluginRemoteTree() {
|
||||
// Ordinary DOM attribute mutations do not specify a channel. RemoteReceiver
|
||||
// defaults those to properties, so explicitly mark them as attributes.
|
||||
const batch = (input as unknown[][]).map((record) => record[0] === 3 && record.length === 4 ? [...record, 2] : record);
|
||||
receiver.connection.mutate(batch as unknown as Parameters<typeof receiver.connection.mutate>[0]);
|
||||
const next = { children: receiver.root.children.map(project) };
|
||||
validatePluginRemoteTree(next);
|
||||
let appliedBatch = batch;
|
||||
let next = applyToScratch(batch);
|
||||
try {
|
||||
validatePluginRemoteTree(next);
|
||||
} catch (error) {
|
||||
if (!isDuplicatePluginViewNodeError(error)) throw error;
|
||||
assertDuplicateOnlyPluginRemoteTree(next);
|
||||
const rewritten = rewriteDuplicateInsertBatch(current, batch);
|
||||
if (!rewritten) throw error;
|
||||
const rewrittenNext = applyToScratch(rewritten);
|
||||
try {
|
||||
validatePluginRemoteTree(rewrittenNext);
|
||||
} catch (rewrittenError) {
|
||||
if (isDuplicatePluginViewNodeError(rewrittenError)) assertDuplicateOnlyPluginRemoteTree(rewrittenNext);
|
||||
throw rewrittenError;
|
||||
}
|
||||
appliedBatch = rewritten;
|
||||
next = rewrittenNext;
|
||||
}
|
||||
receiver.connection.mutate(appliedBatch as unknown as Parameters<typeof receiver.connection.mutate>[0]);
|
||||
validatedTrees.add(next);
|
||||
current = next;
|
||||
return next;
|
||||
} catch (error) {
|
||||
failed = true;
|
||||
current = { children: [] };
|
||||
validatedTrees.add(current);
|
||||
if (!isDuplicatePluginViewNodeError(error)) {
|
||||
failed = true;
|
||||
current = { children: [] };
|
||||
validatedTrees.add(current);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -218,3 +218,52 @@ test('portForward.start surfaces live error status and message when tunnel start
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('views.open resolves visible contribution, triggers open without polluting context, and rejects missing/hidden views', async () => {
|
||||
const opened: Array<{ viewId: string; context?: Record<string, unknown>; params?: unknown }> = [];
|
||||
const queries: unknown[] = [];
|
||||
const ctx: PluginVaultDataContext = {
|
||||
...makeContext({}),
|
||||
viewOpenRuntime: {
|
||||
getPluginContributions: async (query) => {
|
||||
queries.push(query);
|
||||
return {
|
||||
locale: 'en',
|
||||
plugins: [{
|
||||
id: 'com.example.db',
|
||||
version: '1.0.0',
|
||||
displayName: 'Database',
|
||||
commands: [],
|
||||
keybindings: [],
|
||||
menus: [],
|
||||
settings: [],
|
||||
views: [
|
||||
{ id: 'com.example.db.workbench', title: 'Database', location: 'vault-page', visible: true },
|
||||
{ id: 'com.example.db.hidden', title: 'Hidden', location: 'vault-page', visible: false },
|
||||
],
|
||||
}],
|
||||
};
|
||||
},
|
||||
requestOpenPluginView: (detail) => { opened.push(detail); },
|
||||
},
|
||||
};
|
||||
|
||||
const result = await handlePluginVaultDataRequest(
|
||||
'views.open',
|
||||
{ viewId: 'com.example.db.workbench', location: 'vault-page' },
|
||||
ctx,
|
||||
);
|
||||
assert.deepEqual(result, { opened: true, focused: true, location: 'vault-page' });
|
||||
assert.deepEqual(queries[0], { context: { 'netcatty.surface': 'vault-page' } });
|
||||
assert.deepEqual(opened, [{ viewId: 'com.example.db.workbench' }]);
|
||||
|
||||
await assert.rejects(
|
||||
() => handlePluginVaultDataRequest('views.open', { viewId: 'com.example.db.hidden', location: 'vault-page' }, ctx),
|
||||
/not available/,
|
||||
);
|
||||
await assert.rejects(
|
||||
() => handlePluginVaultDataRequest('views.open', { viewId: 'com.example.db.missing', location: 'vault-page' }, ctx),
|
||||
/not available/,
|
||||
);
|
||||
assert.equal(opened.length, 1);
|
||||
});
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
applyPortForwardingRuntimeStatus,
|
||||
getPortForwardingRuntimeRules,
|
||||
} from './usePortForwardingState';
|
||||
import { requestOpenPluginView } from './usePluginViewLifecycle';
|
||||
|
||||
export interface PluginPortForwardRuntimeDeps {
|
||||
startPortForward?: typeof startPortForward;
|
||||
@@ -36,10 +37,16 @@ export interface PluginPortForwardRuntimeDeps {
|
||||
applyRuntimeStatus?: typeof applyPortForwardingRuntimeStatus;
|
||||
}
|
||||
|
||||
export interface PluginViewOpenRuntimeDeps {
|
||||
getPluginContributions?: NonNullable<ReturnType<typeof netcattyBridge.get>>['getPluginContributions'];
|
||||
requestOpenPluginView?: typeof requestOpenPluginView;
|
||||
}
|
||||
|
||||
export type PluginVaultDataContext = {
|
||||
getVault: () => AppVaultRuntime & ReturnType<AppVaultRuntime['readCurrentHostActionState']>;
|
||||
resources: PluginHostActionResources;
|
||||
portForwardRuntime?: PluginPortForwardRuntimeDeps;
|
||||
viewOpenRuntime?: PluginViewOpenRuntimeDeps;
|
||||
};
|
||||
|
||||
type PortForwardSummaryStatus = 'inactive' | 'connecting' | 'active' | 'error';
|
||||
@@ -472,6 +479,42 @@ export async function handlePluginVaultDataRequest(
|
||||
return { focused: true };
|
||||
}
|
||||
|
||||
case 'views.open': {
|
||||
const viewId = typeof payload.viewId === 'string' ? payload.viewId : '';
|
||||
const location = typeof payload.location === 'string' ? payload.location : '';
|
||||
if (!viewId) throw new Error('Plugin view ID is required');
|
||||
const queryContext = location === 'vault-page'
|
||||
? { 'netcatty.surface': 'vault-page' }
|
||||
: location === 'terminal-sidebar'
|
||||
? { 'netcatty.surface': 'terminal-sidebar' }
|
||||
: { 'netcatty.surface': 'view' };
|
||||
const getContributions = ctx.viewOpenRuntime?.getPluginContributions ?? netcattyBridge.get()?.getPluginContributions;
|
||||
if (!getContributions) {
|
||||
throw new Error('Plugin contributions are unavailable');
|
||||
}
|
||||
const snapshot = await getContributions({ context: queryContext });
|
||||
const resolved = snapshot.plugins
|
||||
.flatMap((plugin) => plugin.views)
|
||||
.find((view) => view.id === viewId && view.visible);
|
||||
if (!resolved) {
|
||||
throw new Error(`Plugin view is not available: ${viewId}`);
|
||||
}
|
||||
if (resolved.location === 'terminal-sidebar') {
|
||||
const sessionRuntime = getAppSessionRuntime();
|
||||
const activeTabId = activeTabStore.getActiveTabId();
|
||||
const isTerminalTab = Boolean(
|
||||
sessionRuntime?.sessions.some((s) => s.id === activeTabId)
|
||||
|| sessionRuntime?.workspaces.some((w) => w.id === activeTabId),
|
||||
);
|
||||
if (!isTerminalTab) {
|
||||
throw new Error('An active terminal tab is required to open a terminal sidebar view');
|
||||
}
|
||||
}
|
||||
const openView = ctx.viewOpenRuntime?.requestOpenPluginView ?? requestOpenPluginView;
|
||||
openView({ viewId: resolved.id });
|
||||
return { opened: true, focused: true, location: resolved.location };
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`Unsupported Vault data request: ${kind}`);
|
||||
}
|
||||
|
||||
@@ -60,3 +60,320 @@ test('empty first update holds loading briefly to prevent blank-frame flash then
|
||||
assert.equal(view.getSnapshot().loading, false, 'truly empty view finishes loading after grace window');
|
||||
store.dispose();
|
||||
});
|
||||
test('update and event failures warn concisely with error message before disposing without logging event payloads', async () => {
|
||||
const warns: unknown[][] = [];
|
||||
const originalWarn = console.warn;
|
||||
console.warn = (...args: unknown[]) => { warns.push(args); };
|
||||
try {
|
||||
const f1 = fixture();
|
||||
const store = new PluginViewSessions();
|
||||
const view1 = store.acquire('bad-seq', f1.bridge, request);
|
||||
f1.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: f1.opened[0].instanceId, sequence: 99, css: '', mutations: [] });
|
||||
assert.equal(view1.getSnapshot().error, true);
|
||||
assert.equal(warns.length, 1);
|
||||
assert.match(String(warns[0][0]), /Invalid plugin update order/);
|
||||
assert.ok(warns[0][1] instanceof Error);
|
||||
|
||||
const f2 = fixture();
|
||||
f2.bridge.sendHostDrawnPluginViewEvent = async () => { throw new Error('IPC channel closed'); };
|
||||
const view2 = store.acquire('bad-send', f2.bridge, request);
|
||||
view2.send({ type: 'input', nodeId: 'field', value: 'secret@example.com' });
|
||||
await Promise.resolve();
|
||||
assert.equal(view2.getSnapshot().error, true);
|
||||
assert.equal(warns.length, 2);
|
||||
assert.match(String(warns[1][0]), /IPC channel closed/);
|
||||
assert.doesNotMatch(warns[1].map(String).join(' '), /secret@example\.com/);
|
||||
store.dispose();
|
||||
} finally {
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
});
|
||||
test('recoverable duplicate node update applies as a move and publishes the new tree without warning', () => {
|
||||
const warns: unknown[][] = [];
|
||||
const originalWarn = console.warn;
|
||||
console.warn = (...args: unknown[]) => { warns.push(args); };
|
||||
try {
|
||||
const f = fixture();
|
||||
const store = new PluginViewSessions();
|
||||
const view = store.acquire('dup-move', f.bridge, request);
|
||||
const id = f.opened[0].instanceId;
|
||||
const initialNode = {
|
||||
id: 'row-1',
|
||||
type: 1 as const,
|
||||
element: 'div',
|
||||
attributes: { class: 'row' },
|
||||
children: [{ id: 'cell-1', type: 3 as const, data: 'alpha' }],
|
||||
};
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{display:flex}', mutations: [[0, '~', initialNode, 0]] });
|
||||
assert.equal(view.getSnapshot().loading, false);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, [initialNode]);
|
||||
|
||||
// Re-inserting an existing node (or wrapping it in a new parent without a remove)
|
||||
// is normalized as a move and published immediately with zero warnings.
|
||||
const movedNode = {
|
||||
id: 'group-1',
|
||||
type: 1 as const,
|
||||
element: 'section',
|
||||
attributes: { class: 'sorted' },
|
||||
children: [{
|
||||
id: 'row-1',
|
||||
type: 1 as const,
|
||||
element: 'div',
|
||||
attributes: { class: 'row' },
|
||||
children: [{ id: 'cell-1', type: 3 as const, data: 'alpha' }],
|
||||
}],
|
||||
};
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 2,
|
||||
css: '.sorted{color:blue}',
|
||||
mutations: [[0, '~', movedNode, 1]],
|
||||
} as Update);
|
||||
assert.equal(warns.length, 0);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.equal(view.getSnapshot().css.includes('blue'), true);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, [movedNode]);
|
||||
assert.equal(f.closes.length, 0);
|
||||
assert.equal(store.peek('dup-move'), view);
|
||||
|
||||
// A subsequent incremental update applies cleanly against the moved nodes.
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 3,
|
||||
css: '',
|
||||
cssUnchanged: true,
|
||||
mutations: [
|
||||
[2, 'cell-1', 'beta'],
|
||||
[0, '~', { id: 'row-2', type: 3, data: 'second' }, 1],
|
||||
],
|
||||
} as Update);
|
||||
assert.equal(warns.length, 0);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, [
|
||||
{
|
||||
...movedNode,
|
||||
children: [{ ...initialNode, children: [{ id: 'cell-1', type: 3, data: 'beta' }] }],
|
||||
},
|
||||
{ id: 'row-2', type: 3, data: 'second' },
|
||||
]);
|
||||
|
||||
// Forbidden mutations still dispose the session.
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 4,
|
||||
css: '',
|
||||
cssUnchanged: true,
|
||||
mutations: [[3, 'row-1', 'onclick', 'attack()']],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().error, true);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, []);
|
||||
store.dispose();
|
||||
} finally {
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
});
|
||||
|
||||
test('unrecoverable duplicate node update warns without failing the session and accepts subsequent valid updates', () => {
|
||||
const warns: unknown[][] = [];
|
||||
const originalWarn = console.warn;
|
||||
console.warn = (...args: unknown[]) => { warns.push(args); };
|
||||
try {
|
||||
const f = fixture();
|
||||
const store = new PluginViewSessions();
|
||||
const view = store.acquire('dup-recovery', f.bridge, request);
|
||||
const id = f.opened[0].instanceId;
|
||||
const initialNode = {
|
||||
id: 'row-1',
|
||||
type: 1 as const,
|
||||
element: 'div',
|
||||
attributes: { class: 'row' },
|
||||
children: [{ id: 'cell-1', type: 3 as const, data: 'alpha' }],
|
||||
};
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{display:flex}', mutations: [[0, '~', initialNode, 0]] });
|
||||
assert.equal(view.getSnapshot().loading, false);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, [initialNode]);
|
||||
|
||||
// Self-nesting cycle cannot be rewritten as a move; last-resort fallback preserves last good tree.
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 2,
|
||||
css: '',
|
||||
cssUnchanged: true,
|
||||
mutations: [[0, 'row-1', { id: 'row-1', type: 1, element: 'div', attributes: {}, children: [] }, 0]],
|
||||
} as Update);
|
||||
assert.equal(warns.length, 1);
|
||||
assert.match(String(warns[0][0]), /Duplicate view node/);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, [initialNode]);
|
||||
assert.equal(f.closes.length, 0);
|
||||
assert.equal(store.peek('dup-recovery'), view);
|
||||
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 3,
|
||||
css: '',
|
||||
cssUnchanged: true,
|
||||
mutations: [
|
||||
[2, 'cell-1', 'beta'],
|
||||
[0, '~', { id: 'row-2', type: 3, data: 'second' }, 1],
|
||||
],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, [
|
||||
{ ...initialNode, children: [{ id: 'cell-1', type: 3, data: 'beta' }] },
|
||||
{ id: 'row-2', type: 3, data: 'second' },
|
||||
]);
|
||||
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 4,
|
||||
css: '',
|
||||
cssUnchanged: true,
|
||||
mutations: [[3, 'row-1', 'onclick', 'attack()']],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().error, true);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, []);
|
||||
store.dispose();
|
||||
} finally {
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
});
|
||||
|
||||
test('pending CSS from a rejected unrecoverable duplicate update is published on the next accepted update', () => {
|
||||
const originalWarn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
const f = fixture();
|
||||
const store = new PluginViewSessions();
|
||||
const view = store.acquire('css-pending', f.bridge, request);
|
||||
const id = f.opened[0].instanceId;
|
||||
const node = { id: 'row-1', type: 1 as const, element: 'div', attributes: { class: 'row' }, children: [] };
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{color:red}', mutations: [[0, '~', node, 0]] });
|
||||
assert.equal(view.getSnapshot().css.includes('red'), true);
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 2,
|
||||
css: '.row{color:blue}',
|
||||
mutations: [[0, 'row-1', { id: 'row-1', type: 1, element: 'span', attributes: {}, children: [] }, 0]],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.equal(view.getSnapshot().css.includes('red'), true, 'rejected update does not publish CSS immediately');
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 3,
|
||||
css: '',
|
||||
cssUnchanged: true,
|
||||
mutations: [[3, 'row-1', 'class', 'ready']],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.equal(view.getSnapshot().css.includes('blue'), true, 'next accepted update publishes the stashed CSS');
|
||||
store.dispose();
|
||||
} finally {
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
});
|
||||
|
||||
test('explicit CSS matching the last committed value supersedes pending CSS', () => {
|
||||
const originalWarn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
const f = fixture();
|
||||
const store = new PluginViewSessions();
|
||||
const view = store.acquire('css-supersede', f.bridge, request);
|
||||
const id = f.opened[0].instanceId;
|
||||
const node = { id: 'row-1', type: 1 as const, element: 'div', attributes: { class: 'row' }, children: [] };
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{color:red}', mutations: [[0, '~', node, 0]] });
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 2,
|
||||
css: '.row{color:blue}',
|
||||
mutations: [[0, 'row-1', { id: 'row-1', type: 1, element: 'span', attributes: {}, children: [] }, 0]],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().css.includes('red'), true);
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 3,
|
||||
css: '.row{color:red}',
|
||||
mutations: [[3, 'row-1', 'class', 'ready']],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.equal(view.getSnapshot().css.includes('blue'), false);
|
||||
assert.equal(view.getSnapshot().css.includes('red'), true, 'explicit red supersedes pending blue');
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 4,
|
||||
css: '',
|
||||
cssUnchanged: true,
|
||||
mutations: [[3, 'row-1', 'class', 'again']],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().css.includes('red'), true);
|
||||
assert.equal(view.getSnapshot().css.includes('blue'), false);
|
||||
store.dispose();
|
||||
} finally {
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
});
|
||||
|
||||
test('omitted css preserves previous stylesheet and apply failures emit diagnostics', () => {
|
||||
const originalWarn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
const f = fixture();
|
||||
const diagnostics: Array<{ source?: string; message: string; extra?: Record<string, unknown> }> = [];
|
||||
const bridgeWithDiag = {
|
||||
...f.bridge,
|
||||
logDiagnostic: async (payload: { source?: string; message: string; extra?: Record<string, unknown> }) => {
|
||||
diagnostics.push(payload);
|
||||
return { success: true };
|
||||
},
|
||||
};
|
||||
const store = new PluginViewSessions();
|
||||
const view = store.acquire('diag-test', bridgeWithDiag, request);
|
||||
const id = f.opened[0].instanceId;
|
||||
const node = { id: 'n1', type: 1 as const, element: 'div', attributes: {}, children: [] };
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.n{display:flex}', mutations: [[0, '~', node, 0]] });
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 2, mutations: [[3, 'n1', 'class', 'n']] });
|
||||
assert.equal(view.getSnapshot().css.includes('display:flex'), true);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
|
||||
// Duplicate-node recoverable errors should emit at most one diagnostic per session.
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 3, mutations: [[0, 'n1', { id: 'n1', type: 1, element: 'span', attributes: {}, children: [] }, 0]] } as Update);
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 4, mutations: [[0, 'n1', { id: 'n1', type: 1, element: 'span', attributes: {}, children: [] }, 0]] } as Update);
|
||||
assert.equal(diagnostics.length, 1);
|
||||
assert.equal(diagnostics[0].extra?.kind, 'duplicate-node-update');
|
||||
|
||||
// Trigger an out-of-order sequence failure and verify diagnostic is logged.
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 99, mutations: [] });
|
||||
assert.equal(view.getSnapshot().error, true);
|
||||
assert.equal(diagnostics.length, 2);
|
||||
assert.equal(diagnostics[1].source, 'plugin-view');
|
||||
assert.match(diagnostics[1].message, /Invalid plugin update order/);
|
||||
store.dispose();
|
||||
} finally {
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
});
|
||||
@@ -1,9 +1,11 @@
|
||||
import { createPluginRemoteTree } from './pluginRemoteTree';
|
||||
import { createPluginRemoteTree, isDuplicatePluginViewNodeError } from './pluginRemoteTree';
|
||||
import { registerLoadedPluginViewSessions } from './pluginViewSessionRegistry';
|
||||
import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs';
|
||||
import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
|
||||
|
||||
type Bridge = Pick<NonNullable<ReturnType<typeof import('../../infrastructure/services/netcattyBridge').netcattyBridge.get>>, 'openHostDrawnPluginView' | 'closeHostDrawnPluginView' | 'onHostDrawnPluginViewUpdate' | 'onPluginViewClosed' | 'sendHostDrawnPluginViewEvent' | 'getPluginViewResource'>;
|
||||
type NetcattyBridgeApi = NonNullable<ReturnType<typeof import('../../infrastructure/services/netcattyBridge').netcattyBridge.get>>;
|
||||
type Bridge = Pick<NetcattyBridgeApi, 'openHostDrawnPluginView' | 'closeHostDrawnPluginView' | 'onHostDrawnPluginViewUpdate' | 'onPluginViewClosed' | 'sendHostDrawnPluginViewEvent' | 'getPluginViewResource'>
|
||||
& Partial<Pick<NetcattyBridgeApi, 'logDiagnostic'>>;
|
||||
export type PluginViewSnapshot = { tree: ReturnType<ReturnType<typeof createPluginRemoteTree>['snapshot']>; css: string; loading: boolean; error: boolean; settled: boolean };
|
||||
const empty = (): PluginViewSnapshot => ({ tree: { children: [] }, css: '', loading: true, error: false, settled: true });
|
||||
const EMPTY_FIRST_FRAME_GRACE_MS = 60;
|
||||
@@ -26,7 +28,10 @@ export class PluginViewSessions {
|
||||
const id = crypto.randomUUID();
|
||||
const tree = createPluginRemoteTree();
|
||||
let state = empty(); let sequence = 1; let eventId = 0; let disposed = false; let users = 0;
|
||||
let loggedDuplicateNode = false;
|
||||
let lastRawCss: string | null = null;
|
||||
let pendingCss: string | null = null;
|
||||
let pendingRawCss: string | null = null;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let emptyFrameTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const listeners = new Set<() => void>();
|
||||
@@ -42,14 +47,26 @@ export class PluginViewSessions {
|
||||
if (!bridge.openHostDrawnPluginView || !bridge.onHostDrawnPluginViewUpdate || !bridge.onPluginViewClosed) throw new Error('Plugin views unavailable');
|
||||
cleanup.push(bridge.onHostDrawnPluginViewUpdate((update) => {
|
||||
if (disposed || update.kind !== 'host-ui.update' || update.instanceId !== id || update.viewId !== request.viewId) return;
|
||||
let stagedCss: string | null = null;
|
||||
let stagedRawCss: string | null = null;
|
||||
try {
|
||||
if (update.sequence !== sequence++) throw new Error('Invalid plugin update order');
|
||||
const nextCss = update.cssUnchanged
|
||||
? state.css
|
||||
: (lastRawCss !== null && update.css === lastRawCss)
|
||||
? state.css
|
||||
: ((lastRawCss = update.css), validatePluginStylesheet(update.css));
|
||||
if (update.cssUnchanged || update.css === undefined) {
|
||||
// keep pending CSS, if any, for the nextCss fallback below
|
||||
} else if (lastRawCss !== null && update.css === lastRawCss) {
|
||||
// Explicit CSS equal to the last committed raw CSS supersedes any pending stylesheet.
|
||||
pendingCss = null;
|
||||
pendingRawCss = null;
|
||||
} else {
|
||||
stagedCss = validatePluginStylesheet(update.css);
|
||||
stagedRawCss = update.css;
|
||||
}
|
||||
const nextCss = stagedCss ?? pendingCss ?? state.css;
|
||||
const nextTree = tree.apply(update.mutations);
|
||||
if (stagedRawCss !== null) lastRawCss = stagedRawCss;
|
||||
else if (pendingRawCss !== null) lastRawCss = pendingRawCss;
|
||||
pendingCss = null;
|
||||
pendingRawCss = null;
|
||||
const settled = (update.acknowledgedEvent ?? 0) >= eventId;
|
||||
if (state.loading && !hasRenderableTreeContent(nextTree)) {
|
||||
// Hold the host loading surface briefly while an older SDK flushes its
|
||||
@@ -68,7 +85,34 @@ export class PluginViewSessions {
|
||||
emptyFrameTimer = undefined;
|
||||
}
|
||||
publish({ tree: nextTree, css: nextCss, loading: false, error: false, settled });
|
||||
} catch { dispose(true); }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.warn(`[PluginViewSession] Failed to apply update for ${request.viewId}: ${message}`, error);
|
||||
const duplicateNode = isDuplicatePluginViewNodeError(error);
|
||||
if (!duplicateNode || !loggedDuplicateNode) {
|
||||
if (duplicateNode) loggedDuplicateNode = true;
|
||||
void bridge.logDiagnostic?.({
|
||||
source: 'plugin-view',
|
||||
message: `Failed to apply update for ${request.viewId}: ${message}`,
|
||||
extra: {
|
||||
kind: duplicateNode ? 'duplicate-node-update' : 'apply-update-failed',
|
||||
viewId: request.viewId,
|
||||
sequence: update.sequence,
|
||||
mutationCount: Array.isArray(update.mutations) ? update.mutations.length : null,
|
||||
},
|
||||
}).catch(() => {});
|
||||
}
|
||||
// Recoverable duplicate-only batches are normalized as moves in
|
||||
// createPluginRemoteTree(); only unrecoverable duplicates reach here.
|
||||
if (duplicateNode) {
|
||||
if (stagedCss !== null && stagedRawCss !== null) {
|
||||
pendingCss = stagedCss;
|
||||
pendingRawCss = stagedRawCss;
|
||||
}
|
||||
return;
|
||||
}
|
||||
dispose(true);
|
||||
}
|
||||
}));
|
||||
cleanup.push(bridge.onPluginViewClosed((event) => { if (event.instanceId === id) dispose(true); }));
|
||||
void bridge.openHostDrawnPluginView({ ...request, instanceId: id }).then(() => {
|
||||
@@ -100,7 +144,18 @@ export class PluginViewSessions {
|
||||
send: (event: HostDrawnViewEvent) => {
|
||||
if (disposed || users === 0) return;
|
||||
publish({ ...state, settled: false });
|
||||
void bridge.sendHostDrawnPluginViewEvent?.(id, { ...event, eventId: ++eventId }).catch(() => dispose(true));
|
||||
void bridge.sendHostDrawnPluginViewEvent?.(id, { ...event, eventId: ++eventId }).catch((error) => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.warn(`[PluginViewSession] Failed to send event for ${request.viewId}: ${message}`);
|
||||
if (!disposed) {
|
||||
void bridge.logDiagnostic?.({
|
||||
source: 'plugin-view',
|
||||
message: `Failed to send event for ${request.viewId}: ${message}`,
|
||||
extra: { kind: 'send-event-failed', viewId: request.viewId, eventType: event.type },
|
||||
}).catch(() => {});
|
||||
}
|
||||
dispose(true);
|
||||
});
|
||||
},
|
||||
dispose,
|
||||
};
|
||||
|
||||
@@ -25,6 +25,7 @@ export type SettingsChromeSnapshot = {
|
||||
windowOpacity: number;
|
||||
showSftpTab: boolean;
|
||||
showHostTreeSidebar: boolean;
|
||||
removeTopTabsDragArea: boolean;
|
||||
showRecentHosts: boolean;
|
||||
hostClickBehavior: HostClickBehavior;
|
||||
showOnlyUngroupedHostsInRoot: boolean;
|
||||
@@ -59,6 +60,7 @@ export const DEFAULT_SETTINGS_CHROME_SNAPSHOT: SettingsChromeSnapshot = Object.f
|
||||
windowOpacity: 1,
|
||||
showSftpTab: true,
|
||||
showHostTreeSidebar: true,
|
||||
removeTopTabsDragArea: false,
|
||||
showRecentHosts: true,
|
||||
hostClickBehavior: 'connect',
|
||||
showOnlyUngroupedHostsInRoot: false,
|
||||
@@ -86,6 +88,7 @@ export function settingsChromeSnapshotsEqual(
|
||||
&& a.windowOpacity === b.windowOpacity
|
||||
&& a.showSftpTab === b.showSftpTab
|
||||
&& a.showHostTreeSidebar === b.showHostTreeSidebar
|
||||
&& a.removeTopTabsDragArea === b.removeTopTabsDragArea
|
||||
&& a.showRecentHosts === b.showRecentHosts
|
||||
&& a.hostClickBehavior === b.hostClickBehavior
|
||||
&& a.showOnlyUngroupedHostsInRoot === b.showOnlyUngroupedHostsInRoot
|
||||
|
||||
@@ -137,6 +137,7 @@ export type { HostClickBehavior } from '../../domain/hostClickBehavior';
|
||||
export const DEFAULT_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT = false;
|
||||
export const DEFAULT_SHOW_SFTP_TAB = true;
|
||||
export const DEFAULT_SHOW_HOST_TREE_SIDEBAR = true;
|
||||
export const DEFAULT_REMOVE_TOP_TABS_DRAG_AREA = false;
|
||||
export const DEFAULT_SHELL_ONLY_TAB_NUMBER_SHORTCUTS = false;
|
||||
export const DEFAULT_SHOW_TAB_NUMBER_BADGES = true;
|
||||
export const DEFAULT_DISABLE_TERMINAL_FONT_ZOOM = false;
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
STORAGE_KEY_HOST_CLICK_BEHAVIOR,
|
||||
STORAGE_KEY_SHOW_SFTP_TAB,
|
||||
STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR,
|
||||
STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA,
|
||||
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN,
|
||||
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
|
||||
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN,
|
||||
@@ -136,6 +137,7 @@ interface UseSettingsStorageSyncParams {
|
||||
showOnlyUngroupedHostsInRoot: boolean;
|
||||
showSftpTab: boolean;
|
||||
showHostTreeSidebar: boolean;
|
||||
removeTopTabsDragArea: boolean;
|
||||
terminalSidePanelAutoOpen: boolean;
|
||||
terminalSidePanelAutoOpenTab: TerminalSidePanelAutoOpenTab;
|
||||
localShellSidePanelAutoOpen: boolean;
|
||||
@@ -194,6 +196,7 @@ interface UseSettingsStorageSyncParams {
|
||||
setShowOnlyUngroupedHostsInRootState: Dispatch<SetStateAction<boolean>>;
|
||||
setShowSftpTabState: Dispatch<SetStateAction<boolean>>;
|
||||
setShowHostTreeSidebarState: Dispatch<SetStateAction<boolean>>;
|
||||
setRemoveTopTabsDragAreaState: Dispatch<SetStateAction<boolean>>;
|
||||
setTerminalSidePanelAutoOpenState: Dispatch<SetStateAction<boolean>>;
|
||||
setTerminalSidePanelAutoOpenTabState: Dispatch<SetStateAction<TerminalSidePanelAutoOpenTab>>;
|
||||
setLocalShellSidePanelAutoOpenState: Dispatch<SetStateAction<boolean>>;
|
||||
@@ -238,7 +241,7 @@ export function useSettingsStorageSync({
|
||||
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
|
||||
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
|
||||
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, removeTopTabsDragArea, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
|
||||
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
|
||||
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
|
||||
@@ -249,7 +252,7 @@ export function useSettingsStorageSync({
|
||||
setFollowAppTerminalThemeState, setTerminalFontFamilyId, setTerminalFontSize,
|
||||
setSftpDoubleClickBehavior, setSftpAutoSync, setSftpShowHiddenFiles,
|
||||
setSftpUseCompressedUpload, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode,
|
||||
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
|
||||
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setRemoveTopTabsDragAreaState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
|
||||
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled,
|
||||
setRemoteDesktopAutoRecordState, setRemoteDesktopRecordingFpsState, setRemoteDesktopRecordingIncludeAudioState, setRemoteDesktopRecordingMaxMbState, setRemoteDesktopRecordingRetentionDaysState,
|
||||
setSshDebugLogsEnabled, setSshDeepLinkEnabledState, setJmsDeepLinkEnabledState, setJumpServerRdpLaunchModeState, setExplorerContextMenuEnabledState,
|
||||
@@ -266,7 +269,7 @@ export function useSettingsStorageSync({
|
||||
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
|
||||
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
|
||||
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, removeTopTabsDragArea, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
|
||||
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
|
||||
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
|
||||
@@ -278,7 +281,7 @@ export function useSettingsStorageSync({
|
||||
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
|
||||
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
|
||||
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, removeTopTabsDragArea, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
|
||||
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
|
||||
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
|
||||
@@ -548,6 +551,12 @@ export function useSettingsStorageSync({
|
||||
setShowHostTreeSidebarState(newValue);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA && e.newValue !== null) {
|
||||
const newValue = e.newValue === 'true';
|
||||
if (newValue !== s.removeTopTabsDragArea) {
|
||||
setRemoveTopTabsDragAreaState(newValue);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN && e.newValue !== null) {
|
||||
const newValue = e.newValue === 'true';
|
||||
if (newValue !== s.terminalSidePanelAutoOpen) {
|
||||
@@ -701,6 +710,7 @@ export function useSettingsStorageSync({
|
||||
setSftpSkipUnchanged,
|
||||
setShowOnlyUngroupedHostsInRootState,
|
||||
setShowHostTreeSidebarState,
|
||||
setRemoveTopTabsDragAreaState,
|
||||
setTerminalSidePanelAutoOpenState,
|
||||
setTerminalSidePanelAutoOpenTabState,
|
||||
setLocalShellSidePanelAutoOpenState,
|
||||
|
||||
@@ -1,21 +1,38 @@
|
||||
import {
|
||||
buildSftpDownloadDialogDirectoryOptions,
|
||||
normalizeSftpDefaultDownloadDirectory,
|
||||
type SftpDownloadDialogDirectoryOptions,
|
||||
} from "../../../domain/sftpDownloadLocation";
|
||||
import { STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR } from "../../../infrastructure/config/storageKeys";
|
||||
import {
|
||||
STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR,
|
||||
STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR,
|
||||
} from "../../../infrastructure/config/storageKeys";
|
||||
import { localStorageAdapter } from "../../../infrastructure/persistence/localStorageAdapter";
|
||||
|
||||
/**
|
||||
* Read the device-local default download folder at call time so every SFTP
|
||||
* Read the device-local download folders at call time so every SFTP
|
||||
* surface (main view, terminal side panel, other windows) sees the latest
|
||||
* value without threading it through props.
|
||||
*/
|
||||
export const getSftpDownloadDialogDirectoryOptions = (): SftpDownloadDialogDirectoryOptions => {
|
||||
let stored: string | null = null;
|
||||
let lastUsed: string | null = null;
|
||||
try {
|
||||
stored = localStorageAdapter.readString(STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR);
|
||||
lastUsed = localStorageAdapter.readString(STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR);
|
||||
} catch {
|
||||
// Storage unavailable (non-browser host); fall back to system Downloads.
|
||||
}
|
||||
return buildSftpDownloadDialogDirectoryOptions(stored);
|
||||
return buildSftpDownloadDialogDirectoryOptions(stored, lastUsed);
|
||||
};
|
||||
|
||||
/** Remember a confirmed download destination without changing the setting. */
|
||||
export const rememberSftpDownloadDirectory = (directory: string): void => {
|
||||
const normalized = normalizeSftpDefaultDownloadDirectory(directory);
|
||||
if (!normalized) return;
|
||||
try {
|
||||
localStorageAdapter.writeString(STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR, normalized);
|
||||
} catch {
|
||||
// Unavailable storage must not interrupt the download.
|
||||
}
|
||||
};
|
||||
@@ -1022,6 +1022,9 @@ export const useSftpConnections = ({
|
||||
id: connectionId,
|
||||
hostId: host.id,
|
||||
hostLabel: host.label,
|
||||
hostname: host.hostname,
|
||||
port: host.port,
|
||||
username: host.username,
|
||||
isLocal: false,
|
||||
status: "connecting",
|
||||
currentPath: normalizedCachedStartPath,
|
||||
|
||||
@@ -47,6 +47,7 @@ test('Win32 adapters confirm actual native cwd and reject stale revisions or for
|
||||
publish: value => terminalCwdStore.setCwd(id, value, 'backend-strict'),
|
||||
});
|
||||
t.after(() => controller.dispose());
|
||||
assert.equal(await controller.refresh(), cwd);
|
||||
const revision = terminalCwdStore.getSessionRevision(id);
|
||||
terminalCwdStore.setCwd(id, 'C:\\other', 'backend-strict');
|
||||
terminalCwdStore.setCwd(id, 'C:\\base', 'backend-strict');
|
||||
@@ -207,7 +208,7 @@ for (const probe of ['fails', 'stalls'] as const) {
|
||||
t.after(() => controller.dispose());
|
||||
await controller.change('/next', new AbortController().signal, () => {});
|
||||
assert.deepEqual(writes, ["cd -- '/next'\r"]);
|
||||
assert.equal(controller.hasConfirmedCwd(), true);
|
||||
assert.equal(controller.getConfirmedCwd(), '/next');
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { DirectoryPickerError, directoryChangeCommand, isDirectoryPath, COMPLETE_DIRECTORY_CAPABILITIES, type DirectoryCapabilities } from '../../domain/directoryPicker';
|
||||
import { sameDirectoryPath, type DirectoryTarget } from '../../domain/directoryPath';
|
||||
import { DirectoryPickerError, directoryChangeCommand, COMPLETE_DIRECTORY_CAPABILITIES, type DirectoryCapabilities } from '../../domain/directoryPicker';
|
||||
import { isAbsoluteDirectoryPath, sameDirectoryPath, type DirectoryTarget } from '../../domain/directoryPath';
|
||||
import type { TerminalDirectoryIO } from '../../infrastructure/services/terminalDirectory';
|
||||
import { terminalCwdStore } from './terminalCwdStore';
|
||||
|
||||
@@ -17,21 +17,32 @@ export function createTerminalDirectoryController(options: {
|
||||
capabilities?: DirectoryCapabilities;
|
||||
buildChangeCommand?: (path: string) => string | null;
|
||||
trustOsc7?: boolean;
|
||||
localPosixSessionId?: string;
|
||||
}) {
|
||||
const target = Object.freeze({ ...options.target ?? { authority: `session:${options.sessionId}`, pathFlavor: 'posix' as const } });
|
||||
const capabilities = Object.freeze({ ...options.capabilities ?? COMPLETE_DIRECTORY_CAPABILITIES });
|
||||
const trustsOsc7 = target.pathFlavor === 'posix' && options.trustOsc7 !== false;
|
||||
const valid = (path: string | null | undefined): path is string => isDirectoryPath(path, target.pathFlavor);
|
||||
const valid = (path: string | null | undefined): path is string => isAbsoluteDirectoryPath(path, target.pathFlavor);
|
||||
const same = (a: string, b: string) => sameDirectoryPath(a, b, target.pathFlavor);
|
||||
let disposed = false;
|
||||
let changing = false;
|
||||
let confirmed = false;
|
||||
let verifiedCwd: string | null = null;
|
||||
const cwdListeners = new Set<() => void>();
|
||||
const notifyCwd = () => cwdListeners.forEach(listener => listener());
|
||||
let refreshing: Promise<string> | null = null;
|
||||
let refreshAgain = false;
|
||||
let cwdError: DirectoryPickerError | null = null;
|
||||
const lifetime = new AbortController();
|
||||
const current = () => !disposed && options.isCurrent();
|
||||
function getConfirmedCwd(): string | null {
|
||||
if (!current() || !capabilities.readCwd) return null;
|
||||
const cwd = terminalCwdStore.getCwd(options.sessionId);
|
||||
const source = terminalCwdStore.getSource(options.sessionId);
|
||||
if (source === 'stale') return null;
|
||||
if (trustsOsc7 && source === 'osc7' && valid(cwd)) return cwd;
|
||||
if (options.trustOsc7 === false && target.pathFlavor === 'posix') return verifiedCwd;
|
||||
return verifiedCwd !== null && cwd === verifiedCwd ? verifiedCwd : null;
|
||||
}
|
||||
function check(signal?: AbortSignal) {
|
||||
if (!current() || signal?.aborted) throw new DirectoryPickerError('unavailable');
|
||||
}
|
||||
@@ -69,7 +80,7 @@ export function createTerminalDirectoryController(options: {
|
||||
// events and picker remounts. Only a cd submission may probe past its own
|
||||
// pre-write report while waiting for fresh confirmation.
|
||||
const reported = activeShellCwd();
|
||||
if (reported) { confirmed = true; cwdError = null; return reported; }
|
||||
if (reported) { cwdError = null; return reported; }
|
||||
if (refreshing) {
|
||||
// Output may settle while a pre-cd query is still in flight. Keep one
|
||||
// follow-up query so that its older result cannot be the last update.
|
||||
@@ -83,10 +94,10 @@ export function createTerminalDirectoryController(options: {
|
||||
if (!valid(cwd)) throw new DirectoryPickerError('unknown');
|
||||
} catch (error) {
|
||||
if (current() && !trustsOsc7) {
|
||||
confirmed = false;
|
||||
verifiedCwd = null;
|
||||
cwdError = error instanceof DirectoryPickerError ? error : new DirectoryPickerError('unknown');
|
||||
options.publish('');
|
||||
notifyCwd();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
@@ -94,12 +105,12 @@ export function createTerminalDirectoryController(options: {
|
||||
const reported = activeShellCwd();
|
||||
const live = terminalCwdStore.getCwd(options.sessionId);
|
||||
const verifiedCwdChanged = verifiedCwd !== cwd;
|
||||
confirmed = true;
|
||||
verifiedCwd = cwd;
|
||||
cwdError = null;
|
||||
if (reported) return reported;
|
||||
if (live !== cwd || terminalCwdStore.getSource(options.sessionId) === 'stale'
|
||||
|| (options.trustOsc7 === false && verifiedCwdChanged)) options.publish(cwd);
|
||||
|| verifiedCwdChanged) options.publish(cwd);
|
||||
if (verifiedCwdChanged) notifyCwd();
|
||||
return cwd;
|
||||
})();
|
||||
refreshing = pending;
|
||||
@@ -126,7 +137,7 @@ export function createTerminalDirectoryController(options: {
|
||||
check(signal);
|
||||
if (!valid(canonical)) throw new DirectoryPickerError('unsupportedPath');
|
||||
ready(); // The shell can become busy while resolving a remote symlink.
|
||||
if (expectedCwd && (options.trustOsc7 === false ? verifiedCwd : terminalCwdStore.getCwd(options.sessionId)) !== expectedCwd) throw new DirectoryPickerError('unavailable');
|
||||
if (expectedCwd && getConfirmedCwd() !== expectedCwd) throw new DirectoryPickerError('unavailable');
|
||||
if (expectedRevision !== undefined && terminalCwdStore.getSessionRevision(options.sessionId) !== expectedRevision) throw new DirectoryPickerError('unavailable');
|
||||
const submittedRevision = terminalCwdStore.getSessionRevision(options.sessionId);
|
||||
options.io.write(command + '\r');
|
||||
@@ -172,17 +183,23 @@ export function createTerminalDirectoryController(options: {
|
||||
};
|
||||
await Promise.race([confirmFromProbe(), confirmFromOsc7()]);
|
||||
check(signal);
|
||||
confirmed = true;
|
||||
} finally { confirmationFinished = true; changing = false; }
|
||||
}
|
||||
return {
|
||||
target,
|
||||
localPosixSessionId: options.localPosixSessionId,
|
||||
capabilities,
|
||||
trustsOsc7,
|
||||
getVerifiedCwd: () => verifiedCwd,
|
||||
getConfirmedCwd,
|
||||
subscribeCwd(listener: () => void) {
|
||||
const unsubscribe = terminalCwdStore.subscribe(listener);
|
||||
cwdListeners.add(listener);
|
||||
return () => {
|
||||
unsubscribe();
|
||||
cwdListeners.delete(listener);
|
||||
};
|
||||
},
|
||||
getCwdError: () => cwdError?.code ?? null,
|
||||
refresh: () => refresh(),
|
||||
hasConfirmedCwd: () => confirmed,
|
||||
async home() {
|
||||
check();
|
||||
const result = await bounded(options.io.home?.() ?? Promise.resolve(null));
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { TerminalDirectoryController } from './terminalDirectoryController'
|
||||
|
||||
const sessions = new Map<string, TerminalDirectoryController>();
|
||||
const consumers = new Map<string, number>();
|
||||
const refreshListeners = new Map<string, Set<() => void>>();
|
||||
const scheduledRefreshes = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
const OUTPUT_SETTLE_MS = 150;
|
||||
|
||||
@@ -36,10 +37,24 @@ export function observeTerminalDirectory(id: string) {
|
||||
else { consumers.delete(id); cancelScheduledRefresh(id); }
|
||||
};
|
||||
}
|
||||
export function subscribeTerminalDirectoryRefresh(id: string, listener: () => void) {
|
||||
const listeners = refreshListeners.get(id) ?? new Set<() => void>();
|
||||
listeners.add(listener);
|
||||
refreshListeners.set(id, listeners);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
if (!listeners.size) refreshListeners.delete(id);
|
||||
};
|
||||
}
|
||||
|
||||
/** Called by the existing command completion path, only while chips are visible. */
|
||||
export function refreshObservedTerminalDirectory(id: string) {
|
||||
cancelScheduledRefresh(id);
|
||||
if (consumers.has(id)) void sessions.get(id)?.refresh().catch(() => {});
|
||||
const controller = consumers.has(id) ? sessions.get(id) : undefined;
|
||||
if (!controller) return;
|
||||
void controller.refresh().then(() => {
|
||||
if (sessions.get(id) === controller) refreshListeners.get(id)?.forEach(listener => listener());
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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()));
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
import {
|
||||
STORAGE_KEY_AI_PROVIDERS,
|
||||
@@ -19,6 +19,8 @@ import {
|
||||
STORAGE_KEY_AI_WEB_SEARCH,
|
||||
STORAGE_KEY_AI_QUICK_MESSAGES,
|
||||
STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION,
|
||||
STORAGE_KEY_AI_AUTO_LLM_TITLE,
|
||||
STORAGE_KEY_AI_TITLE_MODEL,
|
||||
} from '../../infrastructure/config/storageKeys';
|
||||
import type { AIQuickMessage } from '../../infrastructure/ai/quickMessages';
|
||||
import { sanitizeQuickMessages } from '../../infrastructure/ai/quickMessages';
|
||||
@@ -46,6 +48,7 @@ import {
|
||||
DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
normalizeAiToolOutputMaxChars,
|
||||
} from '../../domain/aiToolOutputLimit';
|
||||
import type { TitleModelConfig } from '../../domain/aiSessionTitle';
|
||||
import { AI_STATE_CHANGED_EVENT, emitAIStateChanged } from './aiStateEvents';
|
||||
import { getAIBridge } from './aiStateSnapshots';
|
||||
import { useStoredBoolean } from './useStoredBoolean';
|
||||
@@ -54,6 +57,25 @@ import {
|
||||
readCommandBlocklistSetting,
|
||||
} from './commandBlocklistSettings';
|
||||
|
||||
export type { TitleModelConfig };
|
||||
|
||||
function readTitleModelSetting(): TitleModelConfig | null {
|
||||
const stored = localStorageAdapter.read<unknown>(STORAGE_KEY_AI_TITLE_MODEL);
|
||||
if (!stored || typeof stored !== 'object') return null;
|
||||
const providerId = (stored as TitleModelConfig).providerId;
|
||||
const modelId = (stored as TitleModelConfig).modelId;
|
||||
return typeof providerId === 'string' && providerId.trim()
|
||||
&& typeof modelId === 'string' && modelId.trim()
|
||||
? { providerId: providerId.trim(), modelId: modelId.trim() }
|
||||
: null;
|
||||
}
|
||||
|
||||
function readAgentStringMap(key: string): Record<string, string> {
|
||||
const stored = localStorageAdapter.read<unknown>(key);
|
||||
if (!stored || typeof stored !== 'object' || Array.isArray(stored)) return {};
|
||||
return stored as Record<string, string>;
|
||||
}
|
||||
|
||||
function readPermissionMode(): AIPermissionMode {
|
||||
const stored = localStorageAdapter.readString(STORAGE_KEY_AI_PERMISSION_MODE);
|
||||
if (stored === 'observer' || stored === 'confirm' || stored === 'auto') return stored;
|
||||
@@ -150,6 +172,25 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
|
||||
const [quickMessages, setQuickMessagesRaw] = useState<AIQuickMessage[]>(() =>
|
||||
sanitizeQuickMessages(localStorageAdapter.read<unknown>(STORAGE_KEY_AI_QUICK_MESSAGES)),
|
||||
);
|
||||
const [autoLlmTitle, setAutoLlmTitle] = useStoredBoolean(STORAGE_KEY_AI_AUTO_LLM_TITLE, true);
|
||||
const [titleModel, setTitleModelRaw] = useState<TitleModelConfig | null>(() =>
|
||||
readTitleModelSetting(),
|
||||
);
|
||||
const titleModelRef = useRef(titleModel);
|
||||
titleModelRef.current = titleModel;
|
||||
|
||||
const setTitleModel = useCallback((config: TitleModelConfig | null) => {
|
||||
const normalized = config
|
||||
&& typeof config.providerId === 'string' && config.providerId.trim()
|
||||
&& typeof config.modelId === 'string' && config.modelId.trim()
|
||||
? { providerId: config.providerId.trim(), modelId: config.modelId.trim() }
|
||||
: null;
|
||||
titleModelRef.current = normalized;
|
||||
setTitleModelRaw(normalized);
|
||||
if (normalized) localStorageAdapter.write(STORAGE_KEY_AI_TITLE_MODEL, normalized);
|
||||
else localStorageAdapter.remove(STORAGE_KEY_AI_TITLE_MODEL);
|
||||
emitAIStateChanged(STORAGE_KEY_AI_TITLE_MODEL);
|
||||
}, []);
|
||||
|
||||
const setProviders = useCallback((value: ProviderConfig[] | ((prev: ProviderConfig[]) => ProviderConfig[])) => {
|
||||
setProvidersRaw((prev) => {
|
||||
@@ -183,6 +224,9 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
|
||||
localStorageAdapter.writeString(STORAGE_KEY_AI_ACTIVE_PROVIDER, '');
|
||||
return '';
|
||||
});
|
||||
if (titleModelRef.current?.providerId === id) {
|
||||
setTitleModel(null);
|
||||
}
|
||||
|
||||
if (onRemoveProvider) {
|
||||
onRemoveProvider(id);
|
||||
@@ -196,11 +240,13 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
|
||||
const cleanup = removeProviderReferences(id, agentProviderMap, agentModelMap);
|
||||
if (cleanup.providerMapChanged) {
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_PROVIDER_MAP, cleanup.agentProviderMap);
|
||||
emitAIStateChanged(STORAGE_KEY_AI_AGENT_PROVIDER_MAP);
|
||||
}
|
||||
if (cleanup.modelMapChanged) {
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_MODEL_MAP, cleanup.agentModelMap);
|
||||
emitAIStateChanged(STORAGE_KEY_AI_AGENT_MODEL_MAP);
|
||||
}
|
||||
}, [onRemoveProvider, setProviders]);
|
||||
}, [onRemoveProvider, setProviders, setTitleModel]);
|
||||
|
||||
const setActiveProviderId = useCallback((id: string) => {
|
||||
setActiveProviderIdRaw(id);
|
||||
@@ -375,6 +421,9 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
|
||||
case STORAGE_KEY_AI_QUICK_MESSAGES:
|
||||
setQuickMessagesRaw(sanitizeQuickMessages(localStorageAdapter.read<unknown>(STORAGE_KEY_AI_QUICK_MESSAGES)));
|
||||
break;
|
||||
case STORAGE_KEY_AI_TITLE_MODEL:
|
||||
setTitleModelRaw(readTitleModelSetting());
|
||||
break;
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[useAISettingsState] Failed to process AI settings storage change', key, err);
|
||||
@@ -438,6 +487,10 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
|
||||
setWebSearchConfig,
|
||||
quickMessages,
|
||||
setQuickMessages,
|
||||
autoLlmTitle,
|
||||
setAutoLlmTitle,
|
||||
titleModel,
|
||||
setTitleModel,
|
||||
}), [
|
||||
providers,
|
||||
setProviders,
|
||||
@@ -471,6 +524,10 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
|
||||
setWebSearchConfig,
|
||||
quickMessages,
|
||||
setQuickMessages,
|
||||
autoLlmTitle,
|
||||
setAutoLlmTitle,
|
||||
titleModel,
|
||||
setTitleModel,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -486,6 +543,12 @@ export function useAISettingsState() {
|
||||
STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION,
|
||||
true,
|
||||
);
|
||||
const [agentProviderMap, setAgentProviderMapRaw] = useState<Record<string, string>>(() =>
|
||||
readAgentStringMap(STORAGE_KEY_AI_AGENT_PROVIDER_MAP),
|
||||
);
|
||||
const [agentModelMap, setAgentModelMapRaw] = useState<Record<string, string>>(() =>
|
||||
readAgentStringMap(STORAGE_KEY_AI_AGENT_MODEL_MAP),
|
||||
);
|
||||
|
||||
const setAiSessionMessageCap = useCallback((value: number) => {
|
||||
const normalizedValue = normalizeAiSessionMessageCap(value);
|
||||
@@ -494,23 +557,32 @@ export function useAISettingsState() {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const syncMessageCap = (key: string | null) => {
|
||||
if (key !== STORAGE_KEY_AI_SESSION_MESSAGE_CAP) return;
|
||||
const syncSettingsOnlyKey = (key: string | null) => {
|
||||
try {
|
||||
setAiSessionMessageCapRaw(
|
||||
normalizeAiSessionMessageCap(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP)
|
||||
?? DEFAULT_AI_SESSION_MESSAGE_CAP,
|
||||
),
|
||||
);
|
||||
switch (key) {
|
||||
case STORAGE_KEY_AI_SESSION_MESSAGE_CAP:
|
||||
setAiSessionMessageCapRaw(
|
||||
normalizeAiSessionMessageCap(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP)
|
||||
?? DEFAULT_AI_SESSION_MESSAGE_CAP,
|
||||
),
|
||||
);
|
||||
break;
|
||||
case STORAGE_KEY_AI_AGENT_PROVIDER_MAP:
|
||||
setAgentProviderMapRaw(readAgentStringMap(STORAGE_KEY_AI_AGENT_PROVIDER_MAP));
|
||||
break;
|
||||
case STORAGE_KEY_AI_AGENT_MODEL_MAP:
|
||||
setAgentModelMapRaw(readAgentStringMap(STORAGE_KEY_AI_AGENT_MODEL_MAP));
|
||||
break;
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[useAISettingsState] Failed to process AI settings storage change', key, err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleStorage = (event: StorageEvent) => syncMessageCap(event.key);
|
||||
const handleStorage = (event: StorageEvent) => syncSettingsOnlyKey(event.key);
|
||||
const handleLocalStateChanged = (event: Event) => {
|
||||
syncMessageCap((event as CustomEvent<{ key?: string }>).detail?.key ?? null);
|
||||
syncSettingsOnlyKey((event as CustomEvent<{ key?: string }>).detail?.key ?? null);
|
||||
};
|
||||
|
||||
window.addEventListener('storage', handleStorage);
|
||||
@@ -527,11 +599,15 @@ export function useAISettingsState() {
|
||||
setAiSessionMessageCap,
|
||||
showTerminalSelectionAIAction,
|
||||
setShowTerminalSelectionAIAction,
|
||||
agentProviderMap,
|
||||
agentModelMap,
|
||||
}), [
|
||||
shared,
|
||||
aiSessionMessageCap,
|
||||
setAiSessionMessageCap,
|
||||
showTerminalSelectionAIAction,
|
||||
setShowTerminalSelectionAIAction,
|
||||
agentProviderMap,
|
||||
agentModelMap,
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import React, { act } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { JSDOM } from 'jsdom';
|
||||
|
||||
import type { AISession, ProviderConfig } from '../../infrastructure/ai/types.ts';
|
||||
import {
|
||||
STORAGE_KEY_AI_ACTIVE_PROVIDER,
|
||||
STORAGE_KEY_AI_AGENT_MODEL_MAP,
|
||||
STORAGE_KEY_AI_AGENT_PROVIDER_MAP,
|
||||
STORAGE_KEY_AI_AUTO_LLM_TITLE,
|
||||
STORAGE_KEY_AI_PROVIDERS,
|
||||
STORAGE_KEY_AI_TITLE_MODEL,
|
||||
} from '../../infrastructure/config/storageKeys.ts';
|
||||
import { useAIState, type UseAIStateOptions } from './useAIState.ts';
|
||||
import { useAISessionsStore } from './aiSessionsStore.ts';
|
||||
import {
|
||||
__resetIdbPersistenceForTests,
|
||||
markAiSessionsHydrationComplete,
|
||||
setLatestAISessionsSnapshot,
|
||||
} from './aiStateSnapshots.ts';
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason?: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
type Capture = {
|
||||
ai: ReturnType<typeof useAIState> | null;
|
||||
sessions: AISession[];
|
||||
};
|
||||
|
||||
function Harness({
|
||||
capture,
|
||||
options,
|
||||
}: {
|
||||
capture: Capture;
|
||||
options?: UseAIStateOptions;
|
||||
}) {
|
||||
capture.ai = useAIState(options);
|
||||
capture.sessions = useAISessionsStore().sessions as AISession[];
|
||||
return null;
|
||||
}
|
||||
|
||||
async function setupHook(options?: {
|
||||
sessions?: AISession[];
|
||||
providers?: ProviderConfig[];
|
||||
activeProviderId?: string;
|
||||
agentProviderMap?: Record<string, string>;
|
||||
agentModelMap?: Record<string, string>;
|
||||
autoLlmTitle?: boolean;
|
||||
titleModel?: { providerId: string; modelId: string } | null;
|
||||
generateSessionTitle?: UseAIStateOptions['generateSessionTitle'];
|
||||
}) {
|
||||
const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost' });
|
||||
const prevDescriptors = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const [key, value] of [
|
||||
['window', dom.window],
|
||||
['document', dom.window.document],
|
||||
['localStorage', dom.window.localStorage],
|
||||
['CustomEvent', dom.window.CustomEvent],
|
||||
['Event', dom.window.Event],
|
||||
['IS_REACT_ACT_ENVIRONMENT', true],
|
||||
] as const) {
|
||||
prevDescriptors.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, value });
|
||||
}
|
||||
|
||||
__resetIdbPersistenceForTests();
|
||||
markAiSessionsHydrationComplete();
|
||||
|
||||
if (options?.providers) {
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_PROVIDERS, JSON.stringify(options.providers));
|
||||
}
|
||||
if (options?.activeProviderId) {
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_ACTIVE_PROVIDER, options.activeProviderId);
|
||||
}
|
||||
if (options?.agentProviderMap) {
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_AGENT_PROVIDER_MAP, JSON.stringify(options.agentProviderMap));
|
||||
}
|
||||
if (options?.agentModelMap) {
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_AGENT_MODEL_MAP, JSON.stringify(options.agentModelMap));
|
||||
}
|
||||
if (options?.autoLlmTitle !== undefined) {
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_AUTO_LLM_TITLE, String(options.autoLlmTitle));
|
||||
}
|
||||
if (options?.titleModel) {
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_TITLE_MODEL, JSON.stringify(options.titleModel));
|
||||
}
|
||||
|
||||
const initialSessions = options?.sessions ?? [];
|
||||
setLatestAISessionsSnapshot(initialSessions);
|
||||
dom.window.localStorage.setItem('netcatty_ai_sessions_v1', JSON.stringify(initialSessions));
|
||||
|
||||
const container = dom.window.document.createElement('div');
|
||||
dom.window.document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
const capture: Capture = { ai: null, sessions: [] };
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
React.createElement(Harness, {
|
||||
capture,
|
||||
options: { generateSessionTitle: options?.generateSessionTitle },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
capture,
|
||||
cleanup: async () => {
|
||||
await act(async () => root.unmount());
|
||||
container.remove();
|
||||
dom.window.close();
|
||||
__resetIdbPersistenceForTests();
|
||||
for (const [key, desc] of prevDescriptors) {
|
||||
if (desc) Object.defineProperty(globalThis, key, desc);
|
||||
else delete (globalThis as Record<string, unknown>)[key];
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const providerA: ProviderConfig = {
|
||||
id: 'p-catty',
|
||||
providerId: 'openai',
|
||||
name: 'Main OpenAI',
|
||||
enabled: true,
|
||||
defaultModel: 'gpt-5.4',
|
||||
};
|
||||
|
||||
const providerB: ProviderConfig = {
|
||||
id: 'p-title',
|
||||
providerId: 'openai',
|
||||
name: 'Cheap Title',
|
||||
enabled: true,
|
||||
defaultModel: 'gpt-4o-mini',
|
||||
};
|
||||
|
||||
const untitledSession = (id = 's-1'): AISession => ({
|
||||
id,
|
||||
title: 'New Chat',
|
||||
agentId: 'catty',
|
||||
scope: { type: 'terminal', targetId: 'term-1' },
|
||||
messages: [{ id: 'm-1', role: 'user', content: 'Check slow SSH handshake on prod', timestamp: 1 }],
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
});
|
||||
|
||||
test('autoTitleSession preserves a user rename that happens while LLM title generation is pending', async () => {
|
||||
const pending = deferred<string>();
|
||||
let capturedSignal: AbortSignal | undefined;
|
||||
const { capture, cleanup } = await setupHook({
|
||||
sessions: [untitledSession()],
|
||||
providers: [providerA],
|
||||
activeProviderId: providerA.id,
|
||||
generateSessionTitle: async (_source, opts) => {
|
||||
capturedSignal = opts.signal;
|
||||
return pending.promise;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
let titleTask!: Promise<void>;
|
||||
await act(async () => {
|
||||
titleTask = capture.ai!.autoTitleSession('s-1', 'Check slow SSH handshake on prod');
|
||||
});
|
||||
// Deterministic fallback landed immediately.
|
||||
assert.equal(capture.sessions[0].title, 'Check slow SSH handshake on prod');
|
||||
assert.equal(capturedSignal?.aborted, false);
|
||||
|
||||
// User renames the session (e.g. after closing & reopening the side panel).
|
||||
await act(async () => {
|
||||
capture.ai!.updateSessionTitle('s-1', 'Prod SSH Debug');
|
||||
});
|
||||
assert.equal(capturedSignal?.aborted, true, 'manual rename aborts pending LLM call');
|
||||
assert.equal(capture.sessions[0].title, 'Prod SSH Debug');
|
||||
|
||||
// Even if the LLM promise resolves with a generated title afterwards, it
|
||||
// must not overwrite the user's title.
|
||||
await act(async () => {
|
||||
pending.resolve('Slow SSH Handshake');
|
||||
await titleTask;
|
||||
});
|
||||
assert.equal(capture.sessions[0].title, 'Prod SSH Debug');
|
||||
} finally {
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('autoTitleSession promotes the LLM title when unrenamed and passes Catty or explicit titleModel config', async () => {
|
||||
const seenConfigs: Array<ProviderConfig | null | undefined> = [];
|
||||
const pending = deferred<string>();
|
||||
const { capture, cleanup } = await setupHook({
|
||||
sessions: [untitledSession('s-catty'), untitledSession('s-explicit')],
|
||||
providers: [providerB, providerA],
|
||||
activeProviderId: providerB.id,
|
||||
agentProviderMap: { catty: providerA.id },
|
||||
agentModelMap: { catty: 'gpt-5.4-turbo' },
|
||||
generateSessionTitle: async (_source, opts) => {
|
||||
seenConfigs.push(opts.config);
|
||||
return pending.promise;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
let task!: Promise<void>;
|
||||
await act(async () => {
|
||||
task = capture.ai!.autoTitleSession('s-catty', 'Check slow SSH handshake on prod');
|
||||
});
|
||||
assert.equal(seenConfigs[0]?.id, providerA.id);
|
||||
assert.equal(seenConfigs[0]?.defaultModel, 'gpt-5.4-turbo');
|
||||
|
||||
await act(async () => {
|
||||
pending.resolve('SSH Handshake Audit');
|
||||
await task;
|
||||
});
|
||||
assert.equal(capture.sessions.find((s) => s.id === 's-catty')?.title, 'SSH Handshake Audit');
|
||||
|
||||
// Explicit titleModel overrides Catty model.
|
||||
await act(async () => {
|
||||
capture.ai!.setTitleModel({ providerId: providerB.id, modelId: 'gpt-4o-mini' });
|
||||
});
|
||||
await act(async () => {
|
||||
await capture.ai!.autoTitleSession('s-explicit', 'Inspect nginx error logs');
|
||||
});
|
||||
assert.equal(seenConfigs[1]?.id, providerB.id);
|
||||
assert.equal(seenConfigs[1]?.defaultModel, 'gpt-4o-mini');
|
||||
assert.equal(capture.sessions.find((s) => s.id === 's-explicit')?.title, 'SSH Handshake Audit');
|
||||
} finally {
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('autoTitleSession aborts and ignores deleted sessions, deduplicates concurrent calls, and skips titled chats', async () => {
|
||||
const pending = deferred<string>();
|
||||
let calls = 0;
|
||||
let signalRef: AbortSignal | undefined;
|
||||
const { capture, cleanup } = await setupHook({
|
||||
sessions: [
|
||||
untitledSession('s-del'),
|
||||
untitledSession('s-dup'),
|
||||
{ ...untitledSession('s-titled'), title: 'Already named' },
|
||||
],
|
||||
providers: [providerA],
|
||||
activeProviderId: providerA.id,
|
||||
generateSessionTitle: async (_source, opts) => {
|
||||
calls += 1;
|
||||
signalRef = opts.signal;
|
||||
return pending.promise;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
// Titled chat skips both fallback and LLM.
|
||||
await act(async () => {
|
||||
await capture.ai!.autoTitleSession('s-titled', 'New prompt text');
|
||||
});
|
||||
assert.equal(calls, 0);
|
||||
assert.equal(capture.sessions.find((s) => s.id === 's-titled')?.title, 'Already named');
|
||||
|
||||
// Deleting a session aborts in-flight generation and never resurrects it.
|
||||
let delTask!: Promise<void>;
|
||||
await act(async () => {
|
||||
delTask = capture.ai!.autoTitleSession('s-del', 'Delete me mid-flight');
|
||||
});
|
||||
assert.equal(calls, 1);
|
||||
await act(async () => {
|
||||
capture.ai!.deleteSession('s-del');
|
||||
});
|
||||
assert.equal(signalRef?.aborted, true);
|
||||
await act(async () => {
|
||||
pending.resolve('Ghost title');
|
||||
await delTask;
|
||||
});
|
||||
assert.equal(capture.sessions.some((s) => s.id === 's-del'), false);
|
||||
|
||||
// Duplicate concurrent call for the same session only invokes LLM once.
|
||||
const pendingDup = deferred<string>();
|
||||
const dupHarness = await setupHook({
|
||||
sessions: [untitledSession('s-dup2')],
|
||||
providers: [providerA],
|
||||
activeProviderId: providerA.id,
|
||||
generateSessionTitle: async () => {
|
||||
calls += 1;
|
||||
return pendingDup.promise;
|
||||
},
|
||||
});
|
||||
try {
|
||||
let t1!: Promise<void>;
|
||||
let t2!: Promise<void>;
|
||||
await act(async () => {
|
||||
t1 = dupHarness.capture.ai!.autoTitleSession('s-dup2', 'First call');
|
||||
t2 = dupHarness.capture.ai!.autoTitleSession('s-dup2', 'Second call');
|
||||
});
|
||||
assert.equal(calls, 2);
|
||||
await act(async () => {
|
||||
pendingDup.resolve('Single Title');
|
||||
await Promise.all([t1, t2]);
|
||||
});
|
||||
assert.equal(dupHarness.capture.sessions.find((s) => s.id === 's-dup2')?.title, 'Single Title');
|
||||
} finally {
|
||||
await dupHarness.cleanup();
|
||||
}
|
||||
} finally {
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('autoTitleSession respects autoLlmTitle=false and removeProvider clears dangling titleModel', async () => {
|
||||
let calls = 0;
|
||||
const { capture, cleanup } = await setupHook({
|
||||
sessions: [untitledSession('s-off')],
|
||||
providers: [providerA, providerB],
|
||||
activeProviderId: providerA.id,
|
||||
autoLlmTitle: false,
|
||||
titleModel: { providerId: providerB.id, modelId: 'gpt-4o-mini' },
|
||||
generateSessionTitle: async () => {
|
||||
calls += 1;
|
||||
return 'Should not run';
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
await capture.ai!.autoTitleSession('s-off', 'Fallback only please');
|
||||
});
|
||||
assert.equal(calls, 0);
|
||||
assert.equal(capture.sessions[0].title, 'Fallback only please');
|
||||
|
||||
assert.deepEqual(capture.ai!.titleModel, { providerId: providerB.id, modelId: 'gpt-4o-mini' });
|
||||
await act(async () => {
|
||||
capture.ai!.removeProvider(providerB.id);
|
||||
});
|
||||
assert.equal(capture.ai!.titleModel, null);
|
||||
} finally {
|
||||
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();
|
||||
});
|
||||
+381
-89
@@ -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,
|
||||
@@ -98,8 +100,41 @@ import {
|
||||
buildUndoLastTurnBranch,
|
||||
type UndoLastTurnRestoredDraft,
|
||||
} from '../../domain/aiUndoLastTurn';
|
||||
import {
|
||||
applySessionTitleIfCurrent,
|
||||
buildFallbackTitle,
|
||||
canAutoTitleSession,
|
||||
resolveEffectiveTitleModelConfig,
|
||||
} from '../../domain/aiSessionTitle';
|
||||
import type { generateSessionLlmTitle as GenerateSessionLlmTitleFn } from '../../infrastructure/ai/sessionTitleGeneration';
|
||||
|
||||
export function useAIState() {
|
||||
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;
|
||||
}
|
||||
|
||||
export function useAIState(options?: UseAIStateOptions) {
|
||||
const [hostPermissions, setHostPermissionsRaw] = useState<HostAIPermission[]>(() =>
|
||||
localStorageAdapter.read<HostAIPermission[]>(STORAGE_KEY_AI_HOST_PERMISSIONS) ?? []
|
||||
);
|
||||
@@ -402,11 +437,35 @@ export function useAIState() {
|
||||
setWebSearchConfig,
|
||||
quickMessages,
|
||||
setQuickMessages,
|
||||
autoLlmTitle,
|
||||
setAutoLlmTitle,
|
||||
titleModel,
|
||||
setTitleModel,
|
||||
} = useSharedAISettingsState({
|
||||
ignoreInvalidPermissionModeOnStorage: true,
|
||||
onRemoveProvider: handleRemoveProviderReferences,
|
||||
});
|
||||
|
||||
const providersRef = useRef(providers);
|
||||
providersRef.current = providers;
|
||||
const activeProviderIdRef = useRef(activeProviderId);
|
||||
activeProviderIdRef.current = activeProviderId;
|
||||
const activeModelIdRef = useRef(activeModelId);
|
||||
activeModelIdRef.current = activeModelId;
|
||||
const autoLlmTitleRef = useRef(autoLlmTitle);
|
||||
autoLlmTitleRef.current = autoLlmTitle;
|
||||
const titleModelRef = useRef(titleModel);
|
||||
titleModelRef.current = titleModel;
|
||||
const generateSessionTitleRef = useRef(options?.generateSessionTitle);
|
||||
generateSessionTitleRef.current = options?.generateSessionTitle;
|
||||
const pendingCreatedSessionIdsRef = useRef<Set<string>>(new Set());
|
||||
const titleAbortControllersRef = useRef<Map<string, AbortController>>(new Map());
|
||||
useEffect(() => {
|
||||
for (const session of sessions) {
|
||||
pendingCreatedSessionIdsRef.current.delete(session.id);
|
||||
}
|
||||
}, [sessions]);
|
||||
|
||||
useEffect(() => {
|
||||
setLatestAISessionsSnapshot(sessions);
|
||||
}, [sessions]);
|
||||
@@ -724,6 +783,14 @@ export function useAIState() {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
// Keep the source workspace name when the fork stays in that workspace;
|
||||
// a fork into a different/terminal scope must not inherit a stale name.
|
||||
if (
|
||||
source.workspaceNameSnapshot
|
||||
&& (!viewingScope || (viewingScope.type === 'workspace' && viewingScope.targetId === source.scope.targetId))
|
||||
) {
|
||||
fork.workspaceNameSnapshot = source.workspaceNameSnapshot;
|
||||
}
|
||||
if (plan.contextCompaction) {
|
||||
fork.contextCompaction = plan.contextCompaction;
|
||||
}
|
||||
@@ -739,17 +806,25 @@ export function useAIState() {
|
||||
return fork;
|
||||
}, [persistSessions, setActiveSessionId]);
|
||||
|
||||
const createSession = useCallback((scope: AISessionScope, agentId?: string): AISession => {
|
||||
const createSession = useCallback((
|
||||
scope: AISessionScope,
|
||||
agentId?: string,
|
||||
workspaceNameSnapshot?: string,
|
||||
): AISession => {
|
||||
const now = Date.now();
|
||||
const session: AISession = {
|
||||
id: `ai_${now}_${Math.random().toString(36).slice(2, 8)}`,
|
||||
title: 'New Chat',
|
||||
agentId: agentId || defaultAgentId,
|
||||
scope,
|
||||
...(scope.type === 'workspace' && workspaceNameSnapshot
|
||||
? { workspaceNameSnapshot }
|
||||
: {}),
|
||||
messages: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
pendingCreatedSessionIdsRef.current.add(session.id);
|
||||
setSessionsRaw(prev => {
|
||||
const next = [session, ...prev];
|
||||
setLatestAISessionsSnapshot(next);
|
||||
@@ -796,6 +871,12 @@ export function useAIState() {
|
||||
}, [persistSessions, setActiveSessionId]);
|
||||
|
||||
const deleteSession = useCallback((sessionId: string, scopeKey?: string) => {
|
||||
pendingCreatedSessionIdsRef.current.delete(sessionId);
|
||||
const pendingTitleController = titleAbortControllersRef.current.get(sessionId);
|
||||
if (pendingTitleController) {
|
||||
titleAbortControllersRef.current.delete(sessionId);
|
||||
pendingTitleController.abort();
|
||||
}
|
||||
cleanupDeletedAIChatSessions([sessionId]);
|
||||
if (persistTimerRef.current) {
|
||||
clearTimeout(persistTimerRef.current);
|
||||
@@ -838,6 +919,14 @@ export function useAIState() {
|
||||
const removedSessionIds = sessionsRef.current
|
||||
.filter(s => s.scope.type === scopeType && s.scope.targetId === targetId)
|
||||
.map(s => s.id);
|
||||
for (const removedId of removedSessionIds) {
|
||||
pendingCreatedSessionIdsRef.current.delete(removedId);
|
||||
const pendingTitleController = titleAbortControllersRef.current.get(removedId);
|
||||
if (pendingTitleController) {
|
||||
titleAbortControllersRef.current.delete(removedId);
|
||||
pendingTitleController.abort();
|
||||
}
|
||||
}
|
||||
cleanupDeletedAIChatSessions(removedSessionIds);
|
||||
if (persistTimerRef.current) {
|
||||
clearTimeout(persistTimerRef.current);
|
||||
@@ -865,6 +954,12 @@ export function useAIState() {
|
||||
}, [persistSessions]);
|
||||
|
||||
const updateSessionTitle = useCallback((sessionId: string, title: string) => {
|
||||
// Manual rename supersedes any in-flight automatic title generation.
|
||||
const pendingTitleController = titleAbortControllersRef.current.get(sessionId);
|
||||
if (pendingTitleController) {
|
||||
titleAbortControllersRef.current.delete(sessionId);
|
||||
pendingTitleController.abort();
|
||||
}
|
||||
setSessionsRaw(prev => {
|
||||
const next = prev.map(s => s.id === sessionId ? { ...s, title, updatedAt: Date.now() } : s);
|
||||
setLatestAISessionsSnapshot(next);
|
||||
@@ -873,12 +968,221 @@ export function useAIState() {
|
||||
});
|
||||
}, [persistSessions]);
|
||||
|
||||
/**
|
||||
* Auto-title a session if it still carries the placeholder title. Writes a
|
||||
* deterministic fallback immediately, then (when enabled and a model is
|
||||
* configured) upgrades it with a one-shot LLM summary. Lives in application
|
||||
* state so panel close/reopen cannot break the in-flight lifecycle, and
|
||||
* compares against live state atomically so a user rename always wins.
|
||||
*/
|
||||
const autoTitleSession = useCallback(async (
|
||||
sessionId: string,
|
||||
text: string,
|
||||
callerSignal?: AbortSignal,
|
||||
): Promise<void> => {
|
||||
if (!sessionId) return;
|
||||
if (titleAbortControllersRef.current.has(sessionId)) return;
|
||||
|
||||
const snapshot = latestAISessionsSnapshot ?? sessionsRef.current;
|
||||
const existing = snapshot.find((s) => s.id === sessionId);
|
||||
if (existing && !canAutoTitleSession(existing)) return;
|
||||
if (!existing && !pendingCreatedSessionIdsRef.current.has(sessionId)) return;
|
||||
|
||||
const fallback = buildFallbackTitle(text);
|
||||
|
||||
// Phase 1: Atomically apply the deterministic fallback while still untitled.
|
||||
setSessionsRaw((prev) => {
|
||||
const result = applySessionTitleIfCurrent(prev, sessionId, fallback);
|
||||
if (!result.updated) return prev;
|
||||
setLatestAISessionsSnapshot(result.sessions);
|
||||
persistSessions(result.sessions);
|
||||
return result.sessions;
|
||||
});
|
||||
|
||||
if (!autoLlmTitleRef.current || callerSignal?.aborted) return;
|
||||
|
||||
const resolvedTitleConfig = resolveEffectiveTitleModelConfig({
|
||||
titleModel: titleModelRef.current,
|
||||
providers: providersRef.current,
|
||||
activeProviderId: activeProviderIdRef.current,
|
||||
activeModelId: activeModelIdRef.current,
|
||||
agentProviderMap: agentProviderMapRef.current,
|
||||
agentModelMap: agentModelMapRef.current,
|
||||
});
|
||||
if (!resolvedTitleConfig) return;
|
||||
|
||||
const requestController = new AbortController();
|
||||
titleAbortControllersRef.current.set(sessionId, requestController);
|
||||
const onCallerAbort = () => requestController.abort();
|
||||
if (callerSignal) {
|
||||
callerSignal.addEventListener('abort', onCallerAbort, { once: true });
|
||||
}
|
||||
|
||||
try {
|
||||
const latestBeforeCall = (latestAISessionsSnapshot ?? sessionsRef.current)
|
||||
.find((s) => s.id === sessionId);
|
||||
if (
|
||||
latestBeforeCall
|
||||
&& !canAutoTitleSession(latestBeforeCall)
|
||||
&& latestBeforeCall.title !== fallback
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const sourceMessages = latestBeforeCall?.messages?.length
|
||||
? latestBeforeCall.messages
|
||||
: (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;
|
||||
|
||||
const generated = await generateTitle(
|
||||
{ messages: sourceMessages },
|
||||
{
|
||||
config: resolvedTitleConfig,
|
||||
chatSessionId: sessionId,
|
||||
signal: requestController.signal,
|
||||
language: readConfiguredUiLanguage(),
|
||||
},
|
||||
);
|
||||
|
||||
if (requestController.signal.aborted || !generated || generated === fallback) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Phase 2: Atomically promote the LLM title only if the session still
|
||||
// exists and still holds the exact fallback title applied in Phase 1.
|
||||
if (mountedRef.current) {
|
||||
setSessionsRaw((prev) => {
|
||||
const result = applySessionTitleIfCurrent(prev, sessionId, generated, fallback);
|
||||
if (!result.updated) return prev;
|
||||
setLatestAISessionsSnapshot(result.sessions);
|
||||
persistSessions(result.sessions);
|
||||
return result.sessions;
|
||||
});
|
||||
} else {
|
||||
const current = latestAISessionsSnapshot ?? getPersistedAiSessionsSnapshot();
|
||||
const result = applySessionTitleIfCurrent(current, sessionId, generated, fallback);
|
||||
if (result.updated) {
|
||||
setLatestAISessionsSnapshot(result.sessions);
|
||||
persistSessions(result.sessions);
|
||||
emitAIStateChanged(STORAGE_KEY_AI_SESSIONS);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Generation never throws; fallback was already applied above.
|
||||
} finally {
|
||||
if (callerSignal) {
|
||||
callerSignal.removeEventListener('abort', onCallerAbort);
|
||||
}
|
||||
if (titleAbortControllersRef.current.get(sessionId) === requestController) {
|
||||
titleAbortControllersRef.current.delete(sessionId);
|
||||
}
|
||||
}
|
||||
}, [persistSessions]);
|
||||
|
||||
/**
|
||||
* Explicitly regenerate an existing chat's title with the configured LLM
|
||||
* (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, 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 { status: 'empty' };
|
||||
}
|
||||
if (expectedTitle !== undefined && session.title !== expectedTitle) {
|
||||
return { status: 'unchanged', title: session.title };
|
||||
}
|
||||
const resolvedTitleConfig = resolveEffectiveTitleModelConfig({
|
||||
titleModel: titleModelRef.current,
|
||||
providers: providersRef.current,
|
||||
activeProviderId: activeProviderIdRef.current,
|
||||
activeModelId: activeModelIdRef.current,
|
||||
agentProviderMap: agentProviderMapRef.current,
|
||||
agentModelMap: agentModelMapRef.current,
|
||||
});
|
||||
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(
|
||||
{ messages: session.messages },
|
||||
{
|
||||
config: resolvedTitleConfig,
|
||||
chatSessionId: sessionId,
|
||||
signal: controller.signal,
|
||||
fallbackOnFailure: false,
|
||||
language: readConfiguredUiLanguage(),
|
||||
onError: (err) => { capturedError = err; },
|
||||
},
|
||||
);
|
||||
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);
|
||||
if (!result.updated) return sessions;
|
||||
setLatestAISessionsSnapshot(result.sessions);
|
||||
persistSessions(result.sessions);
|
||||
return result.sessions;
|
||||
};
|
||||
if (mountedRef.current) setSessionsRaw(commit);
|
||||
else {
|
||||
const result = commit(latestAISessionsSnapshot ?? getPersistedAiSessionsSnapshot());
|
||||
emitAIStateChanged(STORAGE_KEY_AI_SESSIONS);
|
||||
void result;
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
}, [persistSessions]);
|
||||
|
||||
// Issue #4015 R2: rebind a dangling chat to the panel's current scope.
|
||||
// Rewrites `scope`, clears the dangling marker and makes the chat the
|
||||
// active session of its new scope so it shows in the scoped history again.
|
||||
const rebindSessionScope = useCallback((
|
||||
sessionId: string,
|
||||
scope: { type: 'terminal' | 'workspace'; targetId: string; hostIds?: string[] },
|
||||
workspaceNameSnapshot?: string,
|
||||
) => {
|
||||
const scopeKey = `${scope.type}:${scope.targetId}`;
|
||||
// Capture the PRE-rebind active map before rebindActiveSessionMap drops the
|
||||
@@ -903,9 +1207,15 @@ export function useAIState() {
|
||||
if (scope.hostIds && scope.hostIds.length > 0) {
|
||||
nextScope.hostIds = [...scope.hostIds];
|
||||
}
|
||||
// Snapshot follows the binding: keep it only for workspace scopes.
|
||||
// `rest` may still carry a stale snapshot from a previous workspace.
|
||||
const { workspaceNameSnapshot: _staleSnapshot, ...withoutSnapshot } = rest;
|
||||
return {
|
||||
...rest,
|
||||
...withoutSnapshot,
|
||||
scope: nextScope,
|
||||
...(scope.type === 'workspace' && workspaceNameSnapshot
|
||||
? { workspaceNameSnapshot }
|
||||
: {}),
|
||||
updatedAt: Date.now(),
|
||||
} as AISession;
|
||||
});
|
||||
@@ -1089,20 +1399,12 @@ export function useAIState() {
|
||||
}, [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);
|
||||
@@ -1113,31 +1415,24 @@ export function useAIState() {
|
||||
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);
|
||||
@@ -1147,32 +1442,25 @@ export function useAIState() {
|
||||
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);
|
||||
@@ -1207,38 +1495,30 @@ export function useAIState() {
|
||||
}, [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]);
|
||||
@@ -1453,6 +1733,10 @@ export function useAIState() {
|
||||
setWebSearchConfig,
|
||||
quickMessages,
|
||||
setQuickMessages,
|
||||
autoLlmTitle,
|
||||
setAutoLlmTitle,
|
||||
titleModel,
|
||||
setTitleModel,
|
||||
// sessions / activeSessionIdMap / draftsByScope / panelViewByScope live in
|
||||
// aiSessionsStore so streaming updates do not rebuild this config object.
|
||||
setActiveSessionId,
|
||||
@@ -1468,6 +1752,8 @@ export function useAIState() {
|
||||
deleteSession,
|
||||
deleteSessionsByTarget,
|
||||
updateSessionTitle,
|
||||
autoTitleSession,
|
||||
regenerateSessionTitle,
|
||||
rebindSessionScope,
|
||||
exportSessionsBackup,
|
||||
importSessionsBackup,
|
||||
@@ -1522,6 +1808,10 @@ export function useAIState() {
|
||||
setWebSearchConfig,
|
||||
quickMessages,
|
||||
setQuickMessages,
|
||||
autoLlmTitle,
|
||||
setAutoLlmTitle,
|
||||
titleModel,
|
||||
setTitleModel,
|
||||
setActiveSessionId,
|
||||
ensureDraftForScope,
|
||||
updateDraft,
|
||||
@@ -1535,6 +1825,8 @@ export function useAIState() {
|
||||
deleteSession,
|
||||
deleteSessionsByTarget,
|
||||
updateSessionTitle,
|
||||
autoTitleSession,
|
||||
regenerateSessionTitle,
|
||||
rebindSessionScope,
|
||||
exportSessionsBackup,
|
||||
importSessionsBackup,
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -63,6 +63,8 @@ interface CloudSyncRunOptions {
|
||||
conflictActionOverride?: CloudSyncConflictAction;
|
||||
applyConvergentPayload?: ConvergentPayloadApplier;
|
||||
signal?: AbortSignal;
|
||||
/** One-shot manual sync: skip convergent fan-out (single-provider only). */
|
||||
forceSingleProvider?: boolean;
|
||||
}
|
||||
|
||||
export interface CloudSyncHook {
|
||||
@@ -134,7 +136,7 @@ export interface CloudSyncHook {
|
||||
syncToProvider: (
|
||||
provider: CloudProvider,
|
||||
payload: SyncPayload,
|
||||
opts?: Pick<CloudSyncRunOptions, 'overrideShrink' | 'applyConvergentPayload' | 'signal'>,
|
||||
opts?: Pick<CloudSyncRunOptions, 'overrideShrink' | 'applyConvergentPayload' | 'signal' | 'forceSingleProvider'>,
|
||||
) => Promise<SyncResult>;
|
||||
downloadFromProvider: (provider: CloudProvider) => Promise<RemoteSyncPayload | null>;
|
||||
commitRemoteInspection: (provider: CloudProvider, remoteFile: SyncedFile, payload: SyncPayload, opts?: { recordDownload?: boolean }) => Promise<void>;
|
||||
@@ -818,7 +820,7 @@ export const useCloudSync = (): CloudSyncHook => {
|
||||
const syncToProviderWithUnlock = useCallback(async (
|
||||
provider: CloudProvider,
|
||||
payload: SyncPayload,
|
||||
opts?: Pick<CloudSyncRunOptions, 'overrideShrink' | 'applyConvergentPayload' | 'signal'>,
|
||||
opts?: Pick<CloudSyncRunOptions, 'overrideShrink' | 'applyConvergentPayload' | 'signal' | 'forceSingleProvider'>,
|
||||
) => {
|
||||
await ensureUnlocked();
|
||||
const controller = new AbortController();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
|
||||
import { DirectoryPickerError, directoryParent, filterDirectories, isDirectoryPath, type DirectoryEntry, type DirectoryPickerErrorCode } from '../../domain/directoryPicker';
|
||||
import { DirectoryPickerError, filterDirectories, type DirectoryEntry, type DirectoryPickerErrorCode } from '../../domain/directoryPicker';
|
||||
import { parentDirectoryPath } from '../../domain/directoryPath';
|
||||
import { resolveComposeDirectoryDisplay, type ComposeDirectoryDisplay } from '../../domain/composeDirectoryDisplay';
|
||||
import { terminalCwdStore } from './terminalCwdStore';
|
||||
import { getTerminalDirectory, observeTerminalDirectory, subscribeTerminalDirectories } from './terminalDirectoryRegistry';
|
||||
@@ -7,15 +8,9 @@ import { getTerminalDirectory, observeTerminalDirectory, subscribeTerminalDirect
|
||||
export function useComposeDirectoryPicker(sessionId: string) {
|
||||
const controller = useSyncExternalStore(subscribeTerminalDirectories, () => getTerminalDirectory(sessionId), () => null);
|
||||
const pathFlavor = controller?.target.pathFlavor ?? 'posix';
|
||||
useSyncExternalStore(terminalCwdStore.subscribe, terminalCwdStore.getVersion, terminalCwdStore.getVersion);
|
||||
const [confirmation, setConfirmation] = useState<{ sessionId: string; controller: typeof controller } | null>(null);
|
||||
const confirmed = confirmation?.sessionId === sessionId && confirmation.controller === controller;
|
||||
const getCurrentCwd = useCallback(() => controller?.trustsOsc7 === false && pathFlavor === 'posix'
|
||||
? controller.getVerifiedCwd() : terminalCwdStore.getCwd(sessionId), [controller, pathFlavor, sessionId]);
|
||||
const observedCwd = getCurrentCwd();
|
||||
const cwd = controller && isDirectoryPath(observedCwd, pathFlavor)
|
||||
&& (confirmed || controller.hasConfirmedCwd() || (controller.trustsOsc7 && terminalCwdStore.getSource(sessionId) === 'osc7'))
|
||||
? observedCwd : null;
|
||||
const subscribeCwd = controller?.subscribeCwd ?? terminalCwdStore.subscribe;
|
||||
const getCurrentCwd = useCallback(() => controller?.getConfirmedCwd() ?? null, [controller]);
|
||||
const cwd = useSyncExternalStore(subscribeCwd, getCurrentCwd, () => null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [query, setQuery] = useState('');
|
||||
const [showHidden, setShowHidden] = useState(false);
|
||||
@@ -47,11 +42,11 @@ export function useComposeDirectoryPicker(sessionId: string) {
|
||||
const stopObserving = observeTerminalDirectory(sessionId);
|
||||
lifetime.current = new AbortController();
|
||||
sending.current = false;
|
||||
setConfirmation(null); setOpen(false); setPending(false); setLoading(false); setHome(null); setError(null); setEntries([]);
|
||||
setOpen(false); setPending(false); setLoading(false); setHome(null); setError(null); setEntries([]);
|
||||
listingBase.current = null;
|
||||
listingRevision.current = null;
|
||||
if (controller) void Promise.all([controller.refresh(), controller.home()]).then(([, nextHome]) => {
|
||||
if (generation.current === id) { setConfirmation({ sessionId, controller }); setHome(nextHome); }
|
||||
if (generation.current === id) setHome(nextHome);
|
||||
}).catch(failure => { if (generation.current === id) report(failure, 'unknown'); });
|
||||
return () => {
|
||||
generation.current = id + 1;
|
||||
@@ -63,9 +58,9 @@ export function useComposeDirectoryPicker(sessionId: string) {
|
||||
if (!controller) { setError('unavailable'); return; }
|
||||
const id = generation.current;
|
||||
setError(null);
|
||||
try { await controller.refresh(); if (generation.current === id) setConfirmation({ sessionId, controller }); }
|
||||
try { await controller.refresh(); }
|
||||
catch (failure) { if (generation.current === id) report(failure, 'unknown'); }
|
||||
}, [controller, report, sessionId]);
|
||||
}, [controller, report]);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!controller || !cwd) return;
|
||||
@@ -105,7 +100,7 @@ export function useComposeDirectoryPicker(sessionId: string) {
|
||||
if (!controller) { setError('unavailable'); return; }
|
||||
if (sending.current) return;
|
||||
if (!cwd || getCurrentCwd() !== cwd
|
||||
|| (path !== directoryParent(cwd, pathFlavor) && (listingBase.current !== cwd
|
||||
|| (path !== parentDirectoryPath(cwd, pathFlavor) && (listingBase.current !== cwd
|
||||
|| listingRevision.current !== terminalCwdStore.getSessionRevision(sessionId)))) { setError('unavailable'); return; }
|
||||
sending.current = true; setPending(true); setError(null);
|
||||
const id = generation.current;
|
||||
@@ -120,11 +115,11 @@ export function useComposeDirectoryPicker(sessionId: string) {
|
||||
}, [controller, report, cwd, sessionId, pathFlavor, getCurrentCwd]);
|
||||
|
||||
const filtered = useMemo(() => filterDirectories(entries, query, showHidden), [entries, query, showHidden]);
|
||||
const cwdError = controller?.getCwdError() ?? null;
|
||||
const cwdError = useSyncExternalStore(subscribeCwd, () => controller?.getCwdError() ?? null, () => null);
|
||||
const waitsForCwd = error === 'unknown' || error === 'integrationUnavailable' || error === 'cmdIntegrationUnavailable'
|
||||
|| error === 'gitBashIntegrationUnavailable' || error === 'wslIntegrationUnavailable' || error === 'nonFilesystem';
|
||||
|| error === 'gitBashIntegrationUnavailable' || error === 'wslIntegrationUnavailable' || error === 'cygwinIntegrationUnavailable' || error === 'nonFilesystem';
|
||||
return { cwd, home, display, pathFlavor, open, setOpen, query, setQuery, showHidden, setShowHidden, entries: filtered,
|
||||
parent: cwd ? directoryParent(cwd, pathFlavor) : null, loading, pending,
|
||||
parent: cwd ? parentDirectoryPath(cwd, pathFlavor) : null, loading, pending,
|
||||
error: cwdError ?? (cwd && waitsForCwd ? null : error),
|
||||
available: !!controller?.capabilities.listDirectories && !!controller.capabilities.changeDirectory && !!controller.capabilities.confirmChange,
|
||||
refresh, reload: load, change };
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import React from 'react';
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
|
||||
import type { TerminalGitHeadResult } from '../../domain/terminalGitHead';
|
||||
import { useComposeGitBranch } from './useComposeGitBranch';
|
||||
import { createTerminalDirectoryController } from './terminalDirectoryController';
|
||||
import { observeTerminalDirectory, refreshObservedTerminalDirectory, registerTerminalDirectory } from './terminalDirectoryRegistry';
|
||||
import { terminalCwdStore } from './terminalCwdStore';
|
||||
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
|
||||
test('Git chip follows confirmed cwd and ignores an old worktree result', async t => {
|
||||
const id = 'git-chip-test';
|
||||
const calls: { id: string; cwd: string; resolve: (head: TerminalGitHeadResult) => void }[] = [];
|
||||
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
|
||||
Object.defineProperty(globalThis, 'window', { configurable: true, value: {
|
||||
netcatty: { readLocalSessionGitHead: (backendId: string, cwd: string) => new Promise<TerminalGitHeadResult>(resolve => {
|
||||
calls.push({ id: backendId, cwd, resolve });
|
||||
}) },
|
||||
} });
|
||||
const controller = createTerminalDirectoryController({
|
||||
sessionId: id, localPosixSessionId: 'local-pty', isCurrent: () => true, isReady: () => true,
|
||||
io: { cwd: async () => '/other', list: async () => ({ entries: [], home: null }), realpath: async value => value, write() {} },
|
||||
publish: cwd => terminalCwdStore.setCwd(id, cwd, 'backend-strict'),
|
||||
});
|
||||
const unregister = registerTerminalDirectory(id, controller);
|
||||
const stopObserving = observeTerminalDirectory(id);
|
||||
let root!: ReactTestRenderer;
|
||||
let head: ReturnType<typeof useComposeGitBranch>;
|
||||
function Harness() { head = useComposeGitBranch(id); 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);
|
||||
};
|
||||
t.after(async () => {
|
||||
await act(async () => { root?.unmount(); });
|
||||
stopObserving(); unregister(); terminalCwdStore.setCwd(id, null);
|
||||
if (previousWindow) Object.defineProperty(globalThis, 'window', previousWindow);
|
||||
else Reflect.deleteProperty(globalThis, 'window');
|
||||
});
|
||||
terminalCwdStore.setCwd(id, '/old', 'inferred');
|
||||
await act(async () => { root = create(React.createElement(Harness)); });
|
||||
assert.equal(head!, null);
|
||||
assert.deepEqual(calls, []);
|
||||
await act(async () => { terminalCwdStore.setCwd(id, '/old', 'osc7'); });
|
||||
await waitForCalls(1);
|
||||
assert.equal(calls[0].id, 'local-pty');
|
||||
assert.equal(calls[0].cwd, '/old');
|
||||
await act(async () => { terminalCwdStore.setCwd(id, '/other', 'osc7'); });
|
||||
await waitForCalls(2);
|
||||
await act(async () => { calls[1].resolve({ kind: 'branch', name: 'current', worktreeRoot: '/other' }); });
|
||||
await act(async () => { calls[0].resolve({ kind: 'branch', name: 'old', worktreeRoot: '/old' }); });
|
||||
assert.deepEqual(head!, { kind: 'branch', name: 'current', worktreeRoot: '/other' });
|
||||
refreshObservedTerminalDirectory(id);
|
||||
await waitForCalls(3);
|
||||
await act(async () => { calls[2].resolve({ kind: 'detached', hash: '123abcd', worktreeRoot: '/other' }); });
|
||||
assert.deepEqual(head!, { kind: 'detached', hash: '123abcd', worktreeRoot: '/other' });
|
||||
await act(async () => { terminalCwdStore.setCwd(id, null); });
|
||||
assert.equal(head!, null);
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import { useEffect, useState, useSyncExternalStore } from 'react';
|
||||
import type { TerminalGitHead } from '../../domain/terminalGitHead';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
import { getTerminalDirectory, subscribeTerminalDirectories, subscribeTerminalDirectoryRefresh } from './terminalDirectoryRegistry';
|
||||
import type { TerminalDirectoryController } from './terminalDirectoryController';
|
||||
|
||||
const noCwd = () => null;
|
||||
const noSubscription = () => () => {};
|
||||
const REFRESH_DELAY_MS = 150;
|
||||
|
||||
export function useComposeGitBranch(sessionId: string): TerminalGitHead | null {
|
||||
const controller = useSyncExternalStore(subscribeTerminalDirectories, () => getTerminalDirectory(sessionId), () => null);
|
||||
const backendId = controller?.localPosixSessionId;
|
||||
const cwd = useSyncExternalStore(
|
||||
backendId ? controller.subscribeCwd : noSubscription,
|
||||
backendId ? controller.getConfirmedCwd : noCwd,
|
||||
noCwd,
|
||||
);
|
||||
const [result, setResult] = useState<{ controller: TerminalDirectoryController; cwd: string; head: TerminalGitHead | null } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!controller || !backendId || !cwd || !bridge?.readLocalSessionGitHead) return;
|
||||
let active = true;
|
||||
let pending = false;
|
||||
let refreshAgain = false;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const isCurrent = () => active && getTerminalDirectory(sessionId) === controller && controller.getConfirmedCwd() === cwd;
|
||||
|
||||
const read = async () => {
|
||||
if (!isCurrent()) return;
|
||||
pending = true;
|
||||
try {
|
||||
const next = await bridge.readLocalSessionGitHead?.(backendId, cwd);
|
||||
if (isCurrent() && !refreshAgain) {
|
||||
setResult({ controller, cwd, head: next?.kind === 'branch' || next?.kind === 'detached' ? next : null });
|
||||
}
|
||||
} catch {
|
||||
if (isCurrent() && !refreshAgain) setResult({ controller, cwd, head: null });
|
||||
} finally {
|
||||
pending = false;
|
||||
if (refreshAgain && active) {
|
||||
refreshAgain = false;
|
||||
schedule();
|
||||
}
|
||||
}
|
||||
};
|
||||
const schedule = () => {
|
||||
if (pending) {
|
||||
refreshAgain = true;
|
||||
return;
|
||||
}
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => { void read(); }, REFRESH_DELAY_MS);
|
||||
};
|
||||
schedule();
|
||||
const unsubscribe = subscribeTerminalDirectoryRefresh(sessionId, schedule);
|
||||
return () => {
|
||||
active = false;
|
||||
clearTimeout(timer);
|
||||
unsubscribe();
|
||||
setResult(current => current?.controller === controller && current.cwd === cwd ? null : current);
|
||||
};
|
||||
}, [backendId, controller, cwd, sessionId]);
|
||||
|
||||
return result?.controller === controller && result.cwd === cwd ? result.head : null;
|
||||
}
|
||||
@@ -0,0 +1,480 @@
|
||||
/**
|
||||
* useExternalEditorSettings - Reactive store & launcher for External Editor integration
|
||||
*
|
||||
* Device-local (not cloud-synced because executable paths differ across machines).
|
||||
* Uses useSyncExternalStore + window `storage` events so the Settings window and
|
||||
* main Terminal/SFTP windows stay immediately in sync.
|
||||
*/
|
||||
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';
|
||||
import {
|
||||
buildDirectSshTarget,
|
||||
buildSshBridgeHostname,
|
||||
getHostKeyForExternalEditor,
|
||||
normalizeExternalEditorSettings,
|
||||
validateAndNormalizeRemotePath,
|
||||
type ExternalEditorConnectionMode,
|
||||
type ExternalEditorHostIdentity,
|
||||
type ExternalEditorHostTrustPolicy,
|
||||
type ExternalEditorPresetId,
|
||||
type ExternalEditorSettings,
|
||||
type ExternalEditorTargetKind,
|
||||
} from '../../domain/externalEditor';
|
||||
import { STORAGE_KEY_EXTERNAL_EDITOR } from '../../infrastructure/config/storageKeys';
|
||||
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
import {
|
||||
netcattyBridge,
|
||||
type ExternalEditorBridgeConfigStatus,
|
||||
type ExternalEditorDetectEntry,
|
||||
type ExternalEditorOpenRemoteResult,
|
||||
} from '../../infrastructure/services/netcattyBridge';
|
||||
|
||||
export type {
|
||||
ExternalEditorBridgeConfigStatus,
|
||||
ExternalEditorDetectEntry,
|
||||
ExternalEditorOpenRemoteResult,
|
||||
};
|
||||
|
||||
const subscribers = new Set<() => void>();
|
||||
|
||||
function hasBrowserStorage(): boolean {
|
||||
return typeof window !== 'undefined' && 'localStorage' in window;
|
||||
}
|
||||
|
||||
function loadExternalEditorSettings(): ExternalEditorSettings {
|
||||
if (!hasBrowserStorage()) {
|
||||
return normalizeExternalEditorSettings(undefined);
|
||||
}
|
||||
try {
|
||||
const stored = localStorageAdapter.read<Partial<ExternalEditorSettings>>(STORAGE_KEY_EXTERNAL_EDITOR);
|
||||
return normalizeExternalEditorSettings(stored);
|
||||
} catch {
|
||||
return normalizeExternalEditorSettings(undefined);
|
||||
}
|
||||
}
|
||||
|
||||
let currentSettings: ExternalEditorSettings = loadExternalEditorSettings();
|
||||
let storageListenerAttached = false;
|
||||
|
||||
function ensureStorageListener() {
|
||||
if (storageListenerAttached || typeof window === 'undefined' || typeof window.addEventListener !== 'function') {
|
||||
return;
|
||||
}
|
||||
storageListenerAttached = true;
|
||||
window.addEventListener('storage', (event: StorageEvent) => {
|
||||
if (event.key === STORAGE_KEY_EXTERNAL_EDITOR) {
|
||||
writeSettings(loadExternalEditorSettings(), false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
ensureStorageListener();
|
||||
|
||||
function notifySubscribers() {
|
||||
subscribers.forEach((cb) => cb());
|
||||
}
|
||||
|
||||
function writeSettings(next: ExternalEditorSettings, persist = true) {
|
||||
currentSettings = normalizeExternalEditorSettings(next);
|
||||
if (persist && hasBrowserStorage()) {
|
||||
try {
|
||||
localStorageAdapter.write(STORAGE_KEY_EXTERNAL_EDITOR, currentSettings);
|
||||
} catch {
|
||||
// ignore storage write failures in restricted contexts
|
||||
}
|
||||
}
|
||||
notifySubscribers();
|
||||
}
|
||||
|
||||
function subscribe(callback: () => void) {
|
||||
subscribers.add(callback);
|
||||
return () => {
|
||||
subscribers.delete(callback);
|
||||
};
|
||||
}
|
||||
|
||||
export function getExternalEditorSettingsSnapshot(): ExternalEditorSettings {
|
||||
return currentSettings;
|
||||
}
|
||||
|
||||
export function updateExternalEditorSettings(
|
||||
updater: (prev: ExternalEditorSettings) => ExternalEditorSettings,
|
||||
): ExternalEditorSettings {
|
||||
const next = updater(currentSettings);
|
||||
writeSettings(next, true);
|
||||
return currentSettings;
|
||||
}
|
||||
|
||||
export function setExternalEditorHostTrust(
|
||||
host: ExternalEditorHostIdentity,
|
||||
policy: ExternalEditorHostTrustPolicy,
|
||||
): void {
|
||||
const hostKey = getHostKeyForExternalEditor(host);
|
||||
if (!hostKey) return;
|
||||
updateExternalEditorSettings((prev) => ({
|
||||
...prev,
|
||||
trustedHosts: {
|
||||
...prev.trustedHosts,
|
||||
[hostKey]: policy,
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
export function removeExternalEditorHostTrust(hostKey: string): void {
|
||||
updateExternalEditorSettings((prev) => {
|
||||
if (!Object.prototype.hasOwnProperty.call(prev.trustedHosts, hostKey)) return prev;
|
||||
const nextTrusted = { ...prev.trustedHosts };
|
||||
delete nextTrusted[hostKey];
|
||||
return {
|
||||
...prev,
|
||||
trustedHosts: nextTrusted,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export interface LaunchRemoteExternalEditorParams {
|
||||
editorId?: ExternalEditorPresetId;
|
||||
host: ExternalEditorHostIdentity;
|
||||
remotePath: string;
|
||||
fallbackCwd?: string;
|
||||
kind?: ExternalEditorTargetKind;
|
||||
sessionId?: string;
|
||||
sftpId?: string;
|
||||
settings?: ExternalEditorSettings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared application-layer launcher invoked by both Terminal OSC 7337 handlers
|
||||
* and SFTP context menus.
|
||||
*/
|
||||
export async function launchRemoteExternalEditor(
|
||||
params: LaunchRemoteExternalEditorParams,
|
||||
): Promise<ExternalEditorOpenRemoteResult> {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.externalEditor?.openRemote) {
|
||||
throw new Error('External editor integration requires the desktop application.');
|
||||
}
|
||||
|
||||
const settings = params.settings ?? getExternalEditorSettingsSnapshot();
|
||||
const editorId = params.editorId ?? settings.defaultEditor;
|
||||
const editorConfig = settings.editors[editorId];
|
||||
|
||||
const validated = validateAndNormalizeRemotePath(params.remotePath, params.fallbackCwd);
|
||||
if (!validated.ok) {
|
||||
throw new Error('error' in validated ? validated.error : 'Invalid remote path');
|
||||
}
|
||||
|
||||
const connectionMode = settings.connectionMode;
|
||||
const bridgeHost = connectionMode === 'bridge'
|
||||
? buildSshBridgeHostname(params.host)
|
||||
: undefined;
|
||||
const directSshTarget = connectionMode === 'direct'
|
||||
? buildDirectSshTarget(params.host) ?? undefined
|
||||
: undefined;
|
||||
|
||||
if (connectionMode === 'direct' && !directSshTarget) {
|
||||
throw new Error('Cannot construct a valid OpenSSH target for this host.');
|
||||
}
|
||||
|
||||
return bridge.externalEditor.openRemote({
|
||||
editorId,
|
||||
executablePath: editorConfig?.executablePath || undefined,
|
||||
customArgs: editorId === 'custom' ? editorConfig?.customArgs : undefined,
|
||||
connectionMode,
|
||||
bridgeHost,
|
||||
directSshTarget,
|
||||
sessionId: params.sessionId,
|
||||
sftpId: params.sftpId,
|
||||
hostId: params.host.hostId,
|
||||
hostname: params.host.hostname,
|
||||
port: params.host.port,
|
||||
username: params.host.username,
|
||||
remotePath: validated.path,
|
||||
kind: params.kind ?? 'auto',
|
||||
});
|
||||
}
|
||||
|
||||
export async function detectInstalledExternalEditors(): Promise<Record<string, ExternalEditorDetectEntry>> {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.externalEditor?.detect) return {};
|
||||
return (await bridge.externalEditor.detect()) || {};
|
||||
}
|
||||
|
||||
export async function getExternalEditorBridgeConfigStatus(): Promise<ExternalEditorBridgeConfigStatus | null> {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.externalEditor?.getBridgeConfigStatus) return null;
|
||||
return (await bridge.externalEditor.getBridgeConfigStatus()) || null;
|
||||
}
|
||||
|
||||
export async function installExternalEditorBridgeConfig(): Promise<ExternalEditorBridgeConfigStatus | null> {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.externalEditor?.installBridgeConfig) return null;
|
||||
return bridge.externalEditor.installBridgeConfig();
|
||||
}
|
||||
|
||||
export async function removeExternalEditorBridgeConfig(): Promise<ExternalEditorBridgeConfigStatus | null> {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.externalEditor?.removeBridgeConfig) return null;
|
||||
return bridge.externalEditor.removeBridgeConfig();
|
||||
}
|
||||
|
||||
export async function selectExternalEditorApplication(): Promise<{ path: string; name?: string } | null> {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.selectApplication) return null;
|
||||
return (await bridge.selectApplication()) || null;
|
||||
}
|
||||
|
||||
function getTerminalAutoSetupSnapshotKey(): string {
|
||||
const s = currentSettings;
|
||||
return `${s.terminalRequestsEnabled ? 1 : 0}:${s.autoSetupShellIntegration ? 1 : 0}:${s.defaultEditor}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrow selector for Terminal panes so edits to unrelated External Editor settings
|
||||
* (executable paths, custom args, trust list, bridge mode) never re-render open terminals.
|
||||
*/
|
||||
export function useExternalEditorTerminalAutoSetupConfig(): {
|
||||
terminalRequestsEnabled: boolean;
|
||||
autoSetupShellIntegration: boolean;
|
||||
defaultEditor: ExternalEditorPresetId;
|
||||
} {
|
||||
const key = useSyncExternalStore(
|
||||
subscribe,
|
||||
getTerminalAutoSetupSnapshotKey,
|
||||
getTerminalAutoSetupSnapshotKey,
|
||||
);
|
||||
useEffect(() => {
|
||||
ensureStorageListener();
|
||||
}, []);
|
||||
const [reqFlag, autoFlag, defaultEditor] = key.split(':');
|
||||
return {
|
||||
terminalRequestsEnabled: reqFlag === '1',
|
||||
autoSetupShellIntegration: autoFlag === '1',
|
||||
defaultEditor: defaultEditor as ExternalEditorPresetId,
|
||||
};
|
||||
}
|
||||
|
||||
export function useExternalEditorSettings() {
|
||||
const settings = useSyncExternalStore(
|
||||
subscribe,
|
||||
getExternalEditorSettingsSnapshot,
|
||||
getExternalEditorSettingsSnapshot,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
ensureStorageListener();
|
||||
}, []);
|
||||
|
||||
const setDefaultEditor = useCallback((editorId: ExternalEditorPresetId) => {
|
||||
updateExternalEditorSettings((prev) => ({
|
||||
...prev,
|
||||
defaultEditor: editorId,
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const setEditorExecutablePath = useCallback((editorId: ExternalEditorPresetId, executablePath: string) => {
|
||||
updateExternalEditorSettings((prev) => ({
|
||||
...prev,
|
||||
editors: {
|
||||
...prev.editors,
|
||||
[editorId]: {
|
||||
...prev.editors[editorId],
|
||||
executablePath,
|
||||
},
|
||||
},
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const setCustomEditorArgs = useCallback((customArgs: string[]) => {
|
||||
updateExternalEditorSettings((prev) => ({
|
||||
...prev,
|
||||
editors: {
|
||||
...prev.editors,
|
||||
custom: {
|
||||
...prev.editors.custom,
|
||||
customArgs,
|
||||
},
|
||||
},
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const setTerminalRequestsEnabled = useCallback((enabled: boolean) => {
|
||||
updateExternalEditorSettings((prev) => ({
|
||||
...prev,
|
||||
terminalRequestsEnabled: enabled,
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const setAutoSetupShellIntegration = useCallback((enabled: boolean) => {
|
||||
updateExternalEditorSettings((prev) => ({
|
||||
...prev,
|
||||
autoSetupShellIntegration: enabled,
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const setDefaultTrustPolicy = useCallback((policy: ExternalEditorHostTrustPolicy) => {
|
||||
updateExternalEditorSettings((prev) => ({
|
||||
...prev,
|
||||
defaultTrustPolicy: policy,
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const setConnectionMode = useCallback((mode: ExternalEditorConnectionMode) => {
|
||||
updateExternalEditorSettings((prev) => ({
|
||||
...prev,
|
||||
connectionMode: mode,
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const setHostTrustPolicy = useCallback((hostKey: string, policy: ExternalEditorHostTrustPolicy) => {
|
||||
updateExternalEditorSettings((prev) => ({
|
||||
...prev,
|
||||
trustedHosts: {
|
||||
...prev.trustedHosts,
|
||||
[hostKey]: policy,
|
||||
},
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const removeHostTrustPolicy = useCallback((hostKey: string) => {
|
||||
removeExternalEditorHostTrust(hostKey);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
settings,
|
||||
setDefaultEditor,
|
||||
setEditorExecutablePath,
|
||||
setCustomEditorArgs,
|
||||
setTerminalRequestsEnabled,
|
||||
setAutoSetupShellIntegration,
|
||||
setDefaultTrustPolicy,
|
||||
setConnectionMode,
|
||||
setHostTrustPolicy,
|
||||
removeHostTrustPolicy,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Application-state hook owning external editor detection, `~/.ssh/config` bridge
|
||||
* installation/removal, and application picker lifecycle so UI settings sections
|
||||
* stay presentation-only.
|
||||
*/
|
||||
export function useExternalEditorEnvironment() {
|
||||
const [detectedEditors, setDetectedEditors] = useState<Record<string, ExternalEditorDetectEntry>>({});
|
||||
const [detecting, setDetecting] = useState(false);
|
||||
const [selectingApp, setSelectingApp] = useState(false);
|
||||
const [bridgeStatus, setBridgeStatus] = useState<ExternalEditorBridgeConfigStatus | null>(null);
|
||||
const [bridgeBusy, setBridgeBusy] = useState(false);
|
||||
const [bridgeError, setBridgeError] = useState<string | null>(null);
|
||||
|
||||
const mountedRef = useRef(true);
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const refreshStatus = useCallback(async () => {
|
||||
setDetecting(true);
|
||||
try {
|
||||
const [detected, cfg] = await Promise.all([
|
||||
detectInstalledExternalEditors(),
|
||||
getExternalEditorBridgeConfigStatus(),
|
||||
]);
|
||||
if (!mountedRef.current) return;
|
||||
setDetectedEditors(detected);
|
||||
setBridgeStatus(cfg);
|
||||
setBridgeError(null);
|
||||
} catch (err) {
|
||||
if (!mountedRef.current) return;
|
||||
setBridgeError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
if (mountedRef.current) {
|
||||
setDetecting(false);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refreshStatus();
|
||||
}, [refreshStatus]);
|
||||
|
||||
const browseExecutable = useCallback(async (editorId: ExternalEditorPresetId): Promise<string | null> => {
|
||||
setSelectingApp(true);
|
||||
try {
|
||||
const picked = await selectExternalEditorApplication();
|
||||
if (picked?.path) {
|
||||
updateExternalEditorSettings((prev) => ({
|
||||
...prev,
|
||||
editors: {
|
||||
...prev.editors,
|
||||
[editorId]: {
|
||||
...prev.editors[editorId],
|
||||
executablePath: picked.path,
|
||||
},
|
||||
},
|
||||
}));
|
||||
return picked.path;
|
||||
}
|
||||
return null;
|
||||
} catch (err) {
|
||||
console.error('[ExternalEditor] Failed to select executable:', err);
|
||||
return null;
|
||||
} finally {
|
||||
if (mountedRef.current) {
|
||||
setSelectingApp(false);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
const installBridgeConfig = useCallback(async () => {
|
||||
setBridgeBusy(true);
|
||||
setBridgeError(null);
|
||||
try {
|
||||
const status = await installExternalEditorBridgeConfig();
|
||||
if (mountedRef.current && status) {
|
||||
setBridgeStatus(status);
|
||||
}
|
||||
} catch (err) {
|
||||
if (mountedRef.current) {
|
||||
setBridgeError(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
} finally {
|
||||
if (mountedRef.current) {
|
||||
setBridgeBusy(false);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
const removeBridgeConfig = useCallback(async () => {
|
||||
setBridgeBusy(true);
|
||||
setBridgeError(null);
|
||||
try {
|
||||
const status = await removeExternalEditorBridgeConfig();
|
||||
if (mountedRef.current && status) {
|
||||
setBridgeStatus(status);
|
||||
}
|
||||
} catch (err) {
|
||||
if (mountedRef.current) {
|
||||
setBridgeError(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
} finally {
|
||||
if (mountedRef.current) {
|
||||
setBridgeBusy(false);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
detectedEditors,
|
||||
detecting,
|
||||
selectingApp,
|
||||
bridgeStatus,
|
||||
bridgeBusy,
|
||||
bridgeError,
|
||||
refreshStatus,
|
||||
browseExecutable,
|
||||
installBridgeConfig,
|
||||
removeBridgeConfig,
|
||||
};
|
||||
}
|
||||
@@ -16,7 +16,10 @@ export const checkAppShortcut = (
|
||||
return null;
|
||||
};
|
||||
|
||||
// Get list of key bindings that should be handled at app level (not by terminal)
|
||||
// Get list of key bindings that should be handled at app level (not by terminal).
|
||||
// Conditional shortcuts that pass through to the terminal when unavailable
|
||||
// (like toggleHostTree and addSessionToWorkspace) stay out so an unconsumed
|
||||
// chord still gets full Kitty/Win32/broadcast handling in xterm.
|
||||
export const getAppLevelActions = (): Set<string> => {
|
||||
return new Set([
|
||||
'switchToTab',
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
import { useAppLockChrome } from './appRuntimeBridge';
|
||||
import { resolvePluginViewWindowScope } from './pluginViewScopes';
|
||||
import { pluginViewSessions, type PluginViewSnapshot } from './pluginViewSession';
|
||||
import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
|
||||
@@ -7,15 +8,17 @@ import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
|
||||
const initial = (): PluginViewSnapshot => ({ tree: { children: [] }, css: '', loading: true, error: false, settled: true });
|
||||
export function useHostDrawnPluginView({ viewId, version, slot, active, context, subscribeHidden, unavailable }: {
|
||||
viewId: string; version: string; slot: string; active: boolean; context: Record<string, unknown>;
|
||||
subscribeHidden(listener: () => void): () => void; unavailable(): void;
|
||||
subscribeHidden(listener: (hidden?: boolean) => void): () => void; unavailable(): void;
|
||||
}) {
|
||||
const { locked } = useAppLockChrome();
|
||||
const effectiveActive = active && !locked;
|
||||
const contextKey = JSON.stringify(context);
|
||||
const key = JSON.stringify([viewId, version, slot, contextKey]);
|
||||
const scopeId = typeof window !== 'undefined'
|
||||
? resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` })
|
||||
: '';
|
||||
const sessionKey = scopeId ? JSON.stringify([scopeId, key]) : '';
|
||||
const cachedSession = active && sessionKey ? pluginViewSessions.peek(sessionKey) : null;
|
||||
const cachedSession = effectiveActive && sessionKey ? pluginViewSessions.peek(sessionKey) : null;
|
||||
const [state, setState] = useState<{
|
||||
key: string;
|
||||
snapshot: PluginViewSnapshot;
|
||||
@@ -29,7 +32,7 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
|
||||
const unavailableRef = useRef(unavailable); unavailableRef.current = unavailable;
|
||||
const sessionRef = useRef<{ key: string; image(path: string): Promise<string>; send(event: HostDrawnViewEvent): void } | null>(null);
|
||||
useEffect(() => {
|
||||
if (!active) {
|
||||
if (!effectiveActive) {
|
||||
setHidden(false);
|
||||
return;
|
||||
}
|
||||
@@ -38,18 +41,33 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
|
||||
const resolvedScopeId = resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` });
|
||||
try {
|
||||
const session = pluginViewSessions.acquire(JSON.stringify([resolvedScopeId, key]), bridge, { viewId, scopeId: resolvedScopeId, context: JSON.parse(contextKey) });
|
||||
sessionRef.current = { key, send: session.send, image: session.image };
|
||||
const update = () => { const snapshot = session.getSnapshot(); setState({ key, snapshot, image: session.image }); if (snapshot.error) unavailableRef.current(); };
|
||||
const activeHandle = { key, send: session.send, image: session.image };
|
||||
sessionRef.current = activeHandle;
|
||||
const update = () => {
|
||||
const snapshot = session.getSnapshot();
|
||||
if (snapshot.error) sessionRef.current = null;
|
||||
setState({ key, snapshot, image: session.image });
|
||||
};
|
||||
const stop = session.subscribe(update); update(); setHidden(false);
|
||||
const stopHidden = subscribeHidden(() => { sessionRef.current = null; setHidden(true); });
|
||||
const stopHidden = subscribeHidden((nextHidden = true) => {
|
||||
if (nextHidden) {
|
||||
sessionRef.current = null;
|
||||
setHidden(true);
|
||||
} else {
|
||||
if (!session.getSnapshot().error) sessionRef.current = activeHandle;
|
||||
setHidden(false);
|
||||
}
|
||||
});
|
||||
return () => { sessionRef.current = null; stopHidden(); stop(); session.release(); };
|
||||
} catch { unavailableRef.current(); }
|
||||
}, [active, contextKey, key, slot, subscribeHidden, viewId]);
|
||||
}, [effectiveActive, contextKey, key, slot, subscribeHidden, viewId]);
|
||||
const fallbackLoadImage = useCallback((path: string) => {
|
||||
const session = sessionRef.current;
|
||||
return active && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable'));
|
||||
}, [active, key]);
|
||||
const hasCurrentState = active && state.key === key && cachedSession !== null && state.image === cachedSession.image;
|
||||
return effectiveActive && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable'));
|
||||
}, [effectiveActive, key]);
|
||||
const hasCurrentState = effectiveActive
|
||||
&& state.key === key
|
||||
&& (cachedSession !== null ? state.image === cachedSession.image : state.snapshot.error);
|
||||
const resolvedSnapshot = hasCurrentState
|
||||
? state.snapshot
|
||||
: cachedSession
|
||||
@@ -59,9 +77,9 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
|
||||
? state.image
|
||||
: (cachedSession?.image ?? fallbackLoadImage);
|
||||
const sendEvent = useCallback((event: HostDrawnViewEvent) => {
|
||||
const session = sessionRef.current; if (active && session?.key === key) session.send(event);
|
||||
}, [active, key]);
|
||||
const session = sessionRef.current; if (effectiveActive && session?.key === key) session.send(event);
|
||||
}, [effectiveActive, key]);
|
||||
// A newly selected plugin must never receive values from the previous tree,
|
||||
// even during the render before effect cleanup and the next activation.
|
||||
return { ...resolvedSnapshot, visible: active && !hidden, loadImage, sendEvent };
|
||||
return { ...resolvedSnapshot, visible: effectiveActive && !hidden, loadImage, sendEvent };
|
||||
}
|
||||
@@ -73,15 +73,31 @@ export function usePluginHostActions() {
|
||||
if (entry.prompt.request.kind === 'vault.requestHostDraft' && vault.managedSources !== entry.managedSources) throw new Error('Managed sources changed during draft review');
|
||||
}, [getVault]);
|
||||
|
||||
const clearReview = useCallback((entry: Review) => {
|
||||
if (current.current !== entry) return;
|
||||
current.current = null;
|
||||
responding.current = false;
|
||||
setReview(null);
|
||||
setRemember(false);
|
||||
setBusy(false);
|
||||
setError(false);
|
||||
}, []);
|
||||
|
||||
const fail = useCallback(async (entry: Review) => {
|
||||
if (current.current !== entry) return;
|
||||
setError(true);
|
||||
try {
|
||||
await netcattyBridge.get()?.respondPluginInteraction?.({
|
||||
const accepted = await netcattyBridge.get()?.respondPluginInteraction?.({
|
||||
requestId: entry.prompt.requestId, actionToken: entry.completionToken ?? entry.prompt.actionToken, action: 'fail',
|
||||
});
|
||||
} catch { /* A stopped runtime or closed window already invalidates it. */ }
|
||||
}, []);
|
||||
if (accepted === false) {
|
||||
clearReview(entry);
|
||||
}
|
||||
} catch {
|
||||
// A stopped runtime, closed window, or already-settled prompt will never send { closed: true }.
|
||||
clearReview(entry);
|
||||
}
|
||||
}, [clearReview]);
|
||||
|
||||
const execute = useCallback(async (entry: Review) => {
|
||||
const bridge = netcattyBridge.get();
|
||||
@@ -140,7 +156,8 @@ export function usePluginHostActions() {
|
||||
entry.claimed = true;
|
||||
assertCurrent(entry);
|
||||
await openHostSession(entry.host);
|
||||
await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
|
||||
const completed = await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
|
||||
if (completed === false) clearReview(entry);
|
||||
return;
|
||||
}
|
||||
let action: PluginHostAction;
|
||||
@@ -161,9 +178,16 @@ export function usePluginHostActions() {
|
||||
},
|
||||
connect: openHostSession,
|
||||
});
|
||||
await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
|
||||
const completed = await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
|
||||
if (completed === false) clearReview(entry);
|
||||
} catch { await fail(entry); }
|
||||
}, [assertCurrent, fail, getVault]);
|
||||
finally {
|
||||
if (current.current === entry) {
|
||||
responding.current = false;
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
}, [assertCurrent, clearReview, fail, getVault]);
|
||||
|
||||
useEffect(() => {
|
||||
const bridge = netcattyBridge.get();
|
||||
@@ -282,7 +306,7 @@ export function usePluginHostActions() {
|
||||
if (!entry || responding.current || (action === 'cancel' && entry.claimed)) return;
|
||||
responding.current = true; setBusy(true); setError(false);
|
||||
try {
|
||||
assertCurrent(entry);
|
||||
if (action !== 'cancel') assertCurrent(entry);
|
||||
const request = entry.prompt.request;
|
||||
const selected = request.kind === 'vault.selectHosts' && action === 'submit' ? selectedIds.map((id) => {
|
||||
const revision = entry.candidateRevisions.get(id);
|
||||
@@ -296,18 +320,24 @@ export function usePluginHostActions() {
|
||||
|| request.kind === 'network.stream.tlsConfirm'
|
||||
);
|
||||
const effectiveRemember = rememberOverride ?? remember;
|
||||
await netcattyBridge.require().respondPluginInteraction?.({
|
||||
const accepted = await netcattyBridge.require().respondPluginInteraction?.({
|
||||
requestId: entry.prompt.requestId, actionToken: entry.prompt.actionToken, action,
|
||||
...(selected === undefined ? {} : { resources: selected }),
|
||||
...(draft === undefined ? {} : { draft }),
|
||||
...(request.kind === 'vault.requestConnect' && action === 'submit' ? { scriptsRun: entry.scriptsRun } : {}),
|
||||
...(includeRemember && effectiveRemember ? { remember: true } : {}),
|
||||
});
|
||||
} catch { await fail(entry); }
|
||||
if (accepted === false) {
|
||||
clearReview(entry);
|
||||
}
|
||||
} catch {
|
||||
if (action === 'cancel') clearReview(entry);
|
||||
else await fail(entry);
|
||||
}
|
||||
finally {
|
||||
if (current.current === entry && entry.prompt.phase === 'request') { responding.current = false; setBusy(false); }
|
||||
}
|
||||
}, [assertCurrent, fail, remember, selectedIds]);
|
||||
}, [assertCurrent, clearReview, fail, remember, selectedIds]);
|
||||
|
||||
return { review, selectedIds, setSelectedIds, remember, setRemember, busy, error, respond };
|
||||
}
|
||||
@@ -19,7 +19,7 @@ export function usePluginHostInteractions() {
|
||||
if (current.current?.requestId !== event.requestId) return;
|
||||
current.current = null; setPrompt(null);
|
||||
} else {
|
||||
if (event.request.kind.startsWith('vault.') || event.request.kind === 'network.stream.connectViaHost') return;
|
||||
if (event.request.kind.startsWith('vault.') || event.request.kind.startsWith('network.stream.')) return;
|
||||
current.current = event as UiPrompt;
|
||||
if (event.request.kind === 'terminal.selection.read' && event.phase === 'request') {
|
||||
setPrompt(null);
|
||||
|
||||
@@ -26,6 +26,7 @@ export const OPEN_PLUGIN_VIEW_EVENT = 'netcatty:open-plugin-view';
|
||||
export interface OpenPluginViewDetail {
|
||||
viewId: string;
|
||||
context?: Record<string, unknown>;
|
||||
params?: unknown;
|
||||
}
|
||||
|
||||
export type ResolvedPluginView = {
|
||||
@@ -148,7 +149,12 @@ export function usePluginViewLifecycle({
|
||||
}, [contributions.loading, contributions.snapshot.plugins]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!requested || activeView?.view.location !== 'tab') return;
|
||||
if (!requested || viewContributions.loading) return;
|
||||
if (!resolvedActiveView) {
|
||||
setRequested(null);
|
||||
return;
|
||||
}
|
||||
if (activeView?.view.location !== 'tab') return;
|
||||
pluginViewTabStore.open({
|
||||
pluginId: activeView.plugin.id,
|
||||
pluginName: activeView.plugin.displayName,
|
||||
@@ -158,7 +164,7 @@ export function usePluginViewLifecycle({
|
||||
context: requested.context,
|
||||
});
|
||||
setRequested(null);
|
||||
}, [activeView, requested]);
|
||||
}, [activeView, requested, resolvedActiveView, viewContributions.loading]);
|
||||
|
||||
useEffect(() => {
|
||||
const stop = pluginViewTabStore.onDidClose(({ tab }) => closePluginViewSessionIfLoaded(tab.viewId));
|
||||
|
||||
@@ -766,13 +766,14 @@ export const useSessionState = ({
|
||||
const preferredTabId = activeTabStore.getPreviousActiveTabId();
|
||||
const tabOrderSnapshot = tabOrderRef.current;
|
||||
const sessionsSnapshot = sessionsRef.current;
|
||||
// Queue removal outside the workspace updater so React retains it when
|
||||
// lower-priority session updates are rebased after this close.
|
||||
setSessions(prevSessions => prevSessions.filter(s => s.workspaceId !== workspaceId));
|
||||
setTabOrder(prevTabOrder => prevTabOrder.filter(id => id !== workspaceId));
|
||||
setWorkspaces(prevWorkspaces => {
|
||||
const remainingWorkspaces = prevWorkspaces.filter(w => w.id !== workspaceId);
|
||||
const remainingSessions = sessionsSnapshot.filter(s => s.workspaceId !== workspaceId);
|
||||
|
||||
setSessions(prevSessions => prevSessions.filter(s => s.workspaceId !== workspaceId));
|
||||
|
||||
const nextActiveTabId = resolveActiveTabAfterCloseWorkspace({
|
||||
currentActiveTabId: activeTabStore.getActiveTabId(),
|
||||
closedWorkspaceId: workspaceId,
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import React, { useEffect } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { flushSync } from 'react-dom';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { activeTabStore } from './activeTabStore';
|
||||
import { useSessionState } from './useSessionState';
|
||||
import type { Host } from '../../domain/models';
|
||||
|
||||
const settle = (ms = 20) => new Promise<void>(resolve => setTimeout(resolve, ms));
|
||||
|
||||
test('workspace Close does not restore removed panes when a queued session update is rebased', async () => {
|
||||
const dom = new JSDOM('<div id="root"></div>', { url: 'http://localhost' });
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const [key, value] of Object.entries({
|
||||
window: dom.window, document: dom.window.document,
|
||||
localStorage: dom.window.localStorage, CustomEvent: dom.window.CustomEvent,
|
||||
Event: dom.window.Event,
|
||||
})) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, value });
|
||||
}
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
let state!: ReturnType<typeof useSessionState>;
|
||||
let closingId = '';
|
||||
const mounts = new Map<string, number>();
|
||||
function Pane({ id }: { id: string }) {
|
||||
useEffect(() => { mounts.set(id, (mounts.get(id) ?? 0) + 1); }, [id]);
|
||||
return null;
|
||||
}
|
||||
function Probe() {
|
||||
state = useSessionState({ persistSessionRestore: false });
|
||||
return <>
|
||||
<button onClick={() => state.closeWorkspace(closingId)}>Close</button>
|
||||
{state.sessions.map(s => <Pane key={s.id} id={s.id} />)}
|
||||
</>;
|
||||
}
|
||||
async function connect(name: string, count: number) {
|
||||
const hosts = Array.from({ length: count }, (_, i) => ({
|
||||
id: `${name}-${i}`, label: `${name}-${i}`, hostname: 'host.test',
|
||||
username: 'alice', protocol: 'ssh',
|
||||
} as Host));
|
||||
flushSync(() => state.createWorkspaceWithHosts(name, hosts));
|
||||
await settle();
|
||||
const workspace = state.workspaces.at(-1)!;
|
||||
flushSync(() => {
|
||||
for (const s of state.sessions.filter(s => s.workspaceId === workspace.id)) {
|
||||
state.updateSessionStatus(s.id, 'connected');
|
||||
}
|
||||
});
|
||||
await settle();
|
||||
return workspace;
|
||||
}
|
||||
async function close(id: string, queueCwd = false) {
|
||||
closingId = id;
|
||||
// A cwd observation without pendingInitialCwd queues a no-op update at
|
||||
// default priority. The discrete Close runs first; React later rebases
|
||||
// that queue. Wrapping this preparation in act would hide the schedule.
|
||||
const session = state.sessions.find(s => s.workspaceId === id)!;
|
||||
if (queueCwd) state.updateSessionRestoreCwd(session.id, '/home/alice');
|
||||
document.querySelector('button')!.click();
|
||||
await settle(100);
|
||||
assert(!state.workspaces.some(w => w.id === id));
|
||||
assert(!state.sessions.some(s => s.workspaceId === id), 'closed workspace sessions must stay removed after queued updates settle');
|
||||
}
|
||||
try {
|
||||
activeTabStore.setActiveTabId('vault', { recordPrevious: false });
|
||||
flushSync(() => root.render(<Probe />));
|
||||
const left = await connect('left', 2);
|
||||
const target = await connect('target', 6);
|
||||
const targetIds = state.sessions.filter(s => s.workspaceId === target.id).map(s => s.id);
|
||||
// Keep the target mounted while other connected workspaces are used.
|
||||
for (let i = 0; i < 3; i++) await close((await connect(`warm-${i}`, 2)).id);
|
||||
const right = await connect('right', 2);
|
||||
await close(right.id);
|
||||
await close(left.id);
|
||||
assert.deepEqual(state.sessions.map(s => s.id), targetIds);
|
||||
assert(state.sessions.every(s => s.status === 'connected'));
|
||||
assert.equal(activeTabStore.getActiveTabId(), target.id);
|
||||
await close(target.id, true);
|
||||
assert.equal(state.sessions.length, 0);
|
||||
assert.equal(state.workspaces.length, 0);
|
||||
assert.equal(activeTabStore.getActiveTabId(), 'vault');
|
||||
assert([...mounts.values()].every(count => count === 1), 'Close must not remount any closed pane');
|
||||
} finally {
|
||||
flushSync(() => root.unmount());
|
||||
activeTabStore.setActiveTabId('vault', { recordPrevious: false });
|
||||
await settle();
|
||||
dom.window.close();
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -88,6 +88,7 @@ import {
|
||||
STORAGE_KEY_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT,
|
||||
STORAGE_KEY_SHOW_SFTP_TAB,
|
||||
STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR,
|
||||
STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA,
|
||||
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN,
|
||||
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
|
||||
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN,
|
||||
@@ -98,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';
|
||||
@@ -145,6 +149,7 @@ import {
|
||||
DEFAULT_HOST_CLICK_BEHAVIOR,
|
||||
DEFAULT_SHOW_SFTP_TAB,
|
||||
DEFAULT_SHOW_HOST_TREE_SIDEBAR,
|
||||
DEFAULT_REMOVE_TOP_TABS_DRAG_AREA,
|
||||
DEFAULT_SHELL_ONLY_TAB_NUMBER_SHORTCUTS,
|
||||
DEFAULT_SHOW_TAB_NUMBER_BADGES,
|
||||
DEFAULT_DISABLE_TERMINAL_FONT_ZOOM,
|
||||
@@ -472,6 +477,10 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR);
|
||||
return stored ?? DEFAULT_SHOW_HOST_TREE_SIDEBAR;
|
||||
});
|
||||
const [removeTopTabsDragArea, setRemoveTopTabsDragAreaState] = useState<boolean>(() => {
|
||||
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA);
|
||||
return stored ?? DEFAULT_REMOVE_TOP_TABS_DRAG_AREA;
|
||||
});
|
||||
const [terminalSidePanelAutoOpen, setTerminalSidePanelAutoOpenState] = useState<boolean>(() => {
|
||||
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN);
|
||||
return stored ?? DEFAULT_TERMINAL_SIDE_PANEL_AUTO_OPEN_ENABLED;
|
||||
@@ -1186,6 +1195,8 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
setShowSftpTabState(storedShowSftpTab ?? DEFAULT_SHOW_SFTP_TAB);
|
||||
const storedShowHostTreeSidebar = localStorageAdapter.readBoolean(STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR);
|
||||
setShowHostTreeSidebarState(storedShowHostTreeSidebar ?? DEFAULT_SHOW_HOST_TREE_SIDEBAR);
|
||||
const storedRemoveTopTabsDragArea = localStorageAdapter.readBoolean(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA);
|
||||
setRemoveTopTabsDragAreaState(storedRemoveTopTabsDragArea ?? DEFAULT_REMOVE_TOP_TABS_DRAG_AREA);
|
||||
const storedTerminalSidePanelAutoOpen = localStorageAdapter.readBoolean(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN);
|
||||
setTerminalSidePanelAutoOpenState(storedTerminalSidePanelAutoOpen ?? DEFAULT_TERMINAL_SIDE_PANEL_AUTO_OPEN_ENABLED);
|
||||
const storedTerminalSidePanelAutoOpenTab = readStoredString(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB);
|
||||
@@ -1489,7 +1500,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
|
||||
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
|
||||
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, removeTopTabsDragArea, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
|
||||
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
|
||||
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
|
||||
@@ -1501,7 +1512,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
setFollowAppTerminalThemeState, setTerminalFontFamilyId, setTerminalFontSize: applyIncomingTerminalFontSize,
|
||||
setSftpDoubleClickBehavior, setSftpAutoSync, setSftpShowHiddenFiles,
|
||||
setSftpUseCompressedUpload, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode,
|
||||
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
|
||||
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setRemoveTopTabsDragAreaState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
|
||||
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled,
|
||||
setRemoteDesktopAutoRecordState, setRemoteDesktopRecordingFpsState, setRemoteDesktopRecordingIncludeAudioState, setRemoteDesktopRecordingMaxMbState, setRemoteDesktopRecordingRetentionDaysState,
|
||||
setSshDebugLogsEnabled, setSshDeepLinkEnabledState: applyIncomingSshDeepLinkEnabled, setJmsDeepLinkEnabledState: applyIncomingJmsDeepLinkEnabled, setJumpServerRdpLaunchModeState, setExplorerContextMenuEnabledState: applyIncomingExplorerContextMenuEnabled,
|
||||
@@ -1647,6 +1658,13 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
notifySettingsChanged(STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR, enabled);
|
||||
}, [notifySettingsChanged]);
|
||||
|
||||
const setRemoveTopTabsDragArea = useCallback((enabled: boolean) => {
|
||||
setRemoveTopTabsDragAreaState(enabled);
|
||||
localStorageAdapter.writeBoolean(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA, enabled);
|
||||
if (!persistMountedRef.current) return;
|
||||
notifySettingsChanged(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA, enabled);
|
||||
}, [notifySettingsChanged]);
|
||||
|
||||
const setTerminalSidePanelAutoOpen = useCallback((enabled: boolean) => {
|
||||
setTerminalSidePanelAutoOpenState(enabled);
|
||||
localStorageAdapter.writeBoolean(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN, enabled);
|
||||
@@ -2116,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({});
|
||||
@@ -2181,6 +2214,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
windowOpacity,
|
||||
showSftpTab,
|
||||
showHostTreeSidebar,
|
||||
removeTopTabsDragArea,
|
||||
showRecentHosts,
|
||||
hostClickBehavior,
|
||||
showOnlyUngroupedHostsInRoot,
|
||||
@@ -2205,6 +2239,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
restoreTerminalCwd,
|
||||
shellOnlyTabNumberShortcuts,
|
||||
showHostTreeSidebar,
|
||||
removeTopTabsDragArea,
|
||||
showOnlyUngroupedHostsInRoot,
|
||||
showRecentHosts,
|
||||
showSftpTab,
|
||||
@@ -2353,6 +2388,9 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
keyBindings,
|
||||
customKeyBindings,
|
||||
updateKeyBinding,
|
||||
updateKeyBindingExtra,
|
||||
addKeyBindingExtra,
|
||||
removeKeyBindingExtra,
|
||||
resetKeyBinding,
|
||||
resetAllKeyBindings,
|
||||
isHotkeyRecording,
|
||||
@@ -2385,6 +2423,8 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
setShowSftpTab,
|
||||
showHostTreeSidebar,
|
||||
setShowHostTreeSidebar,
|
||||
removeTopTabsDragArea,
|
||||
setRemoveTopTabsDragArea,
|
||||
terminalSidePanelAutoOpen,
|
||||
setTerminalSidePanelAutoOpen,
|
||||
terminalSidePanelAutoOpenTab,
|
||||
|
||||
@@ -11,11 +11,11 @@ type SessionProps = Parameters<typeof useTerminalDirectorySession>[0];
|
||||
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
|
||||
function installBridge(t: TestContext, getAppInfo?: NetcattyBridge['getAppInfo']) {
|
||||
function installBridge(t: TestContext, getAppInfo?: NetcattyBridge['getAppInfo'], discoverShells?: NetcattyBridge['discoverShells']) {
|
||||
const previous = Object.getOwnPropertyDescriptor(globalThis, 'window');
|
||||
let probes = 0; let lists = 0;
|
||||
Object.defineProperty(globalThis, 'window', { configurable: true, value: { netcatty: {
|
||||
getAppInfo,
|
||||
getAppInfo, discoverShells,
|
||||
getSessionPwd: async () => { probes++; return { success: true, cwd: '/actual' }; },
|
||||
listLocalDir: async () => { lists++; return []; },
|
||||
} } });
|
||||
@@ -55,6 +55,19 @@ for (const wrapper of ['wsl-Ubuntu', 'git-bash', 'cygwin']) {
|
||||
});
|
||||
}
|
||||
|
||||
test('a discovered Cygwin terminal registers its own POSIX directory controller', async t => {
|
||||
installBridge(t, async () => ({ name: 'Netcatty', version: 'test', platform: 'win32' }), async () => [
|
||||
{ id: 'cygwin', name: 'Cygwin', command: 'C:/cygwin64/bin/bash.exe', args: ['--login', '-i'], icon: 'cygwin' },
|
||||
]);
|
||||
const props = options('cygwin-tab');
|
||||
props.host = { ...props.host, localShell: 'cygwin' };
|
||||
function Harness() { useTerminalDirectorySession(props); return null; }
|
||||
let root!: ReactTestRenderer;
|
||||
await act(async () => { root = create(React.createElement(Harness)); });
|
||||
t.after(async () => { await act(async () => { root.unmount(); }); });
|
||||
assert.deepEqual(getTerminalDirectory(props.sessionId)?.target, { authority: 'cygwin:cygwin-tab', pathFlavor: 'posix' });
|
||||
});
|
||||
|
||||
for (const platform of ['linux', 'darwin']) {
|
||||
test(`local POSIX directory controller registers on ${platform}`, async t => {
|
||||
installBridge(t, async () => ({ name: 'Netcatty', version: 'test', platform }));
|
||||
|
||||
@@ -7,7 +7,7 @@ import { createTerminalDirectoryController } from './terminalDirectoryController
|
||||
import { registerTerminalDirectory } from './terminalDirectoryRegistry';
|
||||
import { directoryChangeCommand, COMPLETE_DIRECTORY_CAPABILITIES, type WindowsDirectoryShell } from '../../domain/directoryPicker';
|
||||
import type { DirectoryPathFlavor } from '../../domain/directoryPath';
|
||||
import { isDiscoveredGitBash } from '../../lib/localShell';
|
||||
import { isDiscoveredCygwin, isDiscoveredGitBash } from '../../lib/localShell';
|
||||
|
||||
export function useTerminalDirectorySession(options: {
|
||||
sessionId: string;
|
||||
@@ -36,16 +36,18 @@ export function useTerminalDirectorySession(options: {
|
||||
let unregister = () => {};
|
||||
const register = (pathFlavor: DirectoryPathFlavor = 'posix', integration?: WindowsDirectoryShell) => {
|
||||
if (!isCurrent()) return;
|
||||
const sessionFilesystem = integration === 'wsl' || integration === 'cygwin';
|
||||
const controller = createTerminalDirectoryController({
|
||||
sessionId,
|
||||
localPosixSessionId: local && !integration ? backendId : undefined,
|
||||
io: createTerminalDirectoryIO(bridge, backendId, {
|
||||
local, hostname: host.hostname, username: host.username || 'root', port: host.port,
|
||||
encoding: host.sftpEncoding,
|
||||
pathFlavor,
|
||||
windowsShell: integration,
|
||||
}, isCurrent),
|
||||
target: { authority: `${integration === 'wsl' ? 'wsl' : local ? 'local' : 'ssh'}:${backendId}`, pathFlavor },
|
||||
trustOsc7: integration !== 'wsl',
|
||||
target: { authority: `${sessionFilesystem ? integration : local ? 'local' : 'ssh'}:${backendId}`, pathFlavor },
|
||||
trustOsc7: !sessionFilesystem,
|
||||
capabilities: COMPLETE_DIRECTORY_CAPABILITIES,
|
||||
buildChangeCommand: path => directoryChangeCommand(path, integration ?? 'posix', pathFlavor),
|
||||
isCurrent,
|
||||
@@ -67,6 +69,8 @@ export function useTerminalDirectorySession(options: {
|
||||
register('posix', 'wsl');
|
||||
} else if (isDiscoveredGitBash(host.localShell, shells?.find(item => item.id === 'git-bash')?.command)) {
|
||||
register('win32', 'git-bash');
|
||||
} else if (isDiscoveredCygwin(host.localShell, shells?.find(item => item.id === 'cygwin')?.command)) {
|
||||
register('posix', 'cygwin');
|
||||
}
|
||||
}
|
||||
}).catch(() => {});
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
EXTERNAL_EDITOR_AUTO_SETUP_SHELL_PREFIX,
|
||||
EXTERNAL_EDITOR_AUTO_SETUP_UPDATED_MARKER,
|
||||
} from '../../domain/externalEditor';
|
||||
import { createExternalEditorSessionProvisioner } from './useTerminalExternalEditor';
|
||||
|
||||
function flushMicrotasks(): Promise<void> {
|
||||
return new Promise((resolve) => setImmediate(resolve));
|
||||
}
|
||||
|
||||
test('provisions initial editor helpers and activates PATH once, then installs newly selected editor without re-injecting PATH', async () => {
|
||||
const execCalls: { sessionId: string; command: string }[] = [];
|
||||
const writeCalls: { sessionId: string; data: string; opts?: { automated?: boolean } }[] = [];
|
||||
const configuredLabels: string[] = [];
|
||||
|
||||
const provisioner = createExternalEditorSessionProvisioner({
|
||||
setupExec: async (sessionId, command) => {
|
||||
execCalls.push({ sessionId, command });
|
||||
return {
|
||||
success: true,
|
||||
stdout: `${EXTERNAL_EDITOR_AUTO_SETUP_SHELL_PREFIX}posix\n${EXTERNAL_EDITOR_AUTO_SETUP_UPDATED_MARKER}\n`,
|
||||
};
|
||||
},
|
||||
writeToSession: (sessionId, data, opts) => {
|
||||
writeCalls.push({ sessionId, data, opts });
|
||||
},
|
||||
getCurrentSessionId: () => 'sess-1',
|
||||
isReadyForCommandInjection: () => true,
|
||||
onConfigured: (label) => configuredLabels.push(label),
|
||||
});
|
||||
|
||||
// 1. Initial connection with Zed
|
||||
const cancelZed = provisioner.sync({ sessionId: 'sess-1', defaultEditor: 'zed' });
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.equal(execCalls.length, 1);
|
||||
assert.match(execCalls[0].command, /write_bin '\\''zed'\\''/);
|
||||
assert.doesNotMatch(execCalls[0].command, /write_bin '\\''code'\\''/);
|
||||
assert.equal(writeCalls.length, 1);
|
||||
assert.match(writeCalls[0].data, /export PATH="\$HOME\/\.netcatty\/bin:\$PATH" NETCATTY_EXTERNAL_EDITOR=1/);
|
||||
assert.deepEqual(writeCalls[0].opts, { automated: true });
|
||||
assert.deepEqual(configuredLabels, ['Zed']);
|
||||
|
||||
// 2. Switching preferred editor to VS Code in the same live session installs `code`
|
||||
// without injecting a duplicate PATH activation command into the terminal.
|
||||
cancelZed();
|
||||
const cancelVscode = provisioner.sync({ sessionId: 'sess-1', defaultEditor: 'vscode' });
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.equal(execCalls.length, 2);
|
||||
assert.match(execCalls[1].command, /write_bin '\\''code'\\''/);
|
||||
assert.equal(writeCalls.length, 1);
|
||||
assert.deepEqual(configuredLabels, ['Zed', 'VS Code']);
|
||||
|
||||
// 3. Switching back to Zed in the same session is a no-op (already provisioned + activated).
|
||||
cancelVscode();
|
||||
const cancelZedAgain = provisioner.sync({ sessionId: 'sess-1', defaultEditor: 'zed' });
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.equal(execCalls.length, 2);
|
||||
assert.equal(writeCalls.length, 1);
|
||||
cancelZedAgain();
|
||||
});
|
||||
|
||||
test('polls until terminal prompt is ready and cancels cleanly if editor changes before prompt settles', async () => {
|
||||
const execCalls: string[] = [];
|
||||
const writeCalls: string[] = [];
|
||||
const timers = new Map<number, () => void>();
|
||||
let nextTimerId = 1;
|
||||
let ready = false;
|
||||
|
||||
const provisioner = createExternalEditorSessionProvisioner({
|
||||
setupExec: async (_sessionId, command) => {
|
||||
execCalls.push(command);
|
||||
return {
|
||||
success: true,
|
||||
stdout: `${EXTERNAL_EDITOR_AUTO_SETUP_SHELL_PREFIX}fish\n${EXTERNAL_EDITOR_AUTO_SETUP_UPDATED_MARKER}\n`,
|
||||
};
|
||||
},
|
||||
writeToSession: (_sessionId, data) => {
|
||||
writeCalls.push(data);
|
||||
},
|
||||
getCurrentSessionId: () => 'sess-2',
|
||||
isReadyForCommandInjection: () => ready,
|
||||
scheduleTimer: (fn) => {
|
||||
const id = nextTimerId++;
|
||||
timers.set(id, fn);
|
||||
return id as unknown as ReturnType<typeof setTimeout>;
|
||||
},
|
||||
clearTimer: (handle) => {
|
||||
timers.delete(handle as unknown as number);
|
||||
},
|
||||
});
|
||||
|
||||
// Start with Zed while prompt is still busy with MOTD.
|
||||
const cancelZed = provisioner.sync({ sessionId: 'sess-2', defaultEditor: 'zed' });
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.equal(execCalls.length, 1);
|
||||
assert.equal(writeCalls.length, 0);
|
||||
assert.equal(timers.size, 1);
|
||||
|
||||
// Switch to Cursor before prompt becomes ready: old poll is cancelled, Cursor is provisioned.
|
||||
cancelZed();
|
||||
assert.equal(timers.size, 0);
|
||||
|
||||
const cancelCursor = provisioner.sync({ sessionId: 'sess-2', defaultEditor: 'cursor' });
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.equal(execCalls.length, 2);
|
||||
assert.match(execCalls[1], /write_bin '\\''cursor'\\''/);
|
||||
assert.equal(writeCalls.length, 0);
|
||||
assert.equal(timers.size, 1);
|
||||
|
||||
// Prompt becomes ready -> fish PATH activation executes once.
|
||||
ready = true;
|
||||
const scheduled = [...timers.values()];
|
||||
timers.clear();
|
||||
scheduled.forEach((fn) => fn());
|
||||
|
||||
assert.equal(writeCalls.length, 1);
|
||||
assert.match(writeCalls[0], /set -gx PATH "\$HOME\/\.netcatty\/bin" \$PATH/);
|
||||
cancelCursor();
|
||||
});
|
||||
|
||||
test('resets per-session tracking on disconnect so reconnect re-activates PATH', async () => {
|
||||
let activeSessionId = 'sess-3';
|
||||
const execCalls: string[] = [];
|
||||
const writeCalls: string[] = [];
|
||||
|
||||
const provisioner = createExternalEditorSessionProvisioner({
|
||||
setupExec: async (sessionId) => {
|
||||
execCalls.push(sessionId);
|
||||
return {
|
||||
success: true,
|
||||
stdout: `${EXTERNAL_EDITOR_AUTO_SETUP_SHELL_PREFIX}posix\n`,
|
||||
};
|
||||
},
|
||||
writeToSession: (sessionId) => {
|
||||
writeCalls.push(sessionId);
|
||||
},
|
||||
getCurrentSessionId: () => activeSessionId,
|
||||
isReadyForCommandInjection: () => true,
|
||||
});
|
||||
|
||||
const cancelFirst = provisioner.sync({ sessionId: 'sess-3', defaultEditor: 'zed' });
|
||||
await flushMicrotasks();
|
||||
assert.equal(execCalls.length, 1);
|
||||
assert.equal(writeCalls.length, 1);
|
||||
cancelFirst();
|
||||
|
||||
// Disconnect resets session state even if the same sessionId reconnects.
|
||||
provisioner.reset();
|
||||
const cancelSecond = provisioner.sync({ sessionId: 'sess-3', defaultEditor: 'zed' });
|
||||
await flushMicrotasks();
|
||||
assert.equal(execCalls.length, 2);
|
||||
assert.equal(writeCalls.length, 2);
|
||||
cancelSecond();
|
||||
|
||||
// New backend sessionId also provisions and activates fresh.
|
||||
activeSessionId = 'sess-4';
|
||||
const cancelThird = provisioner.sync({ sessionId: 'sess-4', defaultEditor: 'zed' });
|
||||
await flushMicrotasks();
|
||||
assert.equal(execCalls.length, 3);
|
||||
assert.equal(writeCalls.length, 3);
|
||||
cancelThird();
|
||||
});
|
||||
@@ -0,0 +1,387 @@
|
||||
/**
|
||||
* useTerminalExternalEditor - Application-state hook & session provisioner for
|
||||
* Terminal External Editor integration (OSC 7337 requests, per-host trust prompts,
|
||||
* and session-scoped ~/.netcatty/bin helper provisioning + one-time PATH activation).
|
||||
*/
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
EXTERNAL_EDITOR_AUTO_SETUP_UPDATED_MARKER,
|
||||
buildExternalEditorAutoSetupCommand,
|
||||
buildExternalEditorSessionActivateCommand,
|
||||
getExternalEditorLabel,
|
||||
parseExternalEditorAutoSetupShell,
|
||||
resolveExternalEditorTrustPolicy,
|
||||
shouldAutoSetupExternalEditorShell,
|
||||
validateAndNormalizeRemotePath,
|
||||
type ExternalEditorOscRequest,
|
||||
type ExternalEditorPresetId,
|
||||
type ExternalEditorTargetKind,
|
||||
} from '../../domain/externalEditor';
|
||||
import type { Host } from '../../domain/models';
|
||||
import { logger } from '../../lib/logger';
|
||||
import {
|
||||
getExternalEditorSettingsSnapshot,
|
||||
launchRemoteExternalEditor,
|
||||
setExternalEditorHostTrust,
|
||||
useExternalEditorTerminalAutoSetupConfig,
|
||||
} from './useExternalEditorSettings';
|
||||
|
||||
export interface PendingExternalEditorRequest {
|
||||
editorId: ExternalEditorPresetId;
|
||||
editorLabel: string;
|
||||
remotePath: string;
|
||||
kind: ExternalEditorTargetKind;
|
||||
}
|
||||
|
||||
export interface ExternalEditorSessionSetupResult {
|
||||
success?: boolean;
|
||||
stdout?: string;
|
||||
stderr?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface ExternalEditorSessionProvisionerDeps {
|
||||
setupExec: (sessionId: string, command: string) => Promise<ExternalEditorSessionSetupResult>;
|
||||
writeToSession: (sessionId: string, data: string, opts?: { automated?: boolean }) => void;
|
||||
getCurrentSessionId: () => string | null;
|
||||
isReadyForCommandInjection: () => boolean;
|
||||
onConfigured?: (editorLabel: string) => void;
|
||||
onWarn?: (message: string, detail?: unknown) => void;
|
||||
scheduleTimer?: (fn: () => void, ms: number) => ReturnType<typeof setTimeout>;
|
||||
clearTimer?: (handle: ReturnType<typeof setTimeout>) => void;
|
||||
pollIntervalMs?: number;
|
||||
maxPollAttempts?: number;
|
||||
}
|
||||
|
||||
export interface ExternalEditorSessionProvisioner {
|
||||
reset: () => void;
|
||||
sync: (params: {
|
||||
sessionId: string;
|
||||
defaultEditor: ExternalEditorPresetId;
|
||||
}) => () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stateful session helper provisioner separated from React so lifecycle
|
||||
* transitions (initial setup, preferred-editor switching without re-injecting
|
||||
* PATH, disconnect reset, and cancellation) can be tested deterministically.
|
||||
*/
|
||||
export function createExternalEditorSessionProvisioner(
|
||||
deps: ExternalEditorSessionProvisionerDeps,
|
||||
): ExternalEditorSessionProvisioner {
|
||||
const scheduleTimer = deps.scheduleTimer ?? ((fn, ms) => setTimeout(fn, ms));
|
||||
const clearTimer = deps.clearTimer ?? ((handle) => clearTimeout(handle));
|
||||
const pollIntervalMs = deps.pollIntervalMs ?? 100;
|
||||
const maxPollAttempts = deps.maxPollAttempts ?? 60;
|
||||
|
||||
let trackedSessionId: string | null = null;
|
||||
let provisionedEditors = new Set<ExternalEditorPresetId>();
|
||||
let pathActivated = false;
|
||||
|
||||
const reset = () => {
|
||||
trackedSessionId = null;
|
||||
provisionedEditors = new Set();
|
||||
pathActivated = false;
|
||||
};
|
||||
|
||||
const sync = ({
|
||||
sessionId,
|
||||
defaultEditor,
|
||||
}: {
|
||||
sessionId: string;
|
||||
defaultEditor: ExternalEditorPresetId;
|
||||
}): (() => void) => {
|
||||
if (trackedSessionId !== sessionId) {
|
||||
trackedSessionId = sessionId;
|
||||
provisionedEditors = new Set();
|
||||
pathActivated = false;
|
||||
}
|
||||
|
||||
if (provisionedEditors.has(defaultEditor) && pathActivated) {
|
||||
return () => {};
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
let pollTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const setupCmd = buildExternalEditorAutoSetupCommand(defaultEditor);
|
||||
|
||||
void deps.setupExec(sessionId, setupCmd).then((result) => {
|
||||
if (cancelled) return;
|
||||
if (trackedSessionId !== sessionId || deps.getCurrentSessionId() !== sessionId) return;
|
||||
if (!result?.success) {
|
||||
deps.onWarn?.(
|
||||
'[Terminal] External editor session helper setup failed:',
|
||||
result?.error || result?.stderr,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
provisionedEditors.add(defaultEditor);
|
||||
const updated = typeof result.stdout === 'string'
|
||||
&& result.stdout.includes(EXTERNAL_EDITOR_AUTO_SETUP_UPDATED_MARKER);
|
||||
|
||||
// PATH is already active in this shell session (e.g. user changed preferred
|
||||
// editor while connected); the new wrapper in ~/.netcatty/bin is immediately
|
||||
// available without injecting another PATH command into the running terminal.
|
||||
if (pathActivated) {
|
||||
if (updated) {
|
||||
deps.onConfigured?.(getExternalEditorLabel(defaultEditor));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const shellKind = parseExternalEditorAutoSetupShell(result.stdout);
|
||||
const activateCmd = buildExternalEditorSessionActivateCommand(shellKind);
|
||||
|
||||
let attempts = 0;
|
||||
const tryActivateInSession = () => {
|
||||
if (cancelled) return;
|
||||
if (trackedSessionId !== sessionId || deps.getCurrentSessionId() !== sessionId) return;
|
||||
if (pathActivated) return;
|
||||
|
||||
if (deps.isReadyForCommandInjection()) {
|
||||
pathActivated = true;
|
||||
deps.writeToSession(sessionId, activateCmd, { automated: true });
|
||||
if (updated) {
|
||||
deps.onConfigured?.(getExternalEditorLabel(defaultEditor));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
attempts += 1;
|
||||
if (attempts < maxPollAttempts) {
|
||||
pollTimer = scheduleTimer(tryActivateInSession, pollIntervalMs);
|
||||
}
|
||||
};
|
||||
|
||||
tryActivateInSession();
|
||||
}).catch((err) => {
|
||||
if (cancelled) return;
|
||||
deps.onWarn?.('[Terminal] External editor session helper setup error:', err);
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (pollTimer !== null) {
|
||||
clearTimer(pollTimer);
|
||||
pollTimer = null;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
return { reset, sync };
|
||||
}
|
||||
|
||||
export interface UseTerminalExternalEditorOptions {
|
||||
sessionId: string;
|
||||
status: string;
|
||||
host: Pick<
|
||||
Host,
|
||||
'id' | 'hostname' | 'port' | 'username' | 'label' | 'protocol' | 'externalEditorShellIntegration'
|
||||
>;
|
||||
isLocalConnection: boolean;
|
||||
isSerialConnection: boolean;
|
||||
getBackendSessionId: () => string | null;
|
||||
isVisible: () => boolean;
|
||||
getFallbackCwd: () => string | undefined;
|
||||
isReadyForCommandInjection: () => boolean;
|
||||
setupOsc7Tracking?: (sessionId: string, command: string) => Promise<ExternalEditorSessionSetupResult>;
|
||||
writeToSession: (sessionId: string, data: string, opts?: { automated?: boolean }) => void;
|
||||
focusTerminal: () => void;
|
||||
onOpened: (editorLabel: string, remotePath: string) => void;
|
||||
onOpenFailed: (message: string) => void;
|
||||
formatFallbackOpenError: (editorLabel: string) => string;
|
||||
onAutoSetupConfigured: (editorLabel: string) => void;
|
||||
}
|
||||
|
||||
export function useTerminalExternalEditor(options: UseTerminalExternalEditorOptions) {
|
||||
const liveRef = useRef(options);
|
||||
liveRef.current = options;
|
||||
|
||||
const {
|
||||
sessionId,
|
||||
status,
|
||||
host,
|
||||
isLocalConnection,
|
||||
isSerialConnection,
|
||||
} = options;
|
||||
const hostProtocol = host.protocol || 'ssh';
|
||||
|
||||
const [pendingExternalEditorRequest, setPendingExternalEditorRequest] =
|
||||
useState<PendingExternalEditorRequest | null>(null);
|
||||
const pendingExternalEditorRequestRef = useRef(pendingExternalEditorRequest);
|
||||
pendingExternalEditorRequestRef.current = pendingExternalEditorRequest;
|
||||
const lastExternalEditorLaunchRef = useRef<{ key: string; at: number } | null>(null);
|
||||
|
||||
const executeExternalEditorLaunch = useCallback((req: PendingExternalEditorRequest) => {
|
||||
const launchKey = `${req.editorId}:${req.kind}:${req.remotePath}`;
|
||||
const now = Date.now();
|
||||
const prev = lastExternalEditorLaunchRef.current;
|
||||
if (prev && prev.key === launchKey && now - prev.at < 800) {
|
||||
return;
|
||||
}
|
||||
lastExternalEditorLaunchRef.current = { key: launchKey, at: now };
|
||||
|
||||
const current = liveRef.current;
|
||||
void launchRemoteExternalEditor({
|
||||
editorId: req.editorId,
|
||||
host: {
|
||||
hostId: current.host.id,
|
||||
hostname: current.host.hostname,
|
||||
port: current.host.port,
|
||||
username: current.host.username,
|
||||
label: current.host.label,
|
||||
},
|
||||
remotePath: req.remotePath,
|
||||
kind: req.kind,
|
||||
sessionId: current.getBackendSessionId() ?? current.sessionId,
|
||||
}).then(() => {
|
||||
liveRef.current.onOpened(req.editorLabel, req.remotePath);
|
||||
}).catch((err) => {
|
||||
liveRef.current.onOpenFailed(
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: liveRef.current.formatFallbackOpenError(req.editorLabel),
|
||||
);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleOscExternalEditorRequest = useCallback((request: ExternalEditorOscRequest) => {
|
||||
const current = liveRef.current;
|
||||
// Strictly scope OSC 7337 remote editor opens to live SSH sessions on visible tabs.
|
||||
if (current.isLocalConnection || current.isSerialConnection) return;
|
||||
if (!current.isVisible()) return;
|
||||
if ((current.host.protocol || 'ssh') !== 'ssh') return;
|
||||
|
||||
const settings = getExternalEditorSettingsSnapshot();
|
||||
if (!settings.terminalRequestsEnabled) return;
|
||||
|
||||
const fallbackCwd = current.getFallbackCwd();
|
||||
const normalized = validateAndNormalizeRemotePath(request.path, fallbackCwd);
|
||||
if (!normalized.ok) {
|
||||
logger.warn(
|
||||
'[Terminal] Rejected invalid OSC 7337 remote path:',
|
||||
'error' in normalized ? normalized.error : 'invalid path',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const editorId: ExternalEditorPresetId = request.editorId ?? settings.defaultEditor;
|
||||
const editorLabel = getExternalEditorLabel(editorId);
|
||||
const hostIdentity = {
|
||||
hostId: current.host.id,
|
||||
hostname: current.host.hostname,
|
||||
port: current.host.port,
|
||||
username: current.host.username,
|
||||
label: current.host.label,
|
||||
};
|
||||
const trust = resolveExternalEditorTrustPolicy(settings, hostIdentity);
|
||||
if (trust === 'deny') {
|
||||
logger.debug('[Terminal] Ignored OSC 7337 external editor request (host denied)');
|
||||
return;
|
||||
}
|
||||
|
||||
const launchPayload: PendingExternalEditorRequest = {
|
||||
editorId,
|
||||
editorLabel,
|
||||
remotePath: normalized.path,
|
||||
kind: request.kind,
|
||||
};
|
||||
|
||||
if (trust === 'allow') {
|
||||
executeExternalEditorLaunch(launchPayload);
|
||||
return;
|
||||
}
|
||||
|
||||
// Untrusted host: show explicit inline confirmation prompt (do not overwrite an active prompt).
|
||||
setPendingExternalEditorRequest((prev) => prev ?? launchPayload);
|
||||
}, [executeExternalEditorLaunch]);
|
||||
|
||||
const handleExternalEditorPromptResponse = useCallback((decision: 'deny' | 'once' | 'always') => {
|
||||
const currentRequest = pendingExternalEditorRequestRef.current;
|
||||
pendingExternalEditorRequestRef.current = null;
|
||||
setPendingExternalEditorRequest(null);
|
||||
if (currentRequest) {
|
||||
const current = liveRef.current;
|
||||
if (decision === 'always') {
|
||||
setExternalEditorHostTrust({
|
||||
hostId: current.host.id,
|
||||
hostname: current.host.hostname,
|
||||
port: current.host.port,
|
||||
username: current.host.username,
|
||||
label: current.host.label,
|
||||
}, 'allow');
|
||||
executeExternalEditorLaunch(currentRequest);
|
||||
} else if (decision === 'once') {
|
||||
executeExternalEditorLaunch(currentRequest);
|
||||
}
|
||||
}
|
||||
liveRef.current.focusTerminal();
|
||||
}, [executeExternalEditorLaunch]);
|
||||
|
||||
// Session-scoped external editor shell commands: install standalone helpers into
|
||||
// ~/.netcatty/bin over the silent exec channel (never modifying shell rc files)
|
||||
// and prepend ~/.netcatty/bin to PATH once per connected terminal session.
|
||||
const autoSetupConfig = useExternalEditorTerminalAutoSetupConfig();
|
||||
const shouldEnableSessionCommands = shouldAutoSetupExternalEditorShell(
|
||||
autoSetupConfig,
|
||||
{ externalEditorShellIntegration: host.externalEditorShellIntegration },
|
||||
);
|
||||
const defaultExternalEditor = autoSetupConfig.defaultEditor;
|
||||
|
||||
const provisionerRef = useRef<ExternalEditorSessionProvisioner | null>(null);
|
||||
if (!provisionerRef.current) {
|
||||
provisionerRef.current = createExternalEditorSessionProvisioner({
|
||||
setupExec: (activeSessionId, command) => {
|
||||
const fn = liveRef.current.setupOsc7Tracking;
|
||||
if (!fn) return Promise.resolve({ success: false, error: 'setupOsc7Tracking unavailable' });
|
||||
return fn(activeSessionId, command);
|
||||
},
|
||||
writeToSession: (activeSessionId, data, opts) => {
|
||||
liveRef.current.writeToSession(activeSessionId, data, opts);
|
||||
},
|
||||
getCurrentSessionId: () => liveRef.current.getBackendSessionId() ?? liveRef.current.sessionId,
|
||||
isReadyForCommandInjection: () => liveRef.current.isReadyForCommandInjection(),
|
||||
onConfigured: (editorLabel) => liveRef.current.onAutoSetupConfigured(editorLabel),
|
||||
onWarn: (message, detail) => logger.warn(message, detail),
|
||||
scheduleTimer: (fn, ms) => window.setTimeout(fn, ms) as unknown as ReturnType<typeof setTimeout>,
|
||||
clearTimer: (handle) => window.clearTimeout(handle as unknown as number),
|
||||
});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const provisioner = provisionerRef.current;
|
||||
if (!provisioner) return;
|
||||
|
||||
if (status !== 'connected') {
|
||||
provisioner.reset();
|
||||
return;
|
||||
}
|
||||
if (isLocalConnection || isSerialConnection) return;
|
||||
if (hostProtocol !== 'ssh') return;
|
||||
if (!shouldEnableSessionCommands) return;
|
||||
if (!liveRef.current.setupOsc7Tracking) return;
|
||||
|
||||
const activeSessionId = liveRef.current.getBackendSessionId() ?? sessionId;
|
||||
if (!activeSessionId) return;
|
||||
|
||||
return provisioner.sync({
|
||||
sessionId: activeSessionId,
|
||||
defaultEditor: defaultExternalEditor,
|
||||
});
|
||||
}, [
|
||||
status,
|
||||
isLocalConnection,
|
||||
isSerialConnection,
|
||||
hostProtocol,
|
||||
shouldEnableSessionCommands,
|
||||
defaultExternalEditor,
|
||||
sessionId,
|
||||
]);
|
||||
|
||||
return {
|
||||
pendingExternalEditorRequest,
|
||||
handleOscExternalEditorRequest,
|
||||
handleExternalEditorPromptResponse,
|
||||
};
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import { JSDOM } from 'jsdom';
|
||||
|
||||
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;
|
||||
|
||||
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' });
|
||||
@@ -30,9 +32,10 @@ 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 pluginsLoading = false;
|
||||
let pluginsAvailable = true;
|
||||
|
||||
function Fixture() {
|
||||
model = useVaultNavConfig({ activePluginIds, pluginsLoading });
|
||||
model = useVaultNavConfig({ activePluginIds, pluginsLoading, pluginsAvailable });
|
||||
return <div />;
|
||||
}
|
||||
|
||||
@@ -83,6 +86,7 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
|
||||
const coldRoot = createRoot(document.getElementById('root')!);
|
||||
activePluginIds = [];
|
||||
pluginsLoading = true;
|
||||
pluginsAvailable = false;
|
||||
await act(async () => {
|
||||
coldRoot.render(<Fixture />);
|
||||
});
|
||||
@@ -93,6 +97,7 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
|
||||
// Plugins finish loading, but DB_PLUGIN was uninstalled.
|
||||
activePluginIds = [MONITOR_PLUGIN];
|
||||
pluginsLoading = false;
|
||||
pluginsAvailable = true;
|
||||
await act(async () => {
|
||||
coldRoot.render(<Fixture />);
|
||||
});
|
||||
@@ -122,3 +127,125 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('useVaultNavConfig preserves saved plugin order when settled with pluginsAvailable=false and restores slots once plugins become available', 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 pluginsLoading = false;
|
||||
let pluginsAvailable: boolean | undefined = true;
|
||||
|
||||
function Fixture() {
|
||||
model = useVaultNavConfig({ activePluginIds, pluginsLoading, pluginsAvailable });
|
||||
return <div />;
|
||||
}
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<Fixture />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
model.reorder(OFFICIAL_MONITOR_PLUGIN, 'hosts', 'after');
|
||||
model.setVisible('logs', false);
|
||||
});
|
||||
assert.equal(model.visibleIds[1], OFFICIAL_MONITOR_PLUGIN);
|
||||
assert.equal(model.isHidden('logs'), true);
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
|
||||
const restartedRoot = createRoot(document.getElementById('root')!);
|
||||
activePluginIds = [];
|
||||
pluginsLoading = false;
|
||||
pluginsAvailable = false;
|
||||
await act(async () => {
|
||||
restartedRoot.render(
|
||||
<React.StrictMode>
|
||||
<Fixture />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
});
|
||||
|
||||
assert.equal(model.visibleIds.includes(OFFICIAL_MONITOR_PLUGIN), false);
|
||||
assert.equal(model.visibleIds.includes(OFFICIAL_DB_PLUGIN), false);
|
||||
assert.equal(model.config.order[1], OFFICIAL_MONITOR_PLUGIN);
|
||||
assert.equal(model.config.order.includes(OFFICIAL_DB_PLUGIN), true);
|
||||
|
||||
const persistedUnavailable = JSON.parse(
|
||||
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
|
||||
);
|
||||
assert.equal(persistedUnavailable.order[1], OFFICIAL_MONITOR_PLUGIN);
|
||||
assert.equal(persistedUnavailable.order.includes(OFFICIAL_DB_PLUGIN), true);
|
||||
assert.deepEqual(persistedUnavailable.hidden, ['logs']);
|
||||
|
||||
pluginsAvailable = undefined;
|
||||
await act(async () => {
|
||||
restartedRoot.render(
|
||||
<React.StrictMode>
|
||||
<Fixture />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
});
|
||||
const persistedDefault = JSON.parse(
|
||||
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
|
||||
);
|
||||
assert.equal(persistedDefault.order[1], OFFICIAL_MONITOR_PLUGIN);
|
||||
assert.equal(persistedDefault.order.includes(OFFICIAL_DB_PLUGIN), true);
|
||||
|
||||
activePluginIds = [OFFICIAL_DB_PLUGIN, OFFICIAL_MONITOR_PLUGIN];
|
||||
pluginsLoading = false;
|
||||
pluginsAvailable = true;
|
||||
await act(async () => {
|
||||
restartedRoot.render(
|
||||
<React.StrictMode>
|
||||
<Fixture />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
});
|
||||
assert.equal(model.visibleIds[1], OFFICIAL_MONITOR_PLUGIN);
|
||||
assert.equal(model.visibleIds.includes(OFFICIAL_DB_PLUGIN), true);
|
||||
assert.equal(model.isHidden('logs'), true);
|
||||
|
||||
await act(async () => {
|
||||
restartedRoot.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();
|
||||
}
|
||||
});
|
||||
@@ -28,6 +28,8 @@ export interface UseVaultNavConfigOptions {
|
||||
activePluginIds: readonly PluginVaultNavId[];
|
||||
/** Pass true while plugin contributions are still loading on cold start. */
|
||||
pluginsLoading?: boolean;
|
||||
/** Pass true once plugin contributions are available from the plugin runtime. */
|
||||
pluginsAvailable?: boolean;
|
||||
}
|
||||
|
||||
export interface UseVaultNavConfigResult {
|
||||
@@ -76,13 +78,14 @@ function writeStoredVaultNavConfig(config: VaultNavConfig): void {
|
||||
export function useVaultNavConfig({
|
||||
activePluginIds,
|
||||
pluginsLoading = false,
|
||||
pluginsAvailable = false,
|
||||
}: UseVaultNavConfigOptions): UseVaultNavConfigResult {
|
||||
const pluginKey = activePluginIds.join('\0');
|
||||
const stablePluginIds = useMemo<PluginVaultNavId[]>(
|
||||
() => (pluginKey ? (pluginKey.split('\0') as PluginVaultNavId[]) : []),
|
||||
[pluginKey],
|
||||
);
|
||||
const pruneMissingPlugins = !pluginsLoading;
|
||||
const pruneMissingPlugins = !pluginsLoading && pluginsAvailable;
|
||||
|
||||
const [config, setConfig] = useState<VaultNavConfig>(() =>
|
||||
readStoredVaultNavConfig(stablePluginIds, pruneMissingPlugins),
|
||||
|
||||
@@ -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[];
|
||||
|
||||
@@ -440,3 +440,43 @@ test('changed remote transcript resets the local native SDK thread before contin
|
||||
assert.equal(getAISessionsSnapshot().sessions[0].messages.at(-1)?.content, 'Added on another device');
|
||||
delete (window as unknown as { netcatty?: unknown }).netcatty;
|
||||
});
|
||||
|
||||
test('cloud apply keeps receiver workspaceNameSnapshot when workspace binding is unchanged and drops it on rebind', async () => {
|
||||
const local: AISession = {
|
||||
...session(),
|
||||
id: 'ws-chat',
|
||||
scope: { type: 'workspace', targetId: 'ws-1', hostIds: ['h-1'] },
|
||||
workspaceNameSnapshot: 'Prod Cluster (this Mac)',
|
||||
updatedAt: 10,
|
||||
};
|
||||
save([local]);
|
||||
|
||||
// Never uploaded to cloud.
|
||||
const uploaded = await buildCloudSyncPayload(vault, [], { collectPluginSidecars: () => undefined });
|
||||
assert.equal(Object.hasOwn(uploaded.aiSessions?.[0] ?? {}, 'workspaceNameSnapshot'), false);
|
||||
|
||||
// Newer remote update on the same workspace (stripped by remote device, or even
|
||||
// carrying a foreign snapshot that must be stripped on apply) keeps local name.
|
||||
const remoteSameWs: AISession = {
|
||||
...local,
|
||||
updatedAt: 20,
|
||||
title: 'Updated title from peer',
|
||||
workspaceNameSnapshot: 'Peer stale name',
|
||||
};
|
||||
await applySyncPayload({ ...vault, aiSessions: [remoteSameWs], syncedAt: 20 }, { importVaultData: () => undefined });
|
||||
const afterSameWs = getAISessionsSnapshot().sessions.find((s) => s.id === 'ws-chat');
|
||||
assert.equal(afterSameWs?.title, 'Updated title from peer');
|
||||
assert.equal(afterSameWs?.workspaceNameSnapshot, 'Prod Cluster (this Mac)');
|
||||
|
||||
// Newer remote update that rebinds to another workspace drops the old local name.
|
||||
const remoteRebound: AISession = {
|
||||
...local,
|
||||
updatedAt: 30,
|
||||
scope: { type: 'workspace', targetId: 'ws-2', hostIds: ['h-2'] },
|
||||
workspaceNameSnapshot: undefined,
|
||||
};
|
||||
await applySyncPayload({ ...vault, aiSessions: [remoteRebound], syncedAt: 30 }, { importVaultData: () => undefined });
|
||||
const afterRebound = getAISessionsSnapshot().sessions.find((s) => s.id === 'ws-chat');
|
||||
assert.equal(afterRebound?.scope.targetId, 'ws-2');
|
||||
assert.equal(afterRebound?.workspaceNameSnapshot, undefined);
|
||||
});
|
||||
@@ -2422,13 +2422,17 @@ test('sync prepares header encryption once before importing and leaves input unc
|
||||
assert.deepEqual(JSON.parse(localStorage.getItem(storageKeys.STORAGE_KEY_AI_PROVIDERS)!)[0].customHeaders, { 'X-Tenant': sealed });
|
||||
});
|
||||
|
||||
test("SFTP default download folder stays device-local and is never synced", async () => {
|
||||
const key = storageKeys.STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR;
|
||||
assert.equal((SYNCABLE_SETTING_STORAGE_KEYS as readonly string[]).includes(key), false);
|
||||
localStorage.clear();
|
||||
localStorage.setItem(key, "/Users/me/server-files");
|
||||
const payload = buildSyncPayload(vault());
|
||||
assert.equal(JSON.stringify(payload).includes("/Users/me/server-files"), false);
|
||||
await applySyncPayload(payload, { importVaultData: () => {} });
|
||||
assert.equal(localStorage.getItem(key), "/Users/me/server-files");
|
||||
});
|
||||
for (const key of [
|
||||
storageKeys.STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR,
|
||||
storageKeys.STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR,
|
||||
]) {
|
||||
test(`SFTP download folder ${key} stays device-local and is never synced`, async () => {
|
||||
assert.equal((SYNCABLE_SETTING_STORAGE_KEYS as readonly string[]).includes(key), false);
|
||||
localStorage.clear();
|
||||
localStorage.setItem(key, "/Users/me/server-files");
|
||||
const payload = buildSyncPayload(vault());
|
||||
assert.equal(JSON.stringify(payload).includes("/Users/me/server-files"), false);
|
||||
await applySyncPayload(payload, { importVaultData: () => {} });
|
||||
assert.equal(localStorage.getItem(key), "/Users/me/server-files");
|
||||
});
|
||||
}
|
||||
@@ -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 = [
|
||||
|
||||
@@ -1,3 +1,266 @@
|
||||
!ifndef BUILD_UNINSTALLER
|
||||
Var /GLOBAL CreateDesktopShortcutPref
|
||||
!endif
|
||||
|
||||
!macro customHeader
|
||||
!ifndef BUILD_UNINSTALLER
|
||||
!ifdef LANG_ENGLISH
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_ENGLISH} "Create &desktop shortcut"
|
||||
!endif
|
||||
!ifdef LANG_SIMPCHINESE
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_SIMPCHINESE} "创建桌面快捷方式(&D)"
|
||||
!endif
|
||||
!ifdef LANG_TRADCHINESE
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_TRADCHINESE} "建立桌面捷徑(&D)"
|
||||
!endif
|
||||
!ifdef LANG_RUSSIAN
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_RUSSIAN} "Создать ярлык на &рабочем столе"
|
||||
!endif
|
||||
!ifdef LANG_JAPANESE
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_JAPANESE} "デスクトップにショートカットを作成する(&D)"
|
||||
!endif
|
||||
!ifdef LANG_KOREAN
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_KOREAN} "바탕 화면에 바로 가기 만들기(&D)"
|
||||
!endif
|
||||
!ifdef LANG_GERMAN
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_GERMAN} "&Desktopverknüpfung erstellen"
|
||||
!endif
|
||||
!ifdef LANG_FRENCH
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_FRENCH} "Créer un raccourci sur le &bureau"
|
||||
!endif
|
||||
!ifdef LANG_SPANISHINTERNATIONAL
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_SPANISHINTERNATIONAL} "Crear acceso directo en el &escritorio"
|
||||
!endif
|
||||
!ifdef LANG_ITALIAN
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_ITALIAN} "Crea collegamento sul &desktop"
|
||||
!endif
|
||||
!ifdef LANG_DUTCH
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_DUTCH} "&Bureaublad-snelkoppeling maken"
|
||||
!endif
|
||||
!ifdef LANG_DANISH
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_DANISH} "Opret genvej på &skrivebordet"
|
||||
!endif
|
||||
!ifdef LANG_SWEDISH
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_SWEDISH} "Skapa genväg på &skrivbordet"
|
||||
!endif
|
||||
!ifdef LANG_NORWEGIAN
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_NORWEGIAN} "Opprett snarvei på &skrivebordet"
|
||||
!endif
|
||||
!ifdef LANG_FINNISH
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_FINNISH} "Luo pikakuvake &työpöydälle"
|
||||
!endif
|
||||
!ifdef LANG_PORTUGUESE
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_PORTUGUESE} "Criar atalho na &área de trabalho"
|
||||
!endif
|
||||
!ifdef LANG_PORTUGUESEBR
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_PORTUGUESEBR} "Criar atalho na &Área de Trabalho"
|
||||
!endif
|
||||
!ifdef LANG_POLISH
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_POLISH} "Utwórz skrót na &pulpicie"
|
||||
!endif
|
||||
!ifdef LANG_UKRAINIAN
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_UKRAINIAN} "Створити ярлик на &робочому столі"
|
||||
!endif
|
||||
!ifdef LANG_CZECH
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_CZECH} "Vytvořit zástupce na &ploše"
|
||||
!endif
|
||||
!ifdef LANG_SLOVAK
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_SLOVAK} "Vytvoriť odkaz na &ploche"
|
||||
!endif
|
||||
!ifdef LANG_HUNGARIAN
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_HUNGARIAN} "Parancsikon létrehozása az &asztalon"
|
||||
!endif
|
||||
!ifdef LANG_ARABIC
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_ARABIC} "إنشاء اختصار على سطح ال&مكتب"
|
||||
!endif
|
||||
!ifdef LANG_TURKISH
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_TURKISH} "&Masaüstü kısayolu oluştur"
|
||||
!endif
|
||||
!ifdef LANG_THAI
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_THAI} "สร้างทางลัดบน&เดสก์ท็อป"
|
||||
!endif
|
||||
!ifdef LANG_VIETNAMESE
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_VIETNAMESE} "Tạo lối tắt trên &màn hình nền"
|
||||
!endif
|
||||
|
||||
; Determine whether the desktop shortcut should be checked/created.
|
||||
; Must run before uninstallOldVersion deletes the old registry key or shortcut.
|
||||
Function CaptureDesktopShortcutState
|
||||
${if} ${isNoDesktopShortcut}
|
||||
StrCpy $CreateDesktopShortcutPref "false"
|
||||
Return
|
||||
${endif}
|
||||
|
||||
!insertmacro setLinkVars
|
||||
|
||||
ReadRegStr $0 SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut
|
||||
${if} $0 == "false"
|
||||
${if} ${FileExists} "$newDesktopLink"
|
||||
${orIf} ${FileExists} "$oldDesktopLink"
|
||||
StrCpy $CreateDesktopShortcutPref "true"
|
||||
${else}
|
||||
StrCpy $CreateDesktopShortcutPref "false"
|
||||
${endif}
|
||||
Return
|
||||
${endif}
|
||||
|
||||
ReadRegStr $1 SHCTX "${INSTALL_REGISTRY_KEY}" InstallLocation
|
||||
${if} $1 != ""
|
||||
; Existing install: only preserve the shortcut if it still exists on the desktop.
|
||||
${if} ${FileExists} "$newDesktopLink"
|
||||
${orIf} ${FileExists} "$oldDesktopLink"
|
||||
StrCpy $CreateDesktopShortcutPref "true"
|
||||
${else}
|
||||
StrCpy $CreateDesktopShortcutPref "false"
|
||||
${endif}
|
||||
Return
|
||||
${endif}
|
||||
|
||||
; Migrating from per-user to all-users: inspect the previous per-user desktop shortcut.
|
||||
${if} $installMode == "all"
|
||||
ReadRegStr $2 HKCU "${INSTALL_REGISTRY_KEY}" InstallLocation
|
||||
${if} $2 != ""
|
||||
ReadRegStr $3 HKCU "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut
|
||||
SetShellVarContext current
|
||||
!insertmacro setLinkVars
|
||||
${if} ${FileExists} "$newDesktopLink"
|
||||
${orIf} ${FileExists} "$oldDesktopLink"
|
||||
StrCpy $CreateDesktopShortcutPref "true"
|
||||
${elseif} $3 == "false"
|
||||
StrCpy $CreateDesktopShortcutPref "false"
|
||||
${else}
|
||||
StrCpy $CreateDesktopShortcutPref "false"
|
||||
${endif}
|
||||
SetShellVarContext all
|
||||
!insertmacro setLinkVars
|
||||
Return
|
||||
${endif}
|
||||
${endif}
|
||||
|
||||
; Fresh installation: default to creating the desktop shortcut (user can uncheck on finish page).
|
||||
StrCpy $CreateDesktopShortcutPref "true"
|
||||
FunctionEnd
|
||||
|
||||
Function InstFilesShowCaptureDesktopShortcut
|
||||
Call CaptureDesktopShortcutState
|
||||
FunctionEnd
|
||||
!endif
|
||||
!macroend
|
||||
|
||||
!macro ensureDesktopShortcut
|
||||
${if} $appExe == ""
|
||||
StrCpy $appExe "$INSTDIR\${APP_EXECUTABLE_FILENAME}"
|
||||
${endif}
|
||||
${if} $newDesktopLink == ""
|
||||
StrCpy $newDesktopLink "$DESKTOP\${SHORTCUT_NAME}.lnk"
|
||||
${endif}
|
||||
|
||||
${if} $oldDesktopLink != ""
|
||||
${andIf} $oldDesktopLink != $newDesktopLink
|
||||
${andIf} ${FileExists} "$oldDesktopLink"
|
||||
Rename "$oldDesktopLink" "$newDesktopLink"
|
||||
WinShell::UninstShortcut "$oldDesktopLink"
|
||||
${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
|
||||
${if} $newDesktopLink == ""
|
||||
StrCpy $newDesktopLink "$DESKTOP\${SHORTCUT_NAME}.lnk"
|
||||
${endif}
|
||||
|
||||
${if} ${FileExists} "$newDesktopLink"
|
||||
WinShell::UninstShortcut "$newDesktopLink"
|
||||
Delete "$newDesktopLink"
|
||||
System::Call 'Shell32::SHChangeNotify(i 0x8000000, i 0, i 0, i 0)'
|
||||
${endif}
|
||||
${if} $oldDesktopLink != ""
|
||||
${andIf} $oldDesktopLink != $newDesktopLink
|
||||
${andIf} ${FileExists} "$oldDesktopLink"
|
||||
WinShell::UninstShortcut "$oldDesktopLink"
|
||||
Delete "$oldDesktopLink"
|
||||
System::Call 'Shell32::SHChangeNotify(i 0x8000000, i 0, i 0, i 0)'
|
||||
${endif}
|
||||
!macroend
|
||||
|
||||
!macro customPageAfterChangeDir
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_SHOW InstFilesShowCaptureDesktopShortcut
|
||||
!macroend
|
||||
|
||||
!macro customFinishPage
|
||||
!ifndef HIDE_RUN_AFTER_FINISH
|
||||
Function StartApp
|
||||
${if} ${isUpdated}
|
||||
StrCpy $1 "--updated"
|
||||
${else}
|
||||
StrCpy $1 ""
|
||||
${endif}
|
||||
${StdUtils.ExecShellAsUser} $0 "$launchLink" "open" "$1"
|
||||
FunctionEnd
|
||||
|
||||
!define MUI_FINISHPAGE_RUN
|
||||
!define MUI_FINISHPAGE_RUN_FUNCTION "StartApp"
|
||||
!endif
|
||||
|
||||
!define MUI_FINISHPAGE_SHOWREADME ""
|
||||
!define MUI_FINISHPAGE_SHOWREADME_TEXT "$(CREATE_DESKTOP_SHORTCUT_TEXT)"
|
||||
!define MUI_FINISHPAGE_SHOWREADME_FUNCTION "FinishDesktopShortcutNoop"
|
||||
!define MUI_FINISHPAGE_SHOWREADME_NOTCHECKED
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_SHOW FinishPageShow
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_LEAVE FinishPageLeave
|
||||
!insertmacro MUI_PAGE_FINISH
|
||||
|
||||
Function FinishPageShow
|
||||
!ifndef MUI_FINISHPAGE_NOREBOOTSUPPORT
|
||||
${ifNot} ${RebootFlag}
|
||||
!endif
|
||||
${if} $CreateDesktopShortcutPref == "true"
|
||||
SendMessage $mui.FinishPage.ShowReadme ${BM_SETCHECK} ${BST_CHECKED} 0
|
||||
${else}
|
||||
SendMessage $mui.FinishPage.ShowReadme ${BM_SETCHECK} ${BST_UNCHECKED} 0
|
||||
${endif}
|
||||
!ifndef MUI_FINISHPAGE_NOREBOOTSUPPORT
|
||||
${endif}
|
||||
!endif
|
||||
FunctionEnd
|
||||
|
||||
Function FinishPageLeave
|
||||
!ifndef MUI_FINISHPAGE_NOREBOOTSUPPORT
|
||||
${if} ${RebootFlag}
|
||||
${if} $CreateDesktopShortcutPref == "true"
|
||||
!insertmacro ensureDesktopShortcut
|
||||
WriteRegStr SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut "true"
|
||||
${else}
|
||||
!insertmacro removeDesktopShortcut
|
||||
WriteRegStr SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut "false"
|
||||
${endif}
|
||||
Return
|
||||
${endif}
|
||||
!endif
|
||||
|
||||
SendMessage $mui.FinishPage.ShowReadme ${BM_GETCHECK} 0 0 $0
|
||||
${if} $0 = ${BST_CHECKED}
|
||||
StrCpy $CreateDesktopShortcutPref "true"
|
||||
!insertmacro ensureDesktopShortcut
|
||||
WriteRegStr SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut "true"
|
||||
${else}
|
||||
StrCpy $CreateDesktopShortcutPref "false"
|
||||
!insertmacro removeDesktopShortcut
|
||||
WriteRegStr SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut "false"
|
||||
${endif}
|
||||
FunctionEnd
|
||||
|
||||
Function FinishDesktopShortcutNoop
|
||||
FunctionEnd
|
||||
!macroend
|
||||
|
||||
!macro customInit
|
||||
; #3946: external MCP hosts launch Netcatty.exe with ELECTRON_RUN_AS_NODE=1
|
||||
; via netcatty-external-mcp.cmd. Those processes can outlive the host UI as
|
||||
@@ -7,9 +270,17 @@
|
||||
; and /T would terminate the installer itself. Ignore a missing process.
|
||||
nsExec::ExecToLog "taskkill /F /IM Netcatty.exe"
|
||||
Pop $0
|
||||
Call CaptureDesktopShortcutState
|
||||
!macroend
|
||||
|
||||
!macro customInstall
|
||||
WriteRegStr SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut "$CreateDesktopShortcutPref"
|
||||
${if} ${Silent}
|
||||
${andIf} $CreateDesktopShortcutPref == "true"
|
||||
${andIfNot} ${isNoDesktopShortcut}
|
||||
!insertmacro ensureDesktopShortcut
|
||||
${endif}
|
||||
|
||||
; Open a selected folder in a new Netcatty local terminal.
|
||||
; Args go after `--` so Electron/Chromium does not swallow them. Use
|
||||
; `--open-terminal-path="%1."` so paths with spaces stay one token and drive
|
||||
@@ -50,6 +321,13 @@
|
||||
!macroend
|
||||
|
||||
!macro customUnInstall
|
||||
; DO_NOT_CREATE_DESKTOP_SHORTCUT is set so electron-builder never auto-creates
|
||||
; the desktop shortcut; remove an existing shortcut here on real uninstall.
|
||||
${ifNot} ${isKeepShortcuts}
|
||||
WinShell::UninstShortcut "$oldDesktopLink"
|
||||
Delete "$oldDesktopLink"
|
||||
${endif}
|
||||
|
||||
DeleteRegKey SHCTX "Software\Classes\Directory\shell\Netcatty"
|
||||
DeleteRegKey SHCTX "Software\Classes\Directory\Background\shell\Netcatty"
|
||||
DeleteRegKey SHCTX "Software\Classes\Netcatty.SSH"
|
||||
|
||||
@@ -59,6 +59,7 @@ interface AIChatPanelContentProps {
|
||||
activeCompaction?: import('../application/state/useAgentCompactionUi').ActiveCompactionUi | null;
|
||||
contextUsage?: import('../application/state/useAgentCompactionUi').AgentContextUsage | null;
|
||||
inputValue: string;
|
||||
inputValueRevision?: number;
|
||||
setInputValue: (value: string) => void;
|
||||
handleSend: (textOverride?: string) => void;
|
||||
handleSendQuickPrompt?: (promptText: string) => void;
|
||||
@@ -171,6 +172,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
activeCompaction = null,
|
||||
contextUsage = null,
|
||||
inputValue,
|
||||
inputValueRevision,
|
||||
setInputValue,
|
||||
handleSend,
|
||||
handleSendQuickPrompt,
|
||||
@@ -568,6 +570,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
<ChatInput
|
||||
parked={parked}
|
||||
value={inputValue}
|
||||
valueRevision={inputValueRevision}
|
||||
onChange={setInputValue}
|
||||
onSend={handleSend}
|
||||
onSendQuickPrompt={handleSendQuickPrompt}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { Download, MoreHorizontal, Pencil, Search, Trash2, Upload, X } from 'lucide-react';
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { CheckSquare, Download, MoreHorizontal, Pencil, Search, Trash2, Upload, X } from 'lucide-react';
|
||||
import type { AISession } from '../infrastructure/ai/types';
|
||||
import { useI18n } from '../application/i18n/I18nProvider';
|
||||
import { cn } from '../lib/utils';
|
||||
@@ -9,6 +9,8 @@ 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';
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
@@ -52,6 +54,7 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
|
||||
const { t } = useI18n();
|
||||
const [view, setView] = useState<'scoped' | 'global'>('scoped');
|
||||
const [headerMenuOpen, setHeaderMenuOpen] = useState(false);
|
||||
const [globalSelectionMode, setGlobalSelectionMode] = useState(false);
|
||||
const [renderCount, setRenderCount] = useState(SESSION_RENDER_BATCH);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [renamingSessionId, setRenamingSessionId] = useState<string | null>(null);
|
||||
@@ -70,6 +73,22 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
|
||||
setRenderCount(SESSION_RENDER_BATCH);
|
||||
}, [sessions, searchQuery]);
|
||||
|
||||
useEffect(() => {
|
||||
if (view !== 'global' || !globalManager) {
|
||||
setGlobalSelectionMode(false);
|
||||
}
|
||||
}, [view, globalManager]);
|
||||
|
||||
const selectionContextValue = useMemo(
|
||||
() => ({
|
||||
selectionMode: globalSelectionMode,
|
||||
setSelectionMode: setGlobalSelectionMode,
|
||||
}),
|
||||
[globalSelectionMode],
|
||||
);
|
||||
const canSelectGlobalChats = view === 'global' && Boolean(globalManager);
|
||||
const hasHeaderMenu = Boolean(canSelectGlobalChats || onImportSessions || onExportSessions);
|
||||
|
||||
const displayedSessions = filteredSessions.slice(0, renderCount);
|
||||
const hiddenSessionCount = Math.max(0, filteredSessions.length - renderCount);
|
||||
|
||||
@@ -132,7 +151,7 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{(onImportSessions || onExportSessions) && (
|
||||
{hasHeaderMenu && (
|
||||
<Dropdown open={headerMenuOpen} onOpenChange={setHeaderMenuOpen}>
|
||||
<DropdownTrigger asChild>
|
||||
<button
|
||||
@@ -144,6 +163,31 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
|
||||
</button>
|
||||
</DropdownTrigger>
|
||||
<DropdownContent align="end" className="min-w-[152px] p-1" keyboardNavigation>
|
||||
{canSelectGlobalChats && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setHeaderMenuOpen(false);
|
||||
setGlobalSelectionMode((prev) => !prev);
|
||||
}}
|
||||
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"
|
||||
>
|
||||
<CheckSquare
|
||||
size={12}
|
||||
className={cn(
|
||||
'shrink-0',
|
||||
globalSelectionMode ? 'text-primary' : 'text-muted-foreground',
|
||||
)}
|
||||
/>
|
||||
<span>{t('ai.chat.managerToggleSelection')}</span>
|
||||
</button>
|
||||
{(onImportSessions || onExportSessions) && (
|
||||
<div className="my-1 h-px bg-border/50" />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{onImportSessions && (
|
||||
<button
|
||||
type="button"
|
||||
@@ -184,7 +228,9 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
{view === 'global' && globalManager ? (
|
||||
globalManager
|
||||
<GlobalSessionSelectionContext.Provider value={selectionContextValue}>
|
||||
{globalManager}
|
||||
</GlobalSessionSelectionContext.Provider>
|
||||
) : (
|
||||
<>
|
||||
<div className="px-3 py-2 shrink-0 border-b border-border/30">
|
||||
@@ -250,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 (
|
||||
|
||||
+132
-35
@@ -14,6 +14,11 @@ import type {
|
||||
ExternalAgentConfig,
|
||||
} from '../infrastructure/ai/types';
|
||||
import type { VaultNote } from '../domain/models';
|
||||
import {
|
||||
buildFallbackTitle,
|
||||
canAutoTitleSession,
|
||||
resolveCattyEffectiveModel,
|
||||
} from '../domain/aiSessionTitle';
|
||||
import type { ExecutorContext } from '../infrastructure/ai/cattyAgent/executor';
|
||||
import {
|
||||
DEFAULT_MAX_ITERATIONS,
|
||||
@@ -294,6 +299,8 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
undoLastTurnInSession,
|
||||
deleteSession,
|
||||
updateSessionTitle,
|
||||
autoTitleSession,
|
||||
regenerateSessionTitle,
|
||||
rebindSessionScope,
|
||||
exportSessionsBackup,
|
||||
importSessionsBackup,
|
||||
@@ -823,11 +830,19 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
showSessionView(scopeKey, sessionId);
|
||||
}, [scopeKey, showSessionView]);
|
||||
|
||||
const [composerValueRevision, setComposerValueRevision] = useState(0);
|
||||
|
||||
const discardPendingComposerText = useCallback(() => {
|
||||
pendingComposerTextRef.current = null;
|
||||
if (currentDraftRef.current) {
|
||||
currentDraftRef.current = { ...currentDraftRef.current, text: '' };
|
||||
}
|
||||
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]);
|
||||
@@ -1038,26 +1053,16 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
[providers, activeProviderId],
|
||||
);
|
||||
|
||||
const cattyAgentProvider = useMemo(() => {
|
||||
const overrideId = agentProviderMap['catty'];
|
||||
if (overrideId) {
|
||||
const p = providers.find((cfg) => cfg.id === overrideId);
|
||||
if (p) return p;
|
||||
}
|
||||
return activeProvider;
|
||||
}, [agentProviderMap, providers, activeProvider]);
|
||||
|
||||
const cattyAgentModelId = useMemo(() => {
|
||||
const trim = (s: string | undefined | null): string => (s ?? '').trim();
|
||||
const overrideId = agentProviderMap['catty'];
|
||||
const overrideProvider = overrideId
|
||||
? providers.find((cfg) => cfg.id === overrideId)
|
||||
: undefined;
|
||||
if (overrideProvider) {
|
||||
return trim(agentModelMap['catty']) || trim(overrideProvider.defaultModel);
|
||||
}
|
||||
return trim(cattyAgentProvider?.defaultModel) || trim(activeModelId);
|
||||
}, [agentModelMap, agentProviderMap, providers, cattyAgentProvider, activeModelId]);
|
||||
const { provider: cattyAgentProvider, modelId: cattyAgentModelId } = useMemo(
|
||||
() => resolveCattyEffectiveModel({
|
||||
providers,
|
||||
activeProviderId,
|
||||
activeModelId,
|
||||
agentProviderMap,
|
||||
agentModelMap,
|
||||
}),
|
||||
[providers, activeProviderId, activeModelId, agentProviderMap, agentModelMap],
|
||||
);
|
||||
|
||||
const effectiveActiveProvider = currentAgentId === 'catty' ? cattyAgentProvider : activeProvider;
|
||||
const effectiveActiveModelId = currentAgentId === 'catty' ? cattyAgentModelId : activeModelId;
|
||||
@@ -1680,18 +1685,10 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
}, [openSettingsWindow]);
|
||||
|
||||
|
||||
/** Ref to always access latest sessions (avoids stale closure in autoTitleSession). */
|
||||
/** Ref to always access latest sessions inside async send callbacks. */
|
||||
const sessionsRef = useRef(sessions);
|
||||
sessionsRef.current = sessions;
|
||||
|
||||
/** Auto-title a session from the first user message if untitled. */
|
||||
const autoTitleSession = useCallback((sessionId: string, text: string) => {
|
||||
const s = sessionsRef.current.find(x => x.id === sessionId);
|
||||
if (s && (!s.title || s.title === 'New Chat')) {
|
||||
updateSessionTitle(sessionId, text.length > 50 ? text.slice(0, 50) + '...' : text);
|
||||
}
|
||||
}, [updateSessionTitle]);
|
||||
|
||||
const buildExecutorContextForScope = useCallback((scope: {
|
||||
type: 'terminal' | 'workspace' | 'global';
|
||||
targetId?: string;
|
||||
@@ -1875,7 +1872,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
let currentSession = currentSessionView ?? null;
|
||||
if (isDraftMode) {
|
||||
const scope: AISessionScope = { type: scopeType, targetId: scopeTargetId, hostIds: scopeHostIds };
|
||||
const createdSession = createSession(scope, sendAgentId);
|
||||
const createdSession = createSession(scope, sendAgentId, scopeLabel);
|
||||
sessionId = createdSession.id;
|
||||
currentSession = createdSession;
|
||||
if (useDraftAttachments) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
@@ -1983,7 +1980,6 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
updateLastMessage(sessionId, msg => msg.statusText ? { ...msg, statusText: '' } : msg);
|
||||
setStreamingForScope(sessionId, false);
|
||||
abortControllersRef.current.delete(sessionId);
|
||||
autoTitleSession(sessionId, titleText);
|
||||
} else {
|
||||
const toolScope = {
|
||||
type: scopeType,
|
||||
@@ -2005,12 +2001,23 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
terminalSessions,
|
||||
webSearchConfig,
|
||||
getExecutorContext: () => buildExecutorContextForScope(toolScope),
|
||||
autoTitleSession,
|
||||
// Title generation is triggered once, below, for both agent branches.
|
||||
autoTitleSession: () => {},
|
||||
selectedUserSkillSlugs: selectedSkillSlugs,
|
||||
titleText,
|
||||
pluginContext,
|
||||
}, modelAttachments.length > 0 ? modelAttachments : undefined);
|
||||
}
|
||||
// Single title-generation trigger for both agent branches. Pass the
|
||||
// signal explicitly: sendToCattyAgent's finally removes its controller.
|
||||
if (autoTitleSession) {
|
||||
void autoTitleSession(sessionId, titleText, abortController.signal);
|
||||
} else {
|
||||
const current = sessionsRef.current.find((s) => s.id === sessionId);
|
||||
if (canAutoTitleSession(current)) {
|
||||
updateSessionTitle(sessionId, buildFallbackTitle(titleText));
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setIsSending(false);
|
||||
endSendForKey(sendGateKey);
|
||||
@@ -2022,7 +2029,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
validateNoteMentions, loadCodexConfigModel,
|
||||
isStreaming, isUndoingLastTurn, activeProvider, effectiveActiveProvider, effectiveActiveModelId, selectedCattyThinking, scopeKey, currentAgentId,
|
||||
activeModelId, externalAgents,
|
||||
createSession, addMessageToSession, updateMessageById, updateLastMessage,
|
||||
createSession, addMessageToSession, updateMessageById, updateLastMessage, updateSessionTitle,
|
||||
setStreamingForScope,
|
||||
sendToExternalAgent, sendToCattyAgent, reportStreamError, autoTitleSession, t,
|
||||
abortControllersRef, terminalSessions, defaultTargetSession, providers, selectedAgentModel, updateSessionExternalSessionId,
|
||||
@@ -2122,7 +2129,9 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
if (!sessionId || !draft || steeringSessionId || !canSteerCurrentTurn) return;
|
||||
|
||||
if (!validateNoteMentions(draft.attachments)) return;
|
||||
const trimmed = draft.text.trim();
|
||||
const submittedText = draft.text;
|
||||
const draftGeneration = draftGenerationRef.current;
|
||||
const trimmed = submittedText.trim();
|
||||
const attachments = draft.attachments.map((file) => ({
|
||||
base64Data: file.base64Data,
|
||||
mediaType: file.mediaType,
|
||||
@@ -2156,7 +2165,10 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
attachedImages: modelAttachments,
|
||||
});
|
||||
if (result.status === 'accepted') {
|
||||
if (currentDraftRef.current === draft) clearScopeDraft();
|
||||
if (draftGenerationRef.current !== draftGeneration || activeSessionRef.current?.id !== sessionId) return;
|
||||
const pending = pendingComposerTextRef.current;
|
||||
const keepPendingText = pending != null && pending !== submittedText;
|
||||
clearScopeDraft({ keepPendingText });
|
||||
return;
|
||||
}
|
||||
if (result.status !== 'cancelled') {
|
||||
@@ -2430,6 +2442,82 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
deleteSession(sessionId);
|
||||
}, [abortControllersRef, deleteSession, stopStreamingForSession, streamingSessionIds]);
|
||||
|
||||
// Regeneration lives in useAIState so it can reuse the maintainer's
|
||||
// title-model resolution and atomic title-write helpers.
|
||||
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) {
|
||||
if (abortControllersRef.current.has(sessionId) || streamingSessionIds.has(sessionId)) {
|
||||
await stopStreamingForSession(sessionId);
|
||||
}
|
||||
// Each delete records an intentional tombstone so sync can propagate
|
||||
// the removal (the "decrease" side of session-history sync).
|
||||
deleteSession(sessionId);
|
||||
}
|
||||
}, [abortControllersRef, deleteSession, stopStreamingForSession, streamingSessionIds]);
|
||||
|
||||
const handleManagerExport = useCallback((sessionId: string) => {
|
||||
void exportSessionsBackup?.([sessionId]).then((filePath) => {
|
||||
if (filePath == null) {
|
||||
@@ -2464,6 +2552,9 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
onRebind={handleManagerRebind}
|
||||
onRename={handleRenameSession}
|
||||
onDelete={(sessionId) => { void handleManagerDelete(sessionId); }}
|
||||
onDeleteMany={(ids) => { void handleManagerDeleteMany(ids); }}
|
||||
onRegenerateTitle={(sessionId) => handleManagerRegenerateTitle(sessionId)}
|
||||
onRegenerateTitles={(ids) => handleManagerRegenerateTitles(ids)}
|
||||
onExport={handleManagerExport}
|
||||
/>
|
||||
)
|
||||
@@ -2483,6 +2574,9 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
handleManagerRebind,
|
||||
handleRenameSession,
|
||||
handleManagerDelete,
|
||||
handleManagerDeleteMany,
|
||||
handleManagerRegenerateTitle,
|
||||
handleManagerRegenerateTitles,
|
||||
handleManagerExport,
|
||||
onFocusAIScopeTarget,
|
||||
]);
|
||||
@@ -2556,6 +2650,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
contextUsage={contextUsage}
|
||||
canCompact={canCompact}
|
||||
inputValue={inputValue}
|
||||
inputValueRevision={composerValueRevision}
|
||||
setInputValue={setInputValue}
|
||||
handleSend={handleSend}
|
||||
handleSendQuickPrompt={handleSendQuickPrompt}
|
||||
@@ -2666,6 +2761,8 @@ const AI_CHAT_SIDE_PANEL_AI_STATE_KEYS = [
|
||||
'createSession',
|
||||
'deleteSession',
|
||||
'updateSessionTitle',
|
||||
'autoTitleSession',
|
||||
'regenerateSessionTitle',
|
||||
'rebindSessionScope',
|
||||
'exportSessionsBackup',
|
||||
'importSessionsBackup',
|
||||
|
||||
@@ -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
|
||||
@@ -36,7 +37,7 @@ export interface AIChatSidePanelProps {
|
||||
clearDraftForScope: (scopeKey: string) => void;
|
||||
addDraftFiles: (scopeKey: string, fallbackAgentId: string, inputFiles: File[]) => Promise<void>;
|
||||
removeDraftFile: (scopeKey: string, fallbackAgentId: string, fileId: string) => void;
|
||||
createSession: (scope: AISessionScope, agentId?: string) => AISession;
|
||||
createSession: (scope: AISessionScope, agentId?: string, workspaceNameSnapshot?: string) => AISession;
|
||||
/** Non-destructively branch before the last user turn; returns the branch id + restored composer content. */
|
||||
undoLastTurnInSession?: (
|
||||
sessionId: string,
|
||||
@@ -44,6 +45,9 @@ export interface AIChatSidePanelProps {
|
||||
) => Promise<{ sessionId: string; restored: { text: string; attachments: import('../infrastructure/ai/types').UploadedFile[]; selectedUserSkillSlugs: string[] } } | null>;
|
||||
deleteSession: (sessionId: string, scopeKey?: string) => void;
|
||||
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, 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. */
|
||||
|
||||
@@ -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*\/>/);
|
||||
});
|
||||
@@ -690,11 +690,15 @@ const SyncDashboard: React.FC<SyncDashboardProps> = ({
|
||||
if (!ensureSyncablePayload(payload)) return;
|
||||
const result = await sync.syncToProvider(provider, payload, {
|
||||
applyConvergentPayload: onApplyConvergentPayload,
|
||||
// A per-provider button must sync only that provider: skip the
|
||||
// convergent fan-out even when convergent mode is active.
|
||||
// Auto-sync / top-bar Sync Now still use syncAllProviders.
|
||||
forceSingleProvider: true,
|
||||
});
|
||||
|
||||
// Convergent sync fans out to every provider. Even if the
|
||||
// requested provider fails, another provider can verify a newer
|
||||
// joined replica that must be applied before reporting the error.
|
||||
// The selected provider may still carry a newer joined replica
|
||||
// (e.g. written by another device); apply it locally before
|
||||
// reporting the result. This is per-provider only now.
|
||||
if (result.mergedPayload && !result.mergedPayloadApplied && onApplyPayload) {
|
||||
const portableMerged = stripSyncPayloadEncryptedCredentials(result.mergedPayload);
|
||||
await Promise.resolve(onApplyPayload(portableMerged));
|
||||
|
||||
@@ -4,6 +4,7 @@ import { isRemoteDesktopProtocol } from "../domain/remoteDesktop";
|
||||
import React from "react";
|
||||
import { AlertTriangle, ChevronDown, Forward, Globe, HeartPulse, KeyRound, Link2, Palette, Plus, Router, ShieldAlert, TerminalSquare, Timer, Wifi, X, Variable } from "lucide-react";
|
||||
import { customThemeStore } from "../application/state/customThemeStore";
|
||||
import { useExternalEditorSettings } from "../application/state/useExternalEditorSettings";
|
||||
import { clearHostFontSizeOverride, clearHostThemeOverride } from "../domain/terminalAppearance";
|
||||
import { resolveSshAgentToggleUpdate } from "../domain/sshAuth";
|
||||
import { MAX_FONT_SIZE, MIN_FONT_SIZE } from "../infrastructure/config/fonts";
|
||||
@@ -67,6 +68,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
|
||||
proxyInherited = false,
|
||||
clearProxyConfig,
|
||||
}) => {
|
||||
const { settings: externalEditorSettings } = useExternalEditorSettings();
|
||||
const inheritedDeviceType = effectiveGroupDefaults?.deviceType;
|
||||
const effectiveDeviceType = form.deviceType ?? inheritedDeviceType;
|
||||
const effectiveMoshEnabled = form.moshEnabled ?? effectiveGroupDefaults?.moshEnabled;
|
||||
@@ -550,6 +552,39 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
|
||||
enabled={!!form.showLineTimestamps}
|
||||
onToggle={() => update("showLineTimestamps", !form.showLineTimestamps)}
|
||||
/>
|
||||
{isSshView && (
|
||||
<HostDetailsSettingRow
|
||||
label={t("hostDetails.externalEditorShellIntegration")}
|
||||
hint={t("hostDetails.externalEditorShellIntegration.desc")}
|
||||
>
|
||||
<Select
|
||||
value={
|
||||
form.externalEditorShellIntegration === true
|
||||
? "enabled"
|
||||
: form.externalEditorShellIntegration === false
|
||||
? "disabled"
|
||||
: "default"
|
||||
}
|
||||
onValueChange={(v) =>
|
||||
update(
|
||||
"externalEditorShellIntegration",
|
||||
v === "enabled" ? true : v === "disabled" ? false : undefined,
|
||||
)
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-36 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="default">
|
||||
{`${t("hostDetails.backspaceBehavior.default")} (${externalEditorSettings.autoSetupShellIntegration ? t("common.enabled") : t("common.disabled")})`}
|
||||
</SelectItem>
|
||||
<SelectItem value="enabled">{t("common.enabled")}</SelectItem>
|
||||
<SelectItem value="disabled">{t("common.disabled")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</HostDetailsSettingRow>
|
||||
)}
|
||||
{isSshView && !effectiveMoshEnabled && !effectiveEtEnabled && (
|
||||
<>
|
||||
<ToggleRow
|
||||
|
||||
@@ -2,6 +2,11 @@ import React from "react";
|
||||
import { ChevronRight, Info } from "lucide-react";
|
||||
import { applyGroupDefaults, resolveGroupDefaults } from "../domain/groupConfig";
|
||||
import { sanitizeCredentialValue } from "../domain/credentials";
|
||||
import {
|
||||
getExportablePublicKey,
|
||||
hasExportablePublicKey,
|
||||
isKeychainExportDisabled,
|
||||
} from "../domain/keychainExport";
|
||||
import { hasBridgeSshCredentials, resolveBridgeKeyAuth, resolveBridgeSshAgentAuth, resolveHostAuth } from "../domain/sshAuth";
|
||||
import { resolveHostSshConnectionTimeouts } from "../domain/sshConnectionTimeouts";
|
||||
import { connectionTotpFields } from "../domain/totpConfig";
|
||||
@@ -41,6 +46,15 @@ export const KeychainExportPanel: React.FC<KeychainExportPanelProps> = ({
|
||||
onSaveHost,
|
||||
closePanel,
|
||||
}) => {
|
||||
const hasPublicKey = hasExportablePublicKey(panel.key?.publicKey);
|
||||
const exportDisabled = isKeychainExportDisabled({
|
||||
exportHost,
|
||||
exportLocation,
|
||||
exportFilename,
|
||||
publicKey: panel.key?.publicKey,
|
||||
isExporting,
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Key info card */}
|
||||
@@ -159,17 +173,32 @@ export const KeychainExportPanel: React.FC<KeychainExportPanelProps> = ({
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
|
||||
{!hasPublicKey && (
|
||||
<div className="flex items-start gap-2 p-3 bg-muted/50 border border-border/60 rounded-lg">
|
||||
<Info
|
||||
size={14}
|
||||
className="mt-0.5 text-muted-foreground shrink-0"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("keychain.export.missingPublicKeyNote")}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Export button */}
|
||||
<Button
|
||||
className="w-full h-11"
|
||||
disabled={
|
||||
!exportHost ||
|
||||
!exportLocation ||
|
||||
!exportFilename ||
|
||||
isExporting
|
||||
}
|
||||
disabled={exportDisabled}
|
||||
onClick={async () => {
|
||||
if (!exportHost || !panel.key.publicKey) return;
|
||||
if (!exportHost) return;
|
||||
const publicKey = getExportablePublicKey(panel.key?.publicKey);
|
||||
if (!publicKey) {
|
||||
toast.error(
|
||||
t("keychain.export.missingPublicKey"),
|
||||
t("keychain.export.failedTitle"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsExporting(true);
|
||||
|
||||
@@ -216,7 +245,7 @@ export const KeychainExportPanel: React.FC<KeychainExportPanelProps> = ({
|
||||
}
|
||||
|
||||
// Escape the public key for shell (single quotes, escape existing quotes)
|
||||
const escapedPublicKey = panel.key.publicKey.replace(
|
||||
const escapedPublicKey = publicKey.replace(
|
||||
/'/g,
|
||||
"'\\''",
|
||||
);
|
||||
|
||||
@@ -73,8 +73,12 @@ test('Vault navigation mounts a real content slot, yields to host dialogs, and w
|
||||
await act(async () => { selectSection('plugin-vault:missing'); await settle(); });
|
||||
assert.match(document.querySelector('main')!.textContent!, /Built-in hosts/);
|
||||
await act(async () => { snapshot = { ...snapshot, plugins: [{ id: 'com.example.page', version: '1.0.0', displayName: 'Synthetic plugin', commands: [], keybindings: [], menus: [], settings: [], views: [page] }] }; changed?.(); await settle(); });
|
||||
await act(async () => { requestOpenPluginView({ viewId: page.id }); await settle(); });
|
||||
await act(async () => { activeTabStore.setActiveTabId('terminal:synthetic'); await settle(); });
|
||||
assert.equal(activeTabStore.getActiveTabId(), 'terminal:synthetic');
|
||||
await act(async () => { requestOpenPluginView({ viewId: page.id, params: { connectionId: 'db-1' } }); await settle(); });
|
||||
assert.equal(activeTabStore.getActiveTabId(), 'vault', 'opening a vault-page switches the active tab to vault');
|
||||
assert.equal(opens.length, 2);
|
||||
assert.deepEqual(opens[1].context, { 'netcatty.surface': 'vault-page' }, 'activation params must not be merged into contribution context');
|
||||
await act(async () => { selectSection('hosts'); await settle(); });
|
||||
assert.equal(document.querySelector('[data-plugin-vault-page]'), null);
|
||||
} finally {
|
||||
@@ -82,3 +86,91 @@ test('Vault navigation mounts a real content slot, yields to host dialogs, and w
|
||||
for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); }
|
||||
}
|
||||
});
|
||||
|
||||
test('Failed host-drawn view session stays on the plugin vault page with error and retry instead of falling back to Hosts', async () => {
|
||||
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', { pretendToBeVisual: true, url: 'http://localhost' });
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'MutationObserver', '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 Window] });
|
||||
}
|
||||
for (const [key, value] of Object.entries({ getComputedStyle: dom.window.getComputedStyle.bind(dom.window),
|
||||
requestAnimationFrame: dom.window.requestAnimationFrame.bind(dom.window), cancelAnimationFrame: dom.window.cancelAnimationFrame.bind(dom.window), IS_REACT_ACT_ENVIRONMENT: true })) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key)); Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
}
|
||||
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({ x: 200, y: 100, width: 640, height: 480, top: 100, left: 200, right: 840, bottom: 580, toJSON() {} });
|
||||
const { act, useState } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { usePluginVaultPages } = await import('../application/state/usePluginVaultPages');
|
||||
const { PluginVaultNavigation, PluginVaultPage } = await import('./plugins/PluginVaultPages');
|
||||
const { activeTabStore } = await import('../application/state/activeTabStore');
|
||||
const { I18nProvider } = await import('../application/i18n/I18nProvider');
|
||||
const page = { id: 'com.example.page.main', title: 'Synthetic page', location: 'vault-page', visible: true };
|
||||
let snapshot = { locale: 'en', plugins: [{ id: 'com.example.page', version: '1.0.0', displayName: 'Synthetic plugin', commands: [], keybindings: [], menus: [], settings: [], views: [page] }] };
|
||||
let changed: (() => void) | undefined;
|
||||
const listeners = new Set<(event: NetcattyPluginViewClosedEvent) => void>();
|
||||
const opens: NetcattyPluginViewOpenRequest[] = [], closes: string[] = [];
|
||||
Object.assign(dom.window, { netcatty: {
|
||||
async getPluginRuntimeStatus() { return { available: true }; },
|
||||
async getPluginContributions() { return snapshot; },
|
||||
onPluginContributionsChanged(fn: () => void) { changed = fn; return () => { changed = undefined; }; },
|
||||
onPluginViewClosed(fn: (event: NetcattyPluginViewClosedEvent) => void) { listeners.add(fn); return () => { listeners.delete(fn); }; },
|
||||
onHostDrawnPluginViewUpdate() { return () => {}; },
|
||||
async openHostDrawnPluginView(payload: NetcattyPluginViewOpenRequest) { opens.push(payload); return { instanceId: payload.instanceId! }; },
|
||||
async closeHostDrawnPluginView(id: string) { closes.push(id); },
|
||||
} });
|
||||
function Fixture() {
|
||||
const [section, select] = useState<'hosts' | `plugin-vault:${string}`>('hosts');
|
||||
const model = usePluginVaultPages({ locale: 'en', section, select });
|
||||
return <><aside><button data-plugin-vault-fallback onClick={() => select('hosts')}>Hosts</button><PluginVaultNavigation model={model} collapsed={false} /></aside>
|
||||
<main data-section="vault-main">{model.selected ? <PluginVaultPage key={model.selected.key} model={model} /> : <p>Built-in hosts</p>}</main></>;
|
||||
}
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 35));
|
||||
try {
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
await act(async () => { root.render(<I18nProvider locale="en"><Fixture /></I18nProvider>); await settle(); });
|
||||
await act(async () => {
|
||||
document.querySelector<HTMLButtonElement>('button[aria-label="Synthetic page — Synthetic plugin"]')!.click();
|
||||
await import('./plugins/PluginHostDrawnPage');
|
||||
await settle();
|
||||
});
|
||||
assert.equal(opens.length, 1);
|
||||
assert.ok(document.querySelector('[data-plugin-vault-page]'));
|
||||
|
||||
// Session fails while plugin contribution remains active.
|
||||
await act(async () => {
|
||||
for (const listener of listeners) {
|
||||
listener({ instanceId: opens[0].instanceId!, viewId: page.id, pluginId: 'com.example.page', reason: 'view-error' });
|
||||
}
|
||||
await settle();
|
||||
});
|
||||
assert.ok(document.querySelector('[data-plugin-vault-page]'), 'stays on the plugin vault page');
|
||||
assert.doesNotMatch(document.querySelector('main')!.textContent!, /Built-in hosts/);
|
||||
assert.equal(document.querySelector('[data-plugin-remote-surface]'), null, 'does not render an empty remote surface');
|
||||
const alert = document.querySelector('[data-plugin-vault-page] [role="alert"]');
|
||||
assert.ok(alert, 'renders in-page error alert');
|
||||
assert.equal(alert!.textContent, 'The plugin page failed to render.');
|
||||
|
||||
const retryButton = [...document.querySelectorAll<HTMLButtonElement>('[data-plugin-vault-page] button')]
|
||||
.find((btn) => btn.textContent === 'Retry');
|
||||
assert.ok(retryButton, 'renders Retry control');
|
||||
|
||||
await act(async () => {
|
||||
retryButton!.click();
|
||||
await settle();
|
||||
});
|
||||
assert.equal(opens.length, 2, 'clicking Retry opens a new host-drawn plugin view session');
|
||||
assert.notEqual(opens[1].instanceId, opens[0].instanceId);
|
||||
assert.equal(document.querySelector('[data-plugin-vault-page] [role="alert"]'), null);
|
||||
|
||||
// Removing the contribution still falls back to Hosts.
|
||||
await act(async () => { snapshot = { ...snapshot, plugins: [] }; changed?.(); await settle(); });
|
||||
await act(async () => { await settle(); });
|
||||
assert.equal(document.querySelector('[data-plugin-vault-page]'), null);
|
||||
assert.match(document.querySelector('main')!.textContent!, /Built-in hosts/);
|
||||
} finally {
|
||||
await act(async () => { root.unmount(); (await import('../application/state/pluginViewSession')).pluginViewSessions.dispose(); await settle(); }); dom.window.close();
|
||||
for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); }
|
||||
}
|
||||
});
|
||||
+16
-15
@@ -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"));
|
||||
@@ -258,6 +257,12 @@ const SettingsAITabContainer: React.FC = () => {
|
||||
setQuickMessages={aiState.setQuickMessages}
|
||||
showTerminalSelectionAIAction={aiState.showTerminalSelectionAIAction}
|
||||
setShowTerminalSelectionAIAction={aiState.setShowTerminalSelectionAIAction}
|
||||
autoLlmTitle={aiState.autoLlmTitle}
|
||||
setAutoLlmTitle={aiState.setAutoLlmTitle}
|
||||
titleModel={aiState.titleModel}
|
||||
setTitleModel={aiState.setTitleModel}
|
||||
agentProviderMap={aiState.agentProviderMap}
|
||||
agentModelMap={aiState.agentModelMap}
|
||||
/>
|
||||
</AITabErrorBoundary>
|
||||
);
|
||||
@@ -335,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
|
||||
@@ -345,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) => {
|
||||
@@ -581,6 +576,8 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
|
||||
setShowSftpTab={settings.setShowSftpTab}
|
||||
showHostTreeSidebar={settings.showHostTreeSidebar}
|
||||
setShowHostTreeSidebar={settings.setShowHostTreeSidebar}
|
||||
removeTopTabsDragArea={settings.removeTopTabsDragArea}
|
||||
setRemoveTopTabsDragArea={settings.setRemoveTopTabsDragArea}
|
||||
windowOpacity={settings.windowOpacity}
|
||||
setWindowOpacity={settings.setWindowOpacity}
|
||||
windowBackgroundBlur={settings.windowBackgroundBlur}
|
||||
@@ -640,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}
|
||||
@@ -749,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,
|
||||
);
|
||||
});
|
||||
+30
-2
@@ -1,4 +1,5 @@
|
||||
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 { publishTerminalSelectionTarget } from "../infrastructure/plugins/terminalSelectionRegistry";
|
||||
@@ -1411,6 +1412,32 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
const osc52ReadResolverRef = useRef<((allowed: boolean) => void) | null>(null);
|
||||
const [osc7SetupOpen, setOsc7SetupOpen] = useState(false);
|
||||
const [osc7SetupRunning, setOsc7SetupRunning] = useState(false);
|
||||
|
||||
const {
|
||||
pendingExternalEditorRequest,
|
||||
handleOscExternalEditorRequest,
|
||||
handleExternalEditorPromptResponse,
|
||||
} = useTerminalExternalEditor({
|
||||
sessionId,
|
||||
status,
|
||||
host,
|
||||
isLocalConnection,
|
||||
isSerialConnection,
|
||||
getBackendSessionId: () => sessionRef.current ?? sessionId,
|
||||
isVisible: () => isVisibleRef.current,
|
||||
getFallbackCwd: () => terminalCwdTracker.getRendererCwd() ?? knownCwdRef.current ?? undefined,
|
||||
isReadyForCommandInjection: () => isTerminalReadyForCommandInjection(sessionId),
|
||||
setupOsc7Tracking: terminalBackend.setupOsc7Tracking,
|
||||
writeToSession: terminalBackend.writeToSession,
|
||||
focusTerminal: () => termRef.current?.focus(),
|
||||
onOpened: (editor, path) =>
|
||||
toast.success(t("terminal.externalEditor.opened", { editor, path })),
|
||||
onOpenFailed: (message) => toast.error(message),
|
||||
formatFallbackOpenError: (editor) =>
|
||||
t("terminal.externalEditor.failed", { editor }),
|
||||
onAutoSetupConfigured: (editor) =>
|
||||
toast.success(t("terminal.externalEditor.autoSetupConfigured", { editor })),
|
||||
});
|
||||
const handleOsc52ReadRequest = useCallback((): Promise<boolean> => {
|
||||
// Reject if terminal is not visible (background tab) — user can't see the prompt
|
||||
if (!isVisibleRef.current) return Promise.resolve(false);
|
||||
@@ -4812,6 +4839,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
});
|
||||
},
|
||||
onOsc52ReadRequest: handleOsc52ReadRequest,
|
||||
onOscExternalEditorRequest: handleOscExternalEditorRequest,
|
||||
onAutocompleteKeyEvent: (e: KeyboardEvent) => autocompleteKeyEventRef.current?.(e) ?? true,
|
||||
onAutocompleteInput: (data: string) => autocompleteInputRef.current?.(data),
|
||||
onAutocompleteReposition: () => autocompleteRepositionRef.current?.(),
|
||||
@@ -5078,11 +5106,11 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
onWake: wakeFromHibernateRuntime,
|
||||
});
|
||||
|
||||
useTerminalEffects({ isPromptSecurityAlternateScreenActive, CONNECTION_TIMEOUT, Error, XTERM_PERFORMANCE_CONFIG, applyUserCursorPreference, applyUserCursorWidthPreference, shouldApplyUserCursorPreference, snapshotUserCursorPreference, auth, autocompleteCloseRef, autocompleteInputRef, autocompleteKeyEventRef, autocompleteRepositionRef, captureTerminalLogData, chainHosts: resolvedChainHosts, chainProgress, clearTerminalCwd, commandBufferRef, connectionLogBufferRef, containerRef, createPromptLineBreakState, createReplaySafeTerminalLogSanitizer, createXTermRuntime, deferTerminalResizeRef, disableTerminalFontZoomRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippetCommand, finalizeTerminalLogData, fitAddonRef, fontFamilyId, fontSize, fontWeightFixupDoneRef, forceCloseHibernatedSession, forceSyncRenderAfterResize, handleOsc52ReadRequest, handleTerminalDataCaptureOnce, hasConnectedRef, hasRuntimeRef, host, hotkeySchemeRef, hibernatedRef, identities, inWorkspace, isBootActiveRef, bootEpochRef, isBroadcastEnabledRef, broadcastPasswordBypassRef, isComposeBarOpen: effectiveComposeBarOpen, isConnectionAwaitingUserInput, isConnectionPastTcpDial, isWaitingForAutoReconnect, isFocusMode, isFocused, isLocalConnection, isNetworkDevice, isResizing: deferTerminalResize, isRestoringSelectionRef, isSearchOpen, isSerialConnection, isVisible, isVisibleRef, keyBindingsRef, keys, kittyKeyboardProtocolEnabledForSession, knownCwdRef, lastFittedSizeRef, lastToastedErrorRef, logger, mouseTrackingRef, needsHostKeyVerification, onBroadcastInputRef, onBroadcastInterruptPriorityChange, onCommandExecuted, onCommandSubmitted: cwdAwareOnCommandSubmitted, onCommandSettled: onCommandSubmitted, onHotkeyActionRef, onOpenExternalError, onOutputTriggerUserInputRef: noteOutputTriggerUserInputRef, onPluginRuntimeCwdChange: pluginAwareOnRuntimeCwdChange, onSnippetShortkeyRef, onSnippetExecutorChange, onTerminalCwdChange, onTerminalTitleChange, onTerminalBell, onTerminalFontSizeChange, paneLayoutKey, passwordPromptActiveRef, pendingAuthRef, pendingOutputScrollRef, pluginDecorationRefreshRef, pluginDecorationRules, pluginDecorationRulesRef, pluginTerminalLifecycle, pluginTerminalProviderRevision, isPluginTerminalProviderAvailable, requestPluginTerminalProviders, prepareRestoredReconnect, prepareInitialCwdIntent, prevIsResizingRef, promptLineBreakStateRef, resizeSession, resolveHostAuth, resolvedFontFamily, safeFit, scriptRecorderRef: recorderRef, searchAddonRef, serialConfig, serialLineBufferRef, serializeAddonRef, sessionId, sessionRef, sessionStarters, setError, setHasMouseTracking, setIsCancelling, setIsDisconnectedDialogDismissed, requestSearchFocus, setNeedsHostKeyVerification, setPendingHostKeyInfo, setPendingHostKeyRequestId, setProgressLogs, setProgressValue, setShowLogs, setStatus, setConnectionDeadlineAt, shellType, shouldEnableNativeUserInputAutoScroll, shouldProbeSessionCwd, shouldStartTerminalBackend, vaultInitialized, attachExistingSession, attachAuthorization, attachHomeWebContentsIdRef, snippetsRef, splitResizeActive: isResizing, status, statusRef, sudoAutofillRef, t, teardown, telnetLocalEchoRef, termRef, terminalAltKeyOptions, terminalBackend, terminalContextActionsRef, terminalCwdTracker, terminalDataCapturedRef, terminalLogSanitizerRef, terminalOutputHistory: terminalOutputHistoryRef.current, terminalSettings, terminalSettingsRef, terminalTitleRef, toHostKeyInfo, toast, updateStatus, useEffect, useLayoutEffect, workspaceId, xtermRuntimeRef, zmodem, zmodemToastedRef, restoreState });
|
||||
useTerminalEffects({ isPromptSecurityAlternateScreenActive, CONNECTION_TIMEOUT, Error, XTERM_PERFORMANCE_CONFIG, applyUserCursorPreference, applyUserCursorWidthPreference, shouldApplyUserCursorPreference, snapshotUserCursorPreference, auth, autocompleteCloseRef, autocompleteInputRef, autocompleteKeyEventRef, autocompleteRepositionRef, captureTerminalLogData, chainHosts: resolvedChainHosts, chainProgress, clearTerminalCwd, commandBufferRef, connectionLogBufferRef, containerRef, createPromptLineBreakState, createReplaySafeTerminalLogSanitizer, createXTermRuntime, deferTerminalResizeRef, disableTerminalFontZoomRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippetCommand, finalizeTerminalLogData, fitAddonRef, fontFamilyId, fontSize, fontWeightFixupDoneRef, forceCloseHibernatedSession, forceSyncRenderAfterResize, handleOsc52ReadRequest, handleOscExternalEditorRequest, handleTerminalDataCaptureOnce, hasConnectedRef, hasRuntimeRef, host, hotkeySchemeRef, hibernatedRef, identities, inWorkspace, isBootActiveRef, bootEpochRef, isBroadcastEnabledRef, broadcastPasswordBypassRef, isComposeBarOpen: effectiveComposeBarOpen, isConnectionAwaitingUserInput, isConnectionPastTcpDial, isWaitingForAutoReconnect, isFocusMode, isFocused, isLocalConnection, isNetworkDevice, isResizing: deferTerminalResize, isRestoringSelectionRef, isSearchOpen, isSerialConnection, isVisible, isVisibleRef, keyBindingsRef, keys, kittyKeyboardProtocolEnabledForSession, knownCwdRef, lastFittedSizeRef, lastToastedErrorRef, logger, mouseTrackingRef, needsHostKeyVerification, onBroadcastInputRef, onBroadcastInterruptPriorityChange, onCommandExecuted, onCommandSubmitted: cwdAwareOnCommandSubmitted, onCommandSettled: onCommandSubmitted, onHotkeyActionRef, onOpenExternalError, onOutputTriggerUserInputRef: noteOutputTriggerUserInputRef, onPluginRuntimeCwdChange: pluginAwareOnRuntimeCwdChange, onSnippetShortkeyRef, onSnippetExecutorChange, onTerminalCwdChange, onTerminalTitleChange, onTerminalBell, onTerminalFontSizeChange, paneLayoutKey, passwordPromptActiveRef, pendingAuthRef, pendingOutputScrollRef, pluginDecorationRefreshRef, pluginDecorationRules, pluginDecorationRulesRef, pluginTerminalLifecycle, pluginTerminalProviderRevision, isPluginTerminalProviderAvailable, requestPluginTerminalProviders, prepareRestoredReconnect, prepareInitialCwdIntent, prevIsResizingRef, promptLineBreakStateRef, resizeSession, resolveHostAuth, resolvedFontFamily, safeFit, scriptRecorderRef: recorderRef, searchAddonRef, serialConfig, serialLineBufferRef, serializeAddonRef, sessionId, sessionRef, sessionStarters, setError, setHasMouseTracking, setIsCancelling, setIsDisconnectedDialogDismissed, requestSearchFocus, setNeedsHostKeyVerification, setPendingHostKeyInfo, setPendingHostKeyRequestId, setProgressLogs, setProgressValue, setShowLogs, setStatus, setConnectionDeadlineAt, shellType, shouldEnableNativeUserInputAutoScroll, shouldProbeSessionCwd, shouldStartTerminalBackend, vaultInitialized, attachExistingSession, attachAuthorization, attachHomeWebContentsIdRef, snippetsRef, splitResizeActive: isResizing, status, statusRef, sudoAutofillRef, t, teardown, telnetLocalEchoRef, termRef, terminalAltKeyOptions, terminalBackend, terminalContextActionsRef, terminalCwdTracker, terminalDataCapturedRef, terminalLogSanitizerRef, terminalOutputHistory: terminalOutputHistoryRef.current, terminalSettings, terminalSettingsRef, terminalTitleRef, toHostKeyInfo, toast, updateStatus, useEffect, useLayoutEffect, workspaceId, xtermRuntimeRef, zmodem, zmodemToastedRef, restoreState });
|
||||
|
||||
return (
|
||||
<>
|
||||
<TerminalView ctx={{ Activity, ArrowDownToLine, ArrowUpFromLine, Button, Clock3, Copy, Cpu, HardDrive, HoverCard, HoverCardContent, HoverCardTrigger, Maximize2, MemoryStick, Radio, RefreshCcw, Sparkles, SquareArrowOutUpRight, Unplug, TerminalAutocomplete, TerminalComposeBar, TerminalConnectionDialog, TerminalContextMenu, TerminalSearchBar, Tooltip, TooltipContent, TooltipTrigger, ZmodemOverwriteDialog, ZmodemProgressIndicator, auth, autocompleteAcceptTextRef, autocompleteCloseRef, autocompleteHostOs, autocompleteInputRef, autocompleteKeyEventRef, autocompleteRepositionRef, autocompleteSettings, canUpdateHost: !!onUpdateHost, chainProgress, cn, compactToolbar, lineTimestampsAvailable, containerRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippet, executeSnippetCommand, handleAddSelectionToAI: onAddSelectionToAI ? handleAddSelectionToAI : undefined, handleCancelConnect, handleCloseDisconnectedSession, handleCloseSearch, handleDisconnect: (attachExistingSession || compactToolbar) ? undefined : handleDisconnect, handleDismissDisconnectedDialog, handleDragEnter, handleDragLeave, handleDragOver, handleDrop, handleFindNext, handleFindPrevious, handleHostKeyAddAndContinue, handleHostKeyClose, handleHostKeyContinue, handleOpenHostBrowser, handleOpenSFTP, handleOsc52ReadResponse, handleOsc7SetupConfirm, handleOsc7SetupOpenChange, handleReceiveYmodem, handleRetry, handleSearch, handleSendYmodem, handleTopOverlayMouseDownCapture, hasMouseTracking, host, hotkeyScheme, inWorkspace, isBroadcastEnabled, composeSendToAll, onToggleComposeSendTarget, isCancelling, isComposeBarOpen: effectiveComposeBarOpen, isConnectionAwaitingUserInput, isDraggingOver, isFocusMode, isFocusedPane, isLocalConnection, remoteDragDropUsesZmodem, isPluginTerminalProviderAvailable, isReconnectActive, isSerialConnection, isSearchOpen, isSupportedOs, isSystemSidebarEligible, isVisible, keyBindings, keys, identities, knownCwdRef, needsHostKeyVerification, onAddSelectionToAI, onBroadcastInput, onCloseSession, onDetach, onDetachDragEnd, onDetachDragStart, onDetachPointerDown, onEndSessionDrag, onExpandToFocus, onTogglePaneMagnification, onOpenSystem, onRename, onSplitHorizontal, onSplitVertical, onStartSessionDrag, onToggleBroadcast, onUpdateHost: handleUpdateHostFromTerminal, osc52ReadPromptVisible, osc7SetupOpen, osc7SetupRunning, passwordPromptActiveRef, pendingHostKeyInfo, progressLogs, progressValue, renderControls, resolvedFontFamily, restoreState, scrollToBottomAfterProgrammaticInput, searchMatchCount, searchFocusToken, scriptExecutionOverlay: activeScriptRun ? (
|
||||
<TerminalView ctx={{ Activity, ArrowDownToLine, ArrowUpFromLine, Button, Clock3, Copy, Cpu, HardDrive, HoverCard, HoverCardContent, HoverCardTrigger, Maximize2, MemoryStick, Radio, RefreshCcw, Sparkles, SquareArrowOutUpRight, Unplug, TerminalAutocomplete, TerminalComposeBar, TerminalConnectionDialog, TerminalContextMenu, TerminalSearchBar, Tooltip, TooltipContent, TooltipTrigger, ZmodemOverwriteDialog, ZmodemProgressIndicator, auth, autocompleteAcceptTextRef, autocompleteCloseRef, autocompleteHostOs, autocompleteInputRef, autocompleteKeyEventRef, autocompleteRepositionRef, autocompleteSettings, canUpdateHost: !!onUpdateHost, chainProgress, cn, compactToolbar, lineTimestampsAvailable, containerRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippet, executeSnippetCommand, handleAddSelectionToAI: onAddSelectionToAI ? handleAddSelectionToAI : undefined, handleCancelConnect, handleCloseDisconnectedSession, handleCloseSearch, handleDisconnect: (attachExistingSession || compactToolbar) ? undefined : handleDisconnect, handleDismissDisconnectedDialog, handleDragEnter, handleDragLeave, handleDragOver, handleDrop, handleFindNext, handleFindPrevious, handleHostKeyAddAndContinue, handleHostKeyClose, handleHostKeyContinue, handleOpenHostBrowser, handleOpenSFTP, handleOsc52ReadResponse, handleExternalEditorPromptResponse, handleOsc7SetupConfirm, handleOsc7SetupOpenChange, handleReceiveYmodem, handleRetry, handleSearch, handleSendYmodem, handleTopOverlayMouseDownCapture, hasMouseTracking, host, hotkeyScheme, inWorkspace, isBroadcastEnabled, composeSendToAll, onToggleComposeSendTarget, isCancelling, isComposeBarOpen: effectiveComposeBarOpen, isConnectionAwaitingUserInput, isDraggingOver, isFocusMode, isFocusedPane, isLocalConnection, remoteDragDropUsesZmodem, isPluginTerminalProviderAvailable, isReconnectActive, isSerialConnection, isSearchOpen, isSupportedOs, isSystemSidebarEligible, isVisible, keyBindings, keys, identities, knownCwdRef, needsHostKeyVerification, onAddSelectionToAI, onBroadcastInput, onCloseSession, onDetach, onDetachDragEnd, onDetachDragStart, onDetachPointerDown, onEndSessionDrag, onExpandToFocus, onTogglePaneMagnification, onOpenSystem, onRename, onSplitHorizontal, onSplitVertical, onStartSessionDrag, onToggleBroadcast, onUpdateHost: handleUpdateHostFromTerminal, osc52ReadPromptVisible, pendingExternalEditorRequest, osc7SetupOpen, osc7SetupRunning, passwordPromptActiveRef, pendingHostKeyInfo, progressLogs, progressValue, renderControls, resolvedFontFamily, restoreState, scrollToBottomAfterProgrammaticInput, searchMatchCount, searchFocusToken, scriptExecutionOverlay: activeScriptRun ? (
|
||||
<ScriptExecutionOverlay
|
||||
run={activeScriptRun}
|
||||
onPause={() => { void pauseScriptRun(activeScriptRun.runId); }}
|
||||
|
||||
@@ -1497,6 +1497,9 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
if (!shouldProbeCommandCwd({
|
||||
restoreTerminalCwd,
|
||||
visibleSftpHost,
|
||||
latestVisibleSftpHost: visibleSftpHost
|
||||
? hostsRef.current.find((host) => host.id === visibleSftpHost.id)
|
||||
: undefined,
|
||||
sessionHost,
|
||||
globalSftpFollowTerminalCwd: sftpFollowTerminalCwdRef.current,
|
||||
restrictExtraSshChannels: hostRestrictsExtraSshChannels(sessionHost),
|
||||
|
||||
+10
-2
@@ -217,6 +217,7 @@ interface TopTabsProps {
|
||||
tabInsertionTarget?: { tabId: string; position: 'before' | 'after'; additionalTabIds?: readonly string[] },
|
||||
) => void;
|
||||
onAppendHostToWorkspace?: (workspaceId: string, hostId: string) => void;
|
||||
onRequestAddToWorkspace?: (workspaceId: string) => void;
|
||||
showSftpTab: boolean;
|
||||
showHostTreeSidebar: boolean;
|
||||
switchTabKeyBinding: Pick<KeyBinding, 'mac' | 'pc'> | null;
|
||||
@@ -270,6 +271,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
onReorderTabs,
|
||||
onRemoveSessionFromWorkspace,
|
||||
onAppendHostToWorkspace,
|
||||
onRequestAddToWorkspace,
|
||||
showSftpTab,
|
||||
showHostTreeSidebar,
|
||||
switchTabKeyBinding,
|
||||
@@ -288,6 +290,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
const {
|
||||
hotkeyScheme,
|
||||
showTabNumberBadges,
|
||||
removeTopTabsDragArea,
|
||||
shellOnlyTabNumberShortcuts,
|
||||
} = useSettingsChromeStore();
|
||||
const switchTabKey = hotkeyScheme === 'mac'
|
||||
@@ -1031,6 +1034,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
onTabDrop={handleTabDrop}
|
||||
onRenameWorkspace={onRenameWorkspace}
|
||||
onCopyWorkspace={onCopyWorkspace}
|
||||
onRequestAddToWorkspace={onRequestAddToWorkspace}
|
||||
onCloseWorkspace={onCloseWorkspace}
|
||||
onDetachSessionFromWorkspace={handleDetachSessionFromWorkspace}
|
||||
renderBulkCloseItems={renderBulkCloseItems}
|
||||
@@ -1087,6 +1091,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
<div
|
||||
data-top-tabs-root
|
||||
data-section="top-tabs"
|
||||
data-remove-top-tabs-drag-area={removeTopTabsDragArea ? 'true' : undefined}
|
||||
className="relative w-full bg-secondary app-drag"
|
||||
style={{
|
||||
...dragRegionNoSelect,
|
||||
@@ -1099,9 +1104,11 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
tabsContainerRef={tabsContainerRef}
|
||||
updateScrollState={updateScrollState}
|
||||
/>
|
||||
{/* Always-on drag stripe so the window can be moved even when tabs fill the bar */}
|
||||
<div className="absolute inset-x-0 top-0 h-1 app-drag pointer-events-auto z-10" style={dragRegionStyle} aria-hidden />
|
||||
{!removeTopTabsDragArea && (
|
||||
<div className="absolute inset-x-0 top-0 h-1 app-drag pointer-events-auto z-10" style={dragRegionStyle} aria-hidden />
|
||||
)}
|
||||
<div
|
||||
data-section="top-tabs-toolbar-row"
|
||||
className="h-9 flex items-end gap-0 app-drag overflow-visible"
|
||||
style={{
|
||||
...dragRegionStyle,
|
||||
@@ -1387,6 +1394,7 @@ export const topTabsAreEqual = (prev: TopTabsProps, next: TopTabsProps): boolean
|
||||
prev.onMoveSessionToNewWindow === next.onMoveSessionToNewWindow &&
|
||||
prev.onEditHost === next.onEditHost &&
|
||||
prev.onAppendHostToWorkspace === next.onAppendHostToWorkspace &&
|
||||
prev.onRequestAddToWorkspace === next.onRequestAddToWorkspace &&
|
||||
prev.onCopyWorkspace === next.onCopyWorkspace &&
|
||||
prev.onOpenSettings === next.onOpenSettings &&
|
||||
prev.onLockApp === next.onLockApp &&
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -394,6 +394,7 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
const vaultNavConfig = useVaultNavConfig({
|
||||
activePluginIds: activePluginNavIds,
|
||||
pluginsLoading: pluginVault.contributions.loading,
|
||||
pluginsAvailable: pluginVault.contributions.available,
|
||||
});
|
||||
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\}/);
|
||||
@@ -412,3 +412,20 @@ test('renders vault note attachment chips with the note title', () => {
|
||||
assert.match(source, /file\.vaultNoteId \? \(/);
|
||||
assert.match(source, /\{file\.vaultNoteTitle \|\| file\.filename\}/);
|
||||
});
|
||||
|
||||
test('valueRevision clears the uncontrolled textarea even when value stays empty across renders', () => {
|
||||
const chatInputSource = readFileSync(new URL('./ChatInput.tsx', import.meta.url), 'utf8');
|
||||
const sidePanelSource = readFileSync(new URL('../AIChatSidePanel.tsx', import.meta.url), 'utf8');
|
||||
const contentSource = readFileSync(new URL('../AIChatPanelContent.tsx', import.meta.url), 'utf8');
|
||||
|
||||
assert.match(chatInputSource, /valueRevision\?: number/);
|
||||
assert.match(chatInputSource, /prev\.valueRevision === next\.valueRevision/);
|
||||
assert.match(chatInputSource, /const revisionChanged = valueRevision !== lastValueRevisionRef\.current/);
|
||||
assert.match(chatInputSource, /if \(!revisionChanged && value === pushedParentTextRef\.current\) return/);
|
||||
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';
|
||||
@@ -207,6 +207,12 @@ const ComposerSendUi = React.memo(function ComposerSendUi({
|
||||
|
||||
interface ChatInputProps {
|
||||
value: string;
|
||||
/**
|
||||
* Monotonic revision bumped by the parent whenever an authoritative reset
|
||||
* (e.g. post-send draft clear) must be applied to the uncontrolled textarea
|
||||
* even when `value` stayed equal across renders (such as `""` -> `""`).
|
||||
*/
|
||||
valueRevision?: number;
|
||||
onChange: (value: string) => void;
|
||||
onSend: (textOverride?: string) => void;
|
||||
onCompact?: () => void;
|
||||
@@ -303,6 +309,7 @@ interface ChatInputProps {
|
||||
|
||||
const ChatInput: React.FC<ChatInputProps> = ({
|
||||
value,
|
||||
valueRevision = 0,
|
||||
onChange,
|
||||
onSend,
|
||||
onCompact,
|
||||
@@ -548,15 +555,18 @@ const ChatInput: React.FC<ChatInputProps> = ({
|
||||
textareaRef.current?.value ?? composerTextRef.current
|
||||
), []);
|
||||
|
||||
useEffect(() => {
|
||||
if (value === pushedParentTextRef.current) return;
|
||||
const lastValueRevisionRef = useRef(valueRevision);
|
||||
useLayoutEffect(() => {
|
||||
const revisionChanged = valueRevision !== lastValueRevisionRef.current;
|
||||
lastValueRevisionRef.current = valueRevision;
|
||||
if (!revisionChanged && value === pushedParentTextRef.current) return;
|
||||
pushedParentTextRef.current = value;
|
||||
composerTextRef.current = value;
|
||||
if (textareaRef.current && textareaRef.current.value !== value) {
|
||||
textareaRef.current.value = value;
|
||||
}
|
||||
syncHasComposerText(value);
|
||||
}, [syncHasComposerText, value]);
|
||||
}, [syncHasComposerText, value, valueRevision]);
|
||||
|
||||
const commitComposerText = useCallback((next: string) => {
|
||||
composerTextRef.current = next;
|
||||
@@ -568,13 +578,20 @@ const ChatInput: React.FC<ChatInputProps> = ({
|
||||
onChange(next);
|
||||
}, [onChange, syncHasComposerText]);
|
||||
|
||||
const syncUncommittedComposerText = useCallback(() => {
|
||||
const current = readComposerText();
|
||||
if (current !== pushedParentTextRef.current) {
|
||||
commitComposerText(current);
|
||||
}
|
||||
}, [commitComposerText, readComposerText]);
|
||||
|
||||
const parkedRef = useRef(parked);
|
||||
useEffect(() => {
|
||||
const becameParked = parked && !parkedRef.current;
|
||||
parkedRef.current = parked;
|
||||
if (!becameParked) return;
|
||||
commitComposerText(readComposerText());
|
||||
}, [commitComposerText, parked, readComposerText]);
|
||||
syncUncommittedComposerText();
|
||||
}, [parked, syncUncommittedComposerText]);
|
||||
|
||||
const onChangeRef = useRef(onChange);
|
||||
onChangeRef.current = onChange;
|
||||
@@ -1406,7 +1423,7 @@ const ChatInput: React.FC<ChatInputProps> = ({
|
||||
setAiComposerComposing(false);
|
||||
handleInputChange(e.currentTarget.value);
|
||||
}}
|
||||
onBlur={() => commitComposerText(readComposerText())}
|
||||
onBlur={syncUncommittedComposerText}
|
||||
onKeyDown={handleTextareaKeyDown}
|
||||
placeholder={placeholder || (isStreaming && canSteer ? t('ai.codex.steer.placeholder') : defaultPlaceholder)}
|
||||
disabled={composerDisabled}
|
||||
@@ -1977,6 +1994,7 @@ function contextUsageEqual(
|
||||
function chatInputPropsAreEqual(prev: ChatInputProps, next: ChatInputProps): boolean {
|
||||
return (
|
||||
prev.value === next.value
|
||||
&& prev.valueRevision === next.valueRevision
|
||||
&& prev.onChange === next.onChange
|
||||
&& prev.onSend === next.onSend
|
||||
&& prev.onCompact === next.onCompact
|
||||
|
||||
@@ -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">
|
||||
|
||||
Loaded 100 of 377 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user