mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-05 14:03:01 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f42e870e74 | ||
|
|
24c2e6beff | ||
|
|
c59ea270e2 | ||
|
|
9b29c115df | ||
|
|
4eceeda4b7 | ||
|
|
c357d14181 | ||
|
|
e7ade527ee | ||
|
|
54c4db5030 | ||
|
|
e17d7f01b6 | ||
|
|
5098f53944 | ||
|
|
c1df8a6011 | ||
|
|
a8bb5a43fc | ||
|
|
b87360783a | ||
|
|
dc5fcfbc19 | ||
|
|
fcfba34fc1 | ||
|
|
fa554888a6 | ||
|
|
d56150953d | ||
|
|
1b9c744fda | ||
|
|
2318434ac9 | ||
|
|
dcf558e685 | ||
|
|
7683874a4e | ||
|
|
3ac24f7aa2 | ||
|
|
79a6e14f7d | ||
|
|
8043178d54 | ||
|
|
9fb2a5c8c9 | ||
|
|
70ce1258f9 | ||
|
|
c01d057a7d | ||
|
|
cd6e1c6990 | ||
|
|
42c69902e8 | ||
|
|
780d297591 | ||
|
|
b496b00d2f | ||
|
|
a8c69b8e11 | ||
|
|
6d687d570f | ||
|
|
a2f23054df | ||
|
|
0fe069e575 | ||
|
|
1809b7dc02 | ||
|
|
d5a03606b7 | ||
|
|
7cd57adcea | ||
|
|
7d5d234fdd | ||
|
|
eb56936e9b | ||
|
|
6da42ebc53 | ||
|
|
f0483488e1 | ||
|
|
263133f2ea | ||
|
|
887c5779b5 | ||
|
|
27f26d8e69 | ||
|
|
30a74f7c1d | ||
|
|
631d04b654 | ||
|
|
e98e236d54 | ||
|
|
1e063dfa3c | ||
|
|
8b5b0c4416 | ||
|
|
afb0585016 | ||
|
|
6d65c89ecf | ||
|
|
2f214b8725 | ||
|
|
350917fa0e | ||
|
|
fb691318c4 | ||
|
|
9c1af5c73f | ||
|
|
555f193d23 | ||
|
|
88dd20a918 |
No files matched your search
@@ -170,3 +170,6 @@ build_with_vs2022.bat
|
||||
/resources/et/*/et.exe
|
||||
/resources/et/*/et-*-dlls/
|
||||
/resources/et/*/*.dll
|
||||
|
||||
# Local plugin example staging and bundles
|
||||
/examples/plugins/*/.package/
|
||||
@@ -127,6 +127,11 @@ second private RPC shape when extending the host.
|
||||
- `PluginRpcRouter` owns correlation, cancellation, deadlines, stream credit and
|
||||
protocol-failure containment. Runtime identity is assigned by the host and is
|
||||
never accepted from request parameters.
|
||||
- Custom views use only host-rendered DOM: plugin scripts stay in the isolated
|
||||
runtime; the host validates incoming trees, styles, resources and events before
|
||||
rendering. Never reintroduce native child views, iframe UI, or plugin code in
|
||||
the host renderer. See `docs/plugin-platform/host-rendered-ui.md` for authoring,
|
||||
lifecycle, limits and verification.
|
||||
- App quit goes through `runPluginShutdown()` after the dirty-editor guard; do
|
||||
not add another independent quit interception path.
|
||||
|
||||
|
||||
@@ -50,6 +50,9 @@ function SettingsI18nProvider({ children }: { children: React.ReactNode }) {
|
||||
* shell bags; AppSideEffects owns reactive effects + local UI publishing.
|
||||
*/
|
||||
function App() {
|
||||
useEffect(() => {
|
||||
performance.mark('netcatty:renderer:app-mounted');
|
||||
}, []);
|
||||
return (
|
||||
<AppLocalStateProvider>
|
||||
<MonitorRuntimeHost />
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { handleCreateLocalTerminalImpl } from './AppHandlers';
|
||||
|
||||
type CreatedLocal = {
|
||||
shell?: string;
|
||||
shellArgs?: string[];
|
||||
shellName?: string;
|
||||
shellIcon?: string;
|
||||
localStartDir?: string;
|
||||
shellType?: string;
|
||||
};
|
||||
|
||||
function createCtx(overrides?: {
|
||||
localShell?: string;
|
||||
localShellArgs?: string[];
|
||||
discoveredShells?: Array<{ id: string; name: string; command: string; args?: string[]; icon?: string }>;
|
||||
}) {
|
||||
const created: CreatedLocal[] = [];
|
||||
const logs: Array<{ hostLabel: string }> = [];
|
||||
const localShell = overrides?.localShell ?? '';
|
||||
const localShellArgs = overrides?.localShellArgs ?? [];
|
||||
const discoveredShells = overrides?.discoveredShells ?? [];
|
||||
const getCtx = () => ({
|
||||
addConnectionLog: (entry: { hostLabel: string }) => {
|
||||
logs.push(entry);
|
||||
},
|
||||
classifyLocalShellType: () => 'unknown',
|
||||
createLocalTerminal: (options: CreatedLocal) => {
|
||||
created.push(options);
|
||||
return 'session-1';
|
||||
},
|
||||
discoveredShells,
|
||||
resolveShellSetting: (
|
||||
value: string,
|
||||
shells: Array<{ id: string; command: string; args?: string[] }>,
|
||||
customArgs?: string[],
|
||||
) => {
|
||||
if (!value) return null;
|
||||
const match = shells.find((shell) => shell.id === value);
|
||||
if (match) {
|
||||
return { command: match.command, args: customArgs?.length ? customArgs : match.args };
|
||||
}
|
||||
return { command: value, args: customArgs?.length ? customArgs : undefined };
|
||||
},
|
||||
systemInfoRef: { current: { username: 'qi', hostname: 'box' } },
|
||||
terminalSettings: { localShell, localShellArgs },
|
||||
});
|
||||
return { getCtx, created, logs };
|
||||
}
|
||||
|
||||
test('create local terminal resolves Settings custom absolute path when no shell arg is passed', () => {
|
||||
const custom = String.raw`C:\Users\lybing\AppData\Local\Programs\nu\bin\nu.exe`;
|
||||
const { getCtx, created } = createCtx({ localShell: custom });
|
||||
handleCreateLocalTerminalImpl(getCtx as never);
|
||||
assert.equal(created.length, 1);
|
||||
assert.equal(created[0].shell, custom);
|
||||
});
|
||||
|
||||
test('create local terminal ignores MouseEvent-like first args and still uses Settings shell (#4085)', () => {
|
||||
const custom = String.raw`C:\Users\lybing\AppData\Local\Programs\nu\bin\nu.exe`;
|
||||
const { getCtx, created } = createCtx({ localShell: custom });
|
||||
// Vault header historically used onClick={handleCreateLocalTerminal}, so React
|
||||
// passes the click event as the first argument.
|
||||
const fakeClickEvent = { type: 'click', target: {}, preventDefault() {} };
|
||||
handleCreateLocalTerminalImpl(getCtx as never, fakeClickEvent as never);
|
||||
assert.equal(created.length, 1);
|
||||
assert.equal(created[0].shell, custom);
|
||||
});
|
||||
|
||||
test('create local terminal still honors an explicit shell object', () => {
|
||||
const { getCtx, created } = createCtx({ localShell: 'pwsh' });
|
||||
handleCreateLocalTerminalImpl(getCtx as never, {
|
||||
command: String.raw`D:\portable\zsh\zsh.exe`,
|
||||
args: ['-l'],
|
||||
name: 'Portable Zsh',
|
||||
icon: 'zsh',
|
||||
});
|
||||
assert.equal(created.length, 1);
|
||||
assert.equal(created[0].shell, String.raw`D:\portable\zsh\zsh.exe`);
|
||||
assert.deepEqual(created[0].shellArgs, ['-l']);
|
||||
assert.equal(created[0].shellName, 'Portable Zsh');
|
||||
assert.equal(created[0].shellIcon, 'zsh');
|
||||
});
|
||||
@@ -16,6 +16,7 @@ import { isPortForwardingAutoReconnectEnabled } from '../../domain/portForwardin
|
||||
import { buildNumberShortcutTabTargets } from './tabShortcutTargets';
|
||||
import { captureInheritedCwd } from '../state/inheritedCwd';
|
||||
import { fromEditorTabId, isEditorTabId } from '../state/activeTabStore';
|
||||
import { isPluginViewEditingTarget } from '../state/pluginKeybindings';
|
||||
import { resolveBatchTabCloseFocus } from '../state/pluginViewTabStore';
|
||||
|
||||
type AppContextGetter = () => Record<string, any>;
|
||||
@@ -264,7 +265,7 @@ export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: Keybo
|
||||
}
|
||||
}
|
||||
|
||||
const isFormElement = target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable;
|
||||
const isFormElement = target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable || isPluginViewEditingTarget(target);
|
||||
const isMonacoElement =
|
||||
target instanceof HTMLElement &&
|
||||
!!target.closest?.('.monaco-editor, .monaco-diff-editor, .monaco-inputbox');
|
||||
@@ -1137,11 +1138,18 @@ export function handleCreateLocalTerminalImpl(
|
||||
const { addConnectionLog, classifyLocalShellType, createLocalTerminal, discoveredShells, resolveShellSetting, systemInfoRef, terminalSettings } = getCtx();
|
||||
{
|
||||
const { username, hostname } = systemInfoRef.current;
|
||||
const resolved = shell ?? resolveShellSetting(terminalSettings.localShell, discoveredShells, terminalSettings.localShellArgs);
|
||||
// Vault/header buttons historically wired `onClick={handleCreateLocalTerminal}`.
|
||||
// React then passes the MouseEvent as the first arg; treat only real shell
|
||||
// objects (string command) as explicit so Settings localShell still applies (#4085).
|
||||
const explicitShell = shell && typeof shell.command === 'string' ? shell : undefined;
|
||||
const resolved = explicitShell
|
||||
?? resolveShellSetting(terminalSettings.localShell, discoveredShells, terminalSettings.localShellArgs);
|
||||
// Match by ID (not command) to avoid WSL distros all sharing wsl.exe
|
||||
const matchedShell = !shell ? discoveredShells.find(s => s.id === terminalSettings.localShell) : undefined;
|
||||
const shellName = shell?.name ?? matchedShell?.name;
|
||||
const shellIcon = shell?.icon ?? matchedShell?.icon;
|
||||
const matchedShell = !explicitShell
|
||||
? discoveredShells.find(s => s.id === terminalSettings.localShell)
|
||||
: undefined;
|
||||
const shellName = explicitShell?.name ?? matchedShell?.name;
|
||||
const shellIcon = explicitShell?.icon ?? matchedShell?.icon;
|
||||
const sessionId = createLocalTerminal({
|
||||
shellType: classifyLocalShellType(resolved?.command || terminalSettings.localShell, navigator.userAgent),
|
||||
shell: resolved?.command,
|
||||
@@ -1271,16 +1279,14 @@ export function hasMultipleProtocolsImpl(getCtx: AppContextGetter, host: Host) {
|
||||
}
|
||||
|
||||
export function handleHostConnectWithProtocolCheckImpl(getCtx: AppContextGetter, host: Host) {
|
||||
const { handleConnectToHost, hasMultipleProtocols, resolveEffectiveHost, setIsQuickSwitcherOpen, setProtocolSelectHost, setQuickSearch } = getCtx();
|
||||
const { handleConnectToHost, hasMultipleProtocols, resolveEffectiveHost, setIsQuickSwitcherOpen, setProtocolSelectHost } = getCtx();
|
||||
{
|
||||
if (hasMultipleProtocols(host)) {
|
||||
setProtocolSelectHost(resolveEffectiveHost(host));
|
||||
setIsQuickSwitcherOpen(false);
|
||||
setQuickSearch('');
|
||||
} else {
|
||||
handleConnectToHost(host);
|
||||
setIsQuickSwitcherOpen(false);
|
||||
setQuickSearch('');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,12 +139,21 @@ test('ChromeHost builds from chrome settings + session/vault snapshots', () => {
|
||||
assert.doesNotMatch(source, /\buseAppSettingsRuntime\s*\(/);
|
||||
});
|
||||
|
||||
test('DialogsHost builds from local dialog state + selective vault snapshot', () => {
|
||||
test('DialogsHost builds from local dialog state without vault runtime hooks', () => {
|
||||
const source = hostSources['DialogsHost.tsx'];
|
||||
assert.ok(source, 'application/app/hosts/DialogsHost.tsx must exist');
|
||||
assert.match(source, /useVaultSnapshot|useVaultSnapshotField|getVaultSnapshot/);
|
||||
assert.doesNotMatch(source, /\buseVaultState\s*\(/);
|
||||
assert.doesNotMatch(source, /\buseAppVaultRuntime\s*\(/);
|
||||
// Quick switcher search is owned by QuickSwitcherOverlay; republishing the
|
||||
// dialogs bag per keystroke re-rendered the whole shell.
|
||||
assert.doesNotMatch(source, /quickSearch|getHostSearchMatch/);
|
||||
});
|
||||
|
||||
test('QuickSwitcherOverlay owns the quick switcher query', () => {
|
||||
const overlay = readFileSync(join(here, 'QuickSwitcherOverlay.tsx'), 'utf8');
|
||||
assert.match(overlay, /useState\(''\)/);
|
||||
const store = readFileSync(join(here, 'appLocalUiStore.ts'), 'utf8');
|
||||
assert.doesNotMatch(store, /quickSearch/);
|
||||
});
|
||||
|
||||
test('AppSideEffects may use runtime hooks; App must not', () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useCallback, useEffect, useEffectEvent, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import { registerAppHandlers } from './appHandlersBridge';
|
||||
import { registerAppHandlers, stabilizeAppHandlers, type StableAppHandlerCache } from './appHandlersBridge';
|
||||
import { publishAppLocalUi } from './appLocalUiStore';
|
||||
import { activeTabStore, toEditorTabId, fromEditorTabId, isEditorTabId } from '../state/activeTabStore';
|
||||
import { useAutoSync } from '../state/useAutoSync';
|
||||
@@ -19,6 +19,8 @@ import {
|
||||
} from '../state/connectionLogsStore';
|
||||
import { getNotesSnapshot } from '../state/notesStore';
|
||||
import { useVaultAgentBridge } from '../state/useVaultAgentBridge';
|
||||
import { terminalReconnectRegistry } from '../state/terminalReconnectRegistry';
|
||||
import { requestAgentSessionReconnect } from '../state/agentSessionReconnect';
|
||||
import { useWindowControls } from '../state/useWindowControls';
|
||||
import { useTerminalKeyboardFocus } from '../state/useTerminalKeyboardFocus';
|
||||
import { editorTabStore, useEditorTabChromeList } from '../state/editorTabStore';
|
||||
@@ -59,6 +61,7 @@ import { collectSessionIds } from '../../domain/workspace';
|
||||
import { resolveAgentHostWorkspace } from '../../domain/agentHostWorkspace';
|
||||
import { useHostOpenSessionReuse } from '../state/useHostOpenSessionReuse';
|
||||
import type { PaneMagnificationController } from '../../domain/paneMagnification';
|
||||
import { isPluginViewEditingTarget } from '../state/pluginKeybindings';
|
||||
import { resolveCloseIntent } from '../state/resolveCloseIntent';
|
||||
import { resolveSnippetsShortcutIntent } from '../state/resolveSnippetsShortcutIntent';
|
||||
import { isPrimaryModifierWBinding, resolveWindowCommandCloseIntent } from '../state/windowCommandClose';
|
||||
@@ -133,7 +136,6 @@ export function AppSideEffects() {
|
||||
| { mode: 'create' }
|
||||
| null
|
||||
>(null);
|
||||
const [quickSearch, setQuickSearch] = useState('');
|
||||
// Protocol selection dialog state for QuickSwitcher
|
||||
const [protocolSelectHost, setProtocolSelectHost] = useState<Host | null>(null);
|
||||
// Navigation state for VaultView sections
|
||||
@@ -1156,6 +1158,8 @@ export function AppSideEffects() {
|
||||
const topmostOpenDialog = openDialogs[openDialogs.length - 1] ?? null;
|
||||
const topmostDialogClose = topmostOpenDialog?.querySelector<HTMLElement>('[data-dialog-close="true"]');
|
||||
|
||||
if (!topmostDialogClose && isPluginViewEditingTarget(document.activeElement)) return;
|
||||
|
||||
const intent = resolveWindowCommandCloseIntent({
|
||||
activeTabId: activeTabStore.getActiveTabId(),
|
||||
editorTabIds: editorTabs.map((tab) => toEditorTabId(tab.id)),
|
||||
@@ -1524,6 +1528,19 @@ export function AppSideEffects() {
|
||||
sessions, hosts, keys, identities, resolveEffectiveHost,
|
||||
});
|
||||
|
||||
const reconnectSessionForVaultAgent = useCallback((sessionId: string) => {
|
||||
const session = sessions.find((entry) => entry.id === sessionId);
|
||||
return requestAgentSessionReconnect(sessionId, session?.status, terminalReconnectRegistry);
|
||||
}, [sessions]);
|
||||
|
||||
const inspectSessionRecoveryForVaultAgent = useCallback((sessionId: string) => {
|
||||
const session = sessions.find((entry) => entry.id === sessionId);
|
||||
if (!session) return { ok: false, error: `Session "${sessionId}" was not found.` };
|
||||
const live = terminalReconnectRegistry.inspect(sessionId);
|
||||
return { ok: true, sessionId, status: session.status, waitingForInput: false,
|
||||
reconnecting: false, reconnectAllowed: false, ...live };
|
||||
}, [sessions]);
|
||||
|
||||
const closeSessionForVaultAgent = useCallback((sessionId: string) => {
|
||||
if (!sessions.some((session) => session.id === sessionId)) {
|
||||
return { ok: false as const, error: `Session "${sessionId}" was not found.` };
|
||||
@@ -1568,6 +1585,8 @@ export function AppSideEffects() {
|
||||
openHost: openHostForVaultAgent,
|
||||
findExistingSessionForHost: findExistingSessionForHostForVaultAgent,
|
||||
closeSession: closeSessionForVaultAgent,
|
||||
reconnectSession: reconnectSessionForVaultAgent,
|
||||
inspectSessionRecovery: inspectSessionRecoveryForVaultAgent,
|
||||
getScriptSessionMeta: (sessionId) => sessions.find((session) => session.id === sessionId),
|
||||
});
|
||||
|
||||
@@ -1944,7 +1963,7 @@ export function AppSideEffects() {
|
||||
const hasMultipleProtocols = useCallback((host: Host) => { return hasMultipleProtocolsImpl(() => ({ host, resolveEffectiveHost }), host); }, [resolveEffectiveHost]);
|
||||
|
||||
// Handle host connect with protocol selection (used by QuickSwitcher)
|
||||
const handleHostConnectWithProtocolCheck = useCallback((host: Host) => { return handleHostConnectWithProtocolCheckImpl(() => ({ handleConnectToHost, hasMultipleProtocols, host, resolveEffectiveHost, setIsQuickSwitcherOpen, setProtocolSelectHost, setQuickSearch }), host); }, [hasMultipleProtocols, handleConnectToHost, resolveEffectiveHost]);
|
||||
const handleHostConnectWithProtocolCheck = useCallback((host: Host) => { return handleHostConnectWithProtocolCheckImpl(() => ({ handleConnectToHost, hasMultipleProtocols, host, resolveEffectiveHost, setIsQuickSwitcherOpen, setProtocolSelectHost }), host); }, [hasMultipleProtocols, handleConnectToHost, resolveEffectiveHost]);
|
||||
|
||||
// Handle protocol selection from dialog
|
||||
const handleProtocolSelect = useCallback((protocol: HostProtocol, port: number) => { return handleProtocolSelectImpl(() => ({ handleConnectToHost, port, protocol, protocolSelectHost, setProtocolSelectHost }), protocol, port); }, [protocolSelectHost, handleConnectToHost]);
|
||||
@@ -2012,8 +2031,11 @@ export function AppSideEffects() {
|
||||
|
||||
// Hosts assemble domain bags from stores + this flat glue. Do NOT register
|
||||
// catalog arrays or prepared vault/terminal/chrome/dialogs domain bags here.
|
||||
// Handlers are registered behind stable per-key wrappers so session/host
|
||||
// churn does not re-notify every Host (see stabilizeAppHandlers).
|
||||
const appHandlerCacheRef = useRef<StableAppHandlerCache>(new Map());
|
||||
useLayoutEffect(() => {
|
||||
registerAppHandlers({
|
||||
registerAppHandlers(stabilizeAppHandlers(appHandlerCacheRef.current, {
|
||||
// Vault glue
|
||||
handleAddKnownHost,
|
||||
handleDeleteHost,
|
||||
@@ -2073,15 +2095,13 @@ export function AppSideEffects() {
|
||||
setIsCreateWorkspaceOpen,
|
||||
setIsQuickSwitcherOpen,
|
||||
setProtocolSelectHost,
|
||||
setQuickSearch,
|
||||
handleCancelDeleteHost,
|
||||
handleConfirmDeleteHost,
|
||||
});
|
||||
}));
|
||||
publishAppLocalUi({
|
||||
isQuickSwitcherOpen,
|
||||
isCreateWorkspaceOpen,
|
||||
addToWorkspaceDialog,
|
||||
quickSearch,
|
||||
protocolSelectHost,
|
||||
navigateToSection,
|
||||
deepLinkHostDraft,
|
||||
@@ -2147,7 +2167,6 @@ export function AppSideEffects() {
|
||||
isQuickSwitcherOpen,
|
||||
isCreateWorkspaceOpen,
|
||||
addToWorkspaceDialog,
|
||||
quickSearch,
|
||||
protocolSelectHost,
|
||||
navigateToSection,
|
||||
deepLinkHostDraft,
|
||||
|
||||
+51
-54
@@ -46,6 +46,7 @@ import { getAvailablePaneMagnificationController } from '../../domain/paneMagnif
|
||||
import { pluginViewTabStore, usePluginViewTabs } from '../state/pluginViewTabStore';
|
||||
import { buildPluginSettingScopeCatalog } from '../state/usePluginSettingScopeCatalog';
|
||||
import { useWorkSurfaceHostEditor } from '../state/useWorkSurfaceHostEditor';
|
||||
import { QuickSwitcherOverlay } from './QuickSwitcherOverlay';
|
||||
import {
|
||||
appViewDomainsEqual,
|
||||
mergeAppViewDomains,
|
||||
@@ -53,9 +54,6 @@ import {
|
||||
} from './appViewDomains';
|
||||
|
||||
const LazyProtocolSelectDialog = lazy(() => import('../../components/ProtocolSelectDialog'));
|
||||
const LazyQuickSwitcher = lazy(() =>
|
||||
import('../../components/QuickSwitcher').then((m) => ({ default: m.QuickSwitcher })),
|
||||
);
|
||||
const LazyCreateWorkspaceDialog = lazy(() =>
|
||||
import('../../components/CreateWorkspaceDialog').then((m) => ({ default: m.CreateWorkspaceDialog })),
|
||||
);
|
||||
@@ -63,6 +61,9 @@ const LazyTextEditorTabView = lazy(() =>
|
||||
import('../../components/editor/TextEditorTabView').then((m) => ({ default: m.TextEditorTabView })),
|
||||
);
|
||||
|
||||
// Module-level so TopTabs' memo comparator sees a stable callback.
|
||||
const focusEditorWindowTab = (id: string) => { void focusEditorInWindow(id); };
|
||||
|
||||
const TextEditorTabFallback = ({ tabId }: { tabId: string }) => {
|
||||
const isVisible = useIsEditorTabActive(tabId);
|
||||
const hostTreeLayoutWidth = useTerminalHostTreeLayoutWidth();
|
||||
@@ -242,12 +243,10 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
setIsCreateWorkspaceOpen,
|
||||
setIsQuickSwitcherOpen,
|
||||
setProtocolSelectHost,
|
||||
setQuickSearch,
|
||||
} = ctx;
|
||||
|
||||
const dismissTransientOverlays = useCallback(() => {
|
||||
setIsQuickSwitcherOpen(false);
|
||||
setQuickSearch('');
|
||||
setIsCreateWorkspaceOpen(false);
|
||||
setProtocolSelectHost(null);
|
||||
setAddToWorkspaceDialog(null);
|
||||
@@ -260,7 +259,6 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
setIsCreateWorkspaceOpen,
|
||||
setIsQuickSwitcherOpen,
|
||||
setProtocolSelectHost,
|
||||
setQuickSearch,
|
||||
]);
|
||||
|
||||
useMainWindowInputFocusRecovery({ onPageHidden: dismissTransientOverlays });
|
||||
@@ -277,7 +275,7 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
handleRequestCloseEditorTabRef, handleSessionStatusChange, handleSyncNowManual, handleTerminalDataCapture, handleUpdateHostFromTerminal,
|
||||
hostById, hosts, terminalHosts, updateTerminalHosts, hotkeyScheme, identities, importOrReuseKey, isBroadcastEnabled, isComposeSendToAll, onToggleComposeSendTarget, isGlobalBroadcastEnabled, isGlobalComposeSendToAll, onToggleGlobalBroadcast, onToggleGlobalComposeSendTarget, canUseGlobalBroadcast, isCreateWorkspaceOpen, isMacClient, isQuickSwitcherOpen,
|
||||
keyBindings, keyboardInteractiveQueue, keys, logViews, managedSources, navigateToSection, openLogView, openNoteRequest, orderedTabsWithEditors, orphanSessions,
|
||||
passphraseQueue, fidoPromptQueue, protocolSelectHost, proxyProfiles, portForwardingRules, quickResults, quickSearch, removeSessionFromWorkspace, reorderWorkTabs, reorderWorkspaceSessions,
|
||||
passphraseQueue, fidoPromptQueue, protocolSelectHost, proxyProfiles, portForwardingRules, removeSessionFromWorkspace, reorderWorkTabs, reorderWorkspaceSessions,
|
||||
resolveEmptyVaultConflict, resolveSessionAppearance, runSnippet, sessionLogsDir, sessionLogsEnabled, sessionLogsFormat, sessionLogsTimestampsEnabled, sessionRenameTarget, sshDebugLogsEnabled,
|
||||
sessions, setActiveTabId, setDeepLinkHostDraft, setDraggingSessionId, setEditorWordWrap,
|
||||
setNavigateToSection, setTerminalFontFamilyId, setTerminalFontSize, setVaultFocusRequest, updateSessionFontSize, updateSessionRestoreCwd, updateSessionDynamicTitle, updateSessionCodingCliProvider, clearSessionFontSizeOverride,
|
||||
@@ -506,6 +504,16 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
await popOutEditorTab(id, host?.label);
|
||||
}, [hostById]);
|
||||
|
||||
// Stable editor-tab callbacks so memoized TextEditorTabView/TextEditorPane
|
||||
// skip re-rendering when unrelated AppView state changes.
|
||||
const requestCloseEditorTabFromView = useCallback(
|
||||
(id: string) => handleRequestCloseEditorTabRef.current(id),
|
||||
[handleRequestCloseEditorTabRef],
|
||||
);
|
||||
const popOutEditorTabFromView = useCallback((id: string) => {
|
||||
void handlePopOutEditorTab(id);
|
||||
}, [handlePopOutEditorTab]);
|
||||
|
||||
const handleSaveSessionRename = useCallback((name: string) => {
|
||||
if (!sessionRenameTarget) return;
|
||||
if (!name.trim()) return;
|
||||
@@ -583,7 +591,7 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
onClosePluginViewTab={closePluginViewTab}
|
||||
onRequestCloseEditorTab={handleRequestCloseEditorTab}
|
||||
onPopOutEditorTab={handlePopOutEditorTab}
|
||||
onFocusEditorWindowTab={(id) => { void focusEditorInWindow(id); }}
|
||||
onFocusEditorWindowTab={focusEditorWindowTab}
|
||||
hostById={hostById}
|
||||
/>
|
||||
|
||||
@@ -847,8 +855,8 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
hotkeyScheme={hotkeyScheme}
|
||||
keyBindings={keyBindings}
|
||||
hostById={hostById}
|
||||
onRequestClose={(id) => handleRequestCloseEditorTabRef.current(id)}
|
||||
onPopOut={(id) => { void handlePopOutEditorTab(id); }}
|
||||
onRequestClose={requestCloseEditorTabFromView}
|
||||
onPopOut={popOutEditorTabFromView}
|
||||
/>
|
||||
</Suspense>
|
||||
</LazyLoadBoundary>
|
||||
@@ -937,50 +945,39 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
)}
|
||||
|
||||
{isQuickSwitcherOpen && (
|
||||
<LazyLoadBoundary name="Quick switcher" resetKey={quickSearch}>
|
||||
<Suspense fallback={null}>
|
||||
<LazyQuickSwitcher
|
||||
isOpen={isQuickSwitcherOpen}
|
||||
query={quickSearch}
|
||||
results={quickResults}
|
||||
sessions={sessions}
|
||||
workspaces={workspaces}
|
||||
showSftpTab={showSftpTab}
|
||||
onQueryChange={setQuickSearch}
|
||||
onSelect={handleHostConnectWithProtocolCheck}
|
||||
onQuickConnect={openQuickConnectFromInput}
|
||||
onEditHost={(host) => {
|
||||
setIsQuickSwitcherOpen(false);
|
||||
setQuickSearch('');
|
||||
handleEditHostFromOverlay(host);
|
||||
}}
|
||||
onSelectTab={(tabId) => {
|
||||
setActiveTabId(tabId);
|
||||
setIsQuickSwitcherOpen(false);
|
||||
setQuickSearch('');
|
||||
}}
|
||||
onCreateLocalTerminal={(shell) => {
|
||||
handleCreateLocalTerminal(shell);
|
||||
setIsQuickSwitcherOpen(false);
|
||||
setQuickSearch('');
|
||||
}}
|
||||
onCreateWorkspace={() => {
|
||||
setIsQuickSwitcherOpen(false);
|
||||
setQuickSearch('');
|
||||
setAddToWorkspaceDialog({ mode: 'create' });
|
||||
}}
|
||||
onClose={() => {
|
||||
setIsQuickSwitcherOpen(false);
|
||||
setQuickSearch('');
|
||||
}}
|
||||
keyBindings={keyBindings}
|
||||
terminalSettings={terminalSettings}
|
||||
paneMagnificationState={paneMagnificationState}
|
||||
onMagnifyCurrentPane={handleMagnifyCurrentPane}
|
||||
onRestoreMagnifiedPane={handleRestoreMagnifiedPane}
|
||||
/>
|
||||
</Suspense>
|
||||
</LazyLoadBoundary>
|
||||
<QuickSwitcherOverlay
|
||||
hosts={hosts}
|
||||
isOpen={isQuickSwitcherOpen}
|
||||
sessions={sessions}
|
||||
workspaces={workspaces}
|
||||
showSftpTab={showSftpTab}
|
||||
onSelect={handleHostConnectWithProtocolCheck}
|
||||
onQuickConnect={openQuickConnectFromInput}
|
||||
onEditHost={(host) => {
|
||||
setIsQuickSwitcherOpen(false);
|
||||
handleEditHostFromOverlay(host);
|
||||
}}
|
||||
onSelectTab={(tabId) => {
|
||||
setActiveTabId(tabId);
|
||||
setIsQuickSwitcherOpen(false);
|
||||
}}
|
||||
onCreateLocalTerminal={(shell) => {
|
||||
handleCreateLocalTerminal(shell);
|
||||
setIsQuickSwitcherOpen(false);
|
||||
}}
|
||||
onCreateWorkspace={() => {
|
||||
setIsQuickSwitcherOpen(false);
|
||||
setAddToWorkspaceDialog({ mode: 'create' });
|
||||
}}
|
||||
onClose={() => {
|
||||
setIsQuickSwitcherOpen(false);
|
||||
}}
|
||||
keyBindings={keyBindings}
|
||||
terminalSettings={terminalSettings}
|
||||
paneMagnificationState={paneMagnificationState}
|
||||
onMagnifyCurrentPane={handleMagnifyCurrentPane}
|
||||
onRestoreMagnifiedPane={handleRestoreMagnifiedPane}
|
||||
/>
|
||||
)}
|
||||
|
||||
<RenameDraftDialog
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import React, { Suspense, lazy, useMemo, useState } from 'react';
|
||||
|
||||
import type { QuickSwitcherProps } from '../../components/QuickSwitcher';
|
||||
import { LazyLoadBoundary } from '../../components/ui/lazy-load-boundary';
|
||||
import { getHostSearchMatch } from '../../lib/searchMatcher';
|
||||
import type { Host } from '../../types';
|
||||
|
||||
const LazyQuickSwitcher = lazy(() =>
|
||||
import('../../components/QuickSwitcher').then((m) => ({ default: m.QuickSwitcher })),
|
||||
);
|
||||
|
||||
/** Hosts matching the quick switcher query, best match first. */
|
||||
export function filterQuickSwitcherHosts(hosts: Host[], query: string): Host[] {
|
||||
const term = query.trim();
|
||||
if (!term) return hosts;
|
||||
return hosts
|
||||
.map((host) => ({ host, match: getHostSearchMatch(term, host) }))
|
||||
.filter((entry) => entry.match.matched)
|
||||
.sort((left, right) => {
|
||||
if (left.match.score !== right.match.score) {
|
||||
return right.match.score - left.match.score;
|
||||
}
|
||||
return left.host.label.localeCompare(right.host.label);
|
||||
})
|
||||
.map((entry) => entry.host);
|
||||
}
|
||||
|
||||
export type QuickSwitcherOverlayProps =
|
||||
Omit<QuickSwitcherProps, 'query' | 'results' | 'onQueryChange'> & { hosts: Host[] };
|
||||
|
||||
/**
|
||||
* Owns the quick switcher query. It used to live in AppSideEffects and travel
|
||||
* through the app-local UI store, so every keystroke re-rendered the whole
|
||||
* shell (AppSideEffects, every host island, AppShell, AppView and TopTabs).
|
||||
* The overlay is only mounted while the switcher is open, so closing it resets
|
||||
* the query just like the old `setQuickSearch('')` calls did.
|
||||
*/
|
||||
export function QuickSwitcherOverlay({ hosts, ...props }: QuickSwitcherOverlayProps) {
|
||||
const [query, setQuery] = useState('');
|
||||
const results = useMemo(() => filterQuickSwitcherHosts(hosts, query), [hosts, query]);
|
||||
return (
|
||||
<LazyLoadBoundary name="Quick switcher" resetKey={query}>
|
||||
<Suspense fallback={null}>
|
||||
<LazyQuickSwitcher {...props} query={query} results={results} onQueryChange={setQuery} />
|
||||
</Suspense>
|
||||
</LazyLoadBoundary>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import {
|
||||
getAppHandlers,
|
||||
registerAppHandlers,
|
||||
stabilizeAppHandlers,
|
||||
subscribeAppHandlers,
|
||||
type StableAppHandlerCache,
|
||||
} from './appHandlersBridge';
|
||||
|
||||
test('stabilized handlers keep their identity and call the latest implementation', () => {
|
||||
const cache: StableAppHandlerCache = new Map();
|
||||
const ref = { current: 1 };
|
||||
const calls: string[] = [];
|
||||
const first = stabilizeAppHandlers(cache, {
|
||||
closeTabsBatch: (id: string) => calls.push(`v1:${id}`),
|
||||
toggleSidePanelRef: ref,
|
||||
});
|
||||
const second = stabilizeAppHandlers(cache, {
|
||||
closeTabsBatch: (id: string) => calls.push(`v2:${id}`),
|
||||
toggleSidePanelRef: ref,
|
||||
});
|
||||
assert.equal(second.closeTabsBatch, first.closeTabsBatch);
|
||||
assert.equal(second.toggleSidePanelRef, ref, 'non-function values pass through');
|
||||
(first.closeTabsBatch as (id: string) => void)('a');
|
||||
assert.deepEqual(calls, ['v2:a']);
|
||||
});
|
||||
|
||||
test('the bridge does not notify Hosts when only handler implementations change', () => {
|
||||
const cache: StableAppHandlerCache = new Map();
|
||||
let notified = 0;
|
||||
const unsubscribe = subscribeAppHandlers(() => { notified += 1; });
|
||||
try {
|
||||
registerAppHandlers(stabilizeAppHandlers(cache, { handleDeleteHost: () => 'v1' }));
|
||||
const afterFirst = notified;
|
||||
// A session status change recreated the callback (it closes over hosts).
|
||||
registerAppHandlers(stabilizeAppHandlers(cache, { handleDeleteHost: () => 'v2' }));
|
||||
assert.equal(notified, afterFirst);
|
||||
assert.equal((getAppHandlers()!.handleDeleteHost as () => string)(), 'v2');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
registerAppHandlers(null);
|
||||
}
|
||||
});
|
||||
@@ -51,6 +51,37 @@ class AppHandlersBridge {
|
||||
|
||||
const bridge = new AppHandlersBridge();
|
||||
|
||||
export type StableAppHandlerCache = Map<string, { latest: unknown; stable: unknown }>;
|
||||
|
||||
/**
|
||||
* Give every function-valued handler a per-key wrapper with a stable identity
|
||||
* that always calls the latest implementation; non-functions (refs) pass
|
||||
* through. Many glue callbacks close over sessions/workspaces/hosts, so their
|
||||
* identities changed on every session status change and host update (connect
|
||||
* bursts, last-connected times), and the bridge re-notified every Host island,
|
||||
* rebuilding all shell bags and re-rendering AppView/TopTabs each time. The
|
||||
* handlers are actions invoked from events, never read during render.
|
||||
*/
|
||||
export function stabilizeAppHandlers(cache: StableAppHandlerCache, handlers: AppHandlers): AppHandlers {
|
||||
const stableHandlers: AppHandlers = {};
|
||||
for (const [key, value] of Object.entries(handlers)) {
|
||||
if (typeof value !== 'function') {
|
||||
stableHandlers[key] = value;
|
||||
continue;
|
||||
}
|
||||
let entry = cache.get(key);
|
||||
if (!entry) {
|
||||
const created: { latest: unknown; stable: unknown } = { latest: value, stable: null };
|
||||
created.stable = (...args: unknown[]) => (created.latest as (...callArgs: unknown[]) => unknown)(...args);
|
||||
cache.set(key, created);
|
||||
entry = created;
|
||||
}
|
||||
entry.latest = value;
|
||||
stableHandlers[key] = entry.stable;
|
||||
}
|
||||
return stableHandlers;
|
||||
}
|
||||
|
||||
export function registerAppHandlers(handlers: AppHandlers | null): void {
|
||||
bridge.set(handlers);
|
||||
}
|
||||
|
||||
@@ -24,7 +24,6 @@ export type AppLocalUiSnapshot = {
|
||||
| { mode: 'append'; workspaceId: string }
|
||||
| { mode: 'create' }
|
||||
| null;
|
||||
quickSearch: string;
|
||||
protocolSelectHost: Host | null;
|
||||
navigateToSection: VaultSection | null;
|
||||
deepLinkHostDraft: Host | null;
|
||||
@@ -43,7 +42,6 @@ export const EMPTY_APP_LOCAL_UI: AppLocalUiSnapshot = Object.freeze({
|
||||
isQuickSwitcherOpen: false,
|
||||
isCreateWorkspaceOpen: false,
|
||||
addToWorkspaceDialog: null,
|
||||
quickSearch: '',
|
||||
protocolSelectHost: null,
|
||||
navigateToSection: null,
|
||||
deepLinkHostDraft: null,
|
||||
@@ -76,7 +74,6 @@ class AppLocalUiStore {
|
||||
prev.isQuickSwitcherOpen === next.isQuickSwitcherOpen
|
||||
&& prev.isCreateWorkspaceOpen === next.isCreateWorkspaceOpen
|
||||
&& prev.addToWorkspaceDialog === next.addToWorkspaceDialog
|
||||
&& prev.quickSearch === next.quickSearch
|
||||
&& prev.protocolSelectHost === next.protocolSelectHost
|
||||
&& prev.navigateToSection === next.navigateToSection
|
||||
&& prev.deepLinkHostDraft === next.deepLinkHostDraft
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { useLayoutEffect, useMemo, useSyncExternalStore } from 'react';
|
||||
|
||||
import { getHostSearchMatch } from '../../../lib/searchMatcher';
|
||||
import type { Host } from '../../../types';
|
||||
import { useEditorTabChromeList } from '../../state/editorTabStore';
|
||||
import { useVaultSnapshot } from '../../state/vaultSnapshotStore';
|
||||
import { getAppHandlers, subscribeAppHandlers } from '../appHandlersBridge';
|
||||
import {
|
||||
publishAppShellDomainSlice,
|
||||
@@ -11,16 +8,14 @@ import {
|
||||
} from '../appShellPropsStore';
|
||||
import { useAppLocalUiStore } from '../appLocalUiStore';
|
||||
|
||||
const EMPTY_HOST_RESULTS: Host[] = [];
|
||||
|
||||
/**
|
||||
* Dialogs island: local dialog/queue state from `appLocalUiStore`, plus a
|
||||
* selective vault hosts subscription for quick-search results when open.
|
||||
* Dialogs island: local dialog/queue state from `appLocalUiStore`. The quick
|
||||
* switcher owns its query and host results (QuickSwitcherOverlay), so typing
|
||||
* there no longer republishes this bag.
|
||||
* Assembles dialogs + overlays field-by-field — never spreads a prepared bag.
|
||||
*/
|
||||
export function DialogsHost() {
|
||||
const local = useAppLocalUiStore();
|
||||
const vault = useVaultSnapshot();
|
||||
const editorTabs = useEditorTabChromeList();
|
||||
const handlers = useSyncExternalStore(
|
||||
subscribeAppHandlers,
|
||||
@@ -28,22 +23,6 @@ export function DialogsHost() {
|
||||
getAppHandlers,
|
||||
);
|
||||
|
||||
const quickResults = useMemo(() => {
|
||||
if (!local.isQuickSwitcherOpen) return EMPTY_HOST_RESULTS;
|
||||
const term = local.quickSearch.trim();
|
||||
if (!term) return vault.hosts as Host[];
|
||||
return (vault.hosts as Host[])
|
||||
.map((host) => ({ host, match: getHostSearchMatch(term, host) }))
|
||||
.filter((entry) => entry.match.matched)
|
||||
.sort((left, right) => {
|
||||
if (left.match.score !== right.match.score) {
|
||||
return right.match.score - left.match.score;
|
||||
}
|
||||
return left.host.label.localeCompare(right.host.label);
|
||||
})
|
||||
.map((entry) => entry.host);
|
||||
}, [local.isQuickSwitcherOpen, local.quickSearch, vault.hosts]);
|
||||
|
||||
const dialogsDomain = useMemo(() => {
|
||||
if (!handlers) return null;
|
||||
return {
|
||||
@@ -68,14 +47,11 @@ export function DialogsHost() {
|
||||
passphraseQueue: local.passphraseQueue,
|
||||
fidoPromptQueue: local.fidoPromptQueue,
|
||||
protocolSelectHost: local.protocolSelectHost,
|
||||
quickResults,
|
||||
quickSearch: local.quickSearch,
|
||||
resolveEmptyVaultConflict: handlers.resolveEmptyVaultConflict,
|
||||
setAddToWorkspaceDialog: handlers.setAddToWorkspaceDialog,
|
||||
setIsCreateWorkspaceOpen: handlers.setIsCreateWorkspaceOpen,
|
||||
setIsQuickSwitcherOpen: handlers.setIsQuickSwitcherOpen,
|
||||
setProtocolSelectHost: handlers.setProtocolSelectHost,
|
||||
setQuickSearch: handlers.setQuickSearch,
|
||||
};
|
||||
}, [
|
||||
editorTabs,
|
||||
@@ -88,8 +64,6 @@ export function DialogsHost() {
|
||||
local.passphraseQueue,
|
||||
local.fidoPromptQueue,
|
||||
local.protocolSelectHost,
|
||||
local.quickSearch,
|
||||
quickResults,
|
||||
]);
|
||||
|
||||
const overlays = useMemo(() => {
|
||||
|
||||
@@ -14,7 +14,22 @@ function loadComponent(path: string, name: string, bindings: Record<string, unkn
|
||||
const code = ts.transpile(declaration.getText(ast).replace(/^export /, ''), {
|
||||
target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React,
|
||||
});
|
||||
return vm.runInNewContext(`${code}; ${name}`, { React, ...bindings }) as React.ComponentType;
|
||||
// Extracting the function drops imports, so inject bare React hooks/APIs into the sandbox.
|
||||
return vm.runInNewContext(`${code}; ${name}`, {
|
||||
React,
|
||||
useState: React.useState,
|
||||
useEffect: React.useEffect,
|
||||
useLayoutEffect: React.useLayoutEffect,
|
||||
useMemo: React.useMemo,
|
||||
useCallback: React.useCallback,
|
||||
useRef: React.useRef,
|
||||
useReducer: React.useReducer,
|
||||
useContext: React.useContext,
|
||||
memo: React.memo,
|
||||
createElement: React.createElement,
|
||||
Fragment: React.Fragment,
|
||||
...bindings,
|
||||
}) as React.ComponentType;
|
||||
}
|
||||
|
||||
test('monitor controls update their runtime without rendering unrelated app siblings', async () => {
|
||||
@@ -32,6 +47,7 @@ test('monitor controls update their runtime without rendering unrelated app sibl
|
||||
};
|
||||
const MonitorRuntimeHost = loadComponent('./MonitorRuntimeHost.tsx', 'MonitorRuntimeHost', { useMonitorRuntime });
|
||||
const App = loadComponent('../../App.tsx', 'App', {
|
||||
performance: { mark: () => {} },
|
||||
useMonitorRuntime,
|
||||
MonitorRuntimeHost,
|
||||
AppLocalStateProvider: ({ children }: { children: React.ReactNode }) => children,
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import test from 'node:test';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
// Guards for what the startup bundle (index.html entry) may pull in. Each of
|
||||
// these used to land in the entry chunk that every window parses at launch.
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
|
||||
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]);
|
||||
|
||||
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']);
|
||||
});
|
||||
|
||||
test('startup modules do not statically import the AI runtime or SDK providers', () => {
|
||||
const runtimeModules = /harness\/globalAgentRuntime|plugin\/trustedHostRuntime|plugin\/configuredModel|pluginAgent\/trustedAgentRuntime|sdk\/providers/;
|
||||
for (const path of [
|
||||
'application/state/aiStateSnapshots.ts',
|
||||
'application/state/usePluginAIContextHost.ts',
|
||||
'application/state/usePluginAgentHost.ts',
|
||||
]) {
|
||||
const offending = staticImports(read(path)).filter((specifier) => runtimeModules.test(specifier));
|
||||
assert.deepEqual(offending, [], `${path} must load the AI runtime lazily`);
|
||||
}
|
||||
});
|
||||
|
||||
test("Vite's preload helper stays out of the vendor-ai chunk", () => {
|
||||
// The entry imports the helper for its dynamic imports; if it is grouped
|
||||
// with the AI SDK, the whole vendor-ai chunk is preloaded at startup.
|
||||
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'));
|
||||
});
|
||||
@@ -293,7 +293,10 @@ export function useAppStartupEffects(ctx: StartupEffectsContext) {
|
||||
terminalSettings,
|
||||
});
|
||||
|
||||
// Sync tray menu data + handle tray actions
|
||||
// Sync tray menu data + handle tray actions. Hosts are only re-sent when the
|
||||
// host list changed: session status updates (connect bursts) used to resend
|
||||
// and re-serialize every host and rebuild the macOS Dock menu each time.
|
||||
const lastTrayHostsRef = useRef<unknown>(null);
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
const bridge = netcattyBridge.get();
|
||||
@@ -316,17 +319,21 @@ export function useAppStartupEffects(ctx: StartupEffectsContext) {
|
||||
};
|
||||
});
|
||||
|
||||
const hostsForSystemMenu = hosts
|
||||
.filter((host: any) => typeof host?.id === "string" && host.id.length > 0)
|
||||
.map((host: any) => ({
|
||||
id: host.id,
|
||||
label: host.label,
|
||||
hostname: host.hostname,
|
||||
group: host.group,
|
||||
pinned: host.pinned,
|
||||
lastConnectedAt: host.lastConnectedAt,
|
||||
protocol: host.protocol,
|
||||
}));
|
||||
const hostsChanged = lastTrayHostsRef.current !== hosts;
|
||||
lastTrayHostsRef.current = hosts;
|
||||
const hostsForSystemMenu = hostsChanged
|
||||
? hosts
|
||||
.filter((host: any) => typeof host?.id === "string" && host.id.length > 0)
|
||||
.map((host: any) => ({
|
||||
id: host.id,
|
||||
label: host.label,
|
||||
hostname: host.hostname,
|
||||
group: host.group,
|
||||
pinned: host.pinned,
|
||||
lastConnectedAt: host.lastConnectedAt,
|
||||
protocol: host.protocol,
|
||||
}))
|
||||
: undefined;
|
||||
|
||||
void bridge.updateTrayMenuData({
|
||||
sessions: sessionsForTray,
|
||||
@@ -334,7 +341,7 @@ export function useAppStartupEffects(ctx: StartupEffectsContext) {
|
||||
...rule,
|
||||
canStop: hasRuntimeTunnel(rule.id),
|
||||
})),
|
||||
hosts: hostsForSystemMenu,
|
||||
...(hostsForSystemMenu ? { hosts: hostsForSystemMenu } : {}),
|
||||
});
|
||||
}, 250);
|
||||
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import React, { createContext, useContext, useMemo } from 'react';
|
||||
import React, { createContext, useContext, useEffect, useMemo, useSyncExternalStore } from 'react';
|
||||
import { DEFAULT_UI_LOCALE, resolveSupportedLocale } from '../../infrastructure/config/i18n';
|
||||
import { MESSAGES_BY_LOCALE } from './messages';
|
||||
import {
|
||||
getBaseFallbackLocale,
|
||||
getLoadedLocaleMessages,
|
||||
getLocaleMessagesVersion,
|
||||
loadLocaleMessages,
|
||||
subscribeLocaleMessages,
|
||||
type Messages,
|
||||
} from './messages';
|
||||
|
||||
type InterpolationValues = Record<string, string | number | boolean | null | undefined>;
|
||||
|
||||
@@ -29,32 +36,59 @@ const interpolate = (template: string, values?: InterpolationValues): string =>
|
||||
.replace(/\{(\w+)\}/g, replaceSingleBraceToken);
|
||||
};
|
||||
|
||||
const resolveMessage = (resolvedLocale: string, key: string): string | undefined => {
|
||||
const direct = MESSAGES_BY_LOCALE[resolvedLocale]?.[key];
|
||||
if (direct) return direct;
|
||||
const base = resolvedLocale.split('-')[0];
|
||||
const baseKey = Object.keys(MESSAGES_BY_LOCALE).find((k) => k === base || k.startsWith(`${base}-`));
|
||||
const baseHit = baseKey ? MESSAGES_BY_LOCALE[baseKey]?.[key] : undefined;
|
||||
if (baseHit) return baseHit;
|
||||
return MESSAGES_BY_LOCALE[DEFAULT_UI_LOCALE]?.[key];
|
||||
type LocaleDictionaries = {
|
||||
direct?: Messages;
|
||||
base?: Messages;
|
||||
fallback?: Messages;
|
||||
};
|
||||
|
||||
/**
|
||||
* Dictionaries consulted for `resolvedLocale`: exact locale, same-base sibling
|
||||
* (zh-TW -> zh-CN), then English. `_loadedVersion` is only a cache key so a
|
||||
* dictionary that finishes loading yields a fresh snapshot.
|
||||
*/
|
||||
const snapshotLocaleDictionaries = (resolvedLocale: string, _loadedVersion: number): LocaleDictionaries => {
|
||||
const baseKey = getBaseFallbackLocale(resolvedLocale);
|
||||
return {
|
||||
direct: getLoadedLocaleMessages(resolvedLocale),
|
||||
base: baseKey ? getLoadedLocaleMessages(baseKey) : undefined,
|
||||
fallback: getLoadedLocaleMessages(DEFAULT_UI_LOCALE),
|
||||
};
|
||||
};
|
||||
|
||||
const resolveMessage = (dictionaries: LocaleDictionaries, key: string): string | undefined =>
|
||||
dictionaries.direct?.[key] || dictionaries.base?.[key] || dictionaries.fallback?.[key];
|
||||
|
||||
export const I18nProvider: React.FC<{ locale: string; children: React.ReactNode }> = ({
|
||||
locale,
|
||||
children,
|
||||
}) => {
|
||||
const resolvedLocale = resolveSupportedLocale(locale || DEFAULT_UI_LOCALE);
|
||||
// Non-English dictionaries load on demand (index.tsx preloads the saved one
|
||||
// before the first render); re-render consumers once a switch finishes.
|
||||
const messagesVersion = useSyncExternalStore(
|
||||
subscribeLocaleMessages,
|
||||
getLocaleMessagesVersion,
|
||||
getLocaleMessagesVersion,
|
||||
);
|
||||
useEffect(() => {
|
||||
void loadLocaleMessages(resolvedLocale).catch(() => {});
|
||||
}, [resolvedLocale]);
|
||||
const dictionaries = useMemo(
|
||||
() => snapshotLocaleDictionaries(resolvedLocale, messagesVersion),
|
||||
[resolvedLocale, messagesVersion],
|
||||
);
|
||||
|
||||
const value = useMemo<I18nContextValue>(() => {
|
||||
return {
|
||||
locale,
|
||||
resolvedLocale,
|
||||
t: (key, values) => {
|
||||
const msg = resolveMessage(resolvedLocale, key) ?? key;
|
||||
const msg = resolveMessage(dictionaries, key) ?? key;
|
||||
return interpolate(msg, values);
|
||||
},
|
||||
};
|
||||
}, [locale, resolvedLocale]);
|
||||
}, [dictionaries, locale, resolvedLocale]);
|
||||
|
||||
return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
|
||||
};
|
||||
|
||||
@@ -525,6 +525,8 @@ export const enAiMessages: Messages = {
|
||||
'ai.chat.alwaysAllow': 'Always',
|
||||
'ai.chat.slashStopDesc': 'Stop the current AI turn and cancel in-flight tools',
|
||||
'ai.chat.slashCompactDesc': 'Summarize earlier conversation context',
|
||||
'ai.chat.slashRenameDesc': 'Rename the current chat (/rename <title>)',
|
||||
'ai.chat.slashChatsDesc': 'List the chats visible to this panel',
|
||||
'ai.chat.reject': 'Reject',
|
||||
'ai.chat.toolLabel': 'Tool',
|
||||
'ai.chat.targetLabel': 'Target',
|
||||
@@ -587,6 +589,28 @@ export const enAiMessages: Messages = {
|
||||
'ai.chat.recent': 'Recent',
|
||||
'ai.chat.viewAll': 'View All',
|
||||
'ai.chat.untitled': 'Untitled',
|
||||
'ai.chat.renameChat': 'Rename chat',
|
||||
'ai.chat.renameUsage': 'Usage: /rename <new title>',
|
||||
'ai.chat.renameNoActive': 'No active chat to rename.',
|
||||
'ai.chat.renameDone': 'Chat renamed to "{title}".',
|
||||
'ai.chat.exportSessions': 'Export AI chats',
|
||||
'ai.chat.importSessions': 'Import AI chats',
|
||||
'ai.chat.exportDone': 'AI chats exported to {path}.',
|
||||
'ai.chat.exportDoneNoPath': 'AI chats exported.',
|
||||
'ai.chat.exportUnavailable': 'AI chat export is unavailable in this environment.',
|
||||
'ai.chat.importDone': 'Imported {n} AI chat(s).',
|
||||
'ai.chat.importNone': 'No AI chats found in the selected file.',
|
||||
'ai.chat.chatsHeader': 'Chats visible in this panel:',
|
||||
'ai.chat.chatsEmpty': 'No chats visible in this panel.',
|
||||
'ai.chat.chatsScopeWorkspace': 'Workspace',
|
||||
'ai.chat.chatsScopeTerminal': 'Terminal',
|
||||
'ai.chat.chatsScopeGlobal': 'Global',
|
||||
'ai.chat.chatsScopeDangling': 'Dissociated',
|
||||
'ai.chat.slashRebindDesc': 'Rebind a disconnected chat to this panel (/rebind <n>)',
|
||||
'ai.chat.chatsRebindHint': 'Disconnected chats can be restored with /rebind <n>.',
|
||||
'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.justNow': 'Just now',
|
||||
'ai.chat.minutesAgo': '{n}m ago',
|
||||
'ai.chat.hoursAgo': '{n}h ago',
|
||||
@@ -795,4 +819,27 @@ export const enAiMessages: Messages = {
|
||||
'zmodem.overwrite.skip': 'Skip',
|
||||
'zmodem.overwrite.cancel': 'Cancel',
|
||||
'settings.shortcuts.resetToDefault': 'Reset to default',
|
||||
"ai.toolSettings.immediate": "Changes take effect immediately. Closing this window does not undo them.",
|
||||
"ai.toolSettings.privacyOn": "Text redaction enabled",
|
||||
"ai.toolSettings.privacyOff": "Text redaction disabled",
|
||||
"ai.toolSettings.ruleSummary": "{cidrs} additional IP ranges · {patterns} custom patterns",
|
||||
"ai.toolSettings.configurePrivacy": "Configure privacy",
|
||||
"ai.toolSettings.unsaved": "Unsaved changes",
|
||||
"ai.toolSettings.viewSkills": "View CLI guidance",
|
||||
"ai.toolSettings.viewPrompt": "View setup prompt",
|
||||
"ai.toolSettings.behavior": "MCP behavior",
|
||||
"ai.toolSettings.configureBehavior": "Configure behavior",
|
||||
"ai.toolSettings.configureClients": "Configure clients",
|
||||
"ai.toolSettings.httpOn": "HTTP enabled",
|
||||
"ai.toolSettings.httpOff": "HTTP disabled",
|
||||
"ai.toolSettings.loopback": "Local connections only (127.0.0.1)",
|
||||
"ai.toolSettings.configureHttp": "Configure HTTP",
|
||||
"ai.toolSettings.hideSecret": "Hide secret",
|
||||
"ai.toolSettings.showSecret": "Show secret",
|
||||
"ai.toolSettings.manualSetup": "Manual setup",
|
||||
"ai.toolSettings.format": "Format",
|
||||
"ai.toolSettings.connectionDetails": "Connection details",
|
||||
"ai.toolSettings.conflict": "Settings changed in another window. Your draft is preserved. Cancel and reopen to load the saved settings.",
|
||||
"ai.toolSettings.retry": "Retry",
|
||||
"ai.toolSettings.applyingHttp": "Applying HTTP configuration...",
|
||||
};
|
||||
@@ -161,7 +161,12 @@ export const enCoreMessages: Messages = {
|
||||
'settings.system.clearTempFiles': 'Clear temp files',
|
||||
'settings.system.clearing': 'Clearing...',
|
||||
'settings.system.clearResult': 'Deleted {deleted} file(s), {failed} failed.',
|
||||
'settings.system.tempDirectoryHint': 'Temporary files are created when opening remote files with external applications. They are automatically cleaned up when SFTP sessions close.',
|
||||
'settings.system.tempDirChoose': 'Choose folder',
|
||||
'settings.system.tempDirManual': 'Enter an absolute folder path',
|
||||
'settings.system.tempDirApply': 'Apply',
|
||||
'settings.system.tempDirReset': 'Reset to default',
|
||||
'settings.system.tempDirError': 'Unable to use this folder.',
|
||||
'settings.system.tempDirectoryHint': 'Netcatty creates a Netcatty temp subfolder in the chosen folder for SFTP staging and external editing. Changing the folder during a transfer may affect that transfer.',
|
||||
'settings.system.credentials.title': 'Credential Protection',
|
||||
'settings.system.credentials.status': 'Status',
|
||||
'settings.system.credentials.checking': 'Checking...',
|
||||
@@ -1375,6 +1380,9 @@ Highlight the focused split pane:
|
||||
"settings.plugins.openManager": "Open plugin manager",
|
||||
"settings.plugins.sources.conflict": "This ID is installed from another source. Uninstall and explicitly reset its private data before switching. Existing source:",
|
||||
"settings.plugins.sources.clearPrivate": "Also clear this source’s private data, grants and secrets to reinstall from another source. This cannot be undone.",
|
||||
"settings.plugins.sources.short.official": "Official",
|
||||
"settings.plugins.sources.short.thirdparty": "Third-party",
|
||||
"settings.plugins.sources.short.local": "Local",
|
||||
"settings.plugins.sources.official": "Official marketplace",
|
||||
"settings.plugins.sources.thirdparty": "Third-party marketplace",
|
||||
"settings.plugins.sources.manage": "Manage sources",
|
||||
@@ -1393,6 +1401,7 @@ Highlight the focused split pane:
|
||||
"settings.plugins.sources.local": "Local import",
|
||||
"settings.plugins.sources.all": "All sources",
|
||||
"settings.plugins.title": "Plugins",
|
||||
"settings.plugins.configuration": "Plugin settings",
|
||||
"settings.plugins.description": "Manage your plugins and explore the catalog.",
|
||||
'settings.plugins.loading': 'Loading plugin settings…',
|
||||
'settings.plugins.empty': 'No enabled plugin contributes settings.',
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
export const enMonitorMessages = {
|
||||
"monitor.systemDisks": "System partitions ({count})",
|
||||
"monitor.systemDisksAlert": "System partition usage exceeds 80%; expanded automatically.",
|
||||
"monitor.diskIoTotal": "Total",
|
||||
"monitor.partitionIoHint": "I/O of the block device backing this mount. Mounts sharing a device show the same rates. Unavailable until two valid samples or when no block device can be identified; not supported on macOS.",
|
||||
"monitor.diskIo": "Disk I/O",
|
||||
"monitor.diskRead": "Read",
|
||||
"monitor.diskWrite": "Write",
|
||||
|
||||
@@ -460,6 +460,7 @@ export const enTerminalMessages: Messages = {
|
||||
'cloudSync.localBackups.clearFailed': 'Could not clear all local backups. Please retry.',
|
||||
'cloudSync.localBackups.title': 'Local Backup History',
|
||||
'cloudSync.localBackups.desc': 'Netcatty keeps local restore points before app version changes and before vault restores.',
|
||||
'cloudSync.localBackups.folderWarning': 'This folder alone is not a complete, portable backup. Deleting or wiping the app profile (userData) may make these restore points unreadable.',
|
||||
'cloudSync.localBackups.retentionTitle': 'Backup Retention',
|
||||
'cloudSync.localBackups.retentionDesc': 'Choose how many local backups Netcatty should keep.',
|
||||
'cloudSync.localBackups.maxCount': 'Max backups',
|
||||
@@ -474,6 +475,7 @@ export const enTerminalMessages: Messages = {
|
||||
'cloudSync.localBackups.restoreSuccess': 'Local backup restored.',
|
||||
'cloudSync.localBackups.restoreFailedTitle': 'Restore failed',
|
||||
'cloudSync.localBackups.restoreMissing': 'Backup not found.',
|
||||
'cloudSync.localBackups.decryptFailed': 'The current app profile cannot decrypt this backup. The encryption key may be missing, the profile may have changed, or the backup may be damaged.',
|
||||
'cloudSync.localBackups.protectiveBackupFailed': 'Safety backup could not be created, so the restore was aborted to protect your current data. Resolve the underlying issue (e.g. keychain access) and try again. Details: {message}',
|
||||
'cloudSync.localBackups.restoreConfirmTitle': 'Restore this backup?',
|
||||
'cloudSync.localBackups.restoreConfirmDesc': 'Your current hosts, keys, snippets and settings will be replaced with the contents of this backup. A protective snapshot of your current data is taken automatically first.',
|
||||
|
||||
@@ -525,6 +525,8 @@ export const esAiMessages: Messages = {
|
||||
'ai.chat.alwaysAllow': 'Siempre',
|
||||
'ai.chat.slashStopDesc': 'Detener el turno actual de IA y cancelar las herramientas en curso',
|
||||
'ai.chat.slashCompactDesc': 'Resumir el contexto anterior de la conversación',
|
||||
'ai.chat.slashRenameDesc': 'Renombrar el chat actual (/rename <título>)',
|
||||
'ai.chat.slashChatsDesc': 'Listar los chats visibles en este panel',
|
||||
'ai.chat.reject': 'Rechazar',
|
||||
'ai.chat.toolLabel': 'Herramienta',
|
||||
'ai.chat.targetLabel': 'Destino',
|
||||
@@ -587,6 +589,28 @@ export const esAiMessages: Messages = {
|
||||
'ai.chat.recent': 'Recientes',
|
||||
'ai.chat.viewAll': 'Ver todo',
|
||||
'ai.chat.untitled': 'Sin título',
|
||||
'ai.chat.renameChat': 'Renombrar chat',
|
||||
'ai.chat.renameUsage': 'Uso: /rename <nuevo título>',
|
||||
'ai.chat.renameNoActive': 'No hay ningún chat activo para renombrar.',
|
||||
'ai.chat.renameDone': 'Chat renombrado a «{title}».',
|
||||
'ai.chat.exportSessions': 'Exportar chats de IA',
|
||||
'ai.chat.importSessions': 'Importar chats de IA',
|
||||
'ai.chat.exportDone': 'Chats de IA exportados a {path}.',
|
||||
'ai.chat.exportDoneNoPath': 'Chats de IA exportados.',
|
||||
'ai.chat.exportUnavailable': 'La exportación de chats de IA no está disponible en este entorno.',
|
||||
'ai.chat.importDone': 'Se importaron {n} chat(s) de IA.',
|
||||
'ai.chat.importNone': 'No se encontraron chats de IA en el archivo seleccionado.',
|
||||
'ai.chat.chatsHeader': 'Chats visibles en este panel:',
|
||||
'ai.chat.chatsEmpty': 'No hay chats visibles en este panel.',
|
||||
'ai.chat.chatsScopeWorkspace': 'Workspace',
|
||||
'ai.chat.chatsScopeTerminal': 'Terminal',
|
||||
'ai.chat.chatsScopeGlobal': 'Global',
|
||||
'ai.chat.chatsScopeDangling': 'Desasociado',
|
||||
'ai.chat.slashRebindDesc': 'Reasociar un chat desconectado a este panel (/rebind <n>)',
|
||||
'ai.chat.chatsRebindHint': 'Los chats desconectados se pueden restaurar con /rebind <n>.',
|
||||
'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.justNow': 'Ahora mismo',
|
||||
'ai.chat.minutesAgo': 'hace {n} min',
|
||||
'ai.chat.hoursAgo': 'hace {n} h',
|
||||
@@ -795,4 +819,27 @@ export const esAiMessages: Messages = {
|
||||
'zmodem.overwrite.skip': 'Omitir',
|
||||
'zmodem.overwrite.cancel': 'Cancelar',
|
||||
'settings.shortcuts.resetToDefault': 'Restablecer al predeterminado',
|
||||
"ai.toolSettings.immediate": "Los cambios se aplican inmediatamente. Cerrar esta ventana no los deshace.",
|
||||
"ai.toolSettings.privacyOn": "Ocultación de texto activada",
|
||||
"ai.toolSettings.privacyOff": "Ocultación de texto desactivada",
|
||||
"ai.toolSettings.ruleSummary": "{cidrs} rangos IP adicionales · {patterns} patrones personalizados",
|
||||
"ai.toolSettings.configurePrivacy": "Configurar privacidad",
|
||||
"ai.toolSettings.unsaved": "Cambios sin guardar",
|
||||
"ai.toolSettings.viewSkills": "Ver instrucciones de CLI",
|
||||
"ai.toolSettings.viewPrompt": "Ver instrucciones de conexión",
|
||||
"ai.toolSettings.behavior": "Comportamiento de MCP",
|
||||
"ai.toolSettings.configureBehavior": "Configurar comportamiento",
|
||||
"ai.toolSettings.configureClients": "Configurar clientes",
|
||||
"ai.toolSettings.httpOn": "HTTP activado",
|
||||
"ai.toolSettings.httpOff": "HTTP desactivado",
|
||||
"ai.toolSettings.loopback": "Solo conexiones locales (127.0.0.1)",
|
||||
"ai.toolSettings.configureHttp": "Configurar HTTP",
|
||||
"ai.toolSettings.hideSecret": "Ocultar secreto",
|
||||
"ai.toolSettings.showSecret": "Mostrar secreto",
|
||||
"ai.toolSettings.manualSetup": "Configuración manual",
|
||||
"ai.toolSettings.format": "Formato",
|
||||
"ai.toolSettings.connectionDetails": "Detalles de conexión",
|
||||
"ai.toolSettings.conflict": "La configuración cambió en otra ventana. Se conserva el borrador. Cancela y vuelve a abrir para cargar la configuración guardada.",
|
||||
"ai.toolSettings.retry": "Reintentar",
|
||||
"ai.toolSettings.applyingHttp": "Aplicando la configuración HTTP...",
|
||||
};
|
||||
@@ -161,7 +161,12 @@ export const esCoreMessages: Messages = {
|
||||
'settings.system.clearTempFiles': 'Limpiar archivos temporales',
|
||||
'settings.system.clearing': 'Limpiando...',
|
||||
'settings.system.clearResult': 'Se eliminaron {deleted} archivo(s), {failed} fallaron.',
|
||||
'settings.system.tempDirectoryHint': 'Los archivos temporales se crean al abrir archivos remotos con aplicaciones externas. Se limpian automáticamente cuando las sesiones SFTP se cierran.',
|
||||
'settings.system.tempDirChoose': 'Elegir carpeta',
|
||||
'settings.system.tempDirManual': 'Introduce una ruta de carpeta absoluta',
|
||||
'settings.system.tempDirApply': 'Aplicar',
|
||||
'settings.system.tempDirReset': 'Restablecer predeterminado',
|
||||
'settings.system.tempDirError': 'No se puede usar esta carpeta.',
|
||||
'settings.system.tempDirectoryHint': 'Se usa para el almacenamiento temporal de transferencias SFTP y archivos abiertos con aplicaciones externas. Cambiar la carpeta durante una transferencia puede afectar esa transferencia.',
|
||||
'settings.system.credentials.title': 'Protección de credenciales',
|
||||
'settings.system.credentials.status': 'Estado',
|
||||
'settings.system.credentials.checking': 'Comprobando...',
|
||||
@@ -1375,6 +1380,9 @@ Resalta el panel dividido enfocado:
|
||||
"settings.plugins.openManager": "Abrir gestor de plugins",
|
||||
"settings.plugins.sources.conflict": "This ID is installed from another source. Uninstall and explicitly reset its private data before switching. Existing source:",
|
||||
"settings.plugins.sources.clearPrivate": "Also clear this source’s private data, grants and secrets to reinstall from another source. This cannot be undone.",
|
||||
"settings.plugins.sources.short.official": "Oficial",
|
||||
"settings.plugins.sources.short.thirdparty": "Terceros",
|
||||
"settings.plugins.sources.short.local": "Local",
|
||||
"settings.plugins.sources.official": "Official marketplace",
|
||||
"settings.plugins.sources.thirdparty": "Third-party marketplace",
|
||||
"settings.plugins.sources.manage": "Manage sources",
|
||||
@@ -1393,6 +1401,7 @@ Resalta el panel dividido enfocado:
|
||||
"settings.plugins.sources.local": "Local import",
|
||||
"settings.plugins.sources.all": "All sources",
|
||||
"settings.plugins.title": "Plugins",
|
||||
"settings.plugins.configuration": "Ajustes del plugin",
|
||||
"settings.plugins.description": "Gestiona tus plugins y explora el catálogo.",
|
||||
'settings.plugins.loading': 'Cargando ajustes del plugin…',
|
||||
'settings.plugins.empty': 'Ningún plugin activado aporta ajustes.',
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
export const esMonitorMessages = {
|
||||
"monitor.systemDisks": "Particiones del sistema ({count})",
|
||||
"monitor.systemDisksAlert": "El uso de una partición del sistema supera el 80 %; se ha expandido automáticamente.",
|
||||
"monitor.diskIoTotal": "Total",
|
||||
"monitor.partitionIoHint": "E/S del dispositivo de bloques de este montaje. Los montajes del mismo dispositivo muestran las mismas tasas. No disponible hasta tener dos muestras válidas o sin un dispositivo identificable; no compatible con macOS.",
|
||||
"monitor.diskIo": "E/S de disco",
|
||||
"monitor.diskRead": "Lectura",
|
||||
"monitor.diskWrite": "Escritura",
|
||||
|
||||
@@ -460,6 +460,7 @@ export const esTerminalMessages: Messages = {
|
||||
'cloudSync.localBackups.clearFailed': 'No se pudieron eliminar todas las copias locales. Inténtalo de nuevo.',
|
||||
'cloudSync.localBackups.title': 'Historial de copias de seguridad locales',
|
||||
'cloudSync.localBackups.desc': 'Netcatty conserva puntos de restauración locales antes de los cambios de versión de la app y antes de las restauraciones de la bóveda.',
|
||||
'cloudSync.localBackups.folderWarning': 'Esta carpeta por sí sola no es una copia de seguridad completa y portátil. Eliminar o vaciar el perfil de la aplicación (userData) puede impedir la lectura de estos puntos de restauración.',
|
||||
'cloudSync.localBackups.retentionTitle': 'Retención de copias de seguridad',
|
||||
'cloudSync.localBackups.retentionDesc': 'Elige cuántas copias de seguridad locales debe conservar Netcatty.',
|
||||
'cloudSync.localBackups.maxCount': 'Copias máximas',
|
||||
@@ -474,6 +475,7 @@ export const esTerminalMessages: Messages = {
|
||||
'cloudSync.localBackups.restoreSuccess': 'Copia de seguridad local restaurada.',
|
||||
'cloudSync.localBackups.restoreFailedTitle': 'Falló la restauración',
|
||||
'cloudSync.localBackups.restoreMissing': 'No se encontró la copia de seguridad.',
|
||||
'cloudSync.localBackups.decryptFailed': 'El perfil actual de la aplicación no puede descifrar esta copia. Puede faltar la clave de cifrado, haber cambiado el perfil o estar dañada la copia.',
|
||||
'cloudSync.localBackups.protectiveBackupFailed': 'No se pudo crear la copia de seguridad de protección, por lo que la restauración se canceló para proteger tus datos actuales. Resuelve el problema subyacente (p. ej., acceso al keychain) e inténtalo de nuevo. Detalles: {message}',
|
||||
'cloudSync.localBackups.restoreConfirmTitle': '¿Restaurar esta copia de seguridad?',
|
||||
'cloudSync.localBackups.restoreConfirmDesc': 'Tus hosts, claves, snippets y configuraciones actuales se reemplazarán con el contenido de esta copia de seguridad. Se crea automáticamente una instantánea de protección de tus datos actuales primero.',
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import {
|
||||
getBaseFallbackLocale,
|
||||
getLoadedLocaleMessages,
|
||||
getLocaleMessagesVersion,
|
||||
loadLocaleMessages,
|
||||
subscribeLocaleMessages,
|
||||
} from '../messages';
|
||||
|
||||
test('only English is loaded until another locale is requested', () => {
|
||||
assert.ok(getLoadedLocaleMessages('en'));
|
||||
assert.equal(getLoadedLocaleMessages('ru'), undefined);
|
||||
});
|
||||
|
||||
test('zh-TW resolves through zh-CN, matching the old static lookup order', () => {
|
||||
assert.equal(getBaseFallbackLocale('zh-TW'), 'zh-CN');
|
||||
assert.equal(getBaseFallbackLocale('zh-CN'), 'zh-CN');
|
||||
assert.equal(getBaseFallbackLocale('es'), 'es');
|
||||
assert.equal(getBaseFallbackLocale('fr'), undefined);
|
||||
});
|
||||
|
||||
test('loading a locale also loads its fallback and notifies subscribers once each', async () => {
|
||||
const before = getLocaleMessagesVersion();
|
||||
let notified = 0;
|
||||
const unsubscribe = subscribeLocaleMessages(() => { notified += 1; });
|
||||
await Promise.all([loadLocaleMessages('zh-TW'), loadLocaleMessages('zh-TW')]);
|
||||
unsubscribe();
|
||||
assert.ok(getLoadedLocaleMessages('zh-TW'));
|
||||
assert.ok(getLoadedLocaleMessages('zh-CN'), 'base fallback is loaded with zh-TW');
|
||||
assert.equal(notified, 2, 'one notification per newly loaded dictionary');
|
||||
assert.equal(getLocaleMessagesVersion(), before + 2);
|
||||
await loadLocaleMessages('zh-TW');
|
||||
assert.equal(getLocaleMessagesVersion(), before + 2, 'already loaded locales are not reloaded');
|
||||
});
|
||||
@@ -464,6 +464,8 @@ export const ruAiMessages: Messages = {
|
||||
'ai.chat.alwaysAllow': 'Всегда разрешать',
|
||||
'ai.chat.slashStopDesc': 'Остановить текущий ход AI и отменить выполняющиеся инструменты',
|
||||
'ai.chat.slashCompactDesc': 'Сжать ранний контекст разговора',
|
||||
'ai.chat.slashRenameDesc': 'Переименовать текущий чат (/rename <название>)',
|
||||
'ai.chat.slashChatsDesc': 'Показать чаты, видимые в этой панели',
|
||||
'ai.chat.reject': 'Отклонить',
|
||||
'ai.chat.toolLabel': 'Инструмент',
|
||||
'ai.chat.targetLabel': 'Цель',
|
||||
@@ -526,6 +528,28 @@ export const ruAiMessages: Messages = {
|
||||
'ai.chat.recent': 'Недавние',
|
||||
'ai.chat.viewAll': 'Показать всё',
|
||||
'ai.chat.untitled': 'Без названия',
|
||||
'ai.chat.renameChat': 'Переименовать чат',
|
||||
'ai.chat.renameUsage': 'Использование: /rename <новое название>',
|
||||
'ai.chat.renameNoActive': 'Нет активного чата для переименования.',
|
||||
'ai.chat.renameDone': 'Чат переименован в «{title}».',
|
||||
'ai.chat.exportSessions': 'Экспортировать чаты ИИ',
|
||||
'ai.chat.importSessions': 'Импортировать чаты ИИ',
|
||||
'ai.chat.exportDone': 'Чаты ИИ экспортированы в {path}.',
|
||||
'ai.chat.exportDoneNoPath': 'Чаты ИИ экспортированы.',
|
||||
'ai.chat.exportUnavailable': 'Экспорт чатов ИИ недоступен в этой среде.',
|
||||
'ai.chat.importDone': 'Импортировано чатов ИИ: {n}.',
|
||||
'ai.chat.importNone': 'В выбранном файле не найдено чатов ИИ.',
|
||||
'ai.chat.chatsHeader': 'Чаты, видимые в этой панели:',
|
||||
'ai.chat.chatsEmpty': 'В этой панели нет видимых чатов.',
|
||||
'ai.chat.chatsScopeWorkspace': 'Workspace',
|
||||
'ai.chat.chatsScopeTerminal': 'Терминал',
|
||||
'ai.chat.chatsScopeGlobal': 'Глобально',
|
||||
'ai.chat.chatsScopeDangling': 'Связь потеряна',
|
||||
'ai.chat.slashRebindDesc': 'Привязать потерянный чат к этой панели (/rebind <n>)',
|
||||
'ai.chat.chatsRebindHint': 'Потерянные чаты можно восстановить командой /rebind <n>.',
|
||||
'ai.chat.rebindUsage': 'Использование: /rebind <номер из /chats>',
|
||||
'ai.chat.rebindDone': 'Чат «{title}» привязан к этой панели.',
|
||||
'ai.chat.rebindUnavailable': 'В области этой панели нет цели для привязки.',
|
||||
'ai.chat.justNow': 'Только что',
|
||||
'ai.chat.minutesAgo': '{n}м назад',
|
||||
'ai.chat.hoursAgo': '{n}ч назад',
|
||||
@@ -724,4 +748,27 @@ export const ruAiMessages: Messages = {
|
||||
'zmodem.overwrite.skip': 'Пропустить',
|
||||
'zmodem.overwrite.cancel': 'Отмена',
|
||||
'settings.shortcuts.resetToDefault': 'Сбросить по умолчанию',
|
||||
"ai.toolSettings.immediate": "Изменения применяются сразу. Закрытие окна не отменяет их.",
|
||||
"ai.toolSettings.privacyOn": "Скрытие текста включено",
|
||||
"ai.toolSettings.privacyOff": "Скрытие текста выключено",
|
||||
"ai.toolSettings.ruleSummary": "Дополнительные диапазоны IP: {cidrs} · Пользовательские шаблоны: {patterns}",
|
||||
"ai.toolSettings.configurePrivacy": "Настроить приватность",
|
||||
"ai.toolSettings.unsaved": "Есть несохранённые изменения",
|
||||
"ai.toolSettings.viewSkills": "Инструкции CLI",
|
||||
"ai.toolSettings.viewPrompt": "Инструкции подключения",
|
||||
"ai.toolSettings.behavior": "Поведение MCP",
|
||||
"ai.toolSettings.configureBehavior": "Настроить поведение",
|
||||
"ai.toolSettings.configureClients": "Настроить клиенты",
|
||||
"ai.toolSettings.httpOn": "HTTP включён",
|
||||
"ai.toolSettings.httpOff": "HTTP выключен",
|
||||
"ai.toolSettings.loopback": "Только локальные подключения (127.0.0.1)",
|
||||
"ai.toolSettings.configureHttp": "Настроить HTTP",
|
||||
"ai.toolSettings.hideSecret": "Скрыть секрет",
|
||||
"ai.toolSettings.showSecret": "Показать секрет",
|
||||
"ai.toolSettings.manualSetup": "Ручная настройка",
|
||||
"ai.toolSettings.format": "Формат",
|
||||
"ai.toolSettings.connectionDetails": "Параметры подключения",
|
||||
"ai.toolSettings.conflict": "Настройки изменены в другом окне. Черновик сохранён. Отмените и откройте окно снова, чтобы загрузить сохранённые настройки.",
|
||||
"ai.toolSettings.retry": "Повторить",
|
||||
"ai.toolSettings.applyingHttp": "Применение настроек HTTP...",
|
||||
};
|
||||
@@ -134,7 +134,12 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.system.clearTempFiles': 'Очистить временные файлы',
|
||||
'settings.system.clearing': 'Очистка...',
|
||||
'settings.system.clearResult': 'Удалено файлов: {deleted}, ошибок: {failed}.',
|
||||
'settings.system.tempDirectoryHint': 'Временные файлы создаются при открытии удалённых файлов во внешних приложениях. Они автоматически очищаются при закрытии SFTP-сессий.',
|
||||
'settings.system.tempDirChoose': 'Выбрать папку',
|
||||
'settings.system.tempDirManual': 'Введите абсолютный путь к папке',
|
||||
'settings.system.tempDirApply': 'Применить',
|
||||
'settings.system.tempDirReset': 'Сбросить по умолчанию',
|
||||
'settings.system.tempDirError': 'Не удалось использовать эту папку.',
|
||||
'settings.system.tempDirectoryHint': 'Используется для промежуточного хранения SFTP-передач и файлов, открытых во внешних приложениях. Смена папки во время передачи может повлиять на эту передачу.',
|
||||
'settings.system.credentials.title': 'Защита учётных данных',
|
||||
'settings.system.credentials.status': 'Статус',
|
||||
'settings.system.credentials.checking': 'Проверка...',
|
||||
@@ -1240,6 +1245,9 @@ export const ruCoreMessages: Messages = {
|
||||
"settings.plugins.openManager": "Открыть управление плагинами",
|
||||
"settings.plugins.sources.conflict": "This ID is installed from another source. Uninstall and explicitly reset its private data before switching. Existing source:",
|
||||
"settings.plugins.sources.clearPrivate": "Also clear this source’s private data, grants and secrets to reinstall from another source. This cannot be undone.",
|
||||
"settings.plugins.sources.short.official": "Официальный",
|
||||
"settings.plugins.sources.short.thirdparty": "Сторонний",
|
||||
"settings.plugins.sources.short.local": "Локальный",
|
||||
"settings.plugins.sources.official": "Official marketplace",
|
||||
"settings.plugins.sources.thirdparty": "Third-party marketplace",
|
||||
"settings.plugins.sources.manage": "Manage sources",
|
||||
@@ -1258,6 +1266,7 @@ export const ruCoreMessages: Messages = {
|
||||
"settings.plugins.sources.local": "Local import",
|
||||
"settings.plugins.sources.all": "All sources",
|
||||
"settings.plugins.title": "Плагины",
|
||||
"settings.plugins.configuration": "Настройки плагина",
|
||||
"settings.plugins.description": "Управляйте плагинами и просматривайте каталог.",
|
||||
'settings.plugins.loading': 'Загрузка настроек плагинов…',
|
||||
'settings.plugins.empty': 'Включённые плагины не предоставляют настройки.',
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
export const ruMonitorMessages = {
|
||||
"monitor.systemDisks": "Системные разделы ({count})",
|
||||
"monitor.systemDisksAlert": "Использование системного раздела превышает 80 %; группа раскрыта автоматически.",
|
||||
"monitor.diskIoTotal": "Всего",
|
||||
"monitor.partitionIoHint": "Ввод-вывод блочного устройства точки монтирования. Точки одного устройства показывают одинаковые скорости. Недоступно до двух корректных замеров или без определённого устройства; macOS не поддерживается.",
|
||||
"monitor.diskIo": "Дисковый ввод-вывод",
|
||||
"monitor.diskRead": "Чтение",
|
||||
"monitor.diskWrite": "Запись",
|
||||
|
||||
@@ -478,6 +478,7 @@ export const ruTerminalMessages: Messages = {
|
||||
'cloudSync.localBackups.clearFailed': 'Не удалось удалить все локальные копии. Повторите попытку.',
|
||||
'cloudSync.localBackups.title': 'История локальных резервных копий',
|
||||
'cloudSync.localBackups.desc': 'Netcatty сохраняет локальные точки восстановления перед сменой версии приложения и перед восстановлением хранилища.',
|
||||
'cloudSync.localBackups.folderWarning': 'Эта папка сама по себе не является полной переносимой резервной копией. Удаление или очистка профиля приложения (userData) может сделать эти точки восстановления нечитаемыми.',
|
||||
'cloudSync.localBackups.retentionTitle': 'Хранение резервных копий',
|
||||
'cloudSync.localBackups.retentionDesc': 'Выберите, сколько локальных резервных копий должен хранить Netcatty.',
|
||||
'cloudSync.localBackups.maxCount': 'Макс. число копий',
|
||||
@@ -492,6 +493,7 @@ export const ruTerminalMessages: Messages = {
|
||||
'cloudSync.localBackups.restoreSuccess': 'Локальная резервная копия восстановлена.',
|
||||
'cloudSync.localBackups.restoreFailedTitle': 'Ошибка восстановления',
|
||||
'cloudSync.localBackups.restoreMissing': 'Резервная копия не найдена.',
|
||||
'cloudSync.localBackups.decryptFailed': 'Текущий профиль приложения не может расшифровать эту копию. Возможно, отсутствует ключ шифрования, профиль изменился или копия повреждена.',
|
||||
'cloudSync.localBackups.protectiveBackupFailed': 'Не удалось создать защитную резервную копию, поэтому восстановление было прервано для защиты ваших текущих данных. Устраните основную проблему (например, доступ к keychain) и попробуйте снова. Подробности: {message}',
|
||||
'cloudSync.localBackups.restoreConfirmTitle': 'Восстановить эту резервную копию?',
|
||||
'cloudSync.localBackups.restoreConfirmDesc': 'Ваши текущие хосты, ключи, сниппеты и настройки будут заменены содержимым этой резервной копии. Перед этим автоматически создаётся защитный снимок текущих данных.',
|
||||
|
||||
@@ -525,6 +525,8 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.chat.alwaysAllow': '始终',
|
||||
'ai.chat.slashStopDesc': '停止当前 AI 回合并取消进行中的工具',
|
||||
'ai.chat.slashCompactDesc': '压缩较早的会话上下文',
|
||||
'ai.chat.slashRenameDesc': '重命名当前聊天(/rename <标题>)',
|
||||
'ai.chat.slashChatsDesc': '列出此面板可见的聊天',
|
||||
'ai.chat.reject': '拒绝',
|
||||
'ai.chat.toolLabel': '工具',
|
||||
'ai.chat.targetLabel': '目标',
|
||||
@@ -587,6 +589,28 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.chat.recent': '最近',
|
||||
'ai.chat.viewAll': '查看全部',
|
||||
'ai.chat.untitled': '无标题',
|
||||
'ai.chat.renameChat': '重命名聊天',
|
||||
'ai.chat.renameUsage': '用法:/rename <新标题>',
|
||||
'ai.chat.renameNoActive': '当前没有可重命名的聊天。',
|
||||
'ai.chat.renameDone': '聊天已重命名为「{title}」。',
|
||||
'ai.chat.exportSessions': '导出 AI 会话',
|
||||
'ai.chat.importSessions': '导入 AI 会话',
|
||||
'ai.chat.exportDone': 'AI 会话已导出到 {path}。',
|
||||
'ai.chat.exportDoneNoPath': 'AI 会话已导出。',
|
||||
'ai.chat.exportUnavailable': '当前环境不支持导出 AI 会话。',
|
||||
'ai.chat.importDone': '已导入 {n} 个 AI 会话。',
|
||||
'ai.chat.importNone': '所选文件中没有可导入的 AI 会话。',
|
||||
'ai.chat.chatsHeader': '此面板可见的聊天:',
|
||||
'ai.chat.chatsEmpty': '此面板没有可见的聊天。',
|
||||
'ai.chat.chatsScopeWorkspace': '工作区',
|
||||
'ai.chat.chatsScopeTerminal': '终端',
|
||||
'ai.chat.chatsScopeGlobal': '全局',
|
||||
'ai.chat.chatsScopeDangling': '已断开关联',
|
||||
'ai.chat.slashRebindDesc': '将断联的聊天重绑到此面板(/rebind <序号>)',
|
||||
'ai.chat.chatsRebindHint': '断联的聊天可用 /rebind <序号> 恢复。',
|
||||
'ai.chat.rebindUsage': '用法:/rebind <序号>',
|
||||
'ai.chat.rebindDone': '聊天“{title}”已重绑到此面板。',
|
||||
'ai.chat.rebindUnavailable': '当前面板范围内没有可用的重绑目标。',
|
||||
'ai.chat.justNow': '刚刚',
|
||||
'ai.chat.minutesAgo': '{n}分钟前',
|
||||
'ai.chat.hoursAgo': '{n}小时前',
|
||||
@@ -795,4 +819,27 @@ export const zhCNAiMessages: Messages = {
|
||||
'zmodem.overwrite.skip': '跳过',
|
||||
'zmodem.overwrite.cancel': '取消',
|
||||
'settings.shortcuts.resetToDefault': '重置为默认',
|
||||
"ai.toolSettings.immediate": "更改立即生效,关闭此窗口不会撤销。",
|
||||
"ai.toolSettings.privacyOn": "已启用文本脱敏",
|
||||
"ai.toolSettings.privacyOff": "未启用文本脱敏",
|
||||
"ai.toolSettings.ruleSummary": "{cidrs} 个附加 IP 范围 · {patterns} 条自定义规则",
|
||||
"ai.toolSettings.configurePrivacy": "配置隐私",
|
||||
"ai.toolSettings.unsaved": "有未保存的更改",
|
||||
"ai.toolSettings.viewSkills": "查看 CLI 指引",
|
||||
"ai.toolSettings.viewPrompt": "查看接入提示词",
|
||||
"ai.toolSettings.behavior": "MCP 行为",
|
||||
"ai.toolSettings.configureBehavior": "配置行为",
|
||||
"ai.toolSettings.configureClients": "配置客户端",
|
||||
"ai.toolSettings.httpOn": "HTTP 已启用",
|
||||
"ai.toolSettings.httpOff": "HTTP 未启用",
|
||||
"ai.toolSettings.loopback": "仅本地连接(127.0.0.1)",
|
||||
"ai.toolSettings.configureHttp": "配置 HTTP",
|
||||
"ai.toolSettings.hideSecret": "隐藏密钥",
|
||||
"ai.toolSettings.showSecret": "显示密钥",
|
||||
"ai.toolSettings.manualSetup": "手动配置",
|
||||
"ai.toolSettings.format": "格式",
|
||||
"ai.toolSettings.connectionDetails": "连接详情",
|
||||
"ai.toolSettings.conflict": "设置已在另一窗口更改,当前草稿已保留。请取消并重新打开以加载已保存的设置。",
|
||||
"ai.toolSettings.retry": "重试",
|
||||
"ai.toolSettings.applyingHttp": "正在应用 HTTP 配置…",
|
||||
};
|
||||
@@ -165,7 +165,12 @@ export const zhCNCoreMessages: Messages = {
|
||||
'settings.system.clearTempFiles': '清理临时文件',
|
||||
'settings.system.clearing': '清理中...',
|
||||
'settings.system.clearResult': '已删除 {deleted} 个文件,{failed} 个失败。',
|
||||
'settings.system.tempDirectoryHint': '临时文件在使用外部应用打开远程文件时创建。SFTP 会话关闭时会自动清理。',
|
||||
'settings.system.tempDirChoose': '选择文件夹',
|
||||
'settings.system.tempDirManual': '输入绝对文件夹路径',
|
||||
'settings.system.tempDirApply': '应用',
|
||||
'settings.system.tempDirReset': '恢复默认',
|
||||
'settings.system.tempDirError': '无法使用此文件夹。',
|
||||
'settings.system.tempDirectoryHint': 'Netcatty 在所选文件夹中创建 Netcatty 临时子文件夹,用于 SFTP 传输暂存和外部编辑文件。传输期间更改文件夹可能影响该传输。',
|
||||
'settings.system.credentials.title': '凭据保护',
|
||||
'settings.system.credentials.status': '状态',
|
||||
'settings.system.credentials.checking': '检查中...',
|
||||
@@ -1290,6 +1295,9 @@ Vaults 标签保持扁平,不使用这块背景。
|
||||
"settings.plugins.openManager": "打开插件管理",
|
||||
"settings.plugins.sources.conflict": "此 ID 已从其他来源安装。请先卸载并明确清理旧来源数据,再换源重装。原来源:",
|
||||
"settings.plugins.sources.clearPrivate": "同时清除本来源的私有数据、授权和秘密,以便显式换源重装。此操作不可撤销。",
|
||||
"settings.plugins.sources.short.official": "官方",
|
||||
"settings.plugins.sources.short.thirdparty": "第三方",
|
||||
"settings.plugins.sources.short.local": "本地",
|
||||
"settings.plugins.sources.official": "官方市场",
|
||||
"settings.plugins.sources.thirdparty": "第三方市场",
|
||||
"settings.plugins.sources.manage": "管理来源",
|
||||
@@ -1308,6 +1316,7 @@ Vaults 标签保持扁平,不使用这块背景。
|
||||
"settings.plugins.sources.local": "本地导入",
|
||||
"settings.plugins.sources.all": "全部来源",
|
||||
"settings.plugins.title": "插件",
|
||||
"settings.plugins.configuration": "插件设置",
|
||||
"settings.plugins.description": "管理已安装插件,浏览精选目录。",
|
||||
'settings.plugins.loading': '正在加载插件设置…',
|
||||
'settings.plugins.empty': '当前没有已启用插件提供设置。',
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
export const zhCNMonitorMessages = {
|
||||
"monitor.systemDisks": "系统分区({count})",
|
||||
"monitor.systemDisksAlert": "系统分区使用率超过 80%,已自动展开。",
|
||||
"monitor.diskIoTotal": "汇总",
|
||||
"monitor.partitionIoHint": "此挂载点对应块设备的读写速率;共用设备的挂载点显示相同速率。取得两次有效采样前或无法识别块设备时显示 --;暂不支持 macOS。",
|
||||
"monitor.diskIo": "磁盘 I/O",
|
||||
"monitor.diskRead": "读取",
|
||||
"monitor.diskWrite": "写入",
|
||||
|
||||
@@ -888,6 +888,7 @@ export const zhCNVaultMessages: Messages = {
|
||||
'cloudSync.localBackups.clearFailed': '未能清空全部本地备份,请重试。',
|
||||
'cloudSync.localBackups.title': '本地备份历史',
|
||||
'cloudSync.localBackups.desc': 'Netcatty 会在版本变化前,以及恢复主机库前,自动留下一份本地恢复点。',
|
||||
'cloudSync.localBackups.folderWarning': '仅复制此文件夹并不构成完整、可迁移的备份。删除或清空应用配置目录(userData)可能导致这些恢复点无法读取。',
|
||||
'cloudSync.localBackups.retentionTitle': '备份保留数量',
|
||||
'cloudSync.localBackups.retentionDesc': '设置 Netcatty 最多保留多少份本地备份。',
|
||||
'cloudSync.localBackups.maxCount': '最多保留',
|
||||
@@ -902,6 +903,7 @@ export const zhCNVaultMessages: Messages = {
|
||||
'cloudSync.localBackups.restoreSuccess': '已恢复本地备份。',
|
||||
'cloudSync.localBackups.restoreFailedTitle': '恢复失败',
|
||||
'cloudSync.localBackups.restoreMissing': '找不到这份备份。',
|
||||
'cloudSync.localBackups.decryptFailed': '当前应用配置无法解密此备份。可能是加密密钥丢失、应用配置已更改,或备份已损坏。',
|
||||
'cloudSync.localBackups.protectiveBackupFailed': '无法创建保护性备份,已中止恢复以避免覆盖当前数据。请先解决底层问题(例如钥匙串访问)后重试。详情:{message}',
|
||||
'cloudSync.localBackups.restoreConfirmTitle': '确认恢复此备份?',
|
||||
'cloudSync.localBackups.restoreConfirmDesc': '当前的主机、密钥、代码片段与设置将被替换为此备份中的内容。系统会先自动创建一个保护性快照,便于撤销。',
|
||||
|
||||
@@ -515,6 +515,8 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.chat.alwaysAllow': '始終',
|
||||
'ai.chat.slashStopDesc': '停止目前 AI 回合並取消進行中的工具',
|
||||
'ai.chat.slashCompactDesc': '壓縮較早的對話上下文',
|
||||
'ai.chat.slashRenameDesc': '重新命名目前聊天(/rename <標題>)',
|
||||
'ai.chat.slashChatsDesc': '列出此面板可見的聊天',
|
||||
'ai.chat.reject': '拒絕',
|
||||
'ai.chat.toolLabel': '工具',
|
||||
'ai.chat.targetLabel': '目標',
|
||||
@@ -577,6 +579,28 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.chat.recent': '最近',
|
||||
'ai.chat.viewAll': '檢視全部',
|
||||
'ai.chat.untitled': '無標題',
|
||||
'ai.chat.renameChat': '重新命名聊天',
|
||||
'ai.chat.renameUsage': '用法:/rename <新標題>',
|
||||
'ai.chat.renameNoActive': '目前沒有可重新命名的聊天。',
|
||||
'ai.chat.renameDone': '聊天已重新命名為「{title}」。',
|
||||
'ai.chat.exportSessions': '匯出 AI 會話',
|
||||
'ai.chat.importSessions': '匯入 AI 會話',
|
||||
'ai.chat.exportDone': 'AI 會話已匯出到 {path}。',
|
||||
'ai.chat.exportDoneNoPath': 'AI 會話已匯出。',
|
||||
'ai.chat.exportUnavailable': '目前環境不支援匯出 AI 會話。',
|
||||
'ai.chat.importDone': '已匯入 {n} 個 AI 會話。',
|
||||
'ai.chat.importNone': '所選檔案中沒有可匯入的 AI 會話。',
|
||||
'ai.chat.chatsHeader': '此面板可見的聊天:',
|
||||
'ai.chat.chatsEmpty': '此面板沒有可見的聊天。',
|
||||
'ai.chat.chatsScopeWorkspace': '工作區',
|
||||
'ai.chat.chatsScopeTerminal': '終端',
|
||||
'ai.chat.chatsScopeGlobal': '全域',
|
||||
'ai.chat.chatsScopeDangling': '已斷開關聯',
|
||||
'ai.chat.slashRebindDesc': '將斷開關聯的聊天重新綁定到此面板(/rebind <序號>)',
|
||||
'ai.chat.chatsRebindHint': '斷開關聯的聊天可用 /rebind <序號> 恢復。',
|
||||
'ai.chat.rebindUsage': '用法:/rebind <序號>',
|
||||
'ai.chat.rebindDone': '聊天「{title}」已重新綁定到此面板。',
|
||||
'ai.chat.rebindUnavailable': '目前面板範圍內沒有可用的重新綁定目標。',
|
||||
'ai.chat.justNow': '剛剛',
|
||||
'ai.chat.minutesAgo': '{n}分鐘前',
|
||||
'ai.chat.hoursAgo': '{n}小時前',
|
||||
@@ -785,4 +809,27 @@ export const zhTWAiMessages: Messages = {
|
||||
'zmodem.overwrite.skip': '跳過',
|
||||
'zmodem.overwrite.cancel': '取消',
|
||||
'settings.shortcuts.resetToDefault': '重設為預設值',
|
||||
"ai.toolSettings.immediate": "變更立即生效,關閉此視窗不會復原。",
|
||||
"ai.toolSettings.privacyOn": "已啟用文字遮蔽",
|
||||
"ai.toolSettings.privacyOff": "未啟用文字遮蔽",
|
||||
"ai.toolSettings.ruleSummary": "{cidrs} 個額外 IP 範圍 · {patterns} 條自訂規則",
|
||||
"ai.toolSettings.configurePrivacy": "設定隱私",
|
||||
"ai.toolSettings.unsaved": "有未儲存的變更",
|
||||
"ai.toolSettings.viewSkills": "查看 CLI 指引",
|
||||
"ai.toolSettings.viewPrompt": "查看接入提示詞",
|
||||
"ai.toolSettings.behavior": "MCP 行為",
|
||||
"ai.toolSettings.configureBehavior": "設定行為",
|
||||
"ai.toolSettings.configureClients": "設定用戶端",
|
||||
"ai.toolSettings.httpOn": "HTTP 已啟用",
|
||||
"ai.toolSettings.httpOff": "HTTP 未啟用",
|
||||
"ai.toolSettings.loopback": "僅本機連線(127.0.0.1)",
|
||||
"ai.toolSettings.configureHttp": "設定 HTTP",
|
||||
"ai.toolSettings.hideSecret": "隱藏金鑰",
|
||||
"ai.toolSettings.showSecret": "顯示金鑰",
|
||||
"ai.toolSettings.manualSetup": "手動設定",
|
||||
"ai.toolSettings.format": "格式",
|
||||
"ai.toolSettings.connectionDetails": "連線詳情",
|
||||
"ai.toolSettings.conflict": "設定已在其他視窗變更,目前草稿已保留。請取消並重新開啟以載入已儲存的設定。",
|
||||
"ai.toolSettings.retry": "重試",
|
||||
"ai.toolSettings.applyingHttp": "正在套用 HTTP 設定…",
|
||||
};
|
||||
@@ -167,7 +167,12 @@ export const zhTWCoreMessages: Messages = {
|
||||
'settings.system.clearTempFiles': '清理臨時檔案',
|
||||
'settings.system.clearing': '清理中...',
|
||||
'settings.system.clearResult': '已刪除 {deleted} 個檔案,{failed} 個失敗。',
|
||||
'settings.system.tempDirectoryHint': '臨時檔案在使用外部應用程式開啟遠端檔案時建立。SFTP 工作階段關閉時會自動清理。',
|
||||
'settings.system.tempDirChoose': '選擇資料夾',
|
||||
'settings.system.tempDirManual': '輸入絕對資料夾路徑',
|
||||
'settings.system.tempDirApply': '套用',
|
||||
'settings.system.tempDirReset': '恢復預設',
|
||||
'settings.system.tempDirError': '無法使用此資料夾。',
|
||||
'settings.system.tempDirectoryHint': '用於 SFTP 傳輸暫存與外部編輯檔案。傳輸期間變更資料夾可能影響該傳輸。',
|
||||
'settings.system.credentials.title': '憑證保護',
|
||||
'settings.system.credentials.status': '狀態',
|
||||
'settings.system.credentials.checking': '檢查中...',
|
||||
@@ -1261,6 +1266,9 @@ Vaults 分頁維持扁平,不使用這塊背景。
|
||||
"settings.plugins.openManager": "開啟插件管理",
|
||||
"settings.plugins.sources.conflict": "此 ID 已从其他来源安装。请先卸载并明确清理旧来源数据,再换源重装。原来源:",
|
||||
"settings.plugins.sources.clearPrivate": "同时清除本来源的私有数据、授权和秘密,以便显式换源重装。此操作不可撤销。",
|
||||
"settings.plugins.sources.short.official": "官方",
|
||||
"settings.plugins.sources.short.thirdparty": "第三方",
|
||||
"settings.plugins.sources.short.local": "本機",
|
||||
"settings.plugins.sources.official": "官方市场",
|
||||
"settings.plugins.sources.thirdparty": "第三方市场",
|
||||
"settings.plugins.sources.manage": "管理来源",
|
||||
@@ -1279,6 +1287,7 @@ Vaults 分頁維持扁平,不使用這塊背景。
|
||||
"settings.plugins.sources.local": "本地导入",
|
||||
"settings.plugins.sources.all": "全部来源",
|
||||
"settings.plugins.title": "插件",
|
||||
"settings.plugins.configuration": "插件設定",
|
||||
"settings.plugins.description": "管理已安裝插件,瀏覽精選目錄。",
|
||||
'settings.plugins.loading': '正在載入外掛程式設定…',
|
||||
"settings.plugins.market.results": "{count} 個插件",
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
export const zhTWMonitorMessages = {
|
||||
"monitor.systemDisks": "系統分割區({count})",
|
||||
"monitor.systemDisksAlert": "系統分割區使用率超過 80%,已自動展開。",
|
||||
"monitor.diskIoTotal": "彙總",
|
||||
"monitor.partitionIoHint": "此掛載點對應區塊裝置的讀寫速率;共用裝置的掛載點顯示相同速率。取得兩次有效取樣前或無法識別區塊裝置時顯示 --;暫不支援 macOS。",
|
||||
"monitor.diskIo": "磁碟 I/O",
|
||||
"monitor.diskRead": "讀取",
|
||||
"monitor.diskWrite": "寫入",
|
||||
|
||||
@@ -888,6 +888,7 @@ export const zhTWVaultMessages: Messages = {
|
||||
'cloudSync.localBackups.clearFailed': '未能清空全部本機備份,請重試。',
|
||||
'cloudSync.localBackups.title': '本機備份歷史',
|
||||
'cloudSync.localBackups.desc': 'Netcatty 會在版本變化前,以及恢復主機庫前,自動留下一份本機恢復點。',
|
||||
'cloudSync.localBackups.folderWarning': '僅複製此資料夾並不構成完整、可攜的備份。刪除或清空應用程式設定目錄(userData)可能導致這些還原點無法讀取。',
|
||||
'cloudSync.localBackups.retentionTitle': '備份保留數量',
|
||||
'cloudSync.localBackups.retentionDesc': '設定 Netcatty 最多保留多少份本機備份。',
|
||||
'cloudSync.localBackups.maxCount': '最多保留',
|
||||
@@ -902,6 +903,7 @@ export const zhTWVaultMessages: Messages = {
|
||||
'cloudSync.localBackups.restoreSuccess': '已恢復本機備份。',
|
||||
'cloudSync.localBackups.restoreFailedTitle': '恢復失敗',
|
||||
'cloudSync.localBackups.restoreMissing': '找不到這份備份。',
|
||||
'cloudSync.localBackups.decryptFailed': '目前的應用程式設定無法解密此備份。可能是加密金鑰遺失、應用程式設定已變更,或備份已損毀。',
|
||||
'cloudSync.localBackups.protectiveBackupFailed': '無法建立保護性備份,已中止恢復以避免覆蓋目前資料。請先解決底層問題(例如鑰匙串存取)後重試。詳情:{message}',
|
||||
'cloudSync.localBackups.restoreConfirmTitle': '確認恢復此備份?',
|
||||
'cloudSync.localBackups.restoreConfirmDesc': '目前的主機、金鑰、程式碼片段與設定將被替換為此備份中的內容。系統會先自動建立一個保護性快照,便於復原。',
|
||||
|
||||
@@ -1,17 +1,78 @@
|
||||
import en, { type Messages } from './locales/en';
|
||||
import zhCN from './locales/zh-CN';
|
||||
import zhTW from './locales/zh-TW';
|
||||
import ru from './locales/ru';
|
||||
import es from './locales/es';
|
||||
|
||||
// Keep keys stable; add new locales by adding another import and map entry.
|
||||
// Keep keys stable; add new locales by adding a loader below and an entry in
|
||||
// SUPPORTED_UI_LOCALES (infrastructure/config/i18n.ts).
|
||||
export { type Messages };
|
||||
|
||||
export const MESSAGES_BY_LOCALE: Record<string, Messages> = {
|
||||
en,
|
||||
ru,
|
||||
es,
|
||||
'zh-CN': zhCN,
|
||||
'zh-TW': zhTW,
|
||||
/**
|
||||
* Lookup order for the "same base language" fallback in I18nProvider (for
|
||||
* example zh-TW falls back to zh-CN, the first `zh*` entry). Matches the key
|
||||
* order of the old static MESSAGES_BY_LOCALE map.
|
||||
*/
|
||||
export const LOCALE_MESSAGE_KEYS = ['en', 'ru', 'es', 'zh-CN', 'zh-TW'] as const;
|
||||
|
||||
/**
|
||||
* Only English is bundled with the startup chunk; other locales are loaded on
|
||||
* demand. All five dictionaries used to be parsed by every window at startup
|
||||
* (~1.3 MB of the entry chunk) even though one locale is in use.
|
||||
*/
|
||||
const LOCALE_LOADERS: Record<string, () => Promise<{ default: Messages }>> = {
|
||||
ru: () => import('./locales/ru'),
|
||||
es: () => import('./locales/es'),
|
||||
'zh-CN': () => import('./locales/zh-CN'),
|
||||
'zh-TW': () => import('./locales/zh-TW'),
|
||||
};
|
||||
|
||||
const loadedMessages: Record<string, Messages> = { en };
|
||||
const pendingLoads = new Map<string, Promise<void>>();
|
||||
const listeners = new Set<() => void>();
|
||||
let messagesVersion = 0;
|
||||
|
||||
export function getLoadedLocaleMessages(locale: string): Messages | undefined {
|
||||
return loadedMessages[locale];
|
||||
}
|
||||
|
||||
export function getLocaleMessagesVersion(): number {
|
||||
return messagesVersion;
|
||||
}
|
||||
|
||||
export function subscribeLocaleMessages(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
/** The same-base fallback locale that I18nProvider consults for `locale`. */
|
||||
export function getBaseFallbackLocale(locale: string): string | undefined {
|
||||
const base = locale.split('-')[0];
|
||||
return LOCALE_MESSAGE_KEYS.find((key) => key === base || key.startsWith(`${base}-`));
|
||||
}
|
||||
|
||||
function loadOne(locale: string): Promise<void> {
|
||||
if (loadedMessages[locale]) return Promise.resolve();
|
||||
const loader = LOCALE_LOADERS[locale];
|
||||
if (!loader) return Promise.resolve();
|
||||
let pending = pendingLoads.get(locale);
|
||||
if (!pending) {
|
||||
pending = loader()
|
||||
.then((module) => {
|
||||
loadedMessages[locale] = module.default;
|
||||
messagesVersion += 1;
|
||||
for (const listener of listeners) listener();
|
||||
})
|
||||
.finally(() => {
|
||||
pendingLoads.delete(locale);
|
||||
});
|
||||
pendingLoads.set(locale, pending);
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** Load the dictionaries `locale` resolves through (itself and its base fallback). */
|
||||
export function loadLocaleMessages(locale: string): Promise<void> {
|
||||
const needed = new Set([locale]);
|
||||
const fallback = getBaseFallbackLocale(locale);
|
||||
if (fallback) needed.add(fallback);
|
||||
return Promise.all([...needed].map(loadOne)).then(() => undefined);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { requestAgentSessionReconnect } from './agentSessionReconnect';
|
||||
|
||||
test('reconnect preserves identity and only dispatches disconnected eligible sessions', () => {
|
||||
let calls = 0;
|
||||
const registry = { isActive: () => false, requestIfAvailable: () => { calls++; return true; } };
|
||||
assert.equal(requestAgentSessionReconnect('s', undefined, registry).ok, false);
|
||||
assert.equal(requestAgentSessionReconnect('s', 'connected', registry).status, 'connected');
|
||||
assert.equal(requestAgentSessionReconnect('s', 'connecting', registry).started, false);
|
||||
const result = requestAgentSessionReconnect('s', 'disconnected', registry);
|
||||
assert.deepEqual(result, { ok: true, started: true, sessionId: 's', status: 'reconnecting', shellReady: false });
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
test('auto/manual reconnect and unavailable terminal cannot queue another recovery', () => {
|
||||
const registry = { isActive: () => true, requestIfAvailable: () => { throw Error('must not dispatch'); } };
|
||||
assert.equal(requestAgentSessionReconnect('s', 'disconnected', registry).started, false);
|
||||
assert.equal(requestAgentSessionReconnect('s', 'disconnected', { isActive: () => false, requestIfAvailable: () => false }).code, 'RECONNECT_UNAVAILABLE');
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
type ReconnectRegistry = {
|
||||
isActive: (sessionId: string) => boolean;
|
||||
requestIfAvailable: (sessionId: string) => boolean;
|
||||
};
|
||||
|
||||
/** Synchronous dispatch only: no queued recovery after scope/terminal disposal. */
|
||||
export function requestAgentSessionReconnect(
|
||||
sessionId: string,
|
||||
status: string | undefined,
|
||||
registry: ReconnectRegistry,
|
||||
): Record<string, unknown> {
|
||||
if (!status) return { ok: false, started: false, error: `Session "${sessionId}" was not found.` };
|
||||
if (status === 'connected') return { ok: true, started: false, sessionId, status: 'connected', shellReady: false };
|
||||
if (status === 'connecting' || registry.isActive(sessionId)) {
|
||||
return { ok: true, started: false, sessionId, status: 'reconnecting' };
|
||||
}
|
||||
if (status !== 'disconnected' || !registry.requestIfAvailable(sessionId)) {
|
||||
return { ok: false, started: false, sessionId, code: 'RECONNECT_UNAVAILABLE', error: 'Reconnect is unavailable: terminal may be unmounted, waiting for authentication, or recovering. Inspect session state and the Netcatty UI.' };
|
||||
}
|
||||
return { ok: true, started: true, sessionId, status: 'reconnecting', shellReady: false };
|
||||
}
|
||||
@@ -2,14 +2,9 @@ import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import type {
|
||||
AIPanelView,
|
||||
AISession,
|
||||
} from "../../infrastructure/ai/types.ts";
|
||||
import { createEmptyDraft } from "./aiDraftState.ts";
|
||||
import {
|
||||
pruneInactiveScopedSessions,
|
||||
pruneInactiveScopedTransientState,
|
||||
} from "./aiScopeCleanup.ts";
|
||||
import { pruneInactiveScopedSessions } from "./aiScopeCleanup.ts";
|
||||
|
||||
function createSession(id: string, scope: AISession["scope"], externalSessionId?: string): AISession {
|
||||
return {
|
||||
@@ -24,47 +19,6 @@ function createSession(id: string, scope: AISession["scope"], externalSessionId?
|
||||
};
|
||||
}
|
||||
|
||||
test("pruneInactiveScopedTransientState removes closed workspace and terminal scope state", () => {
|
||||
const activeSessionIdMap = {
|
||||
"terminal:open-terminal": "session-open",
|
||||
"terminal:closed-terminal": "session-closed-terminal",
|
||||
"workspace:open-workspace": "session-open-workspace",
|
||||
"workspace:closed-workspace": "session-closed-workspace",
|
||||
};
|
||||
const draftsByScope = {
|
||||
"terminal:open-terminal": createEmptyDraft("catty"),
|
||||
"terminal:closed-terminal": createEmptyDraft("catty"),
|
||||
"workspace:open-workspace": createEmptyDraft("catty"),
|
||||
"workspace:closed-workspace": createEmptyDraft("catty"),
|
||||
};
|
||||
const panelViewByScope = {
|
||||
"terminal:open-terminal": { mode: "draft" },
|
||||
"terminal:closed-terminal": { mode: "session", sessionId: "session-closed-terminal" },
|
||||
"workspace:open-workspace": { mode: "draft" },
|
||||
"workspace:closed-workspace": { mode: "session", sessionId: "session-closed-workspace" },
|
||||
} satisfies Record<string, AIPanelView>;
|
||||
|
||||
const next = pruneInactiveScopedTransientState(
|
||||
activeSessionIdMap,
|
||||
draftsByScope,
|
||||
panelViewByScope,
|
||||
new Set(["open-terminal", "open-workspace"]),
|
||||
);
|
||||
|
||||
assert.deepEqual(next.activeSessionIdMap, {
|
||||
"terminal:open-terminal": "session-open",
|
||||
"workspace:open-workspace": "session-open-workspace",
|
||||
});
|
||||
assert.deepEqual(next.draftsByScope, {
|
||||
"terminal:open-terminal": draftsByScope["terminal:open-terminal"],
|
||||
"workspace:open-workspace": draftsByScope["workspace:open-workspace"],
|
||||
});
|
||||
assert.deepEqual(next.panelViewByScope, {
|
||||
"terminal:open-terminal": panelViewByScope["terminal:open-terminal"],
|
||||
"workspace:open-workspace": panelViewByScope["workspace:open-workspace"],
|
||||
});
|
||||
});
|
||||
|
||||
test("pruneInactiveScopedSessions reports inactive targets without deleting persisted history", () => {
|
||||
const sessions = [
|
||||
createSession("terminal-restorable", {
|
||||
|
||||
@@ -6,7 +6,6 @@ import type {
|
||||
|
||||
type DraftsByScope = Partial<Record<string, AIDraft>>;
|
||||
type PanelViewByScope = Partial<Record<string, AIPanelView>>;
|
||||
type ActiveSessionIdMap = Record<string, string | null>;
|
||||
|
||||
function isInactiveScopedTarget(
|
||||
scopeKey: string,
|
||||
@@ -55,41 +54,6 @@ export function pruneInactiveScopedState(
|
||||
};
|
||||
}
|
||||
|
||||
export function pruneInactiveScopedTransientState(
|
||||
activeSessionIdMap: ActiveSessionIdMap,
|
||||
draftsByScope: DraftsByScope,
|
||||
panelViewByScope: PanelViewByScope,
|
||||
activeTargetIds: Set<string>,
|
||||
): {
|
||||
activeSessionIdMap: ActiveSessionIdMap;
|
||||
draftsByScope: DraftsByScope;
|
||||
panelViewByScope: PanelViewByScope;
|
||||
} {
|
||||
let activeSessionMapChanged = false;
|
||||
const nextActiveSessionIdMap: ActiveSessionIdMap = {};
|
||||
|
||||
for (const [scopeKey, sessionId] of Object.entries(activeSessionIdMap)) {
|
||||
if (isInactiveScopedTarget(scopeKey, activeTargetIds)) {
|
||||
activeSessionMapChanged = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
nextActiveSessionIdMap[scopeKey] = sessionId;
|
||||
}
|
||||
|
||||
const nextScopedState = pruneInactiveScopedState(
|
||||
draftsByScope,
|
||||
panelViewByScope,
|
||||
activeTargetIds,
|
||||
);
|
||||
|
||||
return {
|
||||
activeSessionIdMap: activeSessionMapChanged ? nextActiveSessionIdMap : activeSessionIdMap,
|
||||
draftsByScope: nextScopedState.draftsByScope,
|
||||
panelViewByScope: nextScopedState.panelViewByScope,
|
||||
};
|
||||
}
|
||||
|
||||
export function pruneInactiveScopedSessions(
|
||||
sessions: AISession[],
|
||||
activeTargetIds: Set<string>,
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import type { AISession } from '../../infrastructure/ai/types';
|
||||
import {
|
||||
DebouncedBackupMirror,
|
||||
isMissingOrCorruptSessionsStore,
|
||||
mergeImportedSessions,
|
||||
parseBackupSessions,
|
||||
readLiveSessionsArray,
|
||||
shouldRestoreFromBackup,
|
||||
} from './aiSessionsBackup';
|
||||
import { prepareRestoredSessions, pruneSessionsForStorage } from './aiStateSnapshots';
|
||||
|
||||
function makeSession(id: string, updatedAt = 1_000): AISession {
|
||||
return {
|
||||
id,
|
||||
title: id,
|
||||
agentId: 'catty',
|
||||
scope: { type: 'workspace', targetId: 'ws-1' },
|
||||
messages: [],
|
||||
createdAt: updatedAt,
|
||||
updatedAt,
|
||||
} as never;
|
||||
}
|
||||
|
||||
test('isMissingOrCorruptSessionsStore distinguishes missing or corrupt stores from valid arrays', () => {
|
||||
assert.equal(isMissingOrCorruptSessionsStore(null), true);
|
||||
assert.equal(isMissingOrCorruptSessionsStore(''), true);
|
||||
assert.equal(isMissingOrCorruptSessionsStore('[]'), false);
|
||||
assert.equal(isMissingOrCorruptSessionsStore('{corrupt'), true);
|
||||
assert.equal(isMissingOrCorruptSessionsStore('{}'), true);
|
||||
assert.equal(isMissingOrCorruptSessionsStore('[{"id":"s1"}]'), false);
|
||||
});
|
||||
|
||||
test('readLiveSessionsArray normalizes missing and corrupt stores', () => {
|
||||
for (const raw of [null, undefined, '', '{}', 'not-json']) {
|
||||
assert.deepEqual(readLiveSessionsArray(raw), []);
|
||||
}
|
||||
const sessions = [makeSession('s1')];
|
||||
assert.deepEqual(readLiveSessionsArray(JSON.stringify(sessions)), sessions);
|
||||
});
|
||||
|
||||
test('parseBackupSessions ignores corrupt payloads and drops malformed entries', () => {
|
||||
assert.equal(parseBackupSessions(null), null);
|
||||
assert.equal(parseBackupSessions(''), null);
|
||||
assert.equal(parseBackupSessions('not json'), null);
|
||||
assert.equal(parseBackupSessions('{"id":"s1"}'), null);
|
||||
assert.equal(parseBackupSessions(JSON.stringify([{ id: 's1' }])), null);
|
||||
const sessions = parseBackupSessions(JSON.stringify([
|
||||
{ id: 's1' },
|
||||
{ nope: true },
|
||||
{ id: 'missing-scope', title: 'Missing scope', agentId: 'catty', messages: [], updatedAt: 1000 },
|
||||
{ ...makeSession('null-scope'), scope: null },
|
||||
{ ...makeSession('missing-title'), title: undefined },
|
||||
{ ...makeSession('missing-agent'), agentId: undefined },
|
||||
{ ...makeSession('null-message'), messages: [null] },
|
||||
{ ...makeSession('incomplete-message'), messages: [{ id: 'm' }] },
|
||||
{ ...makeSession('missing-content'), messages: [{ id: 'm', role: 'user', timestamp: 1000 }] },
|
||||
{ ...makeSession('invalid-content'), messages: [{ id: 'm', role: 'user', timestamp: 1000, content: null }] },
|
||||
{ ...makeSession('invalid-timestamp'), messages: [{ id: 'm', role: 'user', timestamp: null, content: 'hello' }] },
|
||||
null,
|
||||
{ ...makeSession('s2'), messages: [{ id: 'm', role: 'user', timestamp: 1000, content: 'hello' }] },
|
||||
]));
|
||||
assert.deepEqual(sessions?.map((session) => session.id), ['s2']);
|
||||
});
|
||||
|
||||
test('restore preserves all sessions when cloud sync is enabled', () => {
|
||||
const sessions = Array.from({ length: 51 }, (_, index) => makeSession(`s${index}`, index));
|
||||
assert.deepEqual(prepareRestoredSessions(sessions, true), sessions);
|
||||
const local = prepareRestoredSessions(sessions, false);
|
||||
assert.equal(local.length, 50);
|
||||
assert.equal(local.some(session => session.id === 's0'), false);
|
||||
});
|
||||
|
||||
test('malformed imports cannot reach pruning or inject broken sessions', () => {
|
||||
const current = [makeSession('live')];
|
||||
const malformed = parseBackupSessions(JSON.stringify([{ id: 's1' }]));
|
||||
assert.deepEqual(mergeImportedSessions(current, pruneSessionsForStorage(malformed ?? [])), current);
|
||||
const valid = parseBackupSessions(JSON.stringify([{ id: 's1' }, makeSession('valid')]));
|
||||
const merged = mergeImportedSessions(current, pruneSessionsForStorage(valid ?? []));
|
||||
assert.deepEqual(new Set(merged.map((session) => session.id)), new Set(['live', 'valid']));
|
||||
});
|
||||
|
||||
test('restore happens only on a missing or corrupt live store with a non-empty backup', () => {
|
||||
const backup = JSON.stringify([makeSession('s1')]);
|
||||
// Empty (or wiped) store -> restore.
|
||||
assert.equal(shouldRestoreFromBackup(null, backup), true);
|
||||
assert.equal(shouldRestoreFromBackup('', backup), true);
|
||||
assert.equal(shouldRestoreFromBackup('[]', backup), false);
|
||||
assert.equal(shouldRestoreFromBackup('{corrupt', backup), true);
|
||||
// Non-empty live store -> never restore (explicit deletions must win).
|
||||
assert.equal(shouldRestoreFromBackup('[{"id":"live"}]', backup), false);
|
||||
// Empty/corrupt backup -> nothing to restore.
|
||||
assert.equal(shouldRestoreFromBackup(null, null), false);
|
||||
assert.equal(shouldRestoreFromBackup(null, '[]'), false);
|
||||
assert.equal(shouldRestoreFromBackup(null, '{corrupt'), false);
|
||||
});
|
||||
|
||||
test('mergeImportedSessions keys by id with the newer updatedAt winning', () => {
|
||||
const current = [makeSession('keep', 100), makeSession('older', 100)];
|
||||
const imported = [makeSession('newer', 200), makeSession('older', 50), makeSession('added', 1)];
|
||||
const merged = mergeImportedSessions(current, imported);
|
||||
const byId = new Map(merged.map((session) => [session.id, session]));
|
||||
assert.equal(byId.get('older')?.updatedAt, 100);
|
||||
assert.equal(byId.get('newer')?.updatedAt, 200);
|
||||
assert.equal(byId.has('added'), true);
|
||||
assert.equal(byId.has('keep'), true);
|
||||
// Sorted newest-first for stable history ordering.
|
||||
assert.deepEqual(
|
||||
merged.map((session) => session.updatedAt),
|
||||
[...merged.map((session) => session.updatedAt)].sort((a, b) => b - a),
|
||||
);
|
||||
});
|
||||
|
||||
test('DebouncedBackupMirror writes once per batch with the last payload', async () => {
|
||||
const writes: string[] = [];
|
||||
const mirror = new DebouncedBackupMirror((json) => writes.push(json), 15);
|
||||
mirror.schedule('{"gen":1}');
|
||||
mirror.schedule('{"gen":2}');
|
||||
await new Promise((resolve) => setTimeout(resolve, 30));
|
||||
mirror.schedule('{"gen":3}');
|
||||
mirror.schedule('{"gen":4}');
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
assert.deepEqual(writes, ['{"gen":2}', '{"gen":4}']);
|
||||
});
|
||||
|
||||
test('DebouncedBackupMirror flushNow writes the pending payload immediately', () => {
|
||||
const writes: string[] = [];
|
||||
const mirror = new DebouncedBackupMirror((json) => writes.push(json), 60_000);
|
||||
mirror.schedule('{"gen":1}');
|
||||
mirror.flushNow();
|
||||
assert.deepEqual(writes, ['{"gen":1}']);
|
||||
// A second flush with nothing pending is a no-op.
|
||||
mirror.flushNow();
|
||||
assert.deepEqual(writes, ['{"gen":1}']);
|
||||
});
|
||||
|
||||
test('readLiveSessionsArray treats non-array JSON as empty (corrupt)', () => {
|
||||
assert.deepEqual(readLiveSessionsArray(null), []);
|
||||
assert.deepEqual(readLiveSessionsArray(''), []);
|
||||
assert.deepEqual(readLiveSessionsArray('{}'), []);
|
||||
assert.deepEqual(readLiveSessionsArray('{"sessions":[]}'), []);
|
||||
assert.deepEqual(readLiveSessionsArray('not-json'), []);
|
||||
assert.deepEqual(readLiveSessionsArray('[]'), []);
|
||||
assert.equal(readLiveSessionsArray('[{"id":"a"}]').length, 1);
|
||||
});
|
||||
@@ -0,0 +1,162 @@
|
||||
import type { AISession } from '../../infrastructure/ai/types';
|
||||
|
||||
/**
|
||||
* Renderer-side logic for the AI session durability layer (issue #4015 R2
|
||||
* follow-up): a disk mirror of the localStorage session store plus a
|
||||
* restore-on-empty-store boot path. The IPC plumbing lives in
|
||||
* `electron/bridges/aiSessionsBackupBridge.cjs`; this module keeps the
|
||||
* decisions pure so they can be tested without Electron.
|
||||
*/
|
||||
|
||||
/** Debounce window: at most one backup write per mutation burst (~2s). */
|
||||
export const AI_SESSIONS_BACKUP_DEBOUNCE_MS = 2000;
|
||||
|
||||
export interface AiSessionsBackupBridge {
|
||||
aiSessionsBackupWrite?: (payload: { json: string }) => Promise<{ ok: boolean }>;
|
||||
aiSessionsBackupReadLatest?: () => Promise<{ ok: boolean; json?: string }>;
|
||||
aiSessionsBackupExport?: (payload: { json: string }) => Promise<{ success: boolean; filePath?: string }>;
|
||||
aiSessionsBackupImport?: () => Promise<{ success: boolean; json?: string }>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the live sessions store once, returning both whether it is usable and
|
||||
* its sessions. The history is often several MB; the helpers below used to
|
||||
* parse it twice per call, and mount ran them back to back (five parses).
|
||||
*/
|
||||
export function parseSessionsStore(raw: string | null | undefined): { valid: boolean; sessions: AISession[] } {
|
||||
if (raw == null || raw === '') return { valid: false, sessions: [] };
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
return Array.isArray(parsed)
|
||||
? { valid: true, sessions: parsed as AISession[] }
|
||||
: { valid: false, sessions: [] };
|
||||
} catch {
|
||||
return { valid: false, sessions: [] };
|
||||
}
|
||||
}
|
||||
|
||||
/** Restore only when the live store is missing or malformed. A valid empty
|
||||
* array represents an intentional deletion and must remain authoritative. */
|
||||
export function isMissingOrCorruptSessionsStore(raw: string | null | undefined): boolean {
|
||||
return !parseSessionsStore(raw).valid;
|
||||
}
|
||||
|
||||
/** Read the live sessions array from a raw localStorage string. Returns [] when
|
||||
* missing/corrupt (including parseable non-arrays such as `{}`), so callers never
|
||||
* treat a non-array as AISession[]. */
|
||||
export function readLiveSessionsArray(raw: string | null | undefined): AISession[] {
|
||||
return parseSessionsStore(raw).sessions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a backup payload into sessions. Returns null when the payload is
|
||||
* corrupt or malformed (ignored gracefully); also drops entries without a
|
||||
* usable required fields. Backup generations are written by the same serializer as the
|
||||
* live store, so entries are expected to be full AISession objects.
|
||||
*/
|
||||
|
||||
export function parseBackupSessions(json: string | null | undefined): AISession[] | null {
|
||||
if (typeof json !== 'string' || json === '') return null;
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(json);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!Array.isArray(parsed)) return null;
|
||||
const sessions = parsed.filter(
|
||||
(entry): entry is AISession => (
|
||||
typeof entry === 'object' && entry !== null
|
||||
&& typeof (entry as AISession).id === 'string'
|
||||
&& typeof (entry as AISession).title === 'string'
|
||||
&& typeof (entry as AISession).agentId === 'string'
|
||||
&& typeof (entry as AISession).scope === 'object'
|
||||
&& (entry as AISession).scope !== null
|
||||
&& typeof (entry as AISession).scope.type === 'string'
|
||||
&& Array.isArray((entry as AISession).messages)
|
||||
&& (entry as AISession).messages.every(message => (
|
||||
typeof message === 'object' && message !== null
|
||||
&& typeof message.id === 'string'
|
||||
&& typeof message.role === 'string'
|
||||
&& typeof message.content === 'string'
|
||||
&& typeof message.timestamp === 'number'
|
||||
&& Number.isFinite(message.timestamp)
|
||||
))
|
||||
&& typeof (entry as AISession).updatedAt === 'number'
|
||||
&& Number.isFinite((entry as AISession).updatedAt)
|
||||
),
|
||||
);
|
||||
return sessions.length > 0 ? sessions : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decide whether to restore on boot: only when the live store is missing or corrupt AND
|
||||
* the backup actually contains at least one session.
|
||||
*/
|
||||
export function shouldRestoreFromBackup(
|
||||
liveRaw: string | null | undefined,
|
||||
backupJson: string | null | undefined,
|
||||
): boolean {
|
||||
if (!isMissingOrCorruptSessionsStore(liveRaw)) return false;
|
||||
const sessions = parseBackupSessions(backupJson);
|
||||
return sessions != null && sessions.length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge an imported backup into the current store: entries are keyed by id
|
||||
* and the newer `updatedAt` wins. Explicit user action, so it may overwrite
|
||||
* the live store (unlike the boot restore, which is empty-only).
|
||||
*/
|
||||
export function mergeImportedSessions(current: AISession[], imported: AISession[]): AISession[] {
|
||||
const byId = new Map<string, AISession>();
|
||||
for (const session of current) byId.set(session.id, session);
|
||||
for (const session of imported) {
|
||||
const existing = byId.get(session.id);
|
||||
if (!existing || (session.updatedAt ?? 0) >= (existing.updatedAt ?? 0)) {
|
||||
byId.set(session.id, session);
|
||||
}
|
||||
}
|
||||
return Array.from(byId.values()).sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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).
|
||||
*/
|
||||
export class DebouncedBackupMirror {
|
||||
private timer: ReturnType<typeof setTimeout> | null = null;
|
||||
private pendingJson: string | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly write: (json: string) => void,
|
||||
private readonly debounceMs: number = AI_SESSIONS_BACKUP_DEBOUNCE_MS,
|
||||
) {}
|
||||
|
||||
schedule(json: string) {
|
||||
this.pendingJson = json;
|
||||
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);
|
||||
}, this.debounceMs);
|
||||
}
|
||||
|
||||
flushNow() {
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
const json = this.pendingJson;
|
||||
this.pendingJson = null;
|
||||
if (json != null) this.write(json);
|
||||
}
|
||||
|
||||
reset() {
|
||||
if (this.timer) clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
this.pendingJson = null;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,16 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import test, { type TestContext } from 'node:test';
|
||||
import { createAiPrivacyService } from '../../electron/shared/aiPrivacyService.cjs';
|
||||
import {
|
||||
hasReversibleModelPrivacy,
|
||||
setReversibleModelPrivacy,
|
||||
} from '../../infrastructure/ai/harness/modelSecretRedaction';
|
||||
import {
|
||||
STORAGE_KEY_AI_SESSIONS,
|
||||
STORAGE_KEY_AI_SESSIONS_OVERFLOW,
|
||||
STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW,
|
||||
STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS,
|
||||
} from '../../infrastructure/config/storageKeys';
|
||||
import type { AISession } from '../../infrastructure/ai/types';
|
||||
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
import {
|
||||
@@ -16,6 +22,12 @@ import {
|
||||
latestAISessionsSnapshot,
|
||||
setLatestAIActiveSessionMapSnapshot,
|
||||
setLatestAISessionsSnapshot,
|
||||
rebindActiveSessionMap,
|
||||
readSessionsFromStorage,
|
||||
prewarmAIStateStorageSnapshots,
|
||||
writeSessionsForStorage,
|
||||
flushBackupMirror,
|
||||
__resetBackupMirrorForTests,
|
||||
} from './aiStateSnapshots';
|
||||
|
||||
test('orphan cleanup keeps durable Catty output while explicit deletion removes it', async () => {
|
||||
@@ -72,6 +84,424 @@ function makeSession(id: string, updatedAt: number, messages: unknown[]): AISess
|
||||
} as never;
|
||||
}
|
||||
|
||||
function installSessionStorage(t: TestContext, aggregateQuota = Number.POSITIVE_INFINITY) {
|
||||
const storage = new Map<string, string>();
|
||||
const previousStorage = globalThis.localStorage;
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
configurable: true,
|
||||
value: {
|
||||
getItem: (key: string) => storage.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => {
|
||||
const storedBytes = [...storage].reduce((total, [storedKey, storedValue]) => (
|
||||
total + (storedKey === key ? 0 : Buffer.byteLength(storedKey + storedValue))
|
||||
), 0);
|
||||
if (storedBytes + Buffer.byteLength(key + value) > aggregateQuota) {
|
||||
throw new DOMException('aggregate quota exceeded', 'QuotaExceededError');
|
||||
}
|
||||
storage.set(key, value);
|
||||
},
|
||||
removeItem: (key: string) => { storage.delete(key); },
|
||||
},
|
||||
});
|
||||
__resetBackupMirrorForTests();
|
||||
t.after(() => {
|
||||
__resetBackupMirrorForTests();
|
||||
Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: previousStorage });
|
||||
});
|
||||
storage.set(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS, JSON.stringify({ enabled: false }));
|
||||
return storage;
|
||||
}
|
||||
|
||||
function makeLargeSessions(count = 4) {
|
||||
return Array.from({ length: count }, (_, index) => makeSession(
|
||||
`large-${index}`, count - index,
|
||||
Array.from({ length: 200 }, (_, messageIndex) => ({
|
||||
id: `message-${messageIndex}`,
|
||||
role: messageIndex % 2 ? 'assistant' : 'user',
|
||||
content: 'x'.repeat(5 * 1024 + 128),
|
||||
timestamp: messageIndex,
|
||||
})),
|
||||
));
|
||||
}
|
||||
|
||||
test('local-only writes retain four full large chats across overflow chunks and prewarming', (t) => {
|
||||
const storage = installSessionStorage(t);
|
||||
const sessions = freezeHistory(makeLargeSessions());
|
||||
assert.ok(JSON.stringify(sessions).length > 2 * 1024 * 1024);
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
const primary = JSON.parse(storage.get(STORAGE_KEY_AI_SESSIONS)!) as AISession[];
|
||||
assert.ok(primary.length < sessions.length);
|
||||
assert.ok(storage.has(`${STORAGE_KEY_AI_SESSIONS_OVERFLOW}_2`));
|
||||
for (const [key, value] of storage) {
|
||||
if (key.startsWith(STORAGE_KEY_AI_SESSIONS_OVERFLOW) || key === STORAGE_KEY_AI_SESSIONS) {
|
||||
assert.ok(value.length <= 2 * 1024 * 1024);
|
||||
}
|
||||
}
|
||||
assert.deepEqual(readSessionsFromStorage(), sessions);
|
||||
// A later write of the reloaded history must retain the overflow again.
|
||||
assert.equal(writeSessionsForStorage(readSessionsFromStorage()), true);
|
||||
assert.deepEqual(readSessionsFromStorage(), sessions);
|
||||
const previousSessions = latestAISessionsSnapshot;
|
||||
try {
|
||||
setLatestAISessionsSnapshot(null as unknown as AISession[]);
|
||||
prewarmAIStateStorageSnapshots();
|
||||
assert.deepEqual(latestAISessionsSnapshot, sessions);
|
||||
} finally {
|
||||
setLatestAISessionsSnapshot(previousSessions as AISession[]);
|
||||
}
|
||||
});
|
||||
|
||||
test('backup includes overflow chats before the primary blob is replaced', (t) => {
|
||||
installSessionStorage(t);
|
||||
const backupWrites: string[] = [];
|
||||
const previousWindow = globalThis.window;
|
||||
Object.defineProperty(globalThis, 'window', {
|
||||
configurable: true,
|
||||
value: { netcatty: { aiSessionsBackupWrite: async ({ json }: { json: string }) => {
|
||||
backupWrites.push(json);
|
||||
return { ok: true };
|
||||
} } },
|
||||
});
|
||||
t.after(() => Object.defineProperty(globalThis, 'window', { configurable: true, value: previousWindow }));
|
||||
const sessions = makeLargeSessions();
|
||||
const setItem = globalThis.localStorage.setItem;
|
||||
t.mock.method(globalThis.localStorage, 'setItem', (key: string, value: string) => {
|
||||
if (key === STORAGE_KEY_AI_SESSIONS) {
|
||||
flushBackupMirror();
|
||||
assert.deepEqual(JSON.parse(backupWrites[0]), sessions);
|
||||
}
|
||||
setItem(key, value);
|
||||
});
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
flushBackupMirror();
|
||||
assert.equal(backupWrites.length, 1);
|
||||
const primary = JSON.parse(localStorageAdapter.readString(STORAGE_KEY_AI_SESSIONS)!) as AISession[];
|
||||
const primaryIds = new Set(primary.map(session => session.id));
|
||||
assert.ok(sessions.some(session => !primaryIds.has(session.id)));
|
||||
});
|
||||
|
||||
test('shrinking local history removes stale overflow chunks and deleted chats', (t) => {
|
||||
const storage = installSessionStorage(t);
|
||||
const sessions = makeLargeSessions();
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
assert.equal(writeSessionsForStorage(sessions.slice(0, 2)), true);
|
||||
assert.ok(storage.has(STORAGE_KEY_AI_SESSIONS_OVERFLOW));
|
||||
assert.equal(storage.has(`${STORAGE_KEY_AI_SESSIONS_OVERFLOW}_2`), false);
|
||||
assert.deepEqual(readSessionsFromStorage(), sessions.slice(0, 2));
|
||||
assert.equal(writeSessionsForStorage([sessions[0]]), true);
|
||||
assert.equal(storage.has(STORAGE_KEY_AI_SESSIONS_OVERFLOW), false);
|
||||
assert.deepEqual(readSessionsFromStorage(), [sessions[0]]);
|
||||
assert.equal(writeSessionsForStorage([]), true);
|
||||
assert.deepEqual(readSessionsFromStorage(), []);
|
||||
});
|
||||
|
||||
test('merged storage deduplicates primary and overflow by the newer updatedAt', (t) => {
|
||||
const storage = installSessionStorage(t);
|
||||
const primary = [makeSession('primary-newer', 3, []), makeSession('overflow-newer', 1, [])];
|
||||
const overflow = [makeSession('primary-newer', 2, []), makeSession('overflow-newer', 4, [])];
|
||||
storage.set(STORAGE_KEY_AI_SESSIONS, JSON.stringify(primary));
|
||||
storage.set(STORAGE_KEY_AI_SESSIONS_OVERFLOW, JSON.stringify(overflow));
|
||||
assert.deepEqual(readSessionsFromStorage(), [overflow[1], primary[0]]);
|
||||
});
|
||||
|
||||
test('the 50-session count cap still applies to primary plus overflow', (t) => {
|
||||
installSessionStorage(t);
|
||||
const sessions = Array.from({ length: 51 }, (_, index) => makeSession(`session-${index}`, index, [{
|
||||
id: 'm', role: 'user', content: 'x'.repeat(50 * 1024), timestamp: 0,
|
||||
}]));
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
const loaded = readSessionsFromStorage();
|
||||
assert.equal(loaded.length, 50);
|
||||
assert.deepEqual(loaded.map(session => session.id), sessions.slice(1).reverse().map(session => session.id));
|
||||
});
|
||||
|
||||
test('cloud sync restores overflow if its full authoritative write fails', (t) => {
|
||||
const storage = installSessionStorage(t);
|
||||
assert.equal(writeSessionsForStorage(makeLargeSessions()), true);
|
||||
const originalOverflow = storage.get(STORAGE_KEY_AI_SESSIONS_OVERFLOW);
|
||||
storage.set(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS, JSON.stringify({ enabled: true }));
|
||||
const before = new Map(storage);
|
||||
const sessions = [makeSession('synced', 5, [])];
|
||||
const writeString = localStorageAdapter.writeString;
|
||||
const write = t.mock.method(localStorageAdapter, 'writeString', (key: string, value: string) => (
|
||||
key === STORAGE_KEY_AI_SESSIONS ? false : writeString(key, value)
|
||||
));
|
||||
assert.equal(writeSessionsForStorage(sessions), false);
|
||||
assert.equal(storage.get(STORAGE_KEY_AI_SESSIONS_OVERFLOW), originalOverflow);
|
||||
assert.deepEqual(storage, before);
|
||||
const error = new Error('unexpected primary write failure');
|
||||
write.mock.mockImplementation((key: string, value: string) => {
|
||||
if (key === STORAGE_KEY_AI_SESSIONS) throw error;
|
||||
return writeString(key, value);
|
||||
});
|
||||
assert.throws(() => writeSessionsForStorage(sessions), candidate => candidate === error);
|
||||
assert.deepEqual(storage, before);
|
||||
write.mock.restore();
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
assert.equal([...storage.keys()].some(key => key.startsWith(STORAGE_KEY_AI_SESSIONS_OVERFLOW)), false);
|
||||
assert.deepEqual(readSessionsFromStorage(), sessions);
|
||||
});
|
||||
|
||||
test('enabling cloud sync frees overflow quota for the authoritative primary', (t) => {
|
||||
const storage = installSessionStorage(t, 5 * 1024 * 1024);
|
||||
const sessions = freezeHistory(makeLargeSessions());
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
assert.ok(storage.has(STORAGE_KEY_AI_SESSIONS_OVERFLOW));
|
||||
storage.set(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS, JSON.stringify({ enabled: true }));
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
assert.equal([...storage.keys()].some(key => key.startsWith(STORAGE_KEY_AI_SESSIONS_OVERFLOW)), false);
|
||||
assert.deepEqual(JSON.parse(storage.get(STORAGE_KEY_AI_SESSIONS)!), sessions);
|
||||
assert.deepEqual(readSessionsFromStorage(), sessions);
|
||||
});
|
||||
|
||||
test('aggregate quota retries shed replay bulk from overflow and retain every chat', (t) => {
|
||||
const storage = installSessionStorage(t, 5 * 1024 * 1024);
|
||||
const sessions = freezeHistory(Array.from({ length: 6 }, (_, index) => makeSession(
|
||||
`bulk-${index}`, 6 - index, [{
|
||||
id: `message-${index}`,
|
||||
role: 'assistant',
|
||||
content: 'x'.repeat(700 * 1024),
|
||||
timestamp: index,
|
||||
toolResults: [{ toolCallId: `call-${index}`, content: 'z'.repeat(300 * 1024) }],
|
||||
providerContinuation: {
|
||||
reasoningParts: [{ text: '', providerOptions: { openai: {
|
||||
reasoningEncryptedContent: 'c'.repeat(100 * 1024),
|
||||
} } }],
|
||||
},
|
||||
}],
|
||||
)));
|
||||
assert.ok(JSON.stringify(sessions).length > 5 * 1024 * 1024);
|
||||
const writes = t.mock.method(localStorageAdapter, 'writeString');
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
assert.ok(writes.mock.calls.some(call => call.result === false));
|
||||
const primary = JSON.parse(storage.get(STORAGE_KEY_AI_SESSIONS)!) as AISession[];
|
||||
assert.equal(primary[0].id, sessions[0].id);
|
||||
const overflow = JSON.parse([...storage]
|
||||
.filter(([key]) => key.startsWith(STORAGE_KEY_AI_SESSIONS_OVERFLOW))
|
||||
.map(([, value]) => value).join('')) as AISession[];
|
||||
assert.ok(overflow.length > 0);
|
||||
assert.ok(overflow.every(session => {
|
||||
const message = session.messages[0];
|
||||
return (message.toolResults?.[0].content.length ?? 0) <= 8 * 1024
|
||||
&& !JSON.stringify(message.providerContinuation).includes('reasoningEncryptedContent');
|
||||
}));
|
||||
const loaded = readSessionsFromStorage();
|
||||
assert.deepEqual(loaded.map(session => session.id), sessions.map(session => session.id));
|
||||
assert.deepEqual(loaded.map(session => session.messages[0].content), sessions.map(session => session.messages[0].content));
|
||||
});
|
||||
|
||||
test('a smaller primary reclaims quota before overflow when the final history fits', (t) => {
|
||||
const storage = installSessionStorage(t, 5 * 1024 * 1024);
|
||||
const chat = (id: string, updatedAt: number, mib: number) => makeSession(id, updatedAt, [{
|
||||
id: 'm', role: 'user', content: 'x'.repeat(Math.floor(mib * 1024 * 1024)), timestamp: 0,
|
||||
}]);
|
||||
const previous = [chat('old-primary', 2, 1.9), chat('old-overflow', 1, 1.5)];
|
||||
assert.equal(writeSessionsForStorage(previous), true);
|
||||
const next = [chat('new-primary', 3, 1.1), ...previous];
|
||||
assert.equal(writeSessionsForStorage(next), true);
|
||||
assert.deepEqual(JSON.parse(storage.get(STORAGE_KEY_AI_SESSIONS)!), [next[0]]);
|
||||
assert.deepEqual(readSessionsFromStorage(), next);
|
||||
assert.equal(storage.has(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW), false);
|
||||
});
|
||||
|
||||
test('overflow failure rolls back a replaced primary and the previous overflow', (t) => {
|
||||
const storage = installSessionStorage(t, 5 * 1024 * 1024);
|
||||
const previous = makeLargeSessions();
|
||||
assert.equal(writeSessionsForStorage(previous), true);
|
||||
const before = new Map(storage);
|
||||
const writeString = localStorageAdapter.writeString;
|
||||
const error = new Error('overflow write failed');
|
||||
let failOnce = true;
|
||||
t.mock.method(localStorageAdapter, 'writeString', (key: string, value: string) => {
|
||||
if (failOnce && key === STORAGE_KEY_AI_SESSIONS_OVERFLOW) {
|
||||
failOnce = false;
|
||||
assert.notEqual(storage.get(STORAGE_KEY_AI_SESSIONS), before.get(STORAGE_KEY_AI_SESSIONS));
|
||||
throw error;
|
||||
}
|
||||
return writeString(key, value);
|
||||
});
|
||||
assert.throws(() => writeSessionsForStorage([
|
||||
{ ...previous[0], title: 'New primary' }, ...previous.slice(1),
|
||||
]), candidate => candidate === error);
|
||||
assert.deepEqual(storage, before);
|
||||
});
|
||||
|
||||
test('aggregate quota falls back to a current primary with full backup and persists later turns', (t) => {
|
||||
const storage = installSessionStorage(t, 5 * 1024 * 1024);
|
||||
assert.equal(writeSessionsForStorage([makeSession('previous-primary', 0, [])]), true);
|
||||
__resetBackupMirrorForTests();
|
||||
const backupWrites: string[] = [];
|
||||
const previousWindow = globalThis.window;
|
||||
Object.defineProperty(globalThis, 'window', {
|
||||
configurable: true,
|
||||
value: { netcatty: { aiSessionsBackupWrite: async ({ json }: { json: string }) => {
|
||||
backupWrites.push(json);
|
||||
return { ok: true };
|
||||
} } },
|
||||
});
|
||||
t.after(() => Object.defineProperty(globalThis, 'window', { configurable: true, value: previousWindow }));
|
||||
const sessions = freezeHistory(makeLargeSessions(6));
|
||||
assert.ok(JSON.stringify(sessions).length > 5 * 1024 * 1024);
|
||||
const setItem = globalThis.localStorage.setItem;
|
||||
t.mock.method(globalThis.localStorage, 'setItem', (key: string, value: string) => {
|
||||
if (key === STORAGE_KEY_AI_SESSIONS) {
|
||||
// The full intended history must be scheduled before replacing the old
|
||||
// valid primary, including on the subsequent mutation of the same chat.
|
||||
flushBackupMirror();
|
||||
assert.equal((JSON.parse(backupWrites.at(-1)!) as AISession[]).length, 6);
|
||||
}
|
||||
setItem(key, value);
|
||||
});
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
flushBackupMirror();
|
||||
assert.deepEqual(JSON.parse(backupWrites.at(-1)!), sessions);
|
||||
assert.deepEqual(readSessionsFromStorage(), [sessions[0]]);
|
||||
assert.deepEqual(JSON.parse(storage.get(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW)!), sessions.slice(1).map(session => session.id));
|
||||
assert.equal([...storage.keys()].some(key => key.startsWith(STORAGE_KEY_AI_SESSIONS_OVERFLOW)), false);
|
||||
|
||||
const updated = sessions.map((session, index) => index === 0 ? {
|
||||
...session,
|
||||
updatedAt: session.updatedAt + 1,
|
||||
messages: [...session.messages.slice(1), {
|
||||
id: 'new-turn', role: 'user' as const, content: 'Latest turn survives reload', timestamp: 1000,
|
||||
}],
|
||||
} : session);
|
||||
assert.equal(writeSessionsForStorage(updated), true);
|
||||
flushBackupMirror();
|
||||
assert.deepEqual(JSON.parse(backupWrites.at(-1)!), updated);
|
||||
assert.deepEqual(JSON.parse(storage.get(STORAGE_KEY_AI_SESSIONS)!), [updated[0]]);
|
||||
assert.deepEqual(readSessionsFromStorage(), [updated[0]]);
|
||||
});
|
||||
|
||||
test('live writes resolve only the disk-only IDs included in primary or overflow', (t) => {
|
||||
const storage = installSessionStorage(t);
|
||||
const sessions = makeLargeSessions();
|
||||
storage.set(STORAGE_KEY_AI_SESSIONS, JSON.stringify([sessions[0]]));
|
||||
storage.set(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW, JSON.stringify([
|
||||
sessions[0].id, sessions[1].id, 'unrecovered', 'deleted',
|
||||
]));
|
||||
assert.equal(writeSessionsForStorage(sessions, { deletedSessionIds: ['deleted'] }), true);
|
||||
assert.deepEqual(readSessionsFromStorage(), sessions);
|
||||
assert.deepEqual(JSON.parse(storage.get(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW)!), ['unrecovered']);
|
||||
|
||||
// Reusing the same immutable array must still process explicit deletion,
|
||||
// including when the primary itself has not changed.
|
||||
assert.equal(writeSessionsForStorage(sessions, { deletedSessionIds: ['unrecovered'] }), true);
|
||||
assert.equal(storage.has(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW), false);
|
||||
});
|
||||
|
||||
test('same-array primary writes preserve pending recovery until explicit deletion or sync', (t) => {
|
||||
const storage = installSessionStorage(t);
|
||||
const sessions = [makeSession('primary', 1, [])];
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
storage.set(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW, JSON.stringify(['unrecovered']));
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
assert.deepEqual(JSON.parse(storage.get(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW)!), ['unrecovered']);
|
||||
assert.equal(writeSessionsForStorage(sessions, { deletedSessionIds: ['unrecovered'] }), true);
|
||||
assert.equal(storage.has(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW), false);
|
||||
|
||||
storage.set(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW, JSON.stringify(['unrecovered']));
|
||||
storage.set(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS, JSON.stringify({ enabled: true }));
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
assert.equal(storage.has(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW), false);
|
||||
});
|
||||
|
||||
test('tiny newest chat bounds overflow writes under aggregate quota and preserves unresolved IDs', (t) => {
|
||||
const storage = installSessionStorage(t, 512 * 1024);
|
||||
const sessions = [makeSession('empty-newest', 10, []), ...Array.from({ length: 3 }, (_, index) => (
|
||||
makeSession(`huge-older-${index}`, 3 - index, [{
|
||||
id: 'm', role: 'user', content: 'x'.repeat(768 * 1024), timestamp: 0,
|
||||
}])
|
||||
))];
|
||||
storage.set(STORAGE_KEY_AI_SESSIONS, JSON.stringify([sessions[0]]));
|
||||
storage.set(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW, JSON.stringify(['unrecovered']));
|
||||
const writes = t.mock.method(globalThis.localStorage, 'setItem');
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
assert.ok(writes.mock.callCount() < 150, `bounded writes: ${writes.mock.callCount()}`);
|
||||
assert.deepEqual(readSessionsFromStorage(), [sessions[0]]);
|
||||
assert.deepEqual(JSON.parse(storage.get(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW)!), [
|
||||
'unrecovered', ...sessions.slice(1).map(session => session.id),
|
||||
]);
|
||||
});
|
||||
|
||||
test('primary-only fallback frees primary quota before writing recovery metadata', (t) => {
|
||||
const storage = installSessionStorage(t);
|
||||
const previous = [makeSession('old-primary', 1, [{
|
||||
id: 'm', role: 'user', content: 'x'.repeat(64 * 1024), timestamp: 0,
|
||||
}])];
|
||||
const previousJson = JSON.stringify(previous);
|
||||
const sessions = [makeSession('empty-newest', 10, []), ...makeLargeSessions(2)];
|
||||
storage.set(STORAGE_KEY_AI_SESSIONS, previousJson);
|
||||
// The old primary fills the quota. Metadata fits only after it is replaced.
|
||||
const aggregateQuota = [...storage].reduce((total, [key, value]) => total + key.length + value.length, 0);
|
||||
const setItem = globalThis.localStorage.setItem;
|
||||
t.mock.method(globalThis.localStorage, 'setItem', (key: string, value: string) => {
|
||||
const total = [...storage].reduce((sum, [storedKey, storedValue]) => (
|
||||
sum + (storedKey === key ? 0 : storedKey.length + storedValue.length)
|
||||
), key.length + value.length);
|
||||
if (total > aggregateQuota) throw new DOMException('aggregate quota exceeded', 'QuotaExceededError');
|
||||
setItem(key, value);
|
||||
});
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
assert.deepEqual(readSessionsFromStorage(), [sessions[0]]);
|
||||
assert.deepEqual(JSON.parse(storage.get(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW)!), sessions.slice(1).map(session => session.id));
|
||||
});
|
||||
|
||||
test('primary-only fallback rolls back when recovery metadata cannot be written', (t) => {
|
||||
const storage = installSessionStorage(t);
|
||||
const previous = [makeSession('previous', 0, [])];
|
||||
assert.equal(writeSessionsForStorage(previous), true);
|
||||
storage.set(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW, JSON.stringify(['unrecovered']));
|
||||
const before = new Map(storage);
|
||||
const setItem = globalThis.localStorage.setItem;
|
||||
t.mock.method(globalThis.localStorage, 'setItem', (key: string, value: string) => {
|
||||
if (key.startsWith(STORAGE_KEY_AI_SESSIONS_OVERFLOW) || key === STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW) {
|
||||
throw new DOMException('quota exceeded', 'QuotaExceededError');
|
||||
}
|
||||
setItem(key, value);
|
||||
});
|
||||
assert.equal(writeSessionsForStorage([makeSession('new', 1, []), ...makeLargeSessions(2)]), false);
|
||||
assert.deepEqual(storage, before);
|
||||
});
|
||||
|
||||
test('unchanged primary does not hide modified overflow from the write cache', (t) => {
|
||||
const storage = installSessionStorage(t);
|
||||
const sessions = freezeHistory(makeLargeSessions());
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
storage.set(STORAGE_KEY_AI_SESSIONS_OVERFLOW, 'corrupt overflow');
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
assert.deepEqual(readSessionsFromStorage(), sessions);
|
||||
});
|
||||
|
||||
test('quota failures retain the previous overflow and back up the intended full set', (t) => {
|
||||
const storage = installSessionStorage(t);
|
||||
const original = makeLargeSessions();
|
||||
assert.equal(writeSessionsForStorage(original), true);
|
||||
__resetBackupMirrorForTests();
|
||||
const before = new Map(storage);
|
||||
const next = original.map(session => ({ ...session, title: 'Changed', updatedAt: session.updatedAt + 10 }));
|
||||
t.mock.method(localStorageAdapter, 'writeString', (key: string, value: string) => {
|
||||
if (key === STORAGE_KEY_AI_SESSIONS) return false;
|
||||
storage.set(key, value);
|
||||
return true;
|
||||
});
|
||||
const backupWrites: string[] = [];
|
||||
const previousWindow = globalThis.window;
|
||||
Object.defineProperty(globalThis, 'window', {
|
||||
configurable: true,
|
||||
value: { netcatty: { aiSessionsBackupWrite: async ({ json }: { json: string }) => {
|
||||
backupWrites.push(json);
|
||||
return { ok: true };
|
||||
} } },
|
||||
});
|
||||
t.after(() => Object.defineProperty(globalThis, 'window', { configurable: true, value: previousWindow }));
|
||||
assert.equal(writeSessionsForStorage(next), false);
|
||||
assert.deepEqual(storage, before);
|
||||
assert.deepEqual(readSessionsFromStorage(), original);
|
||||
flushBackupMirror();
|
||||
assert.deepEqual(JSON.parse(backupWrites[0]), next);
|
||||
});
|
||||
|
||||
test('orphan cleanup preserves resumable privacy maps until explicit chat deletion', (t) => {
|
||||
const service = createAiPrivacyService({ maxSessions: 3 });
|
||||
service.configure({ enabled: true });
|
||||
@@ -90,7 +520,10 @@ test('orphan cleanup preserves resumable privacy maps until explicit chat deleti
|
||||
const previousWindow = globalThis.window;
|
||||
const previousSessions = latestAISessionsSnapshot;
|
||||
const previousActiveSessionMap = latestAIActiveSessionMapSnapshot;
|
||||
t.mock.method(localStorageAdapter, 'read', () => null);
|
||||
t.mock.method(localStorageAdapter, 'readString', () => null);
|
||||
t.mock.method(localStorageAdapter, 'write', () => true);
|
||||
t.mock.method(localStorageAdapter, 'writeString', () => true);
|
||||
Object.defineProperty(globalThis, 'window', {
|
||||
configurable: true,
|
||||
value: {
|
||||
@@ -122,8 +555,24 @@ test('orphan cleanup preserves resumable privacy maps until explicit chat deleti
|
||||
try {
|
||||
cleanupOrphanedAISessions(new Set(['open', 'resumed-into']));
|
||||
|
||||
assert.equal(latestAISessionsSnapshot, sessions);
|
||||
// Issue #4015 R2: the dropped chat is marked dangling but its record and
|
||||
// its active pointer stay intact so /chats can offer a rebind.
|
||||
const persistedSessions = latestAISessionsSnapshot;
|
||||
assert.ok(persistedSessions);
|
||||
assert.equal(
|
||||
persistedSessions.find((session) => session.id === 'privacy-orphan')?.scopeDangling,
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
persistedSessions.find((session) => session.id === 'privacy-live')?.scopeDangling,
|
||||
undefined,
|
||||
);
|
||||
assert.equal(
|
||||
persistedSessions.find((session) => session.id === 'privacy-resumed')?.scopeDangling,
|
||||
undefined,
|
||||
);
|
||||
assert.deepEqual(latestAIActiveSessionMapSnapshot, {
|
||||
'terminal:closed': 'privacy-orphan',
|
||||
'terminal:open': 'privacy-live',
|
||||
'terminal:resumed-into': 'privacy-resumed',
|
||||
});
|
||||
@@ -158,6 +607,97 @@ test('orphan cleanup preserves resumable privacy maps until explicit chat deleti
|
||||
}
|
||||
});
|
||||
|
||||
test('orphan cleanup marks dangling chats instead of stripping them, and clears the flag when the target returns', (t) => {
|
||||
const previousSessions = latestAISessionsSnapshot;
|
||||
const previousActiveSessionMap = latestAIActiveSessionMapSnapshot;
|
||||
const read = t.mock.method(localStorageAdapter, 'read', () => null);
|
||||
t.mock.method(localStorageAdapter, 'readString', () => null);
|
||||
t.mock.method(localStorageAdapter, 'write', () => true);
|
||||
const writeString = t.mock.method(localStorageAdapter, 'writeString', () => true);
|
||||
const previousWindow = globalThis.window;
|
||||
Object.defineProperty(globalThis, 'window', {
|
||||
configurable: true,
|
||||
value: { dispatchEvent: () => true, netcatty: {} },
|
||||
});
|
||||
const dangling = {
|
||||
...makeSession('dangling-chat', 1, []),
|
||||
scope: { type: 'terminal' as const, targetId: 'closed-ws' },
|
||||
};
|
||||
const live = {
|
||||
...makeSession('live-chat', 2, []),
|
||||
scope: { type: 'terminal' as const, targetId: 'open' },
|
||||
};
|
||||
setLatestAISessionsSnapshot([dangling, live]);
|
||||
setLatestAIActiveSessionMapSnapshot({
|
||||
'terminal:closed-ws': 'dangling-chat',
|
||||
'terminal:open': 'live-chat',
|
||||
});
|
||||
|
||||
try {
|
||||
cleanupOrphanedAISessions(new Set(['open']));
|
||||
|
||||
let persisted = latestAISessionsSnapshot;
|
||||
assert.ok(persisted);
|
||||
assert.equal(persisted.find((s) => s.id === 'dangling-chat')?.scopeDangling, true);
|
||||
assert.equal(persisted.find((s) => s.id === 'live-chat')?.scopeDangling, undefined);
|
||||
// The active pointer survives the dangling marking.
|
||||
assert.deepEqual(latestAIActiveSessionMapSnapshot, {
|
||||
'terminal:closed-ws': 'dangling-chat',
|
||||
'terminal:open': 'live-chat',
|
||||
});
|
||||
assert.ok(writeString.mock.callCount() > 0);
|
||||
|
||||
// The scope target becomes live again → the dangling flag clears.
|
||||
read.mock.mockImplementation(() => null);
|
||||
cleanupOrphanedAISessions(new Set(['open', 'closed-ws']));
|
||||
persisted = latestAISessionsSnapshot;
|
||||
assert.ok(persisted);
|
||||
assert.equal(persisted.find((s) => s.id === 'dangling-chat')?.scopeDangling, undefined);
|
||||
} finally {
|
||||
setLatestAISessionsSnapshot(previousSessions ?? []);
|
||||
setLatestAIActiveSessionMapSnapshot(previousActiveSessionMap ?? {});
|
||||
Object.defineProperty(globalThis, 'window', {
|
||||
configurable: true,
|
||||
value: previousWindow,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('orphan cleanup with an empty live-target set marks all scoped chats dangling', (t) => {
|
||||
const previousSessions = latestAISessionsSnapshot;
|
||||
const previousActiveSessionMap = latestAIActiveSessionMapSnapshot;
|
||||
t.mock.method(localStorageAdapter, 'read', () => null);
|
||||
t.mock.method(localStorageAdapter, 'readString', () => null);
|
||||
t.mock.method(localStorageAdapter, 'write', () => true);
|
||||
t.mock.method(localStorageAdapter, 'writeString', () => true);
|
||||
const previousWindow = globalThis.window;
|
||||
Object.defineProperty(globalThis, 'window', {
|
||||
configurable: true,
|
||||
value: { dispatchEvent: () => true, netcatty: {} },
|
||||
});
|
||||
const orphan = {
|
||||
...makeSession('orphan-chat', 1, []),
|
||||
scope: { type: 'terminal' as const, targetId: 'gone' },
|
||||
};
|
||||
setLatestAISessionsSnapshot([orphan]);
|
||||
setLatestAIActiveSessionMapSnapshot({ 'terminal:gone': 'orphan-chat' });
|
||||
|
||||
try {
|
||||
// Empty is a valid observed live set (nothing mounted), not "unknown".
|
||||
cleanupOrphanedAISessions(new Set());
|
||||
const persisted = latestAISessionsSnapshot;
|
||||
assert.ok(persisted);
|
||||
assert.equal(persisted.find((s) => s.id === 'orphan-chat')?.scopeDangling, true);
|
||||
} finally {
|
||||
setLatestAISessionsSnapshot(previousSessions ?? []);
|
||||
setLatestAIActiveSessionMapSnapshot(previousActiveSessionMap ?? {});
|
||||
Object.defineProperty(globalThis, 'window', {
|
||||
configurable: true,
|
||||
value: previousWindow,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('serializeSessionsForStorage strips oldest ciphertext before dropping visible sessions', async () => {
|
||||
const { serializeSessionsForStorage } = await import('./aiStateSnapshots');
|
||||
const ciphertext = 'gAAAA'.repeat(50000); // ~250 KB of ciphertext per message
|
||||
@@ -518,49 +1058,26 @@ test('writeSessionsForStorage retries below nominal budgets after a quota failur
|
||||
}
|
||||
});
|
||||
|
||||
test('writeSessionsForStorage reduces several small sessions to fit a sub-512 KB quota', async () => {
|
||||
const { writeSessionsForStorage } = await import('./aiStateSnapshots');
|
||||
test('writeSessionsForStorage splits overflow to fit a sub-512 KB per-key quota', (t) => {
|
||||
const storage = installSessionStorage(t);
|
||||
const writes: string[] = [];
|
||||
let stored: string | undefined;
|
||||
const previousLocalStorage = globalThis.localStorage;
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
configurable: true,
|
||||
value: {
|
||||
getItem: () => null,
|
||||
setItem: (_key: string, value: string) => {
|
||||
writes.push(value);
|
||||
if (value.length > 300 * 1024) {
|
||||
throw new DOMException('quota exceeded', 'QuotaExceededError');
|
||||
}
|
||||
stored = value;
|
||||
},
|
||||
removeItem: () => {},
|
||||
},
|
||||
t.mock.method(globalThis.localStorage, 'setItem', (key: string, value: string) => {
|
||||
writes.push(value);
|
||||
if (value.length > 300 * 1024) {
|
||||
throw new DOMException('quota exceeded', 'QuotaExceededError');
|
||||
}
|
||||
storage.set(key, value);
|
||||
});
|
||||
|
||||
try {
|
||||
const sessions = Array.from({ length: 10 }, (_, index) => makeSession(
|
||||
`session-${index}`,
|
||||
10 - index,
|
||||
[{
|
||||
id: `message-${index}`,
|
||||
role: 'user' as const,
|
||||
content: 'x'.repeat(40 * 1024),
|
||||
timestamp: index,
|
||||
}],
|
||||
));
|
||||
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
assert.ok(writes[0].length > 300 * 1024);
|
||||
assert.ok(stored);
|
||||
assert.ok(stored.length <= 300 * 1024);
|
||||
assert.ok((JSON.parse(stored) as AISession[]).length < sessions.length);
|
||||
} finally {
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
configurable: true,
|
||||
value: previousLocalStorage,
|
||||
});
|
||||
}
|
||||
const sessions = Array.from({ length: 10 }, (_, index) => makeSession(
|
||||
`session-${index}`, 10 - index,
|
||||
[{ id: `message-${index}`, role: 'user', content: 'x'.repeat(40 * 1024), timestamp: index }],
|
||||
));
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
assert.ok(writes[0].length > 300 * 1024);
|
||||
const primary = storage.get(STORAGE_KEY_AI_SESSIONS)!;
|
||||
assert.ok(primary.length <= 300 * 1024);
|
||||
assert.ok((JSON.parse(primary) as AISession[]).length < sessions.length);
|
||||
assert.deepEqual(readSessionsFromStorage(), sessions);
|
||||
});
|
||||
|
||||
test('serializeSessionsForStorage truncates slightly-over-cap tool results to strictly smaller sizes', async () => {
|
||||
@@ -672,50 +1189,26 @@ test('writeSessionsForStorage keeps every chat by shedding tool output under quo
|
||||
}
|
||||
});
|
||||
|
||||
test('writeSessionsForStorage makes a final attempt with only the newest session', async () => {
|
||||
const { writeSessionsForStorage } = await import('./aiStateSnapshots');
|
||||
test('writeSessionsForStorage makes a final attempt with the newest primary and keeps overflow', (t) => {
|
||||
const storage = installSessionStorage(t);
|
||||
const writes: string[] = [];
|
||||
let stored: string | undefined;
|
||||
const previousLocalStorage = globalThis.localStorage;
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
configurable: true,
|
||||
value: {
|
||||
getItem: () => null,
|
||||
setItem: (_key: string, value: string) => {
|
||||
writes.push(value);
|
||||
if (value.length > 50 * 1024) {
|
||||
throw new DOMException('quota exceeded', 'QuotaExceededError');
|
||||
}
|
||||
stored = value;
|
||||
},
|
||||
removeItem: () => {},
|
||||
},
|
||||
t.mock.method(globalThis.localStorage, 'setItem', (key: string, value: string) => {
|
||||
writes.push(value);
|
||||
if (value.length > 50 * 1024) {
|
||||
throw new DOMException('quota exceeded', 'QuotaExceededError');
|
||||
}
|
||||
storage.set(key, value);
|
||||
});
|
||||
|
||||
try {
|
||||
const sessions = Array.from({ length: 10 }, (_, index) => makeSession(
|
||||
`session-${index}`,
|
||||
10 - index,
|
||||
[{
|
||||
id: `message-${index}`,
|
||||
role: 'user' as const,
|
||||
content: 'x'.repeat(40 * 1024),
|
||||
timestamp: index,
|
||||
}],
|
||||
));
|
||||
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
assert.equal(writes.length, 6);
|
||||
assert.ok(stored);
|
||||
const persisted = JSON.parse(stored) as AISession[];
|
||||
assert.deepEqual(persisted.map(session => session.id), ['session-0']);
|
||||
assert.ok(stored.length <= 50 * 1024);
|
||||
} finally {
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
configurable: true,
|
||||
value: previousLocalStorage,
|
||||
});
|
||||
}
|
||||
const sessions = Array.from({ length: 10 }, (_, index) => makeSession(
|
||||
`session-${index}`, 10 - index,
|
||||
[{ id: `message-${index}`, role: 'user', content: 'x'.repeat(40 * 1024), timestamp: index }],
|
||||
));
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
assert.ok(writes.some(value => value.length > 50 * 1024));
|
||||
const primary = storage.get(STORAGE_KEY_AI_SESSIONS)!;
|
||||
assert.deepEqual((JSON.parse(primary) as AISession[]).map(session => session.id), ['session-0']);
|
||||
assert.ok(primary.length <= 50 * 1024);
|
||||
assert.deepEqual(readSessionsFromStorage(), sessions);
|
||||
});
|
||||
|
||||
function freezeHistory<T>(value: T): T {
|
||||
@@ -791,18 +1284,18 @@ test('synced storage bypasses fit-first pruning and non-quota failures still pro
|
||||
const { writeSessionsForStorage } = await import('./aiStateSnapshots');
|
||||
const sessions = freezeHistory(makePersistenceHistory(51, 201));
|
||||
const read = t.mock.method(localStorageAdapter, 'read', () => ({ enabled: true }));
|
||||
const write = t.mock.method(localStorageAdapter, 'write', () => false);
|
||||
const writeString = t.mock.method(localStorageAdapter, 'writeString', () => true);
|
||||
t.mock.method(localStorageAdapter, 'readString', () => null);
|
||||
const writeString = t.mock.method(localStorageAdapter, 'writeString', () => false);
|
||||
assert.equal(writeSessionsForStorage(sessions), false);
|
||||
assert.equal(write.mock.callCount(), 1);
|
||||
assert.equal(write.mock.calls[0].arguments[1], sessions);
|
||||
assert.equal(writeString.mock.callCount(), 0);
|
||||
// Synced: one write of the complete, unpruned history (serialized once).
|
||||
assert.equal(writeString.mock.callCount(), 1);
|
||||
assert.equal(writeString.mock.calls[0].arguments[1], JSON.stringify(sessions));
|
||||
|
||||
read.mock.mockImplementation(() => ({ enabled: false }));
|
||||
const error = new Error('non-quota storage failure');
|
||||
writeString.mock.mockImplementation(() => { throw error; });
|
||||
assert.throws(() => writeSessionsForStorage(sessions), candidate => candidate === error);
|
||||
assert.equal(writeString.mock.callCount(), 1);
|
||||
assert.equal(writeString.mock.callCount(), 2);
|
||||
});
|
||||
|
||||
for (const [budget, expectedCalls] of [[128 * 1024, 160], [0, 161]]) {
|
||||
@@ -817,3 +1310,89 @@ for (const [budget, expectedCalls] of [[128 * 1024, 160], [0, 161]]) {
|
||||
assert.equal(result.sessions.length, budget === 0 ? 1 : 4);
|
||||
});
|
||||
}
|
||||
test('successful store writes schedule a throttled disk backup mirror', async (t) => {
|
||||
const { writeSessionsForStorage, flushBackupMirror, __resetBackupMirrorForTests } =
|
||||
await import('./aiStateSnapshots');
|
||||
__resetBackupMirrorForTests();
|
||||
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 };
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const sessions = freezeHistory(makePersistenceHistory(3, 10));
|
||||
const writeString = t.mock.method(localStorageAdapter, 'writeString', () => true);
|
||||
t.mock.method(localStorageAdapter, 'read', () => null);
|
||||
t.mock.method(localStorageAdapter, 'readString', () => null);
|
||||
try {
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
// Throttled: nothing has been written to disk yet.
|
||||
assert.equal(backupWrites.length, 0);
|
||||
flushBackupMirror();
|
||||
assert.equal(backupWrites.length, 1);
|
||||
// The mirror carries exactly the JSON that landed in localStorage.
|
||||
assert.equal(backupWrites[0], writeString.mock.calls[0].arguments[1]);
|
||||
// A failed shrinking write still mirrors the full count-capped history.
|
||||
writeString.mock.mockImplementation(() => false);
|
||||
assert.equal(writeSessionsForStorage(sessions), false);
|
||||
flushBackupMirror();
|
||||
assert.equal(backupWrites.length, 2);
|
||||
assert.deepEqual(JSON.parse(backupWrites[1]), sessions);
|
||||
} finally {
|
||||
__resetBackupMirrorForTests();
|
||||
Object.defineProperty(globalThis, 'window', {
|
||||
configurable: true,
|
||||
value: previousWindow,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('rebindActiveSessionMap drops stale pointers and sets the new scope', () => {
|
||||
const cleaned = rebindActiveSessionMap(
|
||||
{
|
||||
'terminal:old-ws': 'chat-1',
|
||||
'terminal:other': 'chat-2',
|
||||
'workspace:keep': 'chat-1',
|
||||
},
|
||||
'chat-1',
|
||||
'terminal:new-ws',
|
||||
);
|
||||
assert.deepEqual(cleaned, {
|
||||
'terminal:other': 'chat-2',
|
||||
'terminal:new-ws': 'chat-1',
|
||||
});
|
||||
// Idempotent when already bound to the target scope with no other pointers.
|
||||
assert.deepEqual(
|
||||
rebindActiveSessionMap({ 'terminal:new-ws': 'chat-1' }, 'chat-1', 'terminal:new-ws'),
|
||||
{ 'terminal:new-ws': 'chat-1' },
|
||||
);
|
||||
});
|
||||
|
||||
test('rewriting the same sessions array skips re-serialization while storage still holds it', async (t) => {
|
||||
const { writeSessionsForStorage } = await import('./aiStateSnapshots');
|
||||
const sessions = freezeHistory(makePersistenceHistory(3, 10));
|
||||
let stored: string | null = null;
|
||||
t.mock.method(localStorageAdapter, 'read', () => ({ enabled: true }));
|
||||
const writeString = t.mock.method(localStorageAdapter, 'writeString', (_key: string, value: string) => {
|
||||
stored = value;
|
||||
return true;
|
||||
});
|
||||
t.mock.method(localStorageAdapter, 'readString', (key: string) => key === STORAGE_KEY_AI_SESSIONS ? stored : null);
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
const stringify = t.mock.method(JSON, 'stringify');
|
||||
// Cloud-sync collection writes the same immutable array again.
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
assert.equal(writeString.mock.callCount(), 1);
|
||||
assert.equal(stringify.mock.callCount(), 0);
|
||||
// Another window replaced the store: write again.
|
||||
stored = '[]';
|
||||
assert.equal(writeSessionsForStorage(sessions), true);
|
||||
assert.equal(writeString.mock.callCount(), 2);
|
||||
});
|
||||
@@ -2,6 +2,8 @@ import { localStorageAdapter } from '../../infrastructure/persistence/localStora
|
||||
import {
|
||||
STORAGE_KEY_AI_ACTIVE_SESSION_MAP,
|
||||
STORAGE_KEY_AI_SESSIONS,
|
||||
STORAGE_KEY_AI_SESSIONS_OVERFLOW,
|
||||
STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW,
|
||||
STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS,
|
||||
} from '../../infrastructure/config/storageKeys';
|
||||
import type {
|
||||
@@ -20,14 +22,17 @@ import {
|
||||
} from './aiDraftState';
|
||||
import {
|
||||
pruneInactiveScopedSessions,
|
||||
pruneInactiveScopedTransientState,
|
||||
pruneInactiveScopedState,
|
||||
} from './aiScopeCleanup';
|
||||
import { emitAIStateChanged } from './aiStateEvents';
|
||||
import { getAgentRuntime } from '../../infrastructure/ai/harness/globalAgentRuntime';
|
||||
import { peekAgentRuntimeCleanup } from '../../infrastructure/ai/harness/agentRuntimeHandle';
|
||||
import { setReversibleModelPrivacy } from '../../infrastructure/ai/harness/modelSecretRedaction';
|
||||
import { DebouncedBackupMirror, mergeImportedSessions, readLiveSessionsArray } from './aiSessionsBackup';
|
||||
|
||||
/** Typed accessor for the Electron IPC bridge exposed on `window.netcatty`. */
|
||||
export interface AIBridge {
|
||||
aiSdkAgentCleanup?: (chatSessionId: string) => Promise<{ ok: boolean }>;
|
||||
aiPrivacyClearSession?: (chatSessionId: string) => Promise<{ ok: boolean; error?: string }>;
|
||||
deleteChatToolOutputsTemp?: (chatSessionId: string) => Promise<{ deletedCount: number }>;
|
||||
deleteTerminalToolOutputsEverywhereTemp?: (terminalSessionId: string) => Promise<{ deletedCount: number }>;
|
||||
aiMcpSetPermissionMode?: (mode: AIPermissionMode) => Promise<unknown> | unknown;
|
||||
@@ -35,6 +40,11 @@ export interface AIBridge {
|
||||
aiMcpSetCommandBlocklist?: (blocklist: string[]) => Promise<unknown> | unknown;
|
||||
aiMcpSetCommandTimeout?: (timeout: number) => Promise<unknown> | unknown;
|
||||
aiMcpSetMaxIterations?: (maxIterations: number) => Promise<unknown> | unknown;
|
||||
/** Durability mirror: write one timestamped backup generation to disk. */
|
||||
aiSessionsBackupWrite?: (payload: { json: string }) => Promise<{ ok: boolean }>;
|
||||
aiSessionsBackupReadLatest?: () => Promise<{ ok: boolean; json?: string }>;
|
||||
aiSessionsBackupExport?: (payload: { json: string }) => Promise<{ success: boolean; filePath?: string }>;
|
||||
aiSessionsBackupImport?: () => Promise<{ success: boolean; json?: string }>;
|
||||
}
|
||||
|
||||
export function getAIBridge() {
|
||||
@@ -57,8 +67,18 @@ export async function cleanupSdkAgentSessions(sessionIds: string[]): Promise<voi
|
||||
export function cleanupDeletedAIChatSessions(sessionIds: string[]) {
|
||||
const bridge = getAIBridge();
|
||||
if (sessionIds.length === 0) return;
|
||||
// Only the startup-light handle is imported here; the runtime registers it
|
||||
// when created. Without a runtime there is no in-memory runtime state, but
|
||||
// the reversible-privacy flag (set outside the runtime) and the
|
||||
// main-process privacy mapping may still exist, so always clear those.
|
||||
const runtime = peekAgentRuntimeCleanup();
|
||||
for (const sessionId of sessionIds) {
|
||||
getAgentRuntime().clearChatSession(sessionId);
|
||||
if (runtime) {
|
||||
runtime.clearChatSession(sessionId);
|
||||
} else {
|
||||
setReversibleModelPrivacy(sessionId, false);
|
||||
void bridge?.aiPrivacyClearSession?.(sessionId).catch(() => {});
|
||||
}
|
||||
void bridge?.aiSdkAgentCleanup?.(sessionId).catch(() => {});
|
||||
void bridge?.deleteChatToolOutputsTemp?.(sessionId).catch(() => {});
|
||||
}
|
||||
@@ -66,8 +86,9 @@ export function cleanupDeletedAIChatSessions(sessionIds: string[]) {
|
||||
|
||||
export function cleanupClosedTerminalSessions(terminalSessionIds: string[]) {
|
||||
const bridge = getAIBridge();
|
||||
const runtime = peekAgentRuntimeCleanup();
|
||||
for (const terminalSessionId of new Set(terminalSessionIds)) {
|
||||
getAgentRuntime().clearTerminalSession(terminalSessionId);
|
||||
runtime?.clearTerminalSession(terminalSessionId);
|
||||
void bridge?.deleteTerminalToolOutputsEverywhereTemp?.(terminalSessionId).catch(() => {});
|
||||
}
|
||||
}
|
||||
@@ -82,10 +103,13 @@ function isScopeKeyActive(scopeKey: string, activeTargetIds: Set<string>) {
|
||||
return activeTargetIds.has(targetId);
|
||||
}
|
||||
|
||||
/** Last live terminal/workspace target ids observed by orphan cleanup. */
|
||||
export let latestAIActiveTargetIdsSnapshot: Set<string> = new Set();
|
||||
|
||||
export function cleanupOrphanedAISessions(activeTargetIds: Set<string>) {
|
||||
latestAIActiveTargetIdsSnapshot = activeTargetIds;
|
||||
const currentSessions = latestAISessionsSnapshot
|
||||
?? localStorageAdapter.read<AISession[]>(STORAGE_KEY_AI_SESSIONS)
|
||||
?? [];
|
||||
?? readSessionsFromStorage();
|
||||
|
||||
// Sessions shown by a still-live scope must be protected from cleanup
|
||||
// even when their own `scope.targetId` points at a closed terminal —
|
||||
@@ -111,65 +135,69 @@ export function cleanupOrphanedAISessions(activeTargetIds: Set<string>) {
|
||||
cleanupSdkAgentSessions(nextSessionCleanup.orphanedSessionIds);
|
||||
}
|
||||
|
||||
if (nextSessionCleanup.sessions !== currentSessions) {
|
||||
setLatestAISessionsSnapshot(nextSessionCleanup.sessions);
|
||||
writeSessionsForStorage(nextSessionCleanup.sessions);
|
||||
// Issue #4015 R2: a dropped chat is recoverable now, so mark it dangling
|
||||
// instead of stripping its record or pointer. `/chats` lists dangling chats
|
||||
// with a rebind affordance; the flag clears when the chat is rebound or its
|
||||
// scope target becomes live again.
|
||||
const orphanedIds = new Set(nextSessionCleanup.orphanedSessionIds);
|
||||
let sessionsMarked = false;
|
||||
const markedSessions = currentSessions.map((session) => {
|
||||
if (orphanedIds.has(session.id)) {
|
||||
if (session.scopeDangling) return session;
|
||||
sessionsMarked = true;
|
||||
return { ...session, scopeDangling: true };
|
||||
}
|
||||
if (
|
||||
session.scopeDangling
|
||||
&& (!session.scope.targetId || activeTargetIds.has(session.scope.targetId))
|
||||
) {
|
||||
sessionsMarked = true;
|
||||
const { scopeDangling: _cleared, ...rest } = session;
|
||||
return rest as AISession;
|
||||
}
|
||||
return session;
|
||||
});
|
||||
|
||||
if (sessionsMarked) {
|
||||
setLatestAISessionsSnapshot(markedSessions);
|
||||
// Startup cleanup can run before the disk backup read resolves. Defer
|
||||
// persistence until those chats are merged, preserving their recovery
|
||||
// marker and avoiding a partial backup of only the loaded sessions.
|
||||
const diskOnlyIds = localStorageAdapter.read<string[]>(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW) ?? [];
|
||||
const loadedIds = new Set(markedSessions.map(session => session.id));
|
||||
if (!diskOnlyIds.some(id => !loadedIds.has(id))) {
|
||||
writeSessionsForStorage(markedSessions);
|
||||
}
|
||||
emitAIStateChanged(STORAGE_KEY_AI_SESSIONS);
|
||||
}
|
||||
|
||||
const activeSessionIdMap = preCleanupActiveSessionMap;
|
||||
let activeSessionMapChanged = false;
|
||||
const nextActiveSessionIdMap = { ...activeSessionIdMap };
|
||||
|
||||
for (const scopeKey of Object.keys(activeSessionIdMap)) {
|
||||
if (isScopeKeyActive(scopeKey, activeTargetIds)) continue;
|
||||
delete nextActiveSessionIdMap[scopeKey];
|
||||
activeSessionMapChanged = true;
|
||||
}
|
||||
|
||||
if (activeSessionMapChanged) {
|
||||
setLatestAIActiveSessionMapSnapshot(nextActiveSessionIdMap);
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_ACTIVE_SESSION_MAP, nextActiveSessionIdMap);
|
||||
emitAIStateChanged(STORAGE_KEY_AI_ACTIVE_SESSION_MAP);
|
||||
}
|
||||
|
||||
const currentActiveSessionIdMap = activeSessionMapChanged
|
||||
? nextActiveSessionIdMap
|
||||
: activeSessionIdMap;
|
||||
// Issue #4015 R2: keep active-pointer entries for scopes whose target
|
||||
// closed. Clearing them used to make dangling chats invisible (rank 0) and
|
||||
// unrecoverable from the UI; the pointer is rewritten on rebind instead.
|
||||
const currentDraftsByScope = latestAIDraftsByScopeSnapshot ?? {};
|
||||
const currentPanelViewByScope = latestAIPanelViewByScopeSnapshot ?? {};
|
||||
const prunedScopedTransientState = pruneInactiveScopedTransientState(
|
||||
currentActiveSessionIdMap,
|
||||
const prunedScopedState = pruneInactiveScopedState(
|
||||
currentDraftsByScope,
|
||||
currentPanelViewByScope,
|
||||
activeTargetIds,
|
||||
);
|
||||
|
||||
if (prunedScopedTransientState.activeSessionIdMap !== currentActiveSessionIdMap) {
|
||||
setLatestAIActiveSessionMapSnapshot(prunedScopedTransientState.activeSessionIdMap);
|
||||
localStorageAdapter.write(
|
||||
STORAGE_KEY_AI_ACTIVE_SESSION_MAP,
|
||||
prunedScopedTransientState.activeSessionIdMap,
|
||||
);
|
||||
emitAIStateChanged(STORAGE_KEY_AI_ACTIVE_SESSION_MAP);
|
||||
}
|
||||
|
||||
if (prunedScopedTransientState.draftsByScope !== currentDraftsByScope) {
|
||||
if (prunedScopedState.draftsByScope !== currentDraftsByScope) {
|
||||
for (const scopeKey of Object.keys(currentDraftsByScope)) {
|
||||
if (scopeKey in prunedScopedTransientState.draftsByScope) continue;
|
||||
if (scopeKey in prunedScopedState.draftsByScope) continue;
|
||||
bumpDraftMutationVersion(scopeKey);
|
||||
bumpDraftUploadGeneration(scopeKey);
|
||||
}
|
||||
setLatestAIDraftsByScopeSnapshot(prunedScopedTransientState.draftsByScope);
|
||||
setLatestAIDraftsByScopeSnapshot(prunedScopedState.draftsByScope);
|
||||
emitAIStateChanged(AI_STATE_CHANGED_DRAFTS_BY_SCOPE);
|
||||
}
|
||||
|
||||
if (prunedScopedTransientState.panelViewByScope !== currentPanelViewByScope) {
|
||||
if (prunedScopedState.panelViewByScope !== currentPanelViewByScope) {
|
||||
for (const scopeKey of Object.keys(currentPanelViewByScope)) {
|
||||
if (scopeKey in prunedScopedTransientState.panelViewByScope) continue;
|
||||
if (scopeKey in prunedScopedState.panelViewByScope) continue;
|
||||
bumpDraftMutationVersion(scopeKey);
|
||||
}
|
||||
setLatestAIPanelViewByScopeSnapshot(prunedScopedTransientState.panelViewByScope);
|
||||
setLatestAIPanelViewByScopeSnapshot(prunedScopedState.panelViewByScope);
|
||||
emitAIStateChanged(AI_STATE_CHANGED_PANEL_VIEW_BY_SCOPE);
|
||||
}
|
||||
}
|
||||
@@ -180,10 +208,9 @@ const MAX_STORED_SESSIONS = 50;
|
||||
/** Maximum number of messages per session when persisting to localStorage. */
|
||||
const MAX_SESSION_MESSAGES = 200;
|
||||
/**
|
||||
* Byte budget for the serialized sessions JSON. The localStorage quota is
|
||||
* ~5-10 MB across all keys, and Responses reasoning ciphertext can add tens
|
||||
* of KB per turn, so keep the sessions blob well under the quota with
|
||||
* headroom for the rest of the app's storage keys.
|
||||
* String-length budget for the primary sessions JSON and each overflow chunk.
|
||||
* Replay bulk is shed from the primary blob first; whole sessions that still
|
||||
* do not fit are retained in overflow rather than silently evicted.
|
||||
*/
|
||||
const MAX_SESSIONS_JSON_BYTES = 2 * 1024 * 1024;
|
||||
/** Retry budgets used when the primary budget still fails to persist. */
|
||||
@@ -349,6 +376,10 @@ export function pruneSessionsForStorage(sessions: AISession[]): AISession[] {
|
||||
});
|
||||
}
|
||||
|
||||
export function prepareRestoredSessions(sessions: AISession[], syncEnabled: boolean): AISession[] {
|
||||
return syncEnabled ? sessions : pruneSessionsForStorage(sessions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize sessions for localStorage under a byte budget, escalating pruning
|
||||
* as needed. Returns the JSON to persist plus the (possibly) further-pruned
|
||||
@@ -482,16 +513,226 @@ export function serializeSessionsForStorage(
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist sessions to localStorage with byte-budgeted pruning and retries.
|
||||
* Returns true when the write succeeded; a false result means the payload
|
||||
* could not be persisted even after escalation (it stays memory-only).
|
||||
* Persist sessions to localStorage with byte-budgeted primary/overflow slices.
|
||||
* Returns true when local history was saved, possibly as a newest-primary
|
||||
* fallback with the full history scheduled for disk backup under quota pressure.
|
||||
*/
|
||||
export function writeSessionsForStorage(sessions: AISession[]): boolean {
|
||||
|
||||
// Durability mirror (issue #4015 follow-up): every successful store write
|
||||
// also schedules a debounced disk backup so a wiped/recreated profile does
|
||||
// not take the chat history with it. Persisted history is mirrored, including
|
||||
// overflow sessions, throttled to at most one write per mutation batch.
|
||||
// Before a byte-budget drop, mirror the full
|
||||
// count-capped set even if the subsequent localStorage writes fail.
|
||||
const backupMirror = new DebouncedBackupMirror((json) => {
|
||||
try {
|
||||
void getAIBridge()?.aiSessionsBackupWrite?.({ json })?.catch(() => {});
|
||||
} catch {
|
||||
// Backup failures must never break chat persistence.
|
||||
}
|
||||
});
|
||||
|
||||
export function flushBackupMirror() {
|
||||
try {
|
||||
backupMirror.flushNow();
|
||||
} catch {
|
||||
// Unload and persistence must remain fail-safe.
|
||||
}
|
||||
}
|
||||
|
||||
export function __resetBackupMirrorForTests() {
|
||||
backupMirror.reset();
|
||||
}
|
||||
|
||||
export function scheduleBackupMirror(json: string) {
|
||||
try {
|
||||
backupMirror.schedule(json);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Last successful write: the same immutable sessions array is written again by
|
||||
* the debounced save path and by cloud-sync collection, and each write used to
|
||||
* re-serialize the whole (often multi-MB) history.
|
||||
*/
|
||||
let lastSessionsWrite: { sessions: AISession[]; synced: boolean; json: string } | null = null;
|
||||
|
||||
function rememberSessionsWrite(sessions: AISession[], synced: boolean, json: string): void {
|
||||
lastSessionsWrite = { sessions, synced, json };
|
||||
}
|
||||
|
||||
function storedSessionsJsonEquals(json: string): boolean {
|
||||
try {
|
||||
return localStorageAdapter.readString(STORAGE_KEY_AI_SESSIONS) === json;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function overflowChunkKey(index: number): string {
|
||||
return index === 0 ? STORAGE_KEY_AI_SESSIONS_OVERFLOW : `${STORAGE_KEY_AI_SESSIONS_OVERFLOW}_${index + 1}`;
|
||||
}
|
||||
|
||||
function readOverflowChunks(): string[] {
|
||||
const chunks: string[] = [];
|
||||
for (let index = 0; ; index += 1) {
|
||||
const chunk = localStorageAdapter.readString(overflowChunkKey(index));
|
||||
if (chunk == null) return chunks;
|
||||
chunks.push(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
function clearOverflowChunks(startIndex = 0) {
|
||||
for (let index = startIndex; localStorageAdapter.readString(overflowChunkKey(index)) != null; index += 1) {
|
||||
localStorageAdapter.remove(overflowChunkKey(index));
|
||||
}
|
||||
}
|
||||
|
||||
function writeDiskOverflowIds(ids: string[]): boolean {
|
||||
if (ids.length > 0) {
|
||||
return localStorageAdapter.write(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW, ids);
|
||||
}
|
||||
if (localStorageAdapter.readString(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW) != null) {
|
||||
localStorageAdapter.remove(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Replace the entire overflow blob; never leave a partially written JSON array. */
|
||||
function replaceOverflowChunks(chunks: string[]): boolean {
|
||||
clearOverflowChunks();
|
||||
let complete = false;
|
||||
try {
|
||||
complete = chunks.every((chunk, index) => (
|
||||
localStorageAdapter.writeString(overflowChunkKey(index), chunk)
|
||||
));
|
||||
return complete;
|
||||
} finally {
|
||||
if (!complete) clearOverflowChunks();
|
||||
}
|
||||
}
|
||||
|
||||
/** Read both local retention slices; newer copies win if a session is duplicated. */
|
||||
export function readSessionsFromStorage(): AISession[] {
|
||||
return mergeImportedSessions(
|
||||
readLiveSessionsArray(readOverflowChunks().join('')),
|
||||
readLiveSessionsArray(localStorageAdapter.readString(STORAGE_KEY_AI_SESSIONS)),
|
||||
);
|
||||
}
|
||||
|
||||
export function writeSessionsForStorage(
|
||||
sessions: AISession[],
|
||||
options: { deletedSessionIds?: readonly string[] } = {},
|
||||
): boolean {
|
||||
const synced = Boolean(
|
||||
localStorageAdapter.read<{ enabled?: boolean }>(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS)?.enabled,
|
||||
);
|
||||
// Nothing to do when this exact array was already written in this mode and
|
||||
// storage still holds that write (another window may have replaced it).
|
||||
if (
|
||||
lastSessionsWrite?.sessions === sessions
|
||||
&& lastSessionsWrite.synced === synced
|
||||
&& storedSessionsJsonEquals(lastSessionsWrite.json)
|
||||
// A matching primary alone cannot establish that overflow is intact.
|
||||
&& localStorageAdapter.readString(STORAGE_KEY_AI_SESSIONS_OVERFLOW) == null
|
||||
&& localStorageAdapter.readString(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW) == null
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
// Synced records are authoritative after restart: silently evicting a
|
||||
// session or turn here would turn local retention into cloud deletion.
|
||||
if (localStorageAdapter.read<{ enabled?: boolean }>(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS)?.enabled) {
|
||||
return localStorageAdapter.write(STORAGE_KEY_AI_SESSIONS, sessions);
|
||||
if (synced) {
|
||||
const json = JSON.stringify(sessions);
|
||||
const previousChunks = readOverflowChunks();
|
||||
// The authoritative primary replaces overflow, so free its quota first.
|
||||
clearOverflowChunks();
|
||||
let syncedOk = false;
|
||||
try {
|
||||
syncedOk = localStorageAdapter.writeString(STORAGE_KEY_AI_SESSIONS, json);
|
||||
if (syncedOk) {
|
||||
clearOverflowChunks();
|
||||
if (localStorageAdapter.readString(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW) != null) {
|
||||
localStorageAdapter.remove(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW);
|
||||
}
|
||||
scheduleBackupMirror(json);
|
||||
rememberSessionsWrite(sessions, true, json);
|
||||
}
|
||||
return syncedOk;
|
||||
} finally {
|
||||
if (!syncedOk) replaceOverflowChunks(previousChunks);
|
||||
}
|
||||
}
|
||||
const inputIds = new Set(sessions.map(session => session.id));
|
||||
const pruned = pruneSessionsForStorage(sessions);
|
||||
const retainedIds = new Set(pruned.map(session => session.id));
|
||||
const deletedIds = new Set(options.deletedSessionIds);
|
||||
// A live write can race startup's backup read. Preserve marker IDs absent
|
||||
// from the live input unless explicitly deleted. IDs present in the input
|
||||
// are resolved even if the count cap evicts them; pending IDs block mirroring.
|
||||
const diskOverflowIds = localStorageAdapter.read<unknown>(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW);
|
||||
const unresolvedDiskIds: string[] = Array.isArray(diskOverflowIds)
|
||||
? diskOverflowIds.filter((id): id is string => (
|
||||
typeof id === 'string' && !retainedIds.has(id) && !deletedIds.has(id) && !inputIds.has(id)
|
||||
))
|
||||
: [];
|
||||
let fullBackupScheduled = false;
|
||||
const ensureFullBackup = () => {
|
||||
if (!fullBackupScheduled && unresolvedDiskIds.length === 0) {
|
||||
scheduleBackupMirror(JSON.stringify(pruned));
|
||||
fullBackupScheduled = true;
|
||||
}
|
||||
};
|
||||
const persistCandidate = (
|
||||
candidate: { json: string; sessions: AISession[] },
|
||||
budget: number,
|
||||
chunkBudget = budget,
|
||||
): boolean => {
|
||||
const primaryIds = new Set(candidate.sessions.map(session => session.id));
|
||||
const omitted = pruned.filter(session => !primaryIds.has(session.id));
|
||||
if (omitted.length > 0) ensureFullBackup();
|
||||
// Apply the same replay-bulk ladder to every overflow chat as budgets
|
||||
// tighten. Chunking alone cannot reduce an origin's aggregate quota use.
|
||||
const overflow = omitted.map(session => serializeSessionsForStorage([session], budget).sessions[0]);
|
||||
const overflowJson = overflow.length > 0 ? JSON.stringify(overflow) : '';
|
||||
// Split the array's JSON string, so even one oversized session can span
|
||||
// chunks without losing messages. Concatenate all chunks before parsing.
|
||||
const chunks: string[] = [];
|
||||
// Primary budgets can shrink to a tiny empty chat. Keep overflow writes
|
||||
// bounded independently while still supporting small per-key quotas.
|
||||
const chunkSize = Math.max(32 * 1024, chunkBudget);
|
||||
for (let offset = 0; offset < overflowJson.length; offset += chunkSize) {
|
||||
chunks.push(overflowJson.slice(offset, offset + chunkSize));
|
||||
}
|
||||
const previousChunks = readOverflowChunks();
|
||||
const previousPrimary = localStorageAdapter.readString(STORAGE_KEY_AI_SESSIONS);
|
||||
let primaryWritten = false;
|
||||
let persisted = false;
|
||||
try {
|
||||
// Reclaim both old slices before writing overflow: the final history may
|
||||
// fit even when overflow plus the old, larger primary would exceed quota.
|
||||
clearOverflowChunks();
|
||||
if (!localStorageAdapter.writeString(STORAGE_KEY_AI_SESSIONS, candidate.json)) return false;
|
||||
primaryWritten = true;
|
||||
if (!replaceOverflowChunks(chunks)) return false;
|
||||
if (!writeDiskOverflowIds(unresolvedDiskIds)) return false;
|
||||
persisted = true;
|
||||
if (!fullBackupScheduled && unresolvedDiskIds.length === 0) scheduleBackupMirror(candidate.json);
|
||||
rememberSessionsWrite(sessions, false, candidate.json);
|
||||
return true;
|
||||
} finally {
|
||||
if (!persisted) {
|
||||
clearOverflowChunks();
|
||||
if (primaryWritten) {
|
||||
if (previousPrimary == null) localStorageAdapter.remove(STORAGE_KEY_AI_SESSIONS);
|
||||
else localStorageAdapter.writeString(STORAGE_KEY_AI_SESSIONS, previousPrimary);
|
||||
}
|
||||
replaceOverflowChunks(previousChunks);
|
||||
}
|
||||
}
|
||||
};
|
||||
const primaryCandidates: { json: string; sessions: AISession[] }[] = [];
|
||||
let previousLength = Number.POSITIVE_INFINITY;
|
||||
for (const configuredBudget of [MAX_SESSIONS_JSON_BYTES, ...RETRY_SESSIONS_JSON_BYTES]) {
|
||||
// A real quota failure means the next attempt must be smaller even when
|
||||
@@ -503,20 +744,60 @@ export function writeSessionsForStorage(sessions: AISession[]): boolean {
|
||||
: configuredBudget;
|
||||
const budget = Math.min(configuredBudget, reducedBudget);
|
||||
if (budget < 2) break;
|
||||
const candidate = serializeSessionsForStorage(sessions, budget);
|
||||
if (candidate.json.length >= previousLength) continue;
|
||||
if (localStorageAdapter.writeString(STORAGE_KEY_AI_SESSIONS, candidate.json)) return true;
|
||||
const candidate = serializeSessionsForStorage(pruned, budget);
|
||||
primaryCandidates.push(candidate);
|
||||
// Even an unchanged primary can succeed with smaller overflow chunks or
|
||||
// more degraded overflow replay data at this retry budget.
|
||||
if (persistCandidate(candidate, budget)) return true;
|
||||
previousLength = candidate.json.length;
|
||||
}
|
||||
// Last resort: attempt the smallest representation this serializer can
|
||||
// produce (the newest session with replay-only ciphertext removed). A very
|
||||
// small amount of shared quota may still be enough to preserve that chat.
|
||||
const minimalCandidate = serializeSessionsForStorage(sessions, 0);
|
||||
if (
|
||||
minimalCandidate.json.length < previousLength
|
||||
&& localStorageAdapter.writeString(STORAGE_KEY_AI_SESSIONS, minimalCandidate.json)
|
||||
) {
|
||||
return true;
|
||||
// Last resort: use the smallest primary representation (the newest chat
|
||||
// with replay-only bulk removed), retaining other chats in overflow.
|
||||
const minimalCandidate = serializeSessionsForStorage(pruned, 0);
|
||||
const minimalChunkBudget = Math.min(minimalCandidate.json.length, RETRY_SESSIONS_JSON_BYTES[RETRY_SESSIONS_JSON_BYTES.length - 1]);
|
||||
primaryCandidates.push(minimalCandidate);
|
||||
if (persistCandidate(minimalCandidate, 0, minimalChunkBudget)) return true;
|
||||
|
||||
// If the complete retained set cannot fit, save the newest primary anyway.
|
||||
// Schedule the full disk mirror before discarding overflow; do not let an
|
||||
// old valid primary block persistence of every subsequent conversation turn.
|
||||
ensureFullBackup();
|
||||
const previousChunks = readOverflowChunks();
|
||||
const previousPrimary = localStorageAdapter.readString(STORAGE_KEY_AI_SESSIONS);
|
||||
const previousDiskOverflow = localStorageAdapter.readString(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW);
|
||||
clearOverflowChunks();
|
||||
let primaryWritten = false;
|
||||
let primaryPersisted = false;
|
||||
try {
|
||||
for (const candidate of primaryCandidates) {
|
||||
const primaryIds = new Set(candidate.sessions.map(session => session.id));
|
||||
const diskOnlyIds = [...new Set([
|
||||
...unresolvedDiskIds,
|
||||
...pruned.filter(session => !primaryIds.has(session.id)).map(session => session.id),
|
||||
])];
|
||||
// Replacing a large old primary can free the space needed by metadata.
|
||||
// Roll it back below if the recovery marker still cannot be persisted.
|
||||
if (!localStorageAdapter.writeString(STORAGE_KEY_AI_SESSIONS, candidate.json)) continue;
|
||||
primaryWritten = true;
|
||||
if (writeDiskOverflowIds(diskOnlyIds)) {
|
||||
primaryPersisted = true;
|
||||
rememberSessionsWrite(sessions, false, candidate.json);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (!primaryPersisted) {
|
||||
if (primaryWritten) {
|
||||
if (previousPrimary == null) localStorageAdapter.remove(STORAGE_KEY_AI_SESSIONS);
|
||||
else localStorageAdapter.writeString(STORAGE_KEY_AI_SESSIONS, previousPrimary);
|
||||
}
|
||||
if (previousDiskOverflow != null) {
|
||||
localStorageAdapter.writeString(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW, previousDiskOverflow);
|
||||
} else if (localStorageAdapter.readString(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW) != null) {
|
||||
localStorageAdapter.remove(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW);
|
||||
}
|
||||
replaceOverflowChunks(previousChunks);
|
||||
}
|
||||
}
|
||||
console.warn(
|
||||
'[AIState] Failed to persist AI sessions within the storage quota; recent chat history may not survive a restart.',
|
||||
@@ -531,6 +812,28 @@ export let latestAIPanelViewByScopeSnapshot: PanelViewByScope | null = null;
|
||||
let latestAIDraftMutationVersionByScopeSnapshot: Record<string, number> = {};
|
||||
let latestAIDraftUploadGenerationByScopeSnapshot: Record<string, number> = {};
|
||||
|
||||
|
||||
/**
|
||||
* Issue #4015 R2: rewrite the active-session map when rebinding a dangling
|
||||
* chat. Drops every pointer that still names `sessionId` under a different
|
||||
* scope key, then sets the new scope as active. Callers must persist and
|
||||
* publish the returned map (do not rebuild from a stale snapshot).
|
||||
*/
|
||||
export function rebindActiveSessionMap(
|
||||
activeSessionIdMap: Record<string, string | null>,
|
||||
sessionId: string,
|
||||
scopeKey: string,
|
||||
): Record<string, string | null> {
|
||||
let next = activeSessionIdMap;
|
||||
for (const [key, id] of Object.entries(activeSessionIdMap)) {
|
||||
if (id !== sessionId || key === scopeKey) continue;
|
||||
if (next === activeSessionIdMap) next = { ...activeSessionIdMap };
|
||||
delete next[key];
|
||||
}
|
||||
if (next[scopeKey] === sessionId) return next;
|
||||
return { ...next, [scopeKey]: sessionId };
|
||||
}
|
||||
|
||||
export function setLatestAISessionsSnapshot(sessions: AISession[]) {
|
||||
latestAISessionsSnapshot = sessions;
|
||||
}
|
||||
@@ -543,7 +846,7 @@ export function prewarmAIStateStorageSnapshots() {
|
||||
try {
|
||||
if (latestAISessionsSnapshot === null) {
|
||||
latestAISessionsSnapshot =
|
||||
localStorageAdapter.read<AISession[]>(STORAGE_KEY_AI_SESSIONS) ?? [];
|
||||
readSessionsFromStorage();
|
||||
}
|
||||
if (latestAIActiveSessionMapSnapshot === null) {
|
||||
latestAIActiveSessionMapSnapshot =
|
||||
|
||||
@@ -326,3 +326,20 @@ test("an external clear also drops in-memory compose-bar recall", async () => {
|
||||
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test("saving after a command and peer writes read the clear generation without parsing the history", async (t) => {
|
||||
clearHistory();
|
||||
recordCommand("echo fast-path", "host-fast", "linux");
|
||||
assert.equal(flushCommandHistoryStore(), true);
|
||||
const raw = storage.get(COMMAND_HISTORY_STORAGE_KEY)!;
|
||||
assert.match(raw, /^\{"clearGeneration":\d+,/, "generation is serialized first");
|
||||
|
||||
const parse = t.mock.method(JSON, "parse");
|
||||
recordCommand("echo fast-path-2", "host-fast", "linux");
|
||||
assert.equal(flushCommandHistoryStore(), true);
|
||||
// A peer window's save only needs the generation as well.
|
||||
dispatchStorageEvent(COMMAND_HISTORY_STORAGE_KEY, storage.get(COMMAND_HISTORY_STORAGE_KEY)!, raw);
|
||||
assert.equal(parse.mock.callCount(), 0);
|
||||
parse.mock.restore();
|
||||
assert.ok(queryHistory("echo fast", { hostId: "host-fast" }).some((entry) => entry.command === "echo fast-path-2"));
|
||||
});
|
||||
@@ -68,33 +68,75 @@ function loadStore(): HistoryStore {
|
||||
}
|
||||
|
||||
let saveTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let saveIdleHandle: number | null = null;
|
||||
|
||||
const CLEAR_GENERATION_PREFIX = /^\{"clearGeneration":(\d+)[,}]/;
|
||||
|
||||
/**
|
||||
* The store's clear generation, read from its raw JSON without parsing the
|
||||
* whole history (up to 10k entries, ~1.5 MB). Stores are serialized with
|
||||
* clearGeneration first (serializeStore); other layouts fall back to a parse.
|
||||
*/
|
||||
function readRawClearGeneration(raw: string | null): number | null {
|
||||
if (!raw) return null;
|
||||
const match = CLEAR_GENERATION_PREFIX.exec(raw.slice(0, 48));
|
||||
if (match) return Number(match[1]);
|
||||
try {
|
||||
return readClearGeneration(JSON.parse(raw) as HistoryStore);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function serializeStore(store: HistoryStore): HistoryStore {
|
||||
// Keep clearGeneration first so readRawClearGeneration can find it.
|
||||
return { clearGeneration: readClearGeneration(store), version: store.version, entries: store.entries };
|
||||
}
|
||||
|
||||
function persistStoreNow(store: HistoryStore): boolean {
|
||||
// A peer clear is visible in storage before its queued event is handled.
|
||||
// Never flush a cached pre-clear snapshot over that newer empty store.
|
||||
const persisted = localStorageAdapter.read<HistoryStore>(STORAGE_KEY);
|
||||
if (persisted && readClearGeneration(persisted) > readClearGeneration(store)) {
|
||||
cachedStore = persisted;
|
||||
knownClearGeneration = readClearGeneration(persisted);
|
||||
notifyCommandHistoryCleared();
|
||||
return true;
|
||||
// Only the generation is needed on this per-command path; parse the stored
|
||||
// history just in the rare case where it must be adopted.
|
||||
const persistedGeneration = readRawClearGeneration(localStorageAdapter.readString(STORAGE_KEY));
|
||||
if (persistedGeneration !== null && persistedGeneration > readClearGeneration(store)) {
|
||||
const persisted = localStorageAdapter.read<HistoryStore>(STORAGE_KEY);
|
||||
if (persisted && readClearGeneration(persisted) > readClearGeneration(store)) {
|
||||
cachedStore = persisted;
|
||||
knownClearGeneration = readClearGeneration(persisted);
|
||||
notifyCommandHistoryCleared();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
const ok = localStorageAdapter.write(STORAGE_KEY, store);
|
||||
const ok = localStorageAdapter.write(STORAGE_KEY, serializeStore(store));
|
||||
if (ok) return true;
|
||||
// Storage full — evict lowest scored entries (not just oldest by insertion)
|
||||
const now = Date.now();
|
||||
store.entries.sort((a, b) => scoreEntryAt(b, now) - scoreEntryAt(a, now));
|
||||
store.entries = store.entries.slice(0, Math.floor(MAX_ENTRIES / 2));
|
||||
return localStorageAdapter.write(STORAGE_KEY, store);
|
||||
return localStorageAdapter.write(STORAGE_KEY, serializeStore(store));
|
||||
}
|
||||
|
||||
function hasPendingSave(): boolean {
|
||||
return saveTimer !== null || saveIdleHandle !== null;
|
||||
}
|
||||
|
||||
function saveStore(store: HistoryStore): void {
|
||||
cachedStore = store;
|
||||
// Debounce saves to avoid excessive writes
|
||||
if (saveTimer) clearTimeout(saveTimer);
|
||||
// Debounce saves, then write when the renderer is idle: serializing the
|
||||
// history right after Enter used to land in the middle of command output.
|
||||
cancelPendingSave();
|
||||
saveTimer = setTimeout(() => {
|
||||
persistStoreNow(store);
|
||||
saveTimer = null;
|
||||
const persist = () => {
|
||||
saveIdleHandle = null;
|
||||
persistStoreNow(store);
|
||||
};
|
||||
if (typeof requestIdleCallback === "function") {
|
||||
saveIdleHandle = requestIdleCallback(persist, { timeout: 2000 });
|
||||
} else {
|
||||
persist();
|
||||
}
|
||||
}, 500);
|
||||
}
|
||||
|
||||
@@ -103,6 +145,10 @@ function cancelPendingSave(): void {
|
||||
clearTimeout(saveTimer);
|
||||
saveTimer = null;
|
||||
}
|
||||
if (saveIdleHandle !== null) {
|
||||
if (typeof cancelIdleCallback === "function") cancelIdleCallback(saveIdleHandle);
|
||||
saveIdleHandle = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -129,26 +175,14 @@ function applyExternalCommandHistoryWrite(
|
||||
rawNewValue: string | null,
|
||||
rawOldValue: string | null,
|
||||
): void {
|
||||
let incomingGeneration: number | null = null;
|
||||
if (rawNewValue) {
|
||||
try {
|
||||
incomingGeneration = readClearGeneration(JSON.parse(rawNewValue) as HistoryStore);
|
||||
} catch {
|
||||
incomingGeneration = null;
|
||||
}
|
||||
}
|
||||
// Fires in every other window for each save; read just the generation.
|
||||
const incomingGeneration = readRawClearGeneration(rawNewValue);
|
||||
|
||||
let previousGeneration = knownClearGeneration;
|
||||
if (previousGeneration === null) {
|
||||
// A fresh popup can have compose recall before its first autocomplete query.
|
||||
// The event's old value is its baseline, even after an earlier global clear.
|
||||
try {
|
||||
previousGeneration = rawOldValue
|
||||
? readClearGeneration(JSON.parse(rawOldValue) as HistoryStore)
|
||||
: 0;
|
||||
} catch {
|
||||
previousGeneration = 0;
|
||||
}
|
||||
previousGeneration = readRawClearGeneration(rawOldValue) ?? 0;
|
||||
}
|
||||
if (incomingGeneration !== null && incomingGeneration > previousGeneration) {
|
||||
cancelPendingSave();
|
||||
@@ -156,7 +190,7 @@ function applyExternalCommandHistoryWrite(
|
||||
knownClearGeneration = incomingGeneration;
|
||||
notifyCommandHistoryCleared();
|
||||
} else {
|
||||
if (!saveTimer) cachedStore = null;
|
||||
if (!hasPendingSave()) cachedStore = null;
|
||||
if (incomingGeneration !== null && knownClearGeneration === null) {
|
||||
knownClearGeneration = incomingGeneration;
|
||||
}
|
||||
|
||||
@@ -47,3 +47,45 @@ test("renderer cursor acknowledges GPU publication separately from CPU sample an
|
||||
historyId: "history",
|
||||
});
|
||||
});
|
||||
|
||||
test("idle runtime polls do not notify subscribers until something changes", async () => {
|
||||
const React = await import("react");
|
||||
const { act, create } = await import("react-test-renderer");
|
||||
const { useMonitorSnapshot } = await import("./monitorRuntimeStore");
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
const idle = (takenAt: number): MonitorSnapshot => ({
|
||||
historyMode: "replace",
|
||||
runtimeId: "idle-poll-test",
|
||||
epoch: 7,
|
||||
takenAt,
|
||||
running: [],
|
||||
count: 0,
|
||||
hostCount: 0,
|
||||
activeSessions: [],
|
||||
startedAt: {},
|
||||
hosts: {},
|
||||
});
|
||||
let renders = 0;
|
||||
function Probe() {
|
||||
useMonitorSnapshot();
|
||||
renders += 1;
|
||||
return null;
|
||||
}
|
||||
// Later than anything earlier tests published, so this baseline wins.
|
||||
const base = 1_000_000_000;
|
||||
publishMonitorSnapshot(idle(base));
|
||||
let renderer!: ReturnType<typeof create>;
|
||||
act(() => {
|
||||
renderer = create(React.createElement(Probe));
|
||||
});
|
||||
const baseline = renders;
|
||||
act(() => {
|
||||
for (let at = base + 1000; at <= base + 5000; at += 1000) publishMonitorSnapshot(idle(at));
|
||||
});
|
||||
assert.equal(renders, baseline, "unchanged idle replies must not re-render subscribers");
|
||||
act(() => {
|
||||
publishMonitorSnapshot({ ...idle(base + 6000), running: ["panel"], count: 1 });
|
||||
});
|
||||
assert.equal(renders, baseline + 1, "a real change still notifies");
|
||||
act(() => renderer.unmount());
|
||||
});
|
||||
@@ -14,8 +14,30 @@ const empty: MonitorSnapshot = {
|
||||
};
|
||||
let snapshot = empty;
|
||||
const listeners = new Set<() => void>();
|
||||
export function isIdleMonitorSnapshot(value: MonitorSnapshot): boolean {
|
||||
return value.running.length === 0
|
||||
&& value.count === 0
|
||||
&& value.hostCount === 0
|
||||
&& value.activeSessions.length === 0
|
||||
&& Object.keys(value.hosts).length === 0
|
||||
&& Object.keys(value.startedAt).length === 0;
|
||||
}
|
||||
|
||||
/** An idle runtime polled again: only `takenAt` moved, nothing to render. */
|
||||
function isUnchangedIdleSnapshot(previous: MonitorSnapshot, next: MonitorSnapshot): boolean {
|
||||
return isIdleMonitorSnapshot(previous)
|
||||
&& isIdleMonitorSnapshot(next)
|
||||
&& previous.epoch === next.epoch
|
||||
&& previous.runtimeId === next.runtimeId
|
||||
&& Boolean(previous.unavailable) === Boolean(next.unavailable);
|
||||
}
|
||||
|
||||
export function publishMonitorSnapshot(next: MonitorSnapshot) {
|
||||
snapshot = mergeMonitorSnapshotHistory(snapshot, next);
|
||||
const merged = mergeMonitorSnapshotHistory(snapshot, next);
|
||||
// The runtime is polled even when nothing is monitored; do not wake every
|
||||
// subscriber (host-key dialog, monitor panels) for an unchanged idle reply.
|
||||
if (merged === snapshot || isUnchangedIdleSnapshot(snapshot, merged)) return;
|
||||
snapshot = merged;
|
||||
for (const l of listeners) l();
|
||||
}
|
||||
export function getMonitorHistoryCursor(): MonitorHistoryCursor {
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { observePluginHostSecurityVisibility } from './pluginHostSecurityVisibility';
|
||||
|
||||
test('native modal yields to the host chooser, restores on dismissal, and never restores after cleanup', async () => {
|
||||
const dom = new JSDOM('<body><div role="dialog" aria-modal="true"><div id="mount"></div></div></body>');
|
||||
try {
|
||||
const { document } = dom.window;
|
||||
const calls: boolean[] = [];
|
||||
const stop = observePluginHostSecurityVisibility(document.getElementById('mount')!, (visible) => calls.push(visible));
|
||||
const flush = () => new Promise<void>((resolve) => dom.window.queueMicrotask(resolve));
|
||||
assert.deepEqual(calls, []); // Its own modal does not hide the plugin.
|
||||
const chooser = document.createElement('div');
|
||||
chooser.dataset.hostSecuritySurface = '';
|
||||
document.body.append(chooser);
|
||||
await flush(); assert.deepEqual(calls, [false]);
|
||||
chooser.remove(); await flush(); assert.deepEqual(calls, [false, true]);
|
||||
document.body.append(chooser); await flush();
|
||||
assert.deepEqual(calls, [false, true, false]);
|
||||
stop(); chooser.remove(); await flush();
|
||||
assert.deepEqual(calls, [false, true, false]);
|
||||
} finally { dom.window.close(); }
|
||||
});
|
||||
|
||||
test('hidden security surfaces do not occlude a native view', async () => {
|
||||
const dom = new JSDOM('<body><div id="mount"></div><div hidden><div data-host-security-surface></div></div></body>');
|
||||
try {
|
||||
const calls: boolean[] = [];
|
||||
const stop = observePluginHostSecurityVisibility(dom.window.document.getElementById('mount')!, (visible) => calls.push(visible));
|
||||
assert.deepEqual(calls, []);
|
||||
dom.window.document.querySelector('[hidden]')!.removeAttribute('hidden');
|
||||
await new Promise<void>((resolve) => dom.window.queueMicrotask(resolve));
|
||||
assert.deepEqual(calls, [false]); stop();
|
||||
} finally { dom.window.close(); }
|
||||
});
|
||||
@@ -1,21 +0,0 @@
|
||||
/** Native plugin views must yield while a host-owned security dialog is open. */
|
||||
export function observePluginHostSecurityVisibility(mount: HTMLElement, publish: (visible: boolean) => void): () => void {
|
||||
const document = mount.ownerDocument;
|
||||
let visible = true;
|
||||
const update = () => {
|
||||
const blocked = [...document.querySelectorAll('[data-host-security-surface]')].some((surface) => {
|
||||
const style = document.defaultView!.getComputedStyle(surface);
|
||||
return style.display !== 'none' && style.visibility !== 'hidden'
|
||||
&& !surface.closest('[hidden], [inert], [aria-hidden="true"]');
|
||||
});
|
||||
if (visible === !blocked) return;
|
||||
visible = !blocked;
|
||||
publish(visible);
|
||||
};
|
||||
const observer = new document.defaultView!.MutationObserver(update);
|
||||
observer.observe(document.body, { childList: true, subtree: true, attributes: true,
|
||||
attributeFilter: ['class', 'style', 'hidden', 'inert', 'aria-hidden', 'data-host-security-surface'] });
|
||||
update();
|
||||
// The view lifecycle owns close/retention. Cleanup must never reveal an old view.
|
||||
return () => observer.disconnect();
|
||||
}
|
||||
@@ -33,6 +33,7 @@ const NAMED_KEYS = new Map<string, string>([
|
||||
['tab', 'tab'],
|
||||
]);
|
||||
const PLUGIN_SHORTCUT_EDITABLE_SELECTOR = [
|
||||
'[data-plugin-editing]',
|
||||
'input',
|
||||
'textarea',
|
||||
'select',
|
||||
@@ -44,6 +45,10 @@ const PLUGIN_SHORTCUT_EDITABLE_SELECTOR = [
|
||||
'.monaco-menu-container',
|
||||
].join(', ');
|
||||
|
||||
export function isPluginViewEditingTarget(node: EventTarget | null): boolean {
|
||||
return Boolean((node as Element | null)?.closest?.('[data-plugin-editing]'));
|
||||
}
|
||||
|
||||
function hasEditableShortcutAncestor(node: unknown): boolean {
|
||||
const closest = (node as { closest?: (selector: string) => unknown } | null)?.closest;
|
||||
return typeof closest === 'function'
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { JSDOM } from 'jsdom';
|
||||
|
||||
test('React 19 changes are staged as safe data before any host rendering', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="remote"></div>', { url: 'http://localhost', pretendToBeVisual: true });
|
||||
const saved = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'MutationObserver', 'Event', 'MouseEvent']) {
|
||||
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window] });
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
|
||||
const { default: React, act, useState } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { RemoteMutationObserver } = await import('@remote-dom/core/elements');
|
||||
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
|
||||
const staged = createPluginRemoteTree();
|
||||
const snapshots: ReturnType<typeof staged.snapshot>[] = [];
|
||||
const observer = new RemoteMutationObserver({
|
||||
mutate(records) { snapshots.push(staged.apply(JSON.parse(JSON.stringify(records)))); },
|
||||
call() { throw new Error('Host method calls are unavailable'); },
|
||||
});
|
||||
const container = document.getElementById('remote')!;
|
||||
observer.observe(container);
|
||||
const root = createRoot(container);
|
||||
function Example() {
|
||||
const [count, setCount] = useState(0);
|
||||
return <section className="card" style={{ display: 'grid', gap: '12px' }}><h1>Hello</h1><button type="button" onClick={() => setCount((value) => value + 1)}>Count {count}</button></section>;
|
||||
}
|
||||
try {
|
||||
await act(async () => { root.render(<Example />); await new Promise((resolve) => setTimeout(resolve, 10)); });
|
||||
const first = snapshots.at(-1)!;
|
||||
const section = first.children[0]; assert.equal(section.type, 1);
|
||||
if (section.type !== 1) throw new Error('Expected section');
|
||||
assert.equal(section.attributes.class, 'card');
|
||||
assert.match(section.attributes.style, /display:\s*grid/);
|
||||
await act(async () => { container.querySelector('button')!.click(); await new Promise((resolve) => setTimeout(resolve, 10)); });
|
||||
const updated = JSON.stringify(snapshots.at(-1));
|
||||
assert.match(updated, /Count /); assert.match(updated, /"data":"1"/);
|
||||
assert.equal(staged.isFailed(), false);
|
||||
assert.throws(() => staged.apply([[3, section.id, 'onclick', 'attack()']]));
|
||||
assert.deepEqual(staged.snapshot(), { children: [] });
|
||||
assert.equal(staged.isFailed(), true);
|
||||
assert.throws(() => staged.apply([]));
|
||||
} finally {
|
||||
observer.disconnect(); await act(async () => { root.unmount(); });
|
||||
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT'); dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('removed attributes do not keep checkboxes, menus or old inline styles active', async () => {
|
||||
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
|
||||
const tree = createPluginRemoteTree();
|
||||
tree.apply([[0, '~', { id: 'control', type: 1, element: 'input', attributes: { type: 'checkbox', checked: '', style: 'color:red' }, children: [] }, 0]]);
|
||||
const updated = tree.apply([[3, 'control', 'checked', null], [3, 'control', 'style', null]]);
|
||||
assert.deepEqual(updated.children[0], { id: 'control', type: 1, element: 'input', attributes: { type: 'checkbox' }, children: [] });
|
||||
});
|
||||
|
||||
test('inserting a child into an existing void element fails the view', async () => {
|
||||
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
|
||||
const tree = createPluginRemoteTree();
|
||||
tree.apply([[0, '~', { id: 'input', type: 1, element: 'input', attributes: {}, children: [] }, 0]]);
|
||||
assert.throws(() => tree.apply([[0, 'input', { id: 'child', type: 3, data: 'invalid' }, 0]]), /Void view elements/);
|
||||
assert.equal(tree.isFailed(), true);
|
||||
assert.deepEqual(tree.snapshot(), { children: [] });
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { RemoteReceiver } from '@remote-dom/core/receivers';
|
||||
import { validatePluginMutationBatch, validatePluginRemoteTree } from '@/domain/pluginRemoteTreePolicy.cjs';
|
||||
|
||||
type WireNode = { id: string; type: 3 | 8; data: string } | {
|
||||
id: string; type: 1; element: string; attributes: Record<string, string>; children: WireNode[];
|
||||
};
|
||||
type WireTree = { children: WireNode[] };
|
||||
|
||||
/** Data-only staging area: untrusted changes are never applied directly to the host DOM. */
|
||||
export function createPluginRemoteTree() {
|
||||
const receiver = new RemoteReceiver();
|
||||
let current: WireTree = { children: [] };
|
||||
let failed = false;
|
||||
const project = (node: unknown): WireNode => {
|
||||
const value = node as { id: string; type: number; data?: string; element?: string; attributes?: Record<string, string>; children?: unknown[] };
|
||||
if (value.type === 3 || value.type === 8) return { id: value.id, type: value.type, data: value.data ?? '' };
|
||||
return { id: value.id, type: 1, element: value.element ?? '', attributes: Object.fromEntries(Object.entries(value.attributes ?? {}).filter(([, attribute]) => attribute !== null)), children: (value.children ?? []).map(project) };
|
||||
};
|
||||
return {
|
||||
apply(input: unknown): WireTree {
|
||||
if (failed) throw new Error('Plugin view has been closed after an invalid update');
|
||||
try {
|
||||
validatePluginMutationBatch(input);
|
||||
// Ordinary DOM attribute mutations do not specify a channel. RemoteReceiver
|
||||
// defaults those to properties, so explicitly mark them as attributes.
|
||||
const batch = (input as unknown[][]).map((record) => record[0] === 3 && record.length === 4 ? [...record, 2] : record);
|
||||
receiver.connection.mutate(batch as unknown as Parameters<typeof receiver.connection.mutate>[0]);
|
||||
const next = { children: receiver.root.children.map(project) };
|
||||
validatePluginRemoteTree(next);
|
||||
current = next;
|
||||
return next;
|
||||
} catch (error) {
|
||||
failed = true;
|
||||
current = { children: [] };
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
snapshot(): WireTree { return current; },
|
||||
isFailed(): boolean { return failed; },
|
||||
};
|
||||
}
|
||||
@@ -1,111 +1,7 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import {
|
||||
PluginViewLifecycleController,
|
||||
consumeClosedPluginViewInstance,
|
||||
reconcilePluginViewTabCatalog,
|
||||
markPluginViewOpenTokensClosed,
|
||||
reconcileClosedPluginView,
|
||||
rememberClosedPluginViewInstance,
|
||||
resolvePluginViewSnapshotSelection,
|
||||
shouldReconcilePluginViewTabCatalog,
|
||||
withdrawPluginViewTab,
|
||||
type HostedPluginViewState,
|
||||
} from './pluginViewLifecycle.ts';
|
||||
import { PluginViewTabStore } from './pluginViewTabStore.ts';
|
||||
|
||||
function view(id: string, tabId?: string): HostedPluginViewState {
|
||||
return {
|
||||
id,
|
||||
viewId: `view.${id}`,
|
||||
scopeId: 'window:main',
|
||||
retainContextWhenHidden: false,
|
||||
...(tabId ? { tabId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
test('host close events clear the active renderer instance and identify its native tab', () => {
|
||||
const current = view('active', 'plugin-view:publisher.plugin:view.active');
|
||||
const result = reconcileClosedPluginView({
|
||||
current,
|
||||
retained: new Map([['retained', view('retained')]]),
|
||||
instanceId: 'active',
|
||||
});
|
||||
|
||||
assert.equal(result.current, null);
|
||||
assert.equal(result.matchedCurrent, true);
|
||||
assert.equal(result.closedTabId, current.tabId);
|
||||
assert.equal(result.retained.size, 1);
|
||||
});
|
||||
|
||||
test('host close events remove retained instances without dismissing another active view', () => {
|
||||
const current = view('active');
|
||||
const retainedTab = view('retained-closed', 'plugin-view:publisher.plugin:view.retained');
|
||||
const result = reconcileClosedPluginView({
|
||||
current,
|
||||
retained: new Map([
|
||||
['closed', retainedTab],
|
||||
['kept', view('retained-kept')],
|
||||
]),
|
||||
instanceId: 'retained-closed',
|
||||
});
|
||||
|
||||
assert.equal(result.current, current);
|
||||
assert.equal(result.matchedCurrent, false);
|
||||
assert.equal(result.matchedRetained, true);
|
||||
assert.deepEqual([...result.retained.keys()], ['kept']);
|
||||
assert.equal(result.closedTabId, retainedTab.tabId);
|
||||
});
|
||||
|
||||
test('explicit native-tab close destroys active and retained instances instead of retaining them', () => {
|
||||
const tabId = 'plugin-view:publisher.plugin:view.shared';
|
||||
const result = withdrawPluginViewTab({
|
||||
current: view('active', tabId),
|
||||
retained: new Map([
|
||||
['same-tab', view('retained-same', tabId)],
|
||||
['other-tab', view('retained-other', 'plugin-view:publisher.plugin:view.other')],
|
||||
]),
|
||||
tabId,
|
||||
});
|
||||
|
||||
assert.equal(result.current, null);
|
||||
assert.equal(result.matchedCurrent, true);
|
||||
assert.equal(result.matchedRetained, true);
|
||||
assert.deepEqual(result.instanceIds, ['active', 'retained-same']);
|
||||
assert.deepEqual([...result.retained.keys()], ['other-tab']);
|
||||
});
|
||||
|
||||
test('an early host close tombstone is consumed when the open response arrives later', () => {
|
||||
const tombstones = new Set<string>();
|
||||
rememberClosedPluginViewInstance(tombstones, 'instance-early');
|
||||
assert.equal(consumeClosedPluginViewInstance(tombstones, 'instance-early'), true);
|
||||
assert.equal(consumeClosedPluginViewInstance(tombstones, 'instance-early'), false);
|
||||
|
||||
for (let index = 0; index < 300; index += 1) {
|
||||
rememberClosedPluginViewInstance(tombstones, `instance-${index}`);
|
||||
}
|
||||
assert.equal(tombstones.size, 256);
|
||||
assert.equal(tombstones.has('instance-0'), false);
|
||||
});
|
||||
|
||||
test('explicit close marks only in-flight opens owned by the closed surface', () => {
|
||||
const first = Symbol('first');
|
||||
const second = Symbol('second');
|
||||
const explicitlyClosed = new Set<symbol>();
|
||||
const opening = new Map<string, Set<symbol>>([
|
||||
['window:main\0view.first', new Set([first])],
|
||||
['window:main\0view.second', new Set([second])],
|
||||
]);
|
||||
|
||||
assert.equal(markPluginViewOpenTokensClosed(
|
||||
opening,
|
||||
explicitlyClosed,
|
||||
'window:main\0view.first',
|
||||
), 1);
|
||||
assert.deepEqual([...explicitlyClosed], [first]);
|
||||
assert.equal(markPluginViewOpenTokensClosed(opening, explicitlyClosed, null), 0);
|
||||
});
|
||||
import { reconcilePluginViewTabCatalog, resolvePluginViewSnapshotSelection, shouldReconcilePluginViewTabCatalog } from './pluginViewLifecycle';
|
||||
import { PluginViewTabStore } from './pluginViewTabStore';
|
||||
|
||||
test('locale-only snapshot refresh keeps the owned view alive without weakening context fail-closed behavior', () => {
|
||||
const previous = {
|
||||
@@ -184,30 +80,3 @@ test('active-tab context refresh cannot withdraw the plugin tab that triggered i
|
||||
assert.equal(store.getTabs()[0]?.title, 'Localized View');
|
||||
assert.equal(activeTabId, tab.id);
|
||||
});
|
||||
|
||||
test('lifecycle controller owns retained views, open tokens, tombstones, and teardown', () => {
|
||||
const controller = new PluginViewLifecycleController<HostedPluginViewState>();
|
||||
const tabId = 'plugin-view:publisher.plugin:view.shared';
|
||||
const active = view('active', tabId);
|
||||
const retained = view('retained');
|
||||
controller.setCurrent(active);
|
||||
controller.retain('window:main\0view.retained', retained);
|
||||
|
||||
const token = controller.beginOpen({
|
||||
viewKey: 'window:main\0view.active',
|
||||
tabId,
|
||||
});
|
||||
const closed = controller.handleTabClose(tabId);
|
||||
assert.deepEqual(closed.instanceIds, [active.id]);
|
||||
assert.equal(controller.shouldCloseOpen(token), true);
|
||||
controller.finishOpen({ token, viewKey: 'window:main\0view.active', tabId });
|
||||
assert.equal(controller.shouldCloseOpen(token), false);
|
||||
|
||||
const early = controller.handleHostClose('instance-before-open-response');
|
||||
assert.equal(early.matchedCurrent, false);
|
||||
assert.equal(early.matchedRetained, false);
|
||||
assert.equal(controller.consumeHostClose('instance-before-open-response'), true);
|
||||
|
||||
assert.deepEqual(controller.drain().map((candidate) => candidate.id), [retained.id]);
|
||||
assert.equal(controller.getCurrent(), null);
|
||||
});
|
||||
@@ -1,11 +1,3 @@
|
||||
export interface HostedPluginViewState {
|
||||
id: string;
|
||||
viewId: string;
|
||||
scopeId: string;
|
||||
retainContextWhenHidden: boolean;
|
||||
tabId?: string;
|
||||
}
|
||||
|
||||
export interface PluginViewSnapshotSelection<T> {
|
||||
requestViewId: string;
|
||||
contextKey: string;
|
||||
@@ -81,241 +73,3 @@ export function reconcilePluginViewTabCatalog({
|
||||
store.refreshMetadata(entries);
|
||||
return true;
|
||||
}
|
||||
|
||||
export function reconcileClosedPluginView<T extends HostedPluginViewState>({
|
||||
current,
|
||||
retained,
|
||||
instanceId,
|
||||
}: {
|
||||
current: T | null;
|
||||
retained: ReadonlyMap<string, T>;
|
||||
instanceId: string;
|
||||
}): {
|
||||
current: T | null;
|
||||
retained: Map<string, T>;
|
||||
matchedCurrent: boolean;
|
||||
matchedRetained: boolean;
|
||||
closedTabId?: string;
|
||||
} {
|
||||
const matchedCurrent = current?.id === instanceId;
|
||||
let matchedRetained = false;
|
||||
let retainedTabId: string | undefined;
|
||||
const nextRetained = new Map<string, T>();
|
||||
for (const [key, view] of retained) {
|
||||
if (view.id === instanceId) {
|
||||
matchedRetained = true;
|
||||
retainedTabId = view.tabId;
|
||||
}
|
||||
else nextRetained.set(key, view);
|
||||
}
|
||||
return {
|
||||
current: matchedCurrent ? null : current,
|
||||
retained: nextRetained,
|
||||
matchedCurrent,
|
||||
matchedRetained,
|
||||
...((matchedCurrent ? current?.tabId : retainedTabId)
|
||||
? { closedTabId: matchedCurrent ? current?.tabId : retainedTabId }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function withdrawPluginViewTab<T extends HostedPluginViewState>({
|
||||
current,
|
||||
retained,
|
||||
tabId,
|
||||
}: {
|
||||
current: T | null;
|
||||
retained: ReadonlyMap<string, T>;
|
||||
tabId: string;
|
||||
}): {
|
||||
current: T | null;
|
||||
retained: Map<string, T>;
|
||||
instanceIds: string[];
|
||||
matchedCurrent: boolean;
|
||||
matchedRetained: boolean;
|
||||
} {
|
||||
const matchedCurrent = current?.tabId === tabId;
|
||||
let matchedRetained = false;
|
||||
const instanceIds: string[] = [];
|
||||
if (matchedCurrent && current) instanceIds.push(current.id);
|
||||
const nextRetained = new Map<string, T>();
|
||||
for (const [key, view] of retained) {
|
||||
if (view.tabId === tabId) {
|
||||
matchedRetained = true;
|
||||
instanceIds.push(view.id);
|
||||
} else {
|
||||
nextRetained.set(key, view);
|
||||
}
|
||||
}
|
||||
return {
|
||||
current: matchedCurrent ? null : current,
|
||||
retained: nextRetained,
|
||||
instanceIds,
|
||||
matchedCurrent,
|
||||
matchedRetained,
|
||||
};
|
||||
}
|
||||
|
||||
export function rememberClosedPluginViewInstance(
|
||||
tombstones: Set<string>,
|
||||
instanceId: string,
|
||||
limit = 256,
|
||||
): void {
|
||||
if (tombstones.size >= limit) {
|
||||
const oldest = tombstones.values().next().value;
|
||||
if (typeof oldest === 'string') tombstones.delete(oldest);
|
||||
}
|
||||
tombstones.add(instanceId);
|
||||
}
|
||||
|
||||
export function consumeClosedPluginViewInstance(tombstones: Set<string>, instanceId: string): boolean {
|
||||
return tombstones.delete(instanceId);
|
||||
}
|
||||
|
||||
export function markPluginViewOpenTokensClosed(
|
||||
openingTokens: ReadonlyMap<string, ReadonlySet<symbol>>,
|
||||
explicitlyClosedTokens: Set<symbol>,
|
||||
ownerKey: string | null | undefined,
|
||||
): number {
|
||||
if (!ownerKey) return 0;
|
||||
const tokens = openingTokens.get(ownerKey);
|
||||
if (!tokens) return 0;
|
||||
for (const token of tokens) explicitlyClosedTokens.add(token);
|
||||
return tokens.size;
|
||||
}
|
||||
|
||||
export class PluginViewLifecycleController<T extends HostedPluginViewState = HostedPluginViewState> {
|
||||
private current: T | null = null;
|
||||
private retained = new Map<string, T>();
|
||||
private readonly closedInstanceIds = new Set<string>();
|
||||
private readonly openingTokensByTab = new Map<string, Set<symbol>>();
|
||||
private readonly openingTokensByView = new Map<string, Set<symbol>>();
|
||||
private readonly explicitlyClosedOpenTokens = new Set<symbol>();
|
||||
|
||||
getCurrent(): T | null {
|
||||
return this.current;
|
||||
}
|
||||
|
||||
setCurrent(view: T | null): void {
|
||||
this.current = view;
|
||||
}
|
||||
|
||||
takeCurrent(): T | null {
|
||||
const current = this.current;
|
||||
this.current = null;
|
||||
return current;
|
||||
}
|
||||
|
||||
retain(key: string, view: T): void {
|
||||
this.retained.set(key, view);
|
||||
}
|
||||
|
||||
takeRetained(key: string): T | null {
|
||||
const retained = this.retained.get(key) ?? null;
|
||||
if (retained) this.retained.delete(key);
|
||||
return retained;
|
||||
}
|
||||
|
||||
removeRetained(key: string): void {
|
||||
this.retained.delete(key);
|
||||
}
|
||||
|
||||
removeRetainedWhere(predicate: (view: T) => boolean): T[] {
|
||||
const removed: T[] = [];
|
||||
for (const [key, view] of this.retained) {
|
||||
if (!predicate(view)) continue;
|
||||
this.retained.delete(key);
|
||||
removed.push(view);
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
handleHostClose(instanceId: string) {
|
||||
const next = reconcileClosedPluginView({
|
||||
current: this.current,
|
||||
retained: this.retained,
|
||||
instanceId,
|
||||
});
|
||||
this.current = next.current;
|
||||
this.retained = next.retained;
|
||||
if (!next.matchedCurrent && !next.matchedRetained) {
|
||||
rememberClosedPluginViewInstance(this.closedInstanceIds, instanceId);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
handleTabClose(tabId: string) {
|
||||
const next = withdrawPluginViewTab({
|
||||
current: this.current,
|
||||
retained: this.retained,
|
||||
tabId,
|
||||
});
|
||||
this.current = next.current;
|
||||
this.retained = next.retained;
|
||||
markPluginViewOpenTokensClosed(
|
||||
this.openingTokensByTab,
|
||||
this.explicitlyClosedOpenTokens,
|
||||
tabId,
|
||||
);
|
||||
return next;
|
||||
}
|
||||
|
||||
markViewClosed(viewKey: string | null | undefined): number {
|
||||
return markPluginViewOpenTokensClosed(
|
||||
this.openingTokensByView,
|
||||
this.explicitlyClosedOpenTokens,
|
||||
viewKey,
|
||||
);
|
||||
}
|
||||
|
||||
beginOpen({
|
||||
viewKey,
|
||||
tabId,
|
||||
label,
|
||||
}: {
|
||||
viewKey: string;
|
||||
tabId?: string;
|
||||
label?: string;
|
||||
}): symbol {
|
||||
const token = Symbol(label ?? tabId ?? viewKey);
|
||||
const viewTokens = this.openingTokensByView.get(viewKey) ?? new Set<symbol>();
|
||||
viewTokens.add(token);
|
||||
this.openingTokensByView.set(viewKey, viewTokens);
|
||||
if (tabId) {
|
||||
const tabTokens = this.openingTokensByTab.get(tabId) ?? new Set<symbol>();
|
||||
tabTokens.add(token);
|
||||
this.openingTokensByTab.set(tabId, tabTokens);
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
finishOpen({ token, viewKey, tabId }: { token: symbol; viewKey: string; tabId?: string }): void {
|
||||
this.explicitlyClosedOpenTokens.delete(token);
|
||||
const viewTokens = this.openingTokensByView.get(viewKey);
|
||||
viewTokens?.delete(token);
|
||||
if (viewTokens?.size === 0) this.openingTokensByView.delete(viewKey);
|
||||
if (!tabId) return;
|
||||
const tabTokens = this.openingTokensByTab.get(tabId);
|
||||
tabTokens?.delete(token);
|
||||
if (tabTokens?.size === 0) this.openingTokensByTab.delete(tabId);
|
||||
}
|
||||
|
||||
shouldCloseOpen(token: symbol): boolean {
|
||||
return this.explicitlyClosedOpenTokens.has(token);
|
||||
}
|
||||
|
||||
consumeHostClose(instanceId: string): boolean {
|
||||
return consumeClosedPluginViewInstance(this.closedInstanceIds, instanceId);
|
||||
}
|
||||
|
||||
drain(): T[] {
|
||||
const values = [this.current, ...this.retained.values()].filter((view): view is T => Boolean(view));
|
||||
this.current = null;
|
||||
this.retained.clear();
|
||||
this.closedInstanceIds.clear();
|
||||
this.openingTokensByTab.clear();
|
||||
this.openingTokensByView.clear();
|
||||
this.explicitlyClosedOpenTokens.clear();
|
||||
return values;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import type { HostDrawnViewMessage, HostDrawnViewOpenRequest } from '@netcatty/plugin-contract';
|
||||
type Update = Extract<HostDrawnViewMessage, { kind: 'host-ui.update' }> & { viewId: string };
|
||||
import { PluginViewSessions } from './pluginViewSession';
|
||||
function fixture() {
|
||||
let updates: (data: Update) => void = () => {}; let closed: (data: NetcattyPluginViewClosedEvent) => void = () => {};
|
||||
const opened: HostDrawnViewOpenRequest[] = []; const closes: string[] = []; const events: unknown[] = [];
|
||||
const bridge = { openHostDrawnPluginView: async (request: HostDrawnViewOpenRequest) => { opened.push(request); return { instanceId: request.instanceId }; },
|
||||
closeHostDrawnPluginView: async (id: string) => { closes.push(id); },
|
||||
onHostDrawnPluginViewUpdate: (listener: typeof updates) => { updates = listener; return () => {}; },
|
||||
onPluginViewClosed: (listener: typeof closed) => { closed = listener; return () => {}; },
|
||||
sendHostDrawnPluginViewEvent: async (id: string, event: unknown) => { events.push({ id, event }); } };
|
||||
return { bridge, opened, closes, events, update: (data: Update) => updates(data), close: (data: { instanceId: string }) => closed({ ...data, viewId: request.viewId, pluginId: 'com.example', reason: 'test' }) };
|
||||
}
|
||||
const request = { viewId: 'com.example.view', scopeId: 'window:one', context: {} };
|
||||
test('a hidden view resumes its existing state and plugin instance', async () => {
|
||||
const f = fixture(); const store = new PluginViewSessions();
|
||||
const first = store.acquire('view', f.bridge, request); const id = f.opened[0].instanceId;
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '', mutations: [[0, '~', { id: 'text', type: 3, data: 'kept' }, 0]] });
|
||||
first.release(); const next = store.acquire('view', f.bridge, request);
|
||||
assert.equal(next, first); assert.equal(f.opened.length, 1); assert.deepEqual(next.getSnapshot().tree.children[0], { id: 'text', type: 3, data: 'kept' });
|
||||
next.release(); store.dispose(); await Promise.resolve(); assert.equal(new Set(f.closes).size, 1);
|
||||
});
|
||||
test('host invalidation clears retained content and a reopen creates a new instance', () => {
|
||||
const f = fixture(); const store = new PluginViewSessions(); const old = store.acquire('view', f.bridge, request);
|
||||
f.close({ instanceId: f.opened[0].instanceId }); assert.equal(old.getSnapshot().error, true); assert.deepEqual(old.getSnapshot().tree.children, []);
|
||||
const next = store.acquire('view', f.bridge, request); assert.notEqual(old, next); store.dispose();
|
||||
});
|
||||
test('unacknowledged input is not overwritten by an older plugin update', () => {
|
||||
const f = fixture(); const store = new PluginViewSessions(); const view = store.acquire('view', f.bridge, request);
|
||||
view.send({ type: 'input', nodeId: 'field', value: 'latest' }); assert.equal(view.getSnapshot().settled, false);
|
||||
const base = { kind: 'host-ui.update' as const, viewId: request.viewId, instanceId: f.opened[0].instanceId, css: '', mutations: [] };
|
||||
f.update({ ...base, sequence: 1, acknowledgedEvent: 0 }); assert.equal(view.getSnapshot().settled, false);
|
||||
f.update({ ...base, sequence: 2, acknowledgedEvent: 1 }); assert.equal(view.getSnapshot().settled, true); store.dispose();
|
||||
});
|
||||
test('idle instances are evicted while active instances are never silently replaced', () => {
|
||||
const f = fixture(); const store = new PluginViewSessions(1); const first = store.acquire('one', f.bridge, request);
|
||||
assert.throws(() => store.acquire('two', f.bridge, request), /Too many/); first.release();
|
||||
const second = store.acquire('two', f.bridge, request); assert.notEqual(second, first); assert.equal(f.closes.length, 1); store.dispose();
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { createPluginRemoteTree } from './pluginRemoteTree';
|
||||
import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs';
|
||||
import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
|
||||
|
||||
type Bridge = Pick<NonNullable<ReturnType<typeof import('../../infrastructure/services/netcattyBridge').netcattyBridge.get>>, 'openHostDrawnPluginView' | 'closeHostDrawnPluginView' | 'onHostDrawnPluginViewUpdate' | 'onPluginViewClosed' | 'sendHostDrawnPluginViewEvent' | 'getPluginViewResource'>;
|
||||
export type PluginViewSnapshot = { tree: ReturnType<ReturnType<typeof createPluginRemoteTree>['snapshot']>; css: string; loading: boolean; error: boolean; settled: boolean };
|
||||
const empty = (): PluginViewSnapshot => ({ tree: { children: [] }, css: '', loading: true, error: false, settled: true });
|
||||
|
||||
/** Owns a window's bounded, retained UI instances independently of React mounts. */
|
||||
export class PluginViewSessions {
|
||||
private sessions = new Map<string, ReturnType<PluginViewSessions['create']>>();
|
||||
constructor(private readonly capacity = 16, private readonly idleMs = 300_000) {}
|
||||
private create(key: string, bridge: Bridge, request: Omit<import('@netcatty/plugin-contract').HostDrawnViewOpenRequest, 'instanceId'>) {
|
||||
const id = crypto.randomUUID();
|
||||
const tree = createPluginRemoteTree();
|
||||
let state = empty(); let sequence = 1; let eventId = 0; let disposed = false; let users = 0;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const listeners = new Set<() => void>();
|
||||
const publish = (next: PluginViewSnapshot) => { state = next; for (const listener of listeners) listener(); };
|
||||
const cleanup: Array<() => void> = [];
|
||||
const dispose = (failed = false) => {
|
||||
if (disposed) return;
|
||||
disposed = true; clearTimeout(timer); cleanup.forEach((stop) => stop());
|
||||
this.sessions.delete(key);
|
||||
publish({ ...empty(), loading: false, error: failed });
|
||||
void bridge.closeHostDrawnPluginView?.(id).catch(() => {});
|
||||
};
|
||||
if (!bridge.openHostDrawnPluginView || !bridge.onHostDrawnPluginViewUpdate || !bridge.onPluginViewClosed) throw new Error('Plugin views unavailable');
|
||||
cleanup.push(bridge.onHostDrawnPluginViewUpdate((update) => {
|
||||
if (disposed || update.kind !== 'host-ui.update' || update.instanceId !== id || update.viewId !== request.viewId) return;
|
||||
try {
|
||||
if (update.sequence !== sequence++) throw new Error('Invalid plugin update order');
|
||||
publish({ tree: tree.apply(update.mutations), css: validatePluginStylesheet(update.css), loading: false, error: false, settled: (update.acknowledgedEvent ?? 0) >= eventId });
|
||||
} catch { dispose(true); }
|
||||
}));
|
||||
cleanup.push(bridge.onPluginViewClosed((event) => { if (event.instanceId === id) dispose(true); }));
|
||||
void bridge.openHostDrawnPluginView({ ...request, instanceId: id }).then(() => {
|
||||
if (disposed) void bridge.closeHostDrawnPluginView?.(id).catch(() => {});
|
||||
}).catch(() => dispose(true));
|
||||
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;
|
||||
},
|
||||
get idle() { return users === 0; },
|
||||
getSnapshot: () => state,
|
||||
subscribe(listener: () => void) { listeners.add(listener); return () => { listeners.delete(listener); }; },
|
||||
acquire: () => { clearTimeout(timer); users++; },
|
||||
release: () => { if (--users === 0 && !disposed) timer = setTimeout(() => dispose(), this.idleMs); },
|
||||
send: (event: HostDrawnViewEvent) => {
|
||||
if (disposed || users === 0) return;
|
||||
publish({ ...state, settled: false });
|
||||
void bridge.sendHostDrawnPluginViewEvent?.(id, { ...event, eventId: ++eventId }).catch(() => dispose(true));
|
||||
},
|
||||
dispose,
|
||||
};
|
||||
}
|
||||
acquire(key: string, bridge: Bridge, request: Omit<import('@netcatty/plugin-contract').HostDrawnViewOpenRequest, 'instanceId'>) {
|
||||
let session = this.sessions.get(key);
|
||||
if (!session) {
|
||||
while (this.sessions.size >= this.capacity) {
|
||||
const candidate = [...this.sessions.values()].find((item) => item.idle);
|
||||
if (!candidate) throw new Error('Too many open plugin views');
|
||||
candidate.dispose();
|
||||
}
|
||||
session = this.create(key, bridge, request); this.sessions.set(key, session);
|
||||
}
|
||||
session.acquire(); return session;
|
||||
}
|
||||
closeView(viewId: string) { for (const session of [...this.sessions.values()]) if (session.viewId === viewId) session.dispose(); }
|
||||
closeScope(scope: string) { for (const session of [...this.sessions.values()]) if (session.scope === scope) session.dispose(); }
|
||||
dispose() { for (const session of [...this.sessions.values()]) session.dispose(); }
|
||||
}
|
||||
export const pluginViewSessions = new PluginViewSessions();
|
||||
@@ -393,12 +393,10 @@ export function useSftpFollowTerminalCwd({
|
||||
handledFollowRef.current = { connectionId: currentConnection.id, terminalCwd: targetPath };
|
||||
}
|
||||
}, [
|
||||
activeSessionId,
|
||||
activeTerminalCwd,
|
||||
activeTerminalCwdTrusted,
|
||||
canFollowTerminalCwd,
|
||||
effectiveFollowTerminalCwd,
|
||||
focusedSessionId,
|
||||
hasActiveWork,
|
||||
isVisible,
|
||||
onGetTerminalCwd,
|
||||
|
||||
@@ -3,6 +3,37 @@ import test from 'node:test';
|
||||
|
||||
import { createTerminalReconnectRegistry } from './terminalReconnectRegistry';
|
||||
|
||||
test('recovery snapshots use the current handler and disappear on unmount', () => {
|
||||
const registry = createTerminalReconnectRegistry();
|
||||
assert.equal(registry.inspect('s'), null);
|
||||
const unregister = registry.register('s', () => {}, () => false,
|
||||
() => ({ status: 'disconnected', waitingForInput: true, reconnecting: false }));
|
||||
assert.equal(registry.inspect('s')?.waitingForInput, true);
|
||||
assert.equal(registry.inspect('s')?.reconnectAllowed, false);
|
||||
unregister();
|
||||
assert.equal(registry.inspect('s'), null);
|
||||
});
|
||||
|
||||
test('agent reconnect never queues an unmounted terminal', () => {
|
||||
const registry = createTerminalReconnectRegistry();
|
||||
assert.equal(registry.requestIfAvailable('missing'), false);
|
||||
let calls = 0;
|
||||
registry.register('missing', () => { calls++; });
|
||||
assert.equal(calls, 0);
|
||||
});
|
||||
|
||||
test('agent reconnect respects live eligibility and active reconnects', () => {
|
||||
const registry = createTerminalReconnectRegistry();
|
||||
let eligible = false;
|
||||
let calls = 0;
|
||||
registry.register('s', () => { calls++; registry.setActive('s', true); }, () => eligible);
|
||||
assert.equal(registry.requestIfAvailable('s'), false);
|
||||
eligible = true;
|
||||
assert.equal(registry.requestIfAvailable('s'), true);
|
||||
assert.equal(registry.requestIfAvailable('s'), false);
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
test('a registered terminal session can be reconnected on request', () => {
|
||||
const registry = createTerminalReconnectRegistry();
|
||||
const requestedSessionIds: string[] = [];
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
type TerminalReconnectHandler = () => void;
|
||||
export type TerminalRecoverySnapshot = { status: string; waitingForInput: boolean; reconnecting: boolean; stopped?: boolean };
|
||||
|
||||
export const createTerminalReconnectRegistry = () => {
|
||||
const handlers = new Map<string, TerminalReconnectHandler>();
|
||||
const eligibility = new Map<string, () => boolean>();
|
||||
const recoveryReaders = new Map<string, () => TerminalRecoverySnapshot>();
|
||||
const pendingRequests = new Set<string>();
|
||||
const activeSessionIds = new Set<string>();
|
||||
const enterReconnectEnabledIds = new Set<string>();
|
||||
@@ -28,19 +31,40 @@ export const createTerminalReconnectRegistry = () => {
|
||||
return () => listeners.delete(listener);
|
||||
};
|
||||
|
||||
const register = (sessionId: string, handler: TerminalReconnectHandler): (() => void) => {
|
||||
const register = (sessionId: string, handler: TerminalReconnectHandler,
|
||||
canReconnect: () => boolean = () => false, readRecovery?: () => TerminalRecoverySnapshot): (() => void) => {
|
||||
handlers.set(sessionId, handler);
|
||||
eligibility.set(sessionId, canReconnect);
|
||||
if (readRecovery) recoveryReaders.set(sessionId, readRecovery);
|
||||
else recoveryReaders.delete(sessionId);
|
||||
if (pendingRequests.delete(sessionId)) {
|
||||
handler();
|
||||
}
|
||||
return () => {
|
||||
if (handlers.get(sessionId) === handler) {
|
||||
handlers.delete(sessionId);
|
||||
eligibility.delete(sessionId);
|
||||
recoveryReaders.delete(sessionId);
|
||||
setActive(sessionId, false);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const inspect = (sessionId: string) => {
|
||||
const state = recoveryReaders.get(sessionId)?.();
|
||||
if (!state) return null;
|
||||
return { ...state, reconnecting: state.reconnecting || isActive(sessionId),
|
||||
reconnectAllowed: !isActive(sessionId) && Boolean(eligibility.get(sessionId)?.()) };
|
||||
};
|
||||
|
||||
// Agent requests must never survive unmount or bypass authentication/auto-retry.
|
||||
const requestIfAvailable = (sessionId: string): boolean => {
|
||||
const handler = handlers.get(sessionId);
|
||||
if (!handler || isActive(sessionId) || !eligibility.get(sessionId)?.()) return false;
|
||||
handler();
|
||||
return true;
|
||||
};
|
||||
|
||||
const request = (sessionId: string): boolean => {
|
||||
if (isActive(sessionId)) return false;
|
||||
const handler = handlers.get(sessionId);
|
||||
@@ -66,7 +90,9 @@ export const createTerminalReconnectRegistry = () => {
|
||||
|
||||
return {
|
||||
register,
|
||||
inspect,
|
||||
request,
|
||||
requestIfAvailable,
|
||||
requestEnterReconnect,
|
||||
setEnterReconnectEnabled,
|
||||
setActive,
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { JSDOM } from 'jsdom';
|
||||
|
||||
test('plugin tools stay in the toolbar and retain placement across catalog changes and remount', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost' });
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const key of ['window', 'document', 'navigator', 'localStorage', 'StorageEvent', 'CustomEvent', 'Event']) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window] });
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
|
||||
const { default: React, act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { useTerminalSidePanelTabOrder, TERMINAL_SIDE_PANEL_TAB_DEFAULT_ORDER } = await import('./terminalSidePanelTabs');
|
||||
const { STORAGE_KEY_TERMINAL_SIDE_PANEL_TAB_LAYOUT } = await import('../../infrastructure/config/storageKeys');
|
||||
const plugin = 'plugin-view:com.example.sidebar.page' as const;
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_TERMINAL_SIDE_PANEL_TAB_LAYOUT, JSON.stringify({ order: TERMINAL_SIDE_PANEL_TAB_DEFAULT_ORDER, placement: {} }));
|
||||
let model: ReturnType<typeof useTerminalSidePanelTabOrder>;
|
||||
let tools: typeof plugin[] = [];
|
||||
function Fixture() { model = useTerminalSidePanelTabOrder(tools); return <div />; }
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
const render = async () => { await act(async () => { root.render(<Fixture />); }); };
|
||||
try {
|
||||
await render();
|
||||
tools = [plugin]; await render();
|
||||
assert.equal(model!.sidePanelTabOrder[1], plugin, 'new plugin is a visible toolbar item');
|
||||
assert.ok(model!.partition([...TERMINAL_SIDE_PANEL_TAB_DEFAULT_ORDER, plugin]).shown.includes(plugin));
|
||||
await act(async () => { model!.setPlacement(plugin, 'collapse', [...TERMINAL_SIDE_PANEL_TAB_DEFAULT_ORDER, plugin]); });
|
||||
tools = []; await render();
|
||||
assert.ok(!model!.partition(TERMINAL_SIDE_PANEL_TAB_DEFAULT_ORDER).collapsed.includes(plugin));
|
||||
tools = [plugin]; await render();
|
||||
assert.ok(model!.partition([...TERMINAL_SIDE_PANEL_TAB_DEFAULT_ORDER, plugin]).collapsed.includes(plugin));
|
||||
await act(async () => { root.unmount(); });
|
||||
const nextRoot = createRoot(document.getElementById('root')!);
|
||||
tools = []; await act(async () => { nextRoot.render(<Fixture />); });
|
||||
tools = [plugin]; await act(async () => { nextRoot.render(<Fixture />); });
|
||||
assert.ok(model!.partition([...TERMINAL_SIDE_PANEL_TAB_DEFAULT_ORDER, plugin]).collapsed.includes(plugin), 'cold catalog loading preserves preference');
|
||||
await act(async () => { nextRoot.unmount(); });
|
||||
} finally {
|
||||
for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); }
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT'); dom.window.close();
|
||||
}
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef } from 'react';
|
||||
|
||||
import {
|
||||
normalizeToolbarItemLayout,
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
} from '../../infrastructure/config/storageKeys';
|
||||
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
import { useToolbarItemLayout } from './useToolbarItemLayout';
|
||||
import type { BuiltinSidePanelTool, SidePanelTool } from '../../domain/sidePanelLayout';
|
||||
import { isPluginSidePanelTool, type BuiltinSidePanelTool, type SidePanelTool } from '../../domain/sidePanelLayout';
|
||||
|
||||
export type TerminalSidePanelTabId = SidePanelTool;
|
||||
|
||||
@@ -101,7 +101,7 @@ function migrateSidePanelTabLayoutIfNeeded(): void {
|
||||
|
||||
migrateSidePanelTabLayoutIfNeeded();
|
||||
|
||||
export function useTerminalSidePanelTabOrder(): {
|
||||
export function useTerminalSidePanelTabOrder(pluginTools: readonly SidePanelTool[] = []): {
|
||||
sidePanelTabOrder: TerminalSidePanelTabId[];
|
||||
setSidePanelTabOrder: (order: TerminalSidePanelTabId[]) => void;
|
||||
layout: ToolbarItemLayout;
|
||||
@@ -111,6 +111,23 @@ export function useTerminalSidePanelTabOrder(): {
|
||||
resetLayout: () => void;
|
||||
partition: ReturnType<typeof useToolbarItemLayout>['partition'];
|
||||
} {
|
||||
// Keep preferences for temporarily unavailable/disabled plugins, including
|
||||
// across a cold start before the contribution catalog finishes loading.
|
||||
const knownPluginTools = useRef<Set<string> | null>(null);
|
||||
if (!knownPluginTools.current) {
|
||||
let stored: unknown;
|
||||
try { stored = localStorageAdapter.read(STORAGE_KEY_TERMINAL_SIDE_PANEL_TAB_LAYOUT); } catch { stored = null; }
|
||||
const order = stored && typeof stored === 'object' && !Array.isArray(stored)
|
||||
? (stored as { order?: unknown }).order : [];
|
||||
knownPluginTools.current = new Set(Array.isArray(order)
|
||||
? order.filter((id): id is string => typeof id === 'string' && isPluginSidePanelTool(id)) : []);
|
||||
}
|
||||
for (const tool of pluginTools) if (isPluginSidePanelTool(tool)) knownPluginTools.current.add(tool);
|
||||
const pluginKey = [...knownPluginTools.current].join('\0');
|
||||
const defaults = useMemo<ToolbarItemLayoutDefaults>(() => {
|
||||
const plugins = pluginKey ? pluginKey.split('\0') : [];
|
||||
return { order: [TERMINAL_SIDE_PANEL_TAB_DEFAULT_ORDER[0], ...plugins, ...TERMINAL_SIDE_PANEL_TAB_DEFAULT_ORDER.slice(1)] };
|
||||
}, [pluginKey]);
|
||||
const {
|
||||
layout,
|
||||
setPlacement,
|
||||
@@ -121,9 +138,28 @@ export function useTerminalSidePanelTabOrder(): {
|
||||
partition,
|
||||
} = useToolbarItemLayout(
|
||||
STORAGE_KEY_TERMINAL_SIDE_PANEL_TAB_LAYOUT,
|
||||
TERMINAL_SIDE_PANEL_TAB_LAYOUT_DEFAULTS,
|
||||
defaults,
|
||||
);
|
||||
|
||||
// Newly installed plugins get a visible slot near the start even when an
|
||||
// older saved layout already exists. Existing choices always keep their order.
|
||||
const activePluginKey = pluginTools.filter(isPluginSidePanelTool).join('\0');
|
||||
useEffect(() => {
|
||||
const active = activePluginKey ? activePluginKey.split('\0') : [];
|
||||
if (!active.length || active.some((id) => !layout.order.includes(id))) return;
|
||||
let stored: unknown;
|
||||
try { stored = localStorageAdapter.read(STORAGE_KEY_TERMINAL_SIDE_PANEL_TAB_LAYOUT); } catch { return; }
|
||||
const storedOrder = stored && typeof stored === 'object' && !Array.isArray(stored)
|
||||
? (stored as { order?: unknown }).order : null;
|
||||
const saved = new Set(Array.isArray(storedOrder) ? storedOrder : []);
|
||||
const fresh = active.filter((id) => !saved.has(id));
|
||||
if (!fresh.length) return;
|
||||
const rest = layout.order.filter((id) => !fresh.includes(id));
|
||||
const index = Math.max(0, rest.indexOf('sftp') + 1);
|
||||
const next = [...rest.slice(0, index), ...fresh, ...rest.slice(index)];
|
||||
if (next.some((id, i) => id !== layout.order[i])) setOrder(next);
|
||||
}, [activePluginKey, layout.order, setOrder]);
|
||||
|
||||
const sidePanelTabOrder = layout.order as TerminalSidePanelTabId[];
|
||||
|
||||
const setSidePanelTabOrder = useCallback(
|
||||
|
||||
@@ -0,0 +1,456 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import React, { act } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import type { AISession } from '../../infrastructure/ai/types';
|
||||
import { STORAGE_KEY_AI_ACTIVE_SESSION_MAP, STORAGE_KEY_AI_SESSIONS, STORAGE_KEY_AI_SESSIONS_OVERFLOW, STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW, STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS } from '../../infrastructure/config/storageKeys';
|
||||
import { useAIState } from './useAIState';
|
||||
import { useAISessionsStore } from './aiSessionsStore';
|
||||
import { __resetBackupMirrorForTests, flushBackupMirror, readSessionsFromStorage, setLatestAIActiveSessionMapSnapshot, setLatestAISessionsSnapshot, writeSessionsForStorage } from './aiStateSnapshots';
|
||||
|
||||
for (const enabled of [true, false]) {
|
||||
test(`appending to long history preserves the synced prefix (chat sync ${enabled})`, async () => {
|
||||
const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost' });
|
||||
for (const name of ['window', 'document', 'localStorage', 'CustomEvent', 'Event'] as const) {
|
||||
Object.defineProperty(globalThis, name, { configurable: true, value: name === 'window' ? dom.window : dom.window[name] });
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, value: true });
|
||||
const source: AISession = {
|
||||
id: 'long-chat', title: 'Long chat', agentId: 'codex', externalSessionId: 'native-thread',
|
||||
scope: { type: 'global' }, createdAt: 1, updatedAt: 501,
|
||||
messages: [{ id: 'system', role: 'system', content: 'Instruction', timestamp: 0 },
|
||||
...Array.from({ length: 500 }, (_, index) => ({ id: `message-${index}`, role: 'user' as const, content: `Prompt ${index}`, timestamp: index + 1 }))],
|
||||
};
|
||||
setLatestAISessionsSnapshot([source]);
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_SESSIONS, JSON.stringify([source]));
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS, JSON.stringify({ enabled }));
|
||||
let ai: ReturnType<typeof useAIState>;
|
||||
let sessions: readonly AISession[] = [];
|
||||
function Harness() {
|
||||
ai = useAIState();
|
||||
sessions = useAISessionsStore().sessions;
|
||||
return null;
|
||||
}
|
||||
const container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(async () => { root.render(React.createElement(Harness)); });
|
||||
await act(async () => {
|
||||
ai!.addMessageToSession(source.id, { id: 'new-reply', role: 'assistant', content: 'Continued', timestamp: 502 });
|
||||
});
|
||||
const updated = sessions.find(value => value.id === source.id)!;
|
||||
assert.equal(updated.messages.length, enabled ? 502 : 500);
|
||||
assert.equal(updated.messages[0].id, 'system');
|
||||
assert.equal(updated.messages[1].id, enabled ? 'message-0' : 'message-2');
|
||||
assert.equal(updated.messages.at(-1)?.id, 'new-reply');
|
||||
assert.equal(updated.externalSessionId, 'native-thread');
|
||||
} finally {
|
||||
await act(async () => { root.unmount(); });
|
||||
container.remove();
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('startup and cross-window updates load overflow chats and mirror the merged history', async () => {
|
||||
const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost' });
|
||||
for (const name of ['window', 'document', 'localStorage', 'CustomEvent', 'Event'] as const) {
|
||||
Object.defineProperty(globalThis, name, { configurable: true, value: name === 'window' ? dom.window : dom.window[name] });
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, value: true });
|
||||
const primary: AISession = {
|
||||
id: 'primary', title: 'Primary', agentId: 'catty', scope: { type: 'global' },
|
||||
createdAt: 1, updatedAt: 2, messages: [],
|
||||
};
|
||||
const overflow = { ...primary, id: 'overflow', title: 'Overflow', updatedAt: 1 };
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_SESSIONS, JSON.stringify([primary]));
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_SESSIONS_OVERFLOW, JSON.stringify([overflow]));
|
||||
setLatestAISessionsSnapshot(null as unknown as AISession[]);
|
||||
__resetBackupMirrorForTests();
|
||||
const backups: string[] = [];
|
||||
Object.assign(dom.window, { netcatty: { aiSessionsBackupWrite: async ({ json }: { json: string }) => {
|
||||
backups.push(json);
|
||||
return { ok: true };
|
||||
} } });
|
||||
let sessions: readonly AISession[] = [];
|
||||
function Harness() {
|
||||
useAIState();
|
||||
sessions = useAISessionsStore().sessions;
|
||||
return null;
|
||||
}
|
||||
const container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(async () => { root.render(React.createElement(Harness)); });
|
||||
assert.deepEqual(sessions, [primary, overflow]);
|
||||
flushBackupMirror();
|
||||
assert.deepEqual(JSON.parse(backups[0]), [primary, overflow]);
|
||||
const updatedOverflow = { ...overflow, title: 'Updated elsewhere', updatedAt: 3 };
|
||||
await act(async () => {
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_SESSIONS_OVERFLOW, JSON.stringify([updatedOverflow]));
|
||||
dom.window.dispatchEvent(new dom.window.StorageEvent('storage', { key: STORAGE_KEY_AI_SESSIONS_OVERFLOW }));
|
||||
});
|
||||
assert.deepEqual(sessions, [updatedOverflow, primary]);
|
||||
} finally {
|
||||
await act(async () => { root.unmount(); });
|
||||
__resetBackupMirrorForTests();
|
||||
setLatestAISessionsSnapshot([]);
|
||||
container.remove();
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
for (const scopeType of ['global', 'terminal'] as const) {
|
||||
test(`import retains disk-only chats in live history across rename and deletion (${scopeType})`, async () => {
|
||||
const dom = new JSDOM('<!doctype html><html><body></body></html>', {
|
||||
url: 'http://localhost', storageQuota: 5 * 1024 * 1024,
|
||||
});
|
||||
const previousDOMException = globalThis.DOMException;
|
||||
for (const name of ['window', 'document', 'localStorage', 'CustomEvent', 'Event', 'DOMException'] as const) {
|
||||
Object.defineProperty(globalThis, name, { configurable: true, value: name === 'window' ? dom.window : dom.window[name] });
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, value: true });
|
||||
const source: AISession[] = Array.from({ length: 6 }, (_, index) => ({
|
||||
id: `imported-${index}`, title: `Imported ${index}`, agentId: 'catty',
|
||||
scope: scopeType === 'global' ? { type: 'global' } : { type: 'terminal', targetId: 'closed-terminal' },
|
||||
createdAt: 1, updatedAt: 6 - index,
|
||||
messages: [{ id: 'm', role: 'user', content: 'x'.repeat(Math.floor(1.1 * 1024 * 1024)), timestamp: 1 }],
|
||||
}));
|
||||
const ids = source.map(session => session.id);
|
||||
const backups: string[] = [];
|
||||
Object.assign(dom.window, { netcatty: {
|
||||
aiSessionsBackupImport: async () => ({ success: true, json: JSON.stringify(source) }),
|
||||
aiSessionsBackupWrite: async ({ json }: { json: string }) => { backups.push(json); return { ok: true }; },
|
||||
} });
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_SESSIONS, '[]');
|
||||
setLatestAISessionsSnapshot([]);
|
||||
setLatestAIActiveSessionMapSnapshot({});
|
||||
__resetBackupMirrorForTests();
|
||||
let ai!: ReturnType<typeof useAIState>;
|
||||
let sessions: readonly AISession[] = [];
|
||||
function Harness() {
|
||||
ai = useAIState();
|
||||
sessions = useAISessionsStore().sessions;
|
||||
return null;
|
||||
}
|
||||
const container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(async () => { root.render(React.createElement(Harness)); });
|
||||
await act(async () => { ai.cleanupOrphanedSessions(new Set()); });
|
||||
let importedCount = 0;
|
||||
await act(async () => { importedCount = await ai.importSessionsBackup(); });
|
||||
assert.equal(importedCount, source.length);
|
||||
assert.deepEqual(sessions.map(session => session.id), ids);
|
||||
assert.deepEqual(readSessionsFromStorage().map(session => session.id), [ids[0]]);
|
||||
assert.deepEqual(JSON.parse(dom.window.localStorage.getItem(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW)!), ids.slice(1));
|
||||
assert.equal(sessions.every(session => !!session.scopeDangling === (scopeType === 'terminal')), true);
|
||||
flushBackupMirror();
|
||||
assert.deepEqual(JSON.parse(backups.at(-1)!), sessions);
|
||||
|
||||
await act(async () => { ai.updateSessionTitle(ids[0], 'Renamed after import'); });
|
||||
assert.deepEqual(sessions.map(session => session.id), ids);
|
||||
assert.equal(sessions[0].title, 'Renamed after import');
|
||||
assert.deepEqual(JSON.parse(dom.window.localStorage.getItem(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW)!), ids.slice(1));
|
||||
flushBackupMirror();
|
||||
assert.deepEqual(JSON.parse(backups.at(-1)!), sessions);
|
||||
|
||||
await act(async () => { ai.deleteSession(ids[5]); });
|
||||
assert.deepEqual(sessions.map(session => session.id), ids.slice(0, 5));
|
||||
assert.deepEqual(JSON.parse(dom.window.localStorage.getItem(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW)!), ids.slice(1, 5));
|
||||
flushBackupMirror();
|
||||
assert.deepEqual(JSON.parse(backups.at(-1)!), sessions);
|
||||
} finally {
|
||||
await act(async () => { root.unmount(); });
|
||||
__resetBackupMirrorForTests();
|
||||
setLatestAISessionsSnapshot([]);
|
||||
setLatestAIActiveSessionMapSnapshot({});
|
||||
container.remove();
|
||||
dom.window.close();
|
||||
Object.defineProperty(globalThis, 'DOMException', { configurable: true, value: previousDOMException });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('startup recovers disk-only chats before mirroring a valid partial primary', async () => {
|
||||
const dom = new JSDOM('<!doctype html><html><body></body></html>', {
|
||||
url: 'http://localhost', storageQuota: 5 * 1024 * 1024,
|
||||
});
|
||||
const previousDOMException = globalThis.DOMException;
|
||||
for (const name of ['window', 'document', 'localStorage', 'CustomEvent', 'Event', 'DOMException'] as const) {
|
||||
Object.defineProperty(globalThis, name, { configurable: true, value: name === 'window' ? dom.window : dom.window[name] });
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, value: true });
|
||||
const source: AISession[] = Array.from({ length: 6 }, (_, index) => ({
|
||||
id: `chat-${index}`, title: `Chat ${index}`, agentId: 'catty', scope: { type: 'global' },
|
||||
createdAt: 1, updatedAt: 6 - index,
|
||||
messages: [{ id: 'm', role: 'user', content: 'x'.repeat(Math.floor(1.1 * 1024 * 1024)), timestamp: 1 }],
|
||||
}));
|
||||
const backups: string[] = [];
|
||||
let reads = 0;
|
||||
let resolveRead!: (backup: { ok: boolean; json: string }) => void;
|
||||
Object.assign(dom.window, { netcatty: {
|
||||
aiSessionsBackupWrite: async ({ json }: { json: string }) => { backups.push(json); return { ok: true }; },
|
||||
aiSessionsBackupReadLatest: () => {
|
||||
reads += 1;
|
||||
return new Promise(resolve => { resolveRead = resolve; });
|
||||
},
|
||||
} });
|
||||
__resetBackupMirrorForTests();
|
||||
assert.equal(writeSessionsForStorage(source), true);
|
||||
flushBackupMirror();
|
||||
assert.deepEqual(JSON.parse(backups[0]), source);
|
||||
assert.deepEqual(readSessionsFromStorage(), [source[0]]);
|
||||
assert.deepEqual(JSON.parse(dom.window.localStorage.getItem(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW)!), source.slice(1).map(session => session.id));
|
||||
// A newer local copy must win, and an old deleted chat in the backup must
|
||||
// stay deleted: only the explicitly recorded disk-only IDs are recovered.
|
||||
const primary = { ...source[0], title: 'Newer primary', updatedAt: 10 };
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_SESSIONS, JSON.stringify([primary]));
|
||||
const expected = [primary, ...source.slice(1)];
|
||||
const staleBackup = JSON.stringify([...source, { ...source[5], id: 'deleted-chat' }]);
|
||||
backups.length = 0;
|
||||
__resetBackupMirrorForTests();
|
||||
setLatestAISessionsSnapshot(null as unknown as AISession[]);
|
||||
let sessions: readonly AISession[] = [];
|
||||
function Harness() {
|
||||
useAIState();
|
||||
sessions = useAISessionsStore().sessions;
|
||||
return null;
|
||||
}
|
||||
const container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(async () => { root.render(React.createElement(Harness)); });
|
||||
assert.equal(reads, 1);
|
||||
flushBackupMirror();
|
||||
assert.deepEqual(backups, []);
|
||||
await act(async () => { resolveRead({ ok: true, json: staleBackup }); });
|
||||
assert.deepEqual(sessions, expected);
|
||||
flushBackupMirror();
|
||||
assert.deepEqual(JSON.parse(backups.at(-1)!), expected);
|
||||
assert.deepEqual(readSessionsFromStorage(), [primary]);
|
||||
} finally {
|
||||
await act(async () => { root.unmount(); });
|
||||
__resetBackupMirrorForTests();
|
||||
setLatestAISessionsSnapshot([]);
|
||||
container.remove();
|
||||
dom.window.close();
|
||||
Object.defineProperty(globalThis, 'DOMException', { configurable: true, value: previousDOMException });
|
||||
}
|
||||
});
|
||||
|
||||
for (const scopeType of ['terminal', 'workspace'] as const) {
|
||||
test(`startup orphan cleanup preserves pending disk-only recovery (${scopeType})`, async () => {
|
||||
const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost' });
|
||||
for (const name of ['window', 'document', 'localStorage', 'CustomEvent', 'Event'] as const) {
|
||||
Object.defineProperty(globalThis, name, { configurable: true, value: name === 'window' ? dom.window : dom.window[name] });
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, value: true });
|
||||
const primary: AISession = {
|
||||
id: 'closed-primary', title: 'Closed primary', agentId: 'catty',
|
||||
scope: { type: scopeType, targetId: 'closed-target' },
|
||||
createdAt: 1, updatedAt: 2, messages: [],
|
||||
};
|
||||
const diskOnly: AISession = {
|
||||
...primary, id: 'disk-only', title: 'Disk only', updatedAt: 1,
|
||||
scope: { type: scopeType, targetId: 'another-closed-target' },
|
||||
};
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_SESSIONS, JSON.stringify([primary]));
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW, JSON.stringify([diskOnly.id]));
|
||||
setLatestAISessionsSnapshot(null as unknown as AISession[]);
|
||||
__resetBackupMirrorForTests();
|
||||
const backups: string[] = [];
|
||||
let reads = 0;
|
||||
let resolveRead!: (backup: { ok: boolean; json: string }) => void;
|
||||
Object.assign(dom.window, { netcatty: {
|
||||
aiSessionsBackupWrite: async ({ json }: { json: string }) => { backups.push(json); return { ok: true }; },
|
||||
aiSessionsBackupReadLatest: () => {
|
||||
reads += 1;
|
||||
return new Promise(resolve => { resolveRead = resolve; });
|
||||
},
|
||||
} });
|
||||
let sessions: readonly AISession[] = [];
|
||||
function Harness() {
|
||||
const ai = useAIState();
|
||||
sessions = useAISessionsStore().sessions;
|
||||
// TerminalLayerSupport performs this cleanup on mount, while the disk
|
||||
// backup IPC read can still be pending.
|
||||
React.useEffect(() => { ai.cleanupOrphanedSessions(new Set()); }, [ai.cleanupOrphanedSessions]);
|
||||
return null;
|
||||
}
|
||||
const container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(async () => { root.render(React.createElement(Harness)); });
|
||||
assert.equal(reads, 1);
|
||||
assert.deepEqual(sessions, [{ ...primary, scopeDangling: true }]);
|
||||
assert.deepEqual(JSON.parse(dom.window.localStorage.getItem(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW)!), [diskOnly.id]);
|
||||
flushBackupMirror();
|
||||
assert.deepEqual(backups, []);
|
||||
|
||||
await act(async () => { resolveRead({ ok: true, json: JSON.stringify([primary, diskOnly]) }); });
|
||||
const expected = [primary, diskOnly].map(session => ({ ...session, scopeDangling: true }));
|
||||
assert.deepEqual(sessions, expected);
|
||||
assert.deepEqual(readSessionsFromStorage(), expected);
|
||||
assert.equal(dom.window.localStorage.getItem(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW), null);
|
||||
flushBackupMirror();
|
||||
assert.deepEqual(JSON.parse(backups.at(-1)!), expected);
|
||||
} finally {
|
||||
await act(async () => { root.unmount(); });
|
||||
__resetBackupMirrorForTests();
|
||||
setLatestAISessionsSnapshot([]);
|
||||
container.remove();
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
for (const mutation of ['rename', 'create', 'delete', 'delete-pending'] as const) {
|
||||
test(`live ${mutation} preserves intended history across pending disk recovery`, async () => {
|
||||
const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost' });
|
||||
for (const name of ['window', 'document', 'localStorage', 'CustomEvent', 'Event'] as const) {
|
||||
Object.defineProperty(globalThis, name, { configurable: true, value: name === 'window' ? dom.window : dom.window[name] });
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, value: true });
|
||||
const primary: AISession = {
|
||||
id: 'primary', title: 'Primary', agentId: 'catty', scope: { type: 'global' },
|
||||
createdAt: 1, updatedAt: 2, messages: [],
|
||||
};
|
||||
const diskOnly = { ...primary, id: 'disk-only', updatedAt: 1 };
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_SESSIONS, JSON.stringify([primary]));
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW, JSON.stringify([diskOnly.id]));
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_ACTIVE_SESSION_MAP, JSON.stringify({ 'global:': diskOnly.id }));
|
||||
setLatestAIActiveSessionMapSnapshot({ 'global:': diskOnly.id });
|
||||
setLatestAISessionsSnapshot(null as unknown as AISession[]);
|
||||
__resetBackupMirrorForTests();
|
||||
const backups: string[] = [];
|
||||
let resolveRead!: (backup: { ok: boolean; json: string }) => void;
|
||||
Object.assign(dom.window, { netcatty: {
|
||||
aiSessionsBackupWrite: async ({ json }: { json: string }) => { backups.push(json); return { ok: true }; },
|
||||
aiSessionsBackupReadLatest: () => new Promise(resolve => { resolveRead = resolve; }),
|
||||
} });
|
||||
let ai!: ReturnType<typeof useAIState>;
|
||||
let snapshot!: ReturnType<typeof useAISessionsStore>;
|
||||
function Harness() {
|
||||
ai = useAIState();
|
||||
snapshot = useAISessionsStore();
|
||||
return null;
|
||||
}
|
||||
const container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(async () => { root.render(React.createElement(Harness)); });
|
||||
assert.equal(snapshot.activeSessionIdMap['global:'], diskOnly.id);
|
||||
await act(async () => {
|
||||
if (mutation === 'rename') ai.updateSessionTitle(primary.id, 'Renamed before recovery');
|
||||
else if (mutation === 'create') ai.createSession({ type: 'global' }, 'catty');
|
||||
else ai.deleteSession(mutation === 'delete-pending' ? diskOnly.id : primary.id);
|
||||
});
|
||||
const liveBeforeRecovery = [...snapshot.sessions];
|
||||
const expectedActiveId = mutation === 'create' ? liveBeforeRecovery[0].id
|
||||
: mutation === 'delete-pending' ? null : diskOnly.id;
|
||||
assert.equal(snapshot.activeSessionIdMap['global:'], expectedActiveId);
|
||||
assert.deepEqual(readSessionsFromStorage(), liveBeforeRecovery);
|
||||
const recoveryMarker = dom.window.localStorage.getItem(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW);
|
||||
assert.deepEqual(recoveryMarker == null ? null : JSON.parse(recoveryMarker), mutation === 'delete-pending' ? null : [diskOnly.id]);
|
||||
flushBackupMirror();
|
||||
assert.deepEqual(backups.map(json => JSON.parse(json)), mutation === 'delete-pending' ? [liveBeforeRecovery] : []);
|
||||
|
||||
await act(async () => { resolveRead({ ok: true, json: JSON.stringify([primary, diskOnly]) }); });
|
||||
const expected = mutation === 'delete-pending' ? liveBeforeRecovery : [...liveBeforeRecovery, diskOnly];
|
||||
assert.deepEqual(snapshot.sessions, expected);
|
||||
assert.deepEqual(readSessionsFromStorage(), expected);
|
||||
assert.equal(dom.window.localStorage.getItem(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW), null);
|
||||
flushBackupMirror();
|
||||
assert.deepEqual(JSON.parse(backups.at(-1)!), expected);
|
||||
} finally {
|
||||
await act(async () => { root.unmount(); });
|
||||
__resetBackupMirrorForTests();
|
||||
setLatestAISessionsSnapshot([]);
|
||||
setLatestAIActiveSessionMapSnapshot({});
|
||||
container.remove();
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('count-cap eviction clears a loaded disk-only marker and resumes backup mirroring', () => {
|
||||
const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost' });
|
||||
for (const name of ['window', 'document', 'localStorage', 'CustomEvent', 'Event'] as const) {
|
||||
Object.defineProperty(globalThis, name, { configurable: true, value: name === 'window' ? dom.window : dom.window[name] });
|
||||
}
|
||||
const source: AISession[] = Array.from({ length: 51 }, (_, index) => ({
|
||||
id: `chat-${index}`, title: `Chat ${index}`, agentId: 'catty', scope: { type: 'global' },
|
||||
createdAt: 1, updatedAt: 51 - index, messages: [],
|
||||
}));
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW, JSON.stringify([source[50].id]));
|
||||
const backups: string[] = [];
|
||||
Object.assign(dom.window, { netcatty: { aiSessionsBackupWrite: async ({ json }: { json: string }) => {
|
||||
backups.push(json);
|
||||
return { ok: true };
|
||||
} } });
|
||||
__resetBackupMirrorForTests();
|
||||
try {
|
||||
assert.equal(writeSessionsForStorage(source), true);
|
||||
assert.deepEqual(readSessionsFromStorage(), source.slice(0, 50));
|
||||
assert.equal(dom.window.localStorage.getItem(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW), null);
|
||||
flushBackupMirror();
|
||||
assert.deepEqual(backups.map(json => JSON.parse(json)), [source.slice(0, 50)]);
|
||||
} finally {
|
||||
__resetBackupMirrorForTests();
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
for (const keepPrimary of [true, false]) {
|
||||
test(`deletion clears disk-only recovery and remains authoritative (keep primary ${keepPrimary})`, async () => {
|
||||
const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost' });
|
||||
for (const name of ['window', 'document', 'localStorage', 'CustomEvent', 'Event'] as const) {
|
||||
Object.defineProperty(globalThis, name, { configurable: true, value: name === 'window' ? dom.window : dom.window[name] });
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, value: true });
|
||||
const primary: AISession = {
|
||||
id: 'primary', title: 'Primary', agentId: 'catty', scope: { type: 'global' },
|
||||
createdAt: 1, updatedAt: 2, messages: [],
|
||||
};
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_SESSIONS, JSON.stringify([primary]));
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW, JSON.stringify(['deleted-chat']));
|
||||
const remaining = keepPrimary ? [primary] : [];
|
||||
assert.equal(writeSessionsForStorage(remaining, { deletedSessionIds: ['deleted-chat'] }), true);
|
||||
assert.equal(dom.window.localStorage.getItem(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW), null);
|
||||
__resetBackupMirrorForTests();
|
||||
setLatestAISessionsSnapshot(null as unknown as AISession[]);
|
||||
let reads = 0;
|
||||
Object.assign(dom.window, { netcatty: { aiSessionsBackupReadLatest: async () => {
|
||||
reads += 1;
|
||||
return { ok: true, json: JSON.stringify([primary, { ...primary, id: 'deleted-chat' }]) };
|
||||
} } });
|
||||
let sessions: readonly AISession[] = [];
|
||||
function Harness() {
|
||||
useAIState();
|
||||
sessions = useAISessionsStore().sessions;
|
||||
return null;
|
||||
}
|
||||
const container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(async () => { root.render(React.createElement(Harness)); });
|
||||
assert.equal(reads, 0);
|
||||
assert.deepEqual(sessions, remaining);
|
||||
} finally {
|
||||
await act(async () => { root.unmount(); });
|
||||
__resetBackupMirrorForTests();
|
||||
setLatestAISessionsSnapshot([]);
|
||||
container.remove();
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
+213
-19
@@ -14,12 +14,15 @@ import {
|
||||
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,
|
||||
STORAGE_KEY_AI_ACTIVE_SESSION_MAP,
|
||||
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';
|
||||
@@ -63,12 +66,18 @@ import {
|
||||
bumpDraftUploadGeneration,
|
||||
cleanupDeletedAIChatSessions,
|
||||
cleanupOrphanedAISessions,
|
||||
latestAIActiveTargetIdsSnapshot,
|
||||
getAIBridge,
|
||||
flushBackupMirror,
|
||||
getDraftUploadGeneration,
|
||||
latestAIActiveSessionMapSnapshot,
|
||||
latestAIDraftsByScopeSnapshot,
|
||||
latestAIPanelViewByScopeSnapshot,
|
||||
latestAISessionsSnapshot,
|
||||
prepareRestoredSessions,
|
||||
readSessionsFromStorage,
|
||||
scheduleBackupMirror,
|
||||
rebindActiveSessionMap,
|
||||
writeSessionsForStorage,
|
||||
setLatestAIActiveSessionMapSnapshot,
|
||||
setLatestAIDraftsByScopeSnapshot,
|
||||
@@ -77,6 +86,12 @@ import {
|
||||
type DraftsByScope,
|
||||
type PanelViewByScope,
|
||||
} from './aiStateSnapshots';
|
||||
import {
|
||||
isMissingOrCorruptSessionsStore,
|
||||
parseSessionsStore,
|
||||
mergeImportedSessions,
|
||||
parseBackupSessions,
|
||||
} from './aiSessionsBackup';
|
||||
import { AI_STATE_CHANGED_EVENT, emitAIStateChanged } from './aiStateEvents';
|
||||
import {
|
||||
persistCommandBlocklistSetting,
|
||||
@@ -168,9 +183,82 @@ export function useAIState() {
|
||||
// ── Sessions ──
|
||||
const [sessions, setSessionsRaw] = useState<AISession[]>(() =>
|
||||
latestAISessionsSnapshot
|
||||
?? localStorageAdapter.read<AISession[]>(STORAGE_KEY_AI_SESSIONS)
|
||||
?? []
|
||||
?? readSessionsFromStorage()
|
||||
);
|
||||
// An explicit empty array is authoritative, even if the backup is stale.
|
||||
// Disk-only overflow IDs also permit recovery, without reviving deleted chats.
|
||||
useEffect(() => {
|
||||
window.addEventListener('beforeunload', flushBackupMirror);
|
||||
return () => window.removeEventListener('beforeunload', flushBackupMirror);
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
const liveRaw = localStorageAdapter.readString(STORAGE_KEY_AI_SESSIONS);
|
||||
const liveStore = parseSessionsStore(liveRaw);
|
||||
const liveSessions = readSessionsFromStorage();
|
||||
const diskOnlyRecovery = (localStorageAdapter.read<string[]>(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW)?.length ?? 0) > 0;
|
||||
if (!diskOnlyRecovery && (liveStore.valid || liveSessions.length > 0)) {
|
||||
if (liveSessions.length > 0) scheduleBackupMirror(JSON.stringify(liveSessions));
|
||||
return;
|
||||
}
|
||||
if (!diskOnlyRecovery && latestAISessionsSnapshot && latestAISessionsSnapshot.length > 0) return;
|
||||
const bridge = getAIBridge();
|
||||
if (!bridge?.aiSessionsBackupReadLatest) return;
|
||||
let cancelled = false;
|
||||
const canRestore = () => diskOnlyRecovery
|
||||
? (localStorageAdapter.read<string[]>(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW)?.length ?? 0) > 0
|
||||
: isMissingOrCorruptSessionsStore(localStorageAdapter.readString(STORAGE_KEY_AI_SESSIONS))
|
||||
&& readSessionsFromStorage().length === 0
|
||||
&& (latestAISessionsSnapshot?.length ?? 0) === 0
|
||||
&& sessionsRef.current.length === 0;
|
||||
void (async () => {
|
||||
try {
|
||||
if (!canRestore()) return;
|
||||
const backup = await bridge.aiSessionsBackupReadLatest?.();
|
||||
if (cancelled || !backup?.ok) return;
|
||||
// Re-check after the async gap so live mutations and deletions win.
|
||||
if (!canRestore()) return;
|
||||
const backupSessions = parseBackupSessions(backup.json);
|
||||
if (!backupSessions) return;
|
||||
const diskOnlyIds = new Set(localStorageAdapter.read<string[]>(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW) ?? []);
|
||||
const recovered = diskOnlyRecovery
|
||||
? mergeImportedSessions(
|
||||
backupSessions.filter(session => diskOnlyIds.has(session.id)),
|
||||
latestAISessionsSnapshot ?? readSessionsFromStorage(),
|
||||
)
|
||||
: backupSessions;
|
||||
const syncEnabled = !!localStorageAdapter.read<{ enabled?: boolean }>(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS)?.enabled;
|
||||
const restored = prepareRestoredSessions(recovered, syncEnabled);
|
||||
if (restored.length === 0) return;
|
||||
// Apply restore synchronously (not inside a setState updater). A
|
||||
// deferred updater would leave didRestore false and skip dangling
|
||||
// marking even when the records later land in React state.
|
||||
setLatestAISessionsSnapshot(restored);
|
||||
writeSessionsForStorage(restored);
|
||||
emitAIStateChanged(STORAGE_KEY_AI_SESSIONS);
|
||||
// Restore does not change live terminals/workspaces, so the orphan-
|
||||
// cleanup effect will not run. Reuse the last known live target set
|
||||
// (empty is valid: nothing live) so chats bound to missing scopes
|
||||
// become dangling and /chats can offer /rebind.
|
||||
cleanupOrphanedAISessions(latestAIActiveTargetIdsSnapshot);
|
||||
const nextSessions = latestAISessionsSnapshot ?? restored;
|
||||
sessionsRef.current = nextSessions;
|
||||
setSessionsRaw(nextSessions);
|
||||
setActiveSessionIdMapRaw(
|
||||
latestAIActiveSessionMapSnapshot
|
||||
?? localStorageAdapter.read<Record<string, string | null>>(STORAGE_KEY_AI_ACTIVE_SESSION_MAP)
|
||||
?? {},
|
||||
);
|
||||
console.info(
|
||||
`[AIState] Restored ${restored.length} AI session(s) from the disk backup.`,
|
||||
);
|
||||
} catch {
|
||||
// Backup restore must never break startup.
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
// Ref that always holds the latest sessions for use inside debounced callbacks
|
||||
const sessionsRef = useRef(sessions);
|
||||
useEffect(() => {
|
||||
@@ -245,6 +333,11 @@ export function useAIState() {
|
||||
|
||||
useEffect(() => {
|
||||
const validSessionIds = new Set<string>(sessions.map((session) => session.id));
|
||||
// Disk-only chats may not have arrived from the startup backup read yet.
|
||||
// Keep their active pointers and panel views until recovery or deletion.
|
||||
for (const id of localStorageAdapter.read<string[]>(STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW) ?? []) {
|
||||
validSessionIds.add(id);
|
||||
}
|
||||
let changed = false;
|
||||
const nextActiveSessionIdMap: Record<string, string | null> = {};
|
||||
|
||||
@@ -464,7 +557,9 @@ export function useAIState() {
|
||||
useEffect(() => {
|
||||
const handleStorage = (e: StorageEvent) => {
|
||||
try {
|
||||
switch (e.key) {
|
||||
const key = e.key === STORAGE_KEY_AI_SESSIONS_OVERFLOW || e.key?.startsWith(`${STORAGE_KEY_AI_SESSIONS_OVERFLOW}_`)
|
||||
? STORAGE_KEY_AI_SESSIONS : e.key;
|
||||
switch (key) {
|
||||
case STORAGE_KEY_AI_PROVIDERS: {
|
||||
const parsed = localStorageAdapter.read<ProviderConfig[]>(STORAGE_KEY_AI_PROVIDERS);
|
||||
if (parsed != null && !Array.isArray(parsed)) {
|
||||
@@ -556,7 +651,7 @@ export function useAIState() {
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_SESSIONS: {
|
||||
const nextSessions = localStorageAdapter.read<AISession[]>(STORAGE_KEY_AI_SESSIONS) ?? [];
|
||||
const nextSessions = readSessionsFromStorage();
|
||||
setLatestAISessionsSnapshot(nextSessions);
|
||||
setSessionsRaw(nextSessions);
|
||||
break;
|
||||
@@ -598,8 +693,7 @@ export function useAIState() {
|
||||
case STORAGE_KEY_AI_SESSIONS:
|
||||
setSessionsRaw(
|
||||
latestAISessionsSnapshot
|
||||
?? localStorageAdapter.read<AISession[]>(STORAGE_KEY_AI_SESSIONS)
|
||||
?? [],
|
||||
?? readSessionsFromStorage(),
|
||||
);
|
||||
return;
|
||||
case STORAGE_KEY_AI_ACTIVE_SESSION_MAP:
|
||||
@@ -651,8 +745,8 @@ export function useAIState() {
|
||||
}, []);
|
||||
|
||||
// ── Session CRUD ──
|
||||
const persistSessions = useCallback((next: AISession[]) => {
|
||||
writeSessionsForStorage(next);
|
||||
const persistSessions = useCallback((next: AISession[], deletedSessionIds?: readonly string[]) => {
|
||||
writeSessionsForStorage(next, { deletedSessionIds });
|
||||
}, []);
|
||||
|
||||
// Debounced version of persistSessions for high-frequency updates (e.g. streaming)
|
||||
@@ -797,7 +891,7 @@ export function useAIState() {
|
||||
setSessionsRaw(prev => {
|
||||
const next = prev.filter(s => s.id !== sessionId);
|
||||
setLatestAISessionsSnapshot(next);
|
||||
persistSessions(next);
|
||||
persistSessions(next, [sessionId]);
|
||||
return next;
|
||||
});
|
||||
if (scopeKey) {
|
||||
@@ -841,7 +935,7 @@ export function useAIState() {
|
||||
return !(s.scope.type === scopeType && s.scope.targetId === targetId);
|
||||
});
|
||||
setLatestAISessionsSnapshot(next);
|
||||
persistSessions(next);
|
||||
persistSessions(next, removedSessionIds);
|
||||
return next;
|
||||
});
|
||||
const scopeKey = `${scopeType}:${targetId}`;
|
||||
@@ -866,6 +960,102 @@ export function useAIState() {
|
||||
});
|
||||
}, [persistSessions]);
|
||||
|
||||
// Issue #4015 R2: rebind a dangling chat to the panel's current scope.
|
||||
// Rewrites `scope`, clears the dangling marker and makes the chat the
|
||||
// active session of its new scope so it shows in the scoped history again.
|
||||
const rebindSessionScope = useCallback((
|
||||
sessionId: string,
|
||||
scope: { type: 'terminal' | 'workspace'; targetId: string; hostIds?: string[] },
|
||||
) => {
|
||||
const scopeKey = `${scope.type}:${scope.targetId}`;
|
||||
setSessionsRaw(prev => {
|
||||
const next = prev.map(s => {
|
||||
if (s.id !== sessionId) return s;
|
||||
const { scopeDangling: _cleared, ...rest } = s;
|
||||
// Replace scope entirely (including hostIds) so history matching follows
|
||||
// the destination terminal/workspace rather than the chat's old host.
|
||||
const nextScope: AISession['scope'] = {
|
||||
type: scope.type,
|
||||
targetId: scope.targetId,
|
||||
};
|
||||
if (scope.hostIds && scope.hostIds.length > 0) {
|
||||
nextScope.hostIds = [...scope.hostIds];
|
||||
}
|
||||
return {
|
||||
...rest,
|
||||
scope: nextScope,
|
||||
updatedAt: Date.now(),
|
||||
} as AISession;
|
||||
});
|
||||
setLatestAISessionsSnapshot(next);
|
||||
persistSessions(next);
|
||||
return next;
|
||||
});
|
||||
// Drop stale pointers that still reference this chat under its previous
|
||||
// scope key, then restore the active pointer for the new scope.
|
||||
// Compute + persist inside the updater so a deferred React setState still
|
||||
// writes the cleaned map (outer capture would stay null and skip persist).
|
||||
setActiveSessionIdMapRaw(prev => {
|
||||
const next = rebindActiveSessionMap(prev, sessionId, scopeKey);
|
||||
setLatestAIActiveSessionMapSnapshot(next);
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_ACTIVE_SESSION_MAP, next);
|
||||
emitAIStateChanged(STORAGE_KEY_AI_ACTIVE_SESSION_MAP);
|
||||
return next;
|
||||
});
|
||||
// Open the rebound chat in this panel; active-map alone loses to an
|
||||
// explicit draft/session panelView that still points elsewhere.
|
||||
setPanelViewByScope((prev) => setSessionView(prev, scopeKey, sessionId));
|
||||
}, [persistSessions, setPanelViewByScope]);
|
||||
|
||||
// Manual durability escape hatch (issue #4015 follow-up): export the
|
||||
// current store to a user-chosen JSON file, or import one back in.
|
||||
// Import is an explicit action, so it may overwrite the live store.
|
||||
const exportSessionsBackup = useCallback(async (): Promise<string | null> => {
|
||||
const bridge = getAIBridge();
|
||||
if (!bridge?.aiSessionsBackupExport) return null;
|
||||
const result = await bridge.aiSessionsBackupExport({
|
||||
json: JSON.stringify(sessionsRef.current),
|
||||
});
|
||||
return result?.success ? (result.filePath ?? '') : null;
|
||||
}, []);
|
||||
|
||||
const importSessionsBackup = useCallback(async (): Promise<number> => {
|
||||
const bridge = getAIBridge();
|
||||
if (!bridge?.aiSessionsBackupImport) return 0;
|
||||
const result = await bridge.aiSessionsBackupImport();
|
||||
if (!result?.success || !result.json) return 0;
|
||||
const imported = parseBackupSessions(result.json);
|
||||
if (!imported || imported.length === 0) return 0;
|
||||
// Merge synchronously against the live ref so orphan cleanup sees the
|
||||
// imported chats even if React would defer a setState updater.
|
||||
const syncEnabled = !!localStorageAdapter.read<{ enabled?: boolean }>(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS)?.enabled;
|
||||
const next = prepareRestoredSessions(mergeImportedSessions(sessionsRef.current, imported), syncEnabled);
|
||||
if (!writeSessionsForStorage(next)) return 0;
|
||||
// Local readback can omit disk-only overflow chats. Keep the complete
|
||||
// prepared history live so cleanup and later writes retain those chats.
|
||||
const importedIds = new Set(imported.map(session => session.id));
|
||||
sessionsRef.current = next;
|
||||
setLatestAISessionsSnapshot(next);
|
||||
setSessionsRaw(next);
|
||||
emitAIStateChanged(STORAGE_KEY_AI_SESSIONS);
|
||||
// Import does not change live terminals/workspaces, so the orphan-cleanup
|
||||
// effect will not run. Reuse the last known live target set (empty is
|
||||
// valid: nothing live) to mark chats bound to missing scopes as dangling
|
||||
// so /chats can offer /rebind.
|
||||
cleanupOrphanedAISessions(latestAIActiveTargetIdsSnapshot);
|
||||
const nextSessions =
|
||||
latestAISessionsSnapshot
|
||||
?? next;
|
||||
sessionsRef.current = nextSessions;
|
||||
setSessionsRaw(nextSessions);
|
||||
setActiveSessionIdMapRaw(
|
||||
latestAIActiveSessionMapSnapshot
|
||||
?? localStorageAdapter.read<Record<string, string | null>>(STORAGE_KEY_AI_ACTIVE_SESSION_MAP)
|
||||
?? {},
|
||||
);
|
||||
return nextSessions.filter(session => importedIds.has(session.id)).length;
|
||||
}, []);
|
||||
|
||||
const updateSessionExternalSessionId = useCallback((sessionId: string, externalSessionId: string | undefined) => {
|
||||
setSessionsRaw(prev => {
|
||||
const next = prev.map(s => (
|
||||
@@ -879,16 +1069,17 @@ export function useAIState() {
|
||||
});
|
||||
}, [debouncedPersistSessions]);
|
||||
|
||||
// Maximum messages per session to prevent unbounded memory growth
|
||||
// Local-only retention. Synced history must match the full-history storage policy.
|
||||
const MAX_MESSAGES_PER_SESSION = 500;
|
||||
|
||||
const addMessageToSession = useCallback((sessionId: string, message: ChatMessage) => {
|
||||
const syncEnabled = localStorageAdapter.read<{ enabled?: boolean }>(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS)?.enabled === true;
|
||||
setSessionsRaw(prev => {
|
||||
const next = prev.map(s => {
|
||||
if (s.id !== sessionId) return s;
|
||||
let msgs = [...s.messages, message];
|
||||
// Trim oldest messages if exceeding limit (keep system messages)
|
||||
if (msgs.length > MAX_MESSAGES_PER_SESSION) {
|
||||
// Dropping synced prefixes makes the next cloud merge add them back.
|
||||
if (!syncEnabled && msgs.length > MAX_MESSAGES_PER_SESSION) {
|
||||
const systemMsgs = msgs.filter(m => m.role === 'system');
|
||||
const nonSystemMsgs = msgs.filter(m => m.role !== 'system');
|
||||
const dropped = nonSystemMsgs.length - (MAX_MESSAGES_PER_SESSION - systemMsgs.length);
|
||||
@@ -1134,8 +1325,7 @@ export function useAIState() {
|
||||
|
||||
const nextSessions =
|
||||
latestAISessionsSnapshot
|
||||
?? localStorageAdapter.read<AISession[]>(STORAGE_KEY_AI_SESSIONS)
|
||||
?? [];
|
||||
?? readSessionsFromStorage();
|
||||
sessionsRef.current = nextSessions;
|
||||
setSessionsRaw(nextSessions);
|
||||
setActiveSessionIdMapRaw(
|
||||
@@ -1187,8 +1377,7 @@ export function useAIState() {
|
||||
?? {};
|
||||
const currentSessions =
|
||||
latestAISessionsSnapshot
|
||||
?? localStorageAdapter.read<AISession[]>(STORAGE_KEY_AI_SESSIONS)
|
||||
?? [];
|
||||
?? readSessionsFromStorage();
|
||||
const currentPanelViewByScope = latestAIPanelViewByScopeSnapshot ?? {};
|
||||
const result = handoffDissolvedWorkspaceAIScope({
|
||||
activeSessionIdMap: currentMap,
|
||||
@@ -1233,8 +1422,7 @@ export function useAIState() {
|
||||
?? {};
|
||||
const currentSessions =
|
||||
latestAISessionsSnapshot
|
||||
?? localStorageAdapter.read<AISession[]>(STORAGE_KEY_AI_SESSIONS)
|
||||
?? [];
|
||||
?? readSessionsFromStorage();
|
||||
const result = retargetWorkspaceActiveChatAfterMemberLoss({
|
||||
activeSessionIdMap: currentMap,
|
||||
sessions: currentSessions,
|
||||
@@ -1370,6 +1558,9 @@ export function useAIState() {
|
||||
deleteSession,
|
||||
deleteSessionsByTarget,
|
||||
updateSessionTitle,
|
||||
rebindSessionScope,
|
||||
exportSessionsBackup,
|
||||
importSessionsBackup,
|
||||
updateSessionExternalSessionId,
|
||||
addMessageToSession,
|
||||
updateLastMessage,
|
||||
@@ -1432,6 +1623,9 @@ export function useAIState() {
|
||||
deleteSession,
|
||||
deleteSessionsByTarget,
|
||||
updateSessionTitle,
|
||||
rebindSessionScope,
|
||||
exportSessionsBackup,
|
||||
importSessionsBackup,
|
||||
updateSessionExternalSessionId,
|
||||
addMessageToSession,
|
||||
updateLastMessage,
|
||||
|
||||
@@ -11,6 +11,10 @@ import {
|
||||
} from "./useActiveChromeTheme.ts";
|
||||
import { TERMINAL_THEMES } from "../../infrastructure/config/terminalThemes.ts";
|
||||
import { readFileSync } from "node:fs";
|
||||
import {
|
||||
getSettingsChromeSnapshot,
|
||||
publishSettingsChromeSnapshot,
|
||||
} from "./settingsChromeStore.ts";
|
||||
|
||||
function createInlineStyle() {
|
||||
const values = new Map<string, string>();
|
||||
@@ -98,6 +102,60 @@ test("syncActiveChromeTheme skips surface refresh when the active theme fingerpr
|
||||
}
|
||||
});
|
||||
|
||||
for (const preference of ["system", "light", "dark"] as const) {
|
||||
for (const chromeType of ["light", "dark"] as const) {
|
||||
test(`syncActiveChromeTheme uses ${preference === "system" ? "system" : chromeType} native theme for ${preference} preference and ${chromeType} chrome`, () => {
|
||||
const globals = globalThis as typeof globalThis & { document?: Document; window?: Window };
|
||||
const originalDocument = globals.document;
|
||||
const originalWindow = globals.window;
|
||||
const originalSnapshot = getSettingsChromeSnapshot();
|
||||
const theme = TERMINAL_THEMES.find((candidate) => candidate.type === chromeType);
|
||||
assert.ok(theme);
|
||||
const themeCalls: string[] = [];
|
||||
const backgroundCalls: string[] = [];
|
||||
globals.document = {
|
||||
documentElement: {
|
||||
dataset: {},
|
||||
classList: { remove: () => {}, add: () => {} },
|
||||
removeAttribute: () => {},
|
||||
},
|
||||
getElementById: () => null,
|
||||
createElement: () => ({}),
|
||||
head: { appendChild: () => {} },
|
||||
querySelector: () => null,
|
||||
} as unknown as Document;
|
||||
globals.window = {
|
||||
netcatty: {
|
||||
setTheme: (value: string) => themeCalls.push(value),
|
||||
setBackgroundColor: (value: string) => backgroundCalls.push(value),
|
||||
},
|
||||
} as unknown as Window & typeof globalThis;
|
||||
|
||||
try {
|
||||
publishSettingsChromeSnapshot({ ...originalSnapshot, theme: preference });
|
||||
syncActiveChromeTheme(theme, () => {
|
||||
throw new Error("app theme should not be restored for an active chrome theme");
|
||||
});
|
||||
|
||||
assert.deepEqual(themeCalls, [preference === "system" ? "system" : chromeType]);
|
||||
assert.deepEqual(backgroundCalls, [theme.colors.background]);
|
||||
} finally {
|
||||
publishSettingsChromeSnapshot(originalSnapshot);
|
||||
if (originalDocument) {
|
||||
globals.document = originalDocument;
|
||||
} else {
|
||||
delete globals.document;
|
||||
}
|
||||
if (originalWindow) {
|
||||
globals.window = originalWindow;
|
||||
} else {
|
||||
delete globals.window;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test("active chrome theme foreground uses contrast calculation", () => {
|
||||
const source = readFileSync(new URL("./useActiveChromeTheme.ts", import.meta.url), "utf8");
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { pluginThemeRegistry } from '../../infrastructure/config/pluginThemeRegistry';
|
||||
import { usePluginThemeRevision } from './usePluginThemeRuntime';
|
||||
import { useSettingsChromeStore } from './settingsChromeStore';
|
||||
import { getSettingsChromeSnapshot, useSettingsChromeStore } from './settingsChromeStore';
|
||||
import { useLayoutEffect, useRef } from "react";
|
||||
import type { TerminalTheme } from "../../domain/models";
|
||||
import {
|
||||
@@ -239,7 +239,9 @@ function applyActiveChromeTheme(theme: TerminalTheme) {
|
||||
function refreshActiveChromeThemeSurfaces(theme: TerminalTheme) {
|
||||
const targetClass = theme.type === "dark" ? "dark" : "light";
|
||||
if (typeof window !== "undefined") {
|
||||
netcattyBridge.get()?.setTheme?.(targetClass);
|
||||
// Preserve OS preference events instead of locking nativeTheme to the chrome type.
|
||||
const themeSource = getSettingsChromeSnapshot().theme === "system" ? "system" : targetClass;
|
||||
netcattyBridge.get()?.setTheme?.(themeSource);
|
||||
netcattyBridge.get()?.setBackgroundColor?.(theme.colors.background);
|
||||
}
|
||||
applyTopTabsChromeThemeVars(theme);
|
||||
|
||||
@@ -92,3 +92,21 @@ test("selectPreferredRuntimeAppLockState prefers initialized state when versions
|
||||
current,
|
||||
);
|
||||
});
|
||||
|
||||
test("selectPreferredRuntimeAppLockState keeps the current object when a resync changes nothing", () => {
|
||||
const current = normalizeRuntimeAppLockState({
|
||||
initialized: true,
|
||||
locked: false,
|
||||
reason: null,
|
||||
version: 4,
|
||||
lastUnlockedAt: 1000,
|
||||
lastActivityAt: 2000,
|
||||
});
|
||||
const resynced = normalizeRuntimeAppLockState({ ...current });
|
||||
assert.notEqual(resynced, current);
|
||||
// Window focus resyncs must not hand React a new state object.
|
||||
assert.equal(selectPreferredRuntimeAppLockState(current, resynced), current);
|
||||
|
||||
const changed = normalizeRuntimeAppLockState({ ...current, locked: true, reason: "idle" });
|
||||
assert.equal(selectPreferredRuntimeAppLockState(current, changed), changed);
|
||||
});
|
||||
@@ -43,7 +43,20 @@ export function selectPreferredRuntimeAppLockState(
|
||||
if (incoming.version < current.version) return current;
|
||||
if (incoming.initialized && !current.initialized) return incoming;
|
||||
if (!incoming.initialized && current.initialized) return current;
|
||||
return incoming;
|
||||
// Every window focus/visibility change resyncs; keep the current object when
|
||||
// nothing changed so the gate (and the provider tree under it) does not
|
||||
// re-render.
|
||||
return isSameRuntimeAppLockState(current, incoming) ? current : incoming;
|
||||
}
|
||||
|
||||
function isSameRuntimeAppLockState(left: RuntimeAppLockState, right: RuntimeAppLockState): boolean {
|
||||
return left.initialized === right.initialized
|
||||
&& left.locked === right.locked
|
||||
&& left.reason === right.reason
|
||||
&& left.version === right.version
|
||||
&& left.lastLockedAt === right.lastLockedAt
|
||||
&& left.lastUnlockedAt === right.lastUnlockedAt
|
||||
&& left.lastActivityAt === right.lastActivityAt;
|
||||
}
|
||||
|
||||
export function useAppLockRuntime(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
|
||||
import {
|
||||
normalizeAppLockSettings,
|
||||
@@ -131,6 +131,8 @@ export function createOptimisticUnlockedRuntimeState(
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
export const APP_LOCK_ACTIVITY_REPORT_INTERVAL_MS = 1000;
|
||||
export function useAppLockState(settings: AppLockSettings) {
|
||||
const normalizedSettings = useMemo(() => normalizeAppLockSettings(settings), [settings]);
|
||||
const systemUnlockRefreshKey = `${normalizedSettings.enabled}:${normalizedSettings.systemUnlockEnabled}:${Boolean(normalizedSettings.passwordVerifier)}`;
|
||||
@@ -160,8 +162,14 @@ export function useAppLockState(settings: AppLockSettings) {
|
||||
void bridge?.setAppLockRuntimeLocked?.(reason);
|
||||
}, [bridge, normalizedSettings]);
|
||||
|
||||
// Activity only resets a minutes-long idle timer; one report per second is
|
||||
// enough instead of an IPC per keystroke, wheel tick and pointer event.
|
||||
const lastActivityReportAtRef = useRef(0);
|
||||
const recordActivity = useCallback(() => {
|
||||
if (effectiveRuntimeState.locked) return;
|
||||
const now = Date.now();
|
||||
if (now - lastActivityReportAtRef.current < APP_LOCK_ACTIVITY_REPORT_INTERVAL_MS) return;
|
||||
lastActivityReportAtRef.current = now;
|
||||
void bridge?.reportAppLockActivity?.();
|
||||
}, [bridge, effectiveRuntimeState.locked]);
|
||||
|
||||
@@ -249,7 +257,9 @@ export function useAppLockState(settings: AppLockSettings) {
|
||||
void refreshSystemUnlockStatus();
|
||||
}, [refreshSystemUnlockStatus, systemUnlockRefreshKey]);
|
||||
|
||||
return {
|
||||
// Stable identity: AppLockGate passes this to <App>, whose provider tree
|
||||
// re-renders whenever it changes.
|
||||
return useMemo(() => ({
|
||||
initialized: effectiveRuntimeState.initialized,
|
||||
locked: effectiveRuntimeState.locked,
|
||||
lockReason: effectiveRuntimeState.reason,
|
||||
@@ -261,5 +271,17 @@ export function useAppLockState(settings: AppLockSettings) {
|
||||
reset,
|
||||
recordActivity,
|
||||
resync: refreshRuntimeState,
|
||||
};
|
||||
}), [
|
||||
effectiveRuntimeState.initialized,
|
||||
effectiveRuntimeState.locked,
|
||||
effectiveRuntimeState.reason,
|
||||
lockNow,
|
||||
unlock,
|
||||
unlockWithSystemAuth,
|
||||
systemUnlockStatus,
|
||||
refreshSystemUnlockStatus,
|
||||
reset,
|
||||
recordActivity,
|
||||
refreshRuntimeState,
|
||||
]);
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { PluginViewLifecycleController, type HostedPluginViewState } from './pluginViewLifecycle';
|
||||
import { resolvePluginViewWindowScope } from './pluginViewScopes';
|
||||
import { isPluginViewOccluded } from './pluginViewOcclusion';
|
||||
import type { UsePluginContributionsResult } from './usePluginContributions';
|
||||
|
||||
type ViewAdapter = Pick<UsePluginContributionsResult, 'openView' | 'closeView' | 'focusView' | 'setViewBounds' | 'setViewVisibility' | 'onViewClosed' | 'onViewFocused'>;
|
||||
|
||||
/** Host-owned mounting only. No plugin router, DOM, session or vault data API. */
|
||||
export function useEmbeddedPluginView({ viewId, version, slot, active, context, adapter, subscribeHidden, unavailable, focused, focusOnReveal = false }: {
|
||||
viewId: string;
|
||||
version: string;
|
||||
slot: string;
|
||||
active: boolean;
|
||||
context: Record<string, unknown>;
|
||||
adapter: ViewAdapter;
|
||||
subscribeHidden(listener: () => void): () => void;
|
||||
unavailable(): void;
|
||||
focused?(): void;
|
||||
focusOnReveal?: boolean;
|
||||
}) {
|
||||
const mountRef = useRef<HTMLDivElement>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const adapterRef = useRef(adapter);
|
||||
const unavailableRef = useRef(unavailable);
|
||||
const focusedRef = useRef(focused);
|
||||
const revealFocusRef = useRef(focusOnReveal);
|
||||
const requestFocusRef = useRef<() => void>(() => {});
|
||||
revealFocusRef.current = focusOnReveal;
|
||||
focusedRef.current = focused;
|
||||
adapterRef.current = adapter;
|
||||
unavailableRef.current = unavailable;
|
||||
useEffect(() => {
|
||||
const mount = mountRef.current;
|
||||
if (!active || !mount) return;
|
||||
let cancelled = false;
|
||||
const lifecycle = new PluginViewLifecycleController<HostedPluginViewState>();
|
||||
const instanceId = crypto.randomUUID();
|
||||
const scopeId = resolvePluginViewWindowScope({ pathname: window.location.pathname,
|
||||
search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` });
|
||||
const { openView, closeView, focusView, setViewBounds, setViewVisibility, onViewClosed, onViewFocused } = adapterRef.current;
|
||||
const close = () => {
|
||||
if (cancelled) return;
|
||||
cancelled = true;
|
||||
lifecycle.markViewClosed(viewId);
|
||||
void closeView(instanceId).catch(() => {});
|
||||
};
|
||||
const failCurrent = () => {
|
||||
if (cancelled) return;
|
||||
close();
|
||||
unavailableRef.current();
|
||||
};
|
||||
const unsubscribe = onViewClosed((event) => {
|
||||
lifecycle.handleHostClose(event.instanceId);
|
||||
if (event.instanceId === instanceId && !cancelled) {
|
||||
close();
|
||||
unavailableRef.current();
|
||||
}
|
||||
});
|
||||
const stopOnHide = subscribeHidden(close);
|
||||
const stopOnFocus = onViewFocused((event) => {
|
||||
if (!cancelled && event.instanceId === instanceId) focusedRef.current?.();
|
||||
});
|
||||
const bounds = () => {
|
||||
const rect = mount.getBoundingClientRect();
|
||||
return { x: Math.round(rect.x), y: Math.round(rect.y), width: Math.max(1, Math.round(rect.width)), height: Math.max(1, Math.round(rect.height)) };
|
||||
};
|
||||
let opened = false;
|
||||
let lastBounds = '';
|
||||
let visible = false;
|
||||
const focus = () => {
|
||||
if (!cancelled && opened && visible && revealFocusRef.current && !isPluginViewOccluded(mount)) void focusView(instanceId).catch(() => {});
|
||||
};
|
||||
requestFocusRef.current = focus;
|
||||
const updateVisibility = () => {
|
||||
if (!opened || cancelled) return;
|
||||
const rect = mount.getBoundingClientRect();
|
||||
const next = rect.width > 0 && rect.height > 0 && !isPluginViewOccluded(mount);
|
||||
if (visible === next) return;
|
||||
visible = next;
|
||||
void setViewVisibility(instanceId, next).then(() => { if (next) focus(); }).catch(failCurrent);
|
||||
};
|
||||
const resize = () => {
|
||||
if (opened && !cancelled) {
|
||||
const next = bounds();
|
||||
const key = JSON.stringify(next);
|
||||
if (key !== lastBounds) { lastBounds = key; void setViewBounds(instanceId, next).catch(failCurrent); }
|
||||
}
|
||||
updateVisibility();
|
||||
};
|
||||
const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(resize);
|
||||
observer?.observe(mount);
|
||||
const mutations = new MutationObserver(resize);
|
||||
mutations.observe(document.body, { childList: true, subtree: true, attributes: true,
|
||||
attributeFilter: ['class', 'style', 'hidden', 'inert', 'role', 'aria-modal', 'aria-hidden', 'data-state', 'data-app-lock-overlay', 'data-radix-popper-content-wrapper', 'data-native-view-occluder'] });
|
||||
window.addEventListener('resize', resize);
|
||||
document.addEventListener('scroll', resize, true);
|
||||
setLoading(true);
|
||||
const opening = lifecycle.beginOpen({ viewKey: viewId });
|
||||
void openView({ viewId, instanceId, scopeId, bounds: bounds(), context }).then(async (result) => {
|
||||
if (cancelled || lifecycle.shouldCloseOpen(opening) || lifecycle.consumeHostClose(result.instanceId)) {
|
||||
await closeView(result.instanceId);
|
||||
return;
|
||||
}
|
||||
opened = true;
|
||||
lifecycle.setCurrent({ id: result.instanceId, viewId, scopeId, retainContextWhenHidden: false });
|
||||
resize();
|
||||
setLoading(false);
|
||||
}).catch(() => {
|
||||
if (!cancelled) { close(); unavailableRef.current(); }
|
||||
}).finally(() => lifecycle.finishOpen({ token: opening, viewKey: viewId }));
|
||||
return () => {
|
||||
close(); unsubscribe(); stopOnHide(); stopOnFocus(); observer?.disconnect(); mutations.disconnect();
|
||||
window.removeEventListener('resize', resize); document.removeEventListener('scroll', resize, true);
|
||||
};
|
||||
}, [active, context, slot, subscribeHidden, version, viewId]);
|
||||
useEffect(() => { if (focusOnReveal) requestFocusRef.current(); }, [focusOnReveal]);
|
||||
return { mountRef, loading };
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
import { resolvePluginViewWindowScope } from './pluginViewScopes';
|
||||
import { pluginViewSessions, type PluginViewSnapshot } from './pluginViewSession';
|
||||
import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
|
||||
|
||||
const initial = (): PluginViewSnapshot => ({ tree: { children: [] }, css: '', loading: true, error: false, settled: true });
|
||||
export function useHostDrawnPluginView({ viewId, version, slot, active, context, subscribeHidden, unavailable }: {
|
||||
viewId: string; version: string; slot: string; active: boolean; context: Record<string, unknown>;
|
||||
subscribeHidden(listener: () => void): () => void; unavailable(): void;
|
||||
}) {
|
||||
const contextKey = JSON.stringify(context);
|
||||
const key = JSON.stringify([viewId, version, slot, contextKey]);
|
||||
const [state, setState] = useState<{ key: string; snapshot: PluginViewSnapshot }>({ key: '', snapshot: initial() });
|
||||
const [hidden, setHidden] = useState(false);
|
||||
const unavailableRef = useRef(unavailable); unavailableRef.current = unavailable;
|
||||
const sessionRef = useRef<{ key: string; image(path: string): Promise<string>; send(event: HostDrawnViewEvent): void } | null>(null);
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge) { unavailableRef.current(); return; }
|
||||
const scopeId = resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` });
|
||||
try {
|
||||
const session = pluginViewSessions.acquire(JSON.stringify([scopeId, key]), bridge, { viewId, scopeId, context: JSON.parse(contextKey) });
|
||||
const update = () => { const snapshot = session.getSnapshot(); setState({ key, snapshot }); if (snapshot.error) unavailableRef.current(); };
|
||||
const stop = session.subscribe(update); update(); setHidden(false);
|
||||
sessionRef.current = { key, send: session.send, image: session.image };
|
||||
const stopHidden = subscribeHidden(() => { sessionRef.current = null; setHidden(true); });
|
||||
return () => { sessionRef.current = null; stopHidden(); stop(); session.release(); };
|
||||
} catch { unavailableRef.current(); }
|
||||
}, [active, contextKey, key, slot, subscribeHidden, viewId]);
|
||||
const loadImage = useCallback((path: string) => {
|
||||
const session = sessionRef.current;
|
||||
return active && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable'));
|
||||
}, [active, key]);
|
||||
const sendEvent = useCallback((event: HostDrawnViewEvent) => {
|
||||
const session = sessionRef.current; if (active && session?.key === key) session.send(event);
|
||||
}, [active, key]);
|
||||
// A newly selected plugin must never receive values from the previous tree,
|
||||
// even during the render before effect cleanup and the next activation.
|
||||
return { ...(state.key === key ? state.snapshot : initial()), visible: active && !hidden, loadImage, sendEvent };
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useState } from "react";
|
||||
import { buildMonitorDiskListLayout, type MonitorDiskListStats } from "../../domain/monitorDisks";
|
||||
|
||||
/** Volatile per-host disclosure preference; capacity alerts always force it open. */
|
||||
export function useMonitorDiskGroups() {
|
||||
const [expandedHosts, setExpandedHosts] = useState<ReadonlySet<string>>(() => new Set());
|
||||
return {
|
||||
layoutFor: (hostId: string, stats?: MonitorDiskListStats | null) =>
|
||||
buildMonitorDiskListLayout(stats, expandedHosts.has(hostId)),
|
||||
toggle: (hostId: string) => setExpandedHosts(previous => {
|
||||
const next = new Set(previous);
|
||||
if (next.has(hostId)) next.delete(hostId);
|
||||
else next.add(hostId);
|
||||
return next;
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import { useMonitorPanels } from "./monitorPanelsStorage";
|
||||
import {
|
||||
monitorActions,
|
||||
getMonitorHistoryCursor,
|
||||
isIdleMonitorSnapshot,
|
||||
publishMonitorSnapshot,
|
||||
publishMonitorUnavailable,
|
||||
} from "./monitorRuntimeStore";
|
||||
@@ -157,16 +158,24 @@ export function useMonitorRuntime() {
|
||||
isInitialized,
|
||||
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.
|
||||
const hasRunningPanels = running.size > 0;
|
||||
useEffect(() => {
|
||||
const bridge = netcattyBridge.get();
|
||||
let disposed = false;
|
||||
let pending = false;
|
||||
let remoteRunning = false;
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
const poll = async () => {
|
||||
if (pending || !bridge?.monitorSnapshot) return;
|
||||
pending = true;
|
||||
try {
|
||||
const snapshot = await bridge.monitorSnapshot(getMonitorHistoryCursor());
|
||||
if (disposed) return;
|
||||
remoteRunning = !isIdleMonitorSnapshot(snapshot);
|
||||
if (
|
||||
(epoch.current !== null && epoch.current !== snapshot.epoch) ||
|
||||
(runtimeId.current !== null &&
|
||||
@@ -186,13 +195,16 @@ export function useMonitorRuntime() {
|
||||
pending = false;
|
||||
}
|
||||
};
|
||||
void poll();
|
||||
const timer = setInterval(() => {
|
||||
void poll();
|
||||
}, 1000);
|
||||
const schedule = () => {
|
||||
if (disposed) return;
|
||||
timer = setTimeout(() => {
|
||||
void poll().finally(schedule);
|
||||
}, hasRunningPanels || remoteRunning ? 1000 : 10_000);
|
||||
};
|
||||
void poll().finally(schedule);
|
||||
return () => {
|
||||
disposed = true;
|
||||
clearInterval(timer);
|
||||
if (timer) clearTimeout(timer);
|
||||
};
|
||||
}, []);
|
||||
}, [hasRunningPanels]);
|
||||
}
|
||||
@@ -3,8 +3,7 @@ import type { TerminalSession, Workspace } from '../../domain/models';
|
||||
import { getNotesSnapshot } from './notesStore';
|
||||
import { useActiveTabId } from './activeTabStore';
|
||||
import { getAppAppLockRuntime } from './appRuntimeBridge';
|
||||
import { createTrustedPluginAIHostRuntime } from '../../infrastructure/ai/plugin/trustedHostRuntime';
|
||||
import { getConfiguredPluginModel, prepareConfiguredPluginModel } from '../../infrastructure/ai/plugin/configuredModel';
|
||||
import type { createTrustedPluginAIHostRuntime } from '../../infrastructure/ai/plugin/trustedHostRuntime';
|
||||
import { buildSelectedPluginSources } from '../../infrastructure/ai/plugin/selectedSources';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
|
||||
@@ -27,30 +26,47 @@ export function usePluginAIContextHost({ sessions, workspaces }: { sessions: Ter
|
||||
let mounted = true;
|
||||
let chooser: { runtimeId: string; cancel: () => void } | null = null;
|
||||
const requests = new Map<string, { runtimeId: string; controller: AbortController }>();
|
||||
const runtime = createTrustedPluginAIHostRuntime({
|
||||
getModel: getConfiguredPluginModel,
|
||||
prepareModel: prepareConfiguredPluginModel,
|
||||
isActive: () => mounted && document.visibilityState === 'visible' && getAppAppLockRuntime()?.locked === false,
|
||||
chooseSelected: (signal, runtimeId) => new Promise((resolve, reject) => {
|
||||
if (chooser) { reject(Error('A host selection is already pending')); return; }
|
||||
const finish = (id: string | null) => {
|
||||
if (chooser?.cancel !== cancel) return;
|
||||
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 })));
|
||||
};
|
||||
const cancel = () => finish(null);
|
||||
chooser = { runtimeId, cancel };
|
||||
signal.addEventListener('abort', cancel, { once: true });
|
||||
setNoteId('');
|
||||
// This inventory stays inside trusted host UI. The plugin receives
|
||||
// summaries only for the Note chosen here and current selected scopes.
|
||||
setNoteChoices(getNotesSnapshot().notes.map((note) => ({ id: note.id, title: note.title })));
|
||||
setChoice({ confirm: (id) => finish(id), cancel });
|
||||
if (signal.aborted) cancel();
|
||||
}),
|
||||
// The runtime pulls in the AI SDK providers (~1 MB with the Catty
|
||||
// harness). This host is mounted for every main window, so create it on
|
||||
// the first plugin AI request instead of at startup.
|
||||
type HostRuntime = ReturnType<typeof createTrustedPluginAIHostRuntime>;
|
||||
let runtime: HostRuntime | null = null;
|
||||
let runtimeLoading: Promise<HostRuntime> | null = null;
|
||||
const withLoadedRuntime = (apply: (loaded: HostRuntime) => void) => {
|
||||
if (runtime) apply(runtime);
|
||||
else void runtimeLoading?.then(apply, () => {});
|
||||
};
|
||||
const ensureRuntime = () => runtimeLoading ??= Promise.all([
|
||||
import('../../infrastructure/ai/plugin/trustedHostRuntime'),
|
||||
import('../../infrastructure/ai/plugin/configuredModel'),
|
||||
]).then(([{ createTrustedPluginAIHostRuntime: createRuntime }, { getConfiguredPluginModel, prepareConfiguredPluginModel }]) => {
|
||||
runtime = createRuntime({
|
||||
getModel: getConfiguredPluginModel,
|
||||
prepareModel: prepareConfiguredPluginModel,
|
||||
isActive: () => mounted && document.visibilityState === 'visible' && getAppAppLockRuntime()?.locked === false,
|
||||
chooseSelected: (signal, runtimeId) => new Promise((resolve, reject) => {
|
||||
if (chooser) { reject(Error('A host selection is already pending')); return; }
|
||||
const finish = (id: string | null) => {
|
||||
if (chooser?.cancel !== cancel) return;
|
||||
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 })));
|
||||
};
|
||||
const cancel = () => finish(null);
|
||||
chooser = { runtimeId, cancel };
|
||||
signal.addEventListener('abort', cancel, { once: true });
|
||||
setNoteId('');
|
||||
// This inventory stays inside trusted host UI. The plugin receives
|
||||
// summaries only for the Note chosen here and current selected scopes.
|
||||
setNoteChoices(getNotesSnapshot().notes.map((note) => ({ id: note.id, title: note.title })));
|
||||
setChoice({ confirm: (id) => finish(id), cancel });
|
||||
if (signal.aborted) cancel();
|
||||
}),
|
||||
});
|
||||
if (!mounted) runtime.shutdown();
|
||||
return runtime;
|
||||
});
|
||||
const unsubscribe = bridge.onPluginAIHostRequest((request) => {
|
||||
if (request.kind === 'request.cancel') {
|
||||
@@ -60,24 +76,28 @@ export function usePluginAIContextHost({ sessions, workspaces }: { sessions: Ter
|
||||
if (request.kind === 'runtime.release') {
|
||||
for (const pending of requests.values()) if (pending.runtimeId === request.runtimeId) pending.controller.abort();
|
||||
if (chooser?.runtimeId === request.runtimeId) chooser.cancel();
|
||||
runtime.releaseRuntime(request.runtimeId);
|
||||
withLoadedRuntime((loaded) => loaded.releaseRuntime(request.runtimeId));
|
||||
return;
|
||||
}
|
||||
if (requests.has(request.requestId) || requests.size >= 64) return;
|
||||
const controller = new AbortController();
|
||||
requests.set(request.requestId, { runtimeId: request.runtimeId, controller });
|
||||
void runtime.handle(request.kind, request.payload, request.runtimeId, controller.signal).then(
|
||||
void ensureRuntime().then((loaded) => {
|
||||
// Loading is async: re-check that the host and request are still live.
|
||||
if (!mounted || controller.signal.aborted) throw new Error('Plugin AI request is no longer active');
|
||||
return loaded.handle(request.kind, request.payload, request.runtimeId, controller.signal);
|
||||
}).then(
|
||||
(result) => bridge.respondPluginAIHost({ requestId: request.requestId, actionToken: request.actionToken, result }),
|
||||
() => bridge.respondPluginAIHost({ requestId: request.requestId, actionToken: request.actionToken, error: true }),
|
||||
).catch(() => {}).finally(() => requests.delete(request.requestId));
|
||||
});
|
||||
const pageHide = () => { runtime.shutdown(); for (const pending of requests.values()) pending.controller.abort(); };
|
||||
const pageHide = () => { withLoadedRuntime((loaded) => loaded.shutdown()); for (const pending of requests.values()) pending.controller.abort(); };
|
||||
window.addEventListener('pagehide', pageHide);
|
||||
void bridge.setPluginAIHostReady(true).catch(() => {});
|
||||
return () => {
|
||||
mounted = false; chooser?.cancel(); unsubscribe(); window.removeEventListener('pagehide', pageHide);
|
||||
for (const pending of requests.values()) pending.controller.abort();
|
||||
requests.clear(); runtime.shutdown();
|
||||
requests.clear(); withLoadedRuntime((loaded) => loaded.shutdown());
|
||||
void bridge.setPluginAIHostReady(false).catch(() => {});
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { TerminalSession } from '../../domain/models';
|
||||
import type { PluginAgentHostTerminal } from '@netcatty/plugin-contract';
|
||||
import { createTrustedPluginAgentRuntime } from '../../infrastructure/ai/pluginAgent/trustedAgentRuntime';
|
||||
import type { createTrustedPluginAgentRuntime } from '../../infrastructure/ai/pluginAgent/trustedAgentRuntime';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
import { getAppAppLockRuntime } from './appRuntimeBridge';
|
||||
import { LOCAL_STORAGE_ADAPTER_CHANGED_EVENT } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
@@ -22,58 +22,78 @@ export function usePluginAgentHost(sessions: TerminalSession[]) {
|
||||
let mounted = true;
|
||||
let chooser: { runtimeId: string; cancel: () => void } | null = null;
|
||||
const requests = new Map<string, { runtimeId: string; controller: AbortController }>();
|
||||
const runtime = createTrustedPluginAgentRuntime({
|
||||
isActive: () => mounted && document.visibilityState === 'visible' && getAppAppLockRuntime()?.locked === false,
|
||||
chooseTargets: (signal, runtimeId) => new Promise((resolve, reject) => {
|
||||
if (chooser) { reject(Error('A target selection is already pending')); return; }
|
||||
const items = latest.current.filter((item) => item.status === 'connected').map((item) => ({
|
||||
sessionId: item.id, hostId: item.hostId, hostname: (item.hostname || '').slice(0, 253),
|
||||
label: (item.customName || item.hostLabel || item.id).slice(0, 160),
|
||||
...(item.protocol ? { protocol: item.protocol } : {}), ...(item.username ? { username: item.username.slice(0, 160) } : {}), connected: true,
|
||||
}));
|
||||
const finish = (ids: string[] | null) => {
|
||||
if (chooser?.cancel !== cancel) return;
|
||||
chooser = null; signal.removeEventListener('abort', cancel); setChoice(null);
|
||||
if (ids === null || signal.aborted || ids.length > 32 || new Set(ids).size !== ids.length) { reject(Error('Target selection cancelled')); return; }
|
||||
const selected = ids.map((id) => items.find((item) => item.sessionId === id));
|
||||
if (selected.some((item) => !item || !latest.current.some((session) => session.id === item.sessionId && session.status === 'connected'))) {
|
||||
reject(Error('Selected terminal is no longer connected')); return;
|
||||
}
|
||||
resolve(selected as PluginAgentHostTerminal[]);
|
||||
};
|
||||
const cancel = () => finish(null);
|
||||
chooser = { runtimeId, cancel }; signal.addEventListener('abort', cancel, { once: true });
|
||||
setChoice({ items, confirm: finish, cancel });
|
||||
if (signal.aborted) cancel();
|
||||
}),
|
||||
});
|
||||
// The agent runtime pulls in the whole Catty harness and AI SDK. This host
|
||||
// is mounted for every main window, so create it on the first plugin agent
|
||||
// request instead of at startup; until then there is nothing to cancel,
|
||||
// release or invalidate.
|
||||
type AgentRuntime = ReturnType<typeof createTrustedPluginAgentRuntime>;
|
||||
let runtime: AgentRuntime | null = null;
|
||||
let runtimeLoading: Promise<AgentRuntime> | null = null;
|
||||
const withLoadedRuntime = (apply: (loaded: AgentRuntime) => void) => {
|
||||
if (runtime) apply(runtime);
|
||||
else void runtimeLoading?.then(apply, () => {});
|
||||
};
|
||||
const ensureRuntime = () => runtimeLoading ??= import('../../infrastructure/ai/pluginAgent/trustedAgentRuntime')
|
||||
.then(({ createTrustedPluginAgentRuntime: createRuntime }) => {
|
||||
runtime = createRuntime({
|
||||
isActive: () => mounted && document.visibilityState === 'visible' && getAppAppLockRuntime()?.locked === false,
|
||||
chooseTargets: (signal, runtimeId) => new Promise((resolve, reject) => {
|
||||
if (chooser) { reject(Error('A target selection is already pending')); return; }
|
||||
const items = latest.current.filter((item) => item.status === 'connected').map((item) => ({
|
||||
sessionId: item.id, hostId: item.hostId, hostname: (item.hostname || '').slice(0, 253),
|
||||
label: (item.customName || item.hostLabel || item.id).slice(0, 160),
|
||||
...(item.protocol ? { protocol: item.protocol } : {}), ...(item.username ? { username: item.username.slice(0, 160) } : {}), connected: true,
|
||||
}));
|
||||
const finish = (ids: string[] | null) => {
|
||||
if (chooser?.cancel !== cancel) return;
|
||||
chooser = null; signal.removeEventListener('abort', cancel); setChoice(null);
|
||||
if (ids === null || signal.aborted || ids.length > 32 || new Set(ids).size !== ids.length) { reject(Error('Target selection cancelled')); return; }
|
||||
const selected = ids.map((id) => items.find((item) => item.sessionId === id));
|
||||
if (selected.some((item) => !item || !latest.current.some((session) => session.id === item.sessionId && session.status === 'connected'))) {
|
||||
reject(Error('Selected terminal is no longer connected')); return;
|
||||
}
|
||||
resolve(selected as PluginAgentHostTerminal[]);
|
||||
};
|
||||
const cancel = () => finish(null);
|
||||
chooser = { runtimeId, cancel }; signal.addEventListener('abort', cancel, { once: true });
|
||||
setChoice({ items, confirm: finish, cancel });
|
||||
if (signal.aborted) cancel();
|
||||
}),
|
||||
});
|
||||
if (!mounted) runtime.shutdown();
|
||||
return runtime;
|
||||
});
|
||||
const unsubscribe = bridge.subscribe((request) => {
|
||||
if (request.kind === 'request.cancel') {
|
||||
const pending = requests.get(request.payload.requestId);
|
||||
if (pending?.runtimeId === request.runtimeId) pending.controller.abort();
|
||||
runtime.cancelRequest(request.payload.requestId, request.runtimeId); return;
|
||||
withLoadedRuntime((loaded) => loaded.cancelRequest(request.payload.requestId, request.runtimeId)); return;
|
||||
}
|
||||
if (request.kind === 'runtime.release') {
|
||||
for (const item of requests.values()) if (item.runtimeId === request.runtimeId) item.controller.abort();
|
||||
if (chooser?.runtimeId === request.runtimeId) chooser.cancel();
|
||||
runtime.releaseRuntime(request.runtimeId); return;
|
||||
withLoadedRuntime((loaded) => loaded.releaseRuntime(request.runtimeId)); return;
|
||||
}
|
||||
if (request.kind === 'agent.close') { runtime.releaseChat(request.payload.chatSessionId, request.runtimeId); return; }
|
||||
if (request.kind === 'agent.close') { withLoadedRuntime((loaded) => loaded.releaseChat(request.payload.chatSessionId, request.runtimeId)); return; }
|
||||
if (requests.has(request.requestId) || requests.size >= 64) return;
|
||||
const controller = new AbortController(); requests.set(request.requestId, { runtimeId: request.runtimeId, controller });
|
||||
void runtime.handle(request, controller.signal).then(
|
||||
void ensureRuntime().then((loaded) => {
|
||||
// Loading is async: re-check that the host and request are still live.
|
||||
if (!mounted || controller.signal.aborted) throw new Error('Plugin agent request is no longer active');
|
||||
return loaded.handle(request, controller.signal);
|
||||
}).then(
|
||||
(result) => bridge.respond({ requestId: request.requestId, actionToken: request.actionToken, result }).catch(() =>
|
||||
bridge.respond({ requestId: request.requestId, actionToken: request.actionToken, error: true })),
|
||||
() => bridge.respond({ requestId: request.requestId, actionToken: request.actionToken, error: true }),
|
||||
).catch(() => {}).finally(() => requests.delete(request.requestId));
|
||||
});
|
||||
const pageHide = () => { runtime.shutdown(); for (const item of requests.values()) item.controller.abort(); };
|
||||
const pageHide = () => { withLoadedRuntime((loaded) => loaded.shutdown()); for (const item of requests.values()) item.controller.abort(); };
|
||||
const configurationKeys = new Set([STORAGE_KEY_AI_PROVIDERS, STORAGE_KEY_AI_ACTIVE_PROVIDER, STORAGE_KEY_AI_ACTIVE_MODEL,
|
||||
STORAGE_KEY_AI_AGENT_MODEL_MAP, STORAGE_KEY_AI_AGENT_PROVIDER_MAP, STORAGE_KEY_AI_EXTERNAL_AGENTS]);
|
||||
const configurationChanged = (event: Event) => {
|
||||
const key = event.type === 'storage' ? (event as StorageEvent).key : (event as CustomEvent<{ key: string }>).detail?.key;
|
||||
if (key === null || (key && configurationKeys.has(key))) {
|
||||
runtime.invalidateConfiguration();
|
||||
withLoadedRuntime((loaded) => loaded.invalidateConfiguration());
|
||||
// Invalidate main-owned backend leases too, even with no event read in
|
||||
// flight. Re-advertising availability does not renew existing handles.
|
||||
void bridge.ready(false).then(() => { if (mounted) return bridge.ready(true); }).catch(() => {});
|
||||
@@ -85,7 +105,7 @@ export function usePluginAgentHost(sessions: TerminalSession[]) {
|
||||
return () => {
|
||||
mounted = false; chooser?.cancel(); unsubscribe(); window.removeEventListener('pagehide', pageHide);
|
||||
window.removeEventListener('storage', configurationChanged); window.removeEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, configurationChanged);
|
||||
for (const item of requests.values()) item.controller.abort(); requests.clear(); runtime.shutdown();
|
||||
for (const item of requests.values()) item.controller.abort(); requests.clear(); withLoadedRuntime((loaded) => loaded.shutdown());
|
||||
void bridge.ready(false).catch(() => {});
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -10,6 +10,7 @@ export function usePluginCatalog(selectedId: string | null, sourceId = 'official
|
||||
const [listAttempt, setListAttempt] = useState(0);
|
||||
const [readmeState, setReadmeState] = useState<ReadmeState | null>(null);
|
||||
const [readmeAttempt, setReadmeAttempt] = useState(0);
|
||||
const [imageState, setImageState] = useState<{ id: string; token?: string; sourceId: string; images: Record<string, string> } | null>(null);
|
||||
const [installError, setInstallError] = useState<{ id: string; message: string } | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [sourceBinding, setSourceBinding] = useState<NetcattyPluginSource | null>(null);
|
||||
@@ -51,9 +52,19 @@ export function usePluginCatalog(selectedId: string | null, sourceId = 'official
|
||||
})();
|
||||
return () => { active = false; };
|
||||
}, [selectedId, selectionToken, readmeAttempt, sourceId]);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
if (selectedId && selectionToken) {
|
||||
void netcattyBridge.get()?.getPluginCatalogReadmeImages?.(selectedId, selectionToken, sourceId)
|
||||
.then((images) => { if (active) setImageState({ id: selectedId, token: selectionToken, sourceId, images }); })
|
||||
.catch(() => { if (active) setImageState(null); });
|
||||
}
|
||||
return () => { active = false; };
|
||||
}, [selectedId, selectionToken, sourceId, readmeAttempt]);
|
||||
const currentReadme = readmeState?.id === selectedId && readmeState.token === selectionToken && readmeState.attempt === readmeAttempt ? readmeState : null;
|
||||
return {
|
||||
entries, listStatus, listError, source, sourceBinding,
|
||||
readmeImages: imageState?.id === selectedId && imageState.token === selectionToken && imageState.sourceId === sourceId ? imageState.images : {},
|
||||
readme: currentReadme?.status === 'ready' ? currentReadme.text : null,
|
||||
readmeStatus: currentReadme?.status ?? (selectedId ? 'loading' : 'idle'),
|
||||
readmeError: currentReadme?.error ?? null,
|
||||
|
||||
@@ -86,14 +86,8 @@ export interface UsePluginContributionsResult {
|
||||
updateSetting(pluginId: string, settingId: string, value: unknown, scopeId?: string): Promise<{ restartRequired: boolean }>;
|
||||
resetSetting(pluginId: string, settingId: string, scopeId?: string): Promise<{ restartRequired: boolean }>;
|
||||
selectSettingPath(kind: 'file' | 'directory', title: string, defaultPath?: string): Promise<string | null>;
|
||||
openView(payload: NetcattyPluginViewOpenRequest): Promise<{ instanceId: string }>;
|
||||
closeView(instanceId: string): Promise<void>;
|
||||
focusView(instanceId: string): Promise<void>;
|
||||
setViewBounds(instanceId: string, bounds: { x: number; y: number; width: number; height: number }): Promise<void>;
|
||||
setViewVisibility(instanceId: string, visible: boolean): Promise<void>;
|
||||
setEnvironment(environment: NetcattyPluginEnvironment): Promise<void>;
|
||||
onViewClosed(callback: (event: NetcattyPluginViewClosedEvent) => void): () => void;
|
||||
onViewFocused(callback: (event: import('@netcatty/plugin-contract').PluginViewFocusEvent) => void): () => void;
|
||||
}
|
||||
|
||||
export function usePluginContributions(
|
||||
@@ -189,32 +183,6 @@ export function usePluginContributions(
|
||||
return picker(title, defaultPath);
|
||||
}, [bridge]);
|
||||
|
||||
const openView = useCallback(async (payload: NetcattyPluginViewOpenRequest) => {
|
||||
if (!bridge?.openPluginView) throw new Error('Plugin views are unavailable');
|
||||
return bridge.openPluginView(payload);
|
||||
}, [bridge]);
|
||||
|
||||
const closeView = useCallback(async (instanceId: string) => {
|
||||
if (!bridge?.closePluginView) return;
|
||||
await bridge.closePluginView(instanceId);
|
||||
}, [bridge]);
|
||||
const focusView = useCallback(async (instanceId: string) => {
|
||||
await bridge?.focusPluginView?.({ instanceId });
|
||||
}, [bridge]);
|
||||
|
||||
const setViewBounds = useCallback(async (
|
||||
instanceId: string,
|
||||
bounds: { x: number; y: number; width: number; height: number },
|
||||
) => {
|
||||
if (!bridge?.setPluginViewBounds) return;
|
||||
await bridge.setPluginViewBounds(instanceId, bounds);
|
||||
}, [bridge]);
|
||||
|
||||
const setViewVisibility = useCallback(async (instanceId: string, visible: boolean) => {
|
||||
if (!bridge?.setPluginViewVisibility) return;
|
||||
await bridge.setPluginViewVisibility(instanceId, visible);
|
||||
}, [bridge]);
|
||||
|
||||
const setEnvironment = useCallback(async (environment: NetcattyPluginEnvironment) => {
|
||||
if (!bridge?.setPluginEnvironment) return;
|
||||
await bridge.setPluginEnvironment(environment);
|
||||
@@ -223,10 +191,6 @@ export function usePluginContributions(
|
||||
const onViewClosed = useCallback((callback: (event: NetcattyPluginViewClosedEvent) => void) => (
|
||||
bridge?.onPluginViewClosed?.(callback) ?? (() => {})
|
||||
), [bridge]);
|
||||
const onViewFocused = useCallback((callback: (event: import('@netcatty/plugin-contract').PluginViewFocusEvent) => void) => (
|
||||
bridge?.onPluginViewFocused?.(callback) ?? (() => {})
|
||||
), [bridge]);
|
||||
|
||||
const currentLoadState = resolvePluginContributionLoadState({
|
||||
currentQueryKey: queryKey,
|
||||
loadedQueryKey: loadedSnapshot.queryKey,
|
||||
@@ -245,13 +209,7 @@ export function usePluginContributions(
|
||||
updateSetting,
|
||||
resetSetting,
|
||||
selectSettingPath,
|
||||
openView,
|
||||
closeView,
|
||||
focusView,
|
||||
setViewBounds,
|
||||
setViewVisibility,
|
||||
setEnvironment,
|
||||
onViewClosed,
|
||||
onViewFocused,
|
||||
};
|
||||
}
|
||||
@@ -38,18 +38,20 @@ export function usePluginManager() {
|
||||
const refreshGeneration = generation;
|
||||
return () => { refreshGeneration.current++; unsubscribe?.(); window.removeEventListener('netcatty:plugin-packages-changed', update); };
|
||||
}, [refresh]);
|
||||
const run = useCallback(async (action: (bridge: NetcattyBridge) => Promise<unknown>) => {
|
||||
const run = useCallback(async (action: (bridge: NetcattyBridge) => Promise<unknown>, throwOnError = false) => {
|
||||
if (mutation.current) return;
|
||||
mutation.current = true;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
let failure: Error | null = null;
|
||||
try { await action(netcattyBridge.require()); }
|
||||
catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)); }
|
||||
catch (cause) { failure = cause instanceof Error ? cause : new Error(String(cause)); setError(failure.message); }
|
||||
finally {
|
||||
try { await refresh(); } catch (cause) { setError(String(cause)); }
|
||||
try { await refresh(); } catch (cause) { failure ??= cause instanceof Error ? cause : new Error(String(cause)); setError(failure.message); }
|
||||
mutation.current = false;
|
||||
setBusy(false);
|
||||
}
|
||||
if (throwOnError && failure) throw failure;
|
||||
}, [refresh]);
|
||||
return {
|
||||
plugins, available, statusKnown, busy, error, credentialStorageAvailable, refresh,
|
||||
@@ -70,6 +72,6 @@ export function usePluginManager() {
|
||||
if (!bridge.resetPluginSource) throw new Error('Private source reset unavailable');
|
||||
await bridge.resetPluginSource(id, source.id);
|
||||
}
|
||||
}),
|
||||
}, true),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useI18n } from '../i18n/I18nProvider';
|
||||
import { usePluginContributions } from './usePluginContributions';
|
||||
import { resolvePluginSettingScopeSelection, usePluginSettingScopeCatalog } from './usePluginSettingScopeCatalog';
|
||||
|
||||
export function usePluginSettingsModel(pluginId: string) {
|
||||
const { locale } = useI18n();
|
||||
const catalog = usePluginSettingScopeCatalog();
|
||||
const [scopeIds, setScopeIds] = useState<Partial<Record<NetcattyPluginSettingScopeKind, string>>>({});
|
||||
useEffect(() => {
|
||||
setScopeIds(current => resolvePluginSettingScopeSelection(catalog, current));
|
||||
}, [catalog]);
|
||||
const query = useMemo<NetcattyPluginContributionQuery>(() => ({
|
||||
locale, context: { 'netcatty.surface': 'settings' }, scopeIds,
|
||||
}), [locale, scopeIds]);
|
||||
const contributions = usePluginContributions(query);
|
||||
const plugin = contributions.snapshot.plugins.find(item => item.id === pluginId);
|
||||
const settings = plugin?.settings.filter(setting => setting.visible) ?? [];
|
||||
const contextualScopes = [...new Set(settings.map(setting => setting.scope)
|
||||
.filter((scope): scope is NetcattyPluginSettingScopeKind => scope !== 'application'))];
|
||||
return { ...contributions, plugin, settings, catalog, scopeIds, setScopeIds, contextualScopes };
|
||||
}
|
||||
@@ -14,19 +14,12 @@ import {
|
||||
usePluginViewTabs,
|
||||
} from './pluginViewTabStore';
|
||||
import {
|
||||
PluginViewLifecycleController,
|
||||
reconcilePluginViewTabCatalog,
|
||||
resolvePluginViewSnapshotSelection,
|
||||
type HostedPluginViewState,
|
||||
type PluginViewSnapshotSelection,
|
||||
} from './pluginViewLifecycle';
|
||||
import {
|
||||
canRetainPluginViewInScope,
|
||||
resolvePluginRetainedViewKey,
|
||||
resolvePluginViewWindowScope,
|
||||
} from './pluginViewScopes';
|
||||
import { pluginViewSessions } from './pluginViewSession';
|
||||
import { usePluginContributions } from './usePluginContributions';
|
||||
import { observePluginHostSecurityVisibility } from './pluginHostSecurityVisibility';
|
||||
|
||||
export const OPEN_PLUGIN_VIEW_EVENT = 'netcatty:open-plugin-view';
|
||||
|
||||
@@ -70,17 +63,8 @@ export function usePluginViewLifecycle({
|
||||
const {
|
||||
snapshot,
|
||||
executeCommand,
|
||||
openView,
|
||||
closeView,
|
||||
setViewBounds,
|
||||
setViewVisibility,
|
||||
setEnvironment,
|
||||
onViewClosed,
|
||||
} = contributions;
|
||||
const [instance, setInstance] = useState<HostedPluginViewState | null>(null);
|
||||
const lifecycleRef = useRef(new PluginViewLifecycleController<HostedPluginViewState>());
|
||||
const closeViewRef = useRef(closeView);
|
||||
const mountRef = useRef<HTMLDivElement>(null);
|
||||
const resolvedActiveView = useMemo(() => viewContributions.snapshot.plugins
|
||||
.flatMap((plugin) => plugin.views.map((view) => ({ plugin, view })))
|
||||
.find(({ view }) => view.id === effectiveRequested?.viewId && view.visible && !['vault-page', 'terminal-sidebar'].includes(view.location)) ?? null,
|
||||
@@ -93,16 +77,6 @@ export function usePluginViewLifecycle({
|
||||
requestedViewId: effectiveRequested?.viewId,
|
||||
contextKey: viewQueryContextKey,
|
||||
});
|
||||
const activeViewId = activeView?.view.id;
|
||||
const viewScopeId = typeof window === 'undefined'
|
||||
? 'window:server'
|
||||
: resolvePluginViewWindowScope(window.location);
|
||||
const retainedViewKey = activeViewId
|
||||
? resolvePluginRetainedViewKey(activeViewId, viewScopeId)
|
||||
: null;
|
||||
|
||||
useEffect(() => { closeViewRef.current = closeView; }, [closeView]);
|
||||
|
||||
useEffect(() => {
|
||||
if (viewContributions.loading) return;
|
||||
stableActiveViewRef.current = resolvedActiveView && effectiveRequested?.viewId
|
||||
@@ -114,26 +88,6 @@ export function usePluginViewLifecycle({
|
||||
: null;
|
||||
}, [effectiveRequested?.viewId, resolvedActiveView, viewContributions.loading, viewQueryContextKey]);
|
||||
|
||||
useEffect(() => onViewClosed((event) => {
|
||||
const next = lifecycleRef.current.handleHostClose(event.instanceId);
|
||||
if (next.matchedCurrent) {
|
||||
setInstance(null);
|
||||
setRequested(null);
|
||||
}
|
||||
if (next.closedTabId) pluginViewTabStore.close(next.closedTabId);
|
||||
}), [onViewClosed]);
|
||||
|
||||
useEffect(() => pluginViewTabStore.onDidClose(({ tab }) => {
|
||||
const next = lifecycleRef.current.handleTabClose(tab.id);
|
||||
if (next.matchedCurrent) {
|
||||
setInstance(null);
|
||||
setRequested(null);
|
||||
}
|
||||
for (const instanceId of next.instanceIds) {
|
||||
void closeViewRef.current(instanceId).catch(() => {});
|
||||
}
|
||||
}), []);
|
||||
|
||||
useEffect(() => {
|
||||
const bindings = snapshot.plugins.flatMap((plugin) => plugin.keybindings)
|
||||
.filter((binding) => binding.enabled)
|
||||
@@ -182,164 +136,16 @@ export function usePluginViewLifecycle({
|
||||
setRequested(null);
|
||||
}, [activeView, requested]);
|
||||
|
||||
const hideOrClose = useCallback(async (current: HostedPluginViewState) => {
|
||||
if (!current.retainContextWhenHidden) {
|
||||
await closeView(current.id);
|
||||
return;
|
||||
}
|
||||
const key = resolvePluginRetainedViewKey(current.viewId, current.scopeId);
|
||||
lifecycleRef.current.retain(key, current);
|
||||
try {
|
||||
await setViewVisibility(current.id, false);
|
||||
} catch {
|
||||
lifecycleRef.current.removeRetained(key);
|
||||
await closeView(current.id);
|
||||
}
|
||||
}, [closeView, setViewVisibility]);
|
||||
useEffect(() => {
|
||||
const stop = pluginViewTabStore.onDidClose(({ tab }) => pluginViewSessions.closeView(tab.viewId));
|
||||
return () => { stop(); };
|
||||
}, []);
|
||||
|
||||
const close = useCallback(async () => {
|
||||
lifecycleRef.current.markViewClosed(retainedViewKey);
|
||||
const current = lifecycleRef.current.takeCurrent();
|
||||
setInstance(null);
|
||||
setRequested(null);
|
||||
if (current) await closeView(current.id);
|
||||
}, [closeView, retainedViewKey]);
|
||||
|
||||
useEffect(() => {
|
||||
const removed = lifecycleRef.current.removeRetainedWhere(
|
||||
(retained) => !canRetainPluginViewInScope(retained.scopeId, viewScopeId),
|
||||
);
|
||||
for (const retained of removed) void closeView(retained.id).catch(() => {});
|
||||
}, [closeView, viewScopeId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!instance) return;
|
||||
if (effectiveRequested?.viewId === instance.viewId
|
||||
&& activeViewId === instance.viewId
|
||||
&& instance.scopeId === viewScopeId) return;
|
||||
lifecycleRef.current.takeCurrent();
|
||||
setInstance(null);
|
||||
if (canRetainPluginViewInScope(instance.scopeId, viewScopeId)) {
|
||||
void hideOrClose(instance);
|
||||
} else {
|
||||
void closeView(instance.id).catch(() => {});
|
||||
}
|
||||
}, [activeViewId, closeView, effectiveRequested?.viewId, hideOrClose, instance, viewScopeId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeViewId || !retainedViewKey || !mountRef.current || instance) return;
|
||||
let cancelled = false;
|
||||
const openingTabId = activePluginTab?.id;
|
||||
const openingToken = lifecycleRef.current.beginOpen({
|
||||
viewKey: retainedViewKey,
|
||||
tabId: openingTabId,
|
||||
label: activePluginTab?.id ?? activeViewId,
|
||||
});
|
||||
const bounds = mountRef.current.getBoundingClientRect();
|
||||
const nextBounds = {
|
||||
x: Math.round(bounds.x),
|
||||
y: Math.round(bounds.y),
|
||||
width: Math.max(1, Math.round(bounds.width)),
|
||||
height: Math.max(1, Math.round(bounds.height)),
|
||||
};
|
||||
void (async () => {
|
||||
let opened = lifecycleRef.current.takeRetained(retainedViewKey);
|
||||
if (opened) {
|
||||
try {
|
||||
await setViewBounds(opened.id, nextBounds);
|
||||
await setViewVisibility(opened.id, true);
|
||||
} catch {
|
||||
try { await closeView(opened.id); } catch { /* best-effort cleanup after restore failure */ }
|
||||
opened = null;
|
||||
}
|
||||
}
|
||||
if (!opened) {
|
||||
const result = await openView({
|
||||
viewId: activeViewId,
|
||||
scopeId: viewScopeId,
|
||||
bounds: nextBounds,
|
||||
context: effectiveRequested?.context,
|
||||
});
|
||||
opened = {
|
||||
id: result.instanceId,
|
||||
viewId: activeViewId,
|
||||
scopeId: viewScopeId,
|
||||
retainContextWhenHidden: activeView.view.retainContextWhenHidden === true,
|
||||
...(activePluginTab ? { tabId: activePluginTab.id } : {}),
|
||||
};
|
||||
}
|
||||
if (lifecycleRef.current.consumeHostClose(opened.id)) {
|
||||
throw new Error('Plugin view closed while its open response was in flight');
|
||||
}
|
||||
if (lifecycleRef.current.shouldCloseOpen(openingToken)) {
|
||||
await closeView(opened.id);
|
||||
return;
|
||||
}
|
||||
if (cancelled) {
|
||||
await hideOrClose(opened);
|
||||
return;
|
||||
}
|
||||
lifecycleRef.current.setCurrent(opened);
|
||||
setInstance(opened);
|
||||
})().catch(() => {
|
||||
if (cancelled) return;
|
||||
if (activePluginTab) pluginViewTabStore.close(activePluginTab.id);
|
||||
else setRequested(null);
|
||||
}).finally(() => {
|
||||
lifecycleRef.current.finishOpen({
|
||||
token: openingToken,
|
||||
viewKey: retainedViewKey,
|
||||
tabId: openingTabId,
|
||||
});
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [
|
||||
activePluginTab,
|
||||
activeView?.view.retainContextWhenHidden,
|
||||
activeViewId,
|
||||
closeView,
|
||||
effectiveRequested?.context,
|
||||
hideOrClose,
|
||||
instance,
|
||||
openView,
|
||||
retainedViewKey,
|
||||
setViewBounds,
|
||||
setViewVisibility,
|
||||
viewScopeId,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!instance || !mountRef.current) return;
|
||||
let disposed = false;
|
||||
const stop = observePluginHostSecurityVisibility(mountRef.current, (visible) => {
|
||||
void setViewVisibility(instance.id, visible).catch(() => {
|
||||
if (!disposed) void closeView(instance.id).catch(() => {});
|
||||
});
|
||||
});
|
||||
return () => { disposed = true; stop(); };
|
||||
}, [closeView, instance, setViewVisibility]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!instance || !mountRef.current) return;
|
||||
const update = () => {
|
||||
const bounds = mountRef.current?.getBoundingClientRect();
|
||||
if (!bounds) return;
|
||||
void setViewBounds(instance.id, {
|
||||
x: Math.round(bounds.x),
|
||||
y: Math.round(bounds.y),
|
||||
width: Math.max(1, Math.round(bounds.width)),
|
||||
height: Math.max(1, Math.round(bounds.height)),
|
||||
});
|
||||
};
|
||||
const observer = new ResizeObserver(update);
|
||||
observer.observe(mountRef.current);
|
||||
window.addEventListener('resize', update);
|
||||
update();
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
window.removeEventListener('resize', update);
|
||||
};
|
||||
}, [instance, setViewBounds]);
|
||||
if (activeView) pluginViewSessions.closeView(activeView.view.id);
|
||||
if (activePluginTab) pluginViewTabStore.close(activePluginTab.id);
|
||||
}, [activePluginTab, activeView]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!contributions.available) return;
|
||||
@@ -376,16 +182,10 @@ export function usePluginViewLifecycle({
|
||||
};
|
||||
}, [contributions.available, locale, setEnvironment, suppliedThemeTokens, theme]);
|
||||
|
||||
useEffect(() => () => {
|
||||
const views = lifecycleRef.current.drain();
|
||||
const ids = new Set(views.map((view) => view.id));
|
||||
for (const id of ids) void closeViewRef.current(id);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
activeView,
|
||||
close,
|
||||
effectiveRequested,
|
||||
mountRef,
|
||||
viewQueryContext,
|
||||
};
|
||||
}
|
||||
@@ -2,6 +2,8 @@ import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
|
||||
export interface DiskInfo {
|
||||
diskReadSpeed?: number | null; // Mounted block-device I/O, bytes/sec
|
||||
diskWriteSpeed?: number | null;
|
||||
capacityKey?: string; // Filesystem or shared-pool identity for deduplication
|
||||
filesystemType?: string; // Filesystem type reported by df (for network/FUSE filtering)
|
||||
mountPoint: string;
|
||||
|
||||
@@ -21,9 +21,11 @@ getNextFocusSessionId,
|
||||
insertPaneIntoWorkspace,
|
||||
pruneWorkspaceNode,
|
||||
reorderWorkspaceFocusSessionOrder,
|
||||
setWorkspaceFocusedSessionId,
|
||||
SplitDirection,
|
||||
SplitHint,
|
||||
updateWorkspaceSplitSizes,
|
||||
invertSplitPosition,
|
||||
} from '../../domain/workspace';
|
||||
import { clearSessionFontSizeOverride as clearSessionFontSizeOverrideFields } from '../../domain/terminalAppearance';
|
||||
import {
|
||||
@@ -248,6 +250,8 @@ export const useSessionState = ({
|
||||
const [globalComposeSendToAll, setGlobalComposeSendToAll] = useState<boolean>(false);
|
||||
// Log views: stores open log replay tabs
|
||||
const [logViews, setLogViews] = useState<LogView[]>([]);
|
||||
const logViewsRef = useRef(logViews);
|
||||
logViewsRef.current = logViews;
|
||||
const [restorePreviousSessionRevision, setRestorePreviousSessionRevision] = useState(0);
|
||||
const sessionsRef = useRef(sessions);
|
||||
const tabOrderRef = useRef(tabOrder);
|
||||
@@ -795,12 +799,68 @@ export const useSessionState = ({
|
||||
return workspace.id;
|
||||
}, [setActiveTabId]);
|
||||
|
||||
const addSessionToWorkspace = useCallback((
|
||||
workspaceId: string,
|
||||
sessionId: string,
|
||||
hint: SplitHint
|
||||
) => {
|
||||
if (!hint) return;
|
||||
|
||||
setSessions(prevSessions => {
|
||||
const session = prevSessions.find(s => s.id === sessionId);
|
||||
if (!session || session.workspaceId) return prevSessions;
|
||||
|
||||
setWorkspaces(prevWorkspaces => {
|
||||
const targetWorkspace = prevWorkspaces.find(w => w.id === workspaceId);
|
||||
if (!targetWorkspace) return prevWorkspaces;
|
||||
|
||||
return insertWorkspacePaneIfMissing(prevWorkspaces, workspaceId, sessionId, hint);
|
||||
});
|
||||
|
||||
setActiveTabId(workspaceId);
|
||||
return prevSessions.map(s => s.id === sessionId ? { ...s, workspaceId } : s);
|
||||
});
|
||||
}, [setActiveTabId]);
|
||||
|
||||
// Merge two tabs into one workspace. When one of them already belongs to a
|
||||
// workspace, that workspace (and its id) is reused instead of dissolving
|
||||
// and recreating: the id is what workspace-scoped AI chats bind to, so
|
||||
// regenerating it used to strand every conversation anchored to it
|
||||
// (issue #4015 R3). Only two genuinely standalone tabs create a new id.
|
||||
const createWorkspaceFromSessions = useCallback((
|
||||
baseSessionId: string,
|
||||
joiningSessionId: string,
|
||||
hint: SplitHint
|
||||
) => {
|
||||
if (!hint || baseSessionId === joiningSessionId) return;
|
||||
const baseSession = sessionsRef.current.find((s) => s.id === baseSessionId);
|
||||
const joiningSession = sessionsRef.current.find((s) => s.id === joiningSessionId);
|
||||
const anchorWorkspaceId = baseSession?.workspaceId ?? joiningSession?.workspaceId;
|
||||
if (anchorWorkspaceId) {
|
||||
const anchorSessionId = baseSession?.workspaceId ? baseSessionId : joiningSessionId;
|
||||
const orphanSessionId = anchorSessionId === baseSessionId ? joiningSessionId : baseSessionId;
|
||||
const orphanSession = sessionsRef.current.find((s) => s.id === orphanSessionId);
|
||||
if (!orphanSession || orphanSession.workspaceId) return;
|
||||
// Split next to the anchor's existing pane: the raw drop hint targets
|
||||
// the orphan's pane, which is not part of this workspace tree yet.
|
||||
// When the dragged (joining) pane already owns the workspace, the orphan
|
||||
// is what gets inserted — invert the drop position so the previewed
|
||||
// side still matches (hint describes where the dragged pane should sit).
|
||||
const joinOwnsWorkspace = Boolean(joiningSession?.workspaceId) && !baseSession?.workspaceId;
|
||||
const insertHint = {
|
||||
...hint,
|
||||
targetSessionId: anchorSessionId,
|
||||
position: joinOwnsWorkspace ? invertSplitPosition(hint.position) : hint.position,
|
||||
};
|
||||
addSessionToWorkspace(
|
||||
anchorWorkspaceId,
|
||||
orphanSessionId,
|
||||
insertHint,
|
||||
);
|
||||
// The orphan's standalone tab slot is replaced by the workspace tab.
|
||||
setTabOrder((prevTabOrder) => prevTabOrder.filter((id) => id !== orphanSessionId));
|
||||
return;
|
||||
}
|
||||
// Name the merged workspace after both tabs' connection labels (e.g.
|
||||
// "01/02") so the window title and the rename dialog show the merged
|
||||
// identity instead of the generic "Workspace". Falls back to the default
|
||||
@@ -855,30 +915,7 @@ export const useSessionState = ({
|
||||
return s;
|
||||
});
|
||||
});
|
||||
}, [setActiveTabId]);
|
||||
|
||||
const addSessionToWorkspace = useCallback((
|
||||
workspaceId: string,
|
||||
sessionId: string,
|
||||
hint: SplitHint
|
||||
) => {
|
||||
if (!hint) return;
|
||||
|
||||
setSessions(prevSessions => {
|
||||
const session = prevSessions.find(s => s.id === sessionId);
|
||||
if (!session || session.workspaceId) return prevSessions;
|
||||
|
||||
setWorkspaces(prevWorkspaces => {
|
||||
const targetWorkspace = prevWorkspaces.find(w => w.id === workspaceId);
|
||||
if (!targetWorkspace) return prevWorkspaces;
|
||||
|
||||
return insertWorkspacePaneIfMissing(prevWorkspaces, workspaceId, sessionId, hint);
|
||||
});
|
||||
|
||||
setActiveTabId(workspaceId);
|
||||
return prevSessions.map(s => s.id === sessionId ? { ...s, workspaceId } : s);
|
||||
});
|
||||
}, [setActiveTabId]);
|
||||
}, [addSessionToWorkspace, setActiveTabId]);
|
||||
|
||||
// Add a host into an existing workspace by creating a new session for
|
||||
// that host and appending it as the last pane at the workspace root.
|
||||
@@ -1063,10 +1100,10 @@ export const useSessionState = ({
|
||||
|
||||
// Set the focused session in a workspace (for focus mode)
|
||||
const setWorkspaceFocusedSession = useCallback((workspaceId: string, sessionId: string) => {
|
||||
setWorkspaces(prev => prev.map(ws => {
|
||||
if (ws.id !== workspaceId) return ws;
|
||||
return { ...ws, focusedSessionId: sessionId };
|
||||
}));
|
||||
// Pane click and focus both land here; an unchanged focus must keep the
|
||||
// same array or every click re-renders the whole shell (and re-saves the
|
||||
// session restore snapshot).
|
||||
setWorkspaces(prev => setWorkspaceFocusedSessionId(prev, workspaceId, sessionId));
|
||||
}, []);
|
||||
|
||||
const reorderWorkspaceSessions = useCallback((
|
||||
@@ -1092,7 +1129,7 @@ export const useSessionState = ({
|
||||
|
||||
// Move focus between panes in a workspace
|
||||
const moveFocusInWorkspace = useCallback((workspaceId: string, direction: FocusDirection): boolean => {
|
||||
const workspace = workspaces.find(w => w.id === workspaceId);
|
||||
const workspace = workspacesRef.current.find(w => w.id === workspaceId);
|
||||
if (!workspace) {
|
||||
return false;
|
||||
}
|
||||
@@ -1113,13 +1150,10 @@ export const useSessionState = ({
|
||||
}
|
||||
|
||||
// Update focused session
|
||||
setWorkspaces(prev => prev.map(ws => {
|
||||
if (ws.id !== workspaceId) return ws;
|
||||
return { ...ws, focusedSessionId: nextSessionId };
|
||||
}));
|
||||
setWorkspaces(prev => setWorkspaceFocusedSessionId(prev, workspaceId, nextSessionId));
|
||||
|
||||
return true;
|
||||
}, [workspaces]);
|
||||
}, []);
|
||||
|
||||
// Run a snippet on multiple target hosts - creates a focus mode workspace
|
||||
const runSnippet = useCallback((snippet: Snippet, targetHosts: Host[], commandOverride?: string) => {
|
||||
@@ -1162,6 +1196,10 @@ export const useSessionState = ({
|
||||
}, [setActiveTabId]);
|
||||
|
||||
const orphanSessions = useMemo(() => sessions.filter(s => !s.workspaceId && !s.hiddenFromTabs), [sessions]);
|
||||
// Read by action callbacks at call time so they keep a stable identity:
|
||||
// orphanSessions changes with every session status update.
|
||||
const orphanSessionsRef = useRef(orphanSessions);
|
||||
orphanSessionsRef.current = orphanSessions;
|
||||
const canUseGlobalBroadcast = orphanSessions.length >= 2;
|
||||
|
||||
// Losing the group must disarm broadcast before another tab can join it.
|
||||
@@ -1196,6 +1234,13 @@ export const useSessionState = ({
|
||||
}) => {
|
||||
// Pre-allocate the new id outside the updater so StrictMode's
|
||||
// double-invocation of the functional updater doesn't mint two ids.
|
||||
// Same snapshot the old closure captured (values at click time), read from
|
||||
// refs so this action keeps a stable identity across session updates.
|
||||
const tabIdsAtCall = [
|
||||
...orphanSessionsRef.current.map(s => s.id),
|
||||
...workspacesRef.current.map(w => w.id),
|
||||
...logViewsRef.current.map(lv => lv.id),
|
||||
];
|
||||
const newSessionId = crypto.randomUUID();
|
||||
|
||||
setSessions(prevSessions => {
|
||||
@@ -1216,17 +1261,13 @@ export const useSessionState = ({
|
||||
// StrictMode's double-invocation is harmless.
|
||||
setActiveTabId(newSessionId);
|
||||
setTabOrder(prevTabOrder => {
|
||||
const allTabIds = [
|
||||
...orphanSessions.map(s => s.id),
|
||||
...workspaces.map(w => w.id),
|
||||
...logViews.map(lv => lv.id),
|
||||
];
|
||||
const allTabIds = tabIdsAtCall;
|
||||
return insertCopiedTabOrderIdOnce(prevTabOrder, sessionId, newSessionId, allTabIds);
|
||||
});
|
||||
|
||||
return [...prevSessions, newSession];
|
||||
});
|
||||
}, [orphanSessions, workspaces, logViews, setActiveTabId]);
|
||||
}, [setActiveTabId]);
|
||||
|
||||
// Copy a whole workspace (split/focus tab): clone every pane's session and
|
||||
// reproduce the layout tree in a new tab.
|
||||
@@ -1234,7 +1275,14 @@ export const useSessionState = ({
|
||||
localShellType?: TerminalSession['shellType'];
|
||||
perPaneCwd?: Record<string, string | undefined>;
|
||||
}) => {
|
||||
const sourceWorkspace = workspaces.find(w => w.id === workspaceId);
|
||||
// Same snapshot the old closure captured (values at click time), read from
|
||||
// refs so this action keeps a stable identity across session updates.
|
||||
const tabIdsAtCall = [
|
||||
...orphanSessionsRef.current.map(s => s.id),
|
||||
...workspacesRef.current.map(w => w.id),
|
||||
...logViewsRef.current.map(lv => lv.id),
|
||||
];
|
||||
const sourceWorkspace = workspacesRef.current.find(w => w.id === workspaceId);
|
||||
if (!sourceWorkspace) return;
|
||||
|
||||
// Pre-mint the new workspace id and the old->new session-id map OUTSIDE the
|
||||
@@ -1272,17 +1320,13 @@ export const useSessionState = ({
|
||||
setWorkspaces(prev => addWorkspaceIfMissing(prev, built.newWorkspace));
|
||||
setActiveTabId(newWorkspaceId);
|
||||
setTabOrder(prevTabOrder => {
|
||||
const allTabIds = [
|
||||
...orphanSessions.map(s => s.id),
|
||||
...workspaces.map(w => w.id),
|
||||
...logViews.map(lv => lv.id),
|
||||
];
|
||||
const allTabIds = tabIdsAtCall;
|
||||
return insertCopiedTabOrderIdOnce(prevTabOrder, workspaceId, newWorkspaceId, allTabIds);
|
||||
});
|
||||
|
||||
return [...prevSessions, ...built.newSessions];
|
||||
});
|
||||
}, [workspaces, orphanSessions, logViews, setActiveTabId]);
|
||||
}, [setActiveTabId]);
|
||||
|
||||
const createSessionFromCloneSource = useCallback((sourceSession: TerminalSession, options?: {
|
||||
localShellType?: TerminalSession['shellType'];
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
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 { collectSessionIds } from "../../domain/workspace.ts";
|
||||
import { useSessionState } from "./useSessionState.ts";
|
||||
|
||||
type SessionState = ReturnType<typeof useSessionState>;
|
||||
|
||||
test("merging a workspace tab with a standalone tab reuses the workspace id (issue #4015 R3)", async (t) => {
|
||||
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
|
||||
const eventTarget = new EventTarget() as EventTarget & Record<string, unknown>;
|
||||
Object.assign(eventTarget, {
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
});
|
||||
Object.defineProperty(globalThis, "window", {
|
||||
configurable: true,
|
||||
value: eventTarget,
|
||||
});
|
||||
t.after(() => {
|
||||
if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow);
|
||||
else Reflect.deleteProperty(globalThis, "window");
|
||||
});
|
||||
|
||||
const actEnvironment = globalThis as typeof globalThis & {
|
||||
IS_REACT_ACT_ENVIRONMENT?: boolean;
|
||||
};
|
||||
const previousActEnvironment = actEnvironment.IS_REACT_ACT_ENVIRONMENT;
|
||||
actEnvironment.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
t.after(() => {
|
||||
actEnvironment.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
|
||||
});
|
||||
|
||||
let state: SessionState | null = null;
|
||||
let renderer: ReactTestRenderer | null = null;
|
||||
const current = (): SessionState => {
|
||||
assert.ok(state);
|
||||
return state;
|
||||
};
|
||||
function Probe() {
|
||||
state = useSessionState({ persistSessionRestore: false });
|
||||
return null;
|
||||
}
|
||||
|
||||
await act(async () => {
|
||||
renderer = create(React.createElement(Probe));
|
||||
});
|
||||
|
||||
let baseId = "";
|
||||
let memberId = "";
|
||||
let standaloneId = "";
|
||||
await act(async () => {
|
||||
baseId = current().createLocalTerminal({ shellName: "01" });
|
||||
memberId = current().createLocalTerminal({ shellName: "02" });
|
||||
standaloneId = current().createLocalTerminal({ shellName: "03" });
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
current().createWorkspaceFromSessions(baseId, memberId, {
|
||||
direction: "vertical",
|
||||
position: "right",
|
||||
targetSessionId: baseId,
|
||||
});
|
||||
});
|
||||
const workspaceId = current().workspaces[0]?.id;
|
||||
assert.ok(workspaceId);
|
||||
assert.equal(current().sessions.find((s) => s.id === standaloneId)?.workspaceId ?? "", "");
|
||||
|
||||
// Dropping the standalone tab onto a member of the workspace must join the
|
||||
// existing workspace — regenerating the id would strand AI chats bound to it.
|
||||
await act(async () => {
|
||||
current().createWorkspaceFromSessions(standaloneId, memberId, {
|
||||
direction: "vertical",
|
||||
position: "right",
|
||||
targetSessionId: standaloneId,
|
||||
});
|
||||
});
|
||||
|
||||
assert.equal(current().workspaces.length, 1);
|
||||
assert.equal(current().workspaces[0]?.id, workspaceId);
|
||||
assert.equal(
|
||||
current().sessions.find((s) => s.id === standaloneId)?.workspaceId,
|
||||
workspaceId,
|
||||
);
|
||||
const memberIds = collectSessionIds(current().workspaces[0]!.root);
|
||||
assert.ok(memberIds.includes(standaloneId));
|
||||
assert.ok(memberIds.includes(memberId));
|
||||
// The standalone tab slot is replaced by the workspace tab.
|
||||
assert.ok(!current().orderedTabs.includes(standaloneId));
|
||||
|
||||
|
||||
// Dropping a workspace member onto a standalone tab must insert the
|
||||
// standalone on the opposite side of the drop hint (hint describes where
|
||||
// the dragged member should appear relative to the standalone).
|
||||
let orientationStandaloneId = "";
|
||||
await act(async () => {
|
||||
orientationStandaloneId = current().createLocalTerminal({ shellName: "orient-standalone" });
|
||||
});
|
||||
// memberId is already in workspaceId; drop member onto the new standalone with position "right"
|
||||
// (preview: member to the right of standalone ⇒ standalone should end up LEFT of member).
|
||||
await act(async () => {
|
||||
current().createWorkspaceFromSessions(orientationStandaloneId, memberId, {
|
||||
direction: "vertical",
|
||||
position: "right",
|
||||
targetSessionId: orientationStandaloneId,
|
||||
});
|
||||
});
|
||||
{
|
||||
const root = current().workspaces.find((ws) => ws.id === workspaceId)?.root;
|
||||
assert.ok(root);
|
||||
const ordered = collectSessionIds(root!);
|
||||
const standaloneIdx = ordered.indexOf(orientationStandaloneId);
|
||||
const memberIdx = ordered.indexOf(memberId);
|
||||
assert.ok(standaloneIdx >= 0 && memberIdx >= 0);
|
||||
assert.ok(
|
||||
standaloneIdx < memberIdx,
|
||||
`expected standalone left of member after inverted right-drop, got order ${ordered.join(",")}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Two genuinely standalone tabs still create a fresh workspace.
|
||||
let firstStandaloneId = "";
|
||||
let secondStandaloneId = "";
|
||||
await act(async () => {
|
||||
firstStandaloneId = current().createLocalTerminal({ shellName: "04" });
|
||||
secondStandaloneId = current().createLocalTerminal({ shellName: "05" });
|
||||
});
|
||||
await act(async () => {
|
||||
current().createWorkspaceFromSessions(firstStandaloneId, secondStandaloneId, {
|
||||
direction: "vertical",
|
||||
position: "right",
|
||||
targetSessionId: firstStandaloneId,
|
||||
});
|
||||
});
|
||||
|
||||
assert.equal(current().workspaces.length, 2);
|
||||
const freshWorkspace = current().workspaces.find((candidate) => candidate.id !== workspaceId);
|
||||
assert.ok(freshWorkspace);
|
||||
assert.notEqual(freshWorkspace.id, workspaceId);
|
||||
|
||||
await act(async () => {
|
||||
renderer?.unmount();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useEffect, useMemo, useSyncExternalStore } from 'react';
|
||||
|
||||
import { parseKeyCombo, type HotkeyScheme } from '../../domain/models/keyBindings';
|
||||
|
||||
@@ -70,26 +70,55 @@ export function shouldReleaseShortcutModifier(
|
||||
return !isShortcutModifierHeld(event, requirements);
|
||||
}
|
||||
|
||||
export function useShortcutModifierHeld(
|
||||
// The held flag lives in a tiny store so only the tab icon slots re-render when
|
||||
// it flips. It used to be TopTabs state, which re-rendered the whole tab bar
|
||||
// twice for every Ctrl/⌘ shortcut typed in a terminal (Ctrl+C, ⌘V, ...).
|
||||
let modifierHeld = false;
|
||||
const modifierHeldListeners = new Set<() => void>();
|
||||
|
||||
function publishModifierHeld(next: boolean): void {
|
||||
if (modifierHeld === next) return;
|
||||
modifierHeld = next;
|
||||
for (const listener of modifierHeldListeners) listener();
|
||||
}
|
||||
|
||||
function subscribeModifierHeld(listener: () => void): () => void {
|
||||
modifierHeldListeners.add(listener);
|
||||
return () => {
|
||||
modifierHeldListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
const getModifierHeld = () => modifierHeld;
|
||||
|
||||
/** Whether the tab-switch modifier combination is currently held. */
|
||||
export function useShortcutModifierHeldValue(): boolean {
|
||||
return useSyncExternalStore(subscribeModifierHeld, getModifierHeld, getModifierHeld);
|
||||
}
|
||||
|
||||
/**
|
||||
* Track the modifiers of the effective [1...9] tab-switch binding and publish
|
||||
* whether they are held. Pass a null binding to stop tracking.
|
||||
*/
|
||||
export function useTrackShortcutModifierHeld(
|
||||
keyBinding: string | null,
|
||||
scheme: HotkeyScheme,
|
||||
): boolean {
|
||||
const [isHeld, setIsHeld] = useState(false);
|
||||
): void {
|
||||
const requirements = useMemo(
|
||||
() => getShortcutModifierRequirements(keyBinding, scheme),
|
||||
[keyBinding, scheme],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setIsHeld(false);
|
||||
publishModifierHeld(false);
|
||||
if (!requirements) return;
|
||||
|
||||
// Sync on every modifier transition so extras clear the preview and
|
||||
// releasing an extra modifier can re-arm when the exact combo remains.
|
||||
const syncHeldState = (event: KeyboardEvent) => {
|
||||
setIsHeld(isShortcutModifierHeld(event, requirements));
|
||||
publishModifierHeld(isShortcutModifierHeld(event, requirements));
|
||||
};
|
||||
const clearHeldState = () => setIsHeld(false);
|
||||
const clearHeldState = () => publishModifierHeld(false);
|
||||
const handleVisibilityChange = () => {
|
||||
if (document.visibilityState === 'hidden') {
|
||||
clearHeldState();
|
||||
@@ -106,8 +135,7 @@ export function useShortcutModifierHeld(
|
||||
window.removeEventListener('keyup', syncHeldState, true);
|
||||
window.removeEventListener('blur', clearHeldState);
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
publishModifierHeld(false);
|
||||
};
|
||||
}, [requirements]);
|
||||
|
||||
return isHeld;
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
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 { useToolAccessGuidanceState, type ToolAccessGuidanceState } from './useToolAccessGuidanceState';
|
||||
import { AI_STATE_CHANGED_EVENT } from './aiStateEvents';
|
||||
import { STORAGE_KEY_AI_EXTERNAL_MCP_ENABLED } from '../../infrastructure/config/storageKeys';
|
||||
import type { AIToolIntegrationMode } from '../../infrastructure/ai/types';
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((done) => { resolve = done; });
|
||||
return { promise, resolve };
|
||||
}
|
||||
async function harness() {
|
||||
const requests: ReturnType<typeof deferred<unknown>>[] = [];
|
||||
const events = new EventTarget();
|
||||
const values = new Map([[STORAGE_KEY_AI_EXTERNAL_MCP_ENABLED, 'true']]);
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
const globals = {
|
||||
IS_REACT_ACT_ENVIRONMENT: true,
|
||||
localStorage: { getItem: (key: string) => values.get(key) ?? null, setItem: (key: string, value: string) => values.set(key, value) },
|
||||
window: {
|
||||
netcatty: {
|
||||
externalMcpGetStatus: () => { const request = deferred<unknown>(); requests.push(request); return request.promise; },
|
||||
aiSkillsCliGetInvocation: async () => ({ ok: true, skillPath: '/fixture/skills/SKILL.md', commandPrefix: 'fixture-cli' }),
|
||||
},
|
||||
addEventListener: events.addEventListener.bind(events), removeEventListener: events.removeEventListener.bind(events),
|
||||
dispatchEvent: events.dispatchEvent.bind(events), setTimeout, clearTimeout,
|
||||
},
|
||||
};
|
||||
for (const [key, value] of Object.entries(globals)) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { value, configurable: true, writable: true });
|
||||
}
|
||||
let result!: ToolAccessGuidanceState;
|
||||
function Harness({ mode }: { mode: AIToolIntegrationMode }) { result = useToolAccessGuidanceState(mode); return null; }
|
||||
let renderer!: ReactTestRenderer;
|
||||
await act(async () => { renderer = create(<Harness mode="mcp" />); });
|
||||
return {
|
||||
requests, events, values, result: () => result,
|
||||
skills: async () => { await act(async () => renderer.update(<Harness mode="skills" />)); },
|
||||
close: async () => {
|
||||
await act(async () => renderer.unmount());
|
||||
for (const [key, value] of previous) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
|
||||
},
|
||||
};
|
||||
}
|
||||
const status = (path: string) => ({ ok: true, enabled: true, state: 'running', launcherPath: path, discoveryPath: `${path}.json` });
|
||||
|
||||
test('older MCP guidance response cannot overwrite a newer enable-state refresh', async () => {
|
||||
const h = await harness();
|
||||
try {
|
||||
assert.equal(h.requests.length, 1);
|
||||
await act(async () => { h.events.dispatchEvent(new CustomEvent(AI_STATE_CHANGED_EVENT, { detail: { key: STORAGE_KEY_AI_EXTERNAL_MCP_ENABLED } })); });
|
||||
assert.equal(h.requests.length, 2);
|
||||
await act(async () => h.requests[1].resolve(status('/fixture/new')));
|
||||
assert.equal(h.result().mcpLauncherPath, '/fixture/new');
|
||||
await act(async () => h.requests[0].resolve(status('/fixture/old')));
|
||||
assert.equal(h.result().mcpLauncherPath, '/fixture/new');
|
||||
} finally { await h.close(); }
|
||||
});
|
||||
|
||||
test('switching to Skills ignores pending MCP results and preserves resolved Skills guidance', async () => {
|
||||
const h = await harness();
|
||||
try {
|
||||
await h.skills();
|
||||
await act(async () => h.requests[0].resolve(status('/fixture/stale')));
|
||||
assert.equal(h.result().mcpLauncherPath, null);
|
||||
assert.equal(h.result().skillPath, '/fixture/skills/SKILL.md');
|
||||
assert.equal(h.result().commandPrefix, 'fixture-cli');
|
||||
} finally { await h.close(); }
|
||||
});
|
||||
|
||||
test('MCP guidance completion after unmount has no visible state or retry work', async () => {
|
||||
const h = await harness();
|
||||
const initial = h.result();
|
||||
await h.close();
|
||||
await act(async () => h.requests[0].resolve(status('/fixture/stale')));
|
||||
assert.equal(h.result(), initial);
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { AIToolIntegrationMode } from '../../infrastructure/ai/types';
|
||||
import { STORAGE_KEY_AI_EXTERNAL_MCP_ENABLED } from '../../infrastructure/config/storageKeys';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
@@ -38,14 +38,15 @@ export type ToolAccessGuidanceState = {
|
||||
* runtime is still starting or after an idle shutdown).
|
||||
*/
|
||||
export function useToolAccessGuidanceState(mode: AIToolIntegrationMode): ToolAccessGuidanceState {
|
||||
const requestGeneration = useRef(0);
|
||||
const [skillPath, setSkillPath] = useState<string | null>(null);
|
||||
const [commandPrefix, setCommandPrefix] = useState('');
|
||||
const [mcpLauncherPath, setMcpLauncherPath] = useState<string | null>(null);
|
||||
const [mcpDiscoveryPath, setMcpDiscoveryPath] = useState<string | null>(null);
|
||||
|
||||
const refreshMcpStatus = useCallback(async (): Promise<string | null | undefined> => {
|
||||
const refreshMcpStatus = useCallback(async (isCurrent: () => boolean): Promise<string | null | undefined> => {
|
||||
const status = await netcattyBridge.get()?.externalMcpGetStatus?.();
|
||||
if (!status?.ok) return undefined;
|
||||
if (!isCurrent() || !status?.ok) return undefined;
|
||||
// Do not trust `enabled` alone: the main process flips `enabled` before
|
||||
// host credentials are resolved and the discovery file is written, and it
|
||||
// keeps reporting the configured discovery/launcher paths while starting.
|
||||
@@ -93,9 +94,11 @@ export function useToolAccessGuidanceState(mode: AIToolIntegrationMode): ToolAcc
|
||||
|
||||
const refetch = async () => {
|
||||
if (cancelled) return;
|
||||
const generation = ++requestGeneration.current;
|
||||
const isCurrent = () => !cancelled && generation === requestGeneration.current;
|
||||
const storedEnabled = readExternalMcpStoredEnabled();
|
||||
const readyLauncherPath = await refreshMcpStatus().catch(() => undefined);
|
||||
if (cancelled) return;
|
||||
const readyLauncherPath = await refreshMcpStatus(isCurrent).catch(() => undefined);
|
||||
if (!isCurrent()) return;
|
||||
// The persisted switch is off but the status check failed: drop any
|
||||
// cached launcher/discovery paths. The stored credentials were revoked
|
||||
// by the disable, and falling through to the comparison below would see
|
||||
|
||||
@@ -63,6 +63,9 @@ export function useToolbarItemLayout(
|
||||
const [layout, setLayout] = useState<ToolbarItemLayout>(() => readLayout(storageKey, defaults));
|
||||
|
||||
useEffect(() => {
|
||||
// Defaults can include dynamically discovered items; re-read without writing
|
||||
// so temporary catalog changes never erase stored toolbar preferences.
|
||||
setLayout(readLayout(storageKey, defaults));
|
||||
const sync = (event: Event) => {
|
||||
if (event instanceof StorageEvent && event.key !== storageKey) return;
|
||||
if (event instanceof CustomEvent && event.detail?.key !== storageKey) return;
|
||||
|
||||
@@ -55,6 +55,8 @@ export interface UseVaultAgentBridgeInput {
|
||||
openHost?: VaultAgentApiDeps['openHost'];
|
||||
findExistingSessionForHost?: VaultAgentApiDeps['findExistingSessionForHost'];
|
||||
closeSession?: VaultAgentApiDeps['closeSession'];
|
||||
reconnectSession?: VaultAgentApiDeps['reconnectSession'];
|
||||
inspectSessionRecovery?: VaultAgentApiDeps['inspectSessionRecovery'];
|
||||
getScriptSessionMeta?: (sessionId: string) => Pick<TerminalSession, 'status' | 'customName' | 'hostLabel' | 'hostname' | 'username'> | undefined;
|
||||
}
|
||||
|
||||
@@ -273,6 +275,8 @@ export function useVaultAgentBridge(input: UseVaultAgentBridgeInput): void {
|
||||
? (host, isExternalMcpCall, options) => current.openHost!(host, isExternalMcpCall, options)
|
||||
: undefined,
|
||||
findExistingSessionForHost: current.findExistingSessionForHost,
|
||||
reconnectSession: current.reconnectSession,
|
||||
inspectSessionRecovery: current.inspectSessionRecovery,
|
||||
closeSession: current.closeSession
|
||||
? (sessionId) => current.closeSession!(sessionId)
|
||||
: undefined,
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
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 { JSDOM } from "jsdom";
|
||||
import { installBrowserLockFixture } from "../testSupport/browserLockFixture";
|
||||
import { STORAGE_KEY_SHELL_HISTORY } from "../../infrastructure/config/storageKeys";
|
||||
|
||||
test("shell history append yields the input turn and persists merged entries", async () => {
|
||||
const dom = new JSDOM("", { url: "http://localhost" });
|
||||
const globals = ["window", "localStorage", "CustomEvent", "IS_REACT_ACT_ENVIRONMENT", "navigator"];
|
||||
const previous = new Map(globals.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
|
||||
Object.defineProperties(globalThis, {
|
||||
window: { value: dom.window, configurable: true },
|
||||
localStorage: { value: dom.window.localStorage, configurable: true },
|
||||
CustomEvent: { value: dom.window.CustomEvent, configurable: true },
|
||||
IS_REACT_ACT_ENVIRONMENT: { value: true, configurable: true },
|
||||
});
|
||||
installBrowserLockFixture();
|
||||
const { useVaultState } = await import("./useVaultState");
|
||||
let state: ReturnType<typeof useVaultState>;
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
const Probe = () => { state = useVaultState({ syncConnectionLogTerminalData: false }); return null; };
|
||||
try {
|
||||
await act(async () => { renderer = create(React.createElement(Probe)); });
|
||||
for (let attempt = 0; !state!.isInitialized && attempt < 50; attempt++) {
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });
|
||||
}
|
||||
assert.equal(state!.isInitialized, true);
|
||||
const entry = { command: " echo hello ", hostId: "local", hostLabel: "Local", sessionId: "one" };
|
||||
act(() => {
|
||||
state!.addShellHistoryEntry(entry);
|
||||
state!.addShellHistoryEntry({ ...entry, sessionId: "two" });
|
||||
assert.equal(dom.window.localStorage.getItem(STORAGE_KEY_SHELL_HISTORY), null);
|
||||
assert.equal(state!.shellHistory.length, 0);
|
||||
});
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 20)); });
|
||||
const saved = JSON.parse(dom.window.localStorage.getItem(STORAGE_KEY_SHELL_HISTORY)!);
|
||||
assert.equal(saved.length, 1);
|
||||
assert.equal(saved[0].command, "echo hello");
|
||||
assert.equal(saved[0].sessionId, "two");
|
||||
assert.deepEqual(state!.shellHistory, saved);
|
||||
|
||||
for (const clear of [() => state!.clearShellHistory(), () => state!.clearAllCommandHistory()]) {
|
||||
act(() => {
|
||||
state!.addShellHistoryEntry(entry);
|
||||
state!.addShellHistoryEntry({ ...entry, command: "another command" });
|
||||
clear();
|
||||
});
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 20)); });
|
||||
assert.deepEqual(state!.shellHistory, []);
|
||||
assert.deepEqual(JSON.parse(dom.window.localStorage.getItem(STORAGE_KEY_SHELL_HISTORY)!), []);
|
||||
}
|
||||
} finally {
|
||||
await act(async () => { renderer?.unmount(); });
|
||||
dom.window.close();
|
||||
for (const key of globals) {
|
||||
const descriptor = previous.get(key);
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -317,6 +317,7 @@ export const useVaultState = (options?: UseVaultStateOptions) => {
|
||||
const [noteGroups, setNoteGroups] = useState<string[]>([]);
|
||||
const [knownHosts, setKnownHosts] = useState<KnownHost[]>([]);
|
||||
const [shellHistory, setShellHistory] = useState<ShellHistoryEntry[]>([]);
|
||||
const shellHistoryGenerationRef = useRef(0);
|
||||
const [connectionLogs, setConnectionLogs] = useState<ConnectionLog[]>([]);
|
||||
const [managedSources, setManagedSources] = useState<ManagedSource[]>([]);
|
||||
const [groupConfigs, setGroupConfigs] = useState<GroupConfig[]>([]);
|
||||
@@ -1445,19 +1446,25 @@ export const useVaultState = (options?: UseVaultStateOptions) => {
|
||||
|
||||
const addShellHistoryEntry = useCallback(
|
||||
(entry: Omit<ShellHistoryEntry, "id" | "timestamp">) => {
|
||||
setShellHistory((prev) => {
|
||||
const updated = mergeGlobalHistoryOnAppend(prev, entry);
|
||||
if (updated === prev) return prev;
|
||||
// Persist immediately so crash between commit and layout effect cannot drop history.
|
||||
// Store republish is also done in useLayoutEffect for load/storage-event paths.
|
||||
localStorageAdapter.write(STORAGE_KEY_SHELL_HISTORY, updated);
|
||||
return updated;
|
||||
});
|
||||
const generation = shellHistoryGenerationRef.current;
|
||||
// Yield the input turn before history rendering and synchronous storage work.
|
||||
// Persist in the next task to keep the crash-loss window small.
|
||||
setTimeout(() => {
|
||||
if (generation !== shellHistoryGenerationRef.current) return;
|
||||
setShellHistory((prev) => {
|
||||
if (generation !== shellHistoryGenerationRef.current) return prev;
|
||||
const updated = mergeGlobalHistoryOnAppend(prev, entry);
|
||||
if (updated === prev) return prev;
|
||||
localStorageAdapter.write(STORAGE_KEY_SHELL_HISTORY, updated);
|
||||
return updated;
|
||||
});
|
||||
}, 0);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const clearShellHistory = useCallback(() => {
|
||||
shellHistoryGenerationRef.current += 1;
|
||||
setShellHistory([]);
|
||||
localStorageAdapter.write(STORAGE_KEY_SHELL_HISTORY, []);
|
||||
publishShellHistorySnapshot([]);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
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 { act, create } from 'react-test-renderer';
|
||||
|
||||
import {
|
||||
collectSidePanelPanes,
|
||||
|
||||
@@ -79,6 +79,17 @@ test('sync persistence survives restart beyond the local-only history limits', (
|
||||
assert.equal(localOnly[0].messages.length, 200);
|
||||
});
|
||||
|
||||
test('sync collection after restart includes overflow before clearing it', () => {
|
||||
const primary = session();
|
||||
const overflow = { ...session(), id: 'overflow-chat', updatedAt: 1 };
|
||||
save([primary], true);
|
||||
storage.set(keys.STORAGE_KEY_AI_SESSIONS_OVERFLOW, JSON.stringify([overflow]));
|
||||
snapshots.setLatestAISessionsSnapshot(null as unknown as AISession[]);
|
||||
assert.deepEqual(collectAiSessionsForSync()?.map(value => value.id), [primary.id, overflow.id]);
|
||||
assert.equal(storage.has(keys.STORAGE_KEY_AI_SESSIONS_OVERFLOW), false);
|
||||
assert.deepEqual(JSON.parse(storage.get(keys.STORAGE_KEY_AI_SESSIONS)!).map((value: AISession) => value.id), [primary.id, overflow.id]);
|
||||
});
|
||||
|
||||
test('failed history persistence refuses upload without pruning the cloud representation', async () => {
|
||||
save([session()]);
|
||||
const original = globalThis.localStorage.setItem;
|
||||
@@ -208,13 +219,15 @@ test('replacement stops active turns and waits for finalizers before persisting
|
||||
globalThis.localStorage.setItem = (key, value) => { if (key === keys.STORAGE_KEY_AI_SESSIONS) order.push('persist'); original(key, value); };
|
||||
const incoming = { ...session(), updatedAt: 3, messages: [...session().messages,
|
||||
{ id: 'remote', role: 'user' as const, content: 'Remote', timestamp: 3 }] };
|
||||
await applySyncPayload(remotePayload(remove ? [] : [incoming]), { importVaultData: () => undefined });
|
||||
await applyLocalVaultPayload(remotePayload(remove ? [] : [incoming]), { importVaultData: () => undefined }, {
|
||||
prepareConvergentRestore: async () => async () => {},
|
||||
});
|
||||
assert.ok(order.indexOf('cancel') < order.indexOf('settled'));
|
||||
assert.ok(order.indexOf('settled') < order.indexOf('persist'));
|
||||
assert.ok(order.indexOf('persist') < order.indexOf('cleanup'));
|
||||
assert.equal(hook!.abortControllersRef.current.has('chat'), false);
|
||||
if (remove) assert.deepEqual(getAISessionsSnapshot().sessions, []);
|
||||
else assert.ok(getAISessionsSnapshot().sessions[0].messages.some(message => message.content === 'Settled'));
|
||||
else assert.equal(getAISessionsSnapshot().sessions[0].messages.at(-1)?.content, 'Remote');
|
||||
wait.mock.restore();
|
||||
globalThis.localStorage.setItem = original;
|
||||
await act(async () => { hook!.setStreamingForScope('chat', false); });
|
||||
@@ -226,6 +239,44 @@ test('replacement stops active turns and waits for finalizers before persisting
|
||||
}
|
||||
});
|
||||
|
||||
test('cloud sync preserves an active trimmed conversation and its native thread', async () => {
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
let hook: UseAIChatStreamingReturn;
|
||||
function Harness() {
|
||||
hook = useAIChatStreaming({ maxIterations: 1, addMessageToSession: () => {}, updateLastMessage: () => {}, updateMessageById: () => {} });
|
||||
return null;
|
||||
}
|
||||
let renderer: ReactTestRenderer;
|
||||
await act(async () => { renderer = create(React.createElement(Harness)); });
|
||||
const calls: string[] = [];
|
||||
const controller = new AbortController();
|
||||
const messages = Array.from({ length: 501 }, (_, i) => ({ id: `m-${i}`, role: 'user' as const, content: `Message ${i}`, timestamp: i }));
|
||||
const remote = { ...session(), agentId: 'codex', messages };
|
||||
// Appending the 501st message trims the oldest message locally.
|
||||
const local = { ...remote, messages: messages.slice(-500), externalSessionId: 'native-thread' };
|
||||
save([local]);
|
||||
hook!.abortControllersRef.current.set('chat', controller);
|
||||
await act(async () => { hook!.setStreamingForScope('chat', true); });
|
||||
Object.assign(window, { netcatty: {
|
||||
aiCattyCancelExec: async () => { calls.push('cancel'); },
|
||||
aiSdkAgentCancel: async () => { calls.push('sdk-cancel'); return { ok: true }; },
|
||||
aiSdkAgentCleanup: async () => { calls.push('cleanup'); return { ok: true }; },
|
||||
} });
|
||||
try {
|
||||
for (const incoming of [[remote], []]) {
|
||||
await applySyncPayload(remotePayload(incoming), { importVaultData: () => undefined });
|
||||
assert.equal(controller.signal.aborted, false);
|
||||
assert.deepEqual(calls, []);
|
||||
assert.deepEqual(getAISessionsSnapshot().sessions, [local]);
|
||||
assert.equal(JSON.parse(storage.get(keys.STORAGE_KEY_AI_SESSIONS)!)[0].externalSessionId, 'native-thread');
|
||||
}
|
||||
} finally {
|
||||
hook!.abortControllersRef.current.delete('chat');
|
||||
await act(async () => { hook!.setStreamingForScope('chat', false); renderer!.unmount(); });
|
||||
delete (window as unknown as { netcatty?: unknown }).netcatty;
|
||||
}
|
||||
});
|
||||
|
||||
test('local restore replaces later sessions and later turns with the backup snapshot', async () => {
|
||||
const backedUp = session();
|
||||
const later = { ...session(), updatedAt: 3, messages: [...session().messages,
|
||||
|
||||
@@ -51,6 +51,7 @@ import { sanitizeQuickMessages } from '../infrastructure/ai/quickMessages';
|
||||
import { emitAIStateChanged } from './state/aiStateEvents';
|
||||
import {
|
||||
latestAISessionsSnapshot,
|
||||
readSessionsFromStorage,
|
||||
setLatestAISessionsSnapshot,
|
||||
writeSessionsForStorage,
|
||||
cleanupSdkAgentSessions,
|
||||
@@ -1073,8 +1074,7 @@ export function collectAiSessionsForSync(): SyncPayload['aiSessions'] {
|
||||
|
||||
function collectLocalAiSessions(): NonNullable<SyncPayload['aiSessions']> {
|
||||
return latestAISessionsSnapshot
|
||||
?? localStorageAdapter.read<SyncPayload['aiSessions']>(STORAGE_KEY_AI_SESSIONS)
|
||||
?? [];
|
||||
?? readSessionsFromStorage();
|
||||
}
|
||||
|
||||
/** Build the portable payload; device-local data is added by the backup builder. */
|
||||
@@ -1275,6 +1275,8 @@ export async function buildLocalVaultPayloadAsync(
|
||||
|
||||
/** Merge downloaded chat data through the existing state and persistence boundary. */
|
||||
async function applyAiSessionData(sessions: NonNullable<SyncPayload['aiSessions']>, includeLocalOnlyData: boolean): Promise<void> {
|
||||
const { isAIChatSessionStreaming, stopAIChatSessionBeforeReplacement } = await import('./state/useAIChatStreaming');
|
||||
const preserveActive = (id: string) => !includeLocalOnlyData && isAIChatSessionStreaming(id);
|
||||
const incoming = includeLocalOnlyData
|
||||
? sessions
|
||||
: sessions.map(stripAiSessionDeviceState);
|
||||
@@ -1282,26 +1284,29 @@ async function applyAiSessionData(sessions: NonNullable<SyncPayload['aiSessions'
|
||||
const incomingById = new Map(incoming.map((session) => [session.id, session]));
|
||||
const portableMessages = (value: typeof incoming[number]) => stripAiSessionPayloadForSync([value])[0].messages;
|
||||
const affectedIds = collectLocalAiSessions().filter((local) => {
|
||||
if (preserveActive(local.id)) return false;
|
||||
const next = incomingById.get(local.id);
|
||||
if (!next) return true;
|
||||
const candidate = includeLocalOnlyData ? next : mergeAiSessionLists([local], [next])[0];
|
||||
return JSON.stringify(portableMessages(local)) !== JSON.stringify(portableMessages(candidate));
|
||||
}).map((session) => session.id);
|
||||
if (affectedIds.length > 0) {
|
||||
const { stopAIChatSessionBeforeReplacement } = await import('./state/useAIChatStreaming');
|
||||
await Promise.all(affectedIds.map(stopAIChatSessionBeforeReplacement));
|
||||
}
|
||||
// Stop finalizers can finish the last local message. Read it again before
|
||||
// merging so the stopped turn cannot write into a replaced/deleted session.
|
||||
const localSessions = collectLocalAiSessions();
|
||||
const localById = new Map(localSessions.map((session) => [session.id, session]));
|
||||
const removedIds = localSessions.filter((session) => !incomingIds.has(session.id)).map((session) => session.id);
|
||||
const removedIds = localSessions.filter((session) => !incomingIds.has(session.id) && !preserveActive(session.id)).map((session) => session.id);
|
||||
const resetSdkSessions: string[] = [];
|
||||
// The sync merge has already decided which session IDs survive. Backups
|
||||
// restore their exact transcript; cloud survivors still retain local turns.
|
||||
const candidates = includeLocalOnlyData ? incoming
|
||||
: mergeAiSessionLists(localSessions.filter((session) => incomingIds.has(session.id)), incoming);
|
||||
const mergedSessions = candidates.map((session) => {
|
||||
// Keep active cloud sessions intact until a later sync, including remote deletions.
|
||||
const retainedActive = localSessions.filter((session) => preserveActive(session.id));
|
||||
const mergedSessions = [...candidates.filter((session) => !preserveActive(session.id)), ...retainedActive].map((session) => {
|
||||
if (preserveActive(session.id)) return session;
|
||||
// Native SDK threads belong to this device. Reuse the local thread
|
||||
// only while it already contains the entire merged transcript.
|
||||
const local = localById.get(session.id);
|
||||
|
||||
@@ -40,3 +40,35 @@ test('terminal side panel tools share one primary toolbar height', () => {
|
||||
assert.match(source, /TERMINAL_SIDE_PANEL_INNER_HEADER_CLASS/);
|
||||
}
|
||||
});
|
||||
|
||||
test('/rename and /chats panel commands stay out of the agent message path', () => {
|
||||
const sidePanel = preparingSource;
|
||||
// Panel implements the commands with updateSessionTitle + a note state —
|
||||
// never addMessageToSession, so the commands cannot leak into chat history.
|
||||
assert.match(sidePanel, /handleRenameSession = useCallback/);
|
||||
assert.match(sidePanel, /handleListChats = useCallback/);
|
||||
assert.match(sidePanel, /updateSessionTitle\(sessionId, title\)/);
|
||||
assert.match(sidePanel, /setPanelCommandNote\(formatAiChatsListingNote\(entries, t\)\)/);
|
||||
const renameHandler = sidePanel.slice(
|
||||
sidePanel.indexOf('handleRenameSession = useCallback'),
|
||||
sidePanel.indexOf('const handleRenameSlashCommand'),
|
||||
);
|
||||
assert.doesNotMatch(renameHandler, /addMessageToSession/);
|
||||
const chatsHandler = sidePanel.slice(
|
||||
sidePanel.indexOf('handleListChats = useCallback'),
|
||||
sidePanel.indexOf('const handleSend'),
|
||||
);
|
||||
assert.doesNotMatch(chatsHandler, /addMessageToSession/);
|
||||
// Wiring reaches AIChatPanelContent.
|
||||
assert.match(sidePanel, /onRenameActiveChat=\{handleRenameSlashCommand\}/);
|
||||
assert.match(sidePanel, /onListChats=\{handleListChats\}/);
|
||||
});
|
||||
|
||||
test('AIChatPanelContent renders the panel command note and wires rename/list props', () => {
|
||||
assert.match(panelSource, /panelCommandNote \? \(/);
|
||||
assert.match(panelSource, /role="status"/);
|
||||
assert.match(panelSource, /onDismissPanelCommandNote/);
|
||||
assert.match(panelSource, /onRenameSession=\{onRenameActiveChat\}/);
|
||||
assert.match(panelSource, /onListChats=\{onListChats\}/);
|
||||
assert.match(panelSource, /onRename=\{onRenameSession\}/);
|
||||
});
|
||||
@@ -57,6 +57,20 @@ interface AIChatPanelContentProps {
|
||||
setInputValue: (value: string) => void;
|
||||
handleSend: () => void;
|
||||
handleCompact: () => void;
|
||||
/** Rename a chat by id (history drawer edit affordance). Panel action, never agent content. */
|
||||
onRenameSession?: (sessionId: string, title: string) => void;
|
||||
/** `/rename <title>` for the current chat. Panel action, never agent content. */
|
||||
onRenameActiveChat?: (title: string) => void;
|
||||
/** `/chats`: list the chats visible to this panel. Panel action, never agent content. */
|
||||
onListChats?: () => void;
|
||||
/** `/rebind <n>`: rebind a dangling chat to this panel's scope. Panel action, never agent content. */
|
||||
onRebindChat?: (arg: string) => void;
|
||||
/** `/chats` listing output, rendered as a system-style note above the composer. */
|
||||
panelCommandNote?: string | null;
|
||||
onDismissPanelCommandNote?: () => void;
|
||||
/** Manual durability escape hatch: export/import the whole session store. */
|
||||
onExportSessions?: () => void;
|
||||
onImportSessions?: () => void;
|
||||
/** Undo last turn is offered at a safe boundary (never mid-tool / mid-compaction). */
|
||||
canUndoLastTurn?: boolean;
|
||||
handleUndoLastTurn?: () => void;
|
||||
@@ -142,6 +156,14 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
setInputValue,
|
||||
handleSend,
|
||||
handleCompact,
|
||||
onRenameSession,
|
||||
onRenameActiveChat,
|
||||
onListChats,
|
||||
onRebindChat,
|
||||
panelCommandNote,
|
||||
onDismissPanelCommandNote,
|
||||
onExportSessions,
|
||||
onImportSessions,
|
||||
canUndoLastTurn = false,
|
||||
handleUndoLastTurn,
|
||||
canCompact = false,
|
||||
@@ -309,6 +331,9 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
activeSessionId={activeSessionId}
|
||||
onSelect={sending ? () => undefined : handleSelectSession}
|
||||
onDelete={handleDeleteSession}
|
||||
onRename={onRenameSession}
|
||||
onExportSessions={onExportSessions}
|
||||
onImportSessions={onImportSessions}
|
||||
onClose={() => setShowHistory(false)}
|
||||
/>
|
||||
</React.Profiler>
|
||||
@@ -369,6 +394,21 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
{!hideInput && (
|
||||
<React.Profiler {...getAIPanelProfilerProps('AIChatPanel.Input')}>
|
||||
<div>
|
||||
{panelCommandNote ? (
|
||||
<div role="status" className="mx-3 mb-1.5 rounded-md border border-border/50 bg-muted/30 px-2.5 py-1.5 text-[11px] leading-4 text-muted-foreground">
|
||||
<span className="block max-h-48 overflow-y-auto whitespace-pre-wrap break-words">{panelCommandNote}</span>
|
||||
{onDismissPanelCommandNote && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('common.close')}
|
||||
onClick={onDismissPanelCommandNote}
|
||||
className="mt-1 text-[11px] text-muted-foreground/60 underline-offset-2 transition-colors hover:text-foreground hover:underline cursor-pointer"
|
||||
>
|
||||
{t('common.close')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
{steerWarning ? (
|
||||
<div role="status" className="mx-3 mb-1.5 rounded-md border border-amber-500/25 bg-amber-500/10 px-2.5 py-1.5 text-[11px] leading-4 text-amber-600 dark:text-amber-400">
|
||||
{steerWarning}
|
||||
@@ -396,6 +436,9 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
onChange={setInputValue}
|
||||
onSend={handleSend}
|
||||
onCompact={handleCompact}
|
||||
onRenameSession={onRenameActiveChat}
|
||||
onListChats={onListChats}
|
||||
onRebindChat={onRebindChat}
|
||||
canCompact={canCompact}
|
||||
onSteer={handleSteer}
|
||||
onStop={handleStop}
|
||||
|
||||
@@ -3,7 +3,7 @@ import test from "node:test";
|
||||
import React from "react";
|
||||
|
||||
import type { AISession } from "../infrastructure/ai/types.ts";
|
||||
import { MESSAGES_BY_LOCALE } from "../application/i18n/messages.ts";
|
||||
import { getLoadedLocaleMessages, loadLocaleMessages } from "../application/i18n/messages.ts";
|
||||
import { createDomRenderer, dispatchDomEvent, installDomEnvironment, runWithAct } from "./test-support/renderReactDom.tsx";
|
||||
|
||||
test("history drawer filters, pages, clears and explains the bounded search in every locale", async () => {
|
||||
@@ -107,9 +107,11 @@ test("history drawer filters, pages, clears and explains the bounded search in e
|
||||
assert.equal(closed, 1);
|
||||
|
||||
for (const locale of ["en", "zh-CN", "zh-TW", "es", "ru"]) {
|
||||
// Non-English dictionaries load on demand.
|
||||
await loadLocaleMessages(locale);
|
||||
await render(sessions, locale);
|
||||
await enterQuery("no-such-content");
|
||||
const messages = MESSAGES_BY_LOCALE[locale];
|
||||
const messages = getLoadedLocaleMessages(locale)!;
|
||||
const input = renderer.container.querySelector("input")!;
|
||||
const hint = dom.document.getElementById(input.getAttribute("aria-describedby")!);
|
||||
for (const key of ["ai.chat.searchSessions", "ai.chat.searchSessionsHint", "ai.chat.noMatchingSessions"]) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useEffect, useId, useRef, useState } from 'react';
|
||||
import { Search, Trash2, X } from 'lucide-react';
|
||||
import { Download, Pencil, Search, Trash2, Upload, X } from 'lucide-react';
|
||||
import type { AISession } from '../infrastructure/ai/types';
|
||||
import { useI18n } from '../application/i18n/I18nProvider';
|
||||
import { cn } from '../lib/utils';
|
||||
@@ -19,6 +19,12 @@ interface SessionHistoryDrawerProps {
|
||||
activeSessionId: string | null;
|
||||
onSelect: (sessionId: string) => void;
|
||||
onDelete: (e: React.MouseEvent, sessionId: string) => void;
|
||||
/** Rename a chat inline (issue #4015 R5). Empty titles are ignored. */
|
||||
onRename?: (sessionId: string, title: string) => void;
|
||||
/** Manual durability escape hatch: export the whole store to a JSON file. */
|
||||
onExportSessions?: () => void;
|
||||
/** Import sessions from a JSON export; merges by id, newer wins. */
|
||||
onImportSessions?: () => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
@@ -30,11 +36,17 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
|
||||
activeSessionId,
|
||||
onSelect,
|
||||
onDelete,
|
||||
onRename,
|
||||
onExportSessions,
|
||||
onImportSessions,
|
||||
onClose,
|
||||
}) => {
|
||||
const { t } = useI18n();
|
||||
const [renderCount, setRenderCount] = useState(SESSION_RENDER_BATCH);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [renamingSessionId, setRenamingSessionId] = useState<string | null>(null);
|
||||
const [renameDraft, setRenameDraft] = useState('');
|
||||
const renameInputRef = useRef<HTMLInputElement>(null);
|
||||
const searchHintId = useId();
|
||||
const searchInputRef = useRef<HTMLInputElement>(null);
|
||||
const { filteredSessions, isSearching } = useSessionHistorySearch(
|
||||
@@ -52,16 +64,69 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
|
||||
const displayedSessions = filteredSessions.slice(0, renderCount);
|
||||
const hiddenSessionCount = Math.max(0, filteredSessions.length - renderCount);
|
||||
|
||||
useEffect(() => {
|
||||
if (renamingSessionId) renameInputRef.current?.focus();
|
||||
}, [renamingSessionId]);
|
||||
|
||||
const beginRename = (sessionId: string, currentTitle: string) => {
|
||||
setRenamingSessionId(sessionId);
|
||||
setRenameDraft(currentTitle);
|
||||
};
|
||||
|
||||
const commitRename = () => {
|
||||
if (renamingSessionId && renameDraft.trim()) {
|
||||
onRename?.(renamingSessionId, renameDraft.trim());
|
||||
}
|
||||
setRenamingSessionId(null);
|
||||
setRenameDraft('');
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col min-h-0">
|
||||
<div className="px-4 py-2.5 flex items-center justify-between shrink-0 border-b border-border/30">
|
||||
<span className="text-[13px] font-medium text-foreground/80">{t('ai.chat.allSessions')}</span>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-[12px] text-muted-foreground/60 hover:text-muted-foreground transition-colors cursor-pointer"
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
<div className="flex items-center gap-2">
|
||||
{onImportSessions && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onImportSessions();
|
||||
}}
|
||||
className="text-[12px] text-muted-foreground/60 hover:text-muted-foreground transition-colors cursor-pointer"
|
||||
aria-label={t('ai.chat.importSessions')}
|
||||
>
|
||||
<Upload size={14} />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t('ai.chat.importSessions')}</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
{onExportSessions && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onExportSessions();
|
||||
}}
|
||||
className="text-[12px] text-muted-foreground/60 hover:text-muted-foreground transition-colors cursor-pointer"
|
||||
aria-label={t('ai.chat.exportSessions')}
|
||||
>
|
||||
<Download size={14} />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t('ai.chat.exportSessions')}</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-[12px] text-muted-foreground/60 hover:text-muted-foreground transition-colors cursor-pointer"
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="px-3 py-2 shrink-0 border-b border-border/30">
|
||||
<div className="relative">
|
||||
@@ -146,12 +211,52 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
|
||||
)}
|
||||
>
|
||||
<span className={SESSION_HISTORY_ROW_CLASSNAMES.title}>
|
||||
{session.title || t('ai.chat.untitled')}
|
||||
{renamingSessionId === session.id ? (
|
||||
<Input
|
||||
ref={renameInputRef}
|
||||
type="text"
|
||||
value={renameDraft}
|
||||
aria-label={t('ai.chat.renameChat')}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onKeyDown={(e) => {
|
||||
e.stopPropagation();
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
commitRename();
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
setRenamingSessionId(null);
|
||||
setRenameDraft('');
|
||||
}
|
||||
}}
|
||||
onChange={(e) => setRenameDraft(e.target.value)}
|
||||
onBlur={commitRename}
|
||||
className="h-6 text-[12px]"
|
||||
/>
|
||||
) : (
|
||||
session.title || t('ai.chat.untitled')
|
||||
)}
|
||||
</span>
|
||||
<div className={SESSION_HISTORY_ROW_CLASSNAMES.meta}>
|
||||
<span className={SESSION_HISTORY_ROW_CLASSNAMES.time}>
|
||||
{timeStr}
|
||||
</span>
|
||||
{onRename && renamingSessionId !== session.id && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
beginRename(session.id, session.title || '');
|
||||
}}
|
||||
className={SESSION_HISTORY_ROW_CLASSNAMES.deleteButton}
|
||||
>
|
||||
<Pencil size={12} />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t('ai.chat.renameChat')}</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
|
||||
Loaded 100 of 532 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user