mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-26 19:07:17 +00:00
Compare commits
70
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e94f937570 | ||
|
|
1595d2ed62 | ||
|
|
f4a087e890 | ||
|
|
ac8869884f | ||
|
|
d556e5c5de | ||
|
|
3026be2dc9 | ||
|
|
883fdaf114 | ||
|
|
9a49ac33bf | ||
|
|
da162f050b | ||
|
|
834ca122c4 | ||
|
|
ac885e2a36 | ||
|
|
fea4e1eda0 | ||
|
|
cb87b71603 | ||
|
|
b1de01546f | ||
|
|
d5acb4641e | ||
|
|
60841628d6 | ||
|
|
99197b3e18 | ||
|
|
d052a8597c | ||
|
|
d4f819b885 | ||
|
|
8930270820 | ||
|
|
5789b28014 | ||
|
|
8c66f8786d | ||
|
|
29be836550 | ||
|
|
703148c84f | ||
|
|
5b33d410f9 | ||
|
|
c27a40e5f0 | ||
|
|
30f9a91576 | ||
|
|
6461acb575 | ||
|
|
2347f33bc8 | ||
|
|
22e6b02ce2 | ||
|
|
58bc929a17 | ||
|
|
7e94183b89 | ||
|
|
b8d05b3074 | ||
|
|
e99ab5a8eb | ||
|
|
9a2d6ef7bf | ||
|
|
27a6f2e7a6 | ||
|
|
c52ca5f730 | ||
|
|
0aeb1df039 | ||
|
|
b8f3577cd8 | ||
|
|
412f6c4ec6 | ||
|
|
32b1b633db | ||
|
|
e2b0f83ea9 | ||
|
|
4d7906a710 | ||
|
|
9c14e3934f | ||
|
|
59db998ec4 | ||
|
|
78c7d30648 | ||
|
|
4c3f0ce80b | ||
|
|
fd732dff9c | ||
|
|
93bec7497c | ||
|
|
fa9b28adde | ||
|
|
0eefb9ea46 | ||
|
|
ed90d61014 | ||
|
|
d066f1f082 | ||
|
|
b64c36fd40 | ||
|
|
403c690061 | ||
|
|
a4805b3e3d | ||
|
|
5a1352aab0 | ||
|
|
a9cf94aeba | ||
|
|
196132621c | ||
|
|
0098f2e670 | ||
|
|
730c8cad59 | ||
|
|
d9cb9a8fbc | ||
|
|
bbbcf72b81 | ||
|
|
10ad09fe34 | ||
|
|
040aec53b2 | ||
|
|
2bf8611919 | ||
|
|
1d53af5a51 | ||
|
|
3c3319eead | ||
|
|
50dbb5cb5f | ||
|
|
462c2adb2a |
No files matched your search
@@ -154,7 +154,7 @@ jobs:
|
||||
NETCATTY_SSH_TEST_RUNTIME: electron
|
||||
run: node --test electron/bridges/sshChaChaTransport.test.cjs
|
||||
|
||||
- name: Exercise native PowerShell directory navigation in ConPTY
|
||||
- name: Exercise native PowerShell and CMD directory navigation in ConPTY
|
||||
env:
|
||||
NETCATTY_DIRECTORY_WINDOWS_LIVE: "1"
|
||||
run: |
|
||||
|
||||
@@ -100,7 +100,7 @@ Placement rules (`resolveAgentKinds` in `toolSurfaces.cjs`):
|
||||
| Vault bridge | `electron/bridges/aiBridge/vaultAgentBridge.cjs` + `infrastructure/ai/vaultAgentBridgeClient.ts` | Renderer vault state; **never** returns password/privateKey |
|
||||
| AI context | `buildAITerminalSessionInfo` + `useTerminalAiContexts` | Per-session `hostChain` + `activePortForwards`; mirrored in `getContext` and Catty system prompt |
|
||||
|
||||
**Policy:** SFTP writes/transfers, `portforward_start`, and `host_notes_set` require confirm-mode approval. Observer mode blocks writes.
|
||||
**Policy:** SFTP writes/transfers, `portforward_start`, and `host_notes_set` require confirm-mode approval. Observer mode blocks writes. `terminal_execute_bulk` (2–20 sessions, loaded via the `terminal_bulk` toolset) is all-or-nothing before sending and sets `policy.requiresFreshApproval`: remembered grants and external-client session approval never satisfy it. See `docs/features/terminal-execute-bulk.md`.
|
||||
|
||||
**Handles:** `ToolOutputStore` persists across turns per chat session; cleared on chat session delete. Large `sftp.read` results spill to `tool_output_read`.
|
||||
|
||||
|
||||
@@ -1032,3 +1032,108 @@ test('host list shortcut calls the same store toggle as the toolbar button', ()
|
||||
const source = readFileSync(new URL('./app/AppSideEffects.tsx', import.meta.url), 'utf8');
|
||||
assert.match(source, /toggleHostTree:\s*\(\)\s*=>\s*terminalHostTreeStore\.toggle\(\)/);
|
||||
});
|
||||
|
||||
test('Cmd+Shift+T on macOS and Ctrl+Shift+T on PC dispatch reopenClosedTab and stay out of text inputs', () => {
|
||||
for (const [scheme, keyProps] of [
|
||||
['mac', { metaKey: true, ctrlKey: false }],
|
||||
['pc', { metaKey: false, ctrlKey: true }],
|
||||
] as const) {
|
||||
const target = new FakeHTMLElement();
|
||||
const actions: string[] = [];
|
||||
let prevented = false;
|
||||
let stopped = false;
|
||||
|
||||
handleGlobalHotkeyKeyDownImpl(() => ({
|
||||
HOTKEY_DEBUG: false,
|
||||
closeTabKeyStr: '',
|
||||
executeHotkeyAction: (action: string) => {
|
||||
actions.push(action);
|
||||
},
|
||||
hotkeyScheme: scheme,
|
||||
keyBindings: DEFAULT_KEY_BINDINGS,
|
||||
matchesKeyBinding,
|
||||
}), {
|
||||
key: 'T',
|
||||
code: 'KeyT',
|
||||
...keyProps,
|
||||
altKey: false,
|
||||
shiftKey: true,
|
||||
target,
|
||||
composedPath: () => [target],
|
||||
preventDefault: () => { prevented = true; },
|
||||
stopPropagation: () => { stopped = true; },
|
||||
} as unknown as KeyboardEvent);
|
||||
|
||||
assert.deepEqual(actions, ['reopenClosedTab']);
|
||||
assert.equal(prevented, true);
|
||||
assert.equal(stopped, true);
|
||||
|
||||
const input = new FakeInputHTMLElement();
|
||||
const inputActions: string[] = [];
|
||||
handleGlobalHotkeyKeyDownImpl(() => ({
|
||||
HOTKEY_DEBUG: false,
|
||||
closeTabKeyStr: '',
|
||||
executeHotkeyAction: (action: string) => {
|
||||
inputActions.push(action);
|
||||
},
|
||||
hotkeyScheme: scheme,
|
||||
keyBindings: DEFAULT_KEY_BINDINGS,
|
||||
matchesKeyBinding,
|
||||
}), {
|
||||
key: 'T',
|
||||
code: 'KeyT',
|
||||
...keyProps,
|
||||
altKey: false,
|
||||
shiftKey: true,
|
||||
target: input,
|
||||
composedPath: () => [input],
|
||||
preventDefault: () => {},
|
||||
stopPropagation: () => {},
|
||||
} as unknown as KeyboardEvent);
|
||||
|
||||
assert.deepEqual(inputActions, []);
|
||||
}
|
||||
});
|
||||
|
||||
test('executeHotkeyActionImpl reopenClosedTab calls reopenLastClosedTab and records connection logs for reopened workspace panes', () => {
|
||||
const logs: Array<Record<string, unknown>> = [];
|
||||
let receivedHostIds: string[] = [];
|
||||
const hostsById = new Map([
|
||||
['h-1', { id: 'h-1', label: 'Prod', hostname: 'prod.test', username: 'ops', port: 22, os: 'linux', group: '', tags: [] }],
|
||||
]);
|
||||
|
||||
executeHotkeyActionImpl(() => ({
|
||||
activeTabStore: { getActiveTabId: () => 'vault' },
|
||||
addConnectionLogRef: { current: (log: Record<string, unknown>) => logs.push(log) },
|
||||
editorTabs: [],
|
||||
hostsById,
|
||||
orderedTabs: [],
|
||||
reopenLastClosedTab: (opts: { availableHostIds?: ReadonlySet<string> }) => {
|
||||
receivedHostIds = [...(opts.availableHostIds ?? [])];
|
||||
return {
|
||||
kind: 'workspace',
|
||||
tabId: 'ws-new',
|
||||
workspace: { id: 'ws-new', title: 'Prod Split', root: { id: 'p', type: 'pane', sessionId: 's-new-1' } },
|
||||
sessions: [
|
||||
{ id: 's-new-1', hostId: 'h-1', hostLabel: 'Prod', hostname: 'prod.test', username: 'ops', status: 'connecting', protocol: 'ssh', workspaceId: 'ws-new' },
|
||||
{ id: 's-new-2', hostId: 'local-terminal', hostLabel: 'Local Terminal', hostname: 'localhost', username: 'local', status: 'connecting', protocol: 'local', workspaceId: 'ws-new' },
|
||||
],
|
||||
};
|
||||
},
|
||||
sessions: [],
|
||||
settings: {},
|
||||
systemInfoRef: { current: { username: 'dev', hostname: 'laptop' } },
|
||||
toEditorTabId: (id: string) => id,
|
||||
workspaces: [],
|
||||
}), 'reopenClosedTab', {} as KeyboardEvent);
|
||||
|
||||
assert.deepEqual(receivedHostIds, ['h-1']);
|
||||
assert.equal(logs.length, 2);
|
||||
assert.equal(logs[0].sessionId, 's-new-1');
|
||||
assert.equal(logs[0].hostId, 'h-1');
|
||||
assert.equal(logs[0].username, 'ops');
|
||||
assert.equal(logs[1].sessionId, 's-new-2');
|
||||
assert.equal(logs[1].hostId, '');
|
||||
assert.equal(logs[1].username, 'dev');
|
||||
assert.equal(logs[1].protocol, 'local');
|
||||
});
|
||||
@@ -915,7 +915,7 @@ export async function closeTabsBatchImpl(getCtx: AppContextGetter, targetIds: st
|
||||
}
|
||||
|
||||
export function executeHotkeyActionImpl(getCtx: AppContextGetter, action: string, e: KeyboardEvent) {
|
||||
const { IS_DEV, MOVE_FOCUS_DEBOUNCE_MS, activeTabStore, addConnectionLogRef, canUseGlobalBroadcast, closePluginViewTab, closeSession, closeTabInFlightRef, closeWorkspace, collectSessionIds, confirmIfBusyLocalTerminal, createLocalTerminalWithCurrentShell, editorTabs, fromEditorTabId, handleOpenSettingsRef, handleRequestCloseEditorTabRef, isEditorTabId, isPluginViewTabId, isQuickSwitcherOpen, lastMoveFocusTimeRef, moveFocusInWorkspace, orderedTabs, resolveCloseIntent, resolveSnippetsShortcutIntent, sessions, setActiveTabId, setAddToWorkspaceDialog, setIsQuickSwitcherOpen, setNavigateToSection, settings, sftpPaneMagnificationRef, splitSessionWithCurrentShell, systemInfoRef, terminalPaneMagnificationRef, toEditorTabId, toggleBroadcast, toggleGlobalBroadcast, toggleHostTree, toggleScriptsSidePanelRef, toggleSidePanelRef, toggleWindowOpacity, workspaces } = getCtx();
|
||||
const { IS_DEV, MOVE_FOCUS_DEBOUNCE_MS, activeTabStore, addConnectionLogRef, canUseGlobalBroadcast, closePluginViewTab, closeSession, closeTabInFlightRef, closeWorkspace, collectSessionIds, confirmIfBusyLocalTerminal, createLocalTerminalWithCurrentShell, editorTabs, fromEditorTabId, handleOpenSettingsRef, handleRequestCloseEditorTabRef, hostsById, isEditorTabId, isPluginViewTabId, isQuickSwitcherOpen, lastMoveFocusTimeRef, moveFocusInWorkspace, orderedTabs, reopenLastClosedTab, resolveCloseIntent, resolveSnippetsShortcutIntent, sessions, setActiveTabId, setAddToWorkspaceDialog, setIsQuickSwitcherOpen, setNavigateToSection, settings, sftpPaneMagnificationRef, splitSessionWithCurrentShell, systemInfoRef, terminalPaneMagnificationRef, toEditorTabId, toggleBroadcast, toggleGlobalBroadcast, toggleHostTree, toggleScriptsSidePanelRef, toggleSidePanelRef, toggleWindowOpacity, workspaces } = getCtx();
|
||||
{
|
||||
const shortcutTabs = buildNumberShortcutTabTargets({
|
||||
showSftpTab: settings.showSftpTab ?? true,
|
||||
@@ -1061,6 +1061,39 @@ export function executeHotkeyActionImpl(getCtx: AppContextGetter, action: string
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'reopenClosedTab': {
|
||||
const reopened = reopenLastClosedTab?.({
|
||||
availableHostIds: hostsById ? new Set(hostsById.keys()) : undefined,
|
||||
hostsById,
|
||||
});
|
||||
if (reopened && addConnectionLogRef?.current) {
|
||||
const reopenedSessions = reopened.kind === 'session'
|
||||
? [reopened.session]
|
||||
: reopened.sessions;
|
||||
const localUsername = systemInfoRef?.current?.username ?? '';
|
||||
const localHostname = systemInfoRef?.current?.hostname ?? '';
|
||||
const startTime = Date.now();
|
||||
for (const reopenedSession of reopenedSessions) {
|
||||
addConnectionLogRef.current({
|
||||
sessionId: reopenedSession.id,
|
||||
hostId: reopenedSession.protocol === 'local' && reopenedSession.hostId === 'local-terminal'
|
||||
? ''
|
||||
: reopenedSession.hostId,
|
||||
hostLabel: reopenedSession.hostLabel,
|
||||
hostname: reopenedSession.hostname,
|
||||
username: reopenedSession.protocol === 'local'
|
||||
? localUsername
|
||||
: reopenedSession.username,
|
||||
protocol: reopenedSession.protocol || 'ssh',
|
||||
startTime,
|
||||
localUsername,
|
||||
localHostname,
|
||||
saved: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'openHosts':
|
||||
setActiveTabId('vault');
|
||||
break;
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import React, { memo, useMemo } from 'react';
|
||||
import React, { memo, useMemo, useRef } from 'react';
|
||||
|
||||
import { useActiveTabId } from '../state/activeTabStore';
|
||||
import { useAppearanceChromeStore } from '../state/appearanceChromeStore';
|
||||
import type { EditorTabChrome } from '../state/editorTabStore';
|
||||
import type { LogView } from '../state/logViewState';
|
||||
import { useTerminalHostTreeOpen } from '../state/terminalHostTreeStore';
|
||||
import { useManualTerminalChromeSurfaceInjection } from '../state/useManualTerminalChromeSurfaceInjection';
|
||||
import { TerminalHostTreeSidebar } from '../../components/terminalLayer/TerminalHostTreeSidebar';
|
||||
import type {
|
||||
@@ -93,6 +94,7 @@ const AppHostTreeLayerInner: React.FC<AppHostTreeLayerProps> = ({
|
||||
onCreateLocalTerminal,
|
||||
}) => {
|
||||
const activeTabId = useActiveTabId();
|
||||
const isHostTreeOpen = useTerminalHostTreeOpen();
|
||||
const { accentMode, customAccent } = useAppearanceChromeStore();
|
||||
const sessionIds = useMemo(() => new Set(sessions.map((session) => session.id)), [sessions]);
|
||||
const workspaceIds = useMemo(() => new Set(workspaces.map((workspace) => workspace.id)), [workspaces]);
|
||||
@@ -113,13 +115,18 @@ const AppHostTreeLayerInner: React.FC<AppHostTreeLayerProps> = ({
|
||||
sessionIds,
|
||||
workspaceIds,
|
||||
});
|
||||
const sidebarActive = surfaceVisible && enabled && isHostTreeOpen;
|
||||
|
||||
const activeHostId = useMemo(() => resolveWorkTabActiveHostId({
|
||||
activeTabId,
|
||||
editorTabs,
|
||||
sessions,
|
||||
workspaces,
|
||||
}), [activeTabId, editorTabs, sessions, workspaces]);
|
||||
const activeHostId = useMemo(() => (
|
||||
sidebarActive
|
||||
? resolveWorkTabActiveHostId({
|
||||
activeTabId,
|
||||
editorTabs,
|
||||
sessions,
|
||||
workspaces,
|
||||
})
|
||||
: undefined
|
||||
), [activeTabId, editorTabs, sessions, sidebarActive, workspaces]);
|
||||
|
||||
const hostTreeTheme = useMemo(() => (
|
||||
resolveActiveChromeTheme({
|
||||
@@ -150,6 +157,13 @@ const AppHostTreeLayerInner: React.FC<AppHostTreeLayerProps> = ({
|
||||
themeById,
|
||||
workspaceById,
|
||||
]);
|
||||
const lastActiveSidebarThemeRef = useRef(hostTreeTheme);
|
||||
if (sidebarActive) {
|
||||
lastActiveSidebarThemeRef.current = hostTreeTheme;
|
||||
}
|
||||
const sidebarPreviewTheme = sidebarActive
|
||||
? hostTreeTheme
|
||||
: lastActiveSidebarThemeRef.current;
|
||||
|
||||
useManualTerminalChromeSurfaceInjection(
|
||||
hostTreeTheme,
|
||||
@@ -168,7 +182,7 @@ const AppHostTreeLayerInner: React.FC<AppHostTreeLayerProps> = ({
|
||||
hosts={hosts}
|
||||
customGroups={customGroups}
|
||||
groupConfigs={groupConfigs}
|
||||
resolvedPreviewTheme={hostTreeTheme}
|
||||
resolvedPreviewTheme={sidebarPreviewTheme}
|
||||
activeHostId={activeHostId}
|
||||
onConnect={onConnect}
|
||||
onNewHost={onNewHost}
|
||||
|
||||
@@ -22,6 +22,10 @@ test('visible log view leaves room for the terminal host sidebar', () => {
|
||||
assert.deepEqual(getLogViewWrapperStyle(true, 220), {
|
||||
left: 220,
|
||||
});
|
||||
assert.deepEqual(getLogViewWrapperStyle(true, 220, true), {
|
||||
left: 220,
|
||||
transition: 'left 220ms cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
});
|
||||
});
|
||||
|
||||
test('hidden log view remains hidden while preserving host sidebar offset', () => {
|
||||
@@ -76,3 +80,10 @@ test('terminal layer force-mounts immediately when a hidden MCP session exists',
|
||||
assert.match(appMountsSource, /useState\(isVisible \|\| hasHiddenSession\)/);
|
||||
assert.match(appMountsSource, /if \(isVisible \|\| hasHiddenSession\) setShouldMount\(true\)/);
|
||||
});
|
||||
|
||||
test('AppMounts narrows active-tab subscriptions instead of using useActiveTabId', () => {
|
||||
assert.doesNotMatch(appMountsSource, /\buseActiveTabId\b/);
|
||||
assert.match(appMountsSource, /const isVisible = useIsTabActive\(logView\.id\);/);
|
||||
assert.match(appMountsSource, /const isTerminalSurfaceActive = useIsTerminalSurfaceActive\(sessionIds, workspaceIds\);/);
|
||||
assert.match(appMountsSource, /<LazyLoadBoundary name="Terminal" resetKey=\{isVisible \? "active" : "idle"\}>/);
|
||||
});
|
||||
@@ -1,6 +1,10 @@
|
||||
import React, { Suspense, lazy, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useActiveTabId, useIsSftpActive, useIsVaultActive } from '../state/activeTabStore';
|
||||
import { useTerminalHostTreeLayoutWidth } from '../state/terminalHostTreeStore';
|
||||
import React, { Suspense, lazy, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
|
||||
import { activeTabStore, useIsSftpActive, useIsTabActive, useIsVaultActive } from '../state/activeTabStore';
|
||||
import {
|
||||
useTerminalHostTreeLayoutTransitionAnimated,
|
||||
useTerminalHostTreeLayoutWidth,
|
||||
} from '../state/terminalHostTreeStore';
|
||||
import { TERMINAL_HOST_TREE_LEFT_TRANSITION } from '../state/terminalHostTreeAnimation';
|
||||
import { isTerminalContentTabSurface } from './workTabSurface';
|
||||
import { cn } from '../../lib/utils';
|
||||
import { ConnectionLog, TerminalTheme } from '../../types';
|
||||
@@ -68,9 +72,11 @@ interface LogViewWrapperProps {
|
||||
export function getLogViewWrapperStyle(
|
||||
isVisible: boolean,
|
||||
hostTreeLayoutWidth: number,
|
||||
animateLayout = false,
|
||||
): React.CSSProperties {
|
||||
const baseStyle = {
|
||||
const baseStyle: React.CSSProperties = {
|
||||
left: hostTreeLayoutWidth,
|
||||
...(animateLayout ? { transition: TERMINAL_HOST_TREE_LEFT_TRANSITION } : null),
|
||||
};
|
||||
return isVisible
|
||||
? baseStyle
|
||||
@@ -78,11 +84,15 @@ export function getLogViewWrapperStyle(
|
||||
}
|
||||
|
||||
export const LogViewWrapper: React.FC<LogViewWrapperProps> = ({ logView, defaultTerminalTheme, defaultFontSize, onClose, onUpdateLog }) => {
|
||||
const activeTabId = useActiveTabId();
|
||||
const isVisible = activeTabId === logView.id;
|
||||
const isVisible = useIsTabActive(logView.id);
|
||||
const hostTreeLayoutWidth = useTerminalHostTreeLayoutWidth();
|
||||
const hostTreeLayoutAnimated = useTerminalHostTreeLayoutTransitionAnimated();
|
||||
|
||||
const containerStyle = getLogViewWrapperStyle(isVisible, hostTreeLayoutWidth);
|
||||
const containerStyle = getLogViewWrapperStyle(
|
||||
isVisible,
|
||||
hostTreeLayoutWidth,
|
||||
isVisible && hostTreeLayoutAnimated,
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -163,15 +173,27 @@ export const SftpViewMount: React.FC<SftpViewProps> = (props) => {
|
||||
);
|
||||
};
|
||||
|
||||
export function useIsTerminalSurfaceActive(
|
||||
sessionIds: ReadonlySet<string>,
|
||||
workspaceIds: ReadonlySet<string>,
|
||||
): boolean {
|
||||
const getSnapshot = useCallback(
|
||||
() =>
|
||||
isTerminalContentTabSurface({
|
||||
activeTabId: activeTabStore.getActiveTabId(),
|
||||
sessionIds,
|
||||
workspaceIds,
|
||||
}),
|
||||
[sessionIds, workspaceIds],
|
||||
);
|
||||
return useSyncExternalStore(activeTabStore.subscribe, getSnapshot, getSnapshot);
|
||||
}
|
||||
|
||||
export const TerminalLayerMount: React.FC<TerminalLayerProps> = (props) => {
|
||||
const activeTabId = useActiveTabId();
|
||||
const sessionIds = useMemo(() => new Set(props.sessions.map((session) => session.id)), [props.sessions]);
|
||||
const workspaceIds = useMemo(() => new Set(props.workspaces.map((workspace) => workspace.id)), [props.workspaces]);
|
||||
const isVisible = isTerminalContentTabSurface({
|
||||
activeTabId,
|
||||
sessionIds,
|
||||
workspaceIds,
|
||||
}) || !!props.draggingSessionId;
|
||||
const isTerminalSurfaceActive = useIsTerminalSurfaceActive(sessionIds, workspaceIds);
|
||||
const isVisible = isTerminalSurfaceActive || !!props.draggingSessionId;
|
||||
// Silent MCP sessions never become the activeTabId, so `isVisible` alone
|
||||
// would leave this whole layer (and its PTY-starting TerminalPane) unmounted
|
||||
// for up to 5s (the idle-callback fallback below) after host_open returns —
|
||||
@@ -203,7 +225,7 @@ export const TerminalLayerMount: React.FC<TerminalLayerProps> = (props) => {
|
||||
if (!shouldRender) return null;
|
||||
|
||||
return (
|
||||
<LazyLoadBoundary name="Terminal" resetKey={activeTabId}>
|
||||
<LazyLoadBoundary name="Terminal" resetKey={isVisible ? "active" : "idle"}>
|
||||
<Suspense fallback={<TerminalLayerFallback visible={isVisible} />}>
|
||||
<LazyTerminalLayer {...props} />
|
||||
</Suspense>
|
||||
|
||||
@@ -264,6 +264,7 @@ export function AppSideEffects() {
|
||||
closeSession,
|
||||
closeSessions,
|
||||
closeWorkspace,
|
||||
reopenLastClosedTab,
|
||||
updateSessionStatus,
|
||||
createWorkspaceWithHosts,
|
||||
createWorkspaceFromTargets,
|
||||
@@ -293,6 +294,8 @@ export function AppSideEffects() {
|
||||
() => new Map(hosts.map((host) => [host.id, host])),
|
||||
[hosts],
|
||||
);
|
||||
const hostByIdRef = useRef(hostById);
|
||||
hostByIdRef.current = hostById;
|
||||
const terminalHosts = useMemo(
|
||||
() => (ephemeralHosts.length > 0 ? [...hosts, ...ephemeralHosts] : hosts),
|
||||
[hosts, ephemeralHosts],
|
||||
@@ -1128,12 +1131,14 @@ export function AppSideEffects() {
|
||||
fromEditorTabId,
|
||||
handleOpenSettingsRef,
|
||||
handleRequestCloseEditorTabRef,
|
||||
hostsById: hostByIdRef.current,
|
||||
isEditorTabId,
|
||||
isPluginViewTabId,
|
||||
isQuickSwitcherOpen: isQuickSwitcherOpenRef.current,
|
||||
lastMoveFocusTimeRef,
|
||||
moveFocusInWorkspace,
|
||||
orderedTabs: orderedTabsRef.current,
|
||||
reopenLastClosedTab,
|
||||
resolveCloseIntent,
|
||||
resolveSnippetsShortcutIntent,
|
||||
sessions: sessionsRef.current,
|
||||
@@ -1165,6 +1170,7 @@ export function AppSideEffects() {
|
||||
closePluginViewTab,
|
||||
closeSession,
|
||||
closeWorkspace,
|
||||
reopenLastClosedTab,
|
||||
createLocalTerminalWithCurrentShell,
|
||||
splitSessionWithCurrentShell,
|
||||
moveFocusInWorkspace,
|
||||
|
||||
@@ -5,7 +5,11 @@ import { activeTabStore, toEditorTabId, useIsEditorTabActive } from '../state/ac
|
||||
import { editorTabStore, tabIsDirty } from '../state/editorTabStore';
|
||||
import { releaseEditorTabSaveCoordinator, saveEditorTab } from '../state/editorTabSave';
|
||||
import { focusEditorInWindow, popOutEditorTab } from '../state/editorWindowClient';
|
||||
import { useTerminalHostTreeLayoutWidth } from '../state/terminalHostTreeStore';
|
||||
import {
|
||||
useTerminalHostTreeLayoutTransitionAnimated,
|
||||
useTerminalHostTreeLayoutWidth,
|
||||
} from '../state/terminalHostTreeStore';
|
||||
import { TERMINAL_HOST_TREE_LEFT_TRANSITION } from '../state/terminalHostTreeAnimation';
|
||||
import { TopTabs } from '../../components/TopTabs';
|
||||
import { VaultView } from '../../components/VaultView';
|
||||
import { QuickAddSnippetDialog } from '../../components/QuickAddSnippetDialog';
|
||||
@@ -67,12 +71,16 @@ const focusEditorWindowTab = (id: string) => { void focusEditorInWindow(id); };
|
||||
const TextEditorTabFallback = ({ tabId }: { tabId: string }) => {
|
||||
const isVisible = useIsEditorTabActive(tabId);
|
||||
const hostTreeLayoutWidth = useTerminalHostTreeLayoutWidth();
|
||||
const hostTreeLayoutAnimated = useTerminalHostTreeLayoutTransitionAnimated();
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
...(isVisible ? null : { pointerEvents: 'none', visibility: 'hidden' }),
|
||||
zIndex: 20,
|
||||
left: hostTreeLayoutWidth,
|
||||
...(isVisible && hostTreeLayoutAnimated
|
||||
? { transition: TERMINAL_HOST_TREE_LEFT_TRANSITION }
|
||||
: null),
|
||||
}}
|
||||
className="netcatty-lazy-fade-in absolute top-0 right-0 bottom-0 min-h-0 flex flex-col bg-background"
|
||||
aria-hidden="true"
|
||||
|
||||
@@ -0,0 +1,760 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import type { Host, TerminalSession, Workspace } from '../../types';
|
||||
|
||||
function setupDom() {
|
||||
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>();
|
||||
const install = (key: string, value: unknown) => {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
};
|
||||
for (const key of [
|
||||
'window',
|
||||
'document',
|
||||
'navigator',
|
||||
'HTMLElement',
|
||||
'Element',
|
||||
'Node',
|
||||
'MutationObserver',
|
||||
'CustomEvent',
|
||||
'Event',
|
||||
'DOMException',
|
||||
]) {
|
||||
install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
|
||||
}
|
||||
install('localStorage', dom.window.localStorage);
|
||||
install('getComputedStyle', dom.window.getComputedStyle.bind(dom.window));
|
||||
install('requestAnimationFrame', (cb: FrameRequestCallback) => setTimeout(() => cb(Date.now()), 0) as unknown as number);
|
||||
install('cancelAnimationFrame', (id: number) => clearTimeout(id));
|
||||
install(
|
||||
'ResizeObserver',
|
||||
class ResizeObserver {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
},
|
||||
);
|
||||
install('IS_REACT_ACT_ENVIRONMENT', true);
|
||||
|
||||
return {
|
||||
dom,
|
||||
cleanup() {
|
||||
dom.window.close();
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) {
|
||||
Object.defineProperty(globalThis, key, descriptor);
|
||||
} else {
|
||||
Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const flushTabStore = () => new Promise<void>((resolve) => setTimeout(resolve, 25));
|
||||
|
||||
async function waitForAct(
|
||||
act: (fn: () => Promise<void>) => Promise<void>,
|
||||
condition: () => boolean,
|
||||
timeoutMs = 3000,
|
||||
) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (!condition()) {
|
||||
if (Date.now() >= deadline) {
|
||||
throw new Error('Timed out waiting for condition');
|
||||
}
|
||||
await act(async () => {
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 15));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const makeSession = (id: string, hostId: string): TerminalSession => ({
|
||||
id,
|
||||
hostId,
|
||||
hostLabel: `host-${hostId}`,
|
||||
username: 'root',
|
||||
hostname: `${hostId}.example.com`,
|
||||
status: 'connected',
|
||||
});
|
||||
|
||||
const makeWorkspace = (id: string, sessionId: string): Workspace => ({
|
||||
id,
|
||||
title: `Workspace ${id}`,
|
||||
focusedSessionId: sessionId,
|
||||
root: { id: `pane-${id}`, type: 'pane', sessionId },
|
||||
});
|
||||
|
||||
const makeHost = (id: string): Host => ({
|
||||
id,
|
||||
label: `host-${id}`,
|
||||
hostname: `${id}.example.com`,
|
||||
port: 22,
|
||||
username: 'root',
|
||||
authMethod: 'password',
|
||||
tags: [],
|
||||
os: 'linux',
|
||||
});
|
||||
|
||||
test('usePluginVaultPages does not re-render on non-vault tab switches while preserving active state', async () => {
|
||||
const env = setupDom();
|
||||
const { act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { activeTabStore } = await import('../state/activeTabStore');
|
||||
const { usePluginVaultPages } = await import('../state/usePluginVaultPages');
|
||||
|
||||
const previousTabId = activeTabStore.getActiveTabId();
|
||||
Object.assign(env.dom.window, {
|
||||
netcatty: {
|
||||
async getPluginRuntimeStatus() {
|
||||
return { available: true };
|
||||
},
|
||||
async getPluginContributions() {
|
||||
return { locale: 'en', plugins: [] };
|
||||
},
|
||||
onPluginContributionsChanged() {
|
||||
return () => {};
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
let renders = 0;
|
||||
let lastActive: boolean | null = null;
|
||||
const select = () => {};
|
||||
|
||||
function Harness() {
|
||||
renders += 1;
|
||||
const model = usePluginVaultPages({ locale: 'en', section: 'hosts', select });
|
||||
lastActive = model.active;
|
||||
return <div data-active={String(model.active)} />;
|
||||
}
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
try {
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
|
||||
await act(async () => {
|
||||
root.render(<Harness />);
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(lastActive, false);
|
||||
const settledRenders = renders;
|
||||
|
||||
// Switching between terminal tabs and other non-vault tabs must cause 0 re-renders.
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-2');
|
||||
await flushTabStore();
|
||||
});
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('workspace-1');
|
||||
await flushTabStore();
|
||||
});
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('sftp');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(renders, settledRenders);
|
||||
assert.equal(lastActive, false);
|
||||
|
||||
// Switching to vault flips active to true with exactly 1 render.
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(renders, settledRenders + 1);
|
||||
assert.equal(lastActive, true);
|
||||
|
||||
// Switching back to a terminal tab flips active back to false.
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(renders, settledRenders + 2);
|
||||
assert.equal(lastActive, false);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
await flushTabStore();
|
||||
});
|
||||
activeTabStore.setActiveTabId(previousTabId, { recordPrevious: false });
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('useShowHostTreeToggle and TopTabs avoid re-renders when switching between two terminal tabs', async () => {
|
||||
const env = setupDom();
|
||||
const { act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { activeTabStore } = await import('../state/activeTabStore');
|
||||
const { TopTabs, useShowHostTreeToggle } = await import('../../components/TopTabs');
|
||||
const { I18nProvider } = await import('../i18n/I18nProvider');
|
||||
const { TooltipProvider } = await import('../../components/ui/tooltip');
|
||||
|
||||
const previousTabId = activeTabStore.getActiveTabId();
|
||||
const session1 = makeSession('session-1', 'h1');
|
||||
const session2 = makeSession('session-2', 'h2');
|
||||
const workspace1 = makeWorkspace('workspace-1', 'session-1');
|
||||
const hosts = [makeHost('h1'), makeHost('h2')];
|
||||
const hostById = new Map(hosts.map((h) => [h.id, h]));
|
||||
const sessions = [session1, session2];
|
||||
const orphanSessions = [session1, session2];
|
||||
const workspaces = [workspace1];
|
||||
const logViews: never[] = [];
|
||||
const orderedTabs = ['session-1', 'session-2', 'workspace-1'];
|
||||
const editorTabs: never[] = [];
|
||||
const pluginViewTabs: never[] = [];
|
||||
const sessionIds = new Set(['session-1', 'session-2']);
|
||||
const workspaceIds = new Set(['workspace-1']);
|
||||
const logViewIds = new Set(['log-1']);
|
||||
|
||||
let selectorRenders = 0;
|
||||
let lastVisible: boolean | null = null;
|
||||
function SelectorHarness({ enabled }: { enabled: boolean }) {
|
||||
selectorRenders += 1;
|
||||
lastVisible = useShowHostTreeToggle({
|
||||
enabled,
|
||||
logViewIds,
|
||||
orderedTabs,
|
||||
sessionIds,
|
||||
workspaceIds,
|
||||
});
|
||||
return <div data-show={String(lastVisible)} />;
|
||||
}
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
try {
|
||||
// 1. Direct selector test across all tab transitions
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
|
||||
await act(async () => {
|
||||
root.render(<SelectorHarness enabled={true} />);
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(lastVisible, true);
|
||||
const rendersAfterMount = selectorRenders;
|
||||
|
||||
for (const nextTab of ['session-2', 'workspace-1', 'log-1', 'editor:file-1', 'session-1']) {
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId(nextTab);
|
||||
await flushTabStore();
|
||||
});
|
||||
}
|
||||
assert.equal(selectorRenders, rendersAfterMount);
|
||||
assert.equal(lastVisible, true);
|
||||
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(selectorRenders, rendersAfterMount + 1);
|
||||
assert.equal(lastVisible, false);
|
||||
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('sftp');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(selectorRenders, rendersAfterMount + 1);
|
||||
assert.equal(lastVisible, false);
|
||||
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-2');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(selectorRenders, rendersAfterMount + 2);
|
||||
assert.equal(lastVisible, true);
|
||||
|
||||
// Disabled host tree never re-renders on tab switches
|
||||
await act(async () => {
|
||||
root.render(<SelectorHarness enabled={false} />);
|
||||
await flushTabStore();
|
||||
});
|
||||
const rendersWhenDisabled = selectorRenders;
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
await flushTabStore();
|
||||
});
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(selectorRenders, rendersWhenDisabled);
|
||||
assert.equal(lastVisible, false);
|
||||
|
||||
// 2. Full TopTabs mount: verify host-tree toggle stays visible across session-1 -> session-2
|
||||
// and hides when switching to vault.
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>
|
||||
<TopTabs
|
||||
theme="dark"
|
||||
themePreference="dark"
|
||||
hosts={hosts}
|
||||
sessions={sessions}
|
||||
orphanSessions={orphanSessions}
|
||||
workspaces={workspaces}
|
||||
logViews={logViews}
|
||||
orderedTabs={orderedTabs}
|
||||
draggingSessionId={null}
|
||||
isMacClient={false}
|
||||
onCloseSession={noop}
|
||||
onRenameSession={noop}
|
||||
onCopySession={noop}
|
||||
onCopySessionToNewWindow={noop}
|
||||
onRenameWorkspace={noop}
|
||||
onCopyWorkspace={noop}
|
||||
onCloseWorkspace={noop}
|
||||
onCloseLogView={noop}
|
||||
onCloseTabsBatch={noop}
|
||||
onOpenQuickSwitcher={noop}
|
||||
onThemeChange={noop}
|
||||
onOpenSettings={noop}
|
||||
externalMcpEnabled={false}
|
||||
onToggleExternalMcp={noop}
|
||||
windowOpacity={1}
|
||||
setWindowOpacity={noop}
|
||||
onStartSessionDrag={noop}
|
||||
onEndSessionDrag={noop}
|
||||
onReorderTabs={noop}
|
||||
onRemoveSessionFromWorkspace={noop}
|
||||
showSftpTab={true}
|
||||
showHostTreeSidebar={true}
|
||||
switchTabKeyBinding={null}
|
||||
tabDoubleClickBehavior="copy"
|
||||
editorTabs={editorTabs}
|
||||
pluginViewTabs={pluginViewTabs}
|
||||
onClosePluginViewTab={noop}
|
||||
onRequestCloseEditorTab={noop}
|
||||
hostById={hostById}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
await waitForAct(
|
||||
act,
|
||||
() =>
|
||||
document
|
||||
.querySelector('[data-section="top-tabs-host-tree-toggle"]')
|
||||
?.getAttribute('data-visible') === 'true',
|
||||
);
|
||||
const hostTreeToggleSlot = document.querySelector('[data-section="top-tabs-host-tree-toggle"]')!;
|
||||
assert.equal(hostTreeToggleSlot.getAttribute('data-visible'), 'true');
|
||||
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-2');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(hostTreeToggleSlot.getAttribute('data-visible'), 'true');
|
||||
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
await flushTabStore();
|
||||
});
|
||||
await waitForAct(
|
||||
act,
|
||||
() => hostTreeToggleSlot.getAttribute('data-visible') === 'false',
|
||||
);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
await flushTabStore();
|
||||
});
|
||||
activeTabStore.setActiveTabId(previousTabId, { recordPrevious: false });
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('LogViewWrapper does not re-render on unrelated tab switches', async () => {
|
||||
const env = setupDom();
|
||||
const { Profiler, act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { activeTabStore } = await import('../state/activeTabStore');
|
||||
const { LogViewWrapper } = await import('./AppMounts');
|
||||
|
||||
const previousTabId = activeTabStore.getActiveTabId();
|
||||
const logView = {
|
||||
id: 'log-view-1',
|
||||
connectionLogId: 'log-1',
|
||||
log: {
|
||||
id: 'log-1',
|
||||
hostId: 'host-1',
|
||||
hostLabel: 'Prod',
|
||||
hostname: 'prod.example.com',
|
||||
username: 'root',
|
||||
protocol: 'ssh' as const,
|
||||
startTime: 1,
|
||||
localUsername: 'local',
|
||||
localHostname: 'localhost',
|
||||
saved: false,
|
||||
terminalData: '',
|
||||
},
|
||||
};
|
||||
const defaultTerminalTheme = {
|
||||
id: 'default',
|
||||
name: 'Default',
|
||||
type: 'dark' as const,
|
||||
colors: {
|
||||
background: '#000000',
|
||||
foreground: '#ffffff',
|
||||
cursor: '#ffffff',
|
||||
selection: '#444444',
|
||||
black: '#000000',
|
||||
red: '#ff0000',
|
||||
green: '#00ff00',
|
||||
yellow: '#ffff00',
|
||||
blue: '#0000ff',
|
||||
magenta: '#ff00ff',
|
||||
cyan: '#00ffff',
|
||||
white: '#ffffff',
|
||||
brightBlack: '#888888',
|
||||
brightRed: '#ff8888',
|
||||
brightGreen: '#88ff88',
|
||||
brightYellow: '#ffff88',
|
||||
brightBlue: '#8888ff',
|
||||
brightMagenta: '#ff88ff',
|
||||
brightCyan: '#88ffff',
|
||||
brightWhite: '#ffffff',
|
||||
},
|
||||
};
|
||||
|
||||
let commitCount = 0;
|
||||
const onRender = () => {
|
||||
commitCount += 1;
|
||||
};
|
||||
const onClose = () => {};
|
||||
const onUpdateLog = () => {};
|
||||
|
||||
const originalConsoleError = console.error;
|
||||
// LazyLogView imports @xterm/xterm/css/xterm.css which is unsupported under Node ESM
|
||||
// and settles into LazyLoadBoundary's alert fallback; silence that expected boundary log.
|
||||
console.error = () => {};
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
try {
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<Profiler id="log-view-wrapper" onRender={onRender}>
|
||||
<LogViewWrapper
|
||||
logView={logView}
|
||||
defaultTerminalTheme={defaultTerminalTheme}
|
||||
defaultFontSize={14}
|
||||
onClose={onClose}
|
||||
onUpdateLog={onUpdateLog}
|
||||
/>
|
||||
</Profiler>,
|
||||
);
|
||||
});
|
||||
await waitForAct(act, () => document.querySelector('[role="alert"]') !== null);
|
||||
|
||||
const commitsAfterMount = commitCount;
|
||||
const container = document.getElementById('root')!.firstElementChild as HTMLElement;
|
||||
assert.equal(container.getAttribute('data-inactive-app-surface'), 'true');
|
||||
|
||||
// Switching between two terminal tabs and vault must cause 0 re-renders of LogViewWrapper.
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-2');
|
||||
await flushTabStore();
|
||||
});
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(commitCount, commitsAfterMount);
|
||||
assert.equal(container.getAttribute('data-inactive-app-surface'), 'true');
|
||||
|
||||
// Activating this log view re-renders it and reveals the surface.
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId(logView.id);
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(commitCount, commitsAfterMount + 1);
|
||||
assert.equal(container.getAttribute('data-inactive-app-surface'), null);
|
||||
|
||||
// Leaving this log view hides it again.
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(commitCount, commitsAfterMount + 2);
|
||||
assert.equal(container.getAttribute('data-inactive-app-surface'), 'true');
|
||||
} finally {
|
||||
console.error = originalConsoleError;
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
await flushTabStore();
|
||||
});
|
||||
activeTabStore.setActiveTabId(previousTabId, { recordPrevious: false });
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('useIsTerminalSurfaceActive and TerminalLayerMount avoid re-renders on terminal-to-terminal switches', async () => {
|
||||
const env = setupDom();
|
||||
const { Profiler, act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { activeTabStore } = await import('../state/activeTabStore');
|
||||
const { TerminalLayerMount, useIsTerminalSurfaceActive } = await import('./AppMounts');
|
||||
|
||||
const previousTabId = activeTabStore.getActiveTabId();
|
||||
const sessions = [makeSession('session-1', 'h1'), makeSession('session-2', 'h2')];
|
||||
const workspaces = [makeWorkspace('workspace-1', 'session-1')];
|
||||
const sessionIds = new Set(['session-1', 'session-2']);
|
||||
const workspaceIds = new Set(['workspace-1']);
|
||||
|
||||
let renders = 0;
|
||||
let lastActive: boolean | null = null;
|
||||
|
||||
function Harness() {
|
||||
renders += 1;
|
||||
lastActive = useIsTerminalSurfaceActive(sessionIds, workspaceIds);
|
||||
return <div data-terminal-active={String(lastActive)} />;
|
||||
}
|
||||
|
||||
const originalConsoleError = console.error;
|
||||
console.error = () => {};
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
try {
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
|
||||
await act(async () => {
|
||||
root.render(<Harness />);
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(lastActive, true);
|
||||
const rendersAfterMount = renders;
|
||||
|
||||
// Switching between two terminal sessions and a workspace keeps surface active -> 0 re-renders.
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-2');
|
||||
await flushTabStore();
|
||||
});
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('workspace-1');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(renders, rendersAfterMount);
|
||||
assert.equal(lastActive, true);
|
||||
|
||||
// Switching to vault flips active true -> false (1 re-render).
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(renders, rendersAfterMount + 1);
|
||||
assert.equal(lastActive, false);
|
||||
|
||||
// Switching vault -> sftp -> log view keeps surface inactive -> 0 re-renders.
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('sftp');
|
||||
await flushTabStore();
|
||||
});
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('log-1');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(renders, rendersAfterMount + 1);
|
||||
assert.equal(lastActive, false);
|
||||
|
||||
// Returning to a terminal tab flips false -> true (1 re-render).
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-2');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(renders, rendersAfterMount + 2);
|
||||
assert.equal(lastActive, true);
|
||||
|
||||
// Verify TerminalLayerMount itself does not re-render on session-1 -> session-2 -> workspace-1
|
||||
let mountCommits = 0;
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<Profiler
|
||||
id="terminal-layer-mount"
|
||||
onRender={() => {
|
||||
mountCommits += 1;
|
||||
}}
|
||||
>
|
||||
<TerminalLayerMount
|
||||
{...({
|
||||
sessions,
|
||||
workspaces,
|
||||
draggingSessionId: null,
|
||||
} as unknown as ComponentProps<typeof TerminalLayerMount>)}
|
||||
/>
|
||||
</Profiler>,
|
||||
);
|
||||
});
|
||||
await waitForAct(act, () => document.querySelector('[role="alert"]') !== null);
|
||||
|
||||
const commitsAfterTerminalMount = mountCommits;
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-2');
|
||||
await flushTabStore();
|
||||
});
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('workspace-1');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(mountCommits, commitsAfterTerminalMount);
|
||||
|
||||
// Switching away to vault flips isVisible (and LazyLoadBoundary resetKey) and triggers a re-render.
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.ok(mountCommits > commitsAfterTerminalMount);
|
||||
} finally {
|
||||
console.error = originalConsoleError;
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
await flushTabStore();
|
||||
});
|
||||
activeTabStore.setActiveTabId(previousTabId, { recordPrevious: false });
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('usePluginAIContextHost does not re-render on tab switches and reads live activeTabId on demand', async () => {
|
||||
const env = setupDom();
|
||||
const { act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { activeTabStore } = await import('../state/activeTabStore');
|
||||
const { usePluginAIContextHost } = await import('../state/usePluginAIContextHost');
|
||||
const { registerAppAppLockRuntime, getAppAppLockRuntime } = await import('../state/appRuntimeBridge');
|
||||
|
||||
const previousTabId = activeTabStore.getActiveTabId();
|
||||
const oldLock = getAppAppLockRuntime();
|
||||
registerAppAppLockRuntime({ locked: false } as NonNullable<ReturnType<typeof getAppAppLockRuntime>>);
|
||||
|
||||
const sessions = [makeSession('session-1', 'h1'), makeSession('session-2', 'h2')];
|
||||
const workspaces = [makeWorkspace('workspace-1', 'session-1')];
|
||||
|
||||
let requestHandler: ((req: {
|
||||
kind: string;
|
||||
requestId: string;
|
||||
runtimeId: string;
|
||||
actionToken: string;
|
||||
payload: Record<string, unknown>;
|
||||
}) => void) | null = null;
|
||||
const responses: Array<{ requestId: string; result?: unknown; error?: boolean }> = [];
|
||||
|
||||
Object.assign(env.dom.window, {
|
||||
netcatty: {
|
||||
onPluginAIHostRequest(handler: typeof requestHandler) {
|
||||
requestHandler = handler;
|
||||
return () => {
|
||||
requestHandler = null;
|
||||
};
|
||||
},
|
||||
async setPluginAIHostReady() {},
|
||||
async respondPluginAIHost(payload: { requestId: string; result?: unknown; error?: boolean }) {
|
||||
responses.push(payload);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
let renders = 0;
|
||||
let latestChoice: ReturnType<typeof usePluginAIContextHost>['choice'] = null;
|
||||
function Harness() {
|
||||
renders += 1;
|
||||
const host = usePluginAIContextHost({ sessions, workspaces });
|
||||
latestChoice = host.choice;
|
||||
return <div data-testid="ai-context-host" />;
|
||||
}
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
try {
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
|
||||
await act(async () => {
|
||||
root.render(<Harness />);
|
||||
await flushTabStore();
|
||||
});
|
||||
const rendersAfterMount = renders;
|
||||
|
||||
// Switching across any tabs must cause 0 re-renders.
|
||||
for (const nextTab of ['session-2', 'workspace-1', 'vault', 'sftp', 'session-2']) {
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId(nextTab);
|
||||
await flushTabStore();
|
||||
});
|
||||
}
|
||||
assert.equal(renders, rendersAfterMount);
|
||||
|
||||
// Triggering selection on demand without re-rendering must read live activeTabId ('session-2').
|
||||
assert.ok(requestHandler, 'expected plugin AI host request listener to be registered');
|
||||
await act(async () => {
|
||||
requestHandler!({
|
||||
kind: 'context.select',
|
||||
requestId: 'req-1',
|
||||
runtimeId: 'rt-1',
|
||||
actionToken: 'tok-1',
|
||||
payload: {},
|
||||
});
|
||||
});
|
||||
await waitForAct(act, () => latestChoice !== null);
|
||||
|
||||
await act(async () => {
|
||||
latestChoice!.confirm('');
|
||||
});
|
||||
await waitForAct(act, () => responses.length === 1);
|
||||
|
||||
assert.equal(responses[0].error, undefined);
|
||||
const result = responses[0].result as {
|
||||
items: Array<{ hostHandle: string; scope: string; title: string; version: string }>;
|
||||
};
|
||||
const sessionItem = result.items.find((item) => item.scope === 'session');
|
||||
assert.ok(sessionItem, 'expected active session source to be included');
|
||||
assert.equal(sessionItem.title, 'host-h2');
|
||||
|
||||
// Switching tabs without re-rendering must make context.current immediately report false.
|
||||
const rendersBeforeSwitch = renders;
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId('session-1');
|
||||
await flushTabStore();
|
||||
});
|
||||
assert.equal(renders, rendersBeforeSwitch);
|
||||
|
||||
await act(async () => {
|
||||
requestHandler!({
|
||||
kind: 'context.current',
|
||||
requestId: 'req-2',
|
||||
runtimeId: 'rt-1',
|
||||
actionToken: 'tok-2',
|
||||
payload: { hostHandle: sessionItem.hostHandle, version: sessionItem.version },
|
||||
});
|
||||
});
|
||||
await waitForAct(act, () => responses.length === 2);
|
||||
assert.deepEqual(responses[1].result, { current: false });
|
||||
} finally {
|
||||
registerAppAppLockRuntime(oldLock);
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
await flushTabStore();
|
||||
});
|
||||
activeTabStore.setActiveTabId(previousTabId, { recordPrevious: false });
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { existsSync, readFileSync, statSync } from 'node:fs';
|
||||
import { dirname, join, relative, resolve } from 'node:path';
|
||||
import test from 'node:test';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
@@ -11,6 +11,83 @@ const read = (path: string) => readFileSync(join(root, path), 'utf8');
|
||||
const staticImports = (source: string) =>
|
||||
[...source.matchAll(/^\s*import\s+(?!type\b)[^;]*?from\s+['"]([^'"]+)['"]/gm)].map((match) => match[1]);
|
||||
|
||||
const STATIC_SPECIFIER_RE =
|
||||
/(?:^|\n)\s*(?:import\s+(?!type\b)(?:[^;'"]*?\s+from\s+)?|export\s+(?!type\b)[^;'"]*?\s+from\s+)['"]([^'"]+)['"]/g;
|
||||
const CJS_REQUIRE_RE = /\brequire\(\s*['"]([^'"]+)['"]\s*\)/g;
|
||||
|
||||
function extractStaticModuleSpecifiers(filePath: string, source: string): string[] {
|
||||
const specs: string[] = [];
|
||||
for (const match of source.matchAll(STATIC_SPECIFIER_RE)) {
|
||||
specs.push(match[1]);
|
||||
}
|
||||
if (filePath.endsWith('.cjs')) {
|
||||
for (const match of source.matchAll(CJS_REQUIRE_RE)) {
|
||||
specs.push(match[1]);
|
||||
}
|
||||
}
|
||||
return specs;
|
||||
}
|
||||
|
||||
function resolveLocalModule(fromFile: string, specifier: string): string | null {
|
||||
let base: string | null = null;
|
||||
if (specifier.startsWith('@/')) {
|
||||
base = join(root, specifier.slice(2));
|
||||
} else if (specifier.startsWith('.')) {
|
||||
base = resolve(dirname(fromFile), specifier);
|
||||
}
|
||||
if (!base) return null;
|
||||
|
||||
const candidates = [
|
||||
base,
|
||||
`${base}.ts`,
|
||||
`${base}.tsx`,
|
||||
`${base}.js`,
|
||||
`${base}.jsx`,
|
||||
`${base}.mjs`,
|
||||
`${base}.cjs`,
|
||||
join(base, 'index.ts'),
|
||||
join(base, 'index.tsx'),
|
||||
join(base, 'index.js'),
|
||||
join(base, 'index.jsx'),
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
if (existsSync(candidate) && statSync(candidate).isFile()) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function collectStartupExternalDependencies(entryRelativePath: string): Map<string, string[]> {
|
||||
const entryAbs = join(root, entryRelativePath);
|
||||
const visited = new Set<string>([entryAbs]);
|
||||
const parentChain = new Map<string, string[]>([[entryAbs, [entryRelativePath]]]);
|
||||
const externalPaths = new Map<string, string[]>();
|
||||
const queue: string[] = [entryAbs];
|
||||
|
||||
while (queue.length > 0) {
|
||||
const current = queue.shift()!;
|
||||
const source = readFileSync(current, 'utf8');
|
||||
const chain = parentChain.get(current)!;
|
||||
|
||||
for (const specifier of extractStaticModuleSpecifiers(current, source)) {
|
||||
if (specifier.startsWith('.') || specifier.startsWith('@/')) {
|
||||
const resolved = resolveLocalModule(current, specifier);
|
||||
if (resolved && !visited.has(resolved)) {
|
||||
visited.add(resolved);
|
||||
parentChain.set(resolved, [...chain, relative(root, resolved)]);
|
||||
queue.push(resolved);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!externalPaths.has(specifier)) {
|
||||
externalPaths.set(specifier, [...chain, specifier]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return externalPaths;
|
||||
}
|
||||
|
||||
test('only the English dictionary is bundled with the startup entry', () => {
|
||||
const imports = staticImports(read('application/i18n/messages.ts'));
|
||||
assert.deepEqual(imports.filter((path) => path.startsWith('./locales/')), ['./locales/en']);
|
||||
@@ -34,6 +111,27 @@ test("Vite's preload helper stays out of the vendor-ai chunk", () => {
|
||||
assert.match(read('vite.config.ts'), /vite\/preload-helper'\)\) return 'preload-helper'/);
|
||||
});
|
||||
|
||||
test('the QR decoder is loaded on demand', () => {
|
||||
assert.ok(!staticImports(read('components/HostTotpFields.tsx')).includes('jsqr'));
|
||||
test('the QR decoder and RE2JS regex validator are loaded on demand', () => {
|
||||
const imports = staticImports(read('components/HostTotpFields.tsx'));
|
||||
assert.ok(!imports.includes('jsqr'));
|
||||
assert.ok(!imports.includes('re2js'));
|
||||
});
|
||||
|
||||
test('startup entry does not statically reach re2js, css-tree, @remote-dom/core, or @monaco-editor/react', () => {
|
||||
const externals = collectStartupExternalDependencies('index.tsx');
|
||||
const forbidden = [
|
||||
{ label: 're2js', match: (spec: string) => spec === 're2js' || spec.startsWith('re2js/') },
|
||||
{ label: 'css-tree', match: (spec: string) => spec === 'css-tree' || spec.startsWith('css-tree/') },
|
||||
{ label: '@remote-dom/core', match: (spec: string) => spec === '@remote-dom/core' || spec.startsWith('@remote-dom/core/') },
|
||||
{ label: '@monaco-editor/react', match: (spec: string) => spec === '@monaco-editor/react' || spec.startsWith('@monaco-editor/react/') },
|
||||
];
|
||||
|
||||
for (const rule of forbidden) {
|
||||
const matchEntry = [...externals.entries()].find(([spec]) => rule.match(spec));
|
||||
assert.equal(
|
||||
matchEntry,
|
||||
undefined,
|
||||
`${rule.label} must not be statically reachable from index.tsx (found via ${matchEntry?.[1].join(' -> ')})`,
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -1,47 +1,10 @@
|
||||
import type { TerminalTheme } from '../../types';
|
||||
import { resolveReadableForegroundForHsl } from '../../domain/colorContrast';
|
||||
|
||||
function hexToHslToken(hex: string): string {
|
||||
const normalized = hex.startsWith('#') ? hex : `#${hex}`;
|
||||
const r = parseInt(normalized.slice(1, 3), 16) / 255;
|
||||
const g = parseInt(normalized.slice(3, 5), 16) / 255;
|
||||
const b = parseInt(normalized.slice(5, 7), 16) / 255;
|
||||
const max = Math.max(r, g, b);
|
||||
const min = Math.min(r, g, b);
|
||||
let h = 0;
|
||||
let s = 0;
|
||||
const l = (max + min) / 2;
|
||||
|
||||
if (max !== min) {
|
||||
const d = max - min;
|
||||
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
||||
switch (max) {
|
||||
case r:
|
||||
h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
|
||||
break;
|
||||
case g:
|
||||
h = ((b - r) / d + 2) / 6;
|
||||
break;
|
||||
default:
|
||||
h = ((r - g) / d + 4) / 6;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return `${Math.round(h * 3600) / 10} ${Math.round(s * 1000) / 10}% ${Math.round(l * 1000) / 10}%`;
|
||||
}
|
||||
|
||||
function adjustLightnessToken(hsl: string, delta: number): string {
|
||||
const parts = hsl.split(/\s+/);
|
||||
const newL = Math.max(0, Math.min(100, parseFloat(parts[2]) + delta));
|
||||
return `${parts[0]} ${parts[1]} ${Math.round(newL * 10) / 10}%`;
|
||||
}
|
||||
|
||||
function adjustSaturationToken(hsl: string, factor: number): string {
|
||||
const parts = hsl.split(/\s+/);
|
||||
const newS = Math.max(0, Math.min(100, parseFloat(parts[1]) * factor));
|
||||
return `${parts[0]} ${Math.round(newS * 10) / 10}% ${parts[2]}`;
|
||||
}
|
||||
import {
|
||||
adjustLightnessToken,
|
||||
adjustSaturationToken,
|
||||
hexToHslToken,
|
||||
resolveReadableForegroundForHsl,
|
||||
} from '../../domain/colorContrast';
|
||||
|
||||
const setStylePropertyIfChanged = (element: HTMLElement, property: string, value: string) => {
|
||||
if (element.style.getPropertyValue(property) === value) return;
|
||||
|
||||
@@ -618,8 +618,8 @@ export const enAiMessages: Messages = {
|
||||
'ai.chat.rebindUsage': 'Usage: /rebind <number from /chats>',
|
||||
'ai.chat.rebindDone': 'Chat "{title}" rebound to this panel.',
|
||||
'ai.chat.rebindUnavailable': 'No rebind target in this panel scope.',
|
||||
'ai.chat.managerScopeTab': 'Current',
|
||||
'ai.chat.managerAllChatsTab': 'All',
|
||||
'ai.chat.managerScopeTab': 'Current chats',
|
||||
'ai.chat.managerAllChatsTab': 'All chats',
|
||||
'ai.chat.managerSearchPlaceholder': 'Search chat titles…',
|
||||
'ai.chat.managerFilterAllAgents': 'All agents',
|
||||
'ai.chat.managerMoreActions': 'More actions',
|
||||
@@ -722,6 +722,9 @@ export const enAiMessages: Messages = {
|
||||
'ai.safety.responseIdleTimeout.unit': 'sec',
|
||||
'ai.safety.maxIterations': 'Max Iterations',
|
||||
'ai.safety.maxIterations.description': 'Maximum number of AI tool-use loops to prevent runaway execution. External agents may have their own internal iteration limits that take precedence.',
|
||||
'ai.safety.toolOutputMaxChars': 'Built-in AI Tool Output Limit',
|
||||
'ai.safety.toolOutputMaxChars.description': 'Maximum characters kept inline per built-in AI tool result (such as terminal commands or SFTP reads) before truncating and spilling the full output to a saved handle (2,000–200,000).',
|
||||
'ai.safety.toolOutputMaxChars.unit': 'chars',
|
||||
'ai.safety.blocklist': 'Command Blocklist',
|
||||
'ai.safety.blocklist.description': 'Regex patterns to block dangerous commands executed through Netcatty.',
|
||||
'ai.safety.blocklist.placeholder': 'Regex pattern...',
|
||||
|
||||
@@ -475,7 +475,7 @@ export const enCoreMessages: Messages = {
|
||||
'settings.appearance.themeColor.dark': 'Dark palette',
|
||||
'settings.appearance.customCss': 'Custom CSS',
|
||||
'settings.appearance.customCss.desc':
|
||||
'Add custom CSS to personalize the app appearance. Changes apply immediately. Selected top tabs (`.top-tab[data-active="true"]`) read `--top-tab-active-bg`, `--top-tab-active-fg`, and `--top-tab-active-border`. Leave them unset to keep the current look.',
|
||||
'Add custom CSS to personalize the app appearance. Changes apply immediately.',
|
||||
'settings.appearance.customCss.help.ariaLabel': 'Custom CSS help',
|
||||
'settings.appearance.customCss.help.title': 'Custom CSS guide',
|
||||
'settings.appearance.customCss.help.body': `Major UI regions expose a \`data-section\` attribute you can target. Changes apply as soon as you edit the CSS.
|
||||
@@ -1039,6 +1039,7 @@ Highlight the focused split pane:
|
||||
'settings.shortcuts.binding.close-tab': 'Close Tab',
|
||||
'settings.shortcuts.binding.close-session': 'Close Session Pane',
|
||||
'settings.shortcuts.binding.new-tab': 'New Local Tab',
|
||||
'settings.shortcuts.binding.reopen-closed-tab': 'Reopen Closed Tab',
|
||||
'settings.shortcuts.binding.copy': 'Copy from Terminal',
|
||||
'settings.shortcuts.binding.paste': 'Paste to Terminal',
|
||||
'settings.shortcuts.binding.paste-selection': 'Paste Selection to Terminal',
|
||||
|
||||
@@ -13,9 +13,11 @@ export const enTerminalMessages: Messages = {
|
||||
'terminal.directory.refresh': 'Refresh',
|
||||
'terminal.directory.unavailable': 'Directory navigation is unavailable for this session.',
|
||||
'terminal.directory.integrationUnavailable': 'PowerShell directory integration is not ready. Startup arguments or execution policy may prevent it.',
|
||||
'terminal.directory.cmdIntegrationUnavailable': 'Waiting for a directory report from the original Command Prompt session.',
|
||||
'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.',
|
||||
'terminal.directory.accessDenied': 'Permission denied while listing this directory.',
|
||||
'terminal.directory.changeFailed': 'Could not confirm the directory change. Refresh before retrying.',
|
||||
'terminal.directory.unsupportedPath': 'This directory name cannot be sent safely to the terminal.',
|
||||
'settings.terminal.behavior.contextChips': 'Context Chips',
|
||||
|
||||
@@ -421,6 +421,8 @@ export const enVaultMessages: Messages = {
|
||||
'sftp.encoding.auto': 'Auto',
|
||||
'sftp.encoding.utf8': 'UTF-8',
|
||||
'sftp.encoding.gb18030': 'GB18030',
|
||||
'sftp.goBack': 'Go back',
|
||||
'sftp.goForward': 'Go forward',
|
||||
'sftp.goHome': 'Go to home',
|
||||
'sftp.goRoot': 'Go to root',
|
||||
'sftp.folderName': 'Folder name',
|
||||
@@ -491,6 +493,9 @@ export const enVaultMessages: Messages = {
|
||||
|
||||
// SFTP File Opener
|
||||
'sftp.context.copyPath': 'Copy file path',
|
||||
'sftp.context.insertPathToTerminal': 'Insert path into terminal',
|
||||
'sftp.context.cdInTerminal': 'Open in terminal (cd)',
|
||||
'sftp.terminal.insertBlockedUnsafeQuote': 'Cannot insert path while the terminal cursor is inside an unclosed quote or escape',
|
||||
'sftp.context.openWithDefault': 'Open with system default',
|
||||
'sftp.context.openWith': 'Open with...',
|
||||
'sftp.context.edit': 'Edit',
|
||||
@@ -614,6 +619,13 @@ export const enVaultMessages: Messages = {
|
||||
'settings.sftp.packedDownload': 'Packed downloads',
|
||||
'settings.sftp.packedDownload.enable': 'Pack folders and multiple items for download',
|
||||
'settings.sftp.packedDownload.enableDesc': 'Download the selection in one stream and restore its original layout on this device. If the server cannot pack it, download files individually.',
|
||||
'settings.sftp.downloadLocation': 'Download location',
|
||||
'settings.sftp.downloadLocation.directory': 'Default download folder',
|
||||
'settings.sftp.downloadLocation.directoryDesc': 'SFTP download dialogs open in this folder. If it is not set or no longer exists, the system Downloads folder is used.',
|
||||
'settings.sftp.downloadLocation.systemDefault': 'System Downloads folder',
|
||||
'settings.sftp.downloadLocation.browse': 'Browse…',
|
||||
'settings.sftp.downloadLocation.reset': 'Use the system Downloads folder',
|
||||
'settings.sftp.downloadLocation.select': 'Choose default download folder',
|
||||
|
||||
'settings.sftp.skipUnchanged.enable': 'Skip unchanged files',
|
||||
'settings.sftp.skipUnchanged.enableDesc': 'Skip files whose size and modification time already match the destination (rsync-style). Disabled when replacing a folder into a staging path.',
|
||||
@@ -1004,6 +1016,8 @@ export const enVaultMessages: Messages = {
|
||||
'localShell.field.shellResolved': 'Runs {command}',
|
||||
'localShell.field.startDir': 'Start directory',
|
||||
'localShell.field.startDirPlaceholder': 'Inherit global start directory (home if unset)',
|
||||
'localShell.field.startupCommandPlaceholder': 'Command to run after shell starts (e.g. npm run dev)',
|
||||
'localShell.field.startupCommandDesc': 'Runs automatically after the local shell starts in the configured directory.',
|
||||
'localShell.saveAndConnect': 'Save & Connect',
|
||||
|
||||
'hostDetails.plugin.title': 'Plugin connection',
|
||||
|
||||
@@ -618,8 +618,8 @@ export const esAiMessages: Messages = {
|
||||
'ai.chat.rebindUsage': 'Uso: /rebind <número de /chats>',
|
||||
'ai.chat.rebindDone': 'Chat «{title}» reasociado a este panel.',
|
||||
'ai.chat.rebindUnavailable': 'No hay destino de reasociación en el ámbito de este panel.',
|
||||
'ai.chat.managerScopeTab': 'Actual',
|
||||
'ai.chat.managerAllChatsTab': 'Todos',
|
||||
'ai.chat.managerScopeTab': 'Chats actuales',
|
||||
'ai.chat.managerAllChatsTab': 'Todos los chats',
|
||||
'ai.chat.managerSearchPlaceholder': 'Buscar títulos de chats…',
|
||||
'ai.chat.managerFilterAllAgents': 'Todos los agentes',
|
||||
'ai.chat.managerMoreActions': 'Más acciones',
|
||||
@@ -722,6 +722,9 @@ export const esAiMessages: Messages = {
|
||||
'ai.safety.responseIdleTimeout.unit': 'seg',
|
||||
'ai.safety.maxIterations': 'Máximo de iteraciones',
|
||||
'ai.safety.maxIterations.description': 'Máximo de bucles de uso de herramientas de IA para evitar una ejecución descontrolada. Los agentes externos pueden tener sus propios límites de iteración internos que tienen prioridad.',
|
||||
'ai.safety.toolOutputMaxChars': 'Límite de salida de herramientas de IA integrada',
|
||||
'ai.safety.toolOutputMaxChars.description': 'Máximo de caracteres que se mantienen en línea por resultado de herramienta de la IA integrada (como comandos de terminal o lecturas SFTP) antes de truncar y guardar la salida completa en un identificador (2,000–200,000).',
|
||||
'ai.safety.toolOutputMaxChars.unit': 'car.',
|
||||
'ai.safety.blocklist': 'Lista de bloqueo de comandos',
|
||||
'ai.safety.blocklist.description': 'Patrones regex para bloquear comandos peligrosos ejecutados mediante Netcatty.',
|
||||
'ai.safety.blocklist.placeholder': 'Patrón regex...',
|
||||
|
||||
@@ -475,7 +475,7 @@ export const esCoreMessages: Messages = {
|
||||
'settings.appearance.themeColor.dark': 'Paleta oscura',
|
||||
'settings.appearance.customCss': 'CSS personalizado',
|
||||
'settings.appearance.customCss.desc':
|
||||
'Agrega CSS personalizado para personalizar la apariencia de la aplicación. Los cambios se aplican de inmediato. Las pestañas superiores seleccionadas (`.top-tab[data-active="true"]`) leen `--top-tab-active-bg`, `--top-tab-active-fg` y `--top-tab-active-border`. Si no las defines, se conserva el aspecto actual.',
|
||||
'Agrega CSS personalizado para personalizar la apariencia de la aplicación. Los cambios se aplican de inmediato.',
|
||||
'settings.appearance.customCss.help.ariaLabel': 'Ayuda de CSS personalizado',
|
||||
'settings.appearance.customCss.help.title': 'Guía de CSS personalizado',
|
||||
'settings.appearance.customCss.help.body': `Las principales regiones de la interfaz exponen un atributo \`data-section\` que puedes usar como destino. Los cambios se aplican en cuanto editas el CSS.
|
||||
@@ -1039,6 +1039,7 @@ Resalta el panel dividido enfocado:
|
||||
'settings.shortcuts.binding.close-tab': 'Cerrar pestaña',
|
||||
'settings.shortcuts.binding.close-session': 'Cerrar panel de sesión',
|
||||
'settings.shortcuts.binding.new-tab': 'Nueva pestaña local',
|
||||
'settings.shortcuts.binding.reopen-closed-tab': 'Reabrir pestaña cerrada',
|
||||
'settings.shortcuts.binding.copy': 'Copiar desde la terminal',
|
||||
'settings.shortcuts.binding.paste': 'Pegar en la terminal',
|
||||
'settings.shortcuts.binding.paste-selection': 'Pegar selección en la terminal',
|
||||
|
||||
@@ -13,7 +13,9 @@ export const esTerminalMessages: Messages = {
|
||||
'terminal.directory.refresh': 'Actualizar',
|
||||
'terminal.directory.unavailable': 'La navegación de directorios no está disponible para esta sesión.',
|
||||
'terminal.directory.integrationUnavailable': 'La integración de directorios de PowerShell no está lista. Los argumentos de inicio o la política de ejecución pueden impedirla.',
|
||||
'terminal.directory.cmdIntegrationUnavailable': 'Esperando el directorio de la sesión original del símbolo del sistema.',
|
||||
'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.',
|
||||
'terminal.directory.readFailed': 'No se pudo leer el directorio. Actualiza e inténtalo de nuevo.',
|
||||
'terminal.directory.changeFailed': 'No se pudo confirmar el cambio. Actualiza antes de reintentar.',
|
||||
|
||||
@@ -421,6 +421,8 @@ export const esVaultMessages: Messages = {
|
||||
'sftp.encoding.auto': 'Auto',
|
||||
'sftp.encoding.utf8': 'UTF-8',
|
||||
'sftp.encoding.gb18030': 'GB18030',
|
||||
'sftp.goBack': 'Ir atrás',
|
||||
'sftp.goForward': 'Ir adelante',
|
||||
'sftp.goHome': 'Ir al inicio',
|
||||
'sftp.goRoot': 'Ir a la raíz',
|
||||
'sftp.folderName': 'Nombre de la carpeta',
|
||||
@@ -491,6 +493,9 @@ export const esVaultMessages: Messages = {
|
||||
|
||||
// SFTP File Opener
|
||||
'sftp.context.copyPath': 'Copiar ruta del archivo',
|
||||
'sftp.context.insertPathToTerminal': 'Insertar ruta en la terminal',
|
||||
'sftp.context.cdInTerminal': 'Abrir en la terminal (cd)',
|
||||
'sftp.terminal.insertBlockedUnsafeQuote': 'No se puede insertar la ruta mientras el cursor de la terminal esté dentro de una comilla o secuencia de escape sin cerrar',
|
||||
'sftp.context.openWithDefault': 'Abrir con la aplicación predeterminada del sistema',
|
||||
'sftp.context.openWith': 'Abrir con...',
|
||||
'sftp.context.edit': 'Editar',
|
||||
@@ -614,6 +619,13 @@ export const esVaultMessages: Messages = {
|
||||
'settings.sftp.packedDownload': 'Descargas empaquetadas',
|
||||
'settings.sftp.packedDownload.enable': 'Empaquetar carpetas y selecciones múltiples para descargar',
|
||||
'settings.sftp.packedDownload.enableDesc': 'Descarga la selección en una sola transferencia y restaura su estructura original en este dispositivo. Si el servidor no puede empaquetarla, los archivos se descargan por separado.',
|
||||
'settings.sftp.downloadLocation': 'Ubicación de descarga',
|
||||
'settings.sftp.downloadLocation.directory': 'Carpeta de descarga predeterminada',
|
||||
'settings.sftp.downloadLocation.directoryDesc': 'Los diálogos de descarga SFTP se abren en esta carpeta. Si no está configurada o ya no existe, se usa la carpeta Descargas del sistema.',
|
||||
'settings.sftp.downloadLocation.systemDefault': 'Carpeta Descargas del sistema',
|
||||
'settings.sftp.downloadLocation.browse': 'Examinar…',
|
||||
'settings.sftp.downloadLocation.reset': 'Usar la carpeta Descargas del sistema',
|
||||
'settings.sftp.downloadLocation.select': 'Elegir la carpeta de descarga predeterminada',
|
||||
|
||||
'settings.sftp.skipUnchanged.enable': 'Omitir archivos sin cambios',
|
||||
'settings.sftp.skipUnchanged.enableDesc': 'Omite los archivos cuyo tamaño y hora de modificación ya coinciden con el destino (estilo rsync). Deshabilitado al reemplazar una carpeta en una ruta de staging.',
|
||||
@@ -1006,6 +1018,8 @@ export const esVaultMessages: Messages = {
|
||||
'localShell.field.shellResolved': 'Ejecuta {command}',
|
||||
'localShell.field.startDir': 'Directorio de inicio',
|
||||
'localShell.field.startDirPlaceholder': 'Heredar directorio inicial global (personal si no se configura)',
|
||||
'localShell.field.startupCommandPlaceholder': 'Comando para ejecutar al iniciar la shell (p. ej., npm run dev)',
|
||||
'localShell.field.startupCommandDesc': 'Se ejecuta automáticamente cuando la shell local inicia en el directorio configurado.',
|
||||
'localShell.saveAndConnect': 'Guardar y conectar',
|
||||
|
||||
'hostDetails.plugin.title': 'Conexión de plugin',
|
||||
|
||||
@@ -210,3 +210,21 @@ test("managed group delete warning mentions SSH config backup in every locale",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("AI tool output limit settings copy is localized across all five locales", () => {
|
||||
const keys = [
|
||||
"ai.safety.toolOutputMaxChars",
|
||||
"ai.safety.toolOutputMaxChars.description",
|
||||
"ai.safety.toolOutputMaxChars.unit",
|
||||
] 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`);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert.match(zhTW["ai.safety.toolOutputMaxChars.description"], /傳回/);
|
||||
assert.equal(zhTW["ai.safety.toolOutputMaxChars.description"].includes("返回"), false);
|
||||
});
|
||||
@@ -557,8 +557,8 @@ export const ruAiMessages: Messages = {
|
||||
'ai.chat.rebindUsage': 'Использование: /rebind <номер из /chats>',
|
||||
'ai.chat.rebindDone': 'Чат «{title}» привязан к этой панели.',
|
||||
'ai.chat.rebindUnavailable': 'В области этой панели нет цели для привязки.',
|
||||
'ai.chat.managerScopeTab': 'Текущие',
|
||||
'ai.chat.managerAllChatsTab': 'Все',
|
||||
'ai.chat.managerScopeTab': 'Текущие чаты',
|
||||
'ai.chat.managerAllChatsTab': 'Все чаты',
|
||||
'ai.chat.managerSearchPlaceholder': 'Поиск по названиям чатов…',
|
||||
'ai.chat.managerFilterAllAgents': 'Все агенты',
|
||||
'ai.chat.managerMoreActions': 'Ещё действия',
|
||||
@@ -661,6 +661,9 @@ export const ruAiMessages: Messages = {
|
||||
'ai.safety.responseIdleTimeout.unit': 'с',
|
||||
'ai.safety.maxIterations': 'Макс. число итераций',
|
||||
'ai.safety.maxIterations.description': 'Максимальное число циклов использования инструментов AI, чтобы предотвратить бесконтрольное выполнение. У внешних агентов могут быть собственные внутренние лимиты итераций, имеющие приоритет.',
|
||||
'ai.safety.toolOutputMaxChars': 'Лимит вывода инструментов встроенного ИИ',
|
||||
'ai.safety.toolOutputMaxChars.description': 'Максимум символов, оставляемых напрямую в результате инструмента встроенного ИИ (например, вывода команд терминала или чтения SFTP) до обрезки и сохранения полного вывода в дескриптор (2 000–200 000).',
|
||||
'ai.safety.toolOutputMaxChars.unit': 'симв.',
|
||||
'ai.safety.blocklist': 'Чёрный список команд',
|
||||
'ai.safety.blocklist.description': 'Regex-шаблоны для блокировки опасных команд. Применяется как к встроенным, так и к внешним агентам через механизм выполнения Netcatty.',
|
||||
'ai.safety.blocklist.placeholder': 'Regex-шаблон...',
|
||||
|
||||
@@ -432,7 +432,7 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.appearance.themeColor.dark': 'Палитра тёмной темы',
|
||||
'settings.appearance.customCss': 'Пользовательский CSS',
|
||||
'settings.appearance.customCss.desc':
|
||||
'Добавьте пользовательский CSS, чтобы настроить внешний вид. Изменения применяются сразу. Выбранные верхние вкладки (`.top-tab[data-active="true"]`) читают `--top-tab-active-bg`, `--top-tab-active-fg` и `--top-tab-active-border`. Не задавайте их, чтобы сохранить текущий вид.',
|
||||
'Добавьте пользовательский CSS, чтобы настроить внешний вид. Изменения применяются сразу.',
|
||||
'settings.appearance.customCss.help.ariaLabel': 'Справка по пользовательскому CSS',
|
||||
'settings.appearance.customCss.help.title': 'Руководство по пользовательскому CSS',
|
||||
'settings.appearance.customCss.help.body': `Основные области интерфейса помечены атрибутом \`data-section\` для CSS-селекторов. Изменения применяются сразу после правки.
|
||||
@@ -952,6 +952,7 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.shortcuts.binding.close-tab': 'Закрыть вкладку',
|
||||
'settings.shortcuts.binding.close-session': 'Закрыть панель сессии',
|
||||
'settings.shortcuts.binding.new-tab': 'Новая локальная вкладка',
|
||||
'settings.shortcuts.binding.reopen-closed-tab': 'Повторно открыть закрытую вкладку',
|
||||
'settings.shortcuts.binding.copy': 'Копировать из терминала',
|
||||
'settings.shortcuts.binding.paste': 'Вставить в терминал',
|
||||
'settings.shortcuts.binding.paste-selection': 'Вставить выделение в терминал',
|
||||
|
||||
@@ -13,7 +13,9 @@ export const ruTerminalMessages: Messages = {
|
||||
'terminal.directory.refresh': 'Обновить',
|
||||
'terminal.directory.unavailable': 'Навигация по каталогам недоступна для этого сеанса.',
|
||||
'terminal.directory.integrationUnavailable': 'Интеграция каталогов PowerShell не готова. Проверьте параметры запуска и политику выполнения.',
|
||||
'terminal.directory.cmdIntegrationUnavailable': 'Ожидание данных о каталоге от исходного сеанса командной строки.',
|
||||
'terminal.directory.nonFilesystem': 'Текущее расположение PowerShell не является каталогом файловой системы.',
|
||||
'terminal.directory.accessDenied': 'Нет разрешения на просмотр содержимого этого каталога.',
|
||||
'terminal.directory.busy': 'Дождитесь пустой командной строки.',
|
||||
'terminal.directory.readFailed': 'Не удалось прочитать каталог. Попробуйте обновить.',
|
||||
'terminal.directory.changeFailed': 'Не удалось подтвердить смену каталога. Обновите перед повтором.',
|
||||
|
||||
@@ -464,6 +464,8 @@ export const ruVaultMessages: Messages = {
|
||||
'sftp.encoding.auto': 'Авто',
|
||||
'sftp.encoding.utf8': 'UTF-8',
|
||||
'sftp.encoding.gb18030': 'GB18030',
|
||||
'sftp.goBack': 'Назад',
|
||||
'sftp.goForward': 'Вперёд',
|
||||
'sftp.goHome': 'Перейти в домашний каталог',
|
||||
'sftp.goRoot': 'Перейти в корень',
|
||||
'sftp.folderName': 'Имя папки',
|
||||
@@ -534,6 +536,9 @@ export const ruVaultMessages: Messages = {
|
||||
|
||||
// SFTP File Opener
|
||||
'sftp.context.copyPath': 'Копировать путь к файлу',
|
||||
'sftp.context.insertPathToTerminal': 'Вставить путь в терминал',
|
||||
'sftp.context.cdInTerminal': 'Открыть в терминале (cd)',
|
||||
'sftp.terminal.insertBlockedUnsafeQuote': 'Невозможно вставить путь, пока курсор терминала находится внутри незакрытых кавычек или экранирования',
|
||||
'sftp.context.openWithDefault': 'Открыть в системном приложении',
|
||||
'sftp.context.openWith': 'Открыть с помощью...',
|
||||
'sftp.context.edit': 'Редактировать',
|
||||
@@ -657,6 +662,13 @@ export const ruVaultMessages: Messages = {
|
||||
'settings.sftp.packedDownload': 'Скачивание архивом',
|
||||
'settings.sftp.packedDownload.enable': 'Упаковывать папки и выбранные вместе файлы перед скачиванием',
|
||||
'settings.sftp.packedDownload.enableDesc': 'Выбранные файлы передаются одним потоком и распаковываются с сохранением структуры папок. Если сервер не поддерживает упаковку, файлы скачиваются по отдельности.',
|
||||
'settings.sftp.downloadLocation': 'Папка для загрузок',
|
||||
'settings.sftp.downloadLocation.directory': 'Папка загрузок по умолчанию',
|
||||
'settings.sftp.downloadLocation.directoryDesc': 'Диалоги скачивания по SFTP открываются в этой папке. Если она не задана или больше не существует, используется системная папка «Загрузки».',
|
||||
'settings.sftp.downloadLocation.systemDefault': 'Системная папка «Загрузки»',
|
||||
'settings.sftp.downloadLocation.browse': 'Обзор…',
|
||||
'settings.sftp.downloadLocation.reset': 'Использовать системную папку «Загрузки»',
|
||||
'settings.sftp.downloadLocation.select': 'Выберите папку загрузок по умолчанию',
|
||||
|
||||
'settings.sftp.skipUnchanged.enable': 'Пропускать неизменённые файлы',
|
||||
'settings.sftp.skipUnchanged.enableDesc': 'Пропускать файлы, у которых размер и время изменения уже совпадают с назначением (в стиле rsync). Отключается при замене папки во временный путь.',
|
||||
@@ -1042,6 +1054,8 @@ export const ruVaultMessages: Messages = {
|
||||
'localShell.field.shellResolved': 'Запускает {command}',
|
||||
'localShell.field.startDir': 'Начальный каталог',
|
||||
'localShell.field.startDirPlaceholder': 'Использовать общий начальный каталог (иначе домашний)',
|
||||
'localShell.field.startupCommandPlaceholder': 'Команда после запуска оболочки (например, npm run dev)',
|
||||
'localShell.field.startupCommandDesc': 'Выполняется автоматически после запуска локальной оболочки в указанном каталоге.',
|
||||
'localShell.saveAndConnect': 'Сохранить и открыть',
|
||||
|
||||
'hostDetails.plugin.title': 'Подключение плагина',
|
||||
|
||||
@@ -618,8 +618,8 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.chat.rebindUsage': '用法:/rebind <序号>',
|
||||
'ai.chat.rebindDone': '聊天“{title}”已重绑到此面板。',
|
||||
'ai.chat.rebindUnavailable': '当前面板范围内没有可用的重绑目标。',
|
||||
'ai.chat.managerScopeTab': '当前',
|
||||
'ai.chat.managerAllChatsTab': '全部',
|
||||
'ai.chat.managerScopeTab': '当前会话',
|
||||
'ai.chat.managerAllChatsTab': '全部会话',
|
||||
'ai.chat.managerSearchPlaceholder': '搜索会话标题…',
|
||||
'ai.chat.managerFilterAllAgents': '全部 Agent',
|
||||
'ai.chat.managerMoreActions': '更多操作',
|
||||
@@ -722,6 +722,9 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.safety.responseIdleTimeout.unit': '秒',
|
||||
'ai.safety.maxIterations': '最大迭代次数',
|
||||
'ai.safety.maxIterations.description': '防止 AI 失控执行的最大工具调用循环次数。外部 Agent 可能有自己的内部迭代限制,以其为准。',
|
||||
'ai.safety.toolOutputMaxChars': '内置 AI 工具输出限制',
|
||||
'ai.safety.toolOutputMaxChars.description': '内置 AI 单次工具调用(如终端命令或 SFTP 读取)直接返回的最大字符数,超出后会截断并将完整结果保存为可读取的句柄(2,000–200,000)。',
|
||||
'ai.safety.toolOutputMaxChars.unit': '字符',
|
||||
'ai.safety.blocklist': '命令黑名单',
|
||||
'ai.safety.blocklist.description': '用于拦截通过 Netcatty 执行的危险命令的正则表达式。',
|
||||
'ai.safety.blocklist.placeholder': '正则表达式...',
|
||||
|
||||
@@ -482,7 +482,7 @@ export const zhCNCoreMessages: Messages = {
|
||||
'settings.appearance.themeColor.dark': '深色主题',
|
||||
'settings.appearance.customCss': '自定义 CSS',
|
||||
'settings.appearance.customCss.desc':
|
||||
'使用自定义 CSS 个性化界面,修改会立即生效。选中的顶部标签(`.top-tab[data-active="true"]`)会读取 `--top-tab-active-bg`、`--top-tab-active-fg` 和 `--top-tab-active-border`。不设置则保持当前外观。',
|
||||
'使用自定义 CSS 个性化界面,修改会立即生效。',
|
||||
'settings.appearance.customCss.help.ariaLabel': '自定义 CSS 说明',
|
||||
'settings.appearance.customCss.help.title': '自定义 CSS 说明',
|
||||
'settings.appearance.customCss.help.body': `主要 UI 区块都暴露了 \`data-section\` 属性,供你用 CSS 定位。编辑后会立即生效。
|
||||
@@ -1167,6 +1167,8 @@ Vaults 标签保持扁平,不使用这块背景。
|
||||
'sftp.encoding.auto': '自动',
|
||||
'sftp.encoding.utf8': 'UTF-8',
|
||||
'sftp.encoding.gb18030': 'GB18030',
|
||||
'sftp.goBack': '后退',
|
||||
'sftp.goForward': '前进',
|
||||
'sftp.goHome': '返回主目录',
|
||||
'sftp.goRoot': '回到根目录',
|
||||
'sftp.folderName': '文件夹名称',
|
||||
|
||||
@@ -13,7 +13,9 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'terminal.directory.refresh': '刷新',
|
||||
'terminal.directory.unavailable': '此会话暂不支持目录导航。',
|
||||
'terminal.directory.integrationUnavailable': 'PowerShell 目录集成未就绪,启动参数或执行策略可能阻止了加载。',
|
||||
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 会话报告当前目录。',
|
||||
'terminal.directory.nonFilesystem': '当前 PowerShell 位置不是文件系统目录。',
|
||||
'terminal.directory.accessDenied': '没有权限列出此目录。',
|
||||
'terminal.directory.busy': '请等待终端回到空命令提示符。',
|
||||
'terminal.directory.readFailed': '无法读取此目录,请刷新重试。',
|
||||
'terminal.directory.changeFailed': '未能确认目录切换,请刷新后重试。',
|
||||
@@ -97,6 +99,9 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'history.clearAll.dialog.confirm': '全部清空',
|
||||
// SFTP File Opener
|
||||
'sftp.context.copyPath': '复制文件路径',
|
||||
'sftp.context.insertPathToTerminal': '插入路径到终端',
|
||||
'sftp.context.cdInTerminal': '在终端中打开 (cd)',
|
||||
'sftp.terminal.insertBlockedUnsafeQuote': '终端光标位于未闭合的引号或转义符内,无法安全插入路径',
|
||||
'sftp.context.openWith': '打开方式...',
|
||||
'sftp.context.edit': '编辑',
|
||||
'sftp.opener.title': '打开方式',
|
||||
@@ -220,6 +225,13 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'settings.sftp.packedDownload': '打包下载',
|
||||
'settings.sftp.packedDownload.enable': '下载文件夹或多选项目时打包',
|
||||
'settings.sftp.packedDownload.enableDesc': '将所选内容一次传回,在本地自动还原原有目录结构。服务器不支持打包时,自动逐文件下载。',
|
||||
'settings.sftp.downloadLocation': '下载位置',
|
||||
'settings.sftp.downloadLocation.directory': '默认下载文件夹',
|
||||
'settings.sftp.downloadLocation.directoryDesc': '下载 SFTP 文件时,保存对话框默认打开此文件夹。未设置或文件夹已不存在时,使用系统“下载”文件夹。',
|
||||
'settings.sftp.downloadLocation.systemDefault': '系统“下载”文件夹',
|
||||
'settings.sftp.downloadLocation.browse': '浏览…',
|
||||
'settings.sftp.downloadLocation.reset': '恢复为系统“下载”文件夹',
|
||||
'settings.sftp.downloadLocation.select': '选择默认下载文件夹',
|
||||
|
||||
'settings.sftp.skipUnchanged.enable': '跳过未改文件',
|
||||
'settings.sftp.skipUnchanged.enableDesc': '当目标文件的大小与修改时间已与源一致时跳过传输(类似 rsync)。替换到暂存路径时自动禁用。',
|
||||
@@ -590,6 +602,7 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'settings.shortcuts.binding.close-tab': '关闭标签页',
|
||||
'settings.shortcuts.binding.close-session': '关闭会话窗格',
|
||||
'settings.shortcuts.binding.new-tab': '新建本地标签页',
|
||||
'settings.shortcuts.binding.reopen-closed-tab': '重新打开关闭的标签页',
|
||||
'settings.shortcuts.binding.copy': '从终端复制',
|
||||
'settings.shortcuts.binding.paste': '粘贴到终端',
|
||||
'settings.shortcuts.binding.paste-selection': '将选区粘贴到终端',
|
||||
|
||||
@@ -408,6 +408,8 @@ export const zhCNVaultMessages: Messages = {
|
||||
'localShell.field.shellResolved': '启动 {command}',
|
||||
'localShell.field.startDir': '启动目录',
|
||||
'localShell.field.startDirPlaceholder': '继承全局起始目录(未设置时为主目录)',
|
||||
'localShell.field.startupCommandPlaceholder': 'Shell 启动后执行的命令(例如:npm run dev)',
|
||||
'localShell.field.startupCommandDesc': '本地 Shell 在启动目录打开后自动执行该命令。',
|
||||
'localShell.saveAndConnect': '保存并打开',
|
||||
|
||||
'hostDetails.plugin.title': '插件连接',
|
||||
|
||||
@@ -617,8 +617,8 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.chat.rebindUsage': '用法:/rebind <序號>',
|
||||
'ai.chat.rebindDone': '聊天「{title}」已重新綁定到此面板。',
|
||||
'ai.chat.rebindUnavailable': '目前面板範圍內沒有可用的重新綁定目標。',
|
||||
'ai.chat.managerScopeTab': '目前',
|
||||
'ai.chat.managerAllChatsTab': '全部',
|
||||
'ai.chat.managerScopeTab': '目前會話',
|
||||
'ai.chat.managerAllChatsTab': '全部會話',
|
||||
'ai.chat.managerSearchPlaceholder': '搜尋會話標題…',
|
||||
'ai.chat.managerFilterAllAgents': '全部 Agent',
|
||||
'ai.chat.managerMoreActions': '更多操作',
|
||||
@@ -721,6 +721,9 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.safety.responseIdleTimeout.unit': '秒',
|
||||
'ai.safety.maxIterations': '最大迭代次數',
|
||||
'ai.safety.maxIterations.description': '防止 AI 失控執行的最大工具呼叫迴圈次數。外部 Agent 可能有自己的內部迭代限制,以其為準。',
|
||||
'ai.safety.toolOutputMaxChars': '內建 AI 工具輸出上限',
|
||||
'ai.safety.toolOutputMaxChars.description': '內建 AI 單次工具呼叫(例如終端機指令或 SFTP 讀取)直接傳回的最大字元數,超出時會截斷並將完整輸出儲存為可讀取的控制碼(2,000–200,000)。',
|
||||
'ai.safety.toolOutputMaxChars.unit': '字元',
|
||||
'ai.safety.blocklist': '指令黑名單',
|
||||
'ai.safety.blocklist.description': '用於攔截透過 Netcatty 執行的危險指令的正規表示式。',
|
||||
'ai.safety.blocklist.placeholder': '正規表示式...',
|
||||
|
||||
@@ -482,7 +482,7 @@ export const zhTWCoreMessages: Messages = {
|
||||
'settings.appearance.themeColor.dark': '深色主題',
|
||||
'settings.appearance.customCss': '自訂 CSS',
|
||||
'settings.appearance.customCss.desc':
|
||||
'使用自訂 CSS 個人化介面,修改會立即生效。選取的頂部分頁(`.top-tab[data-active="true"]`)會讀取 `--top-tab-active-bg`、`--top-tab-active-fg` 和 `--top-tab-active-border`。不設定則維持目前外觀。',
|
||||
'使用自訂 CSS 個人化介面,修改會立即生效。',
|
||||
'settings.appearance.customCss.help.ariaLabel': '自訂 CSS 說明',
|
||||
'settings.appearance.customCss.help.title': '自訂 CSS 說明',
|
||||
'settings.appearance.customCss.help.body': `主要 UI 區塊都公開了 \`data-section\` 屬性,供你用 CSS 定位。編輯後會立即生效。
|
||||
@@ -1167,6 +1167,8 @@ Vaults 分頁維持扁平,不使用這塊背景。
|
||||
'sftp.encoding.auto': '自動',
|
||||
'sftp.encoding.utf8': 'UTF-8',
|
||||
'sftp.encoding.gb18030': 'GB18030',
|
||||
'sftp.goBack': '後退',
|
||||
'sftp.goForward': '前進',
|
||||
'sftp.goHome': '返回主目錄',
|
||||
'sftp.goRoot': '回到根目錄',
|
||||
'sftp.folderName': '資料夾名稱',
|
||||
|
||||
@@ -13,7 +13,9 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'terminal.directory.refresh': '重新整理',
|
||||
'terminal.directory.unavailable': '此工作階段暫不支援目錄導覽。',
|
||||
'terminal.directory.integrationUnavailable': 'PowerShell 目錄整合尚未就緒,啟動參數或執行原則可能阻止載入。',
|
||||
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 工作階段回報目前目錄。',
|
||||
'terminal.directory.nonFilesystem': '目前 PowerShell 位置不是檔案系統目錄。',
|
||||
'terminal.directory.accessDenied': '沒有權限列出此目錄。',
|
||||
'terminal.directory.busy': '請等待終端回到空白命令提示字元。',
|
||||
'terminal.directory.readFailed': '無法讀取此目錄,請重新整理後重試。',
|
||||
'terminal.directory.changeFailed': '未能確認目錄切換,請重新整理後重試。',
|
||||
@@ -97,6 +99,9 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'history.clearAll.dialog.confirm': '全部清空',
|
||||
// SFTP File Opener
|
||||
'sftp.context.copyPath': '複製檔案路徑',
|
||||
'sftp.context.insertPathToTerminal': '插入路徑到終端機',
|
||||
'sftp.context.cdInTerminal': '在終端機中開啟 (cd)',
|
||||
'sftp.terminal.insertBlockedUnsafeQuote': '終端機游標位於未閉合的引號或跳脫字元內,無法安全插入路徑',
|
||||
'sftp.context.openWith': '開啟方式...',
|
||||
'sftp.context.edit': '編輯',
|
||||
'sftp.opener.title': '開啟方式',
|
||||
@@ -220,6 +225,13 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'settings.sftp.packedDownload': '打包下載',
|
||||
'settings.sftp.packedDownload.enable': '下載資料夾或多個項目時打包',
|
||||
'settings.sftp.packedDownload.enableDesc': '一次傳回所選內容,並在本機自動還原原本的資料夾結構。若伺服器不支援打包,會自動逐檔下載。',
|
||||
'settings.sftp.downloadLocation': '下載位置',
|
||||
'settings.sftp.downloadLocation.directory': '預設下載資料夾',
|
||||
'settings.sftp.downloadLocation.directoryDesc': '下載 SFTP 檔案時,儲存對話框預設開啟此資料夾。未設定或資料夾已不存在時,使用系統「下載」資料夾。',
|
||||
'settings.sftp.downloadLocation.systemDefault': '系統「下載」資料夾',
|
||||
'settings.sftp.downloadLocation.browse': '瀏覽…',
|
||||
'settings.sftp.downloadLocation.reset': '恢復為系統「下載」資料夾',
|
||||
'settings.sftp.downloadLocation.select': '選擇預設下載資料夾',
|
||||
|
||||
'settings.sftp.skipUnchanged.enable': '跳過未改檔案',
|
||||
'settings.sftp.skipUnchanged.enableDesc': '當目標檔案的大小與修改時間已與來源一致時跳過傳輸(類似 rsync)。替換到暫存路徑時自動停用。',
|
||||
@@ -590,6 +602,7 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'settings.shortcuts.binding.close-tab': '關閉分頁',
|
||||
'settings.shortcuts.binding.close-session': '關閉工作階段窗格',
|
||||
'settings.shortcuts.binding.new-tab': '新增本機分頁',
|
||||
'settings.shortcuts.binding.reopen-closed-tab': '重新開啟關閉的分頁',
|
||||
'settings.shortcuts.binding.copy': '從終端複製',
|
||||
'settings.shortcuts.binding.paste': '貼上到終端',
|
||||
'settings.shortcuts.binding.paste-selection': '將選區貼上到終端',
|
||||
|
||||
@@ -408,6 +408,8 @@ export const zhTWVaultMessages: Messages = {
|
||||
'localShell.field.shellResolved': '啟動 {command}',
|
||||
'localShell.field.startDir': '啟動目錄',
|
||||
'localShell.field.startDirPlaceholder': '繼承全域起始目錄(未設定時為主目錄)',
|
||||
'localShell.field.startupCommandPlaceholder': 'Shell 啟動後執行的指令(例如:npm run dev)',
|
||||
'localShell.field.startupCommandDesc': '本地 Shell 在啟動目錄開啟後自動執行該指令。',
|
||||
'localShell.saveAndConnect': '儲存並開啟',
|
||||
|
||||
'hostDetails.plugin.title': '外掛程式連線',
|
||||
|
||||
@@ -138,6 +138,52 @@ test('DebouncedBackupMirror flushNow writes the pending payload immediately', ()
|
||||
assert.deepEqual(writes, ['{"gen":1}']);
|
||||
});
|
||||
|
||||
test('DebouncedBackupMirror defers lazy serializer execution until debounce timer or flushNow fires', async () => {
|
||||
const writes: string[] = [];
|
||||
const serialized: number[] = [];
|
||||
const mirror = new DebouncedBackupMirror((json) => writes.push(json), 15);
|
||||
|
||||
mirror.schedule(() => {
|
||||
serialized.push(1);
|
||||
return '{"gen":1}';
|
||||
});
|
||||
mirror.schedule(() => {
|
||||
serialized.push(2);
|
||||
return '{"gen":2}';
|
||||
});
|
||||
// Neither producer runs synchronously during burst scheduling.
|
||||
assert.deepEqual(serialized, []);
|
||||
assert.deepEqual(writes, []);
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 35));
|
||||
// Only the final producer in the burst is invoked when the timer fires.
|
||||
assert.deepEqual(serialized, [2]);
|
||||
assert.deepEqual(writes, ['{"gen":2}']);
|
||||
|
||||
// flushNow invokes only the pending lazy producer immediately; reset discards without calling it.
|
||||
mirror.schedule(() => {
|
||||
serialized.push(3);
|
||||
return '{"gen":3}';
|
||||
});
|
||||
mirror.schedule(() => {
|
||||
serialized.push(4);
|
||||
return '{"gen":4}';
|
||||
});
|
||||
assert.deepEqual(serialized, [2]);
|
||||
mirror.flushNow();
|
||||
assert.deepEqual(serialized, [2, 4]);
|
||||
assert.deepEqual(writes, ['{"gen":2}', '{"gen":4}']);
|
||||
|
||||
mirror.schedule(() => {
|
||||
serialized.push(5);
|
||||
return '{"gen":5}';
|
||||
});
|
||||
mirror.reset();
|
||||
await new Promise((resolve) => setTimeout(resolve, 30));
|
||||
assert.deepEqual(serialized, [2, 4]);
|
||||
assert.deepEqual(writes, ['{"gen":2}', '{"gen":4}']);
|
||||
});
|
||||
|
||||
test('readLiveSessionsArray treats non-array JSON as empty (corrupt)', () => {
|
||||
assert.deepEqual(readLiveSessionsArray(null), []);
|
||||
assert.deepEqual(readLiveSessionsArray(''), []);
|
||||
|
||||
@@ -119,28 +119,37 @@ export function mergeImportedSessions(current: AISession[], imported: AISession[
|
||||
return Array.from(byId.values()).sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0));
|
||||
}
|
||||
|
||||
export type BackupMirrorInput = string | (() => string);
|
||||
|
||||
/**
|
||||
* Debounced mirror scheduler. One rolling timer per process: the last
|
||||
* mutation batch wins, and the write happens `debounceMs` after the batch
|
||||
* settles (at most once per batch, per the durability spec).
|
||||
* Accepts either a pre-serialized JSON string or a lazy serializer invoked
|
||||
* only when the debounce timer or `flushNow()` actually runs.
|
||||
*/
|
||||
export class DebouncedBackupMirror {
|
||||
private timer: ReturnType<typeof setTimeout> | null = null;
|
||||
private pendingJson: string | null = null;
|
||||
private pendingInput: BackupMirrorInput | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly write: (json: string) => void,
|
||||
private readonly debounceMs: number = AI_SESSIONS_BACKUP_DEBOUNCE_MS,
|
||||
) {}
|
||||
|
||||
schedule(json: string) {
|
||||
this.pendingJson = json;
|
||||
private emit(input: BackupMirrorInput) {
|
||||
const json = typeof input === 'function' ? input() : input;
|
||||
this.write(json);
|
||||
}
|
||||
|
||||
schedule(input: BackupMirrorInput) {
|
||||
this.pendingInput = input;
|
||||
if (this.timer) clearTimeout(this.timer);
|
||||
this.timer = setTimeout(() => {
|
||||
this.timer = null;
|
||||
const json = this.pendingJson;
|
||||
this.pendingJson = null;
|
||||
if (json != null) this.write(json);
|
||||
const pending = this.pendingInput;
|
||||
this.pendingInput = null;
|
||||
if (pending != null) this.emit(pending);
|
||||
}, this.debounceMs);
|
||||
}
|
||||
|
||||
@@ -149,14 +158,14 @@ export class DebouncedBackupMirror {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
const json = this.pendingJson;
|
||||
this.pendingJson = null;
|
||||
if (json != null) this.write(json);
|
||||
const pending = this.pendingInput;
|
||||
this.pendingInput = null;
|
||||
if (pending != null) this.emit(pending);
|
||||
}
|
||||
|
||||
reset() {
|
||||
if (this.timer) clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
this.pendingJson = null;
|
||||
this.pendingInput = null;
|
||||
}
|
||||
}
|
||||
@@ -847,3 +847,75 @@ test('rewriting the same sessions array skips re-serialization and store writes'
|
||||
__resetIdbPersistenceForTests();
|
||||
}
|
||||
});
|
||||
|
||||
test('writeSessionsForStorage defers backup JSON.stringify during bursts and skips unchanged rewrites when sync is disabled', async (t) => {
|
||||
const {
|
||||
writeSessionsForStorage,
|
||||
flushBackupMirror,
|
||||
__flushIdbWritesForTests,
|
||||
__resetBackupMirrorForTests,
|
||||
__resetIdbPersistenceForTests,
|
||||
} = await import('./aiStateSnapshots');
|
||||
__resetBackupMirrorForTests();
|
||||
__resetIdbPersistenceForTests();
|
||||
const idb = installFakeIndexedDb();
|
||||
const backupWrites: string[] = [];
|
||||
const previousWindow = globalThis.window;
|
||||
Object.defineProperty(globalThis, 'window', {
|
||||
configurable: true,
|
||||
value: {
|
||||
netcatty: {
|
||||
aiSessionsBackupWrite: async (payload: { json: string }) => {
|
||||
backupWrites.push(payload.json);
|
||||
return { ok: true };
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
// Default syncEnabled=false path: pruneSessionsForStorage allocates a new array each call.
|
||||
t.mock.method(localStorageAdapter, 'read', () => null);
|
||||
t.mock.method(localStorageAdapter, 'writeString', () => true);
|
||||
try {
|
||||
const stringify = t.mock.method(JSON, 'stringify');
|
||||
const a1 = makeSession('chat-a', 1, [{ id: 'm1', role: 'assistant', content: 'chunk 1', timestamp: 1 }]);
|
||||
const b = makeSession('chat-b', 0, []);
|
||||
const a2 = makeSession('chat-a', 2, [{ id: 'm1', role: 'assistant', content: 'chunk 1+2', timestamp: 2 }]);
|
||||
const a3 = makeSession('chat-a', 3, [{ id: 'm1', role: 'assistant', content: 'chunk 1+2+3', timestamp: 3 }]);
|
||||
|
||||
// Streaming persist burst: 3 consecutive writes must perform 0 eager JSON.stringify calls.
|
||||
assert.equal(writeSessionsForStorage([a1, b]), true);
|
||||
assert.equal(writeSessionsForStorage([a2, b]), true);
|
||||
assert.equal(writeSessionsForStorage([a3, b]), true);
|
||||
assert.equal(stringify.mock.callCount(), 0, 'JSON.stringify must not run eagerly on writeSessionsForStorage');
|
||||
assert.equal(backupWrites.length, 0);
|
||||
|
||||
// Flushing the debounced mirror serializes only the latest persisted snapshot once.
|
||||
flushBackupMirror();
|
||||
assert.equal(stringify.mock.callCount(), 1);
|
||||
assert.equal(backupWrites.length, 1);
|
||||
const flushed = JSON.parse(backupWrites[0]) as AISession[];
|
||||
assert.equal(flushed.find((s) => s.id === 'chat-a')?.messages[0]?.content, 'chunk 1+2+3');
|
||||
|
||||
// Rewriting unchanged sessions with syncEnabled=false (fresh array from pruneSessionsForStorage)
|
||||
// must NOT schedule a redundant mirror or run JSON.stringify on flush.
|
||||
assert.equal(writeSessionsForStorage([a3, b]), true);
|
||||
flushBackupMirror();
|
||||
assert.equal(stringify.mock.callCount(), 1, 'unchanged sessions must not re-schedule mirror when sync is disabled');
|
||||
assert.equal(backupWrites.length, 1);
|
||||
|
||||
// Removing a session still schedules and mirrors the updated set.
|
||||
assert.equal(writeSessionsForStorage([a3], { deletedSessionIds: ['chat-b'] }), true);
|
||||
assert.equal(stringify.mock.callCount(), 1, 'deletion backup serialization is also deferred until flush/debounce');
|
||||
flushBackupMirror();
|
||||
assert.equal(stringify.mock.callCount(), 2);
|
||||
assert.equal(backupWrites.length, 2);
|
||||
assert.deepEqual((JSON.parse(backupWrites[1]) as AISession[]).map((s) => s.id), ['chat-a']);
|
||||
|
||||
await __flushIdbWritesForTests();
|
||||
} finally {
|
||||
idb.restore();
|
||||
__resetBackupMirrorForTests();
|
||||
__resetIdbPersistenceForTests();
|
||||
Object.defineProperty(globalThis, 'window', { configurable: true, value: previousWindow });
|
||||
}
|
||||
});
|
||||
@@ -29,7 +29,7 @@ import {
|
||||
import { emitAIStateChanged } from './aiStateEvents';
|
||||
import { peekAgentRuntimeCleanup } from '../../infrastructure/ai/harness/agentRuntimeHandle';
|
||||
import { setReversibleModelPrivacy } from '../../infrastructure/ai/harness/modelSecretRedaction';
|
||||
import { DebouncedBackupMirror, readLiveSessionsArray } from './aiSessionsBackup';
|
||||
import { DebouncedBackupMirror, readLiveSessionsArray, type BackupMirrorInput } from './aiSessionsBackup';
|
||||
import {
|
||||
idbDeleteSessionIds,
|
||||
idbPutMeta,
|
||||
@@ -305,6 +305,7 @@ let idbWriteQueue: Promise<void> = Promise.resolve();
|
||||
/** Test hook: reset diff state between tests. */
|
||||
export function __resetIdbPersistenceForTests() {
|
||||
lastPersistedSessionsById = new Map();
|
||||
lastMirroredSessions = null;
|
||||
idbWriteQueue = Promise.resolve();
|
||||
// Tests swap the fake indexedDB factory between cases; the cached open
|
||||
// handle must not survive the swap.
|
||||
@@ -429,12 +430,13 @@ export function flushBackupMirror() {
|
||||
export function __resetBackupMirrorForTests() {
|
||||
backupMirror.reset();
|
||||
aiSessionsBackupRecoveryPending = false;
|
||||
lastMirroredSessions = null;
|
||||
}
|
||||
|
||||
export function scheduleBackupMirror(json: string) {
|
||||
export function scheduleBackupMirror(input: BackupMirrorInput) {
|
||||
if (aiSessionsBackupRecoveryPending) return;
|
||||
try {
|
||||
backupMirror.schedule(json);
|
||||
backupMirror.schedule(input);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
@@ -503,9 +505,11 @@ export function writeSessionsForStorage(
|
||||
const removedIds = Array.from(prevById.keys()).filter(id => !persistedIds.has(id));
|
||||
lastPersistedSessionsById = new Map(persisted.map(session => [session.id, session]));
|
||||
|
||||
if (changed.length > 0 || removedIds.length > 0 || lastMirroredSessions !== persisted) {
|
||||
scheduleBackupMirror(JSON.stringify(persisted));
|
||||
lastMirroredSessions = persisted;
|
||||
if (changed.length > 0 || removedIds.length > 0 || lastMirroredSessions === null) {
|
||||
if (!aiSessionsBackupRecoveryPending) {
|
||||
scheduleBackupMirror(() => JSON.stringify(persisted));
|
||||
lastMirroredSessions = persisted;
|
||||
}
|
||||
}
|
||||
queueIdbSessionSync(changed, removedIds, prevById, persisted);
|
||||
return true;
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
* and detached terminal popups) shares the same clear semantics.
|
||||
*/
|
||||
|
||||
import { tokenizeShellLike } from "../../domain/shellTokenizer";
|
||||
import { localStorageAdapter } from "../../infrastructure/persistence/localStorageAdapter";
|
||||
import {
|
||||
STORAGE_KEY_COMMAND_HISTORY,
|
||||
@@ -499,55 +500,6 @@ function normalizeArgumentToken(token: string): string {
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function tokenizeShellLike(input: string): string[] {
|
||||
const tokens: string[] = [];
|
||||
let current = "";
|
||||
let inSingleQuote = false;
|
||||
let inDoubleQuote = false;
|
||||
let escaped = false;
|
||||
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
const ch = input[i];
|
||||
|
||||
if (escaped) {
|
||||
current += ch;
|
||||
escaped = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === "\\") {
|
||||
escaped = true;
|
||||
current += ch;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === "'" && !inDoubleQuote) {
|
||||
inSingleQuote = !inSingleQuote;
|
||||
current += ch;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === '"' && !inSingleQuote) {
|
||||
inDoubleQuote = !inDoubleQuote;
|
||||
current += ch;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === " " && !inSingleQuote && !inDoubleQuote) {
|
||||
if (current.length > 0) {
|
||||
tokens.push(current);
|
||||
current = "";
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
current += ch;
|
||||
}
|
||||
|
||||
tokens.push(current);
|
||||
return tokens;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute a fuzzy match score. Returns 0 for no match.
|
||||
* Higher score = better match quality.
|
||||
|
||||
@@ -7,12 +7,20 @@ test('plugin theme tokens come from the themed app surface style', () => {
|
||||
assert.deepEqual(selectPluginThemeTokens({
|
||||
'--background': '220 10% 10%',
|
||||
'--foreground': '0 0% 98%',
|
||||
'--card': '220 10% 12%',
|
||||
'--primary': '210 90% 55%',
|
||||
'--destructive': '0 84% 60%',
|
||||
'--radius': '0.5rem',
|
||||
'--font-mono': '"JetBrains Mono", monospace',
|
||||
colorScheme: 'dark',
|
||||
'--unknown-plugin-token': 'ignored',
|
||||
}), {
|
||||
'--background': '220 10% 10%',
|
||||
'--foreground': '0 0% 98%',
|
||||
'--card': '220 10% 12%',
|
||||
'--primary': '210 90% 55%',
|
||||
'--destructive': '0 84% 60%',
|
||||
'--radius': '0.5rem',
|
||||
'--font-mono': '"JetBrains Mono", monospace',
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,26 @@
|
||||
export const PLUGIN_THEME_TOKEN_NAMES = Object.freeze([
|
||||
'--background',
|
||||
'--foreground',
|
||||
'--muted',
|
||||
'--muted-foreground',
|
||||
'--border',
|
||||
'--card',
|
||||
'--card-foreground',
|
||||
'--popover',
|
||||
'--popover-foreground',
|
||||
'--primary',
|
||||
'--primary-foreground',
|
||||
'--secondary',
|
||||
'--secondary-foreground',
|
||||
'--muted',
|
||||
'--muted-foreground',
|
||||
'--accent',
|
||||
'--accent-foreground',
|
||||
'--destructive',
|
||||
'--destructive-foreground',
|
||||
'--border',
|
||||
'--input',
|
||||
'--ring',
|
||||
'--radius',
|
||||
'--font-sans',
|
||||
'--font-mono',
|
||||
] as const);
|
||||
|
||||
export function selectPluginThemeTokens(
|
||||
|
||||
@@ -3,10 +3,15 @@ import test from 'node:test';
|
||||
|
||||
import {
|
||||
collectPluginTerminalProviderKinds,
|
||||
createWindowPluginTerminalProviderRegistry,
|
||||
isPluginTerminalProviderKindAvailable,
|
||||
PluginTerminalProviderAvailability,
|
||||
PluginTerminalProviderRegistry,
|
||||
} from './pluginTerminalProviderRegistry.ts';
|
||||
import {
|
||||
_resetSharedPluginRuntimeStatusForTests,
|
||||
getSharedPluginRuntimeStatus,
|
||||
} from './pluginRuntimeStatusCache.ts';
|
||||
|
||||
const session: NetcattyTerminalSessionSnapshot = {
|
||||
sessionId: 'session-1',
|
||||
@@ -430,3 +435,142 @@ test('terminal Provider registry forwards contribution lifecycle invalidation',
|
||||
registry.dispose();
|
||||
assert.equal(disposed, true);
|
||||
});
|
||||
|
||||
test('terminal Provider registry short-circuits cloning, snapshots, and IPC when plugin runtime is disabled, and re-probes on contribution change', async (t) => {
|
||||
_resetSharedPluginRuntimeStatusForTests();
|
||||
let changed: (() => void) | undefined;
|
||||
let available = false;
|
||||
let statusCalls = 0;
|
||||
let listCalls = 0;
|
||||
let lifecycleCalls = 0;
|
||||
const requests: NetcattyTerminalProviderRequest[] = [];
|
||||
const events: NetcattyTerminalSessionEvent[] = [];
|
||||
|
||||
const registry = new PluginTerminalProviderRegistry({
|
||||
async getPluginRuntimeStatus() {
|
||||
statusCalls += 1;
|
||||
return { available } as NetcattyPluginRuntimeStatus;
|
||||
},
|
||||
async listPluginTerminalProviders() {
|
||||
listCalls += 1;
|
||||
return [{
|
||||
pluginId: 'com.example.matcher',
|
||||
pluginVersion: '1.0.0',
|
||||
pluginDisplayName: 'Matcher',
|
||||
provider: {
|
||||
id: 'com.example.matcher.output',
|
||||
label: 'Output matcher',
|
||||
kind: 'terminal.matcher',
|
||||
},
|
||||
}];
|
||||
},
|
||||
async providePluginTerminal(request) {
|
||||
requests.push(request);
|
||||
return [];
|
||||
},
|
||||
async cancelPluginTerminalRequest() { return false; },
|
||||
async publishPluginTerminalSessionEvent(event) {
|
||||
lifecycleCalls += 1;
|
||||
events.push(event);
|
||||
return [];
|
||||
},
|
||||
onPluginContributionsChanged(listener) {
|
||||
changed = listener;
|
||||
return () => {};
|
||||
},
|
||||
});
|
||||
|
||||
const cloneSpy = t.mock.method(globalThis, 'structuredClone');
|
||||
try {
|
||||
// Parallel provider enumerations coalesce onto one runtime status check and make 0 provider IPCs.
|
||||
const [matchers, links] = await Promise.all([
|
||||
registry.listProviders({ kind: 'terminal.matcher' }),
|
||||
registry.listProviders({ kind: 'terminal.link' }),
|
||||
]);
|
||||
assert.deepEqual(matchers, []);
|
||||
assert.deepEqual(links, []);
|
||||
assert.equal(statusCalls, 1);
|
||||
assert.equal(listCalls, 0);
|
||||
assert.equal(cloneSpy.mock.callCount(), 0);
|
||||
|
||||
// Lifecycle events while disabled must not clone, snapshot, or call IPC.
|
||||
await registry.publishSessionEvent({
|
||||
type: 'created',
|
||||
session: { ...session, cwd: '/must-not-be-retained', title: 'Hidden title' },
|
||||
});
|
||||
await registry.publishSessionEvent({
|
||||
type: 'cwdChanged',
|
||||
session: { ...session, cwd: '/also-not-retained' },
|
||||
});
|
||||
await registry.publishSessionEvent({
|
||||
type: 'resized',
|
||||
session: { ...session, cols: 120, rows: 40 },
|
||||
});
|
||||
assert.equal(statusCalls, 1);
|
||||
assert.equal(lifecycleCalls, 0);
|
||||
assert.equal(cloneSpy.mock.callCount(), 0, '0 structuredClone calls when plugin host is disabled');
|
||||
|
||||
// Dev-mode hot-enable: onPluginContributionsChanged invalidates cached status and re-probes.
|
||||
available = true;
|
||||
changed?.();
|
||||
|
||||
// Verify no stale session snapshot was retained while disabled.
|
||||
await registry.request({ kind: 'terminal.completion', operation: 'provide', session });
|
||||
assert.equal(Object.hasOwn(requests[0].session, 'cwd'), false, 'disabled publishSessionEvent must not grow #sessionSnapshots');
|
||||
assert.equal(Object.hasOwn(requests[0].session, 'title'), false);
|
||||
|
||||
const enabledProviders = await registry.listProviders({ kind: 'terminal.matcher' });
|
||||
assert.equal(statusCalls, 2, 'onPluginContributionsChanged invalidates shared runtime status cache');
|
||||
assert.equal(listCalls, 1);
|
||||
assert.equal(enabledProviders.length, 1);
|
||||
|
||||
await registry.publishSessionEvent({ type: 'connected', session: { ...session, cwd: '/live' } });
|
||||
assert.equal(lifecycleCalls, 1);
|
||||
assert.equal(events[0].session.cwd, '/live');
|
||||
} finally {
|
||||
registry.dispose();
|
||||
_resetSharedPluginRuntimeStatusForTests();
|
||||
}
|
||||
});
|
||||
|
||||
test('createWindowPluginTerminalProviderRegistry shares runtime status cache with the window bridge', async (t) => {
|
||||
_resetSharedPluginRuntimeStatusForTests();
|
||||
let statusCalls = 0;
|
||||
let listCalls = 0;
|
||||
let lifecycleCalls = 0;
|
||||
const mockBridge = {
|
||||
async getPluginRuntimeStatus() {
|
||||
statusCalls += 1;
|
||||
return { available: false };
|
||||
},
|
||||
async listPluginTerminalProviders() {
|
||||
listCalls += 1;
|
||||
return [];
|
||||
},
|
||||
async providePluginTerminal() { return []; },
|
||||
async cancelPluginTerminalRequest() { return false; },
|
||||
async publishPluginTerminalSessionEvent() {
|
||||
lifecycleCalls += 1;
|
||||
return [];
|
||||
},
|
||||
} as unknown as NetcattyBridge;
|
||||
|
||||
// Pre-populate shared runtime status cache (as usePluginContributions does on mount).
|
||||
assert.deepEqual(await getSharedPluginRuntimeStatus(mockBridge), { available: false });
|
||||
assert.equal(statusCalls, 1);
|
||||
|
||||
const cloneSpy = t.mock.method(globalThis, 'structuredClone');
|
||||
const registry = createWindowPluginTerminalProviderRegistry(mockBridge);
|
||||
assert.ok(registry);
|
||||
try {
|
||||
assert.deepEqual(await registry.listProviders({ kind: 'terminal.matcher' }), []);
|
||||
await registry.publishSessionEvent({ type: 'created', session });
|
||||
assert.equal(statusCalls, 1, 'reuses cached runtime status from window bridge without extra IPC');
|
||||
assert.equal(listCalls, 0);
|
||||
assert.equal(lifecycleCalls, 0);
|
||||
assert.equal(cloneSpy.mock.callCount(), 0);
|
||||
} finally {
|
||||
registry.dispose();
|
||||
_resetSharedPluginRuntimeStatusForTests();
|
||||
}
|
||||
});
|
||||
@@ -1,8 +1,14 @@
|
||||
import {
|
||||
getSharedPluginRuntimeStatus,
|
||||
invalidateSharedPluginRuntimeStatus,
|
||||
} from './pluginRuntimeStatusCache';
|
||||
|
||||
export interface PluginTerminalProviderBridge {
|
||||
listPluginTerminalProviders(options: NetcattyTerminalProviderQuery): Promise<ReadonlyArray<NetcattyTerminalProviderContribution>>;
|
||||
providePluginTerminal(request: NetcattyTerminalProviderRequest): Promise<ReadonlyArray<NetcattyTerminalProviderResult>>;
|
||||
cancelPluginTerminalRequest(requestId: string): Promise<boolean>;
|
||||
publishPluginTerminalSessionEvent(event: NetcattyTerminalSessionEvent): Promise<ReadonlyArray<{ pluginId: string; delivered: boolean }>>;
|
||||
getPluginRuntimeStatus?(): Promise<NetcattyPluginRuntimeStatus>;
|
||||
onPluginContributionsChanged?(callback: () => void): () => void;
|
||||
}
|
||||
|
||||
@@ -52,6 +58,7 @@ function mergeLifecycleSessionSnapshot(
|
||||
|
||||
export class PluginTerminalProviderRegistry {
|
||||
readonly #bridge: PluginTerminalProviderBridge;
|
||||
readonly #statusBridge: Pick<NetcattyBridge, 'getPluginRuntimeStatus'>;
|
||||
readonly #activeRequests = new Map<string, string>();
|
||||
readonly #sessionSnapshots = new Map<string, NetcattyTerminalSessionSnapshot>();
|
||||
readonly #providerListeners = new Set<() => void>();
|
||||
@@ -62,11 +69,16 @@ export class PluginTerminalProviderRegistry {
|
||||
#bridgeAvailability: 'unknown' | 'available' | 'unavailable' = 'unknown';
|
||||
#disposed = false;
|
||||
|
||||
constructor(bridge: PluginTerminalProviderBridge) {
|
||||
constructor(
|
||||
bridge: PluginTerminalProviderBridge,
|
||||
statusBridge: Pick<NetcattyBridge, 'getPluginRuntimeStatus'> = bridge,
|
||||
) {
|
||||
this.#bridge = bridge;
|
||||
this.#statusBridge = statusBridge;
|
||||
this.#disposeContributionListener = bridge.onPluginContributionsChanged?.(() => {
|
||||
this.#providerListGeneration += 1;
|
||||
this.#bridgeAvailability = 'unknown';
|
||||
invalidateSharedPluginRuntimeStatus(this.#statusBridge);
|
||||
this.#providerListCache.clear();
|
||||
this.#pendingProviderLists.clear();
|
||||
for (const requestId of this.#activeRequests.values()) {
|
||||
@@ -79,6 +91,33 @@ export class PluginTerminalProviderRegistry {
|
||||
});
|
||||
}
|
||||
|
||||
#isUnavailable(): boolean {
|
||||
return this.#disposed || this.#bridgeAvailability === 'unavailable';
|
||||
}
|
||||
|
||||
async #probeRuntimeStatus(generation: number): Promise<boolean> {
|
||||
try {
|
||||
const status = await getSharedPluginRuntimeStatus(this.#statusBridge);
|
||||
if (this.#disposed) return false;
|
||||
if (generation !== this.#providerListGeneration) {
|
||||
return this.#bridgeAvailability !== 'unavailable';
|
||||
}
|
||||
if (!status.available) {
|
||||
this.#bridgeAvailability = 'unavailable';
|
||||
this.#providerListCache.clear();
|
||||
return false;
|
||||
}
|
||||
this.#bridgeAvailability = 'available';
|
||||
return true;
|
||||
} catch {
|
||||
if (!this.#disposed && generation === this.#providerListGeneration) {
|
||||
this.#bridgeAvailability = 'unavailable';
|
||||
this.#providerListCache.clear();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
onDidChangeProviders(listener: () => void): () => void {
|
||||
if (this.#disposed) return () => {};
|
||||
this.#providerListeners.add(listener);
|
||||
@@ -96,6 +135,16 @@ export class PluginTerminalProviderRegistry {
|
||||
const generation = this.#providerListGeneration;
|
||||
const request = (async () => {
|
||||
try {
|
||||
if (
|
||||
this.#bridgeAvailability === 'unknown'
|
||||
&& typeof this.#statusBridge.getPluginRuntimeStatus === 'function'
|
||||
) {
|
||||
const available = await this.#probeRuntimeStatus(generation);
|
||||
if (!available) return Object.freeze([]);
|
||||
}
|
||||
if (this.#isUnavailable()) {
|
||||
return Object.freeze([]);
|
||||
}
|
||||
const providers = freezeValue(await this.#bridge.listPluginTerminalProviders(query));
|
||||
if (generation === this.#providerListGeneration) {
|
||||
if (this.#bridgeAvailability !== 'unavailable') this.#bridgeAvailability = 'available';
|
||||
@@ -206,11 +255,21 @@ export class PluginTerminalProviderRegistry {
|
||||
|
||||
async publishSessionEvent(event: NetcattyTerminalSessionEvent): Promise<void> {
|
||||
if (this.#disposed) return;
|
||||
// Short-circuit BEFORE mergeLifecycleSessionSnapshot so disabled plugin
|
||||
// hosts never run structuredClone/Object.freeze or retain session snapshots.
|
||||
if (this.#bridgeAvailability === 'unavailable') return;
|
||||
if (
|
||||
this.#bridgeAvailability === 'unknown'
|
||||
&& typeof this.#statusBridge.getPluginRuntimeStatus === 'function'
|
||||
) {
|
||||
const available = await this.#probeRuntimeStatus(this.#providerListGeneration);
|
||||
if (!available) return;
|
||||
}
|
||||
if (this.#isUnavailable()) return;
|
||||
const previous = this.#sessionSnapshots.get(event.session.sessionId);
|
||||
const session = mergeLifecycleSessionSnapshot(previous, event);
|
||||
if (event.type === 'disposed') this.#sessionSnapshots.delete(session.sessionId);
|
||||
else this.#sessionSnapshots.set(session.sessionId, session);
|
||||
if (this.#bridgeAvailability === 'unavailable') return;
|
||||
try {
|
||||
await this.#bridge.publishPluginTerminalSessionEvent(freezeValue({ ...event, session }));
|
||||
this.#bridgeAvailability = 'available';
|
||||
@@ -302,10 +361,13 @@ export function createWindowPluginTerminalProviderRegistry(
|
||||
providePluginTerminal: (request) => bridge.providePluginTerminal!(request),
|
||||
cancelPluginTerminalRequest: (requestId) => bridge.cancelPluginTerminalRequest!(requestId),
|
||||
publishPluginTerminalSessionEvent: (event) => bridge.publishPluginTerminalSessionEvent!(event),
|
||||
getPluginRuntimeStatus: bridge.getPluginRuntimeStatus
|
||||
? () => bridge.getPluginRuntimeStatus!()
|
||||
: undefined,
|
||||
onPluginContributionsChanged: bridge.onPluginContributionsChanged
|
||||
? (callback) => bridge.onPluginContributionsChanged!(callback)
|
||||
: undefined,
|
||||
});
|
||||
}, bridge);
|
||||
}
|
||||
|
||||
let windowRegistry: PluginTerminalProviderRegistry | null | undefined;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createPluginRemoteTree } from './pluginRemoteTree';
|
||||
import { registerLoadedPluginViewSessions } from './pluginViewSessionRegistry';
|
||||
import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs';
|
||||
import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
|
||||
|
||||
@@ -37,14 +38,23 @@ export class PluginViewSessions {
|
||||
void bridge.openHostDrawnPluginView({ ...request, instanceId: id }).then(() => {
|
||||
if (disposed) void bridge.closeHostDrawnPluginView?.(id).catch(() => {});
|
||||
}).catch(() => dispose(true));
|
||||
const imageCache = new Map<string, Promise<string>>();
|
||||
return {
|
||||
viewId: request.viewId,
|
||||
scope: request.scopeId,
|
||||
image: async (path: string) => {
|
||||
if (disposed || !bridge.getPluginViewResource) throw new Error('Plugin image unavailable');
|
||||
const result = await bridge.getPluginViewResource({ instanceId: id, path });
|
||||
if (disposed) throw new Error('Plugin view closed');
|
||||
return result.url;
|
||||
image: (path: string) => {
|
||||
if (disposed || !bridge.getPluginViewResource) return Promise.reject(new Error('Plugin image unavailable'));
|
||||
const existing = imageCache.get(path);
|
||||
if (existing) return existing;
|
||||
const pending = bridge.getPluginViewResource({ instanceId: id, path }).then((result) => {
|
||||
if (disposed) throw new Error('Plugin view closed');
|
||||
return result.url;
|
||||
}).catch((error) => {
|
||||
if (imageCache.get(path) === pending) imageCache.delete(path);
|
||||
throw error;
|
||||
});
|
||||
imageCache.set(path, pending);
|
||||
return pending;
|
||||
},
|
||||
get idle() { return users === 0; },
|
||||
getSnapshot: () => state,
|
||||
@@ -76,3 +86,4 @@ export class PluginViewSessions {
|
||||
dispose() { for (const session of [...this.sessions.values()]) session.dispose(); }
|
||||
}
|
||||
export const pluginViewSessions = new PluginViewSessions();
|
||||
registerLoadedPluginViewSessions(pluginViewSessions);
|
||||
@@ -0,0 +1,18 @@
|
||||
type CloseablePluginViewSessions = {
|
||||
closeView(viewId: string): void;
|
||||
};
|
||||
|
||||
let loadedSessions: CloseablePluginViewSessions | null = null;
|
||||
|
||||
/**
|
||||
* Registers the live PluginViewSessions singleton once the lazy host-drawn
|
||||
* plugin view bundle loads, so startup lifecycle hooks can close views without
|
||||
* statically importing css-tree / @remote-dom/core.
|
||||
*/
|
||||
export function registerLoadedPluginViewSessions(sessions: CloseablePluginViewSessions): void {
|
||||
loadedSessions = sessions;
|
||||
}
|
||||
|
||||
export function closePluginViewSessionIfLoaded(viewId: string): void {
|
||||
loadedSessions?.closeView(viewId);
|
||||
}
|
||||
@@ -7,7 +7,9 @@ import {
|
||||
closeSessionsState,
|
||||
closeSessionWorkspaceLayoutState,
|
||||
detachSessionFromWorkspaceState,
|
||||
isPreferredTabAvailableAfterClose,
|
||||
resolveActiveTabAfterCloseSession,
|
||||
resolveActiveTabAfterCloseWorkspace,
|
||||
} from "./sessionWorkspaceDetach";
|
||||
|
||||
const session = (id: string, workspaceId = "ws-1"): TerminalSession => ({
|
||||
@@ -308,3 +310,188 @@ test("closing a subset of standalone sessions keeps tabs outside the batch", ()
|
||||
assert.deepEqual(result.sessions.map((candidate) => candidate.id), ["s1"]);
|
||||
assert.equal(result.activeTabId, undefined);
|
||||
});
|
||||
|
||||
test("issue #4249 scenario 1: closing terminal tabs right-to-left focuses B -> A -> vault", () => {
|
||||
const standaloneSession = (id: string): TerminalSession => ({
|
||||
...session(id),
|
||||
workspaceId: undefined,
|
||||
});
|
||||
|
||||
const step1 = closeSessionsState({
|
||||
sessions: [standaloneSession("a"), standaloneSession("b"), standaloneSession("c")],
|
||||
workspaces: [],
|
||||
sessionIds: ["c"],
|
||||
currentActiveTabId: "c",
|
||||
preferredTabId: "b",
|
||||
tabOrder: ["a", "b", "c"],
|
||||
});
|
||||
assert.equal(step1.activeTabId, "b");
|
||||
|
||||
const step2 = closeSessionsState({
|
||||
sessions: step1.sessions,
|
||||
workspaces: step1.workspaces,
|
||||
sessionIds: ["b"],
|
||||
currentActiveTabId: step1.activeTabId ?? null,
|
||||
preferredTabId: "b",
|
||||
tabOrder: step1.tabOrder,
|
||||
});
|
||||
assert.equal(step2.activeTabId, "a");
|
||||
|
||||
const step3 = closeSessionsState({
|
||||
sessions: step2.sessions,
|
||||
workspaces: step2.workspaces,
|
||||
sessionIds: ["a"],
|
||||
currentActiveTabId: step2.activeTabId ?? null,
|
||||
preferredTabId: "b",
|
||||
tabOrder: step2.tabOrder,
|
||||
});
|
||||
assert.equal(step3.activeTabId, "vault");
|
||||
});
|
||||
|
||||
test("issue #4249 scenario 2: after visiting vault or sftp, closing C -> B -> A stays on adjacent terminals until the last tab closes", () => {
|
||||
const standaloneSession = (id: string): TerminalSession => ({
|
||||
...session(id),
|
||||
workspaceId: undefined,
|
||||
});
|
||||
|
||||
for (const rootView of ["vault", "sftp"] as const) {
|
||||
const step1 = closeSessionsState({
|
||||
sessions: [standaloneSession("a"), standaloneSession("b"), standaloneSession("c")],
|
||||
workspaces: [],
|
||||
sessionIds: ["c"],
|
||||
currentActiveTabId: "c",
|
||||
preferredTabId: rootView,
|
||||
tabOrder: ["a", "b", "c"],
|
||||
});
|
||||
assert.equal(step1.activeTabId, "b", `closing C after ${rootView} should focus B`);
|
||||
|
||||
const step2 = closeSessionsState({
|
||||
sessions: step1.sessions,
|
||||
workspaces: step1.workspaces,
|
||||
sessionIds: ["b"],
|
||||
currentActiveTabId: step1.activeTabId ?? null,
|
||||
preferredTabId: rootView,
|
||||
tabOrder: step1.tabOrder,
|
||||
});
|
||||
assert.equal(step2.activeTabId, "a", `closing B after ${rootView} should focus A`);
|
||||
|
||||
const step3 = closeSessionsState({
|
||||
sessions: step2.sessions,
|
||||
workspaces: step2.workspaces,
|
||||
sessionIds: ["a"],
|
||||
currentActiveTabId: step2.activeTabId ?? null,
|
||||
preferredTabId: rootView,
|
||||
tabOrder: step2.tabOrder,
|
||||
});
|
||||
assert.equal(step3.activeTabId, rootView, `closing last tab A should fall back to ${rootView}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("closing a terminal tab follows visual tabOrder instead of raw session/workspace arrays", () => {
|
||||
const standaloneSession = (id: string): TerminalSession => ({
|
||||
...session(id),
|
||||
workspaceId: undefined,
|
||||
});
|
||||
|
||||
// Raw arrays have [s1, s2] and [ws-1], while visual tab order is [ws-1, s1, s2].
|
||||
const result = closeSessionsState({
|
||||
sessions: [session("ws-pane", "ws-1"), standaloneSession("s1"), standaloneSession("s2")],
|
||||
workspaces: [workspace(["ws-pane"])],
|
||||
sessionIds: ["s2"],
|
||||
currentActiveTabId: "s2",
|
||||
preferredTabId: "vault",
|
||||
tabOrder: ["ws-1", "s1", "s2"],
|
||||
});
|
||||
|
||||
// Must focus adjacent terminal s1, not jump over s1 to ws-1 or vault.
|
||||
assert.equal(result.activeTabId, "s1");
|
||||
});
|
||||
|
||||
test("closing a middle or leftmost terminal tab picks left neighbor first, then right neighbor", () => {
|
||||
const standaloneSession = (id: string): TerminalSession => ({
|
||||
...session(id),
|
||||
workspaceId: undefined,
|
||||
});
|
||||
|
||||
const closeMiddle = closeSessionsState({
|
||||
sessions: [standaloneSession("a"), standaloneSession("b"), standaloneSession("c")],
|
||||
workspaces: [],
|
||||
sessionIds: ["b"],
|
||||
currentActiveTabId: "b",
|
||||
preferredTabId: "sftp",
|
||||
tabOrder: ["a", "b", "c"],
|
||||
});
|
||||
assert.equal(closeMiddle.activeTabId, "a");
|
||||
|
||||
const closeLeftmost = closeSessionsState({
|
||||
sessions: closeMiddle.sessions,
|
||||
workspaces: [],
|
||||
sessionIds: ["a"],
|
||||
currentActiveTabId: "a",
|
||||
preferredTabId: "sftp",
|
||||
tabOrder: closeMiddle.tabOrder,
|
||||
});
|
||||
assert.equal(closeLeftmost.activeTabId, "c");
|
||||
});
|
||||
|
||||
test("resolveActiveTabAfterCloseWorkspace focuses adjacent terminal/workspace before falling back to root view", () => {
|
||||
const standaloneSession = (id: string): TerminalSession => ({
|
||||
...session(id),
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const ws1 = workspace(["p1"], { id: "ws-1" });
|
||||
|
||||
assert.equal(
|
||||
resolveActiveTabAfterCloseWorkspace({
|
||||
currentActiveTabId: "ws-1",
|
||||
closedWorkspaceId: "ws-1",
|
||||
previousWorkspaces: [ws1],
|
||||
remainingWorkspaces: [],
|
||||
remainingSessions: [standaloneSession("s1"), standaloneSession("s2")],
|
||||
tabOrder: ["s1", "ws-1", "s2"],
|
||||
preferredTabId: "sftp",
|
||||
}),
|
||||
"s1",
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
resolveActiveTabAfterCloseWorkspace({
|
||||
currentActiveTabId: "ws-1",
|
||||
closedWorkspaceId: "ws-1",
|
||||
previousWorkspaces: [ws1],
|
||||
remainingWorkspaces: [],
|
||||
remainingSessions: [],
|
||||
tabOrder: ["ws-1"],
|
||||
preferredTabId: "sftp",
|
||||
}),
|
||||
"sftp",
|
||||
);
|
||||
});
|
||||
|
||||
test("isPreferredTabAvailableAfterClose does not treat vault or sftp as surviving terminal tabs", () => {
|
||||
const standaloneSession = (id: string): TerminalSession => ({
|
||||
...session(id),
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const layoutResult = closeSessionWorkspaceLayoutState([], undefined, "c");
|
||||
const remainingSessions = [standaloneSession("a"), standaloneSession("b")];
|
||||
|
||||
assert.equal(
|
||||
isPreferredTabAvailableAfterClose({
|
||||
preferredTabId: "vault",
|
||||
closedSessionId: "c",
|
||||
layoutResult,
|
||||
remainingSessions,
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isPreferredTabAvailableAfterClose({
|
||||
preferredTabId: "sftp",
|
||||
closedSessionId: "c",
|
||||
layoutResult,
|
||||
remainingSessions,
|
||||
}),
|
||||
false,
|
||||
);
|
||||
});
|
||||
@@ -1,6 +1,10 @@
|
||||
import type { TerminalSession, Workspace } from "../../domain/models";
|
||||
import type { AIChatRecencyEntry } from "../../domain/aiSessionRecency";
|
||||
import { resolveMostRecentlyActiveMemberTerminalId } from "../../domain/aiSessionRecency";
|
||||
import {
|
||||
buildOrderedTerminalTabIds,
|
||||
resolveNextActiveTabAfterTerminalClose,
|
||||
} from "../../domain/tabCloseFocus";
|
||||
import { collectSessionIds, createEmptyWorkspaceRoot, pruneWorkspaceNode } from "../../domain/workspace";
|
||||
|
||||
export type DetachSessionFromWorkspaceStateResult = {
|
||||
@@ -128,7 +132,6 @@ export function isPreferredTabAvailableAfterClose(
|
||||
} {
|
||||
const { preferredTabId, closedSessionId, layoutResult, remainingSessions } = input;
|
||||
if (!preferredTabId || preferredTabId === closedSessionId) return false;
|
||||
if (preferredTabId === "vault" || preferredTabId === "sftp") return true;
|
||||
if (layoutResult.workspaces.some((workspace) => workspace.id === preferredTabId)) return true;
|
||||
return remainingSessions.some((session) => (
|
||||
session.id === preferredTabId
|
||||
@@ -143,6 +146,8 @@ export function resolveActiveTabAfterCloseSession({
|
||||
layoutResult,
|
||||
remainingSessions,
|
||||
preferredTabId,
|
||||
orderedTabIdsBeforeClose,
|
||||
tabOrder,
|
||||
}: {
|
||||
currentActiveTabId: string | null;
|
||||
closedSessionId: string;
|
||||
@@ -150,30 +155,61 @@ export function resolveActiveTabAfterCloseSession({
|
||||
layoutResult: CloseSessionWorkspaceLayoutResult;
|
||||
remainingSessions: readonly TerminalSession[];
|
||||
preferredTabId?: string | null;
|
||||
orderedTabIdsBeforeClose?: readonly string[];
|
||||
tabOrder?: readonly string[];
|
||||
}): string | null {
|
||||
const fallbackWorkspace = layoutResult.workspaces[layoutResult.workspaces.length - 1];
|
||||
const fallbackSolo = remainingSessions.filter((session) => !session.workspaceId && !session.hiddenFromTabs).slice(-1)[0];
|
||||
const preferredInput = {
|
||||
preferredTabId,
|
||||
closedSessionId,
|
||||
layoutResult,
|
||||
remainingSessions,
|
||||
};
|
||||
const preferredFallback = isPreferredTabAvailableAfterClose(preferredInput)
|
||||
? preferredInput.preferredTabId
|
||||
: undefined;
|
||||
const fallback = preferredFallback
|
||||
?? fallbackWorkspace?.id
|
||||
?? fallbackSolo?.id
|
||||
?? "vault";
|
||||
const survivingTabIds = buildOrderedTerminalTabIds({
|
||||
sessions: remainingSessions,
|
||||
workspaces: layoutResult.workspaces,
|
||||
tabOrder,
|
||||
});
|
||||
|
||||
// Workspaces survive member loss (#4098 phase 2), so only a closed session
|
||||
// tab that was active needs a replacement.
|
||||
if (currentActiveTabId === closedSessionId) {
|
||||
return fallback;
|
||||
}
|
||||
return resolveNextActiveTabAfterTerminalClose({
|
||||
currentActiveTabId,
|
||||
closedTabId: closedSessionId,
|
||||
orderedTabIdsBeforeClose,
|
||||
survivingTabIds,
|
||||
preferredTabId,
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
export function resolveActiveTabAfterCloseWorkspace({
|
||||
currentActiveTabId,
|
||||
closedWorkspaceId,
|
||||
previousWorkspaces,
|
||||
remainingWorkspaces,
|
||||
remainingSessions,
|
||||
tabOrder,
|
||||
preferredTabId,
|
||||
}: {
|
||||
currentActiveTabId: string | null;
|
||||
closedWorkspaceId: string;
|
||||
previousWorkspaces: readonly Workspace[];
|
||||
remainingWorkspaces: readonly Workspace[];
|
||||
remainingSessions: readonly TerminalSession[];
|
||||
tabOrder?: readonly string[];
|
||||
preferredTabId?: string | null;
|
||||
}): string | null {
|
||||
const orderedTabIdsBeforeClose = buildOrderedTerminalTabIds({
|
||||
sessions: remainingSessions,
|
||||
workspaces: previousWorkspaces,
|
||||
tabOrder,
|
||||
});
|
||||
const survivingTabIds = buildOrderedTerminalTabIds({
|
||||
sessions: remainingSessions,
|
||||
workspaces: remainingWorkspaces,
|
||||
tabOrder,
|
||||
});
|
||||
|
||||
return resolveNextActiveTabAfterTerminalClose({
|
||||
currentActiveTabId,
|
||||
closedTabId: closedWorkspaceId,
|
||||
orderedTabIdsBeforeClose,
|
||||
survivingTabIds,
|
||||
preferredTabId,
|
||||
});
|
||||
}
|
||||
|
||||
export function closeSessionsState({
|
||||
@@ -203,6 +239,11 @@ export function closeSessionsState({
|
||||
const targetSession = nextSessions.find((session) => session.id === sessionId);
|
||||
if (!targetSession) continue;
|
||||
|
||||
const orderedTabIdsBeforeClose = buildOrderedTerminalTabIds({
|
||||
sessions: nextSessions,
|
||||
workspaces: nextWorkspaces,
|
||||
tabOrder: nextTabOrder,
|
||||
});
|
||||
const workspaceId = targetSession.workspaceId;
|
||||
const layoutResult = closeSessionWorkspaceLayoutState(
|
||||
nextWorkspaces,
|
||||
@@ -220,7 +261,10 @@ export function closeSessionsState({
|
||||
layoutResult,
|
||||
remainingSessions: nextSessions,
|
||||
preferredTabId,
|
||||
orderedTabIdsBeforeClose,
|
||||
tabOrder: nextTabOrder,
|
||||
});
|
||||
nextTabOrder = nextTabOrder.filter((id) => id !== sessionId);
|
||||
if (activeTabAfterClose) {
|
||||
nextActiveTabId = activeTabAfterClose;
|
||||
resolvedActiveTabId = activeTabAfterClose;
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import {
|
||||
buildSftpDownloadDialogDirectoryOptions,
|
||||
type SftpDownloadDialogDirectoryOptions,
|
||||
} from "../../../domain/sftpDownloadLocation";
|
||||
import { STORAGE_KEY_SFTP_DEFAULT_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
|
||||
* 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;
|
||||
try {
|
||||
stored = localStorageAdapter.readString(STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR);
|
||||
} catch {
|
||||
// Storage unavailable (non-browser host); fall back to system Downloads.
|
||||
}
|
||||
return buildSftpDownloadDialogDirectoryOptions(stored);
|
||||
};
|
||||
@@ -0,0 +1,213 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { MouseEvent as ReactMouseEvent } from "react";
|
||||
import { JSDOM } from "jsdom";
|
||||
import type { TransferTask } from "../../../types";
|
||||
|
||||
function setupDom() {
|
||||
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>();
|
||||
const install = (key: string, value: unknown) => {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
};
|
||||
for (const key of [
|
||||
"window",
|
||||
"document",
|
||||
"navigator",
|
||||
"HTMLElement",
|
||||
"Element",
|
||||
"Node",
|
||||
"CustomEvent",
|
||||
"Event",
|
||||
"MouseEvent",
|
||||
"StorageEvent",
|
||||
"DOMException",
|
||||
]) {
|
||||
install(key, key === "window" ? dom.window : dom.window[key as keyof typeof dom.window]);
|
||||
}
|
||||
install("localStorage", dom.window.localStorage);
|
||||
install("IS_REACT_ACT_ENVIRONMENT", true);
|
||||
|
||||
return {
|
||||
dom,
|
||||
cleanup() {
|
||||
dom.window.close();
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) {
|
||||
Object.defineProperty(globalThis, key, descriptor);
|
||||
} else {
|
||||
Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const makeTask = (id: string, overrides: Partial<TransferTask> = {}): TransferTask => ({
|
||||
id,
|
||||
fileName: `${id}.bin`,
|
||||
sourcePath: `/src/${id}.bin`,
|
||||
targetPath: `/dst/${id}.bin`,
|
||||
sourceConnectionId: "local",
|
||||
targetConnectionId: "remote-1",
|
||||
direction: "upload",
|
||||
status: "transferring",
|
||||
totalBytes: 1000,
|
||||
transferredBytes: 100,
|
||||
speed: 50,
|
||||
startTime: 1000,
|
||||
isDirectory: false,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
test("useSftpPaneSorting cleans up document drag listeners and pending rAF if unmounted mid-drag", async () => {
|
||||
const env = setupDom();
|
||||
const pendingRafs = new Map<number, FrameRequestCallback>();
|
||||
let nextRafId = 1;
|
||||
const cancelledRafIds: number[] = [];
|
||||
const origRaf = globalThis.requestAnimationFrame;
|
||||
const origCancelRaf = globalThis.cancelAnimationFrame;
|
||||
globalThis.requestAnimationFrame = ((cb: FrameRequestCallback) => {
|
||||
const id = nextRafId++;
|
||||
pendingRafs.set(id, cb);
|
||||
return id;
|
||||
}) as typeof requestAnimationFrame;
|
||||
globalThis.cancelAnimationFrame = ((id: number) => {
|
||||
cancelledRafIds.push(id);
|
||||
pendingRafs.delete(id);
|
||||
}) as typeof cancelAnimationFrame;
|
||||
|
||||
let docMoveAdds = 0;
|
||||
let docMoveRemoves = 0;
|
||||
let docUpAdds = 0;
|
||||
let docUpRemoves = 0;
|
||||
const origDocAdd = document.addEventListener.bind(document);
|
||||
const origDocRemove = document.removeEventListener.bind(document);
|
||||
document.addEventListener = ((type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions) => {
|
||||
if (type === "mousemove") docMoveAdds += 1;
|
||||
if (type === "mouseup") docUpAdds += 1;
|
||||
return origDocAdd(type, listener, options);
|
||||
}) as typeof document.addEventListener;
|
||||
document.removeEventListener = ((type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions) => {
|
||||
if (type === "mousemove") docMoveRemoves += 1;
|
||||
if (type === "mouseup") docUpRemoves += 1;
|
||||
return origDocRemove(type, listener, options);
|
||||
}) as typeof document.removeEventListener;
|
||||
|
||||
const { act } = await import("react");
|
||||
const { createRoot } = await import("react-dom/client");
|
||||
const { useSftpPaneSorting } = await import("./useSftpPaneSorting");
|
||||
|
||||
let latestResult!: ReturnType<typeof useSftpPaneSorting>;
|
||||
function Harness() {
|
||||
latestResult = useSftpPaneSorting();
|
||||
return <div data-name-width={String(latestResult.columnWidths.name)} />;
|
||||
}
|
||||
|
||||
const root = createRoot(document.getElementById("root")!);
|
||||
try {
|
||||
await act(async () => {
|
||||
root.render(<Harness />);
|
||||
});
|
||||
|
||||
// 1. Normal drag updates width and cleans up listeners on mouseup.
|
||||
await act(async () => {
|
||||
latestResult.handleResizeStart("name", {
|
||||
preventDefault() {},
|
||||
stopPropagation() {},
|
||||
clientX: 100,
|
||||
} as unknown as ReactMouseEvent);
|
||||
});
|
||||
assert.equal(docMoveAdds, 1);
|
||||
assert.equal(docUpAdds, 1);
|
||||
|
||||
await act(async () => {
|
||||
document.dispatchEvent(new MouseEvent("mousemove", { clientX: 180 }));
|
||||
});
|
||||
assert.equal(pendingRafs.size, 1);
|
||||
await act(async () => {
|
||||
document.dispatchEvent(new MouseEvent("mouseup"));
|
||||
});
|
||||
assert.equal(docMoveRemoves, 1);
|
||||
assert.equal(docUpRemoves, 1);
|
||||
assert.equal(pendingRafs.size, 0);
|
||||
assert.equal(latestResult.columnWidths.name, 60);
|
||||
|
||||
// 2. Unmounting mid-drag removes both document listeners and cancels pending rAF.
|
||||
await act(async () => {
|
||||
latestResult.handleResizeStart("name", {
|
||||
preventDefault() {},
|
||||
stopPropagation() {},
|
||||
clientX: 100,
|
||||
} as unknown as ReactMouseEvent);
|
||||
});
|
||||
assert.equal(docMoveAdds, 2);
|
||||
assert.equal(docUpAdds, 2);
|
||||
|
||||
await act(async () => {
|
||||
document.dispatchEvent(new MouseEvent("mousemove", { clientX: 200 }));
|
||||
});
|
||||
assert.equal(pendingRafs.size, 1);
|
||||
const queuedRafId = [...pendingRafs.keys()][0];
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
assert.equal(docMoveRemoves, 2);
|
||||
assert.equal(docUpRemoves, 2);
|
||||
assert.equal(pendingRafs.size, 0);
|
||||
assert.ok(cancelledRafIds.includes(queuedRafId));
|
||||
} finally {
|
||||
document.addEventListener = origDocAdd;
|
||||
document.removeEventListener = origDocRemove;
|
||||
globalThis.requestAnimationFrame = origRaf;
|
||||
globalThis.cancelAnimationFrame = origCancelRaf;
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("applyTransferProgressToRows returns same array for unknown taskId and single-slot copies matching rows while honoring pause latch", async () => {
|
||||
const { applyTransferProgressToRows } = await import("./useSftpTransfers");
|
||||
|
||||
const row1 = makeTask("task-1", { transferredBytes: 100, speed: 50 });
|
||||
const row2 = makeTask("task-2", { transferredBytes: 200, speed: 80 });
|
||||
const row3 = makeTask("task-3", { status: "paused", transferredBytes: 300, speed: 0 });
|
||||
const rows = [row1, row2, row3];
|
||||
|
||||
// Unknown taskId -> exact same array reference, zero cloning.
|
||||
const unchanged = applyTransferProgressToRows(rows, "missing-task", { transferredBytes: 999 }, () => false);
|
||||
assert.equal(unchanged, rows);
|
||||
|
||||
// Matching taskId -> shallow single-slot copy preserving untouched row references.
|
||||
const updated = applyTransferProgressToRows(rows, "task-2", { transferredBytes: 450, speed: 120 }, () => false);
|
||||
assert.notEqual(updated, rows);
|
||||
assert.equal(updated[0], row1);
|
||||
assert.equal(updated[2], row3);
|
||||
assert.notEqual(updated[1], row2);
|
||||
assert.equal(updated[1].transferredBytes, 450);
|
||||
assert.equal(updated[1].speed, 120);
|
||||
|
||||
// Stale "transferring" progress tick must not reopen a paused or latched row.
|
||||
const stillPaused = applyTransferProgressToRows(
|
||||
rows,
|
||||
"task-3",
|
||||
{ status: "transferring", transferredBytes: 320, speed: 90 },
|
||||
() => false,
|
||||
);
|
||||
assert.equal(stillPaused[2].status, "paused");
|
||||
assert.equal(stillPaused[2].speed, 0);
|
||||
assert.equal(stillPaused[2].transferredBytes, 320);
|
||||
|
||||
const latchedRow = applyTransferProgressToRows(
|
||||
rows,
|
||||
"task-1",
|
||||
{ status: "transferring", transferredBytes: 150, speed: 75 },
|
||||
(rootId, rowId) => rootId === "task-1" && rowId === "task-1",
|
||||
);
|
||||
assert.equal(latchedRow[0].status, "transferring");
|
||||
assert.equal(latchedRow[0].speed, 0);
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Host, KnownHost, SftpConnection, SftpFileEntry, SftpFilenameEncoding } from "../../../domain/models";
|
||||
import { createNavHistory, type SftpNavHistory } from "../../../domain/sftpNavHistory";
|
||||
|
||||
export interface SftpPane {
|
||||
id: string;
|
||||
@@ -13,6 +14,7 @@ export interface SftpPane {
|
||||
filenameEncoding: SftpFilenameEncoding;
|
||||
showHiddenFiles: boolean;
|
||||
transferMutationToken: number;
|
||||
navHistory?: SftpNavHistory;
|
||||
}
|
||||
|
||||
export interface SftpHostKeyInfo {
|
||||
@@ -57,6 +59,7 @@ export const createEmptyPane = (
|
||||
filenameEncoding: "auto",
|
||||
showHiddenFiles,
|
||||
transferMutationToken: 0,
|
||||
navHistory: createNavHistory(),
|
||||
});
|
||||
|
||||
// File watch event types
|
||||
|
||||
@@ -9,7 +9,8 @@ import { useSftpDirectoryListing } from "./useSftpDirectoryListing";
|
||||
import { useSftpHostCredentials } from "./useSftpHostCredentials";
|
||||
import { buildCacheKey, getSharedRemoteHostCache, setSharedRemoteHostCache } from "./sharedRemoteHostCache";
|
||||
import { resolveRemoteSftpStartState } from "./sftpConnectStartPath";
|
||||
import { normalizeSftpPaneNavigationPath } from "./utils";
|
||||
import { isSameSftpPath, normalizeSftpPaneNavigationPath } from "./utils";
|
||||
import { createNavHistory, resolveSftpConnectNavHistory } from "../../../domain/sftpNavHistory";
|
||||
import {
|
||||
setDirectoryCacheEntry,
|
||||
type DirectoryListingCache,
|
||||
@@ -967,6 +968,12 @@ export const useSftpConnections = ({
|
||||
error: null,
|
||||
connectionLogs: [],
|
||||
filenameEncoding, // Reset encoding for new connection
|
||||
navHistory: resolveSftpConnectNavHistory({
|
||||
sameEndpointReconnect,
|
||||
previousHistory: prev.navHistory,
|
||||
startPath,
|
||||
isSamePath: isSameSftpPath,
|
||||
}),
|
||||
}));
|
||||
|
||||
try {
|
||||
@@ -1039,6 +1046,7 @@ export const useSftpConnections = ({
|
||||
connectionLogs: [],
|
||||
files: isReconnectAttempt ? prev.files : (sharedHostCache?.files ?? []),
|
||||
filenameEncoding, // Reset encoding for new connection
|
||||
navHistory: sameEndpointReconnect ? prev.navHistory : createNavHistory(),
|
||||
}));
|
||||
|
||||
// Subscribe to SFTP connection progress events for auth logging
|
||||
@@ -1280,6 +1288,12 @@ export const useSftpConnections = ({
|
||||
loading: false,
|
||||
reconnecting: false,
|
||||
connectionLogs: [], // Clear after successful connect to avoid replay during navigation
|
||||
navHistory: resolveSftpConnectNavHistory({
|
||||
sameEndpointReconnect,
|
||||
previousHistory: prev.navHistory,
|
||||
startPath,
|
||||
isSamePath: isSameSftpPath,
|
||||
}),
|
||||
}));
|
||||
} catch (err) {
|
||||
await settleFailedSftpConnectIfCurrent({
|
||||
|
||||
@@ -1,28 +1,6 @@
|
||||
import { useCallback } from "react";
|
||||
import type { Host, Identity, KnownHost, SSHKey, TerminalSettings } from "../../../domain/models";
|
||||
import { isEncryptedCredentialPlaceholder, sanitizeCredentialValue } from "../../../domain/credentials";
|
||||
import { resolveBridgeKeyAuth, resolveBridgeSshAgentAuth, resolveHostAuth } from "../../../domain/sshAuth";
|
||||
import { resolveHostKeepalive } from "../../../domain/host";
|
||||
import { connectionTotpFields } from "../../../domain/totpConfig";
|
||||
import { resolveHostSshConnectionTimeouts } from "../../../domain/sshConnectionTimeouts";
|
||||
import {
|
||||
findIncompleteProxyIdentityId,
|
||||
findMissingProxyIdentityId,
|
||||
formatIncompleteProxyIdentityMessage,
|
||||
formatMissingProxyIdentityMessage,
|
||||
hasUnreadableProxyCredential,
|
||||
hasUsableProxyConfig,
|
||||
resolveProxyConfigAuth,
|
||||
} from "../../../domain/proxyProfiles";
|
||||
|
||||
// Fallback used when no global TerminalSettings are wired through (older
|
||||
// call sites or tests). Matches DEFAULT_TERMINAL_SETTINGS so behavior is
|
||||
// identical whether or not the caller passes settings.
|
||||
const FALLBACK_TERMINAL_SETTINGS = {
|
||||
verifyHostKeys: true,
|
||||
keepaliveInterval: 30,
|
||||
keepaliveCountMax: 10,
|
||||
};
|
||||
import { buildSshConnectionCredentials } from "../../../domain/sshConnectionCredentials";
|
||||
|
||||
interface UseSftpHostCredentialsParams {
|
||||
hosts: Host[];
|
||||
@@ -50,183 +28,19 @@ export const buildSftpHostCredentials = ({
|
||||
*/
|
||||
jumpHostsOverride?: Host[];
|
||||
}): NetcattySSHOptions => {
|
||||
const globalTerminalSettings = { ...FALLBACK_TERMINAL_SETTINGS, ...(terminalSettings ?? {}) };
|
||||
if (host.proxyProfileId && !host.proxyConfig) {
|
||||
throw new Error(`Saved proxy for host "${host.label || host.hostname}" is missing. Open host settings and select a valid proxy.`);
|
||||
}
|
||||
if (findMissingProxyIdentityId(host.proxyConfig, identities)) {
|
||||
throw new Error(formatMissingProxyIdentityMessage(host.label || host.hostname));
|
||||
}
|
||||
if (findIncompleteProxyIdentityId(host.proxyConfig, identities)) {
|
||||
throw new Error(formatIncompleteProxyIdentityMessage(host.label || host.hostname));
|
||||
}
|
||||
|
||||
const resolved = resolveHostAuth({ host, keys, identities });
|
||||
const key = resolved.key || null;
|
||||
|
||||
const proxyConfig = host.proxyConfig
|
||||
? resolveProxyConfigAuth(host.proxyConfig, identities)
|
||||
: undefined;
|
||||
let jumpHosts: NetcattyJumpHost[] | undefined;
|
||||
const resolveChainHost = (hostId: string): Host => {
|
||||
const jumpHost = hosts.find((candidate) => candidate.id === hostId);
|
||||
if (!jumpHost) {
|
||||
throw new Error(`Jump host "${hostId}" is missing. Open host settings and repair the jump host chain.`);
|
||||
}
|
||||
return jumpHost;
|
||||
};
|
||||
// A non-empty pinned chain snapshot wins over live hostChain resolution.
|
||||
const chainHosts: Host[] | null = jumpHostsOverride && jumpHostsOverride.length > 0
|
||||
? jumpHostsOverride
|
||||
: host.hostChain?.hostIds && host.hostChain.hostIds.length > 0
|
||||
? host.hostChain.hostIds.map(resolveChainHost)
|
||||
: null;
|
||||
if (chainHosts) {
|
||||
jumpHosts = chainHosts.map((jumpHost, index) => {
|
||||
if (jumpHost.proxyProfileId && !jumpHost.proxyConfig) {
|
||||
throw new Error(`Saved proxy for jump host "${jumpHost.label || jumpHost.hostname}" is missing. Open host settings and select a valid proxy.`);
|
||||
}
|
||||
if (findMissingProxyIdentityId(jumpHost.proxyConfig, identities)) {
|
||||
throw new Error(formatMissingProxyIdentityMessage(jumpHost.label || jumpHost.hostname));
|
||||
}
|
||||
if (findIncompleteProxyIdentityId(jumpHost.proxyConfig, identities)) {
|
||||
throw new Error(formatIncompleteProxyIdentityMessage(jumpHost.label || jumpHost.hostname));
|
||||
}
|
||||
const jumpAuth = resolveHostAuth({
|
||||
host: jumpHost,
|
||||
keys,
|
||||
identities,
|
||||
});
|
||||
const jumpKey = jumpAuth.key;
|
||||
const jumpPassword = sanitizeCredentialValue(jumpAuth.password);
|
||||
const jumpKeyAuth = resolveBridgeKeyAuth({
|
||||
key: jumpKey,
|
||||
fallbackIdentityFilePaths: jumpAuth.authMethod === "password" || jumpAuth.keyId
|
||||
? undefined
|
||||
: jumpHost.identityFilePaths,
|
||||
passphrase: jumpAuth.passphrase,
|
||||
});
|
||||
const jumpAgentAuth = resolveBridgeSshAgentAuth(jumpHost, jumpKey, jumpAuth.authMethod);
|
||||
const hasJumpKeyMaterial = Boolean(
|
||||
jumpAgentAuth.useSshAgent || jumpKeyAuth.privateKey || jumpKeyAuth.identityFilePaths?.length,
|
||||
);
|
||||
const hasConfiguredJumpProxyEndpoint =
|
||||
index === 0 &&
|
||||
hasUsableProxyConfig(jumpHost.proxyConfig);
|
||||
if (
|
||||
hasConfiguredJumpProxyEndpoint &&
|
||||
hasUnreadableProxyCredential(jumpHost.proxyConfig, identities)
|
||||
) {
|
||||
throw new Error(`Proxy credentials for jump host "${jumpHost.label || jumpHost.hostname}" cannot be decrypted on this device. Open host settings and re-enter the proxy password.`);
|
||||
}
|
||||
const hasUnreadableJumpCredential =
|
||||
isEncryptedCredentialPlaceholder(jumpAuth.password) ||
|
||||
isEncryptedCredentialPlaceholder(jumpKey?.privateKey) ||
|
||||
isEncryptedCredentialPlaceholder(jumpAuth.passphrase);
|
||||
if (
|
||||
(jumpAuth.authMethod === "password" && isEncryptedCredentialPlaceholder(jumpAuth.password) && !jumpPassword) ||
|
||||
(jumpAuth.authMethod !== "password" && jumpAuth.authMethod !== "auto" && hasUnreadableJumpCredential && !jumpPassword && !hasJumpKeyMaterial)
|
||||
) {
|
||||
throw new Error(`Saved credentials for jump host "${jumpHost.label || jumpHost.hostname}" cannot be decrypted on this device. Open host settings and re-enter them.`);
|
||||
}
|
||||
const hopKeepalive = resolveHostKeepalive(jumpHost, globalTerminalSettings);
|
||||
const hopConnectionTimeouts = resolveHostSshConnectionTimeouts(jumpHost);
|
||||
return {
|
||||
hostname: jumpHost.hostname,
|
||||
hostId: jumpHost.id,
|
||||
port: jumpHost.port || 22,
|
||||
username: jumpAuth.username || "root",
|
||||
authMethod: jumpAuth.authMethod,
|
||||
requiresMfa: !!jumpHost.requiresMfa,
|
||||
password: jumpPassword,
|
||||
...connectionTotpFields(jumpHost),
|
||||
privateKey: jumpKeyAuth.privateKey,
|
||||
certificate: jumpKey?.certificate,
|
||||
passphrase: jumpKeyAuth.passphrase,
|
||||
publicKey: jumpKey?.publicKey,
|
||||
keyId: jumpAuth.keyId,
|
||||
keySource: jumpKey?.source,
|
||||
label: jumpHost.label,
|
||||
proxy: hasUsableProxyConfig(jumpHost.proxyConfig)
|
||||
? resolveProxyConfigAuth(jumpHost.proxyConfig, identities)
|
||||
: undefined,
|
||||
identityFilePaths: jumpKeyAuth.identityFilePaths,
|
||||
...jumpAgentAuth,
|
||||
keepaliveInterval: hopKeepalive.interval,
|
||||
keepaliveCountMax: hopKeepalive.countMax,
|
||||
sshTcpConnectTimeoutMs: hopConnectionTimeouts.tcpConnectTimeoutSeconds * 1000,
|
||||
sshAuthReadyTimeoutMs: hopConnectionTimeouts.authReadyTimeoutSeconds * 1000,
|
||||
verifyHostKeys: globalTerminalSettings.verifyHostKeys,
|
||||
legacyAlgorithms: jumpHost.legacyAlgorithms,
|
||||
skipEcdsaHostKey: jumpHost.skipEcdsaHostKey,
|
||||
algorithmOverrides: jumpHost.algorithms,
|
||||
};
|
||||
});
|
||||
}
|
||||
const usesTargetProxyForFirstHop = !!proxyConfig && !jumpHosts?.[0]?.proxy;
|
||||
if (usesTargetProxyForFirstHop && hasUnreadableProxyCredential(host.proxyConfig, identities)) {
|
||||
throw new Error("Proxy credentials cannot be decrypted on this device. Open host settings and re-enter the proxy password.");
|
||||
}
|
||||
|
||||
const keyAuth = resolveBridgeKeyAuth({
|
||||
key,
|
||||
fallbackIdentityFilePaths: resolved.authMethod === "password" || resolved.keyId
|
||||
? undefined
|
||||
: host.identityFilePaths,
|
||||
passphrase: resolved.passphrase,
|
||||
const sshCredentials = buildSshConnectionCredentials({
|
||||
host,
|
||||
hosts,
|
||||
keys,
|
||||
identities,
|
||||
knownHosts,
|
||||
terminalSettings,
|
||||
jumpHostsOverride,
|
||||
});
|
||||
const targetAgentAuth = resolveBridgeSshAgentAuth(host, key, resolved.authMethod);
|
||||
const password = sanitizeCredentialValue(resolved.password);
|
||||
const hasKeyMaterial = Boolean(
|
||||
targetAgentAuth.useSshAgent || keyAuth.privateKey || keyAuth.identityFilePaths?.length,
|
||||
);
|
||||
const hasUnreadableCredential =
|
||||
isEncryptedCredentialPlaceholder(resolved.password) ||
|
||||
isEncryptedCredentialPlaceholder(key?.privateKey) ||
|
||||
isEncryptedCredentialPlaceholder(resolved.passphrase);
|
||||
if (
|
||||
(resolved.authMethod === "password" && isEncryptedCredentialPlaceholder(resolved.password) && !password) ||
|
||||
(resolved.authMethod !== "password" && resolved.authMethod !== "auto" && hasUnreadableCredential && !password && !hasKeyMaterial)
|
||||
) {
|
||||
throw new Error("Saved credentials cannot be decrypted on this device. Open host settings and re-enter them.");
|
||||
}
|
||||
|
||||
const targetKeepalive = resolveHostKeepalive(host, globalTerminalSettings);
|
||||
const targetConnectionTimeouts = resolveHostSshConnectionTimeouts(host);
|
||||
return {
|
||||
hostname: host.hostname,
|
||||
hostId: host.id,
|
||||
username: resolved.username,
|
||||
authMethod: resolved.authMethod,
|
||||
requiresMfa: !!host.requiresMfa,
|
||||
port: host.port || 22,
|
||||
password,
|
||||
...connectionTotpFields(host),
|
||||
privateKey: keyAuth.privateKey,
|
||||
certificate: key?.certificate,
|
||||
passphrase: keyAuth.passphrase,
|
||||
publicKey: key?.publicKey,
|
||||
keyId: resolved.keyId,
|
||||
keySource: key?.source,
|
||||
proxy: proxyConfig,
|
||||
jumpHosts: jumpHosts && jumpHosts.length > 0 ? jumpHosts : undefined,
|
||||
...sshCredentials,
|
||||
sudo: host.sftpSudo,
|
||||
fileProtocol: host.sftpFileProtocol || "auto",
|
||||
identityFilePaths: keyAuth.identityFilePaths,
|
||||
...targetAgentAuth,
|
||||
keepaliveInterval: targetKeepalive.interval,
|
||||
keepaliveCountMax: targetKeepalive.countMax,
|
||||
sshTcpConnectTimeoutMs: targetConnectionTimeouts.tcpConnectTimeoutSeconds * 1000,
|
||||
sshAuthReadyTimeoutMs: targetConnectionTimeouts.authReadyTimeoutSeconds * 1000,
|
||||
knownHosts,
|
||||
verifyHostKeys: globalTerminalSettings.verifyHostKeys,
|
||||
// Algorithm settings — must reach the SFTP bridge or hosts that need
|
||||
// legacy mode / the ECDSA skip / advanced overrides would still hit
|
||||
// the original negotiation failure when opening their SFTP pane,
|
||||
// even though the terminal session works.
|
||||
legacyAlgorithms: host.legacyAlgorithms,
|
||||
skipEcdsaHostKey: host.skipEcdsaHostKey,
|
||||
algorithmOverrides: host.algorithms,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,423 @@
|
||||
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 { SftpFileEntry } from "../../../domain/models";
|
||||
import {
|
||||
canGoBack,
|
||||
canGoForward,
|
||||
createNavHistory,
|
||||
resolveSftpConnectNavHistory,
|
||||
} from "../../../domain/sftpNavHistory";
|
||||
import type { DirectoryListingCache } from "./directoryListingCache";
|
||||
import type { SftpPane } from "./types";
|
||||
import { useSftpPaneActions } from "./useSftpPaneActions";
|
||||
|
||||
function createConnectedPane(id: string, connectionId: string, initialPath: string, isLocal = false): SftpPane {
|
||||
return {
|
||||
id,
|
||||
connection: {
|
||||
id: connectionId,
|
||||
hostId: isLocal ? "local" : "host-1",
|
||||
hostLabel: isLocal ? "Local" : "Server",
|
||||
isLocal,
|
||||
status: "connected",
|
||||
currentPath: initialPath,
|
||||
homeDir: "/home/alice",
|
||||
},
|
||||
files: [],
|
||||
loading: false,
|
||||
reconnecting: false,
|
||||
error: null,
|
||||
connectionLogs: [],
|
||||
selectedFiles: new Set(),
|
||||
filter: "",
|
||||
filenameEncoding: "auto",
|
||||
showHiddenFiles: false,
|
||||
transferMutationToken: 0,
|
||||
navHistory: createNavHistory(initialPath),
|
||||
};
|
||||
}
|
||||
|
||||
function mountHarness(options?: {
|
||||
leftInitialPath?: string;
|
||||
rightInitialPath?: string;
|
||||
failingPaths?: Set<string>;
|
||||
dirCacheTtlMs?: number;
|
||||
listDir?: (dirPath: string) => Promise<SftpFileEntry[]>;
|
||||
}) {
|
||||
const previousActFlag = (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT;
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const leftPane = createConnectedPane("tab-left", "conn-left", options?.leftInitialPath ?? "/home/alice", false);
|
||||
const rightPane = createConnectedPane("tab-right", "conn-right", options?.rightInitialPath ?? "/tmp", true);
|
||||
|
||||
const leftTabsRef = { current: { tabs: [leftPane], activeTabId: leftPane.id as string | null } };
|
||||
const rightTabsRef = { current: { tabs: [rightPane], activeTabId: rightPane.id as string | null } };
|
||||
const navSeqRef = { current: { left: 0, right: 0 } };
|
||||
const dirCacheRef = { current: new Map() as DirectoryListingCache };
|
||||
const sftpSessionsRef = { current: new Map<string, string>([["conn-left", "sftp-1"]]) };
|
||||
const lastConnectedHostRef = { current: { left: null, right: null } };
|
||||
const connectionCacheKeyMapRef = { current: new Map<string, string>() };
|
||||
const failingPaths = options?.failingPaths ?? new Set<string>();
|
||||
const listedPaths: string[] = [];
|
||||
|
||||
const getSideTabs = (side: "left" | "right") => (side === "left" ? leftTabsRef : rightTabsRef);
|
||||
const getActivePane = (side: "left" | "right"): SftpPane | null => {
|
||||
const ref = getSideTabs(side).current;
|
||||
return ref.tabs.find((tab) => tab.id === ref.activeTabId) ?? null;
|
||||
};
|
||||
const updateTab = (side: "left" | "right", tabId: string, updater: (pane: SftpPane) => SftpPane) => {
|
||||
const ref = getSideTabs(side);
|
||||
ref.current = {
|
||||
...ref.current,
|
||||
tabs: ref.current.tabs.map((tab) => (tab.id === tabId ? updater(tab) : tab)),
|
||||
};
|
||||
};
|
||||
const updateActiveTab = (side: "left" | "right", updater: (pane: SftpPane) => SftpPane) => {
|
||||
const activeTabId = getSideTabs(side).current.activeTabId;
|
||||
if (!activeTabId) return;
|
||||
updateTab(side, activeTabId, updater);
|
||||
};
|
||||
|
||||
const listDir = async (dirPath: string): Promise<SftpFileEntry[]> => {
|
||||
listedPaths.push(dirPath);
|
||||
if (options?.listDir) {
|
||||
return options.listDir(dirPath);
|
||||
}
|
||||
if (failingPaths.has(dirPath)) {
|
||||
throw new Error(`Permission denied: ${dirPath}`);
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
||||
let actions: ReturnType<typeof useSftpPaneActions> | undefined;
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
|
||||
function Probe() {
|
||||
actions = useSftpPaneActions({
|
||||
hosts: [],
|
||||
getActivePane,
|
||||
updateTab,
|
||||
updateActiveTab,
|
||||
leftTabsRef,
|
||||
rightTabsRef,
|
||||
navSeqRef,
|
||||
dirCacheRef,
|
||||
sftpSessionsRef,
|
||||
lastConnectedHostRef,
|
||||
connectionCacheKeyMapRef,
|
||||
makeCacheKey: (connectionId, dirPath, encoding) => `${connectionId}::${encoding || "auto"}::${dirPath}`,
|
||||
clearCacheForConnection: (connectionId) => {
|
||||
for (const key of dirCacheRef.current.keys()) {
|
||||
if (key.startsWith(`${connectionId}::`)) dirCacheRef.current.delete(key);
|
||||
}
|
||||
},
|
||||
listLocalFiles: listDir,
|
||||
listRemoteFiles: (_sftpId, dirPath) => listDir(dirPath),
|
||||
handleSessionError: () => {},
|
||||
releaseConnection: async () => {},
|
||||
isSessionError: () => false,
|
||||
clearSelectionsExcept: () => {},
|
||||
dirCacheTtlMs: options?.dirCacheTtlMs ?? 10_000,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
get actions() {
|
||||
assert.ok(actions);
|
||||
return actions;
|
||||
},
|
||||
getPane: (side: "left" | "right") => {
|
||||
const pane = getActivePane(side);
|
||||
assert.ok(pane);
|
||||
return pane;
|
||||
},
|
||||
failingPaths,
|
||||
listedPaths,
|
||||
dirCacheRef,
|
||||
updateTab,
|
||||
render: async () => {
|
||||
await act(async () => {
|
||||
renderer = create(React.createElement(Probe));
|
||||
});
|
||||
},
|
||||
unmount: async () => {
|
||||
await act(async () => {
|
||||
renderer?.unmount();
|
||||
});
|
||||
renderer = undefined;
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = previousActFlag;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("useSftpPaneActions records navigations, traverses back/forward without duplicates, and truncates on branch", async () => {
|
||||
const harness = mountHarness();
|
||||
try {
|
||||
await harness.render();
|
||||
|
||||
assert.equal(canGoBack(harness.getPane("left").navHistory!), false);
|
||||
assert.equal(canGoForward(harness.getPane("left").navHistory!), false);
|
||||
|
||||
assert.equal(await harness.actions.navigateTo("left", "/var"), "reached");
|
||||
assert.equal(await harness.actions.navigateTo("left", "/var/log"), "reached");
|
||||
// Navigating to the same current path is a no-op in history
|
||||
assert.equal(await harness.actions.navigateTo("left", "/var/log"), "reached");
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 2);
|
||||
|
||||
// navigateUp pushes parent directory onto history
|
||||
await harness.actions.navigateUp("left");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var");
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log", "/var"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 3);
|
||||
|
||||
// Back moves pointer without pushing duplicates or clearing forward entries
|
||||
assert.equal(await harness.actions.navigateBack("left"), "reached");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var/log");
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 2);
|
||||
assert.equal(canGoForward(harness.getPane("left").navHistory!), true);
|
||||
|
||||
assert.equal(await harness.actions.navigateBack("left"), "reached");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var");
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 1);
|
||||
|
||||
// Refresh preserves forward stack
|
||||
await harness.actions.refresh("left");
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log", "/var"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 1);
|
||||
assert.equal(canGoForward(harness.getPane("left").navHistory!), true);
|
||||
|
||||
// Forward steps ahead without duplicating
|
||||
assert.equal(await harness.actions.navigateForward("left"), "reached");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var/log");
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 2);
|
||||
|
||||
// New navigation from mid-stack truncates forward entries
|
||||
assert.equal(await harness.actions.navigateTo("left", "/etc"), "reached");
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log", "/etc"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 3);
|
||||
assert.equal(canGoForward(harness.getPane("left").navHistory!), false);
|
||||
|
||||
// Right pane history stays independent
|
||||
assert.deepEqual(harness.getPane("right").navHistory?.entries, ["/tmp"]);
|
||||
assert.equal(harness.getPane("right").navHistory?.index, 0);
|
||||
} finally {
|
||||
await harness.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
test("useSftpPaneActions preserves history pointer and forward stack when navigation fails", async () => {
|
||||
const failingPaths = new Set<string>(["/forbidden"]);
|
||||
// Disable cache hits so back/forward also exercises async failure rollback
|
||||
const harness = mountHarness({ failingPaths, dirCacheTtlMs: 0 });
|
||||
try {
|
||||
await harness.render();
|
||||
|
||||
assert.equal(await harness.actions.navigateTo("left", "/var"), "reached");
|
||||
assert.equal(await harness.actions.navigateTo("left", "/var/log"), "reached");
|
||||
assert.equal(await harness.actions.navigateBack("left"), "reached");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var");
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 1);
|
||||
|
||||
// Failed normal navigation must NOT truncate forward entry (/var/log) or push /forbidden
|
||||
assert.equal(await harness.actions.navigateTo("left", "/forbidden"), "failed");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var");
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 1);
|
||||
assert.equal(canGoForward(harness.getPane("left").navHistory!), true);
|
||||
|
||||
// Failed Back navigation must NOT decrement pointer
|
||||
harness.failingPaths.add("/home/alice");
|
||||
assert.equal(await harness.actions.navigateBack("left"), "failed");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var");
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 1);
|
||||
|
||||
// Failed Forward navigation must NOT increment pointer
|
||||
harness.failingPaths.add("/var/log");
|
||||
assert.equal(await harness.actions.navigateForward("left"), "failed");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var");
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 1);
|
||||
|
||||
// Once /var/log is readable again, Forward still works cleanly
|
||||
harness.failingPaths.delete("/var/log");
|
||||
assert.equal(await harness.actions.navigateForward("left"), "reached");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var/log");
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 2);
|
||||
} finally {
|
||||
await harness.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
test("host switch resets navigation history so previous host paths cannot be navigated via Back", async () => {
|
||||
const harness = mountHarness();
|
||||
try {
|
||||
await harness.render();
|
||||
|
||||
assert.equal(await harness.actions.navigateTo("left", "/var"), "reached");
|
||||
assert.equal(await harness.actions.navigateTo("left", "/etc"), "reached");
|
||||
assert.equal(canGoBack(harness.getPane("left").navHistory!), true);
|
||||
|
||||
// Simulate switching connection on the same tab (sameEndpointReconnect = false)
|
||||
harness.updateTab("left", "tab-left", (prev) => ({
|
||||
...prev,
|
||||
connection: prev.connection
|
||||
? { ...prev.connection, id: "conn-host-2", hostId: "host-2", currentPath: "/srv/app" }
|
||||
: null,
|
||||
navHistory: resolveSftpConnectNavHistory({
|
||||
sameEndpointReconnect: false,
|
||||
previousHistory: prev.navHistory,
|
||||
startPath: "/srv/app",
|
||||
}),
|
||||
}));
|
||||
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/srv/app"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 0);
|
||||
assert.equal(canGoBack(harness.getPane("left").navHistory!), false);
|
||||
assert.equal(canGoForward(harness.getPane("left").navHistory!), false);
|
||||
assert.equal(await harness.actions.navigateBack("left"), "aborted");
|
||||
} finally {
|
||||
await harness.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
function createDeferred<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 };
|
||||
}
|
||||
|
||||
test("mid-flight refresh inherits pending push navigation and clears cleanly on settle or failure", async () => {
|
||||
const pendingLoads: Array<{ path: string; deferred: ReturnType<typeof createDeferred<SftpFileEntry[]>> }> = [];
|
||||
const harness = mountHarness({
|
||||
dirCacheTtlMs: 0,
|
||||
listDir: (dirPath) => {
|
||||
if (dirPath === "/slow" || dirPath === "/slow-fail") {
|
||||
const deferred = createDeferred<SftpFileEntry[]>();
|
||||
pendingLoads.push({ path: dirPath, deferred });
|
||||
return deferred.promise;
|
||||
}
|
||||
return Promise.resolve([]);
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await harness.render();
|
||||
|
||||
// Start slow navigation to /slow, then refresh mid-flight before /slow settles.
|
||||
const slowNavPromise = harness.actions.navigateTo("left", "/slow");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/slow");
|
||||
assert.equal(harness.getPane("left").loading, true);
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice"]);
|
||||
|
||||
const refreshPromise = harness.actions.refresh("left");
|
||||
assert.equal(pendingLoads.length, 2);
|
||||
|
||||
// Original slow navigation finishes first (superseded), then refresh settles.
|
||||
pendingLoads[0].deferred.resolve([]);
|
||||
assert.equal(await slowNavPromise, "superseded");
|
||||
pendingLoads[1].deferred.resolve([]);
|
||||
await refreshPromise;
|
||||
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/slow");
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/slow"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 1);
|
||||
|
||||
// Back returns to /home/alice cleanly.
|
||||
assert.equal(await harness.actions.navigateBack("left"), "reached");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/home/alice");
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 0);
|
||||
|
||||
// If a mid-flight refresh fails, currentPath reverts and history/forward stack stay intact.
|
||||
pendingLoads.length = 0;
|
||||
const failNavPromise = harness.actions.navigateTo("left", "/slow-fail");
|
||||
const failRefreshPromise = harness.actions.refresh("left");
|
||||
assert.equal(pendingLoads.length, 2);
|
||||
|
||||
pendingLoads[0].deferred.resolve([]);
|
||||
assert.equal(await failNavPromise, "superseded");
|
||||
pendingLoads[1].deferred.reject(new Error("I/O error"));
|
||||
await failRefreshPromise;
|
||||
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/home/alice");
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/slow"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 0);
|
||||
assert.equal(canGoForward(harness.getPane("left").navHistory!), true);
|
||||
} finally {
|
||||
await harness.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
test("mid-flight refresh during Forward or Back advances history index consistently", async () => {
|
||||
const pendingLoads: Array<{ path: string; deferred: ReturnType<typeof createDeferred<SftpFileEntry[]>> }> = [];
|
||||
let interceptTarget: string | null = null;
|
||||
const harness = mountHarness({
|
||||
dirCacheTtlMs: 0,
|
||||
listDir: (dirPath) => {
|
||||
if (interceptTarget && dirPath === interceptTarget) {
|
||||
const deferred = createDeferred<SftpFileEntry[]>();
|
||||
pendingLoads.push({ path: dirPath, deferred });
|
||||
return deferred.promise;
|
||||
}
|
||||
return Promise.resolve([]);
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await harness.render();
|
||||
|
||||
// Build history: [/home/alice, /var, /var/log], then step Back to /var (index 1).
|
||||
assert.equal(await harness.actions.navigateTo("left", "/var"), "reached");
|
||||
assert.equal(await harness.actions.navigateTo("left", "/var/log"), "reached");
|
||||
assert.equal(await harness.actions.navigateBack("left"), "reached");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var");
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 1);
|
||||
|
||||
// Start Forward -> /var/log, then trigger Refresh before it finishes.
|
||||
interceptTarget = "/var/log";
|
||||
const forwardPromise = harness.actions.navigateForward("left");
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var/log");
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 1);
|
||||
|
||||
const refreshPromise = harness.actions.refresh("left");
|
||||
assert.equal(pendingLoads.length, 2);
|
||||
|
||||
pendingLoads[0].deferred.resolve([]);
|
||||
assert.equal(await forwardPromise, "superseded");
|
||||
pendingLoads[1].deferred.resolve([]);
|
||||
await refreshPromise;
|
||||
|
||||
// Displayed directory and history index must stay synchronized at /var/log (index 2).
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var/log");
|
||||
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log"]);
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 2);
|
||||
|
||||
// Next Back must go to /var (NOT skip /var and jump to /home/alice).
|
||||
interceptTarget = "/var";
|
||||
pendingLoads.length = 0;
|
||||
const backPromise = harness.actions.navigateBack("left");
|
||||
const backRefreshPromise = harness.actions.refresh("left");
|
||||
assert.equal(pendingLoads.length, 2);
|
||||
|
||||
pendingLoads[0].deferred.resolve([]);
|
||||
assert.equal(await backPromise, "superseded");
|
||||
pendingLoads[1].deferred.resolve([]);
|
||||
await backRefreshPromise;
|
||||
|
||||
assert.equal(harness.getPane("left").connection?.currentPath, "/var");
|
||||
assert.equal(harness.getPane("left").navHistory?.index, 1);
|
||||
assert.equal(canGoBack(harness.getPane("left").navHistory!), true);
|
||||
assert.equal(canGoForward(harness.getPane("left").navHistory!), true);
|
||||
} finally {
|
||||
await harness.unmount();
|
||||
}
|
||||
});
|
||||
@@ -24,6 +24,15 @@ import {
|
||||
setDirectoryCacheEntry,
|
||||
type DirectoryListingCache,
|
||||
} from "./directoryListingCache";
|
||||
import {
|
||||
applySftpNavHistoryTransition,
|
||||
createNavHistory,
|
||||
goBack,
|
||||
goForward,
|
||||
resolveSftpEffectiveNavHistoryMode,
|
||||
type PendingSftpNavHistoryTransition,
|
||||
type SftpNavHistoryTransitionMode,
|
||||
} from "../../../domain/sftpNavHistory";
|
||||
|
||||
/** Shared empty set for navigation resets — never mutate this. */
|
||||
const EMPTY_SET = new Set<string>();
|
||||
@@ -58,10 +67,14 @@ export type SftpNavigateOptions = {
|
||||
shouldApply?: () => boolean;
|
||||
/** Restore the previous listing without showing a pane error. */
|
||||
quiet?: boolean;
|
||||
/** Controls how a successful navigation updates per-pane history. Defaults to "push". */
|
||||
historyMode?: SftpNavHistoryTransitionMode;
|
||||
};
|
||||
|
||||
interface UseSftpPaneActionsResult {
|
||||
navigateTo: (side: "left" | "right", path: string, options?: SftpNavigateOptions) => Promise<SftpNavigateResult>;
|
||||
navigateBack: (side: "left" | "right") => Promise<SftpNavigateResult>;
|
||||
navigateForward: (side: "left" | "right") => Promise<SftpNavigateResult>;
|
||||
refresh: (side: "left" | "right", options?: { tabId?: string }) => Promise<void>;
|
||||
navigateUp: (side: "left" | "right") => Promise<void>;
|
||||
openEntry: (side: "left" | "right", entry: SftpFileEntry) => Promise<void>;
|
||||
@@ -151,6 +164,12 @@ export const useSftpPaneActions = ({
|
||||
new Map<string, { connectionId: string; path: string; files: SftpFileEntry[]; selectedFiles: Set<string>; filter: string }>(),
|
||||
);
|
||||
|
||||
// Track the in-flight navigation history transition per tab so a mid-flight
|
||||
// refresh (historyMode: "none") targeting the same unconfirmed destination
|
||||
// inherits the pending transition instead of leaving currentPath and
|
||||
// navHistory out of sync.
|
||||
const pendingNavHistoryRef = useRef(new Map<string, PendingSftpNavHistoryTransition>());
|
||||
|
||||
const navigateTo = useCallback(
|
||||
async (
|
||||
side: "left" | "right",
|
||||
@@ -183,6 +202,14 @@ export const useSftpPaneActions = ({
|
||||
);
|
||||
|
||||
const connectionId = pane.connection.id;
|
||||
const requestedHistoryMode: SftpNavHistoryTransitionMode = options?.historyMode ?? "push";
|
||||
const historyMode = resolveSftpEffectiveNavHistoryMode({
|
||||
requestedMode: requestedHistoryMode,
|
||||
pending: pendingNavHistoryRef.current.get(targetTabId),
|
||||
connectionId,
|
||||
targetPath: normalizedPath,
|
||||
isSamePath: isSameSftpPath,
|
||||
});
|
||||
const requestId = ++navSeqRef.current[side];
|
||||
const cacheKey = makeCacheKey(connectionId, normalizedPath, pane.filenameEncoding);
|
||||
const clearFilterForPathChange = shouldClearSftpFilterForPathChange(pane.connection.currentPath, normalizedPath);
|
||||
@@ -197,6 +224,7 @@ export const useSftpPaneActions = ({
|
||||
cached.files
|
||||
) {
|
||||
tabNavSeqRef.current.set(targetTabId, requestId);
|
||||
pendingNavHistoryRef.current.delete(targetTabId);
|
||||
lastConfirmedRef.current.set(targetTabId, {
|
||||
connectionId,
|
||||
path: normalizedPath,
|
||||
@@ -214,6 +242,13 @@ export const useSftpPaneActions = ({
|
||||
error: null,
|
||||
selectedFiles: EMPTY_SET,
|
||||
filter: clearFilterForPathChange ? "" : prev.filter,
|
||||
navHistory: applySftpNavHistoryTransition({
|
||||
history: prev.navHistory,
|
||||
currentPath: prev.connection?.currentPath,
|
||||
targetPath: normalizedPath,
|
||||
mode: historyMode,
|
||||
isSamePath: isSameSftpPath,
|
||||
}),
|
||||
}));
|
||||
if (!pane.connection.isLocal) {
|
||||
// Use hostId as the shared cache key — this is safe because the
|
||||
@@ -252,6 +287,11 @@ export const useSftpPaneActions = ({
|
||||
const previousFilter = confirmed.filter;
|
||||
const previousError = pane.error;
|
||||
const isTargetRequestCurrent = () => tabNavSeqRef.current.get(targetTabId) === requestId;
|
||||
const clearPendingNavHistoryIfCurrent = () => {
|
||||
if (isTargetRequestCurrent()) {
|
||||
pendingNavHistoryRef.current.delete(targetTabId);
|
||||
}
|
||||
};
|
||||
const getTargetPane = () => {
|
||||
const currentSideTabs = side === "left" ? leftTabsRef.current : rightTabsRef.current;
|
||||
return currentSideTabs.tabs.find((t) => t.id === targetTabId) ?? null;
|
||||
@@ -262,6 +302,7 @@ export const useSftpPaneActions = ({
|
||||
);
|
||||
const restoreConfirmedStateIfCurrent = () => {
|
||||
if (!isTargetRequestCurrent()) return;
|
||||
pendingNavHistoryRef.current.delete(targetTabId);
|
||||
updateTab(side, targetTabId, (prev) => {
|
||||
if (prev.connection?.id !== connectionId || !isTargetRequestCurrent()) return prev;
|
||||
return {
|
||||
@@ -276,6 +317,15 @@ export const useSftpPaneActions = ({
|
||||
});
|
||||
};
|
||||
tabNavSeqRef.current.set(targetTabId, requestId);
|
||||
if (historyMode !== "none") {
|
||||
pendingNavHistoryRef.current.set(targetTabId, {
|
||||
connectionId,
|
||||
path: normalizedPath,
|
||||
mode: historyMode,
|
||||
});
|
||||
} else {
|
||||
pendingNavHistoryRef.current.delete(targetTabId);
|
||||
}
|
||||
// Keep existing files visible during loading — the loading overlay
|
||||
// (pointer-events-none) prevents interaction. This avoids blanking a tab
|
||||
// that gets superseded by another tab navigating on the same side.
|
||||
@@ -305,6 +355,7 @@ export const useSftpPaneActions = ({
|
||||
restoreConfirmedStateIfCurrent();
|
||||
return "aborted";
|
||||
}
|
||||
clearPendingNavHistoryIfCurrent();
|
||||
clearCacheForConnection(pane.connection.id);
|
||||
// For background tabs (explicit tabId), update that tab directly
|
||||
// instead of handleSessionError which targets the active tab.
|
||||
@@ -331,6 +382,7 @@ export const useSftpPaneActions = ({
|
||||
restoreConfirmedStateIfCurrent();
|
||||
return "aborted";
|
||||
}
|
||||
clearPendingNavHistoryIfCurrent();
|
||||
await releaseConnection(pane.connection.id);
|
||||
if (options?.tabId) {
|
||||
updateTab(side, targetTabId, (prev) => ({
|
||||
@@ -368,6 +420,8 @@ export const useSftpPaneActions = ({
|
||||
timestamp: Date.now(),
|
||||
}, { ttlMs: dirCacheTtlMs });
|
||||
|
||||
clearPendingNavHistoryIfCurrent();
|
||||
|
||||
lastConfirmedRef.current.set(targetTabId, {
|
||||
connectionId,
|
||||
path: normalizedPath,
|
||||
@@ -385,6 +439,13 @@ export const useSftpPaneActions = ({
|
||||
loading: false,
|
||||
selectedFiles: EMPTY_SET,
|
||||
filter: clearFilterForPathChange ? "" : prev.filter,
|
||||
navHistory: applySftpNavHistoryTransition({
|
||||
history: prev.navHistory,
|
||||
currentPath: previousPath,
|
||||
targetPath: normalizedPath,
|
||||
mode: historyMode,
|
||||
isSamePath: isSameSftpPath,
|
||||
}),
|
||||
}));
|
||||
if (!pane.connection.isLocal) {
|
||||
setSharedRemoteHostCache(getActivePaneCacheKey(side, pane.connection.hostId, pane.connection.id), {
|
||||
@@ -407,6 +468,7 @@ export const useSftpPaneActions = ({
|
||||
restoreConfirmedStateIfCurrent();
|
||||
return "aborted";
|
||||
}
|
||||
clearPendingNavHistoryIfCurrent();
|
||||
let navigationFailed = false;
|
||||
updateTab(side, targetTabId, (prev) => {
|
||||
if (prev.connection?.id !== connectionId) {
|
||||
@@ -480,7 +542,11 @@ export const useSftpPaneActions = ({
|
||||
}
|
||||
return;
|
||||
}
|
||||
await navigateTo(side, pane.connection.currentPath, { force: true, tabId: options?.tabId });
|
||||
await navigateTo(side, pane.connection.currentPath, {
|
||||
force: true,
|
||||
tabId: options?.tabId,
|
||||
historyMode: "none",
|
||||
});
|
||||
} else if (!pane?.connection && pane?.error) {
|
||||
// For background tabs, don't trigger reconnection (it operates on
|
||||
// the active tab). Just leave the error state for the user to see
|
||||
@@ -504,6 +570,30 @@ export const useSftpPaneActions = ({
|
||||
[getActivePane, leftTabsRef, rightTabsRef, navigateTo, updateActiveTab, lastConnectedHostRef, sftpSessionsRef],
|
||||
);
|
||||
|
||||
const navigateBack = useCallback(
|
||||
async (side: "left" | "right"): Promise<SftpNavigateResult> => {
|
||||
const pane = getActivePane(side);
|
||||
if (!pane?.connection) return "aborted";
|
||||
const history = pane.navHistory ?? createNavHistory(pane.connection.currentPath);
|
||||
const step = goBack(history);
|
||||
if (!step.path) return "aborted";
|
||||
return navigateTo(side, step.path, { historyMode: "back" });
|
||||
},
|
||||
[getActivePane, navigateTo],
|
||||
);
|
||||
|
||||
const navigateForward = useCallback(
|
||||
async (side: "left" | "right"): Promise<SftpNavigateResult> => {
|
||||
const pane = getActivePane(side);
|
||||
if (!pane?.connection) return "aborted";
|
||||
const history = pane.navHistory ?? createNavHistory(pane.connection.currentPath);
|
||||
const step = goForward(history);
|
||||
if (!step.path) return "aborted";
|
||||
return navigateTo(side, step.path, { historyMode: "forward" });
|
||||
},
|
||||
[getActivePane, navigateTo],
|
||||
);
|
||||
|
||||
const navigateUp = useCallback(
|
||||
async (side: "left" | "right") => {
|
||||
const pane = getActivePane(side);
|
||||
@@ -1060,6 +1150,8 @@ export const useSftpPaneActions = ({
|
||||
|
||||
return {
|
||||
navigateTo,
|
||||
navigateBack,
|
||||
navigateForward,
|
||||
refresh,
|
||||
navigateUp,
|
||||
openEntry,
|
||||
|
||||
@@ -98,6 +98,7 @@ export const useSftpPaneSorting = (): UseSftpPaneSortingResult => {
|
||||
|
||||
const rafIdRef = useRef<number | null>(null);
|
||||
const lastClientXRef = useRef(0);
|
||||
const activeDragCleanupRef = useRef<(() => void) | null>(null);
|
||||
|
||||
const applyColumnWidth = useCallback(() => {
|
||||
if (!resizingRef.current) return;
|
||||
@@ -121,6 +122,20 @@ export const useSftpPaneSorting = (): UseSftpPaneSortingResult => {
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const cleanupActiveResize = useCallback(() => {
|
||||
if (rafIdRef.current !== null) {
|
||||
cancelAnimationFrame(rafIdRef.current);
|
||||
rafIdRef.current = null;
|
||||
}
|
||||
resizingRef.current = null;
|
||||
activeDragCleanupRef.current?.();
|
||||
activeDragCleanupRef.current = null;
|
||||
}, []);
|
||||
|
||||
useEffect(() => () => {
|
||||
cleanupActiveResize();
|
||||
}, [cleanupActiveResize]);
|
||||
|
||||
const handleResizeMove = useCallback((e: MouseEvent) => {
|
||||
if (!resizingRef.current) return;
|
||||
lastClientXRef.current = e.clientX;
|
||||
@@ -132,13 +147,15 @@ export const useSftpPaneSorting = (): UseSftpPaneSortingResult => {
|
||||
}, [applyColumnWidth]);
|
||||
|
||||
const handleResizeEnd = useCallback(() => {
|
||||
if (rafIdRef.current !== null) cancelAnimationFrame(rafIdRef.current);
|
||||
if (rafIdRef.current !== null) {
|
||||
cancelAnimationFrame(rafIdRef.current);
|
||||
rafIdRef.current = null;
|
||||
}
|
||||
applyColumnWidth();
|
||||
rafIdRef.current = null;
|
||||
resizingRef.current = null;
|
||||
document.removeEventListener("mousemove", handleResizeMove);
|
||||
document.removeEventListener("mouseup", handleResizeEnd);
|
||||
}, [applyColumnWidth, handleResizeMove]);
|
||||
activeDragCleanupRef.current?.();
|
||||
activeDragCleanupRef.current = null;
|
||||
}, [applyColumnWidth]);
|
||||
|
||||
const handleResizeStart = (
|
||||
field: keyof ColumnWidths,
|
||||
@@ -146,6 +163,7 @@ export const useSftpPaneSorting = (): UseSftpPaneSortingResult => {
|
||||
) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
cleanupActiveResize();
|
||||
lastClientXRef.current = e.clientX;
|
||||
resizingRef.current = {
|
||||
field,
|
||||
@@ -154,6 +172,10 @@ export const useSftpPaneSorting = (): UseSftpPaneSortingResult => {
|
||||
};
|
||||
document.addEventListener("mousemove", handleResizeMove);
|
||||
document.addEventListener("mouseup", handleResizeEnd);
|
||||
activeDragCleanupRef.current = () => {
|
||||
document.removeEventListener("mousemove", handleResizeMove);
|
||||
document.removeEventListener("mouseup", handleResizeEnd);
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -332,6 +332,28 @@ function notifyPathConflict(
|
||||
notify.warning(message, t("sftp.transfers.pathConflict.title"));
|
||||
}
|
||||
|
||||
export function applyTransferProgressToRows(
|
||||
rows: TransferTask[],
|
||||
taskId: string,
|
||||
updates: Partial<TransferTask>,
|
||||
isLatched: (rootId: string, rowId: string) => boolean = isTransferOrRootPauseLatched,
|
||||
): TransferTask[] {
|
||||
const index = rows.findIndex((row) => row.id === taskId);
|
||||
if (index === -1) return rows;
|
||||
const row = rows[index];
|
||||
const merged = { ...row, ...updates };
|
||||
const latched = isLatched(row.parentTaskId ?? row.id, row.id);
|
||||
const nextRow = (
|
||||
(latched || row.status === "paused" || row.status === "pausing")
|
||||
&& (updates.status === "transferring" || updates.status === "pending" || updates.status === "queued")
|
||||
)
|
||||
? { ...merged, status: row.status, speed: 0 }
|
||||
: merged;
|
||||
const next = rows.slice();
|
||||
next[index] = nextRow;
|
||||
return next;
|
||||
}
|
||||
|
||||
export const useSftpTransfers = ({
|
||||
ownerId,
|
||||
canPrepareAdoption,
|
||||
@@ -511,18 +533,7 @@ export const useSftpTransfers = ({
|
||||
pendingProgressByIdRef.current.set(taskId, { ...prevPending, ...updates });
|
||||
// Keep ref hot for cancel/pause checks without waiting for paint.
|
||||
// A byte tick that still says "transferring" must not reopen a latched pause.
|
||||
transfersRef.current = transfersRef.current.map((row) => {
|
||||
if (row.id !== taskId) return row;
|
||||
const merged = { ...row, ...updates };
|
||||
const latched = isTransferOrRootPauseLatched(row.parentTaskId ?? row.id, row.id);
|
||||
if (
|
||||
(latched || row.status === "paused" || row.status === "pausing")
|
||||
&& (updates.status === "transferring" || updates.status === "pending" || updates.status === "queued")
|
||||
) {
|
||||
return { ...merged, status: row.status, speed: 0 };
|
||||
}
|
||||
return merged;
|
||||
});
|
||||
transfersRef.current = applyTransferProgressToRows(transfersRef.current, taskId, updates);
|
||||
scheduleProgressFlush();
|
||||
}, [scheduleProgressFlush]);
|
||||
useEffect(() => () => {
|
||||
|
||||
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
import vm from 'node:vm';
|
||||
import React, { useCallback, useRef, useSyncExternalStore } from 'react';
|
||||
import React, { memo, useCallback, useRef, useSyncExternalStore } from 'react';
|
||||
import { act, create } from 'react-test-renderer';
|
||||
import ts from 'typescript';
|
||||
import { resolveSystemSidebarSession } from '../../domain/systemManager/resolveSystemSession';
|
||||
@@ -25,10 +25,10 @@ const env = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boole
|
||||
test('workspace browser follows focus without replacing the earlier terminal context', async () => {
|
||||
const previous = env.IS_REACT_ACT_ENVIRONMENT;
|
||||
env.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
const browserSlot = ast.statements.find((node) => ts.isFunctionDeclaration(node) && node.name?.text === 'SidePanelBrowserSlot');
|
||||
const browserSlot = ast.statements.find((node) => ts.isFunctionDeclaration(node) && node.name?.text === 'SidePanelBrowserSlotInner');
|
||||
assert.ok(browserSlot);
|
||||
const slotCode = ts.transpile(browserSlot.getText(ast), { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React });
|
||||
const Slot = vm.runInNewContext(`${slotCode}; SidePanelBrowserSlot`, {
|
||||
const Slot = vm.runInNewContext(`${slotCode}; SidePanelBrowserSlotInner`, {
|
||||
React, useRef, useSidePanelLiveSnapshotForTab: useSnapshot, resolveSystemSidebarSession, collectSessionIds,
|
||||
sidePanelHiddenPanelClassName: (hidden: boolean) => hidden ? 'hidden' : 'visible',
|
||||
HostBrowserSidePanel: (props: object) => React.createElement('div', { ...props, 'data-browser-context': true }),
|
||||
@@ -133,3 +133,74 @@ test('new panels wait for their own snapshot and workspace panes accept focus ch
|
||||
env.IS_REACT_ACT_ENVIRONMENT = previous;
|
||||
}
|
||||
});
|
||||
|
||||
test('SidePanelBrowserSlot is memoized and skips re-renders when props are unchanged', async () => {
|
||||
const previous = env.IS_REACT_ACT_ENVIRONMENT;
|
||||
env.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
assert.match(
|
||||
source,
|
||||
/export const SidePanelBrowserSlot = memo\(SidePanelBrowserSlotInner\);/,
|
||||
'SidePanelBrowserSlot must be wrapped in React.memo like sibling side-panel slots',
|
||||
);
|
||||
const browserSlot = ast.statements.find(
|
||||
(node) => ts.isFunctionDeclaration(node) && node.name?.text === 'SidePanelBrowserSlotInner',
|
||||
);
|
||||
assert.ok(browserSlot);
|
||||
const slotCode = ts.transpile(browserSlot.getText(ast), {
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.React,
|
||||
});
|
||||
let renderCount = 0;
|
||||
const MemoSlot = vm.runInNewContext(
|
||||
`${slotCode}; memo(function TrackedBrowserSlot(props) { onRender(); return SidePanelBrowserSlotInner(props); })`,
|
||||
{
|
||||
React,
|
||||
memo,
|
||||
onRender: () => { renderCount += 1; },
|
||||
useRef,
|
||||
useSidePanelLiveSnapshotForTab: useSnapshot,
|
||||
resolveSystemSidebarSession,
|
||||
collectSessionIds,
|
||||
sidePanelHiddenPanelClassName: (hidden: boolean) => (hidden ? 'hidden' : 'visible'),
|
||||
HostBrowserSidePanel: (props: object) => React.createElement('div', { ...props, 'data-browser-context': true }),
|
||||
},
|
||||
) as React.ComponentType<{ tabId: string; ctx: object; isVisible: boolean }>;
|
||||
|
||||
const sessionA = { id: 'session-a', hostId: 'host-a', protocol: 'ssh' };
|
||||
const ctx = {
|
||||
sessions: [sessionA],
|
||||
workspaceById: new Map(),
|
||||
sessionHostsMap: new Map([['session-a', { id: 'host-a', hostname: 'a', protocol: 'ssh' }]]),
|
||||
sftpAuthHostBySessionId: new Map(),
|
||||
effectiveHosts: [],
|
||||
keys: [],
|
||||
identities: [],
|
||||
knownHosts: [],
|
||||
terminalSettings: {},
|
||||
t: (key: string) => key,
|
||||
};
|
||||
|
||||
let renderer: ReturnType<typeof create> | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
renderer = create(React.createElement(MemoSlot, { tabId: 'session-a', ctx, isVisible: false }));
|
||||
});
|
||||
assert.equal(renderCount, 1);
|
||||
|
||||
// Re-rendering the parent with identical tabId/ctx/isVisible must be skipped by memo.
|
||||
await act(async () => {
|
||||
renderer!.update(React.createElement(MemoSlot, { tabId: 'session-a', ctx, isVisible: false }));
|
||||
});
|
||||
assert.equal(renderCount, 1);
|
||||
|
||||
// Visibility changes must still re-render the slot.
|
||||
await act(async () => {
|
||||
renderer!.update(React.createElement(MemoSlot, { tabId: 'session-a', ctx, isVisible: true }));
|
||||
});
|
||||
assert.equal(renderCount, 2);
|
||||
} finally {
|
||||
await act(async () => renderer?.unmount());
|
||||
sidePanelLiveStore.update(SIDE_PANEL_INACTIVE_LIVE_SNAPSHOT);
|
||||
env.IS_REACT_ACT_ENVIRONMENT = previous;
|
||||
}
|
||||
});
|
||||
@@ -44,3 +44,35 @@ test('host tree restored layout width is clamped', () => {
|
||||
assert.equal(clampTerminalHostTreeWidth(0), 176);
|
||||
assert.equal(TERMINAL_HOST_TREE_DEFAULT_WIDTH, 220);
|
||||
});
|
||||
|
||||
test('host tree layout width tracks animated transition flag and deduplicates identical updates', () => {
|
||||
terminalHostTreeStore.setLayoutWidth(0, false);
|
||||
let notifications = 0;
|
||||
const unsubscribe = terminalHostTreeStore.subscribe(() => {
|
||||
notifications += 1;
|
||||
});
|
||||
|
||||
try {
|
||||
terminalHostTreeStore.setLayoutWidth(220, true);
|
||||
assert.equal(terminalHostTreeStore.getLayoutWidth(), 220);
|
||||
assert.equal(terminalHostTreeStore.getLayoutTransitionAnimated(), true);
|
||||
assert.equal(notifications, 1);
|
||||
|
||||
// Repeating same (width, animated) is a no-op.
|
||||
terminalHostTreeStore.setLayoutWidth(220, true);
|
||||
assert.equal(notifications, 1);
|
||||
|
||||
// Clearing animated flag notifies once while keeping layoutWidth intact.
|
||||
terminalHostTreeStore.setLayoutTransitionAnimated(false);
|
||||
assert.equal(terminalHostTreeStore.getLayoutWidth(), 220);
|
||||
assert.equal(terminalHostTreeStore.getLayoutTransitionAnimated(), false);
|
||||
assert.equal(notifications, 2);
|
||||
|
||||
// Repeating clear is a no-op.
|
||||
terminalHostTreeStore.setLayoutTransitionAnimated(false);
|
||||
assert.equal(notifications, 2);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
terminalHostTreeStore.setLayoutWidth(0, false);
|
||||
}
|
||||
});
|
||||
@@ -26,14 +26,18 @@ function readIsOpen(): boolean {
|
||||
|
||||
class TerminalHostTreeStore {
|
||||
private isOpen = readIsOpen();
|
||||
/** Live sidebar width (0 when collapsed) for top-tab alignment. */
|
||||
/** Target sidebar width (0 when collapsed or hidden behind root pages) for top-tab and surface alignment. */
|
||||
private layoutWidth = 0;
|
||||
/** Whether layout consumers should animate transitions to `layoutWidth` (false for instant snaps and drag resize). */
|
||||
private layoutTransitionAnimated = false;
|
||||
private listeners = new Set<Listener>();
|
||||
|
||||
getIsOpen = () => this.isOpen;
|
||||
|
||||
getLayoutWidth = () => this.layoutWidth;
|
||||
|
||||
getLayoutTransitionAnimated = () => this.layoutTransitionAnimated;
|
||||
|
||||
setIsOpen = (open: boolean) => {
|
||||
if (this.isOpen === open) return;
|
||||
this.isOpen = open;
|
||||
@@ -44,10 +48,17 @@ class TerminalHostTreeStore {
|
||||
this.listeners.forEach((listener) => listener());
|
||||
};
|
||||
|
||||
setLayoutWidth = (width: number) => {
|
||||
setLayoutWidth = (width: number, animated = false) => {
|
||||
const next = Math.max(0, Math.round(width));
|
||||
if (this.layoutWidth === next) return;
|
||||
if (this.layoutWidth === next && this.layoutTransitionAnimated === animated) return;
|
||||
this.layoutWidth = next;
|
||||
this.layoutTransitionAnimated = animated;
|
||||
this.listeners.forEach((listener) => listener());
|
||||
};
|
||||
|
||||
setLayoutTransitionAnimated = (animated: boolean) => {
|
||||
if (this.layoutTransitionAnimated === animated) return;
|
||||
this.layoutTransitionAnimated = animated;
|
||||
this.listeners.forEach((listener) => listener());
|
||||
};
|
||||
|
||||
@@ -82,3 +93,11 @@ export const useTerminalHostTreeLayoutWidth = () => {
|
||||
terminalHostTreeStore.getLayoutWidth,
|
||||
);
|
||||
};
|
||||
|
||||
export const useTerminalHostTreeLayoutTransitionAnimated = (): boolean => {
|
||||
return useSyncExternalStore(
|
||||
terminalHostTreeStore.subscribe,
|
||||
terminalHostTreeStore.getLayoutTransitionAnimated,
|
||||
terminalHostTreeStore.getLayoutTransitionAnimated,
|
||||
);
|
||||
};
|
||||
@@ -116,6 +116,7 @@ export interface SendToCattyContext {
|
||||
commandBlocklist?: string[];
|
||||
commandTimeout?: number;
|
||||
responseIdleTimeout?: number;
|
||||
toolOutputMaxChars?: number;
|
||||
terminalSessions: TerminalSessionInfo[];
|
||||
webSearchConfig?: WebSearchConfig | null;
|
||||
getExecutorContext?: () => ExecutorContext;
|
||||
|
||||
@@ -3,14 +3,28 @@ import test from 'node:test';
|
||||
import React from 'react';
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
|
||||
|
||||
import { STORAGE_KEY_AI_COMMAND_BLOCKLIST } from '../../infrastructure/config/storageKeys.ts';
|
||||
import { useAISettingsState } from './useAISettingsState.ts';
|
||||
import {
|
||||
STORAGE_KEY_AI_ACTIVE_PROVIDER,
|
||||
STORAGE_KEY_AI_AGENT_MODEL_MAP,
|
||||
STORAGE_KEY_AI_AGENT_PROVIDER_MAP,
|
||||
STORAGE_KEY_AI_COMMAND_BLOCKLIST,
|
||||
STORAGE_KEY_AI_PERMISSION_MODE,
|
||||
STORAGE_KEY_AI_PROVIDERS,
|
||||
STORAGE_KEY_AI_SESSION_MESSAGE_CAP,
|
||||
STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION,
|
||||
} from '../../infrastructure/config/storageKeys.ts';
|
||||
import type { ProviderConfig } from '../../infrastructure/ai/types.ts';
|
||||
import { useAISettingsState, useSharedAISettingsState } from './useAISettingsState.ts';
|
||||
|
||||
test('command blocklist storage events refresh the mounted AI settings state', async () => {
|
||||
function setupStorageHarness() {
|
||||
const store = new Map<string, string>();
|
||||
const writes: Array<[string, string]> = [];
|
||||
const fakeStorage = {
|
||||
getItem: (key: string) => store.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => store.set(key, String(value)),
|
||||
setItem: (key: string, value: string) => {
|
||||
writes.push([key, String(value)]);
|
||||
store.set(key, String(value));
|
||||
},
|
||||
removeItem: (key: string) => store.delete(key),
|
||||
};
|
||||
const fakeWindow = new EventTarget() as EventTarget & { netcatty?: unknown };
|
||||
@@ -26,6 +40,28 @@ test('command blocklist storage events refresh the mounted AI settings state', a
|
||||
Object.defineProperty(globalThis, 'localStorage', { value: fakeStorage, configurable: true });
|
||||
Object.defineProperty(globalThis, 'window', { value: fakeWindow, configurable: true });
|
||||
|
||||
return {
|
||||
store,
|
||||
writes,
|
||||
fakeStorage,
|
||||
fakeWindow,
|
||||
dispatchStorage: (key: string) => {
|
||||
const event = new Event('storage');
|
||||
Object.defineProperty(event, 'key', { value: key });
|
||||
fakeWindow.dispatchEvent(event);
|
||||
},
|
||||
cleanup: () => {
|
||||
globals.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
|
||||
if (previousLocalStorage) Object.defineProperty(globalThis, 'localStorage', previousLocalStorage);
|
||||
else delete globals.localStorage;
|
||||
if (previousWindow) Object.defineProperty(globalThis, 'window', previousWindow);
|
||||
else delete globals.window;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('command blocklist storage events refresh the mounted AI settings state', async () => {
|
||||
const env = setupStorageHarness();
|
||||
let currentBlocklist: string[] = [];
|
||||
let renderer: ReactTestRenderer | null = null;
|
||||
const Probe = () => {
|
||||
@@ -37,21 +73,159 @@ test('command blocklist storage events refresh the mounted AI settings state', a
|
||||
await act(async () => {
|
||||
renderer = create(React.createElement(Probe));
|
||||
});
|
||||
fakeStorage.setItem(STORAGE_KEY_AI_COMMAND_BLOCKLIST, JSON.stringify(['company-blocked-command']));
|
||||
const event = new Event('storage');
|
||||
Object.defineProperty(event, 'key', { value: STORAGE_KEY_AI_COMMAND_BLOCKLIST });
|
||||
env.fakeStorage.setItem(STORAGE_KEY_AI_COMMAND_BLOCKLIST, JSON.stringify(['company-blocked-command']));
|
||||
await act(async () => {
|
||||
fakeWindow.dispatchEvent(event);
|
||||
env.dispatchStorage(STORAGE_KEY_AI_COMMAND_BLOCKLIST);
|
||||
});
|
||||
assert.deepEqual(currentBlocklist, ['company-blocked-command']);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
renderer?.unmount();
|
||||
});
|
||||
globals.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
|
||||
if (previousLocalStorage) Object.defineProperty(globalThis, 'localStorage', previousLocalStorage);
|
||||
else delete globals.localStorage;
|
||||
if (previousWindow) Object.defineProperty(globalThis, 'window', previousWindow);
|
||||
else delete globals.window;
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('useSharedAISettingsState preserves invalid-permission-mode ignore option vs useAISettingsState fallback', async () => {
|
||||
const env = setupStorageHarness();
|
||||
env.fakeStorage.setItem(STORAGE_KEY_AI_PERMISSION_MODE, 'auto');
|
||||
|
||||
let sharedMode = '';
|
||||
let settingsPageMode = '';
|
||||
let renderer: ReactTestRenderer | null = null;
|
||||
|
||||
const Probe = () => {
|
||||
sharedMode = useSharedAISettingsState({ ignoreInvalidPermissionModeOnStorage: true }).globalPermissionMode;
|
||||
settingsPageMode = useAISettingsState().globalPermissionMode;
|
||||
return null;
|
||||
};
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
renderer = create(React.createElement(Probe));
|
||||
});
|
||||
assert.equal(sharedMode, 'auto');
|
||||
assert.equal(settingsPageMode, 'auto');
|
||||
|
||||
env.fakeStorage.setItem(STORAGE_KEY_AI_PERMISSION_MODE, 'bogus-mode');
|
||||
await act(async () => {
|
||||
env.dispatchStorage(STORAGE_KEY_AI_PERMISSION_MODE);
|
||||
});
|
||||
|
||||
assert.equal(sharedMode, 'auto');
|
||||
assert.equal(settingsPageMode, 'confirm');
|
||||
} finally {
|
||||
await act(async () => {
|
||||
renderer?.unmount();
|
||||
});
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('useSharedAISettingsState onRemoveProvider replaces localStorage map cleanup and updateProvider skips no-op writes', async () => {
|
||||
const env = setupStorageHarness();
|
||||
const provider: ProviderConfig = {
|
||||
id: 'prov-1',
|
||||
providerId: 'openai',
|
||||
name: 'OpenAI',
|
||||
apiKey: 'secret',
|
||||
enabled: true,
|
||||
defaultModel: 'gpt-4o',
|
||||
modelContextWindows: { 'gpt-4o': 128000 },
|
||||
};
|
||||
env.fakeStorage.setItem(STORAGE_KEY_AI_PROVIDERS, JSON.stringify([provider]));
|
||||
env.fakeStorage.setItem(STORAGE_KEY_AI_ACTIVE_PROVIDER, 'prov-1');
|
||||
env.fakeStorage.setItem(STORAGE_KEY_AI_AGENT_PROVIDER_MAP, JSON.stringify({ catty: 'prov-1' }));
|
||||
env.fakeStorage.setItem(STORAGE_KEY_AI_AGENT_MODEL_MAP, JSON.stringify({ catty: 'gpt-4o' }));
|
||||
env.writes.length = 0;
|
||||
|
||||
const removedIds: string[] = [];
|
||||
let api: ReturnType<typeof useSharedAISettingsState> | null = null;
|
||||
let renderer: ReactTestRenderer | null = null;
|
||||
|
||||
const Probe = () => {
|
||||
const onRemoveProvider = React.useCallback((id: string) => {
|
||||
removedIds.push(id);
|
||||
}, []);
|
||||
api = useSharedAISettingsState({ onRemoveProvider });
|
||||
return null;
|
||||
};
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
renderer = create(React.createElement(Probe));
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
api!.updateProvider('prov-1', {
|
||||
name: 'OpenAI',
|
||||
modelContextWindows: { 'gpt-4o': 128000 },
|
||||
});
|
||||
});
|
||||
assert.equal(
|
||||
env.writes.filter(([key]) => key === STORAGE_KEY_AI_PROVIDERS).length,
|
||||
0,
|
||||
'no-op provider patch should not rewrite localStorage',
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
api!.removeProvider('prov-1');
|
||||
});
|
||||
assert.deepEqual(removedIds, ['prov-1']);
|
||||
assert.equal(api!.activeProviderId, '');
|
||||
assert.equal(
|
||||
env.writes.filter(([key]) => key === STORAGE_KEY_AI_AGENT_PROVIDER_MAP || key === STORAGE_KEY_AI_AGENT_MODEL_MAP).length,
|
||||
0,
|
||||
'custom onRemoveProvider must replace default localStorage agent-map cleanup',
|
||||
);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
renderer?.unmount();
|
||||
});
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('SettingsPage-only storage keys do not trigger re-renders in useSharedAISettingsState', async () => {
|
||||
const env = setupStorageHarness();
|
||||
let sharedRenders = 0;
|
||||
let settingsCap = 0;
|
||||
let renderer: ReactTestRenderer | null = null;
|
||||
|
||||
const SharedProbe = () => {
|
||||
sharedRenders += 1;
|
||||
useSharedAISettingsState({ ignoreInvalidPermissionModeOnStorage: true });
|
||||
return null;
|
||||
};
|
||||
const SettingsProbe = () => {
|
||||
settingsCap = useAISettingsState().aiSessionMessageCap;
|
||||
return null;
|
||||
};
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
renderer = create(
|
||||
React.createElement(React.Fragment, null,
|
||||
React.createElement(SharedProbe),
|
||||
React.createElement(SettingsProbe),
|
||||
),
|
||||
);
|
||||
});
|
||||
const rendersAfterMount = sharedRenders;
|
||||
|
||||
env.fakeStorage.setItem(STORAGE_KEY_AI_SESSION_MESSAGE_CAP, '500');
|
||||
env.fakeStorage.setItem(STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION, 'false');
|
||||
await act(async () => {
|
||||
env.dispatchStorage(STORAGE_KEY_AI_SESSION_MESSAGE_CAP);
|
||||
env.dispatchStorage(STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION);
|
||||
});
|
||||
|
||||
assert.equal(settingsCap, 500);
|
||||
assert.equal(sharedRenders, rendersAfterMount);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
renderer?.unmount();
|
||||
});
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
STORAGE_KEY_AI_COMMAND_TIMEOUT,
|
||||
STORAGE_KEY_AI_RESPONSE_IDLE_TIMEOUT,
|
||||
STORAGE_KEY_AI_MAX_ITERATIONS,
|
||||
STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
STORAGE_KEY_AI_SESSION_MESSAGE_CAP,
|
||||
STORAGE_KEY_AI_AGENT_MODEL_MAP,
|
||||
STORAGE_KEY_AI_AGENT_PROVIDER_MAP,
|
||||
@@ -39,6 +40,10 @@ import {
|
||||
DEFAULT_AI_SESSION_MESSAGE_CAP,
|
||||
normalizeAiSessionMessageCap,
|
||||
} from '../../domain/aiSessionMessageCap';
|
||||
import {
|
||||
DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
normalizeAiToolOutputMaxChars,
|
||||
} from '../../domain/aiToolOutputLimit';
|
||||
import { AI_STATE_CHANGED_EVENT, emitAIStateChanged } from './aiStateEvents';
|
||||
import { getAIBridge } from './aiStateSnapshots';
|
||||
import { useStoredBoolean } from './useStoredBoolean';
|
||||
@@ -59,7 +64,44 @@ function readToolIntegrationMode(): AIToolIntegrationMode {
|
||||
: 'mcp';
|
||||
}
|
||||
|
||||
export function useAISettingsState() {
|
||||
function providerPatchIsNoop(
|
||||
current: ProviderConfig,
|
||||
updates: Partial<ProviderConfig>,
|
||||
): boolean {
|
||||
for (const key of Object.keys(updates) as Array<keyof ProviderConfig>) {
|
||||
const nextValue = updates[key];
|
||||
const prevValue = current[key];
|
||||
if (nextValue === prevValue) continue;
|
||||
if (key === 'modelContextWindows') {
|
||||
const prevWindows = (prevValue ?? {}) as Record<string, number>;
|
||||
const nextWindows = (nextValue ?? {}) as Record<string, number>;
|
||||
const nextKeys = Object.keys(nextWindows);
|
||||
if (nextKeys.length !== Object.keys(prevWindows).length) return false;
|
||||
if (nextKeys.some((modelId) => prevWindows[modelId] !== nextWindows[modelId])) return false;
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export interface SharedAISettingsStateOptions {
|
||||
/**
|
||||
* When true, cross-window `storage` events with unrecognized permission mode
|
||||
* strings are ignored instead of falling back to `'confirm'`.
|
||||
*/
|
||||
ignoreInvalidPermissionModeOnStorage?: boolean;
|
||||
/**
|
||||
* Optional replacement for removing provider references from agent maps when
|
||||
* the caller already owns in-memory React state for those maps.
|
||||
*/
|
||||
onRemoveProvider?: (id: string) => void;
|
||||
}
|
||||
|
||||
export function useSharedAISettingsState(options?: SharedAISettingsStateOptions) {
|
||||
const ignoreInvalidPermissionModeOnStorage = options?.ignoreInvalidPermissionModeOnStorage ?? false;
|
||||
const onRemoveProvider = options?.onRemoveProvider;
|
||||
|
||||
const [providers, setProvidersRaw] = useState<ProviderConfig[]>(() =>
|
||||
localStorageAdapter.read<ProviderConfig[]>(STORAGE_KEY_AI_PROVIDERS) ?? []
|
||||
);
|
||||
@@ -92,10 +134,10 @@ export function useAISettingsState() {
|
||||
const [maxIterations, setMaxIterationsRaw] = useState<number>(() =>
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_MAX_ITERATIONS) ?? 20
|
||||
);
|
||||
const [aiSessionMessageCap, setAiSessionMessageCapRaw] = useState<number>(() =>
|
||||
normalizeAiSessionMessageCap(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP)
|
||||
?? DEFAULT_AI_SESSION_MESSAGE_CAP,
|
||||
const [toolOutputMaxChars, setToolOutputMaxCharsRaw] = useState<number>(() =>
|
||||
normalizeAiToolOutputMaxChars(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS)
|
||||
?? DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
)
|
||||
);
|
||||
const [webSearchConfig, setWebSearchConfigRaw] = useState<WebSearchConfig | null>(() =>
|
||||
@@ -104,14 +146,11 @@ export function useAISettingsState() {
|
||||
const [quickMessages, setQuickMessagesRaw] = useState<AIQuickMessage[]>(() =>
|
||||
sanitizeQuickMessages(localStorageAdapter.read<unknown>(STORAGE_KEY_AI_QUICK_MESSAGES)),
|
||||
);
|
||||
const [showTerminalSelectionAIAction, setShowTerminalSelectionAIAction] = useStoredBoolean(
|
||||
STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION,
|
||||
true,
|
||||
);
|
||||
|
||||
const setProviders = useCallback((value: ProviderConfig[] | ((prev: ProviderConfig[]) => ProviderConfig[])) => {
|
||||
setProvidersRaw((prev) => {
|
||||
const next = typeof value === 'function' ? value(prev) : value;
|
||||
if (next === prev) return prev;
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_PROVIDERS, next);
|
||||
return next;
|
||||
});
|
||||
@@ -122,9 +161,15 @@ export function useAISettingsState() {
|
||||
}, [setProviders]);
|
||||
|
||||
const updateProvider = useCallback((id: string, updates: Partial<ProviderConfig>) => {
|
||||
setProviders((prev) => prev.map((provider) => (
|
||||
provider.id === id ? { ...provider, ...updates } : provider
|
||||
)));
|
||||
setProviders((prev) => {
|
||||
const index = prev.findIndex((provider) => provider.id === id);
|
||||
if (index < 0) return prev;
|
||||
const current = prev[index];
|
||||
if (providerPatchIsNoop(current, updates)) return prev;
|
||||
const next = prev.slice();
|
||||
next[index] = { ...current, ...updates };
|
||||
return next;
|
||||
});
|
||||
}, [setProviders]);
|
||||
|
||||
const removeProvider = useCallback((id: string) => {
|
||||
@@ -135,6 +180,11 @@ export function useAISettingsState() {
|
||||
return '';
|
||||
});
|
||||
|
||||
if (onRemoveProvider) {
|
||||
onRemoveProvider(id);
|
||||
return;
|
||||
}
|
||||
|
||||
const agentProviderMap =
|
||||
localStorageAdapter.read<Record<string, string>>(STORAGE_KEY_AI_AGENT_PROVIDER_MAP) ?? {};
|
||||
const agentModelMap =
|
||||
@@ -146,7 +196,7 @@ export function useAISettingsState() {
|
||||
if (cleanup.modelMapChanged) {
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_MODEL_MAP, cleanup.agentModelMap);
|
||||
}
|
||||
}, [setProviders]);
|
||||
}, [onRemoveProvider, setProviders]);
|
||||
|
||||
const setActiveProviderId = useCallback((id: string) => {
|
||||
setActiveProviderIdRaw(id);
|
||||
@@ -208,10 +258,10 @@ export function useAISettingsState() {
|
||||
getAIBridge()?.aiMcpSetMaxIterations?.(value);
|
||||
}, []);
|
||||
|
||||
const setAiSessionMessageCap = useCallback((value: number) => {
|
||||
const normalizedValue = normalizeAiSessionMessageCap(value);
|
||||
setAiSessionMessageCapRaw(normalizedValue);
|
||||
localStorageAdapter.writeNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP, normalizedValue);
|
||||
const setToolOutputMaxChars = useCallback((value: number) => {
|
||||
const normalizedValue = normalizeAiToolOutputMaxChars(value);
|
||||
setToolOutputMaxCharsRaw(normalizedValue);
|
||||
localStorageAdapter.writeNumber(STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS, normalizedValue);
|
||||
}, []);
|
||||
|
||||
const setWebSearchConfig = useCallback((config: WebSearchConfig | null) => {
|
||||
@@ -249,14 +299,26 @@ export function useAISettingsState() {
|
||||
case STORAGE_KEY_AI_ACTIVE_MODEL:
|
||||
setActiveModelIdRaw(localStorageAdapter.readString(STORAGE_KEY_AI_ACTIVE_MODEL) ?? '');
|
||||
break;
|
||||
case STORAGE_KEY_AI_PERMISSION_MODE:
|
||||
setGlobalPermissionModeRaw(readPermissionMode());
|
||||
getAIBridge()?.aiMcpSetPermissionMode?.(readPermissionMode());
|
||||
case STORAGE_KEY_AI_PERMISSION_MODE: {
|
||||
if (ignoreInvalidPermissionModeOnStorage) {
|
||||
const mode = localStorageAdapter.readString(STORAGE_KEY_AI_PERMISSION_MODE);
|
||||
if (mode === 'observer' || mode === 'confirm' || mode === 'auto') {
|
||||
setGlobalPermissionModeRaw(mode);
|
||||
getAIBridge()?.aiMcpSetPermissionMode?.(mode);
|
||||
}
|
||||
} else {
|
||||
const mode = readPermissionMode();
|
||||
setGlobalPermissionModeRaw(mode);
|
||||
getAIBridge()?.aiMcpSetPermissionMode?.(mode);
|
||||
}
|
||||
break;
|
||||
case STORAGE_KEY_AI_TOOL_INTEGRATION_MODE:
|
||||
setToolIntegrationModeRaw(readToolIntegrationMode());
|
||||
getAIBridge()?.aiMcpSetToolIntegrationMode?.(readToolIntegrationMode());
|
||||
}
|
||||
case STORAGE_KEY_AI_TOOL_INTEGRATION_MODE: {
|
||||
const mode = readToolIntegrationMode();
|
||||
setToolIntegrationModeRaw(mode);
|
||||
getAIBridge()?.aiMcpSetToolIntegrationMode?.(mode);
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_EXTERNAL_AGENTS: {
|
||||
const agents = localStorageAdapter.read<ExternalAgentConfig[]>(STORAGE_KEY_AI_EXTERNAL_AGENTS);
|
||||
if (agents != null && !Array.isArray(agents)) break;
|
||||
@@ -294,14 +356,13 @@ export function useAISettingsState() {
|
||||
getAIBridge()?.aiMcpSetMaxIterations?.(iters);
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_SESSION_MESSAGE_CAP:
|
||||
setAiSessionMessageCapRaw(
|
||||
normalizeAiSessionMessageCap(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP)
|
||||
?? DEFAULT_AI_SESSION_MESSAGE_CAP,
|
||||
),
|
||||
);
|
||||
case STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS: {
|
||||
const limit = localStorageAdapter.readNumber(STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS)
|
||||
?? DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS;
|
||||
if (!Number.isFinite(limit)) break;
|
||||
setToolOutputMaxCharsRaw(normalizeAiToolOutputMaxChars(limit));
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_WEB_SEARCH:
|
||||
setWebSearchConfigRaw(localStorageAdapter.read<WebSearchConfig>(STORAGE_KEY_AI_WEB_SEARCH) ?? null);
|
||||
break;
|
||||
@@ -325,7 +386,7 @@ export function useAISettingsState() {
|
||||
window.removeEventListener('storage', handleStorage);
|
||||
window.removeEventListener(AI_STATE_CHANGED_EVENT, handleLocalStateChanged);
|
||||
};
|
||||
}, []);
|
||||
}, [ignoreInvalidPermissionModeOnStorage]);
|
||||
|
||||
useEffect(() => {
|
||||
const bridge = getAIBridge();
|
||||
@@ -365,14 +426,12 @@ export function useAISettingsState() {
|
||||
setResponseIdleTimeout,
|
||||
maxIterations,
|
||||
setMaxIterations,
|
||||
aiSessionMessageCap,
|
||||
setAiSessionMessageCap,
|
||||
toolOutputMaxChars,
|
||||
setToolOutputMaxChars,
|
||||
webSearchConfig,
|
||||
setWebSearchConfig,
|
||||
quickMessages,
|
||||
setQuickMessages,
|
||||
showTerminalSelectionAIAction,
|
||||
setShowTerminalSelectionAIAction,
|
||||
}), [
|
||||
providers,
|
||||
setProviders,
|
||||
@@ -400,12 +459,72 @@ export function useAISettingsState() {
|
||||
setResponseIdleTimeout,
|
||||
maxIterations,
|
||||
setMaxIterations,
|
||||
aiSessionMessageCap,
|
||||
setAiSessionMessageCap,
|
||||
toolOutputMaxChars,
|
||||
setToolOutputMaxChars,
|
||||
webSearchConfig,
|
||||
setWebSearchConfig,
|
||||
quickMessages,
|
||||
setQuickMessages,
|
||||
]);
|
||||
}
|
||||
|
||||
export function useAISettingsState() {
|
||||
const shared = useSharedAISettingsState();
|
||||
const [aiSessionMessageCap, setAiSessionMessageCapRaw] = useState<number>(() =>
|
||||
normalizeAiSessionMessageCap(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP)
|
||||
?? DEFAULT_AI_SESSION_MESSAGE_CAP,
|
||||
)
|
||||
);
|
||||
const [showTerminalSelectionAIAction, setShowTerminalSelectionAIAction] = useStoredBoolean(
|
||||
STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION,
|
||||
true,
|
||||
);
|
||||
|
||||
const setAiSessionMessageCap = useCallback((value: number) => {
|
||||
const normalizedValue = normalizeAiSessionMessageCap(value);
|
||||
setAiSessionMessageCapRaw(normalizedValue);
|
||||
localStorageAdapter.writeNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP, normalizedValue);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const syncMessageCap = (key: string | null) => {
|
||||
if (key !== STORAGE_KEY_AI_SESSION_MESSAGE_CAP) return;
|
||||
try {
|
||||
setAiSessionMessageCapRaw(
|
||||
normalizeAiSessionMessageCap(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP)
|
||||
?? DEFAULT_AI_SESSION_MESSAGE_CAP,
|
||||
),
|
||||
);
|
||||
} catch (err) {
|
||||
console.warn('[useAISettingsState] Failed to process AI settings storage change', key, err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleStorage = (event: StorageEvent) => syncMessageCap(event.key);
|
||||
const handleLocalStateChanged = (event: Event) => {
|
||||
syncMessageCap((event as CustomEvent<{ key?: string }>).detail?.key ?? null);
|
||||
};
|
||||
|
||||
window.addEventListener('storage', handleStorage);
|
||||
window.addEventListener(AI_STATE_CHANGED_EVENT, handleLocalStateChanged);
|
||||
return () => {
|
||||
window.removeEventListener('storage', handleStorage);
|
||||
window.removeEventListener(AI_STATE_CHANGED_EVENT, handleLocalStateChanged);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return useMemo(() => ({
|
||||
...shared,
|
||||
aiSessionMessageCap,
|
||||
setAiSessionMessageCap,
|
||||
showTerminalSelectionAIAction,
|
||||
setShowTerminalSelectionAIAction,
|
||||
}), [
|
||||
shared,
|
||||
aiSessionMessageCap,
|
||||
setAiSessionMessageCap,
|
||||
showTerminalSelectionAIAction,
|
||||
setShowTerminalSelectionAIAction,
|
||||
]);
|
||||
|
||||
+59
-363
@@ -1,18 +1,7 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
import {
|
||||
STORAGE_KEY_AI_PROVIDERS,
|
||||
STORAGE_KEY_AI_ACTIVE_PROVIDER,
|
||||
STORAGE_KEY_AI_ACTIVE_MODEL,
|
||||
STORAGE_KEY_AI_PERMISSION_MODE,
|
||||
STORAGE_KEY_AI_TOOL_INTEGRATION_MODE,
|
||||
STORAGE_KEY_AI_HOST_PERMISSIONS,
|
||||
STORAGE_KEY_AI_EXTERNAL_AGENTS,
|
||||
STORAGE_KEY_AI_DEFAULT_AGENT,
|
||||
STORAGE_KEY_AI_COMMAND_BLOCKLIST,
|
||||
STORAGE_KEY_AI_COMMAND_TIMEOUT,
|
||||
STORAGE_KEY_AI_RESPONSE_IDLE_TIMEOUT,
|
||||
STORAGE_KEY_AI_MAX_ITERATIONS,
|
||||
STORAGE_KEY_AI_SESSIONS,
|
||||
STORAGE_KEY_AI_SESSIONS_OVERFLOW,
|
||||
STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW,
|
||||
@@ -20,30 +9,15 @@ import {
|
||||
STORAGE_KEY_AI_AGENT_MODEL_MAP,
|
||||
STORAGE_KEY_AI_AGENT_PROVIDER_MAP,
|
||||
STORAGE_KEY_AI_AGENT_THINKING_MAP,
|
||||
STORAGE_KEY_AI_WEB_SEARCH,
|
||||
STORAGE_KEY_AI_QUICK_MESSAGES,
|
||||
STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS,
|
||||
} from '../../infrastructure/config/storageKeys';
|
||||
import type { AIQuickMessage } from '../../infrastructure/ai/quickMessages';
|
||||
import { sanitizeQuickMessages } from '../../infrastructure/ai/quickMessages';
|
||||
import type {
|
||||
AIDraft,
|
||||
AISessionContextCompaction,
|
||||
AISession,
|
||||
AIPermissionMode,
|
||||
AIToolIntegrationMode,
|
||||
ProviderConfig,
|
||||
HostAIPermission,
|
||||
ExternalAgentConfig,
|
||||
ChatMessage,
|
||||
AISessionScope,
|
||||
WebSearchConfig,
|
||||
} from '../../infrastructure/ai/types';
|
||||
import {
|
||||
DEFAULT_COMMAND_TIMEOUT_SECONDS,
|
||||
DEFAULT_RESPONSE_IDLE_TIMEOUT_SECONDS,
|
||||
normalizeCommandTimeoutSeconds,
|
||||
normalizeResponseIdleTimeoutSeconds,
|
||||
} from '../../infrastructure/ai/types';
|
||||
import {
|
||||
activateDraftView,
|
||||
@@ -114,10 +88,7 @@ import {
|
||||
readLiveSessionsArray,
|
||||
} from './aiSessionsBackup';
|
||||
import { AI_STATE_CHANGED_EVENT, emitAIStateChanged } from './aiStateEvents';
|
||||
import {
|
||||
persistCommandBlocklistSetting,
|
||||
readCommandBlocklistSetting,
|
||||
} from './commandBlocklistSettings';
|
||||
import { useSharedAISettingsState } from './useAISettingsState';
|
||||
import {
|
||||
handoffDissolvedWorkspaceAIScope,
|
||||
retargetWorkspaceActiveChatAfterMemberLoss,
|
||||
@@ -128,79 +99,11 @@ import {
|
||||
type UndoLastTurnRestoredDraft,
|
||||
} from '../../domain/aiUndoLastTurn';
|
||||
|
||||
|
||||
function providerPatchIsNoop(
|
||||
current: ProviderConfig,
|
||||
updates: Partial<ProviderConfig>,
|
||||
): boolean {
|
||||
for (const key of Object.keys(updates) as Array<keyof ProviderConfig>) {
|
||||
const nextValue = updates[key];
|
||||
const prevValue = current[key];
|
||||
if (nextValue === prevValue) continue;
|
||||
if (key === 'modelContextWindows') {
|
||||
const prevWindows = (prevValue ?? {}) as Record<string, number>;
|
||||
const nextWindows = (nextValue ?? {}) as Record<string, number>;
|
||||
const nextKeys = Object.keys(nextWindows);
|
||||
if (nextKeys.length !== Object.keys(prevWindows).length) return false;
|
||||
if (nextKeys.some((modelId) => prevWindows[modelId] !== nextWindows[modelId])) return false;
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function useAIState() {
|
||||
// ── Provider Config ──
|
||||
const [providers, setProvidersRaw] = useState<ProviderConfig[]>(() =>
|
||||
localStorageAdapter.read<ProviderConfig[]>(STORAGE_KEY_AI_PROVIDERS) ?? []
|
||||
);
|
||||
const [activeProviderId, setActiveProviderIdRaw] = useState<string>(() =>
|
||||
localStorageAdapter.readString(STORAGE_KEY_AI_ACTIVE_PROVIDER) ?? ''
|
||||
);
|
||||
const [activeModelId, setActiveModelIdRaw] = useState<string>(() =>
|
||||
localStorageAdapter.readString(STORAGE_KEY_AI_ACTIVE_MODEL) ?? ''
|
||||
);
|
||||
|
||||
// ── Permission Model ──
|
||||
const [globalPermissionMode, setGlobalPermissionModeRaw] = useState<AIPermissionMode>(() => {
|
||||
const stored = localStorageAdapter.readString(STORAGE_KEY_AI_PERMISSION_MODE);
|
||||
if (stored === 'observer' || stored === 'confirm' || stored === 'auto') return stored;
|
||||
return 'confirm';
|
||||
});
|
||||
const [toolIntegrationMode, setToolIntegrationModeRaw] = useState<AIToolIntegrationMode>(() => {
|
||||
const stored = localStorageAdapter.readString(STORAGE_KEY_AI_TOOL_INTEGRATION_MODE);
|
||||
return stored === 'skills' ? 'skills' : 'mcp';
|
||||
});
|
||||
const [hostPermissions, setHostPermissionsRaw] = useState<HostAIPermission[]>(() =>
|
||||
localStorageAdapter.read<HostAIPermission[]>(STORAGE_KEY_AI_HOST_PERMISSIONS) ?? []
|
||||
);
|
||||
|
||||
// ── External Agents ──
|
||||
const [externalAgents, setExternalAgentsRaw] = useState<ExternalAgentConfig[]>(() =>
|
||||
localStorageAdapter.read<ExternalAgentConfig[]>(STORAGE_KEY_AI_EXTERNAL_AGENTS) ?? []
|
||||
);
|
||||
const [defaultAgentId, setDefaultAgentIdRaw] = useState<string>(() =>
|
||||
localStorageAdapter.readString(STORAGE_KEY_AI_DEFAULT_AGENT) ?? 'catty'
|
||||
);
|
||||
|
||||
// ── Safety Settings ──
|
||||
const [commandBlocklist, setCommandBlocklistRaw] = useState<string[]>(readCommandBlocklistSetting);
|
||||
const [commandTimeout, setCommandTimeoutRaw] = useState<number>(() =>
|
||||
normalizeCommandTimeoutSeconds(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_COMMAND_TIMEOUT) ?? DEFAULT_COMMAND_TIMEOUT_SECONDS,
|
||||
)
|
||||
);
|
||||
const [responseIdleTimeout, setResponseIdleTimeoutRaw] = useState<number>(() =>
|
||||
normalizeResponseIdleTimeoutSeconds(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_RESPONSE_IDLE_TIMEOUT)
|
||||
?? DEFAULT_RESPONSE_IDLE_TIMEOUT_SECONDS,
|
||||
)
|
||||
);
|
||||
const [maxIterations, setMaxIterationsRaw] = useState<number>(() =>
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_MAX_ITERATIONS) ?? 20
|
||||
);
|
||||
|
||||
// ── Sessions ──
|
||||
// Memory-only initial state: the primary store is IndexedDB and loads
|
||||
// asynchronously in the boot effect below (issue #4123). The legacy
|
||||
@@ -450,15 +353,59 @@ export function useAIState() {
|
||||
localStorageAdapter.read<Record<string, string>>(STORAGE_KEY_AI_AGENT_THINKING_MAP) ?? {}
|
||||
);
|
||||
|
||||
// ── Web Search Config ──
|
||||
const [webSearchConfig, setWebSearchConfigRaw] = useState<WebSearchConfig | null>(() =>
|
||||
localStorageAdapter.read<WebSearchConfig>(STORAGE_KEY_AI_WEB_SEARCH) ?? null
|
||||
);
|
||||
const handleRemoveProviderReferences = useCallback((id: string) => {
|
||||
const cleanup = removeProviderReferences(
|
||||
id,
|
||||
agentProviderMapRef.current,
|
||||
agentModelMapRef.current,
|
||||
);
|
||||
if (cleanup.providerMapChanged) {
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_PROVIDER_MAP, cleanup.agentProviderMap);
|
||||
setAgentProviderMapRaw(cleanup.agentProviderMap);
|
||||
}
|
||||
if (cleanup.modelMapChanged) {
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_MODEL_MAP, cleanup.agentModelMap);
|
||||
setAgentModelMapRaw(cleanup.agentModelMap);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// ── Quick Messages (slash prompts) ──
|
||||
const [quickMessages, setQuickMessagesRaw] = useState<AIQuickMessage[]>(() =>
|
||||
sanitizeQuickMessages(localStorageAdapter.read<unknown>(STORAGE_KEY_AI_QUICK_MESSAGES)),
|
||||
);
|
||||
const {
|
||||
providers,
|
||||
setProviders,
|
||||
addProvider,
|
||||
updateProvider,
|
||||
removeProvider,
|
||||
activeProviderId,
|
||||
setActiveProviderId,
|
||||
activeModelId,
|
||||
setActiveModelId,
|
||||
activeProvider,
|
||||
globalPermissionMode,
|
||||
setGlobalPermissionMode,
|
||||
toolIntegrationMode,
|
||||
setToolIntegrationMode,
|
||||
externalAgents,
|
||||
setExternalAgents,
|
||||
defaultAgentId,
|
||||
setDefaultAgentId,
|
||||
commandBlocklist,
|
||||
setCommandBlocklist,
|
||||
commandTimeout,
|
||||
setCommandTimeout,
|
||||
responseIdleTimeout,
|
||||
setResponseIdleTimeout,
|
||||
maxIterations,
|
||||
setMaxIterations,
|
||||
toolOutputMaxChars,
|
||||
setToolOutputMaxChars,
|
||||
webSearchConfig,
|
||||
setWebSearchConfig,
|
||||
quickMessages,
|
||||
setQuickMessages,
|
||||
} = useSharedAISettingsState({
|
||||
ignoreInvalidPermissionModeOnStorage: true,
|
||||
onRemoveProvider: handleRemoveProviderReferences,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
setLatestAISessionsSnapshot(sessions);
|
||||
@@ -589,53 +536,6 @@ export function useAIState() {
|
||||
});
|
||||
}, []);
|
||||
|
||||
const setWebSearchConfig = useCallback((config: WebSearchConfig | null) => {
|
||||
setWebSearchConfigRaw(config);
|
||||
if (config) {
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_WEB_SEARCH, config);
|
||||
} else {
|
||||
localStorageAdapter.remove(STORAGE_KEY_AI_WEB_SEARCH);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const setQuickMessages = useCallback((value: AIQuickMessage[] | ((prev: AIQuickMessage[]) => AIQuickMessage[])) => {
|
||||
setQuickMessagesRaw((prev) => {
|
||||
const nextRaw = typeof value === 'function' ? value(prev) : value;
|
||||
const next = sanitizeQuickMessages(nextRaw);
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_QUICK_MESSAGES, next);
|
||||
emitAIStateChanged(STORAGE_KEY_AI_QUICK_MESSAGES);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
// ── Persist helpers ──
|
||||
const setProviders = useCallback((value: ProviderConfig[] | ((prev: ProviderConfig[]) => ProviderConfig[])) => {
|
||||
setProvidersRaw(prev => {
|
||||
const next = typeof value === 'function' ? value(prev) : value;
|
||||
if (next === prev) return prev;
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_PROVIDERS, next);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const setActiveProviderId = useCallback((id: string) => {
|
||||
setActiveProviderIdRaw(id);
|
||||
localStorageAdapter.writeString(STORAGE_KEY_AI_ACTIVE_PROVIDER, id);
|
||||
}, []);
|
||||
|
||||
const setActiveModelId = useCallback((id: string) => {
|
||||
setActiveModelIdRaw(id);
|
||||
localStorageAdapter.writeString(STORAGE_KEY_AI_ACTIVE_MODEL, id);
|
||||
}, []);
|
||||
|
||||
const setGlobalPermissionMode = useCallback((mode: AIPermissionMode) => {
|
||||
setGlobalPermissionModeRaw(mode);
|
||||
localStorageAdapter.writeString(STORAGE_KEY_AI_PERMISSION_MODE, mode);
|
||||
// Sync to MCP Server bridge (observer mode blocks write operations)
|
||||
const bridge = getAIBridge();
|
||||
bridge?.aiMcpSetPermissionMode?.(mode);
|
||||
}, []);
|
||||
|
||||
const setHostPermissions = useCallback((value: HostAIPermission[] | ((prev: HostAIPermission[]) => HostAIPermission[])) => {
|
||||
setHostPermissionsRaw(prev => {
|
||||
const next = typeof value === 'function' ? value(prev) : value;
|
||||
@@ -644,145 +544,14 @@ export function useAIState() {
|
||||
});
|
||||
}, []);
|
||||
|
||||
const setToolIntegrationMode = useCallback((mode: AIToolIntegrationMode) => {
|
||||
setToolIntegrationModeRaw(mode);
|
||||
localStorageAdapter.writeString(STORAGE_KEY_AI_TOOL_INTEGRATION_MODE, mode);
|
||||
const bridge = getAIBridge();
|
||||
bridge?.aiMcpSetToolIntegrationMode?.(mode);
|
||||
}, []);
|
||||
|
||||
const setExternalAgents = useCallback((value: ExternalAgentConfig[] | ((prev: ExternalAgentConfig[]) => ExternalAgentConfig[])) => {
|
||||
setExternalAgentsRaw(prev => {
|
||||
const next = typeof value === 'function' ? value(prev) : value;
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_EXTERNAL_AGENTS, next);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const setDefaultAgentId = useCallback((id: string) => {
|
||||
setDefaultAgentIdRaw(id);
|
||||
localStorageAdapter.writeString(STORAGE_KEY_AI_DEFAULT_AGENT, id);
|
||||
}, []);
|
||||
|
||||
const setCommandBlocklist = useCallback((value: string[]) => {
|
||||
setCommandBlocklistRaw(value);
|
||||
persistCommandBlocklistSetting(value);
|
||||
// Sync to MCP Server bridge so SDK agents also respect the blocklist
|
||||
const bridge = getAIBridge();
|
||||
bridge?.aiMcpSetCommandBlocklist?.(value);
|
||||
}, []);
|
||||
|
||||
const setCommandTimeout = useCallback((value: number) => {
|
||||
const normalizedValue = normalizeCommandTimeoutSeconds(value);
|
||||
setCommandTimeoutRaw(normalizedValue);
|
||||
localStorageAdapter.writeNumber(STORAGE_KEY_AI_COMMAND_TIMEOUT, normalizedValue);
|
||||
// Sync to MCP Server bridge
|
||||
const bridge = getAIBridge();
|
||||
bridge?.aiMcpSetCommandTimeout?.(normalizedValue);
|
||||
}, []);
|
||||
|
||||
const setResponseIdleTimeout = useCallback((value: number) => {
|
||||
const normalizedValue = normalizeResponseIdleTimeoutSeconds(value);
|
||||
setResponseIdleTimeoutRaw(normalizedValue);
|
||||
localStorageAdapter.writeNumber(STORAGE_KEY_AI_RESPONSE_IDLE_TIMEOUT, normalizedValue);
|
||||
}, []);
|
||||
|
||||
const setMaxIterations = useCallback((value: number) => {
|
||||
setMaxIterationsRaw(value);
|
||||
localStorageAdapter.writeNumber(STORAGE_KEY_AI_MAX_ITERATIONS, value);
|
||||
// Sync to MCP Server bridge (used by SDK agent path)
|
||||
const bridge = getAIBridge();
|
||||
bridge?.aiMcpSetMaxIterations?.(value);
|
||||
}, []);
|
||||
|
||||
// ── Cross-window sync via storage events ──
|
||||
// When the settings window updates localStorage, the main window picks up changes.
|
||||
// Shared AI settings sync is handled by useSharedAISettingsState; this
|
||||
// listener handles session/agent/host-permission keys owned by useAIState.
|
||||
useEffect(() => {
|
||||
const handleStorage = (e: StorageEvent) => {
|
||||
try {
|
||||
const key = e.key;
|
||||
switch (key) {
|
||||
case STORAGE_KEY_AI_PROVIDERS: {
|
||||
const parsed = localStorageAdapter.read<ProviderConfig[]>(STORAGE_KEY_AI_PROVIDERS);
|
||||
if (parsed != null && !Array.isArray(parsed)) {
|
||||
console.warn('[useAIState] Cross-window sync: AI_PROVIDERS is not an array, skipping');
|
||||
break;
|
||||
}
|
||||
setProvidersRaw(parsed ?? []);
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_ACTIVE_PROVIDER:
|
||||
setActiveProviderIdRaw(localStorageAdapter.readString(STORAGE_KEY_AI_ACTIVE_PROVIDER) ?? '');
|
||||
break;
|
||||
case STORAGE_KEY_AI_ACTIVE_MODEL:
|
||||
setActiveModelIdRaw(localStorageAdapter.readString(STORAGE_KEY_AI_ACTIVE_MODEL) ?? '');
|
||||
break;
|
||||
case STORAGE_KEY_AI_PERMISSION_MODE: {
|
||||
const mode = localStorageAdapter.readString(STORAGE_KEY_AI_PERMISSION_MODE);
|
||||
if (mode === 'observer' || mode === 'confirm' || mode === 'auto') {
|
||||
setGlobalPermissionModeRaw(mode);
|
||||
getAIBridge()?.aiMcpSetPermissionMode?.(mode);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_TOOL_INTEGRATION_MODE:
|
||||
{
|
||||
const mode = localStorageAdapter.readString(STORAGE_KEY_AI_TOOL_INTEGRATION_MODE) === 'skills'
|
||||
? 'skills'
|
||||
: 'mcp';
|
||||
setToolIntegrationModeRaw(mode);
|
||||
getAIBridge()?.aiMcpSetToolIntegrationMode?.(mode);
|
||||
}
|
||||
break;
|
||||
case STORAGE_KEY_AI_EXTERNAL_AGENTS: {
|
||||
const agents = localStorageAdapter.read<ExternalAgentConfig[]>(STORAGE_KEY_AI_EXTERNAL_AGENTS);
|
||||
if (agents != null && !Array.isArray(agents)) {
|
||||
console.warn('[useAIState] Cross-window sync: AI_EXTERNAL_AGENTS is not an array, skipping');
|
||||
break;
|
||||
}
|
||||
setExternalAgentsRaw(agents ?? []);
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_DEFAULT_AGENT:
|
||||
setDefaultAgentIdRaw(localStorageAdapter.readString(STORAGE_KEY_AI_DEFAULT_AGENT) ?? 'catty');
|
||||
break;
|
||||
case STORAGE_KEY_AI_COMMAND_BLOCKLIST: {
|
||||
const blocklist = readCommandBlocklistSetting();
|
||||
setCommandBlocklistRaw(blocklist);
|
||||
getAIBridge()?.aiMcpSetCommandBlocklist?.(blocklist);
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_COMMAND_TIMEOUT: {
|
||||
const timeout = localStorageAdapter.readNumber(STORAGE_KEY_AI_COMMAND_TIMEOUT) ?? DEFAULT_COMMAND_TIMEOUT_SECONDS;
|
||||
if (!Number.isFinite(timeout)) {
|
||||
console.warn('[useAIState] Cross-window sync: AI_COMMAND_TIMEOUT is not a finite number, skipping');
|
||||
break;
|
||||
}
|
||||
const normalizedTimeout = normalizeCommandTimeoutSeconds(timeout);
|
||||
setCommandTimeoutRaw(normalizedTimeout);
|
||||
getAIBridge()?.aiMcpSetCommandTimeout?.(normalizedTimeout);
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_RESPONSE_IDLE_TIMEOUT: {
|
||||
const timeout = localStorageAdapter.readNumber(STORAGE_KEY_AI_RESPONSE_IDLE_TIMEOUT)
|
||||
?? DEFAULT_RESPONSE_IDLE_TIMEOUT_SECONDS;
|
||||
if (!Number.isFinite(timeout)) {
|
||||
console.warn('[useAIState] Cross-window sync: AI_RESPONSE_IDLE_TIMEOUT is not a finite number, skipping');
|
||||
break;
|
||||
}
|
||||
setResponseIdleTimeoutRaw(normalizeResponseIdleTimeoutSeconds(timeout));
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_MAX_ITERATIONS: {
|
||||
const iters = localStorageAdapter.readNumber(STORAGE_KEY_AI_MAX_ITERATIONS) ?? 20;
|
||||
if (!Number.isFinite(iters)) {
|
||||
console.warn('[useAIState] Cross-window sync: AI_MAX_ITERATIONS is not a finite number, skipping');
|
||||
break;
|
||||
}
|
||||
setMaxIterationsRaw(iters);
|
||||
getAIBridge()?.aiMcpSetMaxIterations?.(iters);
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_HOST_PERMISSIONS: {
|
||||
const perms = localStorageAdapter.read<HostAIPermission[]>(STORAGE_KEY_AI_HOST_PERMISSIONS);
|
||||
if (perms != null && !Array.isArray(perms)) {
|
||||
@@ -817,14 +586,6 @@ export function useAIState() {
|
||||
setActiveSessionIdMapRaw(nextActiveSessionIdMap);
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_WEB_SEARCH:
|
||||
setWebSearchConfigRaw(localStorageAdapter.read<WebSearchConfig>(STORAGE_KEY_AI_WEB_SEARCH) ?? null);
|
||||
break;
|
||||
case STORAGE_KEY_AI_QUICK_MESSAGES: {
|
||||
const messages = localStorageAdapter.read<unknown>(STORAGE_KEY_AI_QUICK_MESSAGES);
|
||||
setQuickMessagesRaw(sanitizeQuickMessages(messages));
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[useAIState] Cross-window sync: failed to process storage event for key', e.key, err);
|
||||
@@ -896,30 +657,6 @@ export function useAIState() {
|
||||
})();
|
||||
}), []);
|
||||
|
||||
// ── Sync initial safety settings to MCP Server on mount ──
|
||||
useEffect(() => {
|
||||
const bridge = getAIBridge();
|
||||
const initialBlocklist = readCommandBlocklistSetting();
|
||||
bridge?.aiMcpSetCommandBlocklist?.(initialBlocklist);
|
||||
const initialTimeout = normalizeCommandTimeoutSeconds(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_COMMAND_TIMEOUT) ?? DEFAULT_COMMAND_TIMEOUT_SECONDS,
|
||||
);
|
||||
bridge?.aiMcpSetCommandTimeout?.(initialTimeout);
|
||||
const initialMaxIter = localStorageAdapter.readNumber(STORAGE_KEY_AI_MAX_ITERATIONS) ?? 20;
|
||||
bridge?.aiMcpSetMaxIterations?.(initialMaxIter);
|
||||
const storedPermMode = localStorageAdapter.readString(STORAGE_KEY_AI_PERMISSION_MODE);
|
||||
const initialPermMode: AIPermissionMode =
|
||||
storedPermMode === 'observer' || storedPermMode === 'confirm' || storedPermMode === 'auto'
|
||||
? storedPermMode
|
||||
: 'confirm';
|
||||
bridge?.aiMcpSetPermissionMode?.(initialPermMode);
|
||||
const initialToolMode: AIToolIntegrationMode =
|
||||
localStorageAdapter.readString(STORAGE_KEY_AI_TOOL_INTEGRATION_MODE) === 'skills'
|
||||
? 'skills'
|
||||
: 'mcp';
|
||||
bridge?.aiMcpSetToolIntegrationMode?.(initialToolMode);
|
||||
}, []);
|
||||
|
||||
// ── Session CRUD ──
|
||||
const persistSessions = useCallback((next: AISession[], deletedSessionIds?: readonly string[]) => {
|
||||
writeSessionsForStorage(next, { deletedSessionIds });
|
||||
@@ -1664,51 +1401,6 @@ export function useAIState() {
|
||||
}
|
||||
}, [persistSessions]);
|
||||
|
||||
// ── Provider CRUD helpers ──
|
||||
const addProvider = useCallback((provider: ProviderConfig) => {
|
||||
setProviders(prev => [...prev, provider]);
|
||||
}, [setProviders]);
|
||||
|
||||
const updateProvider = useCallback((id: string, updates: Partial<ProviderConfig>) => {
|
||||
setProviders((prev) => {
|
||||
const index = prev.findIndex((provider) => provider.id === id);
|
||||
if (index < 0) return prev;
|
||||
const current = prev[index];
|
||||
if (providerPatchIsNoop(current, updates)) return prev;
|
||||
const next = prev.slice();
|
||||
next[index] = { ...current, ...updates };
|
||||
return next;
|
||||
});
|
||||
}, [setProviders]);
|
||||
|
||||
const removeProvider = useCallback((id: string) => {
|
||||
setProviders(prev => prev.filter(p => p.id !== id));
|
||||
setActiveProviderIdRaw(prevId => {
|
||||
if (prevId === id) {
|
||||
const next = '';
|
||||
localStorageAdapter.writeString(STORAGE_KEY_AI_ACTIVE_PROVIDER, next);
|
||||
return next;
|
||||
}
|
||||
return prevId;
|
||||
});
|
||||
const cleanup = removeProviderReferences(
|
||||
id,
|
||||
agentProviderMapRef.current,
|
||||
agentModelMapRef.current,
|
||||
);
|
||||
if (cleanup.providerMapChanged) {
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_PROVIDER_MAP, cleanup.agentProviderMap);
|
||||
setAgentProviderMapRaw(cleanup.agentProviderMap);
|
||||
}
|
||||
if (cleanup.modelMapChanged) {
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_MODEL_MAP, cleanup.agentModelMap);
|
||||
setAgentModelMapRaw(cleanup.agentModelMap);
|
||||
}
|
||||
}, [setProviders]);
|
||||
|
||||
// ── Computed ──
|
||||
const activeProvider = providers.find(p => p.id === activeProviderId) ?? null;
|
||||
|
||||
// Stream/message updates publish here so AIConfig Context consumers do not
|
||||
// re-render on every token. AIChatPanelsHost reads aiSessionsStore instead.
|
||||
useLayoutEffect(() => {
|
||||
@@ -1749,6 +1441,8 @@ export function useAIState() {
|
||||
setResponseIdleTimeout,
|
||||
maxIterations,
|
||||
setMaxIterations,
|
||||
toolOutputMaxChars,
|
||||
setToolOutputMaxChars,
|
||||
agentModelMap,
|
||||
setAgentModel,
|
||||
agentProviderMap,
|
||||
@@ -1816,6 +1510,8 @@ export function useAIState() {
|
||||
setResponseIdleTimeout,
|
||||
maxIterations,
|
||||
setMaxIterations,
|
||||
toolOutputMaxChars,
|
||||
setToolOutputMaxChars,
|
||||
agentModelMap,
|
||||
setAgentModel,
|
||||
agentProviderMap,
|
||||
|
||||
@@ -317,3 +317,320 @@ test("edited theme previews cannot grow the chrome CSS cache without bound", ()
|
||||
assert.equal(stats.size, CHROME_THEME_CSS_CACHE_MAX_ENTRIES);
|
||||
assert.equal(stats.keys.at(-1), latestFingerprint);
|
||||
});
|
||||
|
||||
test("useActiveChromeTheme skips style rewrite and IPCs on same-fingerprint clone switches", { timeout: 15000 }, async () => {
|
||||
const { JSDOM } = await import("jsdom");
|
||||
const { act, createElement } = await import("react");
|
||||
const { createRoot } = await import("react-dom/client");
|
||||
const { useActiveChromeTheme } = await import("./useActiveChromeTheme");
|
||||
const { getSettingsChromeSnapshot, publishSettingsChromeSnapshot } = await import("./settingsChromeStore");
|
||||
|
||||
const dom = new JSDOM('<!doctype html><html><head></head><body><div data-top-tabs-root></div></body></html>');
|
||||
const originalWindow = globalThis.window;
|
||||
const originalDocument = globalThis.document;
|
||||
const originalSnapshot = getSettingsChromeSnapshot();
|
||||
const environment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const originalActEnvironment = environment.IS_REACT_ACT_ENVIRONMENT;
|
||||
environment.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const themeCalls: string[] = [];
|
||||
const backgroundCalls: string[] = [];
|
||||
const testWindow = dom.window as unknown as Window & typeof globalThis;
|
||||
globalThis.window = testWindow;
|
||||
globalThis.document = dom.window.document;
|
||||
testWindow.netcatty = {
|
||||
setTheme: async (source: string) => { themeCalls.push(source); return true; },
|
||||
setBackgroundColor: async (color: string) => { backgroundCalls.push(color); return true; },
|
||||
} as unknown as NetcattyBridge;
|
||||
|
||||
const baseTheme = TERMINAL_THEMES.find((candidate) => candidate.type === "dark");
|
||||
const otherTheme = TERMINAL_THEMES.find((candidate) => candidate.type === "light");
|
||||
assert.ok(baseTheme);
|
||||
assert.ok(otherTheme);
|
||||
const applyAppTheme = () => {};
|
||||
|
||||
function Harness({ activeTheme }: { activeTheme: typeof baseTheme }) {
|
||||
useActiveChromeTheme({ activeTheme: activeTheme!, applyAppTheme });
|
||||
return null;
|
||||
}
|
||||
|
||||
publishSettingsChromeSnapshot({ ...originalSnapshot, theme: "dark", resolvedTheme: "dark" });
|
||||
let renderer: ReturnType<typeof createRoot> | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
renderer = createRoot(document.createElement("div"));
|
||||
renderer.render(createElement(Harness, { activeTheme: baseTheme }));
|
||||
});
|
||||
|
||||
const styleEl = document.getElementById("netcatty-active-chrome-theme") as HTMLStyleElement | null;
|
||||
assert.ok(styleEl, "initial mount should inject the chrome style tag");
|
||||
assert.equal(themeCalls.length, 1);
|
||||
assert.equal(backgroundCalls.length, 1);
|
||||
|
||||
// Track any writes to styleEl.textContent after initial mount.
|
||||
const textContentDescriptor = Object.getOwnPropertyDescriptor(
|
||||
dom.window.Node.prototype,
|
||||
"textContent",
|
||||
);
|
||||
assert.ok(textContentDescriptor?.get && textContentDescriptor?.set);
|
||||
let styleWrites = 0;
|
||||
Object.defineProperty(styleEl, "textContent", {
|
||||
configurable: true,
|
||||
get() {
|
||||
return textContentDescriptor.get!.call(this);
|
||||
},
|
||||
set(value: string | null) {
|
||||
styleWrites += 1;
|
||||
textContentDescriptor.set!.call(this, value);
|
||||
},
|
||||
});
|
||||
|
||||
// Switch to a structurally equal clone with a new object reference but identical fingerprint.
|
||||
const clonedTheme = { ...baseTheme, colors: { ...baseTheme.colors } };
|
||||
await act(async () => {
|
||||
renderer!.render(createElement(Harness, { activeTheme: clonedTheme }));
|
||||
});
|
||||
|
||||
assert.equal(styleWrites, 0, "same-fingerprint clone must not rewrite <style>");
|
||||
assert.equal(themeCalls.length, 1, "same-fingerprint clone must not invoke setTheme IPC");
|
||||
assert.equal(backgroundCalls.length, 1, "same-fingerprint clone must not invoke setBackgroundColor IPC");
|
||||
|
||||
// Switching to a genuinely different theme must still update <style> and IPCs.
|
||||
await act(async () => {
|
||||
renderer!.render(createElement(Harness, { activeTheme: otherTheme }));
|
||||
});
|
||||
|
||||
assert.equal(styleWrites, 1, "different theme fingerprint must update <style>");
|
||||
assert.equal(themeCalls.length, 2, "different theme fingerprint must invoke setTheme IPC");
|
||||
assert.equal(backgroundCalls.length, 2, "different theme fingerprint must invoke setBackgroundColor IPC");
|
||||
assert.equal(backgroundCalls.at(-1), otherTheme.colors.background);
|
||||
} finally {
|
||||
await act(async () => { renderer?.unmount(); });
|
||||
environment.IS_REACT_ACT_ENVIRONMENT = originalActEnvironment;
|
||||
publishSettingsChromeSnapshot(originalSnapshot);
|
||||
globalThis.window = originalWindow;
|
||||
globalThis.document = originalDocument;
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("useActiveChromeTheme refreshes surfaces when theme mode, pluginThemeRevision, or applyAppTheme changes", { timeout: 15000 }, async () => {
|
||||
const { JSDOM } = await import("jsdom");
|
||||
const { act, createElement } = await import("react");
|
||||
const { createRoot } = await import("react-dom/client");
|
||||
const { useActiveChromeTheme } = await import("./useActiveChromeTheme");
|
||||
const { getSettingsChromeSnapshot, publishSettingsChromeSnapshot } = await import("./settingsChromeStore");
|
||||
const { pluginThemeRegistry } = await import("../../infrastructure/config/pluginThemeRegistry");
|
||||
|
||||
const dom = new JSDOM('<!doctype html><html><head></head><body><div data-top-tabs-root></div></body></html>');
|
||||
const originalWindow = globalThis.window;
|
||||
const originalDocument = globalThis.document;
|
||||
const originalSnapshot = getSettingsChromeSnapshot();
|
||||
const environment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const originalActEnvironment = environment.IS_REACT_ACT_ENVIRONMENT;
|
||||
environment.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const themeCalls: string[] = [];
|
||||
const backgroundCalls: string[] = [];
|
||||
const testWindow = dom.window as unknown as Window & typeof globalThis;
|
||||
globalThis.window = testWindow;
|
||||
globalThis.document = dom.window.document;
|
||||
testWindow.netcatty = {
|
||||
setTheme: async (source: string) => { themeCalls.push(source); return true; },
|
||||
setBackgroundColor: async (color: string) => { backgroundCalls.push(color); return true; },
|
||||
} as unknown as NetcattyBridge;
|
||||
|
||||
const theme = TERMINAL_THEMES.find((candidate) => candidate.type === "dark");
|
||||
assert.ok(theme);
|
||||
const initialApplyAppTheme = () => {};
|
||||
|
||||
function Harness({ applyAppTheme }: { applyAppTheme: () => void }) {
|
||||
useActiveChromeTheme({ activeTheme: theme!, applyAppTheme });
|
||||
return null;
|
||||
}
|
||||
|
||||
publishSettingsChromeSnapshot({ ...originalSnapshot, theme: "dark", resolvedTheme: "dark" });
|
||||
let renderer: ReturnType<typeof createRoot> | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
renderer = createRoot(document.createElement("div"));
|
||||
renderer.render(createElement(Harness, { applyAppTheme: initialApplyAppTheme }));
|
||||
});
|
||||
assert.deepEqual(themeCalls, ["dark"]);
|
||||
assert.equal(backgroundCalls.length, 1);
|
||||
|
||||
// 1. Switching theme 'dark' -> 'system' while resolvedTheme stays 'dark' must still refresh surfaces.
|
||||
await act(async () => {
|
||||
publishSettingsChromeSnapshot({ ...originalSnapshot, theme: "system", resolvedTheme: "dark" });
|
||||
});
|
||||
assert.deepEqual(themeCalls, ["dark", "system"]);
|
||||
assert.equal(backgroundCalls.length, 2);
|
||||
|
||||
// And switching 'system' -> 'dark' while resolvedTheme stays 'dark' must also refresh surfaces.
|
||||
await act(async () => {
|
||||
publishSettingsChromeSnapshot({ ...originalSnapshot, theme: "dark", resolvedTheme: "dark" });
|
||||
});
|
||||
assert.deepEqual(themeCalls, ["dark", "system", "dark"]);
|
||||
assert.equal(backgroundCalls.length, 3);
|
||||
|
||||
// 2. Bumping pluginThemeRevision must still refresh surfaces.
|
||||
document.documentElement.className = "light";
|
||||
await act(async () => {
|
||||
pluginThemeRegistry.setCatalog({ ...pluginThemeRegistry.getCatalog() });
|
||||
});
|
||||
assert.equal(document.documentElement.classList.contains("dark"), true);
|
||||
assert.equal(themeCalls.length, 4);
|
||||
assert.equal(backgroundCalls.length, 4);
|
||||
|
||||
// 3. Changing applyAppTheme identity must still refresh surfaces.
|
||||
document.documentElement.className = "light";
|
||||
await act(async () => {
|
||||
renderer!.render(createElement(Harness, { applyAppTheme: () => {} }));
|
||||
});
|
||||
assert.equal(document.documentElement.classList.contains("dark"), true);
|
||||
assert.equal(themeCalls.length, 5);
|
||||
assert.equal(backgroundCalls.length, 5);
|
||||
} finally {
|
||||
await act(async () => { renderer?.unmount(); });
|
||||
environment.IS_REACT_ACT_ENVIRONMENT = originalActEnvironment;
|
||||
publishSettingsChromeSnapshot(originalSnapshot);
|
||||
globalThis.window = originalWindow;
|
||||
globalThis.document = originalDocument;
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("useActiveChromeTheme restores terminal surfaces when UI palette or accent changes with a stable applyAppTheme wrapper", { timeout: 15000 }, async () => {
|
||||
const { JSDOM } = await import("jsdom");
|
||||
const { act, createElement } = await import("react");
|
||||
const { createRoot } = await import("react-dom/client");
|
||||
const { useActiveChromeTheme } = await import("./useActiveChromeTheme");
|
||||
const { getSettingsChromeSnapshot, publishSettingsChromeSnapshot } = await import("./settingsChromeStore");
|
||||
const { getAppearanceChromeSnapshot, publishAppearanceChromeSnapshot } = await import("./appearanceChromeStore");
|
||||
|
||||
const dom = new JSDOM('<!doctype html><html><head></head><body><div data-top-tabs-root></div></body></html>');
|
||||
const originalWindow = globalThis.window;
|
||||
const originalDocument = globalThis.document;
|
||||
const originalSettingsSnapshot = getSettingsChromeSnapshot();
|
||||
const originalAppearanceSnapshot = getAppearanceChromeSnapshot();
|
||||
const environment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const originalActEnvironment = environment.IS_REACT_ACT_ENVIRONMENT;
|
||||
environment.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const themeCalls: string[] = [];
|
||||
const backgroundCalls: string[] = [];
|
||||
const testWindow = dom.window as unknown as Window & typeof globalThis;
|
||||
globalThis.window = testWindow;
|
||||
globalThis.document = dom.window.document;
|
||||
testWindow.netcatty = {
|
||||
setTheme: async (source: string) => { themeCalls.push(source); return true; },
|
||||
setBackgroundColor: async (color: string) => { backgroundCalls.push(color); return true; },
|
||||
} as unknown as NetcattyBridge;
|
||||
|
||||
const lightTerminalTheme = TERMINAL_THEMES.find((candidate) => candidate.type === "light");
|
||||
assert.ok(lightTerminalTheme);
|
||||
// ChromeHost passes a permanently stable applyAppTheme callback wrapper.
|
||||
const stableApplyAppTheme = () => {};
|
||||
|
||||
function Harness({ activeTheme }: { activeTheme: typeof lightTerminalTheme }) {
|
||||
useActiveChromeTheme({ activeTheme: activeTheme!, applyAppTheme: stableApplyAppTheme });
|
||||
return null;
|
||||
}
|
||||
|
||||
publishSettingsChromeSnapshot({
|
||||
...originalSettingsSnapshot,
|
||||
theme: "dark",
|
||||
resolvedTheme: "dark",
|
||||
darkUiThemeId: "default",
|
||||
lightUiThemeId: "default",
|
||||
});
|
||||
publishAppearanceChromeSnapshot({
|
||||
accentMode: "custom",
|
||||
customAccent: "210 90% 50%",
|
||||
});
|
||||
|
||||
let renderer: ReturnType<typeof createRoot> | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
renderer = createRoot(document.createElement("div"));
|
||||
renderer.render(createElement(Harness, { activeTheme: lightTerminalTheme }));
|
||||
});
|
||||
assert.equal(document.documentElement.classList.contains("light"), true);
|
||||
assert.equal(themeCalls.at(-1), "light");
|
||||
assert.equal(backgroundCalls.at(-1), lightTerminalTheme.colors.background);
|
||||
|
||||
// 1. Dark UI palette changes while light terminal stays active (with a cloned
|
||||
// theme object of identical fingerprint). Simulate applyThemeTokens resetting
|
||||
// root class and native window background to dark app palette first.
|
||||
document.documentElement.className = "dark";
|
||||
themeCalls.push("dark");
|
||||
backgroundCalls.push("#111111");
|
||||
await act(async () => {
|
||||
publishSettingsChromeSnapshot({
|
||||
...originalSettingsSnapshot,
|
||||
theme: "dark",
|
||||
resolvedTheme: "dark",
|
||||
darkUiThemeId: "midnight",
|
||||
lightUiThemeId: "default",
|
||||
});
|
||||
renderer!.render(createElement(Harness, {
|
||||
activeTheme: { ...lightTerminalTheme, colors: { ...lightTerminalTheme.colors } },
|
||||
}));
|
||||
});
|
||||
assert.equal(document.documentElement.classList.contains("light"), true);
|
||||
assert.equal(themeCalls.at(-1), "light");
|
||||
assert.equal(backgroundCalls.at(-1), lightTerminalTheme.colors.background);
|
||||
|
||||
// 2. Light UI palette changes.
|
||||
document.documentElement.className = "dark";
|
||||
themeCalls.push("dark");
|
||||
backgroundCalls.push("#111111");
|
||||
await act(async () => {
|
||||
publishSettingsChromeSnapshot({
|
||||
...originalSettingsSnapshot,
|
||||
theme: "dark",
|
||||
resolvedTheme: "dark",
|
||||
darkUiThemeId: "midnight",
|
||||
lightUiThemeId: "paper",
|
||||
});
|
||||
});
|
||||
assert.equal(document.documentElement.classList.contains("light"), true);
|
||||
assert.equal(themeCalls.at(-1), "light");
|
||||
assert.equal(backgroundCalls.at(-1), lightTerminalTheme.colors.background);
|
||||
|
||||
// 3. Accent mode / custom accent changes while light terminal stays active.
|
||||
document.documentElement.className = "dark";
|
||||
themeCalls.push("dark");
|
||||
backgroundCalls.push("#111111");
|
||||
await act(async () => {
|
||||
publishAppearanceChromeSnapshot({
|
||||
accentMode: "custom",
|
||||
customAccent: "340 80% 55%",
|
||||
});
|
||||
});
|
||||
assert.equal(document.documentElement.classList.contains("light"), true);
|
||||
assert.equal(themeCalls.at(-1), "light");
|
||||
assert.equal(backgroundCalls.at(-1), lightTerminalTheme.colors.background);
|
||||
|
||||
document.documentElement.className = "dark";
|
||||
themeCalls.push("dark");
|
||||
backgroundCalls.push("#111111");
|
||||
await act(async () => {
|
||||
publishAppearanceChromeSnapshot({
|
||||
accentMode: "theme",
|
||||
customAccent: "340 80% 55%",
|
||||
});
|
||||
});
|
||||
assert.equal(document.documentElement.classList.contains("light"), true);
|
||||
assert.equal(themeCalls.at(-1), "light");
|
||||
assert.equal(backgroundCalls.at(-1), lightTerminalTheme.colors.background);
|
||||
} finally {
|
||||
await act(async () => { renderer?.unmount(); });
|
||||
environment.IS_REACT_ACT_ENVIRONMENT = originalActEnvironment;
|
||||
publishSettingsChromeSnapshot(originalSettingsSnapshot);
|
||||
publishAppearanceChromeSnapshot(originalAppearanceSnapshot);
|
||||
globalThis.window = originalWindow;
|
||||
globalThis.document = originalDocument;
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { pluginThemeRegistry } from '../../infrastructure/config/pluginThemeRegistry';
|
||||
import { useAppearanceChromeStore } from './appearanceChromeStore';
|
||||
import { usePluginThemeRevision } from './usePluginThemeRuntime';
|
||||
import { getSettingsChromeSnapshot, useSettingsChromeStore } from './settingsChromeStore';
|
||||
import { useLayoutEffect, useRef } from "react";
|
||||
@@ -10,46 +11,12 @@ import {
|
||||
import { runThemeTransition } from "./themeTransition";
|
||||
import { TERMINAL_THEMES } from "../../infrastructure/config/terminalThemes";
|
||||
import { netcattyBridge } from "../../infrastructure/services/netcattyBridge";
|
||||
import { resolveReadableForegroundForHsl } from "../../domain/colorContrast";
|
||||
|
||||
function hexToHsl(hex: string): string {
|
||||
const r = parseInt(hex.slice(1, 3), 16) / 255;
|
||||
const g = parseInt(hex.slice(3, 5), 16) / 255;
|
||||
const b = parseInt(hex.slice(5, 7), 16) / 255;
|
||||
const max = Math.max(r, g, b);
|
||||
const min = Math.min(r, g, b);
|
||||
let h = 0;
|
||||
let s = 0;
|
||||
const l = (max + min) / 2;
|
||||
if (max !== min) {
|
||||
const d = max - min;
|
||||
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
||||
switch (max) {
|
||||
case r:
|
||||
h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
|
||||
break;
|
||||
case g:
|
||||
h = ((b - r) / d + 2) / 6;
|
||||
break;
|
||||
default:
|
||||
h = ((r - g) / d + 4) / 6;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return `${Math.round(h * 3600) / 10} ${Math.round(s * 1000) / 10}% ${Math.round(l * 1000) / 10}%`;
|
||||
}
|
||||
|
||||
function adjustLightness(hsl: string, delta: number): string {
|
||||
const parts = hsl.split(/\s+/);
|
||||
const nextLightness = Math.max(0, Math.min(100, parseFloat(parts[2]) + delta));
|
||||
return `${parts[0]} ${parts[1]} ${Math.round(nextLightness * 10) / 10}%`;
|
||||
}
|
||||
|
||||
function adjustSaturation(hsl: string, factor: number): string {
|
||||
const parts = hsl.split(/\s+/);
|
||||
const nextSaturation = Math.max(0, Math.min(100, parseFloat(parts[1]) * factor));
|
||||
return `${parts[0]} ${Math.round(nextSaturation * 10) / 10}% ${parts[2]}`;
|
||||
}
|
||||
import {
|
||||
adjustLightnessToken,
|
||||
adjustSaturationToken,
|
||||
hexToHslToken,
|
||||
resolveReadableForegroundForHsl,
|
||||
} from "../../domain/colorContrast";
|
||||
|
||||
const CSS_VARS = [
|
||||
"background",
|
||||
@@ -74,15 +41,15 @@ const CSS_VARS = [
|
||||
] as const;
|
||||
|
||||
function buildChromeCss(theme: TerminalTheme): string {
|
||||
const bg = hexToHsl(theme.colors.background);
|
||||
const fg = hexToHsl(theme.colors.foreground);
|
||||
const cursor = hexToHsl(theme.colors.cursor);
|
||||
const bg = hexToHslToken(theme.colors.background);
|
||||
const fg = hexToHslToken(theme.colors.foreground);
|
||||
const cursor = hexToHslToken(theme.colors.cursor);
|
||||
const isDark = theme.type === "dark";
|
||||
const card = adjustLightness(bg, isDark ? 4 : -3);
|
||||
const secondary = adjustLightness(bg, isDark ? 6 : -5);
|
||||
const muted = adjustLightness(bg, isDark ? 10 : -8);
|
||||
const mutedFg = adjustSaturation(adjustLightness(fg, isDark ? -20 : 20), 0.5);
|
||||
const border = adjustLightness(bg, isDark ? 12 : -10);
|
||||
const card = adjustLightnessToken(bg, isDark ? 4 : -3);
|
||||
const secondary = adjustLightnessToken(bg, isDark ? 6 : -5);
|
||||
const muted = adjustLightnessToken(bg, isDark ? 10 : -8);
|
||||
const mutedFg = adjustSaturationToken(adjustLightnessToken(fg, isDark ? -20 : 20), 0.5);
|
||||
const border = adjustLightnessToken(bg, isDark ? 12 : -10);
|
||||
const primaryFg = resolveReadableForegroundForHsl(cursor);
|
||||
|
||||
const values = [
|
||||
@@ -278,17 +245,60 @@ export function useActiveChromeTheme({
|
||||
applyAppTheme: () => void;
|
||||
}) {
|
||||
const pluginThemeRevision = usePluginThemeRevision();
|
||||
const { resolvedTheme } = useSettingsChromeStore();
|
||||
const { theme, resolvedTheme, lightUiThemeId, darkUiThemeId } = useSettingsChromeStore();
|
||||
const { accentMode, customAccent } = useAppearanceChromeStore();
|
||||
const effectiveTheme = pluginThemeRegistry.isActive(resolvedTheme) ? null : activeTheme;
|
||||
const applyAppThemeRef = useRef(applyAppTheme);
|
||||
applyAppThemeRef.current = applyAppTheme;
|
||||
const prevSurfaceTriggersRef = useRef({
|
||||
theme,
|
||||
resolvedTheme,
|
||||
lightUiThemeId,
|
||||
darkUiThemeId,
|
||||
accentMode,
|
||||
customAccent,
|
||||
pluginThemeRevision,
|
||||
applyAppTheme,
|
||||
});
|
||||
|
||||
useLayoutEffect(() => {
|
||||
// Settings may have just applied the OS theme over a fixed terminal theme.
|
||||
// Reassert its visual surfaces even when the terminal fingerprint is stable;
|
||||
// tab-switch callers retain the default fingerprint fast path.
|
||||
syncActiveChromeTheme(effectiveTheme, applyAppTheme, { refreshSurfaces: true });
|
||||
}, [effectiveTheme, applyAppTheme, pluginThemeRevision, resolvedTheme]);
|
||||
const prev = prevSurfaceTriggersRef.current;
|
||||
const refreshSurfaces =
|
||||
prev.theme !== theme ||
|
||||
prev.resolvedTheme !== resolvedTheme ||
|
||||
prev.lightUiThemeId !== lightUiThemeId ||
|
||||
prev.darkUiThemeId !== darkUiThemeId ||
|
||||
prev.accentMode !== accentMode ||
|
||||
prev.customAccent !== customAccent ||
|
||||
prev.pluginThemeRevision !== pluginThemeRevision ||
|
||||
prev.applyAppTheme !== applyAppTheme;
|
||||
prevSurfaceTriggersRef.current = {
|
||||
theme,
|
||||
resolvedTheme,
|
||||
lightUiThemeId,
|
||||
darkUiThemeId,
|
||||
accentMode,
|
||||
customAccent,
|
||||
pluginThemeRevision,
|
||||
applyAppTheme,
|
||||
};
|
||||
|
||||
// Settings or plugin themes may have just applied the app theme over a fixed
|
||||
// terminal theme. Reassert its visual surfaces only when one of those
|
||||
// surface-refresh triggers changed; same-theme tab switches retain the
|
||||
// default fingerprint fast path.
|
||||
syncActiveChromeTheme(effectiveTheme, applyAppTheme, { refreshSurfaces });
|
||||
}, [
|
||||
effectiveTheme,
|
||||
applyAppTheme,
|
||||
pluginThemeRevision,
|
||||
theme,
|
||||
resolvedTheme,
|
||||
lightUiThemeId,
|
||||
darkUiThemeId,
|
||||
accentMode,
|
||||
customAccent,
|
||||
]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
return () => {
|
||||
|
||||
@@ -2,8 +2,8 @@ import { useCallback } from 'react';
|
||||
import { STORAGE_KEY_COMPOSE_BAR_HEIGHT } from '../../infrastructure/config/storageKeys';
|
||||
import { useStoredNumber } from './useStoredNumber';
|
||||
|
||||
export const COMPOSE_BAR_HEIGHT_DEFAULT = 144;
|
||||
export const COMPOSE_BAR_HEIGHT_MIN = 104;
|
||||
export const COMPOSE_BAR_HEIGHT_DEFAULT = 120;
|
||||
export const COMPOSE_BAR_HEIGHT_MIN = 72;
|
||||
export const COMPOSE_BAR_HEIGHT_MAX = 360;
|
||||
|
||||
const HEIGHT_CLAMP = { min: COMPOSE_BAR_HEIGHT_MIN, max: COMPOSE_BAR_HEIGHT_MAX };
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import React from 'react';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { act } from 'react-test-renderer';
|
||||
import { STORAGE_KEY_COMPOSE_BAR_PINNED_SNIPPETS } from '../../infrastructure/config/storageKeys';
|
||||
import { useComposeBarPinnedSnippets } from './useComposeBarPinnedSnippets';
|
||||
|
||||
function setupDom(t: test.TestContext) {
|
||||
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', {
|
||||
url: 'http://localhost',
|
||||
});
|
||||
const globals = ['window', 'document', 'localStorage', 'CustomEvent', 'Event', 'StorageEvent'] as const;
|
||||
const originals = globals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)] as const);
|
||||
for (const name of globals) {
|
||||
Object.defineProperty(globalThis, name, { configurable: true, value: dom.window[name] });
|
||||
}
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
const rootElement = dom.window.document.querySelector('#root')!;
|
||||
const root = createRoot(rootElement);
|
||||
t.after(async () => {
|
||||
await act(async () => root.unmount());
|
||||
dom.window.close();
|
||||
for (const [name, descriptor] of originals) {
|
||||
if (descriptor) Object.defineProperty(globalThis, name, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, name);
|
||||
}
|
||||
});
|
||||
return { dom, root };
|
||||
}
|
||||
|
||||
test('useComposeBarPinnedSnippets persists reordered pins, ignores unknown IDs, and syncs sibling instances', async (t) => {
|
||||
const { dom, root } = setupDom(t);
|
||||
dom.window.localStorage.setItem(
|
||||
STORAGE_KEY_COMPOSE_BAR_PINNED_SNIPPETS,
|
||||
JSON.stringify(['s1', 's2', 's3']),
|
||||
);
|
||||
|
||||
type HookResult = ReturnType<typeof useComposeBarPinnedSnippets>;
|
||||
let firstHook!: HookResult;
|
||||
let secondHook!: HookResult;
|
||||
|
||||
function Harness({ snippetIdKey }: { snippetIdKey: string }) {
|
||||
firstHook = useComposeBarPinnedSnippets(snippetIdKey);
|
||||
return null;
|
||||
}
|
||||
|
||||
function SiblingHarness({ snippetIdKey }: { snippetIdKey: string }) {
|
||||
secondHook = useComposeBarPinnedSnippets(snippetIdKey);
|
||||
return null;
|
||||
}
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<>
|
||||
<Harness snippetIdKey={'s1\0s2\0s3'} />
|
||||
<SiblingHarness snippetIdKey={'s1\0s2\0s3'} />
|
||||
</>,
|
||||
);
|
||||
});
|
||||
|
||||
assert.deepEqual(firstHook.pinnedIds, ['s1', 's2', 's3']);
|
||||
assert.deepEqual(secondHook.pinnedIds, ['s1', 's2', 's3']);
|
||||
|
||||
await act(async () => {
|
||||
firstHook.reorder('s3', 's1', 'before');
|
||||
});
|
||||
|
||||
assert.deepEqual(firstHook.pinnedIds, ['s3', 's1', 's2']);
|
||||
assert.deepEqual(secondHook.pinnedIds, ['s3', 's1', 's2']);
|
||||
assert.deepEqual(
|
||||
JSON.parse(dom.window.localStorage.getItem(STORAGE_KEY_COMPOSE_BAR_PINNED_SNIPPETS) ?? '[]'),
|
||||
['s3', 's1', 's2'],
|
||||
);
|
||||
|
||||
// Unknown/deleted drag IDs are ignored without corrupting persisted order.
|
||||
await act(async () => {
|
||||
firstHook.reorder('deleted-snippet', 's1', 'before');
|
||||
firstHook.reorder('s2', 'missing-target', 'after');
|
||||
});
|
||||
assert.deepEqual(firstHook.pinnedIds, ['s3', 's1', 's2']);
|
||||
|
||||
// Deleting a snippet prunes it while keeping the customized order of remaining pins.
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<>
|
||||
<Harness snippetIdKey={'s3\0s2'} />
|
||||
<SiblingHarness snippetIdKey={'s3\0s2'} />
|
||||
</>,
|
||||
);
|
||||
});
|
||||
assert.deepEqual(firstHook.pinnedIds, ['s3', 's2']);
|
||||
assert.deepEqual(secondHook.pinnedIds, ['s3', 's2']);
|
||||
assert.deepEqual(
|
||||
JSON.parse(dom.window.localStorage.getItem(STORAGE_KEY_COMPOSE_BAR_PINNED_SNIPPETS) ?? '[]'),
|
||||
['s3', 's2'],
|
||||
);
|
||||
});
|
||||
|
||||
test('useComposeBarPinnedSnippets still seeds defaults on first run when vault snippets are present', async (t) => {
|
||||
const { dom, root } = setupDom(t);
|
||||
type HookResult = ReturnType<typeof useComposeBarPinnedSnippets>;
|
||||
let hook!: HookResult;
|
||||
|
||||
function Harness() {
|
||||
hook = useComposeBarPinnedSnippets('a\0b', ['a', 'b']);
|
||||
return null;
|
||||
}
|
||||
|
||||
await act(async () => {
|
||||
root.render(<Harness />);
|
||||
});
|
||||
|
||||
assert.deepEqual(hook.pinnedIds, ['a', 'b']);
|
||||
assert.deepEqual(
|
||||
JSON.parse(dom.window.localStorage.getItem(STORAGE_KEY_COMPOSE_BAR_PINNED_SNIPPETS) ?? '[]'),
|
||||
['a', 'b'],
|
||||
);
|
||||
});
|
||||
@@ -1,21 +1,32 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
arePinnedSnippetIdsEqual,
|
||||
normalizePinnedSnippetIds,
|
||||
reorderPinnedSnippetIds,
|
||||
type PinnedSnippetDropPosition,
|
||||
} from '../../domain/composeBarPinnedSnippets';
|
||||
import { STORAGE_KEY_COMPOSE_BAR_PINNED_SNIPPETS } from '../../infrastructure/config/storageKeys';
|
||||
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
|
||||
const COMPOSE_BAR_PINNED_SNIPPETS_CHANGE_EVENT = 'netcatty-compose-bar-pinned-snippets-change';
|
||||
|
||||
interface PinnedState {
|
||||
pinnedIds: string[];
|
||||
/** True when the user has never saved pins (localStorage key absent). */
|
||||
neverSaved: boolean;
|
||||
/** True when this state transition should be written to storage and broadcast. */
|
||||
persist: boolean;
|
||||
}
|
||||
|
||||
function readPinnedState(): PinnedState {
|
||||
const stored = localStorageAdapter.read<string[]>(STORAGE_KEY_COMPOSE_BAR_PINNED_SNIPPETS);
|
||||
if (stored === null) {
|
||||
return { pinnedIds: [], neverSaved: true };
|
||||
return { pinnedIds: [], neverSaved: true, persist: false };
|
||||
}
|
||||
return {
|
||||
pinnedIds: Array.isArray(stored) ? stored.filter((id) => typeof id === 'string') : [],
|
||||
pinnedIds: Array.isArray(stored) ? normalizePinnedSnippetIds(stored) : [],
|
||||
neverSaved: false,
|
||||
persist: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -35,35 +46,77 @@ export function useComposeBarPinnedSnippets(
|
||||
snippetIdKey?: string,
|
||||
defaultSeedIds?: readonly string[],
|
||||
) {
|
||||
const [{ pinnedIds, neverSaved }, setPinnedState] = useState(readPinnedState);
|
||||
const skipNextPersistRef = useRef(true);
|
||||
const [{ pinnedIds, neverSaved, persist }, setPinnedState] = useState(readPinnedState);
|
||||
const needsSeedRef = useRef(neverSaved);
|
||||
|
||||
const setPinnedIds = useCallback((updater: string[] | ((prev: string[]) => string[])) => {
|
||||
setPinnedState((prev) => {
|
||||
const nextIds = typeof updater === 'function' ? updater(prev.pinnedIds) : updater;
|
||||
return { pinnedIds: nextIds, neverSaved: false };
|
||||
const nextIds = normalizePinnedSnippetIds(
|
||||
typeof updater === 'function' ? updater(prev.pinnedIds) : updater,
|
||||
);
|
||||
if (arePinnedSnippetIdsEqual(prev.pinnedIds, nextIds)) {
|
||||
return prev;
|
||||
}
|
||||
needsSeedRef.current = false;
|
||||
return { pinnedIds: nextIds, neverSaved: false, persist: true };
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (skipNextPersistRef.current) {
|
||||
skipNextPersistRef.current = false;
|
||||
return;
|
||||
}
|
||||
if (!persist) return;
|
||||
localStorageAdapter.write(STORAGE_KEY_COMPOSE_BAR_PINNED_SNIPPETS, pinnedIds);
|
||||
}, [pinnedIds]);
|
||||
if (typeof window !== 'undefined' && typeof CustomEvent !== 'undefined') {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent(COMPOSE_BAR_PINNED_SNIPPETS_CHANGE_EVENT, {
|
||||
detail: { pinnedIds },
|
||||
}),
|
||||
);
|
||||
}
|
||||
}, [pinnedIds, persist]);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') return;
|
||||
const applyExternalIds = (incoming: readonly unknown[]) => {
|
||||
const nextIds = normalizePinnedSnippetIds(incoming);
|
||||
needsSeedRef.current = false;
|
||||
setPinnedState((prev) => {
|
||||
if (!prev.neverSaved && arePinnedSnippetIdsEqual(prev.pinnedIds, nextIds)) {
|
||||
return prev;
|
||||
}
|
||||
return { pinnedIds: nextIds, neverSaved: false, persist: false };
|
||||
});
|
||||
};
|
||||
|
||||
const handleCustom = (event: Event) => {
|
||||
const detail = (event as CustomEvent<{ pinnedIds?: unknown[] }>).detail;
|
||||
if (!Array.isArray(detail?.pinnedIds)) return;
|
||||
applyExternalIds(detail.pinnedIds);
|
||||
};
|
||||
|
||||
const handleStorage = (event: StorageEvent) => {
|
||||
if (event.key !== STORAGE_KEY_COMPOSE_BAR_PINNED_SNIPPETS) return;
|
||||
const stored = localStorageAdapter.read<string[]>(STORAGE_KEY_COMPOSE_BAR_PINNED_SNIPPETS);
|
||||
applyExternalIds(Array.isArray(stored) ? stored : []);
|
||||
};
|
||||
|
||||
window.addEventListener(COMPOSE_BAR_PINNED_SNIPPETS_CHANGE_EVENT, handleCustom);
|
||||
window.addEventListener('storage', handleStorage);
|
||||
return () => {
|
||||
window.removeEventListener(COMPOSE_BAR_PINNED_SNIPPETS_CHANGE_EVENT, handleCustom);
|
||||
window.removeEventListener('storage', handleStorage);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!needsSeedRef.current) return;
|
||||
|
||||
const seed = defaultSeedIds?.filter(Boolean).slice(0, 4) ?? [];
|
||||
const seed = normalizePinnedSnippetIds(defaultSeedIds ?? []).slice(0, 4);
|
||||
if (seed.length === 0) return;
|
||||
|
||||
const applySeed = () => {
|
||||
if (!needsSeedRef.current) return;
|
||||
needsSeedRef.current = false;
|
||||
setPinnedState({ pinnedIds: [...seed], neverSaved: false });
|
||||
setPinnedState({ pinnedIds: [...seed], neverSaved: false, persist: true });
|
||||
};
|
||||
|
||||
const isBuiltinSeed = seed.every((id) => id.startsWith('__compose_builtin_'));
|
||||
@@ -100,7 +153,14 @@ export function useComposeBarPinnedSnippets(
|
||||
));
|
||||
}, [setPinnedIds]);
|
||||
|
||||
const reorder = useCallback(
|
||||
(draggedId: string, targetId: string, position?: PinnedSnippetDropPosition) => {
|
||||
setPinnedIds((prev) => reorderPinnedSnippetIds(prev, draggedId, targetId, position));
|
||||
},
|
||||
[setPinnedIds],
|
||||
);
|
||||
|
||||
const isPinned = useCallback((id: string) => pinnedIds.includes(id), [pinnedIds]);
|
||||
|
||||
return { pinnedIds, pin, unpin, toggle, isPinned };
|
||||
return { pinnedIds, pin, unpin, toggle, reorder, isPinned };
|
||||
}
|
||||
@@ -109,9 +109,10 @@ export function useComposeDirectoryPicker(sessionId: string) {
|
||||
|
||||
const filtered = useMemo(() => filterDirectories(entries, query, showHidden), [entries, query, showHidden]);
|
||||
const cwdError = controller?.getCwdError() ?? null;
|
||||
const waitsForCwd = error === 'unknown' || error === 'integrationUnavailable' || error === 'cmdIntegrationUnavailable' || error === 'nonFilesystem';
|
||||
return { cwd, home, pathFlavor, open, setOpen, query, setQuery, showHidden, setShowHidden, entries: filtered,
|
||||
parent: cwd ? directoryParent(cwd, pathFlavor) : null, loading, pending,
|
||||
error: cwdError ?? (cwd && (error === 'unknown' || error === 'integrationUnavailable' || error === 'nonFilesystem') ? null : error),
|
||||
error: cwdError ?? (cwd && waitsForCwd ? null : error),
|
||||
available: !!controller?.capabilities.listDirectories && !!controller.capabilities.changeDirectory && !!controller.capabilities.confirmChange,
|
||||
refresh, reload: load, change };
|
||||
}
|
||||
@@ -787,4 +787,130 @@ describe('External MCP manual enable privacy gate', () => {
|
||||
restoreStorage();
|
||||
}
|
||||
});
|
||||
|
||||
it('ref-counts a single 3s poller across multiple mounted hooks, pauses when hidden, and syncs on visible', async (t) => {
|
||||
const React = await import('react');
|
||||
const { act, create } = await import('react-test-renderer');
|
||||
const { useExternalMcpToggleState } = await import('./useExternalMcpToggleState.ts');
|
||||
t.mock.timers.enable({ apis: ['setTimeout', 'setInterval', 'Date'], now: 10_000 });
|
||||
const restoreStorage = installMemoryLocalStorage();
|
||||
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
|
||||
const previousDocument = Object.getOwnPropertyDescriptor(globalThis, 'document');
|
||||
const previousAct = Object.getOwnPropertyDescriptor(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
const events = new EventTarget();
|
||||
const visibilityListeners = new Set<() => void>();
|
||||
let visibilityState: DocumentVisibilityState = 'visible';
|
||||
let statusCalls = 0;
|
||||
let runtimeEnabled = true;
|
||||
|
||||
const bridge = {
|
||||
externalMcpGetStatus: async () => {
|
||||
statusCalls += 1;
|
||||
return { ok: true, enabled: runtimeEnabled, error: null };
|
||||
},
|
||||
};
|
||||
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { value: true, configurable: true });
|
||||
Object.defineProperty(globalThis, 'window', {
|
||||
value: {
|
||||
netcatty: bridge,
|
||||
location: { hash: '#/settings' },
|
||||
addEventListener: events.addEventListener.bind(events),
|
||||
removeEventListener: events.removeEventListener.bind(events),
|
||||
dispatchEvent: events.dispatchEvent.bind(events),
|
||||
setInterval,
|
||||
clearInterval,
|
||||
},
|
||||
configurable: true,
|
||||
});
|
||||
Object.defineProperty(globalThis, 'document', {
|
||||
configurable: true,
|
||||
value: {
|
||||
get visibilityState() { return visibilityState; },
|
||||
get hidden() { return visibilityState === 'hidden'; },
|
||||
addEventListener(type: string, listener: () => void) {
|
||||
if (type === 'visibilitychange') visibilityListeners.add(listener);
|
||||
},
|
||||
removeEventListener(type: string, listener: () => void) {
|
||||
if (type === 'visibilitychange') visibilityListeners.delete(listener);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const setVisibility = async (next: DocumentVisibilityState) => {
|
||||
visibilityState = next;
|
||||
await act(async () => {
|
||||
for (const listener of [...visibilityListeners]) listener();
|
||||
});
|
||||
};
|
||||
|
||||
let hookA!: ReturnType<typeof useExternalMcpToggleState>;
|
||||
let hookB!: ReturnType<typeof useExternalMcpToggleState>;
|
||||
const CaptureA = () => { hookA = useExternalMcpToggleState(); return null; };
|
||||
const CaptureB = () => { hookB = useExternalMcpToggleState(); return null; };
|
||||
const DualMount = ({ showSecond }: { showSecond: boolean }) => (
|
||||
React.createElement(
|
||||
React.Fragment,
|
||||
null,
|
||||
React.createElement(CaptureA),
|
||||
showSecond ? React.createElement(CaptureB) : null,
|
||||
)
|
||||
);
|
||||
|
||||
let renderer: ReturnType<typeof create> | undefined;
|
||||
try {
|
||||
resetExternalMcpStartupReadyForTests();
|
||||
globalThis.localStorage.setItem(STORAGE_KEY_AI_EXTERNAL_MCP_ENABLED, 'true');
|
||||
|
||||
// Mount two instances simultaneously (AppView + Settings > AI): only 1 immediate poll + 1 3s interval
|
||||
await act(async () => {
|
||||
renderer = create(React.createElement(DualMount, { showSecond: true }));
|
||||
});
|
||||
assert.equal(hookA.enabled, true);
|
||||
assert.equal(hookB.enabled, true);
|
||||
assert.equal(statusCalls, 1, 'mounting two hooks must share one initial poll');
|
||||
|
||||
await act(async () => t.mock.timers.tick(EXTERNAL_MCP_RUNTIME_STATUS_POLL_MS));
|
||||
assert.equal(statusCalls, 2, 'one 3s tick must fire exactly one status check across both hooks');
|
||||
|
||||
// Unmounting the second instance keeps the shared poller running
|
||||
await act(async () => {
|
||||
renderer!.update(React.createElement(DualMount, { showSecond: false }));
|
||||
});
|
||||
await act(async () => t.mock.timers.tick(EXTERNAL_MCP_RUNTIME_STATUS_POLL_MS));
|
||||
assert.equal(statusCalls, 3);
|
||||
|
||||
// Re-mount second instance, then hide document: polling pauses completely
|
||||
await act(async () => {
|
||||
renderer!.update(React.createElement(DualMount, { showSecond: true }));
|
||||
});
|
||||
await setVisibility('hidden');
|
||||
await act(async () => t.mock.timers.tick(30_000));
|
||||
assert.equal(statusCalls, 3, 'hidden document must not poll externalMcpGetStatus');
|
||||
|
||||
// Runtime idles off while hidden; returning to visible immediately catches up and updates both hooks
|
||||
runtimeEnabled = false;
|
||||
await setVisibility('visible');
|
||||
assert.equal(statusCalls, 4, 'returning to visible must immediately check runtime status');
|
||||
assert.equal(hookA.enabled, false);
|
||||
assert.equal(hookB.enabled, false);
|
||||
assert.equal(readExternalMcpStoredEnabled(), false);
|
||||
|
||||
// Once disabled, polling stops completely
|
||||
await act(async () => t.mock.timers.tick(30_000));
|
||||
assert.equal(statusCalls, 4, 'disabled switch must stop polling');
|
||||
} finally {
|
||||
if (renderer) await act(async () => renderer!.unmount());
|
||||
assert.equal(visibilityListeners.size, 0, 'visibility listener must detach when ref-count reaches 0');
|
||||
resetExternalMcpStartupReadyForTests();
|
||||
if (previousDocument) Object.defineProperty(globalThis, 'document', previousDocument);
|
||||
else Reflect.deleteProperty(globalThis, 'document');
|
||||
if (previousWindow) Object.defineProperty(globalThis, 'window', previousWindow);
|
||||
else Reflect.deleteProperty(globalThis, 'window');
|
||||
if (previousAct) Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', previousAct);
|
||||
else Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
restoreStorage();
|
||||
t.mock.timers.reset();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -42,6 +42,98 @@ let externalMcpStartupReadyWaitResolve: (() => void) | null = null;
|
||||
/** Bumps on every intentional enable/disable so stale startup applies lose. */
|
||||
let externalMcpEnableGeneration = 0;
|
||||
let externalMcpConfigError: string | null = null;
|
||||
// Module-level ref-counted runtime status poller so multiple mounted hook
|
||||
// instances (AppView + Settings > AI) share a single 3s timer and pause while hidden.
|
||||
let externalMcpPollRefs = 0;
|
||||
let externalMcpPollIntervalId: ReturnType<typeof setInterval> | null = null;
|
||||
let externalMcpPollInFlight = false;
|
||||
let externalMcpPollGeneration = 0;
|
||||
let externalMcpPollVisibilityDocument: Document | null = null;
|
||||
|
||||
function isExternalMcpDocumentHidden(): boolean {
|
||||
if (typeof document === 'undefined') return false;
|
||||
if (typeof document.visibilityState === 'string') {
|
||||
return document.visibilityState === 'hidden';
|
||||
}
|
||||
return document.hidden === true;
|
||||
}
|
||||
|
||||
async function syncExternalMcpRuntimeStatus(): Promise<void> {
|
||||
if (externalMcpPollRefs <= 0 || externalMcpPollInFlight || isExternalMcpDocumentHidden()) {
|
||||
return;
|
||||
}
|
||||
const generation = externalMcpPollGeneration;
|
||||
externalMcpPollInFlight = true;
|
||||
try {
|
||||
// Wait until App has finished startup reconcile so a still-disabled runtime
|
||||
// is not mistaken for "user turned it off / idle timeout".
|
||||
await waitForExternalMcpStartupReady();
|
||||
if (generation !== externalMcpPollGeneration || externalMcpPollRefs <= 0 || isExternalMcpDocumentHidden()) {
|
||||
return;
|
||||
}
|
||||
const status = await netcattyBridge.get()?.externalMcpGetStatus?.();
|
||||
if (generation !== externalMcpPollGeneration || externalMcpPollRefs <= 0) {
|
||||
return;
|
||||
}
|
||||
// Only clear the shared switch for an intentional runtime-off (idle /
|
||||
// explicit disable). Start failures set error and should keep preference.
|
||||
if (status?.ok && !status.enabled && !status.error) {
|
||||
localStorageAdapter.writeBoolean(STORAGE_KEY_AI_EXTERNAL_MCP_ENABLED, false);
|
||||
emitAIStateChanged(STORAGE_KEY_AI_EXTERNAL_MCP_ENABLED);
|
||||
}
|
||||
} catch {
|
||||
// Keep the user's stored switch state during transient bridge errors.
|
||||
} finally {
|
||||
externalMcpPollInFlight = false;
|
||||
}
|
||||
}
|
||||
|
||||
function syncExternalMcpPollTimer(): void {
|
||||
const shouldPoll = externalMcpPollRefs > 0 && !isExternalMcpDocumentHidden();
|
||||
if (shouldPoll) {
|
||||
if (externalMcpPollIntervalId === null) {
|
||||
externalMcpPollIntervalId = setInterval(() => {
|
||||
void syncExternalMcpRuntimeStatus();
|
||||
}, EXTERNAL_MCP_RUNTIME_STATUS_POLL_MS);
|
||||
}
|
||||
} else if (externalMcpPollIntervalId !== null) {
|
||||
clearInterval(externalMcpPollIntervalId);
|
||||
externalMcpPollIntervalId = null;
|
||||
}
|
||||
}
|
||||
|
||||
function handleExternalMcpVisibilityChange(): void {
|
||||
if (isExternalMcpDocumentHidden()) {
|
||||
externalMcpPollGeneration += 1;
|
||||
syncExternalMcpPollTimer();
|
||||
return;
|
||||
}
|
||||
syncExternalMcpPollTimer();
|
||||
void syncExternalMcpRuntimeStatus();
|
||||
}
|
||||
|
||||
function attachExternalMcpVisibilityListener(): void {
|
||||
if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') {
|
||||
return;
|
||||
}
|
||||
if (externalMcpPollVisibilityDocument === document) return;
|
||||
if (
|
||||
externalMcpPollVisibilityDocument
|
||||
&& typeof externalMcpPollVisibilityDocument.removeEventListener === 'function'
|
||||
) {
|
||||
externalMcpPollVisibilityDocument.removeEventListener('visibilitychange', handleExternalMcpVisibilityChange);
|
||||
}
|
||||
document.addEventListener('visibilitychange', handleExternalMcpVisibilityChange);
|
||||
externalMcpPollVisibilityDocument = document;
|
||||
}
|
||||
|
||||
function detachExternalMcpVisibilityListener(): void {
|
||||
if (!externalMcpPollVisibilityDocument) return;
|
||||
if (typeof externalMcpPollVisibilityDocument.removeEventListener === 'function') {
|
||||
externalMcpPollVisibilityDocument.removeEventListener('visibilitychange', handleExternalMcpVisibilityChange);
|
||||
}
|
||||
externalMcpPollVisibilityDocument = null;
|
||||
}
|
||||
|
||||
function getWindowHash(hash?: string): string {
|
||||
if (typeof hash === 'string') return hash;
|
||||
@@ -81,6 +173,14 @@ export function resetExternalMcpStartupReadyForTests(): void {
|
||||
externalMcpEnableGeneration = 0;
|
||||
externalMcpConfigError = null;
|
||||
externalMcpStartupSyncPromise = null;
|
||||
if (externalMcpPollIntervalId !== null) {
|
||||
clearInterval(externalMcpPollIntervalId);
|
||||
externalMcpPollIntervalId = null;
|
||||
}
|
||||
detachExternalMcpVisibilityListener();
|
||||
externalMcpPollRefs = 0;
|
||||
externalMcpPollInFlight = false;
|
||||
externalMcpPollGeneration = 0;
|
||||
}
|
||||
|
||||
export function getExternalMcpEnableGenerationForTests(): number {
|
||||
@@ -763,35 +863,26 @@ export function useExternalMcpToggleState() {
|
||||
useEffect(() => {
|
||||
// Peer windows must never auto-clear the shared stored switch from runtime status.
|
||||
if (isPeerSessionWindow || !enabled) return;
|
||||
let cancelled = false;
|
||||
|
||||
const syncRuntimeStatus = async () => {
|
||||
try {
|
||||
// Wait until App has finished startup reconcile so a still-disabled runtime
|
||||
// is not mistaken for "user turned it off / idle timeout".
|
||||
await waitForExternalMcpStartupReady();
|
||||
if (cancelled) return;
|
||||
const status = await netcattyBridge.get()?.externalMcpGetStatus?.();
|
||||
if (cancelled) return;
|
||||
// Only clear the shared switch for an intentional runtime-off (idle /
|
||||
// explicit disable). Start failures set error and should keep preference.
|
||||
if (status?.ok && !status.enabled && !status.error) {
|
||||
persistEnabled(false);
|
||||
}
|
||||
} catch {
|
||||
// Keep the user's stored switch state during transient bridge errors.
|
||||
externalMcpPollRefs += 1;
|
||||
if (externalMcpPollRefs === 1) {
|
||||
externalMcpPollGeneration += 1;
|
||||
attachExternalMcpVisibilityListener();
|
||||
syncExternalMcpPollTimer();
|
||||
void syncExternalMcpRuntimeStatus();
|
||||
} else if (!isExternalMcpDocumentHidden() && externalMcpPollIntervalId === null) {
|
||||
syncExternalMcpPollTimer();
|
||||
}
|
||||
|
||||
return () => {
|
||||
externalMcpPollRefs = Math.max(0, externalMcpPollRefs - 1);
|
||||
if (externalMcpPollRefs === 0) {
|
||||
externalMcpPollGeneration += 1;
|
||||
detachExternalMcpVisibilityListener();
|
||||
syncExternalMcpPollTimer();
|
||||
}
|
||||
};
|
||||
|
||||
const intervalId = window.setInterval(() => {
|
||||
void syncRuntimeStatus();
|
||||
}, EXTERNAL_MCP_RUNTIME_STATUS_POLL_MS);
|
||||
void syncRuntimeStatus();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.clearInterval(intervalId);
|
||||
};
|
||||
}, [enabled, isPeerSessionWindow, persistEnabled]);
|
||||
}, [enabled, isPeerSessionWindow]);
|
||||
|
||||
return { enabled, setEnabled, error };
|
||||
}
|
||||
@@ -25,6 +25,7 @@ export const getAppLevelActions = (): Set<string> => {
|
||||
'closeTab',
|
||||
'closeSession',
|
||||
'newTab',
|
||||
'reopenClosedTab',
|
||||
'openHosts',
|
||||
'openSftp',
|
||||
'quickSwitch',
|
||||
|
||||
@@ -15,6 +15,8 @@ export type ChainProgress = {
|
||||
currentHop: number;
|
||||
totalHops: number;
|
||||
currentHostLabel: string;
|
||||
/** host:port of the hop being connected; absent from older progress events. */
|
||||
currentHostAddress?: string;
|
||||
connectionPhase: string;
|
||||
} | null;
|
||||
|
||||
@@ -117,13 +119,14 @@ export function useHostConnectionTest(input: HostConnectionTestInput) {
|
||||
|
||||
// Subscribe to chain progress for the active attempt.
|
||||
useEffect(() => {
|
||||
const unsub = backend.onChainProgress?.((sessionId, hop, total, label, phase, phaseError) => {
|
||||
const unsub = backend.onChainProgress?.((sessionId, hop, total, label, phase, phaseError, address) => {
|
||||
if (sessionId !== sessionIdRef.current) return;
|
||||
if (total > 1) {
|
||||
setChainProgress({
|
||||
currentHop: hop,
|
||||
totalHops: total,
|
||||
currentHostLabel: label,
|
||||
currentHostAddress: address,
|
||||
connectionPhase: phase,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -159,18 +159,32 @@ export function useMonitorRuntime() {
|
||||
retryVersion,
|
||||
]);
|
||||
// Poll every second while anything is monitored (here or in another window);
|
||||
// otherwise only every 10 s to notice monitors started elsewhere. Starting a
|
||||
// panel here publishes demand and reads a snapshot immediately, and flipping
|
||||
// `hasRunningPanels` restarts this loop at the fast cadence.
|
||||
// otherwise only every 10 s to notice monitors started elsewhere. Pause
|
||||
// renderer polling while hidden and run an immediate catch-up poll on return
|
||||
// to visible (main-process sampling stays untouched).
|
||||
const hasRunningPanels = running.size > 0;
|
||||
useEffect(() => {
|
||||
const bridge = netcattyBridge.get();
|
||||
let disposed = false;
|
||||
let pending = false;
|
||||
let resyncOnIdle = false;
|
||||
let remoteRunning = false;
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
const isHidden = () => {
|
||||
if (typeof document === "undefined") return false;
|
||||
if (typeof document.visibilityState === "string") {
|
||||
return document.visibilityState === "hidden";
|
||||
}
|
||||
return document.hidden === true;
|
||||
};
|
||||
const clearTimer = () => {
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
timer = null;
|
||||
}
|
||||
};
|
||||
const poll = async () => {
|
||||
if (pending || !bridge?.monitorSnapshot) return;
|
||||
if (disposed || pending || isHidden() || !bridge?.monitorSnapshot) return;
|
||||
pending = true;
|
||||
try {
|
||||
const snapshot = await bridge.monitorSnapshot(getMonitorHistoryCursor());
|
||||
@@ -196,15 +210,41 @@ export function useMonitorRuntime() {
|
||||
}
|
||||
};
|
||||
const schedule = () => {
|
||||
if (disposed) return;
|
||||
if (disposed || isHidden()) return;
|
||||
if (resyncOnIdle) {
|
||||
resyncOnIdle = false;
|
||||
void poll().finally(schedule);
|
||||
return;
|
||||
}
|
||||
clearTimer();
|
||||
timer = setTimeout(() => {
|
||||
timer = null;
|
||||
void poll().finally(schedule);
|
||||
}, hasRunningPanels || remoteRunning ? 1000 : 10_000);
|
||||
};
|
||||
void poll().finally(schedule);
|
||||
const handleVisibilityChange = () => {
|
||||
if (disposed) return;
|
||||
if (isHidden()) {
|
||||
resyncOnIdle = false;
|
||||
clearTimer();
|
||||
return;
|
||||
}
|
||||
clearTimer();
|
||||
if (pending) {
|
||||
resyncOnIdle = true;
|
||||
return;
|
||||
}
|
||||
void poll().finally(schedule);
|
||||
};
|
||||
const doc = typeof document !== "undefined" ? document : null;
|
||||
doc?.addEventListener?.("visibilitychange", handleVisibilityChange);
|
||||
if (!isHidden()) {
|
||||
void poll().finally(schedule);
|
||||
}
|
||||
return () => {
|
||||
disposed = true;
|
||||
if (timer) clearTimeout(timer);
|
||||
clearTimer();
|
||||
doc?.removeEventListener?.("visibilitychange", handleVisibilityChange);
|
||||
};
|
||||
}, [hasRunningPanels]);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import React, { act } from "react";
|
||||
import { create, type ReactTestRenderer } from "react-test-renderer";
|
||||
import { netcattyBridge } from "../../infrastructure/services/netcattyBridge";
|
||||
import {
|
||||
AppSettingsRuntimeContext,
|
||||
AppVaultRuntimeContext,
|
||||
type AppSettingsRuntime,
|
||||
type AppVaultContextValue,
|
||||
} from "./appRuntimeBridge";
|
||||
import { useMonitorRuntime } from "./useMonitorRuntime";
|
||||
|
||||
const MOCK_VAULT_CONTEXT = {
|
||||
hosts: [],
|
||||
keys: [],
|
||||
identities: [],
|
||||
groupConfigs: [],
|
||||
proxyProfiles: [],
|
||||
knownHosts: [],
|
||||
isInitialized: true,
|
||||
} as unknown as AppVaultContextValue;
|
||||
|
||||
const MOCK_SETTINGS_CONTEXT = {
|
||||
terminalSettings: { verifyHostKeys: true, keepaliveInterval: 30, keepaliveCountMax: 10 },
|
||||
} as unknown as AppSettingsRuntime;
|
||||
|
||||
function wrapWithProviders(node: React.ReactElement) {
|
||||
return React.createElement(
|
||||
AppVaultRuntimeContext.Provider,
|
||||
{ value: MOCK_VAULT_CONTEXT },
|
||||
React.createElement(
|
||||
AppSettingsRuntimeContext.Provider,
|
||||
{ value: MOCK_SETTINGS_CONTEXT },
|
||||
node,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function installDomGlobals(initialVisibility: DocumentVisibilityState = "visible") {
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
const setGlobal = (key: string, value: unknown) => {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
};
|
||||
|
||||
const visibilityListeners = new Set<() => void>();
|
||||
const windowListeners = new Map<string, Set<() => void>>();
|
||||
const backing = new Map<string, string>();
|
||||
const storage: Storage = {
|
||||
get length() { return backing.size; },
|
||||
clear() { backing.clear(); },
|
||||
getItem(key) { return backing.get(key) ?? null; },
|
||||
key(index) { return Array.from(backing.keys())[index] ?? null; },
|
||||
removeItem(key) { backing.delete(key); },
|
||||
setItem(key, value) { backing.set(key, value); },
|
||||
};
|
||||
let visibilityState: DocumentVisibilityState = initialVisibility;
|
||||
|
||||
setGlobal("IS_REACT_ACT_ENVIRONMENT", true);
|
||||
setGlobal("localStorage", storage);
|
||||
setGlobal("window", {
|
||||
addEventListener(type: string, listener: () => void) {
|
||||
let set = windowListeners.get(type);
|
||||
if (!set) {
|
||||
set = new Set();
|
||||
windowListeners.set(type, set);
|
||||
}
|
||||
set.add(listener);
|
||||
},
|
||||
removeEventListener(type: string, listener: () => void) {
|
||||
windowListeners.get(type)?.delete(listener);
|
||||
},
|
||||
dispatchEvent() { return true; },
|
||||
});
|
||||
setGlobal("document", {
|
||||
get visibilityState() { return visibilityState; },
|
||||
get hidden() { return visibilityState === "hidden"; },
|
||||
addEventListener(type: string, listener: () => void) {
|
||||
if (type === "visibilitychange") visibilityListeners.add(listener);
|
||||
},
|
||||
removeEventListener(type: string, listener: () => void) {
|
||||
if (type === "visibilitychange") visibilityListeners.delete(listener);
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
visibilityListeners,
|
||||
async setVisibility(next: DocumentVisibilityState) {
|
||||
visibilityState = next;
|
||||
await act(async () => {
|
||||
for (const listener of [...visibilityListeners]) listener();
|
||||
});
|
||||
},
|
||||
restore() {
|
||||
for (const [key, desc] of previous.entries()) {
|
||||
if (desc) Object.defineProperty(globalThis, key, desc);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("useMonitorRuntime pauses monitorSnapshot polling when hidden and catches up immediately on visible", async (t) => {
|
||||
t.mock.timers.enable({ apis: ["setTimeout", "setInterval", "Date"], now: 10_000 });
|
||||
const env = installDomGlobals("visible");
|
||||
|
||||
let snapshotCalls = 0;
|
||||
let updateCalls = 0;
|
||||
|
||||
t.mock.method(netcattyBridge, "get", () => ({
|
||||
monitorUpdate: async () => {
|
||||
updateCalls += 1;
|
||||
return { epoch: 1, runtimeId: "rt-1", panels: {}, hosts: {}, history: {} };
|
||||
},
|
||||
monitorSnapshot: async () => {
|
||||
snapshotCalls += 1;
|
||||
return { epoch: 1, runtimeId: "rt-1", panels: {}, hosts: {}, history: {} };
|
||||
},
|
||||
monitorStopAll: async () => undefined,
|
||||
}));
|
||||
|
||||
function Probe() {
|
||||
useMonitorRuntime();
|
||||
return null;
|
||||
}
|
||||
|
||||
let root: ReactTestRenderer | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
root = create(wrapWithProviders(React.createElement(Probe)));
|
||||
});
|
||||
assert.equal(snapshotCalls, 1, "initial visible poll should run on mount");
|
||||
const initialUpdateCalls = updateCalls;
|
||||
|
||||
// Idle polling interval is 10s while visible
|
||||
await act(async () => t.mock.timers.tick(10_000));
|
||||
assert.equal(snapshotCalls, 2);
|
||||
|
||||
// Hide document: renderer polling pauses, main-process demand is untouched
|
||||
await env.setVisibility("hidden");
|
||||
await act(async () => t.mock.timers.tick(60_000));
|
||||
assert.equal(snapshotCalls, 2, "hidden document must not poll monitorSnapshot");
|
||||
assert.equal(updateCalls, initialUpdateCalls, "main-process monitorUpdate must stay untouched");
|
||||
|
||||
// Return to visible: immediate catch-up poll + resumes 10s timer
|
||||
await env.setVisibility("visible");
|
||||
assert.equal(snapshotCalls, 3, "returning to visible must immediately poll monitorSnapshot");
|
||||
|
||||
await act(async () => t.mock.timers.tick(10_000));
|
||||
assert.equal(snapshotCalls, 4, "polling must resume after returning to visible");
|
||||
} finally {
|
||||
await act(async () => { root?.unmount(); });
|
||||
assert.equal(env.visibilityListeners.size, 0, "visibility listener must detach on unmount");
|
||||
env.restore();
|
||||
t.mock.timers.reset();
|
||||
}
|
||||
});
|
||||
|
||||
test("useMonitorRuntime mounted while hidden waits until visible to poll", async (t) => {
|
||||
t.mock.timers.enable({ apis: ["setTimeout", "setInterval", "Date"], now: 10_000 });
|
||||
const env = installDomGlobals("hidden");
|
||||
|
||||
let snapshotCalls = 0;
|
||||
|
||||
t.mock.method(netcattyBridge, "get", () => ({
|
||||
monitorUpdate: async () => ({ epoch: 1, runtimeId: "rt-1", panels: {}, hosts: {}, history: {} }),
|
||||
monitorSnapshot: async () => {
|
||||
snapshotCalls += 1;
|
||||
return { epoch: 1, runtimeId: "rt-1", panels: {}, hosts: {}, history: {} };
|
||||
},
|
||||
monitorStopAll: async () => undefined,
|
||||
}));
|
||||
|
||||
function Probe() {
|
||||
useMonitorRuntime();
|
||||
return null;
|
||||
}
|
||||
|
||||
let root: ReactTestRenderer | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
root = create(wrapWithProviders(React.createElement(Probe)));
|
||||
});
|
||||
await act(async () => t.mock.timers.tick(60_000));
|
||||
assert.equal(snapshotCalls, 0, "mounted while hidden must not poll monitorSnapshot");
|
||||
|
||||
await env.setVisibility("visible");
|
||||
assert.equal(snapshotCalls, 1, "becoming visible must trigger catch-up poll");
|
||||
} finally {
|
||||
await act(async () => { root?.unmount(); });
|
||||
env.restore();
|
||||
t.mock.timers.reset();
|
||||
}
|
||||
});
|
||||
@@ -1,16 +1,15 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { TerminalSession, Workspace } from '../../domain/models';
|
||||
import { getNotesSnapshot } from './notesStore';
|
||||
import { useActiveTabId } from './activeTabStore';
|
||||
import { activeTabStore } from './activeTabStore';
|
||||
import { getAppAppLockRuntime } from './appRuntimeBridge';
|
||||
import type { createTrustedPluginAIHostRuntime } from '../../infrastructure/ai/plugin/trustedHostRuntime';
|
||||
import { buildSelectedPluginSources } from '../../infrastructure/ai/plugin/selectedSources';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
|
||||
export function usePluginAIContextHost({ sessions, workspaces }: { sessions: TerminalSession[]; workspaces: Workspace[] }) {
|
||||
const activeTabId = useActiveTabId();
|
||||
const latest = useRef({ activeTabId, sessions, workspaces });
|
||||
latest.current = { activeTabId, sessions, workspaces };
|
||||
const latest = useRef({ sessions, workspaces });
|
||||
latest.current = { sessions, workspaces };
|
||||
const [choice, setChoice] = useState<{ confirm: (id: string) => void; cancel: () => void } | null>(null);
|
||||
const [noteId, setNoteId] = useState('');
|
||||
const [noteChoices, setNoteChoices] = useState<Array<{ id: string; title: string }>>([]);
|
||||
@@ -51,8 +50,11 @@ export function usePluginAIContextHost({ sessions, workspaces }: { sessions: Ter
|
||||
chooser = null; signal.removeEventListener('abort', cancel); setChoice(null);
|
||||
if (id === null || signal.aborted) { reject(Error('Selection cancelled')); return; }
|
||||
selectedNoteId = id || null;
|
||||
resolve(buildSelectedPluginSources(() => ({ ...latest.current,
|
||||
note: getNotesSnapshot().notes.find((note) => note.id === selectedNoteId) ?? null })));
|
||||
resolve(buildSelectedPluginSources(() => ({
|
||||
...latest.current,
|
||||
activeTabId: activeTabStore.getActiveTabId(),
|
||||
note: getNotesSnapshot().notes.find((note) => note.id === selectedNoteId) ?? null,
|
||||
})));
|
||||
};
|
||||
const cancel = () => finish(null);
|
||||
chooser = { runtimeId, cancel };
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import React, { act } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
|
||||
import {
|
||||
canReusePluginContributionSnapshot,
|
||||
collectOwnedPluginMenus,
|
||||
createPluginContributionRefreshGuard,
|
||||
failClosedPluginContributionLoad,
|
||||
resolvePluginContributionLoadState,
|
||||
usePluginContributions,
|
||||
type UsePluginContributionsOptions,
|
||||
type UsePluginContributionsResult,
|
||||
} from './usePluginContributions';
|
||||
import { _resetSharedPluginRuntimeStatusForTests } from './pluginRuntimeStatusCache';
|
||||
|
||||
function Probe() {
|
||||
const contributions = usePluginContributions();
|
||||
@@ -30,7 +37,7 @@ test('plugin contribution refresh failures discard the last successful snapshot'
|
||||
assert.match(failure.error.message, /bridge unavailable/u);
|
||||
});
|
||||
|
||||
test('plugin contribution query changes hide the prior snapshot synchronously', () => {
|
||||
test('plugin contribution query changes hide the prior snapshot synchronously without flipping runtime availability', () => {
|
||||
const staleSnapshot = {
|
||||
locale: 'en',
|
||||
plugins: [{ id: 'com.example.stale' }],
|
||||
@@ -43,9 +50,135 @@ test('plugin contribution query changes hide the prior snapshot synchronously',
|
||||
loading: false,
|
||||
});
|
||||
|
||||
assert.equal(selected.available, false);
|
||||
assert.equal(selected.available, true);
|
||||
assert.equal(selected.loading, true);
|
||||
assert.equal(selected.snapshot.plugins.length, 0);
|
||||
|
||||
const unavailable = resolvePluginContributionLoadState({
|
||||
currentQueryKey: '{"context":{"terminal.sessionId":"session-2"}}',
|
||||
loadedQueryKey: '{"context":{"terminal.sessionId":"session-1"}}',
|
||||
snapshot: staleSnapshot,
|
||||
available: false,
|
||||
loading: false,
|
||||
});
|
||||
assert.equal(unavailable.available, false);
|
||||
assert.equal(unavailable.loading, true);
|
||||
assert.equal(unavailable.snapshot.plugins.length, 0);
|
||||
|
||||
const reused = resolvePluginContributionLoadState({
|
||||
currentQueryKey: '{"context":{"terminal.sessionId":"session-2"}}',
|
||||
loadedQueryKey: '{"context":{"terminal.sessionId":"session-1"}}',
|
||||
snapshot: staleSnapshot,
|
||||
available: true,
|
||||
loading: false,
|
||||
reuseSnapshot: true,
|
||||
});
|
||||
assert.equal(reused.available, true);
|
||||
assert.equal(reused.loading, false);
|
||||
assert.equal(reused.snapshot, staleSnapshot);
|
||||
});
|
||||
|
||||
test('canReusePluginContributionSnapshot short-circuits only when settled and context-insensitive', () => {
|
||||
const emptySnapshot: NetcattyPluginContributionSnapshot = { locale: 'en', plugins: [] };
|
||||
const pluginWithoutKeybindings = {
|
||||
locale: 'en',
|
||||
plugins: [{ id: 'com.example.theme', keybindings: [] }],
|
||||
} as unknown as NetcattyPluginContributionSnapshot;
|
||||
const pluginWithKeybindings = {
|
||||
locale: 'en',
|
||||
plugins: [{ id: 'com.example.kb', keybindings: [{ command: 'run', key: 'ctrl+k', enabled: true }] }],
|
||||
} as unknown as NetcattyPluginContributionSnapshot;
|
||||
|
||||
assert.equal(canReusePluginContributionSnapshot({
|
||||
settled: false,
|
||||
available: true,
|
||||
error: null,
|
||||
currentRevision: 0,
|
||||
loadedRevision: 0,
|
||||
currentLocale: 'en',
|
||||
loadedLocale: 'en',
|
||||
snapshot: emptySnapshot,
|
||||
}), false);
|
||||
|
||||
assert.equal(canReusePluginContributionSnapshot({
|
||||
settled: true,
|
||||
available: false,
|
||||
error: null,
|
||||
currentRevision: 0,
|
||||
loadedRevision: 0,
|
||||
currentLocale: 'en',
|
||||
loadedLocale: 'en',
|
||||
snapshot: emptySnapshot,
|
||||
}), true);
|
||||
|
||||
assert.equal(canReusePluginContributionSnapshot({
|
||||
settled: true,
|
||||
available: true,
|
||||
error: null,
|
||||
currentRevision: 0,
|
||||
loadedRevision: 0,
|
||||
currentLocale: 'en',
|
||||
loadedLocale: 'en',
|
||||
snapshot: emptySnapshot,
|
||||
}), true);
|
||||
|
||||
assert.equal(canReusePluginContributionSnapshot({
|
||||
settled: true,
|
||||
available: true,
|
||||
error: null,
|
||||
currentRevision: 1,
|
||||
loadedRevision: 0,
|
||||
currentLocale: 'en',
|
||||
loadedLocale: 'en',
|
||||
snapshot: emptySnapshot,
|
||||
}), false);
|
||||
|
||||
assert.equal(canReusePluginContributionSnapshot({
|
||||
settled: true,
|
||||
available: true,
|
||||
error: null,
|
||||
currentRevision: 0,
|
||||
loadedRevision: 0,
|
||||
currentLocale: 'fr',
|
||||
loadedLocale: 'en',
|
||||
snapshot: emptySnapshot,
|
||||
}), false);
|
||||
|
||||
assert.equal(canReusePluginContributionSnapshot({
|
||||
settled: true,
|
||||
available: true,
|
||||
error: null,
|
||||
currentRevision: 0,
|
||||
loadedRevision: 0,
|
||||
currentLocale: 'en',
|
||||
loadedLocale: 'en',
|
||||
snapshot: pluginWithoutKeybindings,
|
||||
}), false);
|
||||
|
||||
const hasKeybindings = (snapshot: NetcattyPluginContributionSnapshot) =>
|
||||
snapshot.plugins.some((plugin) => plugin.keybindings.length > 0);
|
||||
assert.equal(canReusePluginContributionSnapshot({
|
||||
settled: true,
|
||||
available: true,
|
||||
error: null,
|
||||
currentRevision: 0,
|
||||
loadedRevision: 0,
|
||||
currentLocale: 'en',
|
||||
loadedLocale: 'en',
|
||||
snapshot: pluginWithoutKeybindings,
|
||||
isContextSensitive: hasKeybindings,
|
||||
}), true);
|
||||
assert.equal(canReusePluginContributionSnapshot({
|
||||
settled: true,
|
||||
available: true,
|
||||
error: null,
|
||||
currentRevision: 0,
|
||||
loadedRevision: 0,
|
||||
currentLocale: 'en',
|
||||
loadedLocale: 'en',
|
||||
snapshot: pluginWithKeybindings,
|
||||
isContextSensitive: hasKeybindings,
|
||||
}), false);
|
||||
});
|
||||
|
||||
test('plugin contribution refreshes reject stale asynchronous results', async () => {
|
||||
@@ -90,3 +223,236 @@ test('owned menu rendering inherits command icons when a placement has no overri
|
||||
icon: commandIcon,
|
||||
});
|
||||
});
|
||||
|
||||
function createDomHarness(netcatty: Record<string, unknown>) {
|
||||
_resetSharedPluginRuntimeStatusForTests();
|
||||
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost' });
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
const install = (name: string, value: unknown) => {
|
||||
previous.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
|
||||
Object.defineProperty(globalThis, name, { configurable: true, writable: true, value });
|
||||
};
|
||||
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node']) {
|
||||
install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
|
||||
}
|
||||
install('IS_REACT_ACT_ENVIRONMENT', true);
|
||||
Object.assign(dom.window, { netcatty });
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 20));
|
||||
const perform = async (action: () => void) => act(async () => {
|
||||
action();
|
||||
await settle();
|
||||
});
|
||||
const cleanup = async () => {
|
||||
await act(async () => root.unmount());
|
||||
dom.window.close();
|
||||
_resetSharedPluginRuntimeStatusForTests();
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
};
|
||||
return { root, perform, cleanup };
|
||||
}
|
||||
|
||||
test('usePluginContributions skips context-driven IPC and listener churn when 0 plugins are active and invalidates on change', async () => {
|
||||
let statusCalls = 0;
|
||||
let contributionCalls = 0;
|
||||
let subscribeCalls = 0;
|
||||
let unsubscribeCalls = 0;
|
||||
const listeners = new Set<() => void>();
|
||||
let currentPlugins: NetcattyPluginContributionSnapshot['plugins'] = [];
|
||||
const queriedContexts: Array<Record<string, unknown> | undefined> = [];
|
||||
|
||||
const harness = createDomHarness({
|
||||
async getPluginRuntimeStatus() {
|
||||
statusCalls += 1;
|
||||
return { available: true };
|
||||
},
|
||||
async getPluginContributions(query?: NetcattyPluginContributionQuery) {
|
||||
contributionCalls += 1;
|
||||
queriedContexts.push(query?.context);
|
||||
return { locale: query?.locale ?? 'en', plugins: currentPlugins };
|
||||
},
|
||||
onPluginContributionsChanged(callback: () => void) {
|
||||
subscribeCalls += 1;
|
||||
listeners.add(callback);
|
||||
return () => {
|
||||
unsubscribeCalls += 1;
|
||||
listeners.delete(callback);
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const observed: Array<{ available: boolean; loading: boolean; count: number }> = [];
|
||||
let latest!: UsePluginContributionsResult;
|
||||
function Fixture({ query, options }: { query: NetcattyPluginContributionQuery; options?: UsePluginContributionsOptions }) {
|
||||
latest = usePluginContributions(query, options);
|
||||
observed.push({ available: latest.available, loading: latest.loading, count: latest.snapshot.plugins.length });
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
await harness.perform(() => harness.root.render(
|
||||
<Fixture query={{ locale: 'en', context: { 'netcatty.activeTabId': 'tab-1' } }} />,
|
||||
));
|
||||
assert.equal(latest.available, true);
|
||||
assert.equal(latest.loading, false);
|
||||
assert.equal(statusCalls, 1);
|
||||
assert.equal(contributionCalls, 1);
|
||||
assert.equal(subscribeCalls, 1);
|
||||
assert.equal(unsubscribeCalls, 0);
|
||||
|
||||
observed.length = 0;
|
||||
await harness.perform(() => harness.root.render(
|
||||
<Fixture query={{ locale: 'en', context: { 'netcatty.activeTabId': 'tab-2' } }} />,
|
||||
));
|
||||
assert.equal(latest.available, true);
|
||||
assert.equal(latest.loading, false);
|
||||
assert.equal(contributionCalls, 1, '0 active plugins should short-circuit context-driven re-query');
|
||||
assert.equal(subscribeCalls, 1, 'tab switch should not re-subscribe onPluginContributionsChanged');
|
||||
assert.equal(unsubscribeCalls, 0);
|
||||
assert.equal(observed.every((entry) => entry.available && !entry.loading), true);
|
||||
|
||||
currentPlugins = [{
|
||||
id: 'com.example.active',
|
||||
version: '1.0.0',
|
||||
displayName: 'Active',
|
||||
description: '',
|
||||
commands: [],
|
||||
keybindings: [{ command: 'com.example.run', key: 'ctrl+k', enabled: true }],
|
||||
menus: [],
|
||||
settings: [],
|
||||
views: [],
|
||||
}];
|
||||
await harness.perform(() => {
|
||||
for (const listener of listeners) listener();
|
||||
});
|
||||
assert.equal(contributionCalls, 2, 'onPluginContributionsChanged must invalidate and re-query');
|
||||
assert.deepEqual(queriedContexts.at(-1), { 'netcatty.activeTabId': 'tab-2' });
|
||||
assert.equal(latest.snapshot.plugins.length, 1);
|
||||
assert.equal(latest.available, true);
|
||||
} finally {
|
||||
await harness.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('usePluginContributions keeps available true while failing closed on snapshot during context-sensitive reload', async () => {
|
||||
let resolveTab2!: (snapshot: NetcattyPluginContributionSnapshot) => void;
|
||||
let contributionCalls = 0;
|
||||
const pluginTab1 = {
|
||||
id: 'com.example.kb',
|
||||
version: '1.0.0',
|
||||
displayName: 'KB',
|
||||
description: '',
|
||||
commands: [],
|
||||
keybindings: [{ command: 'com.example.tab1', key: 'ctrl+k', enabled: true }],
|
||||
menus: [],
|
||||
settings: [],
|
||||
views: [],
|
||||
};
|
||||
const pluginTab2 = {
|
||||
...pluginTab1,
|
||||
keybindings: [{ command: 'com.example.tab2', key: 'ctrl+k', enabled: false }],
|
||||
};
|
||||
|
||||
const harness = createDomHarness({
|
||||
async getPluginRuntimeStatus() {
|
||||
return { available: true };
|
||||
},
|
||||
getPluginContributions(query?: NetcattyPluginContributionQuery) {
|
||||
contributionCalls += 1;
|
||||
if (query?.context?.['netcatty.activeTabId'] === 'tab-1') {
|
||||
return Promise.resolve({ locale: 'en', plugins: [pluginTab1] });
|
||||
}
|
||||
return new Promise<NetcattyPluginContributionSnapshot>((resolve) => {
|
||||
resolveTab2 = resolve;
|
||||
});
|
||||
},
|
||||
onPluginContributionsChanged() {
|
||||
return () => {};
|
||||
},
|
||||
});
|
||||
|
||||
let latest!: UsePluginContributionsResult;
|
||||
const availableHistory: boolean[] = [];
|
||||
function Fixture({ tabId }: { tabId: string }) {
|
||||
latest = usePluginContributions({ locale: 'en', context: { 'netcatty.activeTabId': tabId } });
|
||||
availableHistory.push(latest.available);
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
await harness.perform(() => harness.root.render(<Fixture tabId="tab-1" />));
|
||||
assert.equal(latest.available, true);
|
||||
assert.equal(latest.loading, false);
|
||||
assert.equal(latest.snapshot.plugins[0]?.keybindings[0]?.enabled, true);
|
||||
|
||||
availableHistory.length = 0;
|
||||
await harness.perform(() => harness.root.render(<Fixture tabId="tab-2" />));
|
||||
assert.equal(contributionCalls, 2);
|
||||
assert.equal(latest.available, true, 'runtime available must not flip to false during query reload');
|
||||
assert.equal(latest.loading, true);
|
||||
assert.equal(latest.snapshot.plugins.length, 0, 'stale Tab 1 snapshot must fail closed on Tab 2');
|
||||
assert.deepEqual(availableHistory, [true]);
|
||||
|
||||
await harness.perform(() => resolveTab2({ locale: 'en', plugins: [pluginTab2] }));
|
||||
assert.equal(latest.available, true);
|
||||
assert.equal(latest.loading, false);
|
||||
assert.equal(latest.snapshot.plugins[0]?.keybindings[0]?.enabled, false);
|
||||
} finally {
|
||||
await harness.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('usePluginContributions skips context re-queries while runtime is unavailable until contributions change', async () => {
|
||||
let statusCalls = 0;
|
||||
let contributionCalls = 0;
|
||||
let runtimeAvailable = false;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
const harness = createDomHarness({
|
||||
async getPluginRuntimeStatus() {
|
||||
statusCalls += 1;
|
||||
return { available: runtimeAvailable };
|
||||
},
|
||||
async getPluginContributions() {
|
||||
contributionCalls += 1;
|
||||
return { locale: 'en', plugins: [] };
|
||||
},
|
||||
onPluginContributionsChanged(callback: () => void) {
|
||||
listeners.add(callback);
|
||||
return () => { listeners.delete(callback); };
|
||||
},
|
||||
});
|
||||
|
||||
let latest!: UsePluginContributionsResult;
|
||||
function Fixture({ tabId }: { tabId: string }) {
|
||||
latest = usePluginContributions({ locale: 'en', context: { 'netcatty.activeTabId': tabId } });
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
await harness.perform(() => harness.root.render(<Fixture tabId="tab-1" />));
|
||||
assert.equal(latest.available, false);
|
||||
assert.equal(latest.loading, false);
|
||||
assert.equal(statusCalls, 1);
|
||||
assert.equal(contributionCalls, 0);
|
||||
|
||||
await harness.perform(() => harness.root.render(<Fixture tabId="tab-2" />));
|
||||
assert.equal(latest.available, false);
|
||||
assert.equal(latest.loading, false);
|
||||
assert.equal(statusCalls, 1, 'unavailable runtime should not re-query on tab switch');
|
||||
assert.equal(contributionCalls, 0);
|
||||
|
||||
runtimeAvailable = true;
|
||||
await harness.perform(() => {
|
||||
for (const listener of listeners) listener();
|
||||
});
|
||||
assert.equal(latest.available, true);
|
||||
assert.equal(statusCalls, 2);
|
||||
assert.equal(contributionCalls, 1);
|
||||
} finally {
|
||||
await harness.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -10,21 +10,60 @@ const EMPTY_SNAPSHOT: NetcattyPluginContributionSnapshot = Object.freeze({
|
||||
plugins: Object.freeze([]),
|
||||
});
|
||||
|
||||
export type PluginContributionContextSensitivity = (
|
||||
snapshot: NetcattyPluginContributionSnapshot,
|
||||
) => boolean;
|
||||
|
||||
export function hasAnyPluginContributions(
|
||||
snapshot: NetcattyPluginContributionSnapshot,
|
||||
): boolean {
|
||||
return snapshot.plugins.length > 0;
|
||||
}
|
||||
|
||||
export function canReusePluginContributionSnapshot({
|
||||
settled,
|
||||
available,
|
||||
error,
|
||||
currentRevision,
|
||||
loadedRevision,
|
||||
currentLocale,
|
||||
loadedLocale,
|
||||
snapshot,
|
||||
isContextSensitive = hasAnyPluginContributions,
|
||||
}: {
|
||||
settled: boolean;
|
||||
available: boolean;
|
||||
error: Error | null;
|
||||
currentRevision: number;
|
||||
loadedRevision: number;
|
||||
currentLocale: string | undefined;
|
||||
loadedLocale: string | undefined;
|
||||
snapshot: NetcattyPluginContributionSnapshot;
|
||||
isContextSensitive?: PluginContributionContextSensitivity;
|
||||
}): boolean {
|
||||
if (!settled || error !== null || currentRevision !== loadedRevision) return false;
|
||||
if (!available) return true;
|
||||
if (currentLocale !== loadedLocale) return false;
|
||||
return !isContextSensitive(snapshot);
|
||||
}
|
||||
|
||||
export function resolvePluginContributionLoadState({
|
||||
currentQueryKey,
|
||||
loadedQueryKey,
|
||||
snapshot,
|
||||
available,
|
||||
loading,
|
||||
reuseSnapshot = false,
|
||||
}: {
|
||||
currentQueryKey: string;
|
||||
loadedQueryKey: string;
|
||||
snapshot: NetcattyPluginContributionSnapshot;
|
||||
available: boolean;
|
||||
loading: boolean;
|
||||
reuseSnapshot?: boolean;
|
||||
}): Pick<UsePluginContributionsResult, 'available' | 'loading' | 'snapshot'> {
|
||||
if (currentQueryKey !== loadedQueryKey) {
|
||||
return { available: false, loading: true, snapshot: EMPTY_SNAPSHOT };
|
||||
if (currentQueryKey !== loadedQueryKey && !reuseSnapshot) {
|
||||
return { available, loading: true, snapshot: EMPTY_SNAPSHOT };
|
||||
}
|
||||
return { available, loading, snapshot };
|
||||
}
|
||||
@@ -90,15 +129,26 @@ export interface UsePluginContributionsResult {
|
||||
onViewClosed(callback: (event: NetcattyPluginViewClosedEvent) => void): () => void;
|
||||
}
|
||||
|
||||
export interface UsePluginContributionsOptions {
|
||||
enabled?: boolean;
|
||||
isContextSensitive?: PluginContributionContextSensitivity;
|
||||
}
|
||||
|
||||
export function usePluginContributions(
|
||||
query: NetcattyPluginContributionQuery = {},
|
||||
options: { enabled?: boolean } = {},
|
||||
options: UsePluginContributionsOptions = {},
|
||||
): UsePluginContributionsResult {
|
||||
const enabled = options.enabled !== false;
|
||||
const isContextSensitive = options.isContextSensitive ?? hasAnyPluginContributions;
|
||||
const bridge = typeof window === 'undefined' ? undefined : netcattyBridge.get();
|
||||
const queryLocale = query.locale;
|
||||
const queryKey = useMemo(() => JSON.stringify(query), [query]);
|
||||
const [revision, setRevision] = useState(0);
|
||||
const [loadedSnapshot, setLoadedSnapshot] = useState(() => ({
|
||||
queryKey,
|
||||
locale: queryLocale,
|
||||
revision: -1,
|
||||
settled: false,
|
||||
snapshot: EMPTY_SNAPSHOT,
|
||||
}));
|
||||
const [available, setAvailable] = useState(false);
|
||||
@@ -111,7 +161,14 @@ export function usePluginContributions(
|
||||
if (!enabled || !bridge?.getPluginRuntimeStatus || !bridge.getPluginContributions) {
|
||||
if (!isCurrent()) return;
|
||||
setAvailable(false);
|
||||
setLoadedSnapshot({ queryKey, snapshot: EMPTY_SNAPSHOT });
|
||||
setLoadedSnapshot({
|
||||
queryKey,
|
||||
locale: queryLocale,
|
||||
revision,
|
||||
settled: true,
|
||||
snapshot: EMPTY_SNAPSHOT,
|
||||
});
|
||||
setError(null);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
@@ -120,38 +177,79 @@ export function usePluginContributions(
|
||||
if (!isCurrent()) return;
|
||||
setAvailable(status.available);
|
||||
if (!status.available) {
|
||||
setLoadedSnapshot({ queryKey, snapshot: EMPTY_SNAPSHOT });
|
||||
setLoadedSnapshot({
|
||||
queryKey,
|
||||
locale: queryLocale,
|
||||
revision,
|
||||
settled: true,
|
||||
snapshot: EMPTY_SNAPSHOT,
|
||||
});
|
||||
setError(null);
|
||||
return;
|
||||
}
|
||||
const nextSnapshot = await bridge.getPluginContributions(JSON.parse(queryKey));
|
||||
if (!isCurrent()) return;
|
||||
setLoadedSnapshot({ queryKey, snapshot: nextSnapshot });
|
||||
setLoadedSnapshot({
|
||||
queryKey,
|
||||
locale: queryLocale,
|
||||
revision,
|
||||
settled: true,
|
||||
snapshot: nextSnapshot,
|
||||
});
|
||||
setError(null);
|
||||
} catch (cause) {
|
||||
if (!isCurrent()) return;
|
||||
const failure = failClosedPluginContributionLoad(cause);
|
||||
setAvailable(failure.available);
|
||||
setLoadedSnapshot({ queryKey, snapshot: failure.snapshot });
|
||||
setLoadedSnapshot({
|
||||
queryKey,
|
||||
locale: queryLocale,
|
||||
revision,
|
||||
settled: false,
|
||||
snapshot: failure.snapshot,
|
||||
});
|
||||
setError(failure.error);
|
||||
} finally {
|
||||
if (isCurrent()) setLoading(false);
|
||||
}
|
||||
}, [bridge, enabled, queryKey]);
|
||||
}, [bridge, enabled, queryKey, queryLocale, revision]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
const unsubscribe = bridge?.onPluginContributionsChanged?.(() => {
|
||||
invalidateSharedPluginRuntimeStatus(bridge);
|
||||
setRevision((current) => current + 1);
|
||||
});
|
||||
return () => {
|
||||
unsubscribe?.();
|
||||
setRevision((current) => current + 1);
|
||||
};
|
||||
}, [bridge, enabled]);
|
||||
|
||||
const isCurrentSnapshotReusable = canReusePluginContributionSnapshot({
|
||||
settled: loadedSnapshot.settled,
|
||||
available,
|
||||
error,
|
||||
currentRevision: revision,
|
||||
loadedRevision: loadedSnapshot.revision,
|
||||
currentLocale: queryLocale,
|
||||
loadedLocale: loadedSnapshot.locale,
|
||||
snapshot: loadedSnapshot.snapshot,
|
||||
isContextSensitive,
|
||||
});
|
||||
const hasAttemptedCurrentQuery =
|
||||
loadedSnapshot.queryKey === queryKey && loadedSnapshot.revision === revision;
|
||||
const shouldSkipQueryRefresh = isCurrentSnapshotReusable || hasAttemptedCurrentQuery;
|
||||
|
||||
useEffect(() => {
|
||||
const guard = refreshGuard.current;
|
||||
if (!enabled) return () => guard.invalidate();
|
||||
if (shouldSkipQueryRefresh) return;
|
||||
void refresh();
|
||||
const unsubscribe = bridge?.onPluginContributionsChanged?.(() => {
|
||||
invalidateSharedPluginRuntimeStatus(bridge);
|
||||
void refresh();
|
||||
});
|
||||
return () => {
|
||||
guard.invalidate();
|
||||
unsubscribe?.();
|
||||
};
|
||||
}, [bridge, enabled, refresh]);
|
||||
}, [enabled, refresh, shouldSkipQueryRefresh]);
|
||||
|
||||
const executeCommand = useCallback(async (command: string, args?: unknown, context?: Record<string, unknown>) => {
|
||||
if (!bridge?.executePluginCommand) throw new Error('Plugin commands are unavailable');
|
||||
@@ -197,6 +295,7 @@ export function usePluginContributions(
|
||||
snapshot: loadedSnapshot.snapshot,
|
||||
available,
|
||||
loading,
|
||||
reuseSnapshot: isCurrentSnapshotReusable,
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -24,9 +24,17 @@ type Review = {
|
||||
completionToken?: string;
|
||||
};
|
||||
|
||||
function isHostActionRequestKind(kind: string): boolean {
|
||||
return kind.startsWith('vault.')
|
||||
|| kind === 'network.stream.connectViaHost'
|
||||
|| kind === 'network.stream.confirm'
|
||||
|| kind === 'network.stream.tlsConfirm';
|
||||
}
|
||||
|
||||
export function usePluginHostActions() {
|
||||
const [review, setReview] = useState<Review | null>(null);
|
||||
const [selectedIds, setSelectedIds] = useState<string[]>([]);
|
||||
const [remember, setRemember] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState(false);
|
||||
const current = useRef<Review | null>(null);
|
||||
@@ -44,9 +52,19 @@ export function usePluginHostActions() {
|
||||
|
||||
const assertCurrent = useCallback((entry: Review) => {
|
||||
if (current.current !== entry || Date.now() >= entry.prompt.expiresAt) throw new Error('Host action expired');
|
||||
if (entry.prompt.request.kind === 'network.stream.confirm' || entry.prompt.request.kind === 'network.stream.tlsConfirm') {
|
||||
const lock = getAppAppLockRuntime();
|
||||
if (lock && lock.initialized && lock.locked) throw new Error('App is locked');
|
||||
return;
|
||||
}
|
||||
const vault = getVault();
|
||||
const target = entry.prompt.vaultTarget;
|
||||
if (target && resources.current.resolve(target.resourceId, target.revision) !== entry.host) throw new Error('Selected host changed');
|
||||
if (entry.prompt.durableHostId) {
|
||||
const liveHost = vault.hosts.find((candidate) => candidate.id === entry.prompt.durableHostId);
|
||||
if (!liveHost || liveHost !== entry.host) throw new Error('Saved SSH host changed or was removed');
|
||||
} else if (target && resources.current.resolve(target.resourceId, target.revision) !== entry.host) {
|
||||
throw new Error('Selected host changed');
|
||||
}
|
||||
if ((entry.prompt.request.kind === 'vault.requestConnect' || entry.prompt.request.kind === 'network.stream.connectViaHost') && (vault.groupConfigs !== entry.groups || vault.snippets !== entry.snippets)) {
|
||||
throw new Error('Saved connection settings changed');
|
||||
}
|
||||
@@ -71,7 +89,7 @@ export function usePluginHostActions() {
|
||||
assertCurrent(entry);
|
||||
const request = entry.prompt.request;
|
||||
const target = entry.prompt.vaultTarget;
|
||||
if (request.kind === 'network.stream.connectViaHost' && target && entry.host) {
|
||||
if (request.kind === 'network.stream.connectViaHost' && entry.host && (target || entry.prompt.durableHostId)) {
|
||||
const vault = getVault();
|
||||
const settings = getAppSettingsRuntime();
|
||||
if (!settings || !bridge.openPluginHostStream) throw new Error('Host stream unavailable');
|
||||
@@ -83,7 +101,15 @@ export function usePluginHostActions() {
|
||||
|| latest.hosts !== vault.hosts || latest.knownHosts !== vault.knownHosts || getAppSettingsRuntime()?.terminalSettings !== settings.terminalSettings) throw new Error('Connection settings changed');
|
||||
};
|
||||
assertPrepared();
|
||||
await executePluginHostAction({ kind: 'connect', target }, {
|
||||
if (entry.prompt.durableHostId) {
|
||||
entry.claimed = true;
|
||||
await bridge.openPluginHostStream!({
|
||||
response: { requestId: entry.prompt.requestId, actionToken: entry.prompt.actionToken, action: 'commit' },
|
||||
connectionOptions,
|
||||
});
|
||||
return;
|
||||
}
|
||||
await executePluginHostAction({ kind: 'connect', target: target! }, {
|
||||
getVault, resources: resources.current, assertCurrent: assertPrepared,
|
||||
authorizeCommit: async () => { assertPrepared(); },
|
||||
connect: async () => {
|
||||
@@ -126,12 +152,35 @@ export function usePluginHostActions() {
|
||||
const unsubscribe = bridge.onPluginInteraction((event) => {
|
||||
if ('closed' in event) {
|
||||
if (current.current?.prompt.requestId !== event.requestId) return;
|
||||
current.current = null; setReview(null); setBusy(false); responding.current = false;
|
||||
current.current = null; setReview(null); setRemember(false); setBusy(false); responding.current = false;
|
||||
return;
|
||||
}
|
||||
if (!event.request.kind.startsWith('vault.') && event.request.kind !== 'network.stream.connectViaHost') return;
|
||||
if (!isHostActionRequestKind(event.request.kind)) return;
|
||||
const prompt = event as VaultHostPrompt;
|
||||
try {
|
||||
if (prompt.request.kind === 'network.stream.confirm' || prompt.request.kind === 'network.stream.tlsConfirm') {
|
||||
const entry: Review = {
|
||||
prompt, candidates: [], candidateRevisions: new Map(), customGroups: [],
|
||||
groups: [], snippets: [], managedSources: [], scriptsRun: false, claimed: false,
|
||||
};
|
||||
current.current = entry; setSelectedIds([]); setRemember(false); setBusy(false); setError(false); responding.current = false;
|
||||
setReview(entry);
|
||||
return;
|
||||
}
|
||||
if (prompt.phase === 'commit' && prompt.autoCommit && prompt.durableHostId && prompt.request.kind === 'network.stream.connectViaHost') {
|
||||
const vault = getVault();
|
||||
const host = vault.hosts.find((candidate) => candidate.id === prompt.durableHostId);
|
||||
if (!host) throw new Error('Saved SSH host no longer exists');
|
||||
const entry: Review = {
|
||||
prompt, candidates: [], candidateRevisions: new Map(), customGroups: vault.customGroups,
|
||||
host, groups: vault.groupConfigs, snippets: vault.snippets, managedSources: vault.managedSources,
|
||||
scriptsRun: false, claimed: false,
|
||||
};
|
||||
current.current = entry; setSelectedIds([]); setRemember(false); setBusy(true); setError(false); responding.current = false;
|
||||
setReview(null);
|
||||
void execute(entry);
|
||||
return;
|
||||
}
|
||||
if (prompt.phase === 'commit') {
|
||||
const entry = current.current;
|
||||
if (!entry || entry.prompt.requestId !== prompt.requestId || entry.prompt.request.kind !== prompt.request.kind) throw new Error('Host review is unavailable');
|
||||
@@ -150,7 +199,10 @@ export function usePluginHostActions() {
|
||||
scriptsRun: host ? pluginHostRunsSavedScripts(host, vault.groupConfigs, vault.snippets) : false,
|
||||
claimed: false,
|
||||
};
|
||||
current.current = entry; setSelectedIds([]); setBusy(false); setError(false); responding.current = false;
|
||||
const defaultRemember = prompt.request.kind === 'network.stream.connectViaHost'
|
||||
&& 'durable' in prompt.request
|
||||
&& prompt.request.durable === true;
|
||||
current.current = entry; setSelectedIds([]); setRemember(defaultRemember); setBusy(false); setError(false); responding.current = false;
|
||||
if (prompt.request.kind === 'vault.requestConnect' && prompt.permissionMode === 'allow') {
|
||||
setReview(null);
|
||||
void bridge.respondPluginInteraction?.({ requestId: prompt.requestId, actionToken: prompt.actionToken,
|
||||
@@ -168,7 +220,7 @@ export function usePluginHostActions() {
|
||||
};
|
||||
}, [execute, fail, getVault]);
|
||||
|
||||
const respond = useCallback(async (action: 'cancel' | 'submit', draft?: PluginHostDraftFields) => {
|
||||
const respond = useCallback(async (action: 'cancel' | 'submit', draft?: PluginHostDraftFields, rememberOverride?: boolean) => {
|
||||
const entry = current.current;
|
||||
if (!entry || responding.current || (action === 'cancel' && entry.claimed)) return;
|
||||
responding.current = true; setBusy(true); setError(false);
|
||||
@@ -181,17 +233,24 @@ export function usePluginHostActions() {
|
||||
resources.current.resolve(id, revision);
|
||||
return resources.current.metadata(id);
|
||||
}) : undefined;
|
||||
const includeRemember = action === 'submit' && (
|
||||
request.kind === 'network.stream.connectViaHost'
|
||||
|| request.kind === 'network.stream.confirm'
|
||||
|| request.kind === 'network.stream.tlsConfirm'
|
||||
);
|
||||
const effectiveRemember = rememberOverride ?? remember;
|
||||
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); }
|
||||
finally {
|
||||
if (current.current === entry && entry.prompt.phase === 'request') { responding.current = false; setBusy(false); }
|
||||
}
|
||||
}, [assertCurrent, fail, selectedIds]);
|
||||
}, [assertCurrent, fail, remember, selectedIds]);
|
||||
|
||||
return { review, selectedIds, setSelectedIds, busy, error, respond };
|
||||
return { review, selectedIds, setSelectedIds, remember, setRemember, busy, error, respond };
|
||||
}
|
||||
@@ -1,12 +1,15 @@
|
||||
import { useEffect, useMemo, useRef, useSyncExternalStore } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from 'react';
|
||||
import { useI18n } from '../i18n/I18nProvider';
|
||||
import { toast } from '../../components/ui/toast';
|
||||
import { collectSidePanelPanes, isPluginSidePanelTool, type SidePanelLayout } from '../../domain/sidePanelLayout';
|
||||
import { activeTabStore, useActiveTabId } from './activeTabStore';
|
||||
import { activeTabStore } from './activeTabStore';
|
||||
import { getSidePanelLiveSnapshot, subscribeSidePanelLiveSnapshot } from './sidePanelLiveStore';
|
||||
import { usePluginContributions } from './usePluginContributions';
|
||||
import { OPEN_PLUGIN_VIEW_EVENT, type OpenPluginViewDetail } from './usePluginViewLifecycle';
|
||||
|
||||
const noopSubscribe = () => () => {};
|
||||
const getNullSnapshot = () => null;
|
||||
|
||||
export const OPEN_PLUGIN_TERMINAL_SIDEBAR_EVENT = 'netcatty:open-plugin-terminal-sidebar';
|
||||
export const PLUGIN_TERMINAL_SIDEBAR_CONTEXT = Object.freeze({ 'netcatty.surface': 'terminal-sidebar' });
|
||||
/** Required production view-context projection, not a plugin-facing API. */
|
||||
@@ -42,16 +45,87 @@ export function usePluginTerminalSidebar(host: {
|
||||
withdraw(tabId: string, paneId: string, tool: `plugin-view:${string}`): void;
|
||||
}) {
|
||||
const { locale, t } = useI18n();
|
||||
const activeTabId = useActiveTabId();
|
||||
const hostRef = useRef(host);
|
||||
hostRef.current = host;
|
||||
const query = useMemo(() => ({ locale, context: PLUGIN_TERMINAL_SIDEBAR_CONTEXT }), [locale]);
|
||||
const {
|
||||
available,
|
||||
loading,
|
||||
error,
|
||||
snapshot,
|
||||
refresh,
|
||||
executeCommand,
|
||||
updateSetting,
|
||||
resetSetting,
|
||||
selectSettingPath,
|
||||
setEnvironment,
|
||||
onViewClosed,
|
||||
} = usePluginContributions(query);
|
||||
const stableContributions = useMemo(
|
||||
() => ({
|
||||
available,
|
||||
loading,
|
||||
error,
|
||||
snapshot,
|
||||
refresh,
|
||||
executeCommand,
|
||||
updateSetting,
|
||||
resetSetting,
|
||||
selectSettingPath,
|
||||
setEnvironment,
|
||||
onViewClosed,
|
||||
}),
|
||||
[
|
||||
available,
|
||||
loading,
|
||||
error,
|
||||
snapshot,
|
||||
refresh,
|
||||
executeCommand,
|
||||
updateSetting,
|
||||
resetSetting,
|
||||
selectSettingPath,
|
||||
setEnvironment,
|
||||
onViewClosed,
|
||||
],
|
||||
);
|
||||
const pages = useMemo(() => collectPluginTerminalSidebarPages(snapshot.plugins), [snapshot.plugins]);
|
||||
const hasPages = pages.length > 0;
|
||||
// Gate external store subscriptions via no-op subscribe/snapshot guards rather
|
||||
// than conditional hook calls so Rules of Hooks stay intact when pages toggle 0 <-> 1+.
|
||||
const subscribeActiveTab = useCallback(
|
||||
(listener: () => void) => (hasPages ? activeTabStore.subscribe(listener) : noopSubscribe()),
|
||||
[hasPages],
|
||||
);
|
||||
const getActiveTabSnapshot = useCallback(
|
||||
() => (hasPages ? activeTabStore.getActiveTabId() : null),
|
||||
[hasPages],
|
||||
);
|
||||
const activeTabId = useSyncExternalStore(
|
||||
subscribeActiveTab,
|
||||
getActiveTabSnapshot,
|
||||
getNullSnapshot,
|
||||
);
|
||||
// Follow workspace focus without subscribing the whole sidebar to cwd/title
|
||||
// or forwarding the host's live session DTO to a plugin.
|
||||
useSyncExternalStore((listener) => subscribeSidePanelLiveSnapshot(true, listener),
|
||||
() => getSidePanelLiveSnapshot(true).focusedSessionId, () => null);
|
||||
const hostRef = useRef(host); hostRef.current = host;
|
||||
const contributions = usePluginContributions({ locale, context: PLUGIN_TERMINAL_SIDEBAR_CONTEXT });
|
||||
const pages = useMemo(() => collectPluginTerminalSidebarPages(contributions.snapshot.plugins), [contributions.snapshot.plugins]);
|
||||
const sessionId = activeTabId && host.isTerminalTab(activeTabId) ? host.getSession() : null;
|
||||
const subscribeFocusedSession = useCallback(
|
||||
(listener: () => void) => subscribeSidePanelLiveSnapshot(hasPages, listener),
|
||||
[hasPages],
|
||||
);
|
||||
const getFocusedSessionSnapshot = useCallback(
|
||||
() => (hasPages ? getSidePanelLiveSnapshot(true).focusedSessionId : null),
|
||||
[hasPages],
|
||||
);
|
||||
useSyncExternalStore(
|
||||
subscribeFocusedSession,
|
||||
getFocusedSessionSnapshot,
|
||||
getNullSnapshot,
|
||||
);
|
||||
const sessionId = hasPages && activeTabId && hostRef.current.isTerminalTab(activeTabId)
|
||||
? hostRef.current.getSession()
|
||||
: null;
|
||||
useEffect(() => {
|
||||
if (!hasPages) return;
|
||||
const open = (event: Event) => {
|
||||
const detail = (event as CustomEvent<OpenPluginViewDetail & { sessionId?: string }>).detail;
|
||||
const page = pages.find((item) => item.viewId === detail?.viewId);
|
||||
@@ -67,13 +141,17 @@ export function usePluginTerminalSidebar(host: {
|
||||
window.addEventListener(OPEN_PLUGIN_TERMINAL_SIDEBAR_EVENT, open);
|
||||
window.addEventListener(OPEN_PLUGIN_VIEW_EVENT, open);
|
||||
return () => { window.removeEventListener(OPEN_PLUGIN_TERMINAL_SIDEBAR_EVENT, open); window.removeEventListener(OPEN_PLUGIN_VIEW_EVENT, open); };
|
||||
}, [pages, t]);
|
||||
}, [hasPages, pages, t]);
|
||||
const { layouts } = host;
|
||||
useEffect(() => {
|
||||
if (contributions.loading) return;
|
||||
if (loading) return;
|
||||
const allowed = new Set(pages.map((page) => page.tool));
|
||||
for (const [tabId, layout] of host.layouts) for (const pane of collectSidePanelPanes(layout.root)) {
|
||||
if (isPluginSidePanelTool(pane.tool) && !allowed.has(pane.tool)) host.withdraw(tabId, pane.id, pane.tool);
|
||||
for (const [tabId, layout] of layouts) for (const pane of collectSidePanelPanes(layout.root)) {
|
||||
if (isPluginSidePanelTool(pane.tool) && !allowed.has(pane.tool)) hostRef.current.withdraw(tabId, pane.id, pane.tool);
|
||||
}
|
||||
}, [contributions.loading, host, pages]);
|
||||
return { pages, contributions, tabId: activeTabId, sessionId };
|
||||
}, [layouts, loading, pages]);
|
||||
return useMemo(
|
||||
() => ({ pages, contributions: stableContributions, tabId: activeTabId, sessionId }),
|
||||
[activeTabId, pages, sessionId, stableContributions],
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useMemo, useRef } from 'react';
|
||||
import { activeTabStore, useActiveTabId } from './activeTabStore';
|
||||
import { activeTabStore, useIsVaultActive } from './activeTabStore';
|
||||
import { collectPluginVaultPages, PLUGIN_VAULT_PAGE_PREFIX, resolvePluginVaultPage } from './pluginVaultPages';
|
||||
import { usePluginContributions } from './usePluginContributions';
|
||||
import { OPEN_PLUGIN_VIEW_EVENT, type OpenPluginViewDetail } from './usePluginViewLifecycle';
|
||||
@@ -11,7 +11,7 @@ export function usePluginVaultPages({ locale, section, select }: {
|
||||
section: string;
|
||||
select(section: 'hosts' | `plugin-vault:${string}`): void;
|
||||
}) {
|
||||
const active = useActiveTabId() === 'vault';
|
||||
const active = useIsVaultActive();
|
||||
const sectionRef = useRef(section);
|
||||
const focusFrame = useRef<number | null>(null);
|
||||
sectionRef.current = section;
|
||||
|
||||
@@ -60,3 +60,313 @@ test('closing plugin overlays preserves the underlying plugin tab and closing th
|
||||
for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); }
|
||||
}
|
||||
});
|
||||
|
||||
test('tab switches do not tear down MutationObserver, call setPluginEnvironment, or re-query IPC without keybinding plugins', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
const install = (name: string, value: unknown) => {
|
||||
previous.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
|
||||
Object.defineProperty(globalThis, name, { configurable: true, writable: true, value });
|
||||
};
|
||||
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'CustomEvent']) {
|
||||
install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
|
||||
}
|
||||
let observerConstructions = 0;
|
||||
let observerDisconnects = 0;
|
||||
let computedStyleCalls = 0;
|
||||
let matchMediaCalls = 0;
|
||||
let setEnvironmentCalls = 0;
|
||||
let contributionCalls = 0;
|
||||
let contributionsSubscribed = 0;
|
||||
let contributionsUnsubscribed = 0;
|
||||
|
||||
class TrackingMutationObserver {
|
||||
constructor(callback: MutationCallback) {
|
||||
void callback;
|
||||
observerConstructions += 1;
|
||||
}
|
||||
observe() {}
|
||||
disconnect() {
|
||||
observerDisconnects += 1;
|
||||
}
|
||||
takeRecords() { return []; }
|
||||
}
|
||||
install('MutationObserver', TrackingMutationObserver);
|
||||
install('getComputedStyle', (element: Element) => {
|
||||
computedStyleCalls += 1;
|
||||
return dom.window.getComputedStyle(element);
|
||||
});
|
||||
install('requestAnimationFrame', dom.window.requestAnimationFrame.bind(dom.window));
|
||||
install('cancelAnimationFrame', dom.window.cancelAnimationFrame.bind(dom.window));
|
||||
install('IS_REACT_ACT_ENVIRONMENT', true);
|
||||
|
||||
Object.assign(dom.window, {
|
||||
matchMedia: () => {
|
||||
matchMediaCalls += 1;
|
||||
return { matches: false, addEventListener() {}, removeEventListener() {} };
|
||||
},
|
||||
netcatty: {
|
||||
async getPluginRuntimeStatus() { return { available: true }; },
|
||||
async getPluginContributions(query?: NetcattyPluginContributionQuery) {
|
||||
contributionCalls += 1;
|
||||
return {
|
||||
locale: query?.locale ?? 'en',
|
||||
plugins: [{
|
||||
id: 'example.views-only',
|
||||
version: '1.0.0',
|
||||
displayName: 'Views Only',
|
||||
description: '',
|
||||
commands: [],
|
||||
keybindings: [],
|
||||
menus: [],
|
||||
settings: [],
|
||||
views: [{ id: 'example.views-only.tab', title: 'Tab', location: 'tab', visible: true }],
|
||||
}],
|
||||
};
|
||||
},
|
||||
onPluginContributionsChanged() {
|
||||
contributionsSubscribed += 1;
|
||||
return () => { contributionsUnsubscribed += 1; };
|
||||
},
|
||||
async setPluginEnvironment() {
|
||||
setEnvironmentCalls += 1;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const { _resetSharedPluginRuntimeStatusForTests } = await import('./pluginRuntimeStatusCache');
|
||||
_resetSharedPluginRuntimeStatusForTests();
|
||||
const { default: React, act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { usePluginViewLifecycle } = await import('./usePluginViewLifecycle');
|
||||
const { activeTabStore } = await import('./activeTabStore');
|
||||
const { pluginViewTabStore } = await import('./pluginViewTabStore');
|
||||
|
||||
function Fixture({ locale, theme, tabId }: { locale: string; theme: string; tabId: string }) {
|
||||
const keybindingContext = React.useMemo(() => ({
|
||||
'netcatty.surface': 'keybinding',
|
||||
'netcatty.activeTabId': tabId,
|
||||
'terminal.sessionId': tabId,
|
||||
}), [tabId]);
|
||||
usePluginViewLifecycle({ locale, theme, keybindingContext });
|
||||
return null;
|
||||
}
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 30));
|
||||
const perform = async (action: () => void) => act(async () => { action(); await settle(); });
|
||||
|
||||
try {
|
||||
activeTabStore.setActiveTabId('term-a');
|
||||
await perform(() => root.render(React.createElement(Fixture, { locale: 'en', theme: 'dark', tabId: 'term-a' })));
|
||||
|
||||
assert.equal(observerConstructions, 1);
|
||||
assert.equal(observerDisconnects, 0);
|
||||
assert.equal(matchMediaCalls, 3);
|
||||
assert.equal(computedStyleCalls, 1);
|
||||
assert.equal(setEnvironmentCalls, 1);
|
||||
const initialContributionCalls = contributionCalls;
|
||||
const initialSubscriptions = contributionsSubscribed;
|
||||
|
||||
// Switch between terminal tabs repeatedly
|
||||
await perform(() => {
|
||||
activeTabStore.setActiveTabId('term-b');
|
||||
root.render(React.createElement(Fixture, { locale: 'en', theme: 'dark', tabId: 'term-b' }));
|
||||
});
|
||||
await perform(() => {
|
||||
activeTabStore.setActiveTabId('term-c');
|
||||
root.render(React.createElement(Fixture, { locale: 'en', theme: 'dark', tabId: 'term-c' }));
|
||||
});
|
||||
|
||||
assert.equal(observerConstructions, 1, 'tab switch must not recreate MutationObserver');
|
||||
assert.equal(observerDisconnects, 0, 'tab switch must not disconnect MutationObserver');
|
||||
assert.equal(matchMediaCalls, 3, 'tab switch must not recreate matchMedia queries');
|
||||
assert.equal(computedStyleCalls, 1, 'tab switch must not trigger getComputedStyle');
|
||||
assert.equal(setEnvironmentCalls, 1, 'tab switch must not republish plugin environment');
|
||||
assert.equal(contributionCalls, initialContributionCalls, 'tab switch must not re-query IPC when 0 keybinding plugins exist');
|
||||
assert.equal(contributionsSubscribed, initialSubscriptions, 'tab switch must not resubscribe onPluginContributionsChanged');
|
||||
assert.equal(contributionsUnsubscribed, 0);
|
||||
|
||||
// Real theme change still publishes environment without tearing down the observer
|
||||
await perform(() => root.render(React.createElement(Fixture, { locale: 'en', theme: 'light', tabId: 'term-c' })));
|
||||
assert.equal(setEnvironmentCalls, 2, 'real theme change must publish environment');
|
||||
assert.equal(observerConstructions, 1, 'theme change does not recreate MutationObserver');
|
||||
assert.equal(observerDisconnects, 0);
|
||||
} finally {
|
||||
await act(async () => root.unmount());
|
||||
pluginViewTabStore.retain(new Set());
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
_resetSharedPluginRuntimeStatusForTests();
|
||||
dom.window.close();
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('context-sensitive keybinding plugins stay fail-closed during tab switch without tearing down MutationObserver or republishing environment', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
const install = (name: string, value: unknown) => {
|
||||
previous.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
|
||||
Object.defineProperty(globalThis, name, { configurable: true, writable: true, value });
|
||||
};
|
||||
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'KeyboardEvent', 'CustomEvent']) {
|
||||
install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
|
||||
}
|
||||
|
||||
let observerConstructions = 0;
|
||||
let observerDisconnects = 0;
|
||||
let setEnvironmentCalls = 0;
|
||||
const executedCommands: Array<{ command: string; context?: Record<string, unknown> }> = [];
|
||||
const changeListeners = new Set<() => void>();
|
||||
let keybindingPluginInstalled = false;
|
||||
let deferTabB = false;
|
||||
let resolveTabB: ((snapshot: NetcattyPluginContributionSnapshot) => void) | null = null;
|
||||
|
||||
class TrackingMutationObserver {
|
||||
constructor(callback: MutationCallback) {
|
||||
void callback;
|
||||
observerConstructions += 1;
|
||||
}
|
||||
observe() {}
|
||||
disconnect() {
|
||||
observerDisconnects += 1;
|
||||
}
|
||||
takeRecords() { return []; }
|
||||
}
|
||||
install('MutationObserver', TrackingMutationObserver);
|
||||
install('getComputedStyle', dom.window.getComputedStyle.bind(dom.window));
|
||||
install('requestAnimationFrame', dom.window.requestAnimationFrame.bind(dom.window));
|
||||
install('cancelAnimationFrame', dom.window.cancelAnimationFrame.bind(dom.window));
|
||||
install('IS_REACT_ACT_ENVIRONMENT', true);
|
||||
|
||||
const buildSnapshotForContext = (context?: Record<string, unknown>): NetcattyPluginContributionSnapshot => ({
|
||||
locale: 'en',
|
||||
plugins: keybindingPluginInstalled
|
||||
? [{
|
||||
id: 'example.kb',
|
||||
version: '1.0.0',
|
||||
displayName: 'Keybinding Plugin',
|
||||
description: '',
|
||||
commands: [{ id: 'example.kb.run', title: 'Run', enabled: true }],
|
||||
keybindings: [{
|
||||
command: 'example.kb.run',
|
||||
key: 'ctrl+shift+k',
|
||||
enabled: context?.['netcatty.activeTabId'] === 'term-a',
|
||||
}],
|
||||
menus: [],
|
||||
settings: [],
|
||||
views: [],
|
||||
}]
|
||||
: [],
|
||||
});
|
||||
|
||||
Object.assign(dom.window, {
|
||||
matchMedia: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),
|
||||
netcatty: {
|
||||
async getPluginRuntimeStatus() { return { available: true }; },
|
||||
getPluginContributions(query?: NetcattyPluginContributionQuery) {
|
||||
if (deferTabB && query?.context?.['netcatty.activeTabId'] === 'term-b') {
|
||||
return new Promise<NetcattyPluginContributionSnapshot>((resolve) => {
|
||||
resolveTabB = resolve;
|
||||
});
|
||||
}
|
||||
return Promise.resolve(buildSnapshotForContext(query?.context));
|
||||
},
|
||||
onPluginContributionsChanged(callback: () => void) {
|
||||
changeListeners.add(callback);
|
||||
return () => { changeListeners.delete(callback); };
|
||||
},
|
||||
async executePluginCommand(command: string, _args?: unknown, context?: Record<string, unknown>) {
|
||||
executedCommands.push({ command, context });
|
||||
},
|
||||
async setPluginEnvironment() {
|
||||
setEnvironmentCalls += 1;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const { _resetSharedPluginRuntimeStatusForTests } = await import('./pluginRuntimeStatusCache');
|
||||
_resetSharedPluginRuntimeStatusForTests();
|
||||
const { default: React, act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { usePluginViewLifecycle } = await import('./usePluginViewLifecycle');
|
||||
const { activeTabStore } = await import('./activeTabStore');
|
||||
const { pluginViewTabStore } = await import('./pluginViewTabStore');
|
||||
|
||||
function Fixture({ tabId }: { tabId: string }) {
|
||||
const keybindingContext = React.useMemo(() => ({
|
||||
'netcatty.surface': 'keybinding',
|
||||
'netcatty.activeTabId': tabId,
|
||||
'terminal.sessionId': tabId,
|
||||
}), [tabId]);
|
||||
usePluginViewLifecycle({ locale: 'en', theme: 'dark', keybindingContext });
|
||||
return null;
|
||||
}
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 30));
|
||||
const perform = async (action: () => void) => act(async () => { action(); await settle(); });
|
||||
const dispatchShortcut = () => {
|
||||
window.dispatchEvent(new dom.window.KeyboardEvent('keydown', {
|
||||
key: 'k',
|
||||
ctrlKey: true,
|
||||
shiftKey: true,
|
||||
cancelable: true,
|
||||
}));
|
||||
};
|
||||
|
||||
try {
|
||||
activeTabStore.setActiveTabId('term-a');
|
||||
await perform(() => root.render(React.createElement(Fixture, { tabId: 'term-a' })));
|
||||
assert.equal(observerConstructions, 1);
|
||||
assert.equal(setEnvironmentCalls, 1);
|
||||
|
||||
// Install keybinding plugin and notify contributions changed
|
||||
keybindingPluginInstalled = true;
|
||||
await perform(() => {
|
||||
for (const listener of changeListeners) listener();
|
||||
});
|
||||
|
||||
// Shortcut fires on term-a with full activeTabId/sessionId context
|
||||
await perform(dispatchShortcut);
|
||||
assert.equal(executedCommands.length, 1);
|
||||
assert.equal(executedCommands[0]?.command, 'example.kb.run');
|
||||
assert.equal(executedCommands[0]?.context?.['netcatty.activeTabId'], 'term-a');
|
||||
assert.equal(executedCommands[0]?.context?.['terminal.sessionId'], 'term-a');
|
||||
|
||||
// Switch to term-b with in-flight contribution query
|
||||
deferTabB = true;
|
||||
await perform(() => {
|
||||
activeTabStore.setActiveTabId('term-b');
|
||||
root.render(React.createElement(Fixture, { tabId: 'term-b' }));
|
||||
});
|
||||
|
||||
// While term-b query is pending, stale term-a keybinding MUST NOT fire (fail-closed)
|
||||
await perform(dispatchShortcut);
|
||||
assert.equal(executedCommands.length, 1, 'stale Tab A keybinding must not fire while Tab B query is in flight');
|
||||
assert.equal(observerConstructions, 1, 'context-sensitive reload must not recreate MutationObserver');
|
||||
assert.equal(observerDisconnects, 0, 'context-sensitive reload must not disconnect MutationObserver');
|
||||
assert.equal(setEnvironmentCalls, 1, 'context-sensitive reload must not republish plugin environment');
|
||||
|
||||
// Resolve term-b query (keybinding disabled on term-b)
|
||||
assert.ok(resolveTabB, 'expected term-b query to be in flight');
|
||||
await perform(() => resolveTabB?.(buildSnapshotForContext({ 'netcatty.activeTabId': 'term-b' })));
|
||||
await perform(dispatchShortcut);
|
||||
assert.equal(executedCommands.length, 1, 'disabled Tab B keybinding must remain inactive');
|
||||
assert.equal(observerDisconnects, 0);
|
||||
assert.equal(setEnvironmentCalls, 1);
|
||||
} finally {
|
||||
await act(async () => root.unmount());
|
||||
pluginViewTabStore.retain(new Set());
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
_resetSharedPluginRuntimeStatusForTests();
|
||||
dom.window.close();
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
resolvePluginViewSnapshotSelection,
|
||||
type PluginViewSnapshotSelection,
|
||||
} from './pluginViewLifecycle';
|
||||
import { pluginViewSessions } from './pluginViewSession';
|
||||
import { closePluginViewSessionIfLoaded } from './pluginViewSessionRegistry';
|
||||
import { usePluginContributions } from './usePluginContributions';
|
||||
|
||||
export const OPEN_PLUGIN_VIEW_EVENT = 'netcatty:open-plugin-view';
|
||||
@@ -33,6 +33,16 @@ export type ResolvedPluginView = {
|
||||
view: NetcattyPluginContributionSnapshot['plugins'][number]['views'][number];
|
||||
};
|
||||
|
||||
const DEFAULT_VIEW_QUERY_CONTEXT: Readonly<Record<string, unknown>> = Object.freeze({
|
||||
'netcatty.surface': 'view',
|
||||
});
|
||||
|
||||
export function hasPluginKeybindingContributions(
|
||||
snapshot: NetcattyPluginContributionSnapshot,
|
||||
): boolean {
|
||||
return snapshot.plugins.some((plugin) => plugin.keybindings.length > 0);
|
||||
}
|
||||
|
||||
export function requestOpenPluginView(detail: OpenPluginViewDetail) {
|
||||
window.dispatchEvent(new CustomEvent(OPEN_PLUGIN_VIEW_EVENT, { detail }));
|
||||
}
|
||||
@@ -54,12 +64,22 @@ export function usePluginViewLifecycle({
|
||||
const activePluginTab = pluginViewTabs.find((tab) => tab.id === activeTabId) ?? null;
|
||||
const effectiveRequested = resolvePluginViewRequest(requested, activePluginTab);
|
||||
const viewQueryContext = useMemo(
|
||||
() => effectiveRequested?.context ?? { 'netcatty.surface': 'view' },
|
||||
() => effectiveRequested?.context ?? DEFAULT_VIEW_QUERY_CONTEXT,
|
||||
[effectiveRequested?.context],
|
||||
);
|
||||
const viewQueryContextKey = useMemo(() => JSON.stringify(viewQueryContext), [viewQueryContext]);
|
||||
const contributions = usePluginContributions({ locale, context: keybindingContext });
|
||||
const viewContributions = usePluginContributions({ locale, context: viewQueryContext });
|
||||
const keybindingQuery = useMemo(
|
||||
() => ({ locale, context: keybindingContext }),
|
||||
[locale, keybindingContext],
|
||||
);
|
||||
const viewQuery = useMemo(
|
||||
() => ({ locale, context: viewQueryContext }),
|
||||
[locale, viewQueryContext],
|
||||
);
|
||||
const contributions = usePluginContributions(keybindingQuery, {
|
||||
isContextSensitive: hasPluginKeybindingContributions,
|
||||
});
|
||||
const viewContributions = usePluginContributions(viewQuery);
|
||||
const {
|
||||
snapshot,
|
||||
executeCommand,
|
||||
@@ -88,10 +108,14 @@ export function usePluginViewLifecycle({
|
||||
: null;
|
||||
}, [effectiveRequested?.viewId, resolvedActiveView, viewContributions.loading, viewQueryContextKey]);
|
||||
|
||||
const keybindingContextRef = useRef(keybindingContext);
|
||||
keybindingContextRef.current = keybindingContext;
|
||||
|
||||
useEffect(() => {
|
||||
const bindings = snapshot.plugins.flatMap((plugin) => plugin.keybindings)
|
||||
.filter((binding) => binding.enabled)
|
||||
.sort((left, right) => `${left.command}:${left.key}`.localeCompare(`${right.command}:${right.key}`));
|
||||
if (bindings.length === 0) return;
|
||||
const platformKey = resolvePluginShortcutPlatform(navigator.platform);
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.defaultPrevented || event.isComposing || isPluginShortcutEditableEvent(event)) return;
|
||||
@@ -103,11 +127,11 @@ export function usePluginViewLifecycle({
|
||||
});
|
||||
if (!binding) return;
|
||||
event.preventDefault();
|
||||
void executeCommand(binding.command, binding.args, keybindingContext);
|
||||
void executeCommand(binding.command, binding.args, keybindingContextRef.current);
|
||||
};
|
||||
window.addEventListener('keydown', onKeyDown);
|
||||
return () => window.removeEventListener('keydown', onKeyDown);
|
||||
}, [executeCommand, keybindingContext, snapshot.plugins]);
|
||||
}, [executeCommand, snapshot.plugins]);
|
||||
|
||||
useEffect(() => {
|
||||
const listener = (event: Event) => setRequested((event as CustomEvent<OpenPluginViewDetail>).detail);
|
||||
@@ -137,13 +161,13 @@ export function usePluginViewLifecycle({
|
||||
}, [activeView, requested]);
|
||||
|
||||
useEffect(() => {
|
||||
const stop = pluginViewTabStore.onDidClose(({ tab }) => pluginViewSessions.closeView(tab.viewId));
|
||||
const stop = pluginViewTabStore.onDidClose(({ tab }) => closePluginViewSessionIfLoaded(tab.viewId));
|
||||
return () => { stop(); };
|
||||
}, []);
|
||||
|
||||
const close = useCallback(async () => {
|
||||
setRequested(null);
|
||||
if (activeView) pluginViewSessions.closeView(activeView.view.id);
|
||||
if (activeView) closePluginViewSessionIfLoaded(activeView.view.id);
|
||||
// An overlay can be requested while a different plugin tab stays active.
|
||||
// Dismissing that overlay must not close the tab underneath it.
|
||||
if (activeView?.view.location === 'tab' && activePluginTab?.viewId === activeView.view.id) {
|
||||
@@ -151,40 +175,74 @@ export function usePluginViewLifecycle({
|
||||
}
|
||||
}, [activePluginTab, activeView]);
|
||||
|
||||
const runtimeAvailable = contributions.available;
|
||||
const environmentStateRef = useRef({
|
||||
locale,
|
||||
theme,
|
||||
suppliedThemeTokens,
|
||||
setEnvironment,
|
||||
});
|
||||
environmentStateRef.current = {
|
||||
locale,
|
||||
theme,
|
||||
suppliedThemeTokens,
|
||||
setEnvironment,
|
||||
};
|
||||
const environmentPublisherRef = useRef<{ publish: () => void } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!contributions.available) return;
|
||||
if (!runtimeAvailable) {
|
||||
environmentPublisherRef.current = null;
|
||||
return;
|
||||
}
|
||||
const reducedMotionQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
|
||||
const forcedColorsQuery = window.matchMedia('(forced-colors: active)');
|
||||
const contrastQuery = window.matchMedia('(prefers-contrast: more)');
|
||||
let frame = 0;
|
||||
const cancelPendingPublish = () => {
|
||||
if (frame) {
|
||||
cancelAnimationFrame(frame);
|
||||
frame = 0;
|
||||
}
|
||||
};
|
||||
const publish = () => {
|
||||
frame = 0;
|
||||
const styles = suppliedThemeTokens ? null : getComputedStyle(document.documentElement);
|
||||
const themeTokens = suppliedThemeTokens ?? Object.fromEntries(PLUGIN_THEME_TOKEN_NAMES
|
||||
cancelPendingPublish();
|
||||
const current = environmentStateRef.current;
|
||||
const styles = current.suppliedThemeTokens ? null : getComputedStyle(document.documentElement);
|
||||
const themeTokens = current.suppliedThemeTokens ?? Object.fromEntries(PLUGIN_THEME_TOKEN_NAMES
|
||||
.map((name) => [name, styles?.getPropertyValue(name).trim() ?? '']));
|
||||
void setEnvironment({
|
||||
locale,
|
||||
theme,
|
||||
void current.setEnvironment({
|
||||
locale: current.locale,
|
||||
theme: current.theme,
|
||||
reducedMotion: reducedMotionQuery.matches,
|
||||
highContrast: forcedColorsQuery.matches || contrastQuery.matches,
|
||||
themeTokens,
|
||||
}).catch(() => {});
|
||||
};
|
||||
const schedulePublish = () => {
|
||||
if (frame) cancelAnimationFrame(frame);
|
||||
frame = requestAnimationFrame(publish);
|
||||
cancelPendingPublish();
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = 0;
|
||||
publish();
|
||||
});
|
||||
};
|
||||
environmentPublisherRef.current = { publish };
|
||||
const queries = [reducedMotionQuery, forcedColorsQuery, contrastQuery];
|
||||
for (const query of queries) query.addEventListener?.('change', schedulePublish);
|
||||
const observer = new MutationObserver(schedulePublish);
|
||||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'style'] });
|
||||
publish();
|
||||
return () => {
|
||||
if (frame) cancelAnimationFrame(frame);
|
||||
environmentPublisherRef.current = null;
|
||||
cancelPendingPublish();
|
||||
observer.disconnect();
|
||||
for (const query of queries) query.removeEventListener?.('change', schedulePublish);
|
||||
};
|
||||
}, [contributions.available, locale, setEnvironment, suppliedThemeTokens, theme]);
|
||||
}, [runtimeAvailable]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!runtimeAvailable) return;
|
||||
environmentPublisherRef.current?.publish();
|
||||
}, [runtimeAvailable, locale, setEnvironment, suppliedThemeTokens, theme]);
|
||||
|
||||
return {
|
||||
activeView,
|
||||
|
||||
@@ -187,13 +187,13 @@ test("reconnect is requested for auto-start and auto-reconnect rules only", () =
|
||||
assert.equal(isPortForwardingReconnectRequested([], "rule-1"), false);
|
||||
});
|
||||
|
||||
test("network recovery starts an exhausted auto-start rule through the real service path", async (t) => {
|
||||
test("network recovery nudges a long-backoff auto-start rule immediately and ignores auth-failed or stopped rules", async (t) => {
|
||||
const env = installStorage();
|
||||
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
|
||||
let onlineListener: (() => void) | undefined;
|
||||
const startedRuleIds: string[] = [];
|
||||
const exhaustedStartResult = deferred<{ success: boolean; error: string }>();
|
||||
let preparingExhaustedRule = true;
|
||||
const backoffStartResult = deferred<{ success: boolean; error: string }>();
|
||||
let preparingBackoffRule = true;
|
||||
const backendSnapshot = deferred<[]>();
|
||||
let snapshotCalls = 0;
|
||||
const target = {
|
||||
@@ -214,8 +214,11 @@ test("network recovery starts an exhausted auto-start rule through the real serv
|
||||
},
|
||||
startPortForward: async ({ ruleId }: { ruleId: string }) => {
|
||||
startedRuleIds.push(ruleId);
|
||||
if (ruleId === "exhausted" && preparingExhaustedRule) {
|
||||
return exhaustedStartResult.promise;
|
||||
if (ruleId === "backing-off" && preparingBackoffRule) {
|
||||
return backoffStartResult.promise;
|
||||
}
|
||||
if (ruleId === "auth-failed") {
|
||||
return { success: false, error: "All configured authentication methods failed" };
|
||||
}
|
||||
return { success: true };
|
||||
},
|
||||
@@ -226,7 +229,8 @@ test("network recovery starts an exhausted auto-start rule through the real serv
|
||||
});
|
||||
t.after(async () => {
|
||||
await Promise.all([
|
||||
stopAndCleanupRuleAndWait("exhausted"),
|
||||
stopAndCleanupRuleAndWait("backing-off"),
|
||||
stopAndCleanupRuleAndWait("auth-failed"),
|
||||
stopAndCleanupRuleAndWait("already-active"),
|
||||
]);
|
||||
setReconnectCallback(null);
|
||||
@@ -236,14 +240,19 @@ test("network recovery starts an exhausted auto-start rule through the real serv
|
||||
});
|
||||
|
||||
const rules = [
|
||||
rule({ id: "exhausted", autoStart: true }),
|
||||
rule({ id: "backing-off", autoStart: true }),
|
||||
rule({ id: "already-active", autoStart: true }),
|
||||
rule({ id: "auth-failed", autoStart: true }),
|
||||
rule({ id: "manually-stopped", autoStart: true, status: "inactive" }),
|
||||
rule({ id: "manual", autoStart: false }),
|
||||
];
|
||||
env.storage.setItem(STORAGE_KEY_PORT_FORWARDING, JSON.stringify(rules));
|
||||
setReconnectCallback(async () => ({ success: true }));
|
||||
const exhaustedStart = startPortForward(
|
||||
setReconnectCallback(async (ruleId, onStatusChange) => {
|
||||
const targetRule = rules.find((item) => item.id === ruleId)!;
|
||||
return startPortForward(targetRule, host(), [host()], [], [], onStatusChange, true);
|
||||
});
|
||||
|
||||
const backoffStart = startPortForward(
|
||||
rules[0]!,
|
||||
host(),
|
||||
[host()],
|
||||
@@ -252,22 +261,17 @@ test("network recovery starts an exhausted auto-start rule through the real serv
|
||||
() => undefined,
|
||||
true,
|
||||
);
|
||||
const exhaustedConnection = getActiveConnection("exhausted");
|
||||
assert.ok(exhaustedConnection);
|
||||
exhaustedConnection.reconnectAttempts = 5;
|
||||
exhaustedStartResult.resolve({ success: false, error: "offline socket" });
|
||||
await exhaustedStart;
|
||||
preparingExhaustedRule = false;
|
||||
const backoffConnection = getActiveConnection("backing-off");
|
||||
assert.ok(backoffConnection);
|
||||
backoffConnection.reconnectAttempts = 5;
|
||||
backoffStartResult.resolve({ success: false, error: "offline socket" });
|
||||
await backoffStart;
|
||||
assert.equal(backoffConnection.reconnectAttempts, 6);
|
||||
assert.ok(backoffConnection.reconnectTimerCallback);
|
||||
preparingBackoffRule = false;
|
||||
|
||||
await startPortForward(
|
||||
rules[1]!,
|
||||
host(),
|
||||
[host()],
|
||||
[],
|
||||
[],
|
||||
() => undefined,
|
||||
true,
|
||||
);
|
||||
await startPortForward(rules[1]!, host(), [host()], [], [], () => undefined, true);
|
||||
await startPortForward(rules[2]!, host(), [host()], [], [], () => undefined, true);
|
||||
startedRuleIds.length = 0;
|
||||
|
||||
const unsubscribe = subscribeToPortForwardingNetworkRecovery(target, (recoveryRuleIds) =>
|
||||
@@ -282,13 +286,13 @@ test("network recovery starts an exhausted auto-start rule through the real serv
|
||||
assert.equal(snapshotCalls, 1);
|
||||
backendSnapshot.resolve([]);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
assert.deepEqual(startedRuleIds, ["exhausted"]);
|
||||
assert.deepEqual(startedRuleIds, ["backing-off"]);
|
||||
|
||||
unsubscribe();
|
||||
assert.equal(onlineListener, undefined);
|
||||
});
|
||||
|
||||
test("network recovery refreshes retries for a connecting final attempt", async (t) => {
|
||||
test("network recovery refreshes retries for a connecting retry attempt", async (t) => {
|
||||
const env = installStorage();
|
||||
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
|
||||
const startResult = deferred<{ success: boolean; error: string }>();
|
||||
@@ -350,17 +354,18 @@ test("network recovery refreshes retries for a connecting final attempt", async
|
||||
startResult.resolve({ success: false, error: "offline socket" });
|
||||
await pendingStart;
|
||||
assert.equal(connection.reconnectAttempts, 1);
|
||||
assert.equal(connection.error, "Reconnecting (attempt #1, next in 3s)...");
|
||||
assert.ok(connection.reconnectTimerCallback);
|
||||
});
|
||||
|
||||
test("manual stop cancels an exhausted recovery while backend sync is pending", async (t) => {
|
||||
test("manual stop cancels a pending backoff recovery while backend sync is pending", async (t) => {
|
||||
const env = installStorage();
|
||||
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
|
||||
const exhaustedStartResult = deferred<{ success: boolean; error: string }>();
|
||||
const backoffStartResult = deferred<{ success: boolean; error: string }>();
|
||||
const backendSnapshot = deferred<[]>();
|
||||
const stopResult = deferred<{ stopped: number; failed: number; errors: string[] }>();
|
||||
const startedRuleIds: string[] = [];
|
||||
let preparingExhaustedRule = true;
|
||||
let preparingBackoffRule = true;
|
||||
let onlineListener: (() => void) | undefined;
|
||||
const target = {
|
||||
addEventListener(type: string, listener: () => void) {
|
||||
@@ -377,7 +382,7 @@ test("manual stop cancels an exhausted recovery while backend sync is pending",
|
||||
listPortForwards: async () => backendSnapshot.promise,
|
||||
startPortForward: async ({ ruleId }: { ruleId: string }) => {
|
||||
startedRuleIds.push(ruleId);
|
||||
if (preparingExhaustedRule) return exhaustedStartResult.promise;
|
||||
if (preparingBackoffRule) return backoffStartResult.promise;
|
||||
return { success: true };
|
||||
},
|
||||
onPortForwardStatus: () => () => undefined,
|
||||
@@ -385,9 +390,11 @@ test("manual stop cancels an exhausted recovery while backend sync is pending",
|
||||
},
|
||||
},
|
||||
});
|
||||
const exhaustedRule = rule({ id: "exhausted-then-stopped", autoStart: true });
|
||||
env.storage.setItem(STORAGE_KEY_PORT_FORWARDING, JSON.stringify([exhaustedRule]));
|
||||
setReconnectCallback(async () => ({ success: true }));
|
||||
const backoffRule = rule({ id: "backoff-then-stopped", autoStart: true });
|
||||
env.storage.setItem(STORAGE_KEY_PORT_FORWARDING, JSON.stringify([backoffRule]));
|
||||
setReconnectCallback(async (ruleId, onStatusChange) => {
|
||||
return startPortForward(backoffRule, host(), [host()], [], [], onStatusChange, true);
|
||||
});
|
||||
const unsubscribe = subscribeToPortForwardingNetworkRecovery(target, (recoveryRuleIds) =>
|
||||
runPortForwardingAutoStart({
|
||||
...autoStartOptions([host()]),
|
||||
@@ -397,14 +404,14 @@ test("manual stop cancels an exhausted recovery while backend sync is pending",
|
||||
t.after(async () => {
|
||||
unsubscribe();
|
||||
setReconnectCallback(null);
|
||||
await stopAndCleanupRuleAndWait(exhaustedRule.id);
|
||||
await stopAndCleanupRuleAndWait(backoffRule.id);
|
||||
env.restore();
|
||||
if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow);
|
||||
else Reflect.deleteProperty(globalThis, "window");
|
||||
});
|
||||
|
||||
const exhaustedStart = startPortForward(
|
||||
exhaustedRule,
|
||||
const backoffStart = startPortForward(
|
||||
backoffRule,
|
||||
host(),
|
||||
[host()],
|
||||
[],
|
||||
@@ -412,17 +419,17 @@ test("manual stop cancels an exhausted recovery while backend sync is pending",
|
||||
() => undefined,
|
||||
true,
|
||||
);
|
||||
const connection = getActiveConnection(exhaustedRule.id);
|
||||
const connection = getActiveConnection(backoffRule.id);
|
||||
assert.ok(connection);
|
||||
connection.reconnectAttempts = 5;
|
||||
exhaustedStartResult.resolve({ success: false, error: "offline socket" });
|
||||
await exhaustedStart;
|
||||
preparingExhaustedRule = false;
|
||||
backoffStartResult.resolve({ success: false, error: "offline socket" });
|
||||
await backoffStart;
|
||||
preparingBackoffRule = false;
|
||||
startedRuleIds.length = 0;
|
||||
|
||||
onlineListener?.();
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
const manualStop = stopPortForward(exhaustedRule.id, () => undefined);
|
||||
const manualStop = stopPortForward(backoffRule.id, () => undefined);
|
||||
backendSnapshot.resolve([]);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import { localStorageAdapter } from "../../infrastructure/persistence/localStora
|
||||
import {
|
||||
getActiveConnection,
|
||||
isReconnectRecoveryEligible,
|
||||
nudgePendingReconnect,
|
||||
resetReconnectAttempts,
|
||||
setReconnectCallback,
|
||||
startPortForward,
|
||||
@@ -214,12 +215,21 @@ export const runPortForwardingAutoStart = async ({
|
||||
const rules = localStorageAdapter.read<PortForwardingRule[]>(
|
||||
STORAGE_KEY_PORT_FORWARDING,
|
||||
) ?? [];
|
||||
|
||||
if (recoveryRuleIds) {
|
||||
// Nudge rules waiting on a long backoff timer so they retry immediately
|
||||
// after the network comes back online instead of waiting up to 60s.
|
||||
for (const rule of rules) {
|
||||
if (!recoveryRuleIds.has(rule.id)) continue;
|
||||
if (!isPortForwardingAutoReconnectEnabled(rule)) continue;
|
||||
if (!isReconnectRecoveryEligible(rule.id)) continue;
|
||||
nudgePendingReconnect(rule.id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const autoStartRules = rules.filter((rule) =>
|
||||
recoveryRuleIds
|
||||
? recoveryRuleIds.has(rule.id) &&
|
||||
isReconnectRecoveryEligible(rule.id) &&
|
||||
shouldRestartPortForwardingReconnectRule(rule, getActiveConnection(rule.id))
|
||||
: shouldStartPortForwardingAutoStartRule(rule, getActiveConnection(rule.id)),
|
||||
shouldStartPortForwardingAutoStartRule(rule, getActiveConnection(rule.id)),
|
||||
);
|
||||
|
||||
if (autoStartRules.length === 0) return;
|
||||
@@ -445,9 +455,9 @@ export const usePortForwardingAutoStart = ({
|
||||
runAutoStart,
|
||||
]);
|
||||
|
||||
// A local outage can consume all bounded SSH retries. Only an explicit
|
||||
// network recovery event starts a fresh retry cycle, so an unreachable
|
||||
// server still stops retrying after the existing limit.
|
||||
// When the OS reports network restoration, reset backoff counters and nudge
|
||||
// any pending backoff timers so tunnels recover immediately instead of
|
||||
// waiting out a long (up to 60s) retry interval.
|
||||
useEffect(() => {
|
||||
if (!enabled || !isVaultInitialized || typeof window === "undefined") return;
|
||||
return subscribeToPortForwardingNetworkRecovery(window, runAutoStart);
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import React, { act } from "react";
|
||||
import { create, type ReactTestRenderer } from "react-test-renderer";
|
||||
import { netcattyBridge } from "../../infrastructure/services/netcattyBridge";
|
||||
import {
|
||||
resetPortForwardingStateForTests,
|
||||
shouldRunPortForwardingHeartbeat,
|
||||
usePortForwardingState,
|
||||
type UsePortForwardingStateResult,
|
||||
} from "./usePortForwardingState";
|
||||
|
||||
function installDomGlobals() {
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
const setGlobal = (key: string, value: unknown) => {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
};
|
||||
|
||||
const backing = new Map<string, string>();
|
||||
const storage: Storage = {
|
||||
get length() { return backing.size; },
|
||||
clear() { backing.clear(); },
|
||||
getItem(key) { return backing.get(key) ?? null; },
|
||||
key(index) { return Array.from(backing.keys())[index] ?? null; },
|
||||
removeItem(key) { backing.delete(key); },
|
||||
setItem(key, value) { backing.set(key, value); },
|
||||
};
|
||||
|
||||
const visibilityListeners = new Set<() => void>();
|
||||
let visibilityState: DocumentVisibilityState = "visible";
|
||||
|
||||
setGlobal("IS_REACT_ACT_ENVIRONMENT", true);
|
||||
setGlobal("localStorage", storage);
|
||||
setGlobal("window", {
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
dispatchEvent() { return true; },
|
||||
});
|
||||
setGlobal("document", {
|
||||
get visibilityState() { return visibilityState; },
|
||||
get hidden() { return visibilityState === "hidden"; },
|
||||
addEventListener(type: string, listener: () => void) {
|
||||
if (type === "visibilitychange") visibilityListeners.add(listener);
|
||||
},
|
||||
removeEventListener(type: string, listener: () => void) {
|
||||
if (type === "visibilitychange") visibilityListeners.delete(listener);
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
visibilityListeners,
|
||||
async setVisibility(next: DocumentVisibilityState) {
|
||||
visibilityState = next;
|
||||
await act(async () => {
|
||||
for (const listener of [...visibilityListeners]) listener();
|
||||
});
|
||||
},
|
||||
restore() {
|
||||
for (const [key, desc] of previous.entries()) {
|
||||
if (desc) Object.defineProperty(globalThis, key, desc);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("usePortForwardingState disarms heartbeat with 0 rules, arms dynamically on rule add, pauses when hidden, and reconciles on visible", async (t) => {
|
||||
t.mock.timers.enable({ apis: ["setTimeout", "setInterval", "Date"], now: 10_000 });
|
||||
const env = installDomGlobals();
|
||||
resetPortForwardingStateForTests();
|
||||
|
||||
let listCalls = 0;
|
||||
let failList = false;
|
||||
|
||||
t.mock.method(netcattyBridge, "get", () => ({
|
||||
listPortForwards: async () => {
|
||||
listCalls += 1;
|
||||
if (failList) throw new Error("backend unavailable");
|
||||
return [];
|
||||
},
|
||||
subscribePortForwardRuntime: async () => ({ epoch: "e1", revision: 0, tunnels: [] }),
|
||||
onPortForwardRuntime: () => () => undefined,
|
||||
unsubscribePortForwardRuntime: async () => undefined,
|
||||
stopPortForwardByRuleId: async () => ({ stopped: 0, failed: 0, errors: [] }),
|
||||
}));
|
||||
|
||||
let api!: UsePortForwardingStateResult;
|
||||
function Probe() {
|
||||
api = usePortForwardingState();
|
||||
return null;
|
||||
}
|
||||
|
||||
let root: ReactTestRenderer | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
root = create(React.createElement(Probe));
|
||||
});
|
||||
|
||||
// Startup init + runtime subscription run initial syncs, after which
|
||||
// snapshotAvailable is true and globalRules is empty -> heartbeat disarms.
|
||||
const baselineCalls = listCalls;
|
||||
assert.equal(shouldRunPortForwardingHeartbeat(), false);
|
||||
|
||||
await act(async () => t.mock.timers.tick(60_000));
|
||||
assert.equal(listCalls, baselineCalls, "0 rules + healthy snapshot must not run 4s heartbeat");
|
||||
|
||||
// Dynamically adding a rule arms the 4s heartbeat without remounting.
|
||||
let createdId = "";
|
||||
await act(async () => {
|
||||
const created = api.addRule({
|
||||
label: "Web",
|
||||
type: "local",
|
||||
localPort: 8080,
|
||||
remoteHost: "127.0.0.1",
|
||||
remotePort: 80,
|
||||
hostId: "host-1",
|
||||
bindAddress: "127.0.0.1",
|
||||
});
|
||||
createdId = created.id;
|
||||
});
|
||||
assert.equal(shouldRunPortForwardingHeartbeat(), true);
|
||||
|
||||
await act(async () => t.mock.timers.tick(4_000));
|
||||
assert.equal(listCalls, baselineCalls + 1, "heartbeat should fire after rule is added");
|
||||
|
||||
// Hiding the document pauses the 4s heartbeat.
|
||||
await env.setVisibility("hidden");
|
||||
assert.equal(shouldRunPortForwardingHeartbeat(), false);
|
||||
const hiddenCalls = listCalls;
|
||||
await act(async () => t.mock.timers.tick(60_000));
|
||||
assert.equal(listCalls, hiddenCalls, "hidden document must not fire heartbeat ticks");
|
||||
|
||||
// Returning to visible triggers immediate reconcileWithBackend() and resumes 4s ticks.
|
||||
await env.setVisibility("visible");
|
||||
assert.equal(listCalls, hiddenCalls + 1, "returning to visible must immediately reconcile");
|
||||
await act(async () => t.mock.timers.tick(4_000));
|
||||
assert.equal(listCalls, hiddenCalls + 2, "4s heartbeat must resume after returning to visible");
|
||||
|
||||
// Deleting the last rule dynamically disarms the heartbeat again.
|
||||
await act(async () => {
|
||||
api.deleteRule(createdId);
|
||||
});
|
||||
assert.equal(shouldRunPortForwardingHeartbeat(), false);
|
||||
const afterDeleteCalls = listCalls;
|
||||
await act(async () => t.mock.timers.tick(60_000));
|
||||
assert.equal(listCalls, afterDeleteCalls, "deleting last rule must disarm heartbeat");
|
||||
|
||||
// Snapshot unavailable keeps heartbeat armed even with 0 rules until recovery.
|
||||
await act(async () => { root?.unmount(); });
|
||||
resetPortForwardingStateForTests();
|
||||
failList = true;
|
||||
listCalls = 0;
|
||||
|
||||
await act(async () => {
|
||||
root = create(React.createElement(Probe));
|
||||
});
|
||||
assert.equal(shouldRunPortForwardingHeartbeat(), true, "unavailable snapshot must keep heartbeat armed");
|
||||
const unavailableBaseline = listCalls;
|
||||
|
||||
failList = false;
|
||||
await act(async () => t.mock.timers.tick(4_000));
|
||||
assert.equal(listCalls, unavailableBaseline + 1, "recovery heartbeat tick must fire when snapshot was unavailable");
|
||||
assert.equal(shouldRunPortForwardingHeartbeat(), false, "heartbeat must disarm once snapshot recovers with 0 rules");
|
||||
await act(async () => t.mock.timers.tick(60_000));
|
||||
assert.equal(listCalls, unavailableBaseline + 1);
|
||||
} finally {
|
||||
await act(async () => { root?.unmount(); });
|
||||
assert.equal(env.visibilityListeners.size, 0, "visibility listener must detach on unmount");
|
||||
resetPortForwardingStateForTests();
|
||||
env.restore();
|
||||
t.mock.timers.reset();
|
||||
}
|
||||
});
|
||||
@@ -43,9 +43,21 @@ let reconnectCancelListenerRefs = 0;
|
||||
let reconnectCancelCleanup: (() => void) | undefined;
|
||||
let heartbeatRefs = 0;
|
||||
let heartbeatIntervalId: ReturnType<typeof setInterval> | undefined;
|
||||
let heartbeatTickInFlight = false;
|
||||
let heartbeatVisibilityDocument: Document | null = null;
|
||||
let runtimeSubscriptionRefs = 0;
|
||||
let runtimeSubscriptionCleanup: (() => void) | undefined;
|
||||
|
||||
const HEARTBEAT_INTERVAL_MS = 4_000;
|
||||
|
||||
const isPortForwardingDocumentHidden = (): boolean => {
|
||||
if (typeof document === "undefined") return false;
|
||||
if (typeof document.visibilityState === "string") {
|
||||
return document.visibilityState === "hidden";
|
||||
}
|
||||
return document.hidden === true;
|
||||
};
|
||||
|
||||
export type { ViewMode };
|
||||
|
||||
export type SortMode = "manual" | "az" | "za" | "newest" | "oldest";
|
||||
@@ -123,6 +135,104 @@ const listeners = new Set<(rules: PortForwardingRule[]) => void>();
|
||||
// Store Actions
|
||||
const notifyListeners = () => {
|
||||
listeners.forEach((listener) => listener(globalRules));
|
||||
syncPortForwardingHeartbeatTimer();
|
||||
};
|
||||
|
||||
export const shouldRunPortForwardingHeartbeat = (): boolean => (
|
||||
heartbeatRefs > 0
|
||||
&& !isPortForwardingDocumentHidden()
|
||||
&& (globalRules.length > 0 || hasActivePortForwardRuntime() || !snapshotAvailable)
|
||||
);
|
||||
|
||||
const runPortForwardingHeartbeatTick = async (): Promise<void> => {
|
||||
if (heartbeatTickInFlight || heartbeatRefs <= 0 || isPortForwardingDocumentHidden()) {
|
||||
return;
|
||||
}
|
||||
heartbeatTickInFlight = true;
|
||||
try {
|
||||
const reconciliation = await reconcileWithBackend();
|
||||
snapshotAvailable = reconciliation.snapshotAvailable;
|
||||
if (!reconciliation.snapshotAvailable) {
|
||||
// Snapshot failure must surface as unknown/stale — never as inactive.
|
||||
applyRuntimeSnapshotProjection(new Set(), false);
|
||||
return;
|
||||
}
|
||||
// Always re-derive the visible state from the live connection map.
|
||||
// Runtime phases stay in memory only.
|
||||
const normalizedRules = normalizeRulesWithConnections(
|
||||
globalRules,
|
||||
{
|
||||
reconciledGoneRuleIds: new Set(reconciliation.gone),
|
||||
snapshotAvailable: true,
|
||||
},
|
||||
);
|
||||
if (havePortForwardingRuntimeStatesChanged(globalRules, normalizedRules)) {
|
||||
setRuntimeProjection(normalizedRules);
|
||||
} else if (hasPortForwardingRuntimePresenceChanged(reconciliation)) {
|
||||
globalRules = normalizedRules;
|
||||
notifyListeners();
|
||||
}
|
||||
} finally {
|
||||
heartbeatTickInFlight = false;
|
||||
syncPortForwardingHeartbeatTimer();
|
||||
}
|
||||
};
|
||||
|
||||
const syncPortForwardingHeartbeatTimer = (): void => {
|
||||
if (shouldRunPortForwardingHeartbeat()) {
|
||||
if (heartbeatIntervalId === undefined) {
|
||||
heartbeatIntervalId = setInterval(() => {
|
||||
void runPortForwardingHeartbeatTick();
|
||||
}, HEARTBEAT_INTERVAL_MS);
|
||||
}
|
||||
} else if (heartbeatIntervalId !== undefined) {
|
||||
clearInterval(heartbeatIntervalId);
|
||||
heartbeatIntervalId = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const handlePortForwardingVisibilityChange = (): void => {
|
||||
if (isPortForwardingDocumentHidden()) {
|
||||
syncPortForwardingHeartbeatTimer();
|
||||
return;
|
||||
}
|
||||
syncPortForwardingHeartbeatTimer();
|
||||
if (shouldRunPortForwardingHeartbeat()) {
|
||||
void runPortForwardingHeartbeatTick();
|
||||
}
|
||||
};
|
||||
|
||||
const attachPortForwardingVisibilityListener = (): void => {
|
||||
if (typeof document === "undefined" || typeof document.addEventListener !== "function") {
|
||||
return;
|
||||
}
|
||||
if (heartbeatVisibilityDocument === document) return;
|
||||
if (heartbeatVisibilityDocument && typeof heartbeatVisibilityDocument.removeEventListener === "function") {
|
||||
heartbeatVisibilityDocument.removeEventListener("visibilitychange", handlePortForwardingVisibilityChange);
|
||||
}
|
||||
document.addEventListener("visibilitychange", handlePortForwardingVisibilityChange);
|
||||
heartbeatVisibilityDocument = document;
|
||||
};
|
||||
|
||||
const detachPortForwardingVisibilityListener = (): void => {
|
||||
if (!heartbeatVisibilityDocument) return;
|
||||
if (typeof heartbeatVisibilityDocument.removeEventListener === "function") {
|
||||
heartbeatVisibilityDocument.removeEventListener("visibilitychange", handlePortForwardingVisibilityChange);
|
||||
}
|
||||
heartbeatVisibilityDocument = null;
|
||||
};
|
||||
|
||||
export const resetPortForwardingStateForTests = (): void => {
|
||||
if (heartbeatIntervalId !== undefined) {
|
||||
clearInterval(heartbeatIntervalId);
|
||||
heartbeatIntervalId = undefined;
|
||||
}
|
||||
detachPortForwardingVisibilityListener();
|
||||
heartbeatRefs = 0;
|
||||
heartbeatTickInFlight = false;
|
||||
globalRules = [];
|
||||
isInitialized = false;
|
||||
snapshotAvailable = false;
|
||||
};
|
||||
|
||||
const persistPortForwardingConfig = (rules: PortForwardingRule[]) => {
|
||||
@@ -333,6 +443,7 @@ const initializeStore = async () => {
|
||||
snapshotAvailable,
|
||||
}));
|
||||
}
|
||||
syncPortForwardingHeartbeatTimer();
|
||||
};
|
||||
|
||||
const subscribeToPortForwardRuntime = (): (() => void) => {
|
||||
@@ -367,6 +478,7 @@ const subscribeToPortForwardRuntime = (): (() => void) => {
|
||||
snapshotAvailable = reconciliation.snapshotAvailable;
|
||||
if (!reconciliation.snapshotAvailable) {
|
||||
applyRuntimeSnapshotProjection(new Set(), false);
|
||||
syncPortForwardingHeartbeatTimer();
|
||||
return;
|
||||
}
|
||||
applyRuntimeSnapshotProjection(
|
||||
@@ -374,10 +486,12 @@ const subscribeToPortForwardRuntime = (): (() => void) => {
|
||||
true,
|
||||
reconciliation.appeared,
|
||||
);
|
||||
syncPortForwardingHeartbeatTimer();
|
||||
} catch {
|
||||
if (disposed) return;
|
||||
snapshotAvailable = false;
|
||||
applyRuntimeSnapshotProjection(new Set(), false);
|
||||
syncPortForwardingHeartbeatTimer();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -399,6 +513,7 @@ const subscribeToPortForwardRuntime = (): (() => void) => {
|
||||
snapshotAvailable = reconciliation.snapshotAvailable;
|
||||
if (!reconciliation.snapshotAvailable) {
|
||||
applyRuntimeSnapshotProjection(new Set(), false);
|
||||
syncPortForwardingHeartbeatTimer();
|
||||
return;
|
||||
}
|
||||
applyRuntimeSnapshotProjection(
|
||||
@@ -406,6 +521,7 @@ const subscribeToPortForwardRuntime = (): (() => void) => {
|
||||
true,
|
||||
reconciliation.appeared,
|
||||
);
|
||||
syncPortForwardingHeartbeatTimer();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -524,47 +640,20 @@ export const usePortForwardingState = (): UsePortForwardingStateResult => {
|
||||
}, []);
|
||||
|
||||
// Periodic heartbeat: reconcile renderer state with the backend every 4s.
|
||||
// Ref-counted — same pattern as the reconnect cancel listener.
|
||||
// Ref-counted and dynamically armed only while visible and needed (rules
|
||||
// configured, active runtime tunnels, or runtime snapshot not yet available).
|
||||
useEffect(() => {
|
||||
heartbeatRefs++;
|
||||
let intervalId: ReturnType<typeof setInterval> | undefined;
|
||||
if (heartbeatRefs === 1) {
|
||||
const HEARTBEAT_INTERVAL_MS = 4_000;
|
||||
|
||||
const tick = async () => {
|
||||
const reconciliation = await reconcileWithBackend();
|
||||
snapshotAvailable = reconciliation.snapshotAvailable;
|
||||
if (!reconciliation.snapshotAvailable) {
|
||||
// Snapshot failure must surface as unknown/stale — never as inactive.
|
||||
applyRuntimeSnapshotProjection(new Set(), false);
|
||||
return;
|
||||
}
|
||||
// Always re-derive the visible state from the live connection map.
|
||||
// Runtime phases stay in memory only.
|
||||
const normalizedRules = normalizeRulesWithConnections(
|
||||
globalRules,
|
||||
{
|
||||
reconciledGoneRuleIds: new Set(reconciliation.gone),
|
||||
snapshotAvailable: true,
|
||||
},
|
||||
);
|
||||
if (havePortForwardingRuntimeStatesChanged(globalRules, normalizedRules)) {
|
||||
setRuntimeProjection(normalizedRules);
|
||||
} else if (hasPortForwardingRuntimePresenceChanged(reconciliation)) {
|
||||
globalRules = normalizedRules;
|
||||
notifyListeners();
|
||||
}
|
||||
};
|
||||
|
||||
intervalId = setInterval(tick, HEARTBEAT_INTERVAL_MS);
|
||||
heartbeatIntervalId = intervalId;
|
||||
attachPortForwardingVisibilityListener();
|
||||
}
|
||||
syncPortForwardingHeartbeatTimer();
|
||||
return () => {
|
||||
heartbeatRefs--;
|
||||
if (heartbeatRefs === 0 && heartbeatIntervalId !== undefined) {
|
||||
clearInterval(heartbeatIntervalId);
|
||||
heartbeatIntervalId = undefined;
|
||||
heartbeatRefs = Math.max(0, heartbeatRefs - 1);
|
||||
if (heartbeatRefs === 0) {
|
||||
detachPortForwardingVisibilityListener();
|
||||
}
|
||||
syncPortForwardingHeartbeatTimer();
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -831,6 +920,14 @@ export const usePortForwardingState = (): UsePortForwardingStateResult => {
|
||||
|
||||
const selectedRule = rules.find((r) => r.id === selectedRuleId);
|
||||
|
||||
const stopRuleTunnels = useCallback(async (ruleId: string) => {
|
||||
try {
|
||||
return await stopAndCleanupRuleAndWait(ruleId);
|
||||
} finally {
|
||||
syncPortForwardingHeartbeatTimer();
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
rules,
|
||||
selectedRuleId,
|
||||
@@ -857,7 +954,7 @@ export const usePortForwardingState = (): UsePortForwardingStateResult => {
|
||||
stopTunnel,
|
||||
startAllTunnels,
|
||||
stopAllTunnels,
|
||||
stopRuleTunnels: stopAndCleanupRuleAndWait,
|
||||
stopRuleTunnels,
|
||||
hasRuntimeTunnel,
|
||||
hasAnyRuntimeTunnel,
|
||||
|
||||
|
||||
@@ -94,3 +94,88 @@ test('stats reply after disabling cannot publish or schedule recovery', async t
|
||||
t.mock.timers.reset();
|
||||
}
|
||||
});
|
||||
|
||||
test('server stats pauses while document is hidden, preserves cached stats, and catches up on visible', async t => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout', 'setInterval', 'Date'], now: 10_000 });
|
||||
const originalActEnvironment = Object.getOwnPropertyDescriptor(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
const originalDocument = Object.getOwnPropertyDescriptor(globalThis, 'document');
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, value: true });
|
||||
|
||||
const visibilityListeners = new Set<() => void>();
|
||||
let visibilityState: DocumentVisibilityState = 'visible';
|
||||
Object.defineProperty(globalThis, 'document', {
|
||||
configurable: true,
|
||||
value: {
|
||||
get visibilityState() { return visibilityState; },
|
||||
get hidden() { return visibilityState === 'hidden'; },
|
||||
addEventListener(type: string, listener: () => void) {
|
||||
if (type === 'visibilitychange') visibilityListeners.add(listener);
|
||||
},
|
||||
removeEventListener(type: string, listener: () => void) {
|
||||
if (type === 'visibilitychange') visibilityListeners.delete(listener);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const setVisibility = async (next: DocumentVisibilityState) => {
|
||||
visibilityState = next;
|
||||
await act(async () => {
|
||||
for (const listener of [...visibilityListeners]) listener();
|
||||
});
|
||||
};
|
||||
|
||||
let calls = 0;
|
||||
t.mock.method(netcattyBridge, 'get', () => ({
|
||||
getServerStats: async () => {
|
||||
calls += 1;
|
||||
return { success: true, stats: { cpu: 20 + calls } };
|
||||
},
|
||||
}));
|
||||
|
||||
let current: ReturnType<typeof useServerStats>;
|
||||
function Probe() {
|
||||
current = useServerStats({
|
||||
sessionId: 'visibility-pause',
|
||||
enabled: true,
|
||||
refreshInterval: 5,
|
||||
isSupportedOs: true,
|
||||
isConnected: true,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
let root: ReactTestRenderer;
|
||||
try {
|
||||
await act(async () => { root = create(React.createElement(Probe)); });
|
||||
assert.equal(visibilityListeners.size, 1);
|
||||
|
||||
// Warmup initial fetch at 2000ms
|
||||
await act(async () => t.mock.timers.tick(2000));
|
||||
assert.equal(calls, 1);
|
||||
assert.equal(current!.stats.cpu, 21);
|
||||
|
||||
// Transition to hidden: polling pauses and cached stats stay intact
|
||||
await setVisibility('hidden');
|
||||
await act(async () => t.mock.timers.tick(60_000));
|
||||
assert.equal(calls, 1, 'hidden window must not poll server stats');
|
||||
assert.equal(current!.stats.cpu, 21, 'cached stats must be preserved while hidden');
|
||||
|
||||
// Return to visible: immediate catch-up fetch (0ms) + resumes 5s polling
|
||||
await setVisibility('visible');
|
||||
await act(async () => t.mock.timers.tick(0));
|
||||
assert.equal(calls, 2, 'returning to visible must trigger immediate catch-up fetch');
|
||||
assert.equal(current!.stats.cpu, 22);
|
||||
|
||||
await act(async () => t.mock.timers.tick(5000));
|
||||
assert.equal(calls, 3, 'periodic polling must resume after returning to visible');
|
||||
assert.equal(current!.stats.cpu, 23);
|
||||
} finally {
|
||||
await act(async () => root?.unmount());
|
||||
assert.equal(visibilityListeners.size, 0, 'visibility listener must detach when all sessions unmount');
|
||||
if (originalDocument) Object.defineProperty(globalThis, 'document', originalDocument);
|
||||
else Reflect.deleteProperty(globalThis, 'document');
|
||||
if (originalActEnvironment) Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', originalActEnvironment);
|
||||
else Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
t.mock.timers.reset();
|
||||
}
|
||||
});
|
||||
@@ -114,6 +114,41 @@ interface SharedServerStatsSession {
|
||||
const CONSECUTIVE_FAILURE_LIMIT = 3;
|
||||
const serverStatsSessions = new Map<string, SharedServerStatsSession>();
|
||||
let nextClientId = 1;
|
||||
let attachedVisibilityDocument: Document | null = null;
|
||||
|
||||
function isServerStatsDocumentHidden(): boolean {
|
||||
if (typeof document === 'undefined') return false;
|
||||
if (typeof document.visibilityState === 'string') {
|
||||
return document.visibilityState === 'hidden';
|
||||
}
|
||||
return document.hidden === true;
|
||||
}
|
||||
|
||||
function handleServerStatsVisibilityChange(): void {
|
||||
for (const session of serverStatsSessions.values()) {
|
||||
reconcileSharedServerStatsSession(session);
|
||||
}
|
||||
}
|
||||
|
||||
function ensureServerStatsVisibilityListener(): void {
|
||||
if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') {
|
||||
return;
|
||||
}
|
||||
if (attachedVisibilityDocument === document) return;
|
||||
if (attachedVisibilityDocument && typeof attachedVisibilityDocument.removeEventListener === 'function') {
|
||||
attachedVisibilityDocument.removeEventListener('visibilitychange', handleServerStatsVisibilityChange);
|
||||
}
|
||||
document.addEventListener('visibilitychange', handleServerStatsVisibilityChange);
|
||||
attachedVisibilityDocument = document;
|
||||
}
|
||||
|
||||
function maybeDetachServerStatsVisibilityListener(): void {
|
||||
if (serverStatsSessions.size > 0 || !attachedVisibilityDocument) return;
|
||||
if (typeof attachedVisibilityDocument.removeEventListener === 'function') {
|
||||
attachedVisibilityDocument.removeEventListener('visibilitychange', handleServerStatsVisibilityChange);
|
||||
}
|
||||
attachedVisibilityDocument = null;
|
||||
}
|
||||
|
||||
function createEmptyServerStats(): ServerStats {
|
||||
return {
|
||||
@@ -281,6 +316,7 @@ async function fetchSharedServerStats(session: SharedServerStatsSession, force =
|
||||
}
|
||||
if (session.givenUp && !force) return;
|
||||
if (getActiveServerStatsClients(session).length === 0) return;
|
||||
if (!force && isServerStatsDocumentHidden()) return;
|
||||
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.getServerStats) return;
|
||||
@@ -348,13 +384,13 @@ async function fetchSharedServerStats(session: SharedServerStatsSession, force =
|
||||
function reconcileSharedServerStatsSession(session: SharedServerStatsSession): void {
|
||||
const activeClients = getActiveServerStatsClients(session);
|
||||
|
||||
if (activeClients.length === 0) {
|
||||
// Pause polling only. Keep the last successful stats so remounting Overview
|
||||
// (or re-enabling a terminal stats strip) can paint immediately instead of
|
||||
// flashing "No system overview data yet." Still clear give-up / failure so a
|
||||
// later resume can auto-retry (old reset wiped stats + flags together).
|
||||
// Invalidate a request before pausing: a late reply must not publish data
|
||||
// or re-arm failure/retry timers after disconnect/disable.
|
||||
if (activeClients.length === 0 || isServerStatsDocumentHidden()) {
|
||||
// Pause polling only. Keep the last successful stats so remounting Overview,
|
||||
// re-enabling a terminal stats strip, or returning from a hidden window
|
||||
// can paint immediately instead of flashing "No system overview data yet."
|
||||
// Still clear give-up / failure so a later resume can auto-retry (old reset
|
||||
// wiped stats + flags together). Invalidate a request before pausing: a late
|
||||
// reply must not publish data or re-arm failure/retry timers after pause.
|
||||
if (session.pollingActive || session.inflight || session.givenUp) {
|
||||
session.fetchGeneration += 1;
|
||||
}
|
||||
@@ -398,6 +434,7 @@ function maybeDisposeSharedServerStatsSession(session: SharedServerStatsSession)
|
||||
clearServerStatsTimers(session);
|
||||
session.fetchGeneration += 1;
|
||||
serverStatsSessions.delete(session.sessionId);
|
||||
maybeDetachServerStatsVisibilityListener();
|
||||
}
|
||||
|
||||
export function useServerStats({
|
||||
@@ -420,6 +457,7 @@ export function useServerStats({
|
||||
const clientId = clientIdRef.current;
|
||||
if (clientId === null) return;
|
||||
|
||||
ensureServerStatsVisibilityListener();
|
||||
const listener: ServerStatsListener = (nextState) => {
|
||||
setState(nextState);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
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 { Host } from "../../domain/models";
|
||||
import { buildSshDeepLinkEphemeralHostFromSaved } from "../../domain/sshDeepLink";
|
||||
import { collectSessionIds } from "../../domain/workspace";
|
||||
import { activeTabStore } from "./activeTabStore";
|
||||
import { useSessionState } from "./useSessionState";
|
||||
|
||||
const makeHost = (id: string, label: string): Host => ({
|
||||
id,
|
||||
label,
|
||||
hostname: `${id}.example.test`,
|
||||
username: "ubuntu",
|
||||
port: 22,
|
||||
os: "linux",
|
||||
group: "",
|
||||
tags: [],
|
||||
protocol: "ssh",
|
||||
});
|
||||
|
||||
function setupDom(t: test.TestContext) {
|
||||
const dom = new JSDOM('<div id="root"></div>', { url: "http://localhost" });
|
||||
const globals = {
|
||||
window: dom.window,
|
||||
document: dom.window.document,
|
||||
localStorage: dom.window.localStorage,
|
||||
CustomEvent: dom.window.CustomEvent,
|
||||
Event: dom.window.Event,
|
||||
IS_REACT_ACT_ENVIRONMENT: true,
|
||||
};
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const [key, value] of Object.entries(globals)) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, value });
|
||||
}
|
||||
const root = createRoot(document.getElementById("root")!);
|
||||
t.after(async () => {
|
||||
activeTabStore.setActiveTabId("vault");
|
||||
await new Promise((resolve) => dom.window.setTimeout(resolve, 0));
|
||||
await act(async () => root.unmount());
|
||||
dom.window.close();
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
});
|
||||
return { root };
|
||||
}
|
||||
|
||||
test("useSessionState reopens closed standalone tabs and 2-pane split workspaces in LIFO order", async (t) => {
|
||||
const { root } = setupDom(t);
|
||||
let state!: ReturnType<typeof useSessionState>;
|
||||
function Probe() {
|
||||
state = useSessionState({ persistSessionRestore: false });
|
||||
return null;
|
||||
}
|
||||
await act(async () => {
|
||||
root.render(React.createElement(React.StrictMode, null, React.createElement(Probe)));
|
||||
});
|
||||
|
||||
const hostA = makeHost("h-a", "App Server");
|
||||
const hostB = makeHost("h-b", "DB Server");
|
||||
const hostsById = new Map<string, Host>([
|
||||
[hostA.id, hostA],
|
||||
[hostB.id, hostB],
|
||||
]);
|
||||
const availableHostIds = new Set(hostsById.keys());
|
||||
|
||||
// 1. Open and close a standalone SSH host tab and a local terminal tab.
|
||||
let soloId = "";
|
||||
let localId = "";
|
||||
await act(async () => {
|
||||
soloId = state.connectToHost(hostA);
|
||||
localId = state.createLocalTerminal({ shellName: "Zsh", localStartDir: "/tmp" });
|
||||
});
|
||||
await act(async () => {
|
||||
state.updateSessionRestoreCwd(localId, "/Users/dev/workspace");
|
||||
state.renameSessionInline(soloId, "Custom Prod");
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
state.closeSession(soloId);
|
||||
});
|
||||
await act(async () => {
|
||||
state.closeSession(localId);
|
||||
});
|
||||
|
||||
assert.equal(state.sessions.length, 0);
|
||||
assert.equal(state.getClosedTabHistoryCount(), 2);
|
||||
|
||||
// 2. Create a 2-pane split workspace, customize split sizes & focus, then close it.
|
||||
await act(async () => {
|
||||
state.createWorkspaceWithHosts("Ops Split", [hostA, hostB]);
|
||||
});
|
||||
const origWorkspace = state.workspaces[0];
|
||||
assert.ok(origWorkspace);
|
||||
assert.equal(origWorkspace.root.type, "split");
|
||||
const origPaneIds = collectSessionIds(origWorkspace.root);
|
||||
assert.equal(origPaneIds.length, 2);
|
||||
|
||||
await act(async () => {
|
||||
state.updateSplitSizes(origWorkspace.id, origWorkspace.root.id, [0.7, 0.3]);
|
||||
state.setWorkspaceFocusedSession(origWorkspace.id, origPaneIds[1]);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
state.closeWorkspace(origWorkspace.id);
|
||||
});
|
||||
|
||||
assert.equal(state.workspaces.length, 0);
|
||||
assert.equal(state.sessions.length, 0);
|
||||
assert.equal(activeTabStore.getActiveTabId(), "vault");
|
||||
assert.equal(state.getClosedTabHistoryCount(), 3);
|
||||
|
||||
// 3. First reopen: restores the 2-pane split workspace with ratios, title, and focused pane.
|
||||
await act(async () => {
|
||||
const reopened = state.reopenLastClosedTab({ availableHostIds, hostsById });
|
||||
assert.ok(reopened && reopened.kind === "workspace");
|
||||
});
|
||||
assert.equal(state.workspaces.length, 1);
|
||||
assert.equal(state.sessions.length, 2);
|
||||
const restoredWs = state.workspaces[0];
|
||||
assert.notEqual(restoredWs.id, origWorkspace.id);
|
||||
assert.equal(restoredWs.title, "Ops Split");
|
||||
assert.equal(restoredWs.viewMode, "split");
|
||||
assert.equal(restoredWs.root.type, "split");
|
||||
assert.deepEqual(restoredWs.root.sizes, [0.7, 0.3]);
|
||||
assert.equal(activeTabStore.getActiveTabId(), restoredWs.id);
|
||||
|
||||
const restoredPaneIds = collectSessionIds(restoredWs.root);
|
||||
assert.equal(restoredPaneIds.length, 2);
|
||||
assert.equal(restoredWs.focusedSessionId, restoredPaneIds[1]);
|
||||
assert.deepEqual(
|
||||
state.sessions.map((s) => s.hostId),
|
||||
[hostA.id, hostB.id],
|
||||
);
|
||||
assert.ok(state.sessions.every((s) => s.status === "connecting" && s.workspaceId === restoredWs.id));
|
||||
|
||||
// 4. Second reopen: restores the local terminal tab with its last tracked CWD.
|
||||
await act(async () => {
|
||||
const reopened = state.reopenLastClosedTab({ availableHostIds, hostsById });
|
||||
assert.ok(reopened && reopened.kind === "session");
|
||||
});
|
||||
assert.equal(state.sessions.length, 3);
|
||||
const restoredLocal = state.sessions.find((s) => !s.workspaceId && s.protocol === "local");
|
||||
assert.ok(restoredLocal);
|
||||
assert.notEqual(restoredLocal.id, localId);
|
||||
assert.equal(restoredLocal.localStartDir, "/Users/dev/workspace");
|
||||
assert.equal(restoredLocal.status, "connecting");
|
||||
assert.equal(activeTabStore.getActiveTabId(), restoredLocal.id);
|
||||
|
||||
// 5. Third reopen: restores the standalone SSH host tab with customName preserved.
|
||||
await act(async () => {
|
||||
const reopened = state.reopenLastClosedTab({ availableHostIds, hostsById });
|
||||
assert.ok(reopened && reopened.kind === "session");
|
||||
});
|
||||
assert.equal(state.sessions.length, 4);
|
||||
const restoredSolo = state.sessions.find((s) => !s.workspaceId && s.hostId === hostA.id);
|
||||
assert.ok(restoredSolo);
|
||||
assert.notEqual(restoredSolo.id, soloId);
|
||||
assert.equal(restoredSolo.customName, "Custom Prod");
|
||||
assert.equal(restoredSolo.status, "connecting");
|
||||
assert.equal(activeTabStore.getActiveTabId(), restoredSolo.id);
|
||||
|
||||
// 6. Fourth reopen on empty stack is a clean no-op.
|
||||
await act(async () => {
|
||||
const empty = state.reopenLastClosedTab({ availableHostIds, hostsById });
|
||||
assert.equal(empty, null);
|
||||
});
|
||||
assert.equal(state.sessions.length, 4);
|
||||
});
|
||||
|
||||
test("useSessionState skips deleted vault hosts and ignores hidden MCP sessions on reopen", async (t) => {
|
||||
const { root } = setupDom(t);
|
||||
let state!: ReturnType<typeof useSessionState>;
|
||||
function Probe() {
|
||||
state = useSessionState({ persistSessionRestore: false });
|
||||
return null;
|
||||
}
|
||||
await act(async () => {
|
||||
root.render(React.createElement(React.StrictMode, null, React.createElement(Probe)));
|
||||
});
|
||||
|
||||
const keepHost = makeHost("h-keep", "Keep");
|
||||
const deleteHost = makeHost("h-delete", "Delete Me");
|
||||
|
||||
let keepId = "";
|
||||
let deleteId = "";
|
||||
let hiddenId = "";
|
||||
await act(async () => {
|
||||
keepId = state.connectToHost(keepHost);
|
||||
deleteId = state.connectToHost(deleteHost);
|
||||
hiddenId = state.connectToHost(keepHost, { hidden: true });
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
state.closeSession(keepId);
|
||||
});
|
||||
await act(async () => {
|
||||
state.closeSession(deleteId);
|
||||
});
|
||||
await act(async () => {
|
||||
state.closeSession(hiddenId);
|
||||
});
|
||||
|
||||
// Hidden session was never added to history.
|
||||
assert.equal(state.getClosedTabHistoryCount(), 2);
|
||||
|
||||
// Delete `h-delete` from the vault before reopening.
|
||||
const remainingHosts = new Map<string, Host>([[keepHost.id, keepHost]]);
|
||||
const availableHostIds = new Set(remainingHosts.keys());
|
||||
|
||||
await act(async () => {
|
||||
const reopened = state.reopenLastClosedTab({ availableHostIds, hostsById: remainingHosts });
|
||||
assert.ok(reopened && reopened.kind === "session");
|
||||
assert.equal(reopened.session.hostId, keepHost.id);
|
||||
});
|
||||
|
||||
assert.equal(state.sessions.length, 1);
|
||||
assert.equal(state.sessions[0].hostId, keepHost.id);
|
||||
assert.equal(state.getClosedTabHistoryCount(), 0);
|
||||
});
|
||||
|
||||
test("useSessionState prunes deleted hosts from a closed split workspace on reopen without persisting history to localStorage", async (t) => {
|
||||
const { root } = setupDom(t);
|
||||
let state!: ReturnType<typeof useSessionState>;
|
||||
function Probe() {
|
||||
state = useSessionState({ persistSessionRestore: false });
|
||||
return null;
|
||||
}
|
||||
await act(async () => {
|
||||
root.render(React.createElement(React.StrictMode, null, React.createElement(Probe)));
|
||||
});
|
||||
|
||||
const hostA = makeHost("h-a", "Web");
|
||||
const hostB = makeHost("h-b", "Worker");
|
||||
const hostC = makeHost("h-c", "Cache");
|
||||
|
||||
await act(async () => {
|
||||
state.createWorkspaceWithHosts("Cluster", [hostA, hostB, hostC]);
|
||||
});
|
||||
const ws = state.workspaces[0];
|
||||
assert.ok(ws && ws.root.type === "split");
|
||||
await act(async () => {
|
||||
state.updateSplitSizes(ws.id, ws.root.id, [0.2, 0.3, 0.5]);
|
||||
});
|
||||
await act(async () => {
|
||||
state.closeWorkspace(ws.id);
|
||||
});
|
||||
|
||||
assert.equal(window.localStorage.length, 0, "closed tab history must stay in-memory only");
|
||||
|
||||
// Delete hostB from the vault before reopening.
|
||||
const survivingHosts = new Map<string, Host>([
|
||||
[hostA.id, hostA],
|
||||
[hostC.id, hostC],
|
||||
]);
|
||||
await act(async () => {
|
||||
const reopened = state.reopenLastClosedTab({
|
||||
availableHostIds: new Set(survivingHosts.keys()),
|
||||
hostsById: survivingHosts,
|
||||
});
|
||||
assert.ok(reopened && reopened.kind === "workspace");
|
||||
});
|
||||
|
||||
assert.equal(state.workspaces.length, 1);
|
||||
const restored = state.workspaces[0];
|
||||
assert.equal(restored.title, "Cluster");
|
||||
assert.equal(restored.root.type, "split");
|
||||
assert.equal(collectSessionIds(restored.root).length, 2);
|
||||
assert.deepEqual(state.sessions.map((s) => s.hostId), [hostA.id, hostC.id]);
|
||||
assert.ok(Math.abs((restored.root.sizes?.[0] ?? 0) - 2 / 7) < 1e-9);
|
||||
assert.ok(Math.abs((restored.root.sizes?.[1] ?? 0) - 5 / 7) < 1e-9);
|
||||
});
|
||||
|
||||
test("useSessionState excludes ephemeral deep-link hosts with bastion/proxy/legacy settings from reopen history", async (t) => {
|
||||
const { root } = setupDom(t);
|
||||
let state!: ReturnType<typeof useSessionState>;
|
||||
function Probe() {
|
||||
state = useSessionState({ persistSessionRestore: false });
|
||||
return null;
|
||||
}
|
||||
await act(async () => {
|
||||
root.render(React.createElement(React.StrictMode, null, React.createElement(Probe)));
|
||||
});
|
||||
|
||||
const savedHost: Host = {
|
||||
...makeHost("h-bastion-target", "Bastion Target"),
|
||||
hostChain: { hostIds: ["h-jump"] },
|
||||
proxyConfig: { type: "socks5", host: "127.0.0.1", port: 1080 },
|
||||
legacyAlgorithms: true,
|
||||
};
|
||||
const ephemeralHost = buildSshDeepLinkEphemeralHostFromSaved(
|
||||
savedHost,
|
||||
{ rawUrl: `ssh://${savedHost.username}:otp@${savedHost.hostname}`, hostname: savedHost.hostname, username: savedHost.username, password: "otp" },
|
||||
{ id: "ephemeral-1", now: 1000 },
|
||||
);
|
||||
|
||||
let savedSessionId = "";
|
||||
let ephSessionId = "";
|
||||
await act(async () => {
|
||||
savedSessionId = state.connectToHost(savedHost);
|
||||
ephSessionId = state.connectToHost(ephemeralHost);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
state.closeSession(savedSessionId);
|
||||
});
|
||||
await act(async () => {
|
||||
state.closeSession(ephSessionId);
|
||||
});
|
||||
|
||||
// Only the saved vault host was recorded; the ephemeral host was skipped.
|
||||
assert.equal(state.getClosedTabHistoryCount(), 1);
|
||||
|
||||
const hostsById = new Map<string, Host>([[savedHost.id, savedHost]]);
|
||||
await act(async () => {
|
||||
const reopened = state.reopenLastClosedTab({
|
||||
availableHostIds: new Set(hostsById.keys()),
|
||||
hostsById,
|
||||
});
|
||||
assert.ok(reopened && reopened.kind === "session");
|
||||
assert.equal(reopened.session.hostId, savedHost.id);
|
||||
assert.equal(reopened.session.ephemeralHost, undefined);
|
||||
});
|
||||
|
||||
assert.equal(state.sessions.length, 1);
|
||||
assert.equal(state.sessions[0].hostId, savedHost.id);
|
||||
assert.equal(state.getClosedTabHistoryCount(), 0);
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
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 { createLocalShellHost } from '../../domain/localShellHost';
|
||||
import { activeTabStore } from './activeTabStore';
|
||||
import { useSessionState } from './useSessionState';
|
||||
|
||||
async function mountSessionState(t: test.TestContext) {
|
||||
const dom = new JSDOM('<div id="root"></div>', { url: 'http://localhost' });
|
||||
const globals = {
|
||||
window: dom.window,
|
||||
document: dom.window.document,
|
||||
localStorage: dom.window.localStorage,
|
||||
CustomEvent: dom.window.CustomEvent,
|
||||
Event: dom.window.Event,
|
||||
IS_REACT_ACT_ENVIRONMENT: true,
|
||||
};
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const [key, value] of Object.entries(globals)) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, value });
|
||||
}
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
let latestState!: ReturnType<typeof useSessionState>;
|
||||
|
||||
function Probe() {
|
||||
latestState = useSessionState({ persistSessionRestore: false });
|
||||
return null;
|
||||
}
|
||||
|
||||
activeTabStore.setActiveTabId('vault', { recordPrevious: false });
|
||||
await act(async () => {
|
||||
root.render(React.createElement(React.StrictMode, null, React.createElement(Probe)));
|
||||
});
|
||||
|
||||
t.after(async () => {
|
||||
await act(async () => root.unmount());
|
||||
// Reset activeTabStore while DOM globals are still live and flush any
|
||||
// queued notification before closing JSDOM so notifyRafId is cleared.
|
||||
activeTabStore.setActiveTabId('vault', { recordPrevious: false });
|
||||
await new Promise<void>((resolve) => {
|
||||
if (typeof requestAnimationFrame === 'function') {
|
||||
requestAnimationFrame(() => resolve());
|
||||
} else {
|
||||
dom.window.setTimeout(resolve, 0);
|
||||
}
|
||||
});
|
||||
dom.window.close();
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
});
|
||||
|
||||
return () => latestState;
|
||||
}
|
||||
|
||||
test('useSessionState issue #4249 scenario 1: repeated close focuses C -> B -> A -> vault', async (t) => {
|
||||
const getState = await mountSessionState(t);
|
||||
|
||||
let a = '';
|
||||
let b = '';
|
||||
let c = '';
|
||||
await act(async () => { a = getState().createLocalTerminal(); });
|
||||
await act(async () => { b = getState().createLocalTerminal(); });
|
||||
await act(async () => { c = getState().createLocalTerminal(); });
|
||||
assert.equal(activeTabStore.getActiveTabId(), c);
|
||||
|
||||
await act(async () => { getState().closeSession(c); });
|
||||
assert.equal(activeTabStore.getActiveTabId(), b);
|
||||
|
||||
await act(async () => { getState().closeSession(b); });
|
||||
assert.equal(activeTabStore.getActiveTabId(), a);
|
||||
|
||||
await act(async () => { getState().closeSession(a); });
|
||||
assert.equal(activeTabStore.getActiveTabId(), 'vault');
|
||||
});
|
||||
|
||||
for (const rootView of ['vault', 'sftp'] as const) {
|
||||
test(`useSessionState issue #4249 scenario 2 (${rootView}): clicking ${rootView} then closing C -> B -> A stays on terminals until last tab`, async (t) => {
|
||||
const getState = await mountSessionState(t);
|
||||
|
||||
let a = '';
|
||||
let b = '';
|
||||
let c = '';
|
||||
await act(async () => { a = getState().createLocalTerminal(); });
|
||||
await act(async () => { b = getState().createLocalTerminal(); });
|
||||
await act(async () => { c = getState().createLocalTerminal(); });
|
||||
|
||||
// User clicks Vaults/SFTP once, then clicks back to rightmost terminal C.
|
||||
await act(async () => { getState().setActiveTabId(rootView); });
|
||||
await act(async () => { getState().setActiveTabId(c); });
|
||||
assert.equal(activeTabStore.getActiveTabId(), c);
|
||||
assert.equal(activeTabStore.getPreviousActiveTabId(), rootView);
|
||||
|
||||
// Repeated Cmd/Ctrl+W closes C -> B -> A predictably before falling back.
|
||||
await act(async () => { getState().closeSession(c); });
|
||||
assert.equal(activeTabStore.getActiveTabId(), b);
|
||||
|
||||
await act(async () => { getState().closeSession(b); });
|
||||
assert.equal(activeTabStore.getActiveTabId(), a);
|
||||
|
||||
await act(async () => { getState().closeSession(a); });
|
||||
assert.equal(activeTabStore.getActiveTabId(), rootView);
|
||||
});
|
||||
}
|
||||
|
||||
test('useSessionState closing a workspace tab moves to adjacent terminal tab instead of jumping to vault/sftp', async (t) => {
|
||||
const getState = await mountSessionState(t);
|
||||
|
||||
let a = '';
|
||||
let c = '';
|
||||
await act(async () => { a = getState().createLocalTerminal(); });
|
||||
await act(async () => {
|
||||
getState().createWorkspaceWithHosts('WS', [createLocalShellHost({ id: 'ws-local-1' })]);
|
||||
});
|
||||
const wsId = getState().workspaces[0].id;
|
||||
await act(async () => { c = getState().createLocalTerminal(); });
|
||||
|
||||
// Place workspace visually between A and C: [a, wsId, c].
|
||||
await act(async () => { getState().reorderTabs(wsId, a, 'after'); });
|
||||
assert.deepEqual(getState().orderedTabs, [a, wsId, c]);
|
||||
|
||||
// Visit SFTP, return to C, then close C -> WS -> A.
|
||||
await act(async () => { getState().setActiveTabId('sftp'); });
|
||||
await act(async () => { getState().setActiveTabId(c); });
|
||||
|
||||
await act(async () => { getState().closeSession(c); });
|
||||
assert.equal(activeTabStore.getActiveTabId(), wsId);
|
||||
|
||||
await act(async () => { getState().closeWorkspace(wsId); });
|
||||
assert.equal(activeTabStore.getActiveTabId(), a);
|
||||
|
||||
await act(async () => { getState().closeSession(a); });
|
||||
assert.equal(activeTabStore.getActiveTabId(), 'sftp');
|
||||
});
|
||||
@@ -44,6 +44,7 @@ import {
|
||||
import {
|
||||
closeSessionsState,
|
||||
detachSessionFromWorkspaceState,
|
||||
resolveActiveTabAfterCloseWorkspace,
|
||||
} from './sessionWorkspaceDetach';
|
||||
import { getAISessionsSnapshot } from './aiSessionsStore';
|
||||
import { getPersistedAiSessionsSnapshot } from './aiStateSnapshots';
|
||||
@@ -78,6 +79,15 @@ import {
|
||||
import { cleanupClosedTerminalSessions } from './aiStateSnapshots';
|
||||
import { captureClosingTerminalSessions } from './terminalSessionCloseCapture';
|
||||
import { syncSessionHostLabels } from '../../domain/syncSessionHostLabels';
|
||||
import {
|
||||
createClosedSessionEntry,
|
||||
createClosedWorkspaceEntry,
|
||||
materializeClosedTabEntry,
|
||||
popClosedTabEntry,
|
||||
pushClosedTabEntry,
|
||||
type ClosedTabEntry,
|
||||
type ReopenClosedTabMaterialized,
|
||||
} from '../../domain/closedTabHistory';
|
||||
import { useVaultSnapshotField } from './vaultSnapshotStore';
|
||||
|
||||
export function addWorkspaceIfMissing(
|
||||
@@ -279,6 +289,10 @@ export const useSessionState = ({
|
||||
const [restorePreviousSessionRevision, setRestorePreviousSessionRevision] = useState(0);
|
||||
const sessionsRef = useRef(sessions);
|
||||
const tabOrderRef = useRef(tabOrder);
|
||||
// Bounded in-memory LIFO stack of recently closed standalone tabs and split
|
||||
// workspaces (Cmd/Ctrl+Shift+T). Kept in a ref so closing tabs adds no extra
|
||||
// React re-renders and never persists ephemeral/session data to localStorage.
|
||||
const closedTabHistoryRef = useRef<ClosedTabEntry[]>([]);
|
||||
const scheduleSessionRestorePersistRef = useRef<() => void>(() => {});
|
||||
const sessionRestoreCwdByIdRef = useRef(
|
||||
new Map(
|
||||
@@ -616,33 +630,61 @@ export const useSessionState = ({
|
||||
}, []);
|
||||
|
||||
const closeWorkspace = useCallback((workspaceId: string) => {
|
||||
const closedIds = sessionsRef.current
|
||||
.filter(session => session.workspaceId === workspaceId)
|
||||
.map(session => session.id);
|
||||
const closingWorkspace = workspacesRef.current.find(w => w.id === workspaceId);
|
||||
const closingSessions = sessionsRef.current.filter(session => session.workspaceId === workspaceId);
|
||||
if (closingWorkspace && closingSessions.length > 0) {
|
||||
const closedEntry = createClosedWorkspaceEntry(closingWorkspace, closingSessions, {
|
||||
cwdBySessionId: sessionRestoreCwdByIdRef.current,
|
||||
});
|
||||
if (closedEntry) {
|
||||
closedTabHistoryRef.current = pushClosedTabEntry(closedTabHistoryRef.current, closedEntry);
|
||||
}
|
||||
}
|
||||
const closedIds = closingSessions.map(session => session.id);
|
||||
captureClosingTerminalSessions(closedIds);
|
||||
cleanupClosedTerminalSessions(closedIds);
|
||||
for (const sessionId of closedIds) {
|
||||
sessionPresentationStore.clearSession(sessionId);
|
||||
}
|
||||
const preferredTabId = activeTabStore.getPreviousActiveTabId();
|
||||
const tabOrderSnapshot = tabOrderRef.current;
|
||||
const sessionsSnapshot = sessionsRef.current;
|
||||
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 currentActiveTabId = activeTabStore.getActiveTabId();
|
||||
if (currentActiveTabId === workspaceId) {
|
||||
if (remainingWorkspaces.length > 0) {
|
||||
setActiveTabId(remainingWorkspaces[remainingWorkspaces.length - 1].id);
|
||||
} else {
|
||||
setActiveTabId('vault');
|
||||
}
|
||||
const nextActiveTabId = resolveActiveTabAfterCloseWorkspace({
|
||||
currentActiveTabId: activeTabStore.getActiveTabId(),
|
||||
closedWorkspaceId: workspaceId,
|
||||
previousWorkspaces: prevWorkspaces,
|
||||
remainingWorkspaces,
|
||||
remainingSessions,
|
||||
tabOrder: tabOrderSnapshot,
|
||||
preferredTabId,
|
||||
});
|
||||
if (nextActiveTabId) {
|
||||
// Closing must not rewrite previous-tab history to the closed workspace.
|
||||
activeTabStore.setActiveTabId(nextActiveTabId, { recordPrevious: false });
|
||||
}
|
||||
|
||||
return remainingWorkspaces;
|
||||
});
|
||||
}, [setActiveTabId]);
|
||||
}, []);
|
||||
|
||||
const closeSessions = useCallback((sessionIds: string[]) => {
|
||||
for (const sessionId of new Set(sessionIds)) {
|
||||
const targetSession = sessionsRef.current.find(session => session.id === sessionId);
|
||||
if (!targetSession) continue;
|
||||
const closedEntry = createClosedSessionEntry(targetSession, {
|
||||
lastCwd: sessionRestoreCwdByIdRef.current.get(sessionId),
|
||||
});
|
||||
if (closedEntry) {
|
||||
closedTabHistoryRef.current = pushClosedTabEntry(closedTabHistoryRef.current, closedEntry);
|
||||
}
|
||||
}
|
||||
captureClosingTerminalSessions(sessionIds);
|
||||
cleanupClosedTerminalSessions(sessionIds);
|
||||
for (const sessionId of sessionIds) {
|
||||
@@ -671,6 +713,46 @@ export const useSessionState = ({
|
||||
}
|
||||
}, []);
|
||||
|
||||
const reopenLastClosedTab = useCallback((options?: {
|
||||
availableHostIds?: ReadonlySet<string>;
|
||||
hostsById?: ReadonlyMap<string, Host>;
|
||||
}): ReopenClosedTabMaterialized | null => {
|
||||
const { entry, nextHistory } = popClosedTabEntry(closedTabHistoryRef.current, {
|
||||
availableHostIds: options?.availableHostIds,
|
||||
});
|
||||
closedTabHistoryRef.current = nextHistory;
|
||||
if (!entry) return null;
|
||||
|
||||
const materialized = materializeClosedTabEntry(entry, {
|
||||
hostsById: options?.hostsById,
|
||||
});
|
||||
if (!materialized) return null;
|
||||
|
||||
if (materialized.kind === 'session') {
|
||||
const reopenedSession = materialized.session;
|
||||
setSessions(prev => addTerminalSessionIfMissing(prev, reopenedSession));
|
||||
setTabOrder(prev => (prev.includes(reopenedSession.id) ? prev : [...prev, reopenedSession.id]));
|
||||
setActiveTabId(reopenedSession.id);
|
||||
return materialized;
|
||||
}
|
||||
|
||||
const { workspace, sessions: reopenedSessions } = materialized;
|
||||
const reopenedSessionIds = new Set(reopenedSessions.map(s => s.id));
|
||||
setSessions(prev => {
|
||||
if (prev.some(s => reopenedSessionIds.has(s.id))) return prev;
|
||||
return [...prev, ...reopenedSessions];
|
||||
});
|
||||
setWorkspaces(prev => addWorkspaceIfMissing(prev, workspace));
|
||||
setTabOrder(prev => (prev.includes(workspace.id) ? prev : [...prev, workspace.id]));
|
||||
setActiveTabId(workspace.id);
|
||||
return materialized;
|
||||
}, [setActiveTabId]);
|
||||
|
||||
const getClosedTabHistoryCount = useCallback(
|
||||
() => closedTabHistoryRef.current.length,
|
||||
[],
|
||||
);
|
||||
|
||||
const closeSession = useCallback((sessionId: string, e?: MouseEvent) => {
|
||||
e?.stopPropagation();
|
||||
closeSessions([sessionId]);
|
||||
@@ -1584,6 +1666,8 @@ export const useSessionState = ({
|
||||
closeSession,
|
||||
closeSessions,
|
||||
closeWorkspace,
|
||||
reopenLastClosedTab,
|
||||
getClosedTabHistoryCount,
|
||||
updateSessionStatus,
|
||||
updateSessionFontSize,
|
||||
setSessionPoppedOut,
|
||||
|
||||
@@ -91,7 +91,7 @@ import {
|
||||
STORAGE_KEY_SHOW_TAB_NUMBER_BADGES,
|
||||
STORAGE_KEY_DISABLE_TERMINAL_FONT_ZOOM,
|
||||
} from '../../infrastructure/config/storageKeys';
|
||||
import { DEFAULT_UI_LOCALE, resolveSupportedLocale } from '../../infrastructure/config/i18n';
|
||||
import { resolveDefaultUiLocale, resolveSupportedLocale } from '../../infrastructure/config/i18n';
|
||||
import {
|
||||
areCustomKeyBindingsEqual,
|
||||
nextCustomKeyBindingsSyncVersion,
|
||||
@@ -357,7 +357,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
}, []);
|
||||
const [uiLanguage, setUiLanguage] = useState<UILanguage>(() => {
|
||||
const stored = readStoredString(STORAGE_KEY_UI_LANGUAGE);
|
||||
return resolveSupportedLocale(stored || DEFAULT_UI_LOCALE);
|
||||
return resolveDefaultUiLocale(stored);
|
||||
});
|
||||
const [appLockSettings, setAppLockSettingsState] = useState<AppLockSettings>({
|
||||
enabled: false,
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import React, { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { JSDOM } from "jsdom";
|
||||
|
||||
import { STORAGE_KEY_UI_LANGUAGE } from "../../infrastructure/config/storageKeys.ts";
|
||||
import { useSettingsState } from "./useSettingsState.ts";
|
||||
|
||||
const withLanguageDom = async (
|
||||
options: {
|
||||
storedLanguage?: string;
|
||||
languages?: readonly string[];
|
||||
language?: string;
|
||||
},
|
||||
run: (env: {
|
||||
dom: JSDOM;
|
||||
root: Root;
|
||||
setLanguageCalls: string[];
|
||||
}) => Promise<void>,
|
||||
) => {
|
||||
const dom = new JSDOM("<!doctype html><html><body></body></html>", { url: "http://localhost" });
|
||||
const globalAny = globalThis as Record<string, unknown>;
|
||||
const saved = {
|
||||
window: Object.getOwnPropertyDescriptor(globalThis, "window"),
|
||||
document: Object.getOwnPropertyDescriptor(globalThis, "document"),
|
||||
localStorage: Object.getOwnPropertyDescriptor(globalThis, "localStorage"),
|
||||
navigator: Object.getOwnPropertyDescriptor(globalThis, "navigator"),
|
||||
actEnv: Object.getOwnPropertyDescriptor(globalThis, "IS_REACT_ACT_ENVIRONMENT"),
|
||||
};
|
||||
|
||||
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, "navigator", {
|
||||
configurable: true,
|
||||
value: {
|
||||
languages: options.languages ?? [],
|
||||
language: options.language ?? "",
|
||||
},
|
||||
});
|
||||
Object.defineProperty(globalAny, "IS_REACT_ACT_ENVIRONMENT", { configurable: true, value: true });
|
||||
|
||||
const setLanguageCalls: string[] = [];
|
||||
dom.window.netcatty = {
|
||||
setLanguage: async (language: string) => {
|
||||
setLanguageCalls.push(language);
|
||||
return true;
|
||||
},
|
||||
notifySettingsChanged: () => {},
|
||||
} as unknown as Window["netcatty"];
|
||||
|
||||
if (options.storedLanguage !== undefined) {
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_UI_LANGUAGE, options.storedLanguage);
|
||||
}
|
||||
|
||||
const container = dom.window.document.createElement("div");
|
||||
dom.window.document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await run({ dom, root, setLanguageCalls });
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
container.remove();
|
||||
dom.window.close();
|
||||
for (const [key, desc] of Object.entries(saved)) {
|
||||
const targetKey = key === "actEnv" ? "IS_REACT_ACT_ENVIRONMENT" : key;
|
||||
if (desc) {
|
||||
Object.defineProperty(globalThis, targetKey, desc);
|
||||
} else {
|
||||
delete globalAny[targetKey];
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
test("useSettingsState defaults UI language to system locale on first launch", async () => {
|
||||
await withLanguageDom(
|
||||
{ languages: ["zh-CN", "en-US"], language: "zh-CN" },
|
||||
async ({ dom, root, setLanguageCalls }) => {
|
||||
let observedLanguage = "";
|
||||
function Probe() {
|
||||
const settings = useSettingsState({ enableSettingsSync: false, enableSystemEffects: false });
|
||||
observedLanguage = settings.uiLanguage;
|
||||
return null;
|
||||
}
|
||||
|
||||
await act(async () => {
|
||||
root.render(React.createElement(Probe));
|
||||
});
|
||||
|
||||
assert.equal(observedLanguage, "zh-CN");
|
||||
assert.equal(dom.window.localStorage.getItem(STORAGE_KEY_UI_LANGUAGE), "zh-CN");
|
||||
assert.equal(dom.window.document.documentElement.lang, "zh-CN");
|
||||
assert.deepEqual(setLanguageCalls, ["zh-CN"]);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("useSettingsState maps Traditional Chinese priority locale on first launch", async () => {
|
||||
await withLanguageDom(
|
||||
{ languages: ["ja-JP", "zh-HK", "en-US"], language: "ja-JP" },
|
||||
async ({ dom, root, setLanguageCalls }) => {
|
||||
let observedLanguage = "";
|
||||
function Probe() {
|
||||
const settings = useSettingsState({ enableSettingsSync: false, enableSystemEffects: false });
|
||||
observedLanguage = settings.uiLanguage;
|
||||
return null;
|
||||
}
|
||||
|
||||
await act(async () => {
|
||||
root.render(React.createElement(Probe));
|
||||
});
|
||||
|
||||
assert.equal(observedLanguage, "zh-TW");
|
||||
assert.equal(dom.window.localStorage.getItem(STORAGE_KEY_UI_LANGUAGE), "zh-TW");
|
||||
assert.equal(dom.window.document.documentElement.lang, "zh-TW");
|
||||
assert.deepEqual(setLanguageCalls, ["zh-TW"]);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("useSettingsState preserves explicit stored UI language over system locale", async () => {
|
||||
await withLanguageDom(
|
||||
{ storedLanguage: "en", languages: ["zh-CN"], language: "zh-CN" },
|
||||
async ({ dom, root, setLanguageCalls }) => {
|
||||
let observedLanguage = "";
|
||||
function Probe() {
|
||||
const settings = useSettingsState({ enableSettingsSync: false, enableSystemEffects: false });
|
||||
observedLanguage = settings.uiLanguage;
|
||||
return null;
|
||||
}
|
||||
|
||||
await act(async () => {
|
||||
root.render(React.createElement(Probe));
|
||||
});
|
||||
|
||||
assert.equal(observedLanguage, "en");
|
||||
assert.equal(dom.window.localStorage.getItem(STORAGE_KEY_UI_LANGUAGE), "en");
|
||||
assert.equal(dom.window.document.documentElement.lang, "en");
|
||||
assert.deepEqual(setLanguageCalls, ["en"]);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -159,17 +159,22 @@ export const useSftpBackend = () => {
|
||||
|
||||
const showSaveDialog = useCallback(async (
|
||||
defaultPath: string,
|
||||
filters?: Array<{ name: string; extensions: string[] }>
|
||||
filters?: Array<{ name: string; extensions: string[] }>,
|
||||
directoryOptions?: NetcattyDialogDirectoryOptions,
|
||||
) => {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.showSaveDialog) return null;
|
||||
return bridge.showSaveDialog(defaultPath, filters);
|
||||
return bridge.showSaveDialog(defaultPath, filters, directoryOptions);
|
||||
}, []);
|
||||
|
||||
const selectDirectory = async (title?: string, defaultPath?: string) => {
|
||||
const selectDirectory = async (
|
||||
title?: string,
|
||||
defaultPath?: string,
|
||||
directoryOptions?: NetcattyDialogDirectoryOptions,
|
||||
) => {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.selectDirectory) return null;
|
||||
return bridge.selectDirectory(title, defaultPath);
|
||||
return bridge.selectDirectory(title, defaultPath, directoryOptions);
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -466,6 +466,8 @@ export const useSftpState = (
|
||||
|
||||
const {
|
||||
navigateTo,
|
||||
navigateBack,
|
||||
navigateForward,
|
||||
refresh,
|
||||
navigateUp,
|
||||
openEntry,
|
||||
@@ -523,7 +525,7 @@ export const useSftpState = (
|
||||
setTimeout(() => {
|
||||
const refreshedPane = getActivePane(side);
|
||||
if (refreshedPane?.connection) {
|
||||
navigateTo(side, refreshedPane.connection.currentPath, { force: true });
|
||||
navigateTo(side, refreshedPane.connection.currentPath, { force: true, historyMode: "none" });
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
@@ -781,6 +783,8 @@ export const useSftpState = (
|
||||
connect,
|
||||
disconnect,
|
||||
navigateTo,
|
||||
navigateBack,
|
||||
navigateForward,
|
||||
navigateUp,
|
||||
refresh,
|
||||
openEntry,
|
||||
@@ -853,6 +857,8 @@ export const useSftpState = (
|
||||
connect: (...args: Parameters<typeof connect>) => methodsRef.current.connect(...args),
|
||||
disconnect: (...args: Parameters<typeof disconnect>) => methodsRef.current.disconnect(...args),
|
||||
navigateTo: (...args: Parameters<typeof navigateTo>) => methodsRef.current.navigateTo(...args),
|
||||
navigateBack: (...args: Parameters<typeof navigateBack>) => methodsRef.current.navigateBack(...args),
|
||||
navigateForward: (...args: Parameters<typeof navigateForward>) => methodsRef.current.navigateForward(...args),
|
||||
navigateUp: (...args: Parameters<typeof navigateUp>) => methodsRef.current.navigateUp(...args),
|
||||
refresh: (...args: Parameters<typeof refresh>) => methodsRef.current.refresh(...args),
|
||||
openEntry: (...args: Parameters<typeof openEntry>) => methodsRef.current.openEntry(...args),
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { JSDOM } from "jsdom";
|
||||
import React, { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
|
||||
import type { KeyBinding, Snippet } from "../../domain/models.ts";
|
||||
import { useSnippetShortkeyRecorder } from "./useSnippetShortkeyRecorder.ts";
|
||||
|
||||
const makeSnippet = (id: string, label: string, shortkey?: string): Snippet => ({
|
||||
id,
|
||||
label,
|
||||
command: `echo ${id}`,
|
||||
tags: [],
|
||||
package: "",
|
||||
targets: [],
|
||||
shortkey,
|
||||
});
|
||||
|
||||
const stubT = (key: string, values?: Record<string, string | number | boolean | null | undefined>) => {
|
||||
if (!values) return key;
|
||||
return `${key}:${JSON.stringify(values)}`;
|
||||
};
|
||||
|
||||
function installDom() {
|
||||
const dom = new JSDOM("<!doctype html><html><body><div id='root'></div></body></html>");
|
||||
const prevWindow = globalThis.window;
|
||||
const prevDocument = globalThis.document;
|
||||
const prevKeyboardEvent = globalThis.KeyboardEvent;
|
||||
const prevNavigator = globalThis.navigator;
|
||||
const env = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const prevAct = env.IS_REACT_ACT_ENVIRONMENT;
|
||||
|
||||
env.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
Object.defineProperty(globalThis, "window", { value: dom.window, configurable: true });
|
||||
Object.defineProperty(globalThis, "document", { value: dom.window.document, configurable: true });
|
||||
Object.defineProperty(globalThis, "KeyboardEvent", { value: dom.window.KeyboardEvent, configurable: true });
|
||||
Object.defineProperty(globalThis, "navigator", { value: dom.window.navigator, configurable: true });
|
||||
|
||||
return {
|
||||
dom,
|
||||
cleanup() {
|
||||
env.IS_REACT_ACT_ENVIRONMENT = prevAct;
|
||||
Object.defineProperty(globalThis, "window", { value: prevWindow, configurable: true });
|
||||
Object.defineProperty(globalThis, "document", { value: prevDocument, configurable: true });
|
||||
Object.defineProperty(globalThis, "KeyboardEvent", { value: prevKeyboardEvent, configurable: true });
|
||||
Object.defineProperty(globalThis, "navigator", { value: prevNavigator, configurable: true });
|
||||
dom.window.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("useSnippetShortkeyRecorder captures valid shortkeys, ignores modifiers, and cancels on Escape", async () => {
|
||||
const { dom, cleanup } = installDom();
|
||||
const captured: string[] = [];
|
||||
let latest!: ReturnType<typeof useSnippetShortkeyRecorder>;
|
||||
|
||||
function Harness() {
|
||||
latest = useSnippetShortkeyRecorder({
|
||||
snippets: [],
|
||||
hotkeyScheme: "pc",
|
||||
keyBindings: [],
|
||||
t: stubT,
|
||||
onCapture: (key) => captured.push(key),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
let root: Root | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
root = createRoot(dom.window.document.getElementById("root")!);
|
||||
root.render(React.createElement(Harness));
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
latest.setIsRecordingShortkey(true);
|
||||
});
|
||||
assert.equal(latest.isRecordingShortkey, true);
|
||||
|
||||
// Modifier-only key press keeps recording active.
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(new dom.window.KeyboardEvent("keydown", { key: "Control", ctrlKey: true, cancelable: true }));
|
||||
});
|
||||
assert.equal(latest.isRecordingShortkey, true);
|
||||
assert.deepEqual(captured, []);
|
||||
|
||||
// Valid shortcut captures and stops recording.
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(new dom.window.KeyboardEvent("keydown", { key: "k", ctrlKey: true, shiftKey: true, cancelable: true }));
|
||||
});
|
||||
assert.equal(latest.isRecordingShortkey, false);
|
||||
assert.equal(latest.shortkeyError, null);
|
||||
assert.deepEqual(captured, ["Ctrl + Shift + K"]);
|
||||
|
||||
// Escape cancels recording and clears error without capturing.
|
||||
await act(async () => {
|
||||
latest.setShortkeyError("some error");
|
||||
latest.setIsRecordingShortkey(true);
|
||||
});
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(new dom.window.KeyboardEvent("keydown", { key: "Escape", cancelable: true }));
|
||||
});
|
||||
assert.equal(latest.isRecordingShortkey, false);
|
||||
assert.equal(latest.shortkeyError, null);
|
||||
assert.deepEqual(captured, ["Ctrl + Shift + K"]);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root?.unmount();
|
||||
});
|
||||
cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("useSnippetShortkeyRecorder reports system and snippet conflicts while ignoring self", async () => {
|
||||
const { dom, cleanup } = installDom();
|
||||
const captured: string[] = [];
|
||||
let latest!: ReturnType<typeof useSnippetShortkeyRecorder>;
|
||||
|
||||
const keyBindings: KeyBinding[] = [
|
||||
{
|
||||
id: "newTab",
|
||||
action: "newTab",
|
||||
label: "New Tab",
|
||||
mac: "\u2318 + T",
|
||||
pc: "Ctrl + T",
|
||||
category: "tabs",
|
||||
},
|
||||
];
|
||||
const snippets: Snippet[] = [
|
||||
makeSnippet("snip-self", "Self Snippet", "Ctrl + Shift + S"),
|
||||
makeSnippet("snip-other", "Other Snippet", "Ctrl + Shift + O"),
|
||||
];
|
||||
|
||||
function Harness() {
|
||||
latest = useSnippetShortkeyRecorder({
|
||||
snippets,
|
||||
editingSnippetId: "snip-self",
|
||||
hotkeyScheme: "pc",
|
||||
keyBindings,
|
||||
t: stubT,
|
||||
onCapture: (key) => captured.push(key),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
let root: Root | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
root = createRoot(dom.window.document.getElementById("root")!);
|
||||
root.render(React.createElement(Harness));
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
latest.setIsRecordingShortkey(true);
|
||||
});
|
||||
|
||||
// Conflicts with system binding.
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(new dom.window.KeyboardEvent("keydown", { key: "t", ctrlKey: true, cancelable: true }));
|
||||
});
|
||||
assert.equal(latest.isRecordingShortkey, true);
|
||||
assert.match(latest.shortkeyError ?? "", /snippets\.shortkey\.error\.systemConflict/);
|
||||
assert.match(latest.shortkeyError ?? "", /New Tab/);
|
||||
|
||||
// Conflicts with another snippet.
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(new dom.window.KeyboardEvent("keydown", { key: "o", ctrlKey: true, shiftKey: true, cancelable: true }));
|
||||
});
|
||||
assert.equal(latest.isRecordingShortkey, true);
|
||||
assert.match(latest.shortkeyError ?? "", /snippets\.shortkey\.error\.snippetConflict/);
|
||||
assert.match(latest.shortkeyError ?? "", /Other Snippet/);
|
||||
|
||||
// Same shortcut as currently edited snippet is allowed.
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(new dom.window.KeyboardEvent("keydown", { key: "s", ctrlKey: true, shiftKey: true, cancelable: true }));
|
||||
});
|
||||
assert.equal(latest.isRecordingShortkey, false);
|
||||
assert.equal(latest.shortkeyError, null);
|
||||
assert.deepEqual(captured, ["Ctrl + Shift + S"]);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root?.unmount();
|
||||
});
|
||||
cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("useSnippetShortkeyRecorder ignores keydowns while app lock overlay is active", async () => {
|
||||
const { dom, cleanup } = installDom();
|
||||
const captured: string[] = [];
|
||||
let latest!: ReturnType<typeof useSnippetShortkeyRecorder>;
|
||||
|
||||
function Harness() {
|
||||
latest = useSnippetShortkeyRecorder({
|
||||
snippets: [],
|
||||
hotkeyScheme: "pc",
|
||||
keyBindings: [],
|
||||
t: stubT,
|
||||
onCapture: (key) => captured.push(key),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
let root: Root | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
root = createRoot(dom.window.document.getElementById("root")!);
|
||||
root.render(React.createElement(Harness));
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
latest.setIsRecordingShortkey(true);
|
||||
});
|
||||
|
||||
const lockOverlay = dom.window.document.createElement("div");
|
||||
lockOverlay.setAttribute("data-app-lock-overlay", "true");
|
||||
dom.window.document.body.appendChild(lockOverlay);
|
||||
|
||||
const lockedEvent = new dom.window.KeyboardEvent("keydown", {
|
||||
key: "p",
|
||||
ctrlKey: true,
|
||||
cancelable: true,
|
||||
});
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(lockedEvent);
|
||||
});
|
||||
assert.equal(lockedEvent.defaultPrevented, false);
|
||||
assert.equal(latest.isRecordingShortkey, true);
|
||||
assert.deepEqual(captured, []);
|
||||
|
||||
// Removing the lock overlay restores normal capture.
|
||||
lockOverlay.remove();
|
||||
const unlockedEvent = new dom.window.KeyboardEvent("keydown", {
|
||||
key: "p",
|
||||
ctrlKey: true,
|
||||
cancelable: true,
|
||||
});
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(unlockedEvent);
|
||||
});
|
||||
assert.equal(unlockedEvent.defaultPrevented, true);
|
||||
assert.equal(latest.isRecordingShortkey, false);
|
||||
assert.deepEqual(captured, ["Ctrl + P"]);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root?.unmount();
|
||||
});
|
||||
cleanup();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { I18nContextValue } from '../i18n/I18nProvider';
|
||||
import { findActiveSystemShortcutConflict } from '../../domain/activeKeyBindings';
|
||||
import {
|
||||
type HotkeyScheme,
|
||||
type KeyBinding,
|
||||
type Snippet,
|
||||
keyEventToString,
|
||||
keyStringToKeyboardEvent,
|
||||
matchesKeyBinding,
|
||||
} from '../../domain/models';
|
||||
import { isAppLockOverlayActive } from '../../infrastructure/appLockOverlayDom';
|
||||
import { isMacPlatform } from '../../lib/utils';
|
||||
|
||||
const normalizeKeyString = (value: string): string => (
|
||||
value.toLowerCase().replace(/\s+/g, '')
|
||||
);
|
||||
|
||||
export interface UseSnippetShortkeyRecorderOptions {
|
||||
snippets: Snippet[];
|
||||
editingSnippetId?: string;
|
||||
hotkeyScheme: HotkeyScheme;
|
||||
keyBindings: KeyBinding[];
|
||||
t: I18nContextValue['t'];
|
||||
onCapture: (shortkey: string) => void;
|
||||
}
|
||||
|
||||
export function useSnippetShortkeyRecorder({
|
||||
snippets,
|
||||
editingSnippetId,
|
||||
hotkeyScheme,
|
||||
keyBindings,
|
||||
t,
|
||||
onCapture,
|
||||
}: UseSnippetShortkeyRecorderOptions) {
|
||||
const [isRecordingShortkey, setIsRecordingShortkey] = useState(false);
|
||||
const [shortkeyError, setShortkeyError] = useState<string | null>(null);
|
||||
const onCaptureRef = useRef(onCapture);
|
||||
onCaptureRef.current = onCapture;
|
||||
|
||||
const isMac = useMemo(() => (
|
||||
hotkeyScheme === 'mac' || (hotkeyScheme === 'disabled' && isMacPlatform())
|
||||
), [hotkeyScheme]);
|
||||
|
||||
const existingShortkeys = useMemo(() => (
|
||||
snippets.filter((snippet) => Boolean(snippet.shortkey) && snippet.id !== editingSnippetId)
|
||||
), [snippets, editingSnippetId]);
|
||||
|
||||
const validateShortkey = useCallback((key: string): string | null => {
|
||||
if (!key) return null;
|
||||
|
||||
const systemConflict = findActiveSystemShortcutConflict(key, hotkeyScheme, keyBindings);
|
||||
if (systemConflict) {
|
||||
const nameKey = `settings.shortcuts.binding.${systemConflict.id}`;
|
||||
const name = t(nameKey) !== nameKey ? t(nameKey) : systemConflict.label;
|
||||
return t('snippets.shortkey.error.systemConflict', { name });
|
||||
}
|
||||
|
||||
const syntheticEvent = keyStringToKeyboardEvent(key);
|
||||
if (syntheticEvent) {
|
||||
for (const snippet of existingShortkeys) {
|
||||
if (snippet.shortkey && matchesKeyBinding(syntheticEvent, snippet.shortkey, isMac)) {
|
||||
return t('snippets.shortkey.error.snippetConflict', { name: snippet.label });
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const normalizedKey = normalizeKeyString(key);
|
||||
const conflictingSnippet = existingShortkeys.find((snippet) => (
|
||||
snippet.shortkey && normalizeKeyString(snippet.shortkey) === normalizedKey
|
||||
));
|
||||
if (conflictingSnippet) {
|
||||
return t('snippets.shortkey.error.snippetConflict', { name: conflictingSnippet.label });
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}, [existingShortkeys, hotkeyScheme, isMac, keyBindings, t]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isRecordingShortkey) return;
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
// App lock overlay installs later; skip while locked so password keys
|
||||
// never mutate shortkeys (Codex P2).
|
||||
if (isAppLockOverlayActive()) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
if (e.key === 'Escape') {
|
||||
setIsRecordingShortkey(false);
|
||||
setShortkeyError(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (['Meta', 'Control', 'Alt', 'Shift'].includes(e.key)) return;
|
||||
|
||||
const keyString = keyEventToString(e, isMac);
|
||||
const error = validateShortkey(keyString);
|
||||
if (error) {
|
||||
setShortkeyError(error);
|
||||
return;
|
||||
}
|
||||
|
||||
setShortkeyError(null);
|
||||
onCaptureRef.current(keyString);
|
||||
setIsRecordingShortkey(false);
|
||||
};
|
||||
|
||||
const handleClick = () => {
|
||||
setIsRecordingShortkey(false);
|
||||
setShortkeyError(null);
|
||||
};
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
window.addEventListener('click', handleClick, true);
|
||||
}, 100);
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown, true);
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
window.removeEventListener('keydown', handleKeyDown, true);
|
||||
window.removeEventListener('click', handleClick, true);
|
||||
};
|
||||
}, [isRecordingShortkey, isMac, validateShortkey]);
|
||||
|
||||
return {
|
||||
isRecordingShortkey,
|
||||
setIsRecordingShortkey,
|
||||
shortkeyError,
|
||||
setShortkeyError,
|
||||
validateShortkey,
|
||||
};
|
||||
}
|
||||
@@ -419,7 +419,7 @@ export const useTerminalBackend = () => {
|
||||
return bridge.getTelnetEchoMode(sessionId);
|
||||
}, []);
|
||||
|
||||
const onChainProgress = useCallback((cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string) => void) => {
|
||||
const onChainProgress = useCallback((cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string, address?: string) => void) => {
|
||||
const bridge = netcattyBridge.get();
|
||||
return bridge?.onChainProgress?.(cb);
|
||||
}, []);
|
||||
|
||||
@@ -67,19 +67,28 @@ for (const platform of ['linux', 'darwin']) {
|
||||
});
|
||||
}
|
||||
|
||||
test('Windows native PowerShell registers a Win32 controller without enabling CMD or POSIX wrappers', async t => {
|
||||
test('Windows native shells register independent Win32 controllers alongside a Bash session', async t => {
|
||||
installBridge(t, async () => ({ name: 'Netcatty', version: 'test', platform: 'win32' }));
|
||||
function Harness() {
|
||||
function NativeShells() {
|
||||
useTerminalDirectorySession(options('native-powershell', 'local', 'powershell'));
|
||||
useTerminalDirectorySession(options('native-cmd', 'local', 'cmd'));
|
||||
return null;
|
||||
}
|
||||
function Harness({ showNative }: { showNative: boolean }) {
|
||||
const props = options('first-bash');
|
||||
props.host = { ...props.host, localShell: 'git-bash' };
|
||||
useTerminalDirectorySession(props);
|
||||
return showNative ? React.createElement(NativeShells) : null;
|
||||
}
|
||||
let root!: ReactTestRenderer;
|
||||
await act(async () => { root = create(React.createElement(Harness)); });
|
||||
await act(async () => { root = create(React.createElement(Harness, { showNative: false })); });
|
||||
t.after(async () => { await act(async () => { root.unmount(); }); });
|
||||
await act(async () => { root.update(React.createElement(Harness, { showNative: true })); });
|
||||
assert.equal(getTerminalDirectory('first-bash'), null);
|
||||
assert.equal(getTerminalDirectory('native-powershell')?.target.pathFlavor, 'win32');
|
||||
assert.equal(getTerminalDirectory('native-powershell')?.target.authority, 'local:native-powershell');
|
||||
assert.equal(getTerminalDirectory('native-cmd'), null);
|
||||
assert.equal(getTerminalDirectory('native-cmd')?.target.pathFlavor, 'win32');
|
||||
assert.equal(getTerminalDirectory('native-cmd')?.target.authority, 'local:native-cmd');
|
||||
});
|
||||
|
||||
test('Windows SSH sessions do not inherit the local cwd platform limitation', async t => {
|
||||
|
||||
@@ -21,8 +21,9 @@ export function useTerminalDirectorySession(options: {
|
||||
live.current = options;
|
||||
const { sessionId, status, shellType, host } = options;
|
||||
const local = host.protocol === 'local';
|
||||
const windowsShell = shellType === 'powershell' || shellType === 'cmd' ? shellType : undefined;
|
||||
const supported = (local || ((host.protocol ?? 'ssh') === 'ssh' && !host.moshEnabled && !host.etEnabled))
|
||||
&& (shellType !== 'powershell' || local) && shellType !== 'cmd'
|
||||
&& (!windowsShell || local)
|
||||
&& host.deviceType !== 'network' && classifyDistroId(host.distro) !== 'network-device'
|
||||
&& !hostRestrictsExtraSshChannels(host);
|
||||
useEffect(() => {
|
||||
@@ -40,10 +41,11 @@ export function useTerminalDirectorySession(options: {
|
||||
local, hostname: host.hostname, username: host.username || 'root', port: host.port,
|
||||
encoding: host.sftpEncoding,
|
||||
pathFlavor,
|
||||
windowsShell,
|
||||
}, isCurrent),
|
||||
target: { authority: `${local ? 'local' : 'ssh'}:${backendId}`, pathFlavor },
|
||||
capabilities: COMPLETE_DIRECTORY_CAPABILITIES,
|
||||
buildChangeCommand: path => directoryChangeCommand(path, pathFlavor === 'win32' ? 'powershell' : 'posix', pathFlavor),
|
||||
buildChangeCommand: path => directoryChangeCommand(path, windowsShell ?? 'posix', pathFlavor),
|
||||
isCurrent,
|
||||
isReady: () => live.current.isReady(),
|
||||
publish: cwd => live.current.publish(cwd),
|
||||
@@ -54,10 +56,10 @@ export function useTerminalDirectorySession(options: {
|
||||
// POSIX wrappers on Windows still use win32 PTYs. Neither their cwd nor
|
||||
// their path namespace is supported by readLocalSessionCwd/local FS.
|
||||
void bridge.getAppInfo?.().then(info => {
|
||||
if ((info.platform === 'darwin' || info.platform === 'linux') && shellType !== 'powershell') register();
|
||||
else if (info.platform === 'win32' && shellType === 'powershell') register('win32');
|
||||
if ((info.platform === 'darwin' || info.platform === 'linux') && !windowsShell) register();
|
||||
else if (info.platform === 'win32' && windowsShell) register('win32');
|
||||
}).catch(() => {});
|
||||
} else register();
|
||||
return () => { active = false; unregister(); };
|
||||
}, [sessionId, status, supported, local, host.hostname, host.username, host.port, host.sftpEncoding, shellType]);
|
||||
}, [sessionId, status, supported, local, host.hostname, host.username, host.port, host.sftpEncoding, windowsShell]);
|
||||
}
|
||||
Loaded 100 of 561 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user