diff --git a/App.tsx b/App.tsx index 071eb7649..7e93b7fbe 100755 --- a/App.tsx +++ b/App.tsx @@ -291,15 +291,11 @@ function App({ settings }: { settings: SettingsState }) { draggingSessionId, setDraggingSessionId, sessionRenameTarget, - sessionRenameValue, - setSessionRenameValue, startSessionRename, renameSessionInline, submitSessionRename, resetSessionRename, workspaceRenameTarget, - workspaceRenameValue, - setWorkspaceRenameValue, startWorkspaceRename, submitWorkspaceRename, resetWorkspaceRename, @@ -1945,10 +1941,7 @@ function App({ settings }: { settings: SettingsState }) { resetWorkspaceRename, resolvedTheme, sessionRenameTarget, - sessionRenameValue, setActiveTabId, - setSessionRenameValue, - setWorkspaceRenameValue, settings, startSessionRename, renameSessionInline, @@ -1960,8 +1953,7 @@ function App({ settings }: { settings: SettingsState }) { toggleConnectionLogSaved, updateConnectionLog, workspaceRenameTarget, - workspaceRenameValue, - }), [accentMode, clearUnsavedConnectionLogs, closeLogView, customAccent, deleteConnectionLog, handleEndSessionDrag, handleOpenQuickSwitcher, handleOpenSettings, handleRootContextMenu, handleSyncNowManual, isMacClient, logViews, openLogView, orderedTabsWithEditors, orphanSessionsForShell, reorderWorkTabs, resetSessionRename, resetWorkspaceRename, resolvedTheme, sessionRenameTarget, sessionRenameValue, setActiveTabId, setSessionRenameValue, setWorkspaceRenameValue, settings, startSessionRename, renameSessionInline, startWorkspaceRename, submitSessionRename, submitWorkspaceRename, t, themeById, toggleConnectionLogSaved, updateConnectionLog, workspaceRenameTarget, workspaceRenameValue]); + }), [accentMode, clearUnsavedConnectionLogs, closeLogView, customAccent, deleteConnectionLog, handleEndSessionDrag, handleOpenQuickSwitcher, handleOpenSettings, handleRootContextMenu, handleSyncNowManual, isMacClient, logViews, openLogView, orderedTabsWithEditors, orphanSessionsForShell, reorderWorkTabs, resetSessionRename, resetWorkspaceRename, resolvedTheme, sessionRenameTarget, setActiveTabId, settings, startSessionRename, renameSessionInline, startWorkspaceRename, submitSessionRename, submitWorkspaceRename, t, themeById, toggleConnectionLogSaved, updateConnectionLog, workspaceRenameTarget]); const appDialogsDomain = useMemo(() => ({ addToWorkspaceDialog, diff --git a/application/app/AppHostTreeLayer.test.ts b/application/app/AppHostTreeLayer.test.ts index 3f2c78448..3a74fc919 100644 --- a/application/app/AppHostTreeLayer.test.ts +++ b/application/app/AppHostTreeLayer.test.ts @@ -53,3 +53,8 @@ test('shared host tree forwards work-surface host management callbacks', () => { assert.match(hostTreeLayerSource, /onNewHost=\{onNewHost\}/); assert.match(hostTreeLayerSource, /onEditHost=\{onEditHost\}/); }); + +test('shared host tree layer is memoized with a custom areEqual', () => { + assert.match(hostTreeLayerSource, /memo\(AppHostTreeLayerInner,\s*appHostTreeLayerAreEqual\)/); +}); + diff --git a/application/app/AppHostTreeLayer.tsx b/application/app/AppHostTreeLayer.tsx index 40006a0f0..767d22143 100644 --- a/application/app/AppHostTreeLayer.tsx +++ b/application/app/AppHostTreeLayer.tsx @@ -1,4 +1,4 @@ -import React, { useMemo } from 'react'; +import React, { memo, useMemo } from 'react'; import { useActiveTabId } from '../state/activeTabStore'; import type { EditorTabChrome } from '../state/editorTabStore'; @@ -47,7 +47,33 @@ export function getAppHostTreeLayerStyle(surfaceVisible: boolean): React.CSSProp }; } -export const AppHostTreeLayer: React.FC = ({ +function appHostTreeLayerAreEqual( + prev: AppHostTreeLayerProps, + next: AppHostTreeLayerProps, +): boolean { + return prev.enabled === next.enabled + && prev.hosts === next.hosts + && prev.customGroups === next.customGroups + && prev.groupConfigs === next.groupConfigs + && prev.sessions === next.sessions + && prev.workspaces === next.workspaces + && prev.editorTabs === next.editorTabs + && prev.logViews === next.logViews + && prev.orderedTabs === next.orderedTabs + && prev.accentMode === next.accentMode + && prev.currentTerminalTheme === next.currentTerminalTheme + && prev.customAccent === next.customAccent + && prev.followAppTerminalTheme === next.followAppTerminalTheme + && prev.hostById === next.hostById + && prev.themeById === next.themeById + && prev.resolveSessionAppearance === next.resolveSessionAppearance + && prev.onConnect === next.onConnect + && prev.onNewHost === next.onNewHost + && prev.onEditHost === next.onEditHost + && prev.onCreateLocalTerminal === next.onCreateLocalTerminal; +} + +const AppHostTreeLayerInner: React.FC = ({ enabled, hosts, customGroups, @@ -154,3 +180,6 @@ export const AppHostTreeLayer: React.FC = ({ ); }; + +export const AppHostTreeLayer = memo(AppHostTreeLayerInner, appHostTreeLayerAreEqual); +AppHostTreeLayer.displayName = 'AppHostTreeLayer'; diff --git a/application/app/AppView.tsx b/application/app/AppView.tsx index 44a236696..72c235bc5 100644 --- a/application/app/AppView.tsx +++ b/application/app/AppView.tsx @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import React, { Suspense, lazy, memo, useCallback, useEffect, useMemo } from 'react'; +import React, { Suspense, lazy, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { AlertTriangle, Download, Trash2 } from 'lucide-react'; import { activeTabStore, toEditorTabId, useIsEditorTabActive } from '../state/activeTabStore'; import { editorTabStore } from '../state/editorTabStore'; @@ -12,7 +12,7 @@ import { QuickScriptEditorDialog } from '../../components/scripts/QuickScriptEdi import { AddToWorkspaceDialog } from '../../components/workspace/AddToWorkspaceDialog'; import { KeyboardInteractiveModal } from '../../components/KeyboardInteractiveModal'; import { PassphraseModal } from '../../components/PassphraseModal'; -import { UnsavedChangesProvider } from '../../components/editor/UnsavedChangesDialog'; +import { UnsavedChangesProvider, promptUnsavedChanges } from '../../components/editor/UnsavedChangesDialog'; import { SnippetExecutionProvider } from '../../components/SnippetExecutionProvider'; import { Button } from '../../components/ui/button'; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '../../components/ui/dialog'; @@ -66,6 +66,68 @@ const TextEditorTabFallback = ({ tabId }: { tabId: string }) => { ); }; +/** Local draft so keystrokes do not rebuild App chrome domain every character. */ +function RenameDraftDialog({ + open, + inputId, + initialName, + title, + nameLabel, + placeholder, + cancelLabel, + saveLabel, + onCancel, + onSave, +}: { + open: boolean; + inputId: string; + initialName: string; + title: string; + nameLabel: string; + placeholder: string; + cancelLabel: string; + saveLabel: string; + onCancel: () => void; + onSave: (name: string) => void; +}) { + const [draft, setDraft] = useState(initialName); + useEffect(() => { + if (open) setDraft(initialName); + }, [open, initialName]); + + return ( + { + if (!nextOpen) onCancel(); + }}> + + + {title} + +
+ + setDraft(e.target.value)} + onKeyDown={(e) => { + if (e.key !== 'Enter') return; + if (!draft.trim()) return; + onSave(draft); + }} + autoFocus + placeholder={placeholder} + /> +
+ + + + +
+
+ ); +} + + export type AppViewProps = { domains: AppViewDomains; }; @@ -127,14 +189,14 @@ function AppViewInner({ domains }: AppViewProps) { keyBindings, keyboardInteractiveQueue, keys, logViews, managedSources, navigateToSection, noteGroups, notes, openLogView, openNoteRequest, orderedTabsWithEditors, orphanSessions, passphraseQueue, protocolSelectHost, proxyProfiles, portForwardingRules, quickResults, quickSearch, removeSessionFromWorkspace, reorderWorkTabs, reorderWorkspaceSessions, resolveEmptyVaultConflict, resolvedTheme, resolveSessionAppearance, runSnippet, sessionLogsDir, sessionLogsEnabled, sessionLogsFormat, sessionLogsTimestampsEnabled, sessionRenameTarget, sshDebugLogsEnabled, - sessionRenameValue, sessions, setActiveTabId, setDeepLinkHostDraft, setDraggingSessionId, setEditorWordWrap, - setNavigateToSection, setSessionRenameValue, setTerminalFontFamilyId, setTerminalFontSize, setVaultFocusRequest, updateSessionFontSize, updateSessionRestoreCwd, updateSessionDynamicTitle, updateSessionCodingCliProvider, clearSessionFontSizeOverride, - setWorkspaceFocusedSession, setWorkspaceRenameValue, settings, sftpAutoOpenSidebar, sftpFollowTerminalCwd, setSftpFollowTerminalCwd, sftpAutoSync, sftpDefaultViewMode, sftpDoubleClickBehavior, + sessions, setActiveTabId, setDeepLinkHostDraft, setDraggingSessionId, setEditorWordWrap, + setNavigateToSection, setTerminalFontFamilyId, setTerminalFontSize, setVaultFocusRequest, updateSessionFontSize, updateSessionRestoreCwd, updateSessionDynamicTitle, updateSessionCodingCliProvider, clearSessionFontSizeOverride, + setWorkspaceFocusedSession, settings, sftpAutoOpenSidebar, sftpFollowTerminalCwd, setSftpFollowTerminalCwd, sftpAutoSync, sftpDefaultViewMode, sftpDoubleClickBehavior, sftpShowHiddenFiles, sftpUseCompressedUpload, snippetPackages, snippets, splitSessionWithCurrentShell, startSessionRename, startWorkspaceRename, submitSessionRename, submitWorkspaceRename, t, terminalFontFamilyId, terminalFontSize, terminalSettings, terminalThemeId, themeById, toggleBroadcast, toggleConnectionLogSaved, toggleScriptsSidePanelRef, toggleSidePanelRef, toggleWorkspaceViewMode, unmanageSource, updateConnectionLog, readPersistedHosts, readPersistedManagedSources, updateCustomGroups, updateGroupConfigs, updateHostDistro, updateHosts, updateIdentities, updateKeys, updateKnownHosts, updateManagedSources, - updateNoteGroups, updateNotes, updateProxyProfiles, updateSnippetPackages, updateSnippets, updateSplitSizes, updateTerminalSetting, vaultFocusRequest, workspaceRenameTarget, workspaceRenameValue, workspaces, + updateNoteGroups, updateNotes, updateProxyProfiles, updateSnippetPackages, updateSnippets, updateSplitSizes, updateTerminalSetting, vaultFocusRequest, workspaceRenameTarget, workspaces, VaultViewContainer, SftpViewMount, TerminalLayerMount, LogViewWrapper, } = ctx; @@ -211,6 +273,70 @@ function AppViewInner({ domains }: AppViewProps) { pluginViewTabStore.close(tabId); }, [orderedTabsWithEditors]); + const orderedTabsWithEditorsRef = useRef(orderedTabsWithEditors); + orderedTabsWithEditorsRef.current = orderedTabsWithEditors; + + // Stable for TopTabs memo: read ordered tabs via ref; prompt via module singleton. + const handleRequestCloseEditorTab = useCallback(async (id: string): Promise => { + const tab = editorTabStore.getTab(id); + if (!tab) return false; + + const closeEditorAndActivateNeighbor = () => { + const closingTabId = toEditorTabId(id); + const list = orderedTabsWithEditorsRef.current; + const idx = list.indexOf(closingTabId); + releaseEditorTabSaveCoordinator(id); + editorTabStore.close(id); + if (activeTabStore.getActiveTabId() !== closingTabId) return; + const next = list[idx - 1] ?? list[idx + 1] ?? 'vault'; + activeTabStore.setActiveTabId(next === closingTabId ? 'vault' : next); + }; + + const dirty = tab.content !== tab.baselineContent; + if (!dirty) { + closeEditorAndActivateNeighbor(); + return true; + } + const choice = await promptUnsavedChanges(tab.fileName); + if (choice === 'cancel') return false; + if (choice === 'discard') { + closeEditorAndActivateNeighbor(); + return true; + } + if (choice === 'save') { + const ok = await saveEditorTab(id); + if (!ok) { + const msg = editorTabStore.getTab(id)?.saveError ?? 'Save failed'; + toast.error(msg, 'SFTP'); + return false; + } + const latest = editorTabStore.getTab(id); + if (!latest || latest.content !== latest.baselineContent) return false; + closeEditorAndActivateNeighbor(); + return true; + } + + return false; + }, []); + + // Keep the hotkey ref current during render so Cmd/Ctrl+W never sees the + // App.tsx stub `() => false` between commit and useEffect. + handleRequestCloseEditorTabRef.current = handleRequestCloseEditorTab; + + const handleSaveSessionRename = useCallback((name: string) => { + if (!sessionRenameTarget) return; + if (!name.trim()) return; + submitSessionRename(sessionRenameTarget.id, name); + resetSessionRename(); + }, [resetSessionRename, sessionRenameTarget, submitSessionRename]); + + const handleSaveWorkspaceRename = useCallback((name: string) => { + if (!workspaceRenameTarget) return; + if (!name.trim()) return; + submitWorkspaceRename(workspaceRenameTarget.id, name); + resetWorkspaceRename(); + }, [resetWorkspaceRename, submitWorkspaceRename, workspaceRenameTarget]); + useEffect(() => { const catalog = buildPluginSettingScopeCatalog({ hosts, @@ -224,54 +350,7 @@ function AppViewInner({ domains }: AppViewProps) { return ( - {({ prompt }) => { - // Helper: close an editor tab and activate the neighbor (left-preference), or vault. - const closeEditorAndActivateNeighbor = (id: string) => { - const closingTabId = toEditorTabId(id); - const list = orderedTabsWithEditors; - const idx = list.indexOf(closingTabId); - releaseEditorTabSaveCoordinator(id); - editorTabStore.close(id); - if (activeTabStore.getActiveTabId() !== closingTabId) return; - const next = list[idx - 1] ?? list[idx + 1] ?? 'vault'; - activeTabStore.setActiveTabId(next === closingTabId ? 'vault' : next); - }; - - // Real dirty-confirm close handler. - const handleRequestCloseEditorTab = async (id: string): Promise => { - const tab = editorTabStore.getTab(id); - if (!tab) return false; - const dirty = tab.content !== tab.baselineContent; - if (!dirty) { - closeEditorAndActivateNeighbor(id); - return true; - } - const choice = await prompt(tab.fileName); - if (choice === 'cancel') return false; - if (choice === 'discard') { - closeEditorAndActivateNeighbor(id); - return true; - } - if (choice === 'save') { - const ok = await saveEditorTab(id); - if (!ok) { - const msg = editorTabStore.getTab(id)?.saveError ?? 'Save failed'; - toast.error(msg, 'SFTP'); - return false; - } - const latest = editorTabStore.getTab(id); - if (!latest || latest.content !== latest.baselineContent) return false; - closeEditorAndActivateNeighbor(id); - return true; - } - - return false; - }; - - // Expose to the hotkey dispatcher (Cmd/Ctrl+W). - handleRequestCloseEditorTabRef.current = handleRequestCloseEditorTab; - - return ( + {() => (
)} - { - if (!open) { - resetSessionRename(); - } - }}> - - - {t('dialog.renameSession.title')} - -
- - setSessionRenameValue(e.target.value)} - onKeyDown={(e) => { if (e.key === 'Enter') submitSessionRename(); }} - autoFocus - placeholder={t('placeholder.sessionName')} - /> -
- - - - -
-
+ + + - { - if (!open) { - resetWorkspaceRename(); - } - }}> - - - {t('dialog.renameWorkspace.title')} - -
- - setWorkspaceRenameValue(e.target.value)} - onKeyDown={(e) => { if (e.key === 'Enter') submitWorkspaceRename(); }} - autoFocus - placeholder={t('placeholder.workspaceName')} - /> -
- - - - -
-
{isCreateWorkspaceOpen && ( @@ -871,8 +919,7 @@ function AppViewInner({ domains }: AppViewProps) {
- ); - }} + )}
); diff --git a/application/state/aiPanelDiagnostics.ts b/application/state/aiPanelDiagnostics.ts new file mode 100644 index 000000000..a3e39a1d8 --- /dev/null +++ b/application/state/aiPanelDiagnostics.ts @@ -0,0 +1,85 @@ +import type React from 'react'; +import { + STORAGE_KEY_AI_PANEL_DIAGNOSTIC_HIDE, + STORAGE_KEY_AI_PANEL_DIAGNOSTIC_PROFILE, +} from '../../infrastructure/config/storageKeys'; +import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter'; + +export const AI_PANEL_DIAGNOSTIC_HIDE_KEY = STORAGE_KEY_AI_PANEL_DIAGNOSTIC_HIDE; +export const AI_PANEL_DIAGNOSTIC_PROFILE_KEY = STORAGE_KEY_AI_PANEL_DIAGNOSTIC_PROFILE; +export const AI_PANEL_FORCE_HIDE_ALL_CONTENT = false; +export const AI_PANEL_FORCE_HIDE_SHELL = false; + +export type AIPanelDiagnosticPart = + | 'all' + | 'attachments' + | 'header' + | 'history' + | 'input' + | 'markdown' + | 'messages' + | 'recent' + | 'toolcalls'; + +function readLocalStorageValue(key: string): string { + try { + return localStorageAdapter.readString(key) ?? ''; + } catch { + return ''; + } +} + +export function getAIPanelDiagnosticHiddenParts(): ReadonlySet { + if (AI_PANEL_FORCE_HIDE_ALL_CONTENT) { + return new Set(['all']); + } + const raw = readLocalStorageValue(AI_PANEL_DIAGNOSTIC_HIDE_KEY); + return new Set( + raw + .split(',') + .map((part) => part.trim().toLowerCase()) + .filter(Boolean), + ); +} + +export function isAIPanelDiagnosticPartHidden( + part: AIPanelDiagnosticPart, + hiddenParts = getAIPanelDiagnosticHiddenParts(), +): boolean { + return hiddenParts.has('all') || hiddenParts.has(part); +} + +export function isAIPanelDiagnosticsProfilingEnabled(): boolean { + const raw = readLocalStorageValue(AI_PANEL_DIAGNOSTIC_PROFILE_KEY).trim().toLowerCase(); + return raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on'; +} + +export function logAIPanelProfiler( + id: string, + phase: 'mount' | 'update' | 'nested-update', + actualDuration: number, + baseDuration: number, +): void { + if (!isAIPanelDiagnosticsProfilingEnabled()) return; + console.info( + `[AI panel profile] ${id} ${phase}: actual=${actualDuration.toFixed(1)}ms base=${baseDuration.toFixed(1)}ms`, + ); +} + +export function profileAIPanelCalculation(label: string, calculate: () => T): T { + if (!isAIPanelDiagnosticsProfilingEnabled()) return calculate(); + const startedAt = performance.now(); + try { + return calculate(); + } finally { + const elapsed = performance.now() - startedAt; + console.info(`[AI panel profile] ${label}: ${elapsed.toFixed(1)}ms`); + } +} + +export function getAIPanelProfilerProps(id: string): Pick { + return { + id, + onRender: logAIPanelProfiler, + }; +} diff --git a/application/state/appearanceChromeStore.test.ts b/application/state/appearanceChromeStore.test.ts new file mode 100644 index 000000000..621b284d3 --- /dev/null +++ b/application/state/appearanceChromeStore.test.ts @@ -0,0 +1,31 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { + getAppearanceChromeSnapshot, + publishAppearanceChromeSnapshot, + subscribeAppearanceChrome, +} from './appearanceChromeStore.ts'; + +test('appearanceChromeStore notifies subscribers only when accent fields change', () => { + const events: string[] = []; + const unsubscribe = subscribeAppearanceChrome(() => { + const snap = getAppearanceChromeSnapshot(); + events.push(`${snap.accentMode}:${snap.customAccent}`); + }); + + publishAppearanceChromeSnapshot({ accentMode: 'custom', customAccent: '#ff0000' }); + assert.equal(events.at(-1), 'custom:#ff0000'); + assert.equal(getAppearanceChromeSnapshot().customAccent, '#ff0000'); + + publishAppearanceChromeSnapshot({ accentMode: 'custom', customAccent: '#ff0000' }); + assert.equal(events.length, 1); + + publishAppearanceChromeSnapshot({ accentMode: 'custom', customAccent: '#00ff00' }); + assert.equal(events.at(-1), 'custom:#00ff00'); + + publishAppearanceChromeSnapshot({ accentMode: 'theme', customAccent: '#00ff00' }); + assert.equal(events.at(-1), 'theme:#00ff00'); + + unsubscribe(); +}); diff --git a/application/state/appearanceChromeStore.ts b/application/state/appearanceChromeStore.ts new file mode 100644 index 000000000..789395e87 --- /dev/null +++ b/application/state/appearanceChromeStore.ts @@ -0,0 +1,68 @@ +import { useSyncExternalStore } from 'react'; + +type Listener = () => void; + +export type AppearanceChromeSnapshot = { + accentMode: 'theme' | 'custom'; + customAccent: string; +}; + +const DEFAULT_SNAPSHOT: AppearanceChromeSnapshot = Object.freeze({ + accentMode: 'theme', + customAccent: '', +}); + +/** + * External store for app accent chrome so Terminal leaves can apply custom + * accent without TerminalLayer rebuilding on every color-picker drag tick. + */ +class AppearanceChromeStore { + private snapshot: AppearanceChromeSnapshot = DEFAULT_SNAPSHOT; + private listeners = new Set(); + + getSnapshot = (): AppearanceChromeSnapshot => this.snapshot; + + subscribe = (listener: Listener): (() => void) => { + this.listeners.add(listener); + return () => { + this.listeners.delete(listener); + }; + }; + + setSnapshot(next: AppearanceChromeSnapshot): void { + if ( + this.snapshot.accentMode === next.accentMode + && this.snapshot.customAccent === next.customAccent + ) { + return; + } + this.snapshot = next; + for (const listener of this.listeners) { + listener(); + } + } +} + +export const appearanceChromeStore = new AppearanceChromeStore(); + +export function publishAppearanceChromeSnapshot( + snapshot: AppearanceChromeSnapshot, +): void { + appearanceChromeStore.setSnapshot(snapshot); +} + +export function getAppearanceChromeSnapshot(): AppearanceChromeSnapshot { + return appearanceChromeStore.getSnapshot(); +} + +export function subscribeAppearanceChrome(listener: Listener): () => void { + return appearanceChromeStore.subscribe(listener); +} + +export function useAppearanceChromeStore(): AppearanceChromeSnapshot { + return useSyncExternalStore( + subscribeAppearanceChrome, + getAppearanceChromeSnapshot, + getAppearanceChromeSnapshot, + ); +} diff --git a/application/state/notesStore.test.ts b/application/state/notesStore.test.ts new file mode 100644 index 000000000..d4d309218 --- /dev/null +++ b/application/state/notesStore.test.ts @@ -0,0 +1,101 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { + EMPTY_NOTES_SNAPSHOT, + getEmptyNotesSnapshot, + getNotesActions, + getNotesSnapshot, + publishNotesSnapshot, + registerNotesActions, + subscribeNotes, + subscribeNotesNoop, +} from './notesStore.ts'; + +test('notesStore notifies subscribers only when snapshot identity changes', () => { + const events: number[] = []; + const unsubscribe = subscribeNotes(() => { + events.push(getNotesSnapshot().notes.length); + }); + + const firstNotes = [{ + id: 'n1', + title: 'One', + content: 'body', + tags: [], + createdAt: 1, + updatedAt: 1, + order: 1000, + }]; + const firstGroups = ['Ops']; + publishNotesSnapshot({ notes: firstNotes, noteGroups: firstGroups }); + assert.equal(events.at(-1), 1); + assert.equal(getNotesSnapshot().notes, firstNotes); + assert.equal(getNotesSnapshot().noteGroups, firstGroups); + + publishNotesSnapshot({ notes: firstNotes, noteGroups: firstGroups }); + assert.equal(events.length, 1); + + const secondNotes = [ + ...firstNotes, + { + id: 'n2', + title: 'Two', + content: 'more', + tags: [], + createdAt: 2, + updatedAt: 2, + order: 2000, + }, + ]; + publishNotesSnapshot({ notes: secondNotes, noteGroups: firstGroups }); + assert.equal(events.at(-1), 2); + + publishNotesSnapshot({ notes: secondNotes, noteGroups: ['Ops', 'DB'] }); + assert.equal(events.length, 3); + assert.deepEqual(getNotesSnapshot().noteGroups, ['Ops', 'DB']); + + unsubscribe(); +}); + +test('notesStore gated helpers stay empty and never notify', () => { + let called = 0; + const unsub = subscribeNotesNoop(() => { + called += 1; + }); + publishNotesSnapshot({ + notes: [{ + id: 'n1', + title: 'One', + content: 'body', + tags: [], + createdAt: 1, + updatedAt: 1, + order: 1000, + }], + noteGroups: ['Ops'], + }); + assert.equal(called, 0); + assert.equal(getEmptyNotesSnapshot(), EMPTY_NOTES_SNAPSHOT); + assert.equal(getEmptyNotesSnapshot().notes.length, 0); + unsub(); +}); + +test('registerNotesActions exposes update handlers', () => { + const calls: string[] = []; + registerNotesActions({ + updateNotes: () => { + calls.push('notes'); + }, + updateNoteGroups: () => { + calls.push('groups'); + }, + }); + const actions = getNotesActions(); + assert.ok(actions); + actions!.updateNotes([]); + actions!.updateNoteGroups([]); + assert.deepEqual(calls, ['notes', 'groups']); + registerNotesActions(null); + assert.equal(getNotesActions(), null); +}); diff --git a/application/state/notesStore.ts b/application/state/notesStore.ts new file mode 100644 index 000000000..5d9dbcc62 --- /dev/null +++ b/application/state/notesStore.ts @@ -0,0 +1,138 @@ +import { useSyncExternalStore } from 'react'; + +import type { VaultNote } from '../../domain/models'; + +type Listener = () => void; + +export type NotesSnapshot = { + notes: readonly VaultNote[]; + noteGroups: readonly string[]; +}; + +export type NotesActions = { + updateNotes: (notes: VaultNote[]) => void; + updateNoteGroups: (groups: string[]) => void; +}; + +const EMPTY_NOTES: readonly VaultNote[] = Object.freeze([]); +const EMPTY_NOTE_GROUPS: readonly string[] = Object.freeze([]); + +export const EMPTY_NOTES_SNAPSHOT: NotesSnapshot = Object.freeze({ + notes: EMPTY_NOTES, + noteGroups: EMPTY_NOTE_GROUPS, +}); + +/** + * External store for vault notes so Notes / AI side-panel consumers can + * subscribe without forcing TerminalLayer re-renders on every note edit. + */ +class NotesStore { + private snapshot: NotesSnapshot = EMPTY_NOTES_SNAPSHOT; + private actions: NotesActions | null = null; + private listeners = new Set(); + private actionListeners = new Set(); + + getSnapshot = (): NotesSnapshot => this.snapshot; + + subscribe = (listener: Listener): (() => void) => { + this.listeners.add(listener); + return () => { + this.listeners.delete(listener); + }; + }; + + setSnapshot(next: NotesSnapshot): void { + if ( + this.snapshot.notes === next.notes + && this.snapshot.noteGroups === next.noteGroups + ) { + return; + } + this.snapshot = next; + for (const listener of this.listeners) { + listener(); + } + } + + getActions = (): NotesActions | null => this.actions; + + subscribeActions = (listener: Listener): (() => void) => { + this.actionListeners.add(listener); + return () => { + this.actionListeners.delete(listener); + }; + }; + + setActions(next: NotesActions | null): void { + if (this.actions === next) return; + this.actions = next; + for (const listener of this.actionListeners) { + listener(); + } + } +} + +export const notesStore = new NotesStore(); + +export function publishNotesSnapshot(snapshot: NotesSnapshot): void { + notesStore.setSnapshot(snapshot); +} + +export function getNotesSnapshot(): NotesSnapshot { + return notesStore.getSnapshot(); +} + +export function subscribeNotes(listener: Listener): () => void { + return notesStore.subscribe(listener); +} + +/** No-op subscribe for gated (hidden) panel mounts. */ +export function subscribeNotesNoop(_listener: Listener): () => void { + return () => {}; +} + +export function getEmptyNotesSnapshot(): NotesSnapshot { + return EMPTY_NOTES_SNAPSHOT; +} + +export function registerNotesActions(actions: NotesActions | null): void { + notesStore.setActions(actions); +} + +export function getNotesActions(): NotesActions | null { + return notesStore.getActions(); +} + +export function subscribeNotesActions(listener: Listener): () => void { + return notesStore.subscribeActions(listener); +} + +const noopUpdateNotes: NotesActions['updateNotes'] = () => {}; +const noopUpdateNoteGroups: NotesActions['updateNoteGroups'] = () => {}; + +/** + * Subscribe to notes catalog + vault mutation actions for Notes / AI panels. + */ +export function useNotesStore(): { + notes: VaultNote[]; + noteGroups: string[]; + updateNotes: NotesActions['updateNotes']; + updateNoteGroups: NotesActions['updateNoteGroups']; +} { + const snapshot = useSyncExternalStore( + subscribeNotes, + getNotesSnapshot, + getNotesSnapshot, + ); + const actions = useSyncExternalStore( + subscribeNotesActions, + getNotesActions, + getNotesActions, + ); + return { + notes: snapshot.notes as VaultNote[], + noteGroups: snapshot.noteGroups as string[], + updateNotes: actions?.updateNotes ?? noopUpdateNotes, + updateNoteGroups: actions?.updateNoteGroups ?? noopUpdateNoteGroups, + }; +} diff --git a/application/state/sftp/columnLayout.ts b/application/state/sftp/columnLayout.ts new file mode 100644 index 000000000..51f55c9bd --- /dev/null +++ b/application/state/sftp/columnLayout.ts @@ -0,0 +1,32 @@ +export type SortField = "name" | "size" | "modified" | "type"; +export type SortOrder = "asc" | "desc"; + +export interface ColumnWidths { + name: number; + modified: number; + size: number; + type: number; +} + +export type SftpColumnVisibility = Record; + +export const DEFAULT_SFTP_COLUMN_VISIBILITY: SftpColumnVisibility = { + name: true, + modified: true, + size: true, + type: true, +}; + +export const normalizeSftpColumnVisibility = (value: unknown): SftpColumnVisibility => { + if (!value || typeof value !== "object" || Array.isArray(value)) { + return DEFAULT_SFTP_COLUMN_VISIBILITY; + } + + const stored = value as Partial>; + return { + name: true, + modified: stored.modified !== false, + size: stored.size !== false, + type: stored.type !== false, + }; +}; diff --git a/application/state/sftp/localSftpBookmarks.ts b/application/state/sftp/localSftpBookmarks.ts new file mode 100644 index 000000000..7e0b72c39 --- /dev/null +++ b/application/state/sftp/localSftpBookmarks.ts @@ -0,0 +1,83 @@ +import { useCallback, useMemo, useSyncExternalStore } from "react"; +import type { SftpBookmark } from "../../../domain/models"; +import { localStorageAdapter } from "../../../infrastructure/persistence/localStorageAdapter"; +import { STORAGE_KEY_SFTP_LOCAL_BOOKMARKS } from "../../../infrastructure/config/storageKeys"; +import { createSftpBookmark } from "./bookmarkHelpers"; + +type Listener = () => void; + +const listeners = new Set(); + +let snapshot: SftpBookmark[] = + localStorageAdapter.read(STORAGE_KEY_SFTP_LOCAL_BOOKMARKS) ?? []; + +export function subscribeLocalSftpBookmarks(listener: Listener) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +export function getLocalSftpBookmarksSnapshot() { + return snapshot; +} + +export function rehydrateLocalSftpBookmarks() { + snapshot = localStorageAdapter.read(STORAGE_KEY_SFTP_LOCAL_BOOKMARKS) ?? []; + for (const listener of listeners) listener(); +} + +export function setLocalSftpBookmarks( + next: SftpBookmark[] | ((prev: SftpBookmark[]) => SftpBookmark[]), +) { + snapshot = typeof next === "function" ? next(snapshot) : next; + localStorageAdapter.write(STORAGE_KEY_SFTP_LOCAL_BOOKMARKS, snapshot); + for (const listener of listeners) listener(); +} + +if (typeof window !== "undefined") { + window.addEventListener("storage", (event) => { + if (event.key === STORAGE_KEY_SFTP_LOCAL_BOOKMARKS) { + rehydrateLocalSftpBookmarks(); + } + }); +} + +interface UseLocalSftpBookmarksParams { + currentPath: string | undefined; +} + +export const useLocalSftpBookmarks = ({ + currentPath, +}: UseLocalSftpBookmarksParams) => { + const bookmarks = useSyncExternalStore( + subscribeLocalSftpBookmarks, + getLocalSftpBookmarksSnapshot, + getLocalSftpBookmarksSnapshot, + ); + + const isCurrentPathBookmarked = useMemo( + () => !!currentPath && bookmarks.some((b) => b.path === currentPath), + [currentPath, bookmarks], + ); + + const toggleBookmark = useCallback(() => { + if (!currentPath) return; + if (isCurrentPathBookmarked) { + setLocalSftpBookmarks((prev) => prev.filter((b) => b.path !== currentPath)); + } else { + setLocalSftpBookmarks((prev) => [...prev, createSftpBookmark(currentPath)]); + } + }, [currentPath, isCurrentPathBookmarked]); + + const deleteBookmark = useCallback((id: string) => { + setLocalSftpBookmarks((prev) => prev.filter((b) => b.id !== id)); + }, []); + + return { + bookmarks, + isCurrentPathBookmarked, + toggleBookmark, + deleteBookmark, + }; +}; diff --git a/application/state/sftp/sftpClipboardStore.ts b/application/state/sftp/sftpClipboardStore.ts new file mode 100644 index 000000000..39b28fa0f --- /dev/null +++ b/application/state/sftp/sftpClipboardStore.ts @@ -0,0 +1,124 @@ +/** + * SFTP Clipboard Store + * + * Manages clipboard state for SFTP file operations (copy/cut/paste) + * This is a simple store that holds the clipboard state and operation type. + */ + +import { useSyncExternalStore } from "react"; + +type SftpClipboardOperation = "copy" | "cut"; + +export interface SftpClipboardFile { + name: string; + isDirectory: boolean; +} + +interface SftpClipboardState { + files: SftpClipboardFile[]; + sourcePath: string; + sourceConnectionId: string; + sourceSide: "left" | "right"; + operation: SftpClipboardOperation; +} + +type ClipboardListener = () => void; + +let clipboardState: SftpClipboardState | null = null; +const clipboardListeners = new Set(); + +const notifyListeners = () => { + clipboardListeners.forEach((listener) => listener()); +}; + +export const sftpClipboardStore = { + getSnapshot: (): SftpClipboardState | null => clipboardState, + + subscribe: (listener: ClipboardListener) => { + clipboardListeners.add(listener); + return () => clipboardListeners.delete(listener); + }, + + /** + * Copy files to clipboard + */ + copy: ( + files: SftpClipboardFile[], + sourcePath: string, + sourceConnectionId: string, + sourceSide: "left" | "right" + ) => { + clipboardState = { + files, + sourcePath, + sourceConnectionId, + sourceSide, + operation: "copy", + }; + notifyListeners(); + }, + + /** + * Cut files to clipboard + */ + cut: ( + files: SftpClipboardFile[], + sourcePath: string, + sourceConnectionId: string, + sourceSide: "left" | "right" + ) => { + clipboardState = { + files, + sourcePath, + sourceConnectionId, + sourceSide, + operation: "cut", + }; + notifyListeners(); + }, + + /** + * Clear clipboard (called after paste for cut operation) + */ + clear: () => { + clipboardState = null; + notifyListeners(); + }, + + /** + * Update clipboard file list (used for partial cut transfers) + */ + updateFiles: (files: SftpClipboardFile[]) => { + if (!clipboardState) return; + if (files.length === 0) { + clipboardState = null; + } else { + clipboardState = { + ...clipboardState, + files, + }; + } + notifyListeners(); + }, + + /** + * Check if there are files in the clipboard + */ + hasFiles: (): boolean => clipboardState !== null && clipboardState.files.length > 0, + + /** + * Get the clipboard state + */ + get: (): SftpClipboardState | null => clipboardState, +}; + +/** + * React hook to subscribe to clipboard state changes + */ +export const useSftpClipboard = (): SftpClipboardState | null => { + return useSyncExternalStore( + sftpClipboardStore.subscribe, + sftpClipboardStore.getSnapshot, + sftpClipboardStore.getSnapshot + ); +}; diff --git a/application/state/sftp/sftpDialogActionStore.ts b/application/state/sftp/sftpDialogActionStore.ts new file mode 100644 index 000000000..9fdd63641 --- /dev/null +++ b/application/state/sftp/sftpDialogActionStore.ts @@ -0,0 +1,124 @@ +/** + * SFTP Dialog Action Store + * + * Manages dialog action triggers for SFTP operations. + * This store allows keyboard shortcuts to trigger dialogs in the appropriate pane. + */ + +import { useSyncExternalStore, useEffect } from "react"; +import { sftpFocusStore, SftpFocusedSide } from "./sftpFocusStore"; + +type SftpDialogActionType = "rename" | "delete" | "newFolder" | "newFile" | null; + +interface SftpDialogAction { + type: SftpDialogActionType; + targetSide: SftpFocusedSide; + targetScopeId: string; + targetFiles?: string[]; // For rename (single file) or delete (multiple files) + timestamp: number; // To distinguish different triggers of the same action +} + +type ActionListener = () => void; + +let dialogAction: SftpDialogAction | null = null; +const actionListeners = new Set(); + +const notifyListeners = () => { + actionListeners.forEach((listener) => listener()); +}; + +export const sftpDialogActionStore = { + getSnapshot: (): SftpDialogAction | null => dialogAction, + + subscribe: (listener: ActionListener) => { + actionListeners.add(listener); + return () => actionListeners.delete(listener); + }, + + /** + * Trigger a dialog action + */ + trigger: (type: SftpDialogActionType, targetScopeId: string, targetFiles?: string[]) => { + if (!type) { + dialogAction = null; + } else { + dialogAction = { + type, + targetSide: sftpFocusStore.getFocusedSide(), + targetScopeId, + targetFiles, + timestamp: Date.now(), + }; + } + notifyListeners(); + }, + + /** + * Clear the current action (called after a pane handles it) + */ + clear: () => { + dialogAction = null; + notifyListeners(); + }, + + /** + * Get the current action + */ + get: (): SftpDialogAction | null => dialogAction, +}; + +/** + * React hook to subscribe to dialog action changes + */ +export const useSftpDialogAction = (): SftpDialogAction | null => { + return useSyncExternalStore( + sftpDialogActionStore.subscribe, + sftpDialogActionStore.getSnapshot, + sftpDialogActionStore.getSnapshot + ); +}; + +/** + * React hook for a pane to respond to dialog actions + * Only the pane matching the targetSide will execute the callback + */ +export const useSftpDialogActionHandler = ( + side: SftpFocusedSide, + scopeId: string, + handlers: { + onRename?: (fileName: string) => void; + onDelete?: (fileNames: string[]) => void; + onNewFolder?: () => void; + onNewFile?: () => void; + }, + isActive = true +) => { + const action = useSftpDialogAction(); + + useEffect(() => { + if (!action || action.targetSide !== side || action.targetScopeId !== scopeId || !isActive) return; + + // Handle the action and clear it + switch (action.type) { + case "rename": + if (handlers.onRename && action.targetFiles?.[0]) { + handlers.onRename(action.targetFiles[0]); + } + break; + case "delete": + if (handlers.onDelete && action.targetFiles) { + handlers.onDelete(action.targetFiles); + } + break; + case "newFolder": + handlers.onNewFolder?.(); + break; + case "newFile": + handlers.onNewFile?.(); + break; + } + + // Clear the action after handling + sftpDialogActionStore.clear(); + }, [action, side, scopeId, handlers, isActive]); +}; diff --git a/application/state/sftp/sftpFocusStore.ts b/application/state/sftp/sftpFocusStore.ts new file mode 100644 index 000000000..69f9bc50c --- /dev/null +++ b/application/state/sftp/sftpFocusStore.ts @@ -0,0 +1,54 @@ +/** + * SFTP Focused Pane Store + * + * Tracks which SFTP pane (left or right) is currently focused. + * This is used to determine which pane should receive keyboard shortcut actions. + */ + +import { useSyncExternalStore } from "react"; + +export type SftpFocusedSide = "left" | "right"; + +type FocusListener = () => void; + +let focusedSide: SftpFocusedSide = "left"; +const focusListeners = new Set(); + +const notifyListeners = () => { + focusListeners.forEach((listener) => listener()); +}; + +export const sftpFocusStore = { + getSnapshot: (): SftpFocusedSide => focusedSide, + + subscribe: (listener: FocusListener) => { + focusListeners.add(listener); + return () => focusListeners.delete(listener); + }, + + /** + * Set the focused side + */ + setFocusedSide: (side: SftpFocusedSide) => { + if (focusedSide !== side) { + focusedSide = side; + notifyListeners(); + } + }, + + /** + * Get the current focused side + */ + getFocusedSide: (): SftpFocusedSide => focusedSide, +}; + +/** + * React hook to subscribe to focused side changes + */ +export const useSftpFocusedSide = (): SftpFocusedSide => { + return useSyncExternalStore( + sftpFocusStore.subscribe, + sftpFocusStore.getSnapshot, + sftpFocusStore.getSnapshot + ); +}; diff --git a/application/state/sftp/sftpHostViewModeStore.ts b/application/state/sftp/sftpHostViewModeStore.ts new file mode 100644 index 000000000..2d1e8cbcd --- /dev/null +++ b/application/state/sftp/sftpHostViewModeStore.ts @@ -0,0 +1,70 @@ +import { useCallback, useSyncExternalStore } from "react"; +import { localStorageAdapter } from "../../../infrastructure/persistence/localStorageAdapter"; +import { STORAGE_KEY_SFTP_HOST_VIEW_MODES } from "../../../infrastructure/config/storageKeys"; + +// ── Shared external store for per-host SFTP view mode preferences ── + +type ViewMode = 'list' | 'tree'; +type Listener = () => void; + +const listeners = new Set(); + +let snapshot: Record = + localStorageAdapter.read>(STORAGE_KEY_SFTP_HOST_VIEW_MODES) ?? {}; + +function subscribe(listener: Listener) { + listeners.add(listener); + return () => { listeners.delete(listener); }; +} + +function getSnapshot() { + return snapshot; +} + +function persist(next: Record) { + snapshot = next; + localStorageAdapter.write(STORAGE_KEY_SFTP_HOST_VIEW_MODES, snapshot); + for (const l of listeners) l(); +} + +// Sync across windows/tabs via storage events +if (typeof window !== 'undefined') { + window.addEventListener('storage', (e) => { + if (e.key !== STORAGE_KEY_SFTP_HOST_VIEW_MODES) return; + try { + snapshot = e.newValue + ? (JSON.parse(e.newValue) as Record) + : {}; + } catch { + snapshot = {}; + } + for (const l of listeners) l(); + }); +} + +/** Get the saved view mode for a specific host, or null if none saved. */ +export function getHostViewMode(hostId: string): ViewMode | null { + return snapshot[hostId] ?? null; +} + +/** Save the view mode preference for a specific host. */ +export function setHostViewMode(hostId: string, mode: ViewMode): void { + if (snapshot[hostId] === mode) return; + persist({ ...snapshot, [hostId]: mode }); +} + +// ── Hook ── + +export function useSftpHostViewMode(hostId: string | undefined) { + const store = useSyncExternalStore(subscribe, getSnapshot, getSnapshot); + + const mode: ViewMode | null = hostId ? (store[hostId] ?? null) : null; + + const setMode = useCallback((newMode: ViewMode) => { + if (hostId) { + setHostViewMode(hostId, newMode); + } + }, [hostId]); + + return { hostViewMode: mode, setHostViewMode: setMode }; +} diff --git a/application/state/sftp/sftpTreeSelectionStore.ts b/application/state/sftp/sftpTreeSelectionStore.ts new file mode 100644 index 000000000..4182b342b --- /dev/null +++ b/application/state/sftp/sftpTreeSelectionStore.ts @@ -0,0 +1,153 @@ +import { useCallback, useSyncExternalStore } from "react"; + +export interface SftpTreeSelectionItem { + path: string; + name: string; + isDirectory: boolean; + sourcePath: string; +} + +interface SftpTreeSelectionState { + visibleItems: SftpTreeSelectionItem[]; + visibleItemsByPath: Map; + visibleIndexByPath: Map; + visiblePathsSet: Set; + selectedPaths: Set; +} + +const EMPTY_PATHS = new Set(); + +const EMPTY_STATE: SftpTreeSelectionState = { + visibleItems: [], + visibleItemsByPath: new Map(), + visibleIndexByPath: new Map(), + visiblePathsSet: new Set(), + selectedPaths: EMPTY_PATHS, +}; + +type Listener = () => void; + +const paneStates = new Map(); +const paneListeners = new Map>(); + +const notifyPaneListeners = (paneId: string) => { + paneListeners.get(paneId)?.forEach((listener) => listener()); +}; + +const getPaneState = (paneId: string): SftpTreeSelectionState => + paneStates.get(paneId) ?? EMPTY_STATE; + +const setPaneState = ( + paneId: string, + updater: (state: SftpTreeSelectionState) => SftpTreeSelectionState, +) => { + const prev = getPaneState(paneId); + const next = updater(prev); + if (next === prev) return; + if (next.visibleItems.length === 0 && next.selectedPaths.size === 0) { + paneStates.delete(paneId); + } else { + paneStates.set(paneId, next); + } + notifyPaneListeners(paneId); +}; + +export const sftpTreeSelectionStore = { + getPaneState, + + getSelectedItems: (paneId: string): SftpTreeSelectionItem[] => { + const state = getPaneState(paneId); + const result: SftpTreeSelectionItem[] = []; + for (const path of state.selectedPaths) { + const item = state.visibleItemsByPath.get(path); + if (item) result.push(item); + } + return result; + }, + + setVisibleItems: (paneId: string, visibleItems: SftpTreeSelectionItem[]) => { + const visibleItemsByPath = new Map(); + const visibleIndexByPath = new Map(); + const visiblePathsSet = new Set(visibleItems.map((item) => item.path)); + visibleItems.forEach((item, index) => { + visibleItemsByPath.set(item.path, item); + visibleIndexByPath.set(item.path, index); + }); + setPaneState(paneId, (state) => { + const newSelected = new Set([...state.selectedPaths].filter((p) => visiblePathsSet.has(p))); + const changed = + newSelected.size !== state.selectedPaths.size || + [...newSelected].some((p) => !state.selectedPaths.has(p)); + return { + visibleItems, + visibleItemsByPath, + visibleIndexByPath, + visiblePathsSet, + selectedPaths: changed ? newSelected : state.selectedPaths, + }; + }); + }, + + setSelection: (paneId: string, selectedPaths: Iterable) => { + setPaneState(paneId, (state) => ({ + ...state, + selectedPaths: new Set(Array.from(selectedPaths).filter((path) => state.visiblePathsSet.has(path))), + })); + }, + + clearSelection: (paneId: string) => { + setPaneState(paneId, (state) => ({ ...state, selectedPaths: EMPTY_PATHS })); + }, + + clearAllExcept: (paneIdsToKeep?: Iterable) => { + const keep = new Set(paneIdsToKeep ?? []); + Array.from(paneStates.keys()).forEach((paneId) => { + if (keep.has(paneId)) return; + setPaneState(paneId, (state) => { + if (state.selectedPaths.size === 0) return state; + return { ...state, selectedPaths: EMPTY_PATHS }; + }); + }); + }, + + selectAllVisible: (paneId: string) => { + setPaneState(paneId, (state) => ({ + ...state, + selectedPaths: new Set( + state.visibleItems.map((item) => item.path), + ), + })); + }, + + clearPane: (paneId: string) => { + if (!paneStates.has(paneId)) return; + paneStates.delete(paneId); + notifyPaneListeners(paneId); + }, + + subscribe: (paneId: string, listener: Listener) => { + const listeners = paneListeners.get(paneId) ?? new Set(); + listeners.add(listener); + paneListeners.set(paneId, listeners); + return () => { + const current = paneListeners.get(paneId); + if (!current) return; + current.delete(listener); + if (current.size === 0) { + paneListeners.delete(paneId); + } + }; + }, +}; + +export const useSftpTreeSelectionState = (paneId: string): SftpTreeSelectionState => { + const subscribe = useCallback( + (listener: () => void) => sftpTreeSelectionStore.subscribe(paneId, listener), + [paneId], + ); + return useSyncExternalStore( + subscribe, + () => sftpTreeSelectionStore.getPaneState(paneId), + () => sftpTreeSelectionStore.getPaneState(paneId), + ); +}; diff --git a/application/state/sftp/transferPoolIdleTtl.test.ts b/application/state/sftp/transferPoolIdleTtl.test.ts deleted file mode 100644 index 2e18f788b..000000000 --- a/application/state/sftp/transferPoolIdleTtl.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; - -import { - DEFAULT_SFTP_TRANSFER_POOL_IDLE_TTL_MS, - isTransferPoolIdleReclaimDisabled, - resolveSftpTransferPoolIdleTtlMs, -} from "../../../infrastructure/config/sftpTransferPool.ts"; - -test("default pool idle TTL is five minutes", () => { - assert.equal(DEFAULT_SFTP_TRANSFER_POOL_IDLE_TTL_MS, 5 * 60_000); - assert.equal(resolveSftpTransferPoolIdleTtlMs(() => null), DEFAULT_SFTP_TRANSFER_POOL_IDLE_TTL_MS); -}); - -test("accepts preset values including never-reclaim zero", () => { - assert.equal(resolveSftpTransferPoolIdleTtlMs(() => 60_000), 60_000); - assert.equal(resolveSftpTransferPoolIdleTtlMs(() => 0), 0); - assert.equal(resolveSftpTransferPoolIdleTtlMs(() => 123), DEFAULT_SFTP_TRANSFER_POOL_IDLE_TTL_MS); -}); - -test("transfer pool idle reclaim helper is deprecated and always reclaim-enabled", () => { - // Channels close when idle; SSH park is separate. The helper always returns false. - assert.equal(isTransferPoolIdleReclaimDisabled(0), false); - assert.equal(isTransferPoolIdleReclaimDisabled(300_000), false); -}); diff --git a/application/state/sftp/useSftpConnections.ts b/application/state/sftp/useSftpConnections.ts index 6abdb1b90..d7fff6b0a 100644 --- a/application/state/sftp/useSftpConnections.ts +++ b/application/state/sftp/useSftpConnections.ts @@ -2,6 +2,7 @@ import React, { useCallback, useEffect, useRef, useState } from "react"; import type { MutableRefObject } from "react"; import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge"; import type { Host, Identity, KnownHost, SftpConnection, SftpFileEntry, SftpFilenameEncoding, SSHKey } from "../../../domain/models"; +import { createKnownHostFromHostKeyInfo } from "../../../domain/knownHosts"; import type { SftpHostKeyInfo, SftpHostKeyVerificationState, SftpPane } from "./types"; import { useSftpDirectoryListing } from "./useSftpDirectoryListing"; import { useSftpHostCredentials } from "./useSftpHostCredentials"; @@ -206,15 +207,7 @@ const createKnownHostFromSftpHostKeyInfo = ( hostKeyInfo: SftpHostKeyInfo, now = Date.now(), idSuffix = Math.random().toString(36).slice(2, 11), -): KnownHost => ({ - id: hostKeyInfo.knownHostId || `kh-${now}-${idSuffix}`, - hostname: hostKeyInfo.hostname, - port: hostKeyInfo.port || 22, - keyType: hostKeyInfo.keyType, - publicKey: hostKeyInfo.publicKey || `SHA256:${hostKeyInfo.fingerprint}`, - fingerprint: hostKeyInfo.fingerprint, - discoveredAt: now, -}); +): KnownHost => createKnownHostFromHostKeyInfo(hostKeyInfo, { now, idSuffix }); export const useSftpConnections = ({ hosts, diff --git a/application/state/sftp/useSftpPaneSorting.architecture.test.ts b/application/state/sftp/useSftpPaneSorting.architecture.test.ts new file mode 100644 index 000000000..139bab879 --- /dev/null +++ b/application/state/sftp/useSftpPaneSorting.architecture.test.ts @@ -0,0 +1,10 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; + +const source = readFileSync(new URL("./useSftpPaneSorting.ts", import.meta.url), "utf8"); + +test("useSftpPaneSorting imports column layout from application state", () => { + assert.doesNotMatch(source, /from ["'].*components\//); + assert.match(source, /from ["']\.\/columnLayout["']/); +}); diff --git a/application/state/sftp/useSftpPaneSorting.ts b/application/state/sftp/useSftpPaneSorting.ts new file mode 100644 index 000000000..0227747bc --- /dev/null +++ b/application/state/sftp/useSftpPaneSorting.ts @@ -0,0 +1,168 @@ +import React, { useCallback, useEffect, useRef, useState } from "react"; +import { + DEFAULT_SFTP_COLUMN_VISIBILITY, + normalizeSftpColumnVisibility, + type ColumnWidths, + type SftpColumnVisibility, + type SortField, + type SortOrder, +} from "./columnLayout"; +import { STORAGE_KEY_SFTP_VISIBLE_COLUMNS } from "../../../infrastructure/config/storageKeys"; +import { + LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, + localStorageAdapter, +} from "../../../infrastructure/persistence/localStorageAdapter"; +import { useSftpDirectoriesFirst } from "./useSftpDirectoriesFirst"; + +export interface UseSftpPaneSortingResult { + sortField: SortField; + sortOrder: SortOrder; + directoriesFirst: boolean; + columnWidths: ColumnWidths; + visibleColumns: SftpColumnVisibility; + handleSort: (field: SortField) => void; + handleResizeStart: (field: keyof ColumnWidths, e: React.MouseEvent) => void; + toggleColumnVisibility: (field: keyof ColumnWidths) => void; + toggleDirectoriesFirst: () => void; +} + +export const useSftpPaneSorting = (): UseSftpPaneSortingResult => { + const [sortField, setSortField] = useState("name"); + const [sortOrder, setSortOrder] = useState("asc"); + const { directoriesFirst, toggleDirectoriesFirst } = useSftpDirectoriesFirst(); + const [columnWidths, setColumnWidths] = useState({ + name: 56, + modified: 28, + size: 7, + type: 9, + }); + const [visibleColumns, setVisibleColumns] = useState(() => + normalizeSftpColumnVisibility( + localStorageAdapter.read>(STORAGE_KEY_SFTP_VISIBLE_COLUMNS), + ), + ); + + useEffect(() => { + const syncVisibleColumns = (event: Event) => { + if (event instanceof StorageEvent && event.key !== STORAGE_KEY_SFTP_VISIBLE_COLUMNS) return; + if (event instanceof CustomEvent && event.detail?.key !== STORAGE_KEY_SFTP_VISIBLE_COLUMNS) return; + const next = normalizeSftpColumnVisibility( + localStorageAdapter.read>(STORAGE_KEY_SFTP_VISIBLE_COLUMNS), + ); + setVisibleColumns(next); + }; + + window.addEventListener("storage", syncVisibleColumns); + window.addEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, syncVisibleColumns); + return () => { + window.removeEventListener("storage", syncVisibleColumns); + window.removeEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, syncVisibleColumns); + }; + }, []); + + useEffect(() => { + if (visibleColumns[sortField]) return; + setSortField("name"); + setSortOrder("asc"); + }, [sortField, visibleColumns]); + + const toggleColumnVisibility = useCallback((field: keyof ColumnWidths) => { + if (field === "name") return; + setVisibleColumns((current) => { + const next = { + ...DEFAULT_SFTP_COLUMN_VISIBILITY, + ...current, + name: true, + [field]: !current[field], + }; + localStorageAdapter.write(STORAGE_KEY_SFTP_VISIBLE_COLUMNS, next); + return next; + }); + }, []); + + const resizingRef = useRef<{ + field: keyof ColumnWidths; + startX: number; + startWidth: number; + } | null>(null); + + const handleSort = useCallback((field: SortField) => { + if (sortField === field) { + setSortOrder((prev) => (prev === "asc" ? "desc" : "asc")); + } else { + setSortField(field); + setSortOrder("asc"); + } + }, [sortField]); + + const rafIdRef = useRef(null); + const lastClientXRef = useRef(0); + + const applyColumnWidth = useCallback(() => { + if (!resizingRef.current) return; + const { field, startX, startWidth } = resizingRef.current; + const diff = lastClientXRef.current - startX; + const limits: Record = { + name: { min: 36, max: 78 }, + modified: { min: 18, max: 42 }, + size: { min: 5, max: 16 }, + type: { min: 6, max: 18 }, + }; + const { min, max } = limits[field]; + const newWidth = Math.max( + min, + Math.min(max, startWidth + diff / 8), + ); + setColumnWidths((prev) => ({ + ...prev, + [field]: newWidth, + })); + }, []); + + const handleResizeMove = useCallback((e: MouseEvent) => { + if (!resizingRef.current) return; + lastClientXRef.current = e.clientX; + if (rafIdRef.current !== null) return; + rafIdRef.current = requestAnimationFrame(() => { + rafIdRef.current = null; + applyColumnWidth(); + }); + }, [applyColumnWidth]); + + const handleResizeEnd = useCallback(() => { + if (rafIdRef.current !== null) cancelAnimationFrame(rafIdRef.current); + applyColumnWidth(); + rafIdRef.current = null; + resizingRef.current = null; + document.removeEventListener("mousemove", handleResizeMove); + document.removeEventListener("mouseup", handleResizeEnd); + }, [applyColumnWidth, handleResizeMove]); + + const handleResizeStart = ( + field: keyof ColumnWidths, + e: React.MouseEvent, + ) => { + e.preventDefault(); + e.stopPropagation(); + lastClientXRef.current = e.clientX; + resizingRef.current = { + field, + startX: e.clientX, + startWidth: columnWidths[field], + }; + document.addEventListener("mousemove", handleResizeMove); + document.addEventListener("mouseup", handleResizeEnd); + }; + + return { + sortField, + sortOrder, + directoriesFirst, + columnWidths, + visibleColumns, + handleSort, + handleResizeStart, + toggleColumnVisibility, + toggleDirectoriesFirst, + }; +}; diff --git a/application/state/sftp/useSftpTransferLifecycle.ts b/application/state/sftp/useSftpTransferLifecycle.ts index 48b8bdd8c..6e820982f 100644 --- a/application/state/sftp/useSftpTransferLifecycle.ts +++ b/application/state/sftp/useSftpTransferLifecycle.ts @@ -2,25 +2,6 @@ import { useEffect, useLayoutEffect, useRef } from "react"; import { sftpTransferCenterStore } from "../sftpTransferCenterStore"; -export function useWarmSftpTransferPool(params: { - hostIds: readonly string[]; - activeHostId?: string; - warmTransferPoolForHost?: (hostId: string) => void | Promise; -}) { - const warmRef = useRef(params.warmTransferPoolForHost); - warmRef.current = params.warmTransferPoolForHost; - const hostIdsKey = [...new Set([ - ...params.hostIds, - ...(params.activeHostId ? [params.activeHostId] : []), - ])].sort().join("\u0000"); - - useEffect(() => { - for (const hostId of hostIdsKey.split("\u0000").filter(Boolean)) { - void warmRef.current?.(hostId); - } - }, [hostIdsKey]); -} - export function useReportSftpTransferOwnerActivity(params: { ownerId: string; activeTransfersCount: number; diff --git a/application/state/systemManager/useAsyncRecordCache.ts b/application/state/systemManager/useAsyncRecordCache.ts new file mode 100644 index 000000000..48e980dda --- /dev/null +++ b/application/state/systemManager/useAsyncRecordCache.ts @@ -0,0 +1,269 @@ +import { startTransition, useCallback, useEffect, useRef, useState } from 'react'; + +export interface AsyncRecordState { + data: T | null; + loading: boolean; + error: string | null; + updatedAt: number | null; +} + +type RecordMap = Record>; + +interface UseAsyncRecordCacheOptions { + items: TItem[]; + enabled: boolean; + getKey: (item: TItem) => string; + fetchRecord: (item: TItem) => Promise; + prefetchLimit?: number; + prefetchDelayMs?: number; + staleTimeMs?: number; +} + +function delay(ms: number): Promise { + return new Promise((resolve) => window.setTimeout(resolve, ms)); +} + +function scheduleIdleTask(callback: () => void): () => void { + if (typeof window.requestIdleCallback === 'function') { + const id = window.requestIdleCallback(callback, { timeout: 1200 }); + return () => window.cancelIdleCallback(id); + } + + const id = window.setTimeout(callback, 80); + return () => window.clearTimeout(id); +} + +function normalizeRecordError(error: unknown): string { + return error instanceof Error ? error.message : String(error || 'Unknown error'); +} + +function isRecordFresh(record: AsyncRecordState | undefined, staleTimeMs: number): boolean { + if (!record || record.error || record.updatedAt === null) return false; + if (!Number.isFinite(staleTimeMs)) return true; + return Date.now() - record.updatedAt < staleTimeMs; +} + +const EMPTY_RECORDS = {}; + +export function useAsyncRecordCache({ + items, + enabled, + getKey, + fetchRecord, + prefetchLimit = 64, + prefetchDelayMs = 16, + staleTimeMs = 30_000, +}: UseAsyncRecordCacheOptions) { + const [records, setRecords] = useState>(() => EMPTY_RECORDS); + const recordsRef = useRef>(records); + const enabledRef = useRef(enabled); + const inflightRef = useRef(new Set()); + const requestVersionRef = useRef(new Map()); + const queuedForceRef = useRef(new Set()); + const loadRecordRef = useRef<( + item: TItem, + options?: { force?: boolean; urgent?: boolean }, + ) => Promise>(async () => {}); + + recordsRef.current = records; + enabledRef.current = enabled; + + const commitRecords = useCallback(( + updater: (prev: RecordMap) => RecordMap, + urgent = false, + ) => { + const apply = () => { + setRecords((prev) => { + const next = updater(prev); + recordsRef.current = next; + return next; + }); + }; + + if (urgent) { + apply(); + return; + } + + startTransition(apply); + }, []); + + const loadRecord = useCallback(async ( + item: TItem, + options?: { force?: boolean; urgent?: boolean }, + ) => { + if (!enabledRef.current) return; + const key = getKey(item); + if (!key) return; + if (inflightRef.current.has(key)) { + if (options?.force) { + queuedForceRef.current.add(key); + requestVersionRef.current.set(key, (requestVersionRef.current.get(key) ?? 0) + 1); + } + return; + } + + const existing = recordsRef.current[key]; + if (!options?.force && isRecordFresh(existing, staleTimeMs)) { + return; + } + + const requestVersion = (requestVersionRef.current.get(key) ?? 0) + 1; + requestVersionRef.current.set(key, requestVersion); + inflightRef.current.add(key); + commitRecords((prev) => ({ + ...prev, + [key]: { + data: prev[key]?.data ?? null, + loading: true, + error: null, + updatedAt: prev[key]?.updatedAt ?? null, + }, + }), options?.urgent); + + try { + const data = await fetchRecord(item); + if (requestVersionRef.current.get(key) !== requestVersion) return; + commitRecords((prev) => ({ + ...prev, + [key]: { + data, + loading: false, + error: null, + updatedAt: Date.now(), + }, + })); + } catch (error) { + if (requestVersionRef.current.get(key) !== requestVersion) return; + commitRecords((prev) => ({ + ...prev, + [key]: { + data: prev[key]?.data ?? null, + loading: false, + error: normalizeRecordError(error), + updatedAt: prev[key]?.updatedAt ?? null, + }, + })); + } finally { + inflightRef.current.delete(key); + if (queuedForceRef.current.has(key)) { + if (enabledRef.current) { + queuedForceRef.current.delete(key); + void loadRecordRef.current(item, { force: true, urgent: options?.urgent }); + } else { + commitRecords((prev) => { + const current = prev[key]; + if (!current?.loading) return prev; + return { + ...prev, + [key]: { + ...current, + loading: false, + }, + }; + }, true); + } + } + } + }, [commitRecords, fetchRecord, getKey, staleTimeMs]); + + loadRecordRef.current = loadRecord; + + useEffect(() => { + const itemKeys = new Set(items.map(getKey).filter(Boolean)); + for (const key of queuedForceRef.current) { + if (!itemKeys.has(key)) { + queuedForceRef.current.delete(key); + } + } + commitRecords((prev) => { + let changed = false; + const next: RecordMap = {}; + for (const [key, value] of Object.entries(prev) as Array<[string, AsyncRecordState]>) { + if (!itemKeys.has(key)) { + changed = true; + continue; + } + next[key] = value; + } + return changed ? next : prev; + }); + }, [commitRecords, getKey, items]); + + useEffect(() => { + if (!enabled || queuedForceRef.current.size === 0) return; + for (const item of items) { + const key = getKey(item); + if (!key || !queuedForceRef.current.has(key)) continue; + queuedForceRef.current.delete(key); + void loadRecord(item, { force: true, urgent: true }); + } + }, [enabled, getKey, items, loadRecord]); + + useEffect(() => { + if (!enabled || items.length === 0 || prefetchLimit <= 0) return undefined; + + let cancelled = false; + const candidates = items.slice(0, prefetchLimit); + const cancelIdleTask = scheduleIdleTask(() => { + void (async () => { + for (const item of candidates) { + if (cancelled) return; + await loadRecord(item); + if (prefetchDelayMs > 0) { + await delay(prefetchDelayMs); + } + } + })(); + }); + + return () => { + cancelled = true; + cancelIdleTask(); + }; + }, [enabled, items, loadRecord, prefetchDelayMs, prefetchLimit]); + + const invalidateRecord = useCallback((key: string) => { + requestVersionRef.current.set(key, (requestVersionRef.current.get(key) ?? 0) + 1); + queuedForceRef.current.delete(key); + commitRecords((prev) => { + if (!(key in prev)) return prev; + const { [key]: _removed, ...next } = prev; + return next; + }, true); + }, [commitRecords]); + + const invalidateMatching = useCallback((matches: (key: string) => boolean) => { + for (const key of requestVersionRef.current.keys()) { + if (matches(key)) { + requestVersionRef.current.set(key, (requestVersionRef.current.get(key) ?? 0) + 1); + queuedForceRef.current.delete(key); + } + } + commitRecords((prev) => { + let changed = false; + const next: RecordMap = {}; + for (const [key, value] of Object.entries(prev) as Array<[string, AsyncRecordState]>) { + if (matches(key)) { + changed = true; + continue; + } + next[key] = value; + } + return changed ? next : prev; + }, true); + }, [commitRecords]); + + const refreshRecord = useCallback( + (item: TItem) => loadRecord(item, { force: true, urgent: true }), + [loadRecord], + ); + + return { + records, + loadRecord, + refreshRecord, + invalidateRecord, + invalidateMatching, + }; +} diff --git a/application/state/useAIChatStreaming.architecture.test.ts b/application/state/useAIChatStreaming.architecture.test.ts new file mode 100644 index 000000000..db441b834 --- /dev/null +++ b/application/state/useAIChatStreaming.architecture.test.ts @@ -0,0 +1,10 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; + +const source = readFileSync(new URL("./useAIChatStreaming.ts", import.meta.url), "utf8"); + +test("useAIChatStreaming imports streaming support from infrastructure", () => { + assert.match(source, /from ['"]\.\.\/\.\.\/infrastructure\/ai\/aiChatStreamingSupport['"]/); + assert.doesNotMatch(source, /from ['"].*components\//); +}); diff --git a/application/state/useAIChatStreaming.ts b/application/state/useAIChatStreaming.ts new file mode 100644 index 000000000..02ad588e8 --- /dev/null +++ b/application/state/useAIChatStreaming.ts @@ -0,0 +1,268 @@ +/** + * useAIChatStreaming — React UI layer for AI chat streaming. + * + * Turn orchestration lives in AgentRuntime + TurnDrivers; this hook only + * manages streaming state, abort controllers, and UI callbacks. + */ + +import React, { useCallback, useEffect, useRef, useState } from 'react'; +import type { + AIPermissionMode, + AIToolIntegrationMode, + AISession, + ChatMessage, + ChatMessageAttachment, + ExternalAgentConfig, + ProviderConfig, + WebSearchConfig, +} from '../../infrastructure/ai/types'; +import type { ExecutorContext } from '../../infrastructure/ai/cattyAgent/executor'; +import { getAgentRuntime } from '../../infrastructure/ai/harness/globalAgentRuntime'; +import type { + TurnSteerInput, + TurnSteerResult, +} from '../../infrastructure/ai/harness/turnDrivers/types'; +import { classifyError } from '../../infrastructure/ai/errorClassifier'; +import { latestAISessionsSnapshot } from './aiStateSnapshots'; +import { + generateId, + getNetcattyBridge, + type DefaultTargetSessionHint, + type TerminalSessionInfo, +} from '../../infrastructure/ai/aiChatStreamingSupport'; +import { useAgentCompactionUi } from './useAgentCompactionUi'; + +export { getNetcattyBridge } from '../../infrastructure/ai/aiChatStreamingSupport'; +export type { ActiveCompactionUi } from './useAgentCompactionUi'; +export type { DefaultTargetSessionHint } from '../../infrastructure/ai/aiChatStreamingSupport'; + +const sharedStreamingSessionIds = new Set(); +const sharedAbortControllers = new Map(); +const streamingSubscribers = new Set<() => void>(); + +/** Whether a chat session still has an active stream (used to keep panel mounted while hidden). */ +export function isAIChatSessionStreaming(sessionId: string | null | undefined): boolean { + return !!sessionId && sharedStreamingSessionIds.has(sessionId); +} + +function emitStreamingStoreChange(): void { + streamingSubscribers.forEach(listener => { + try { + listener(); + } catch (err) { + console.error('[AIChatStreaming] Failed to notify streaming subscriber:', err); + } + }); +} + +export interface UseAIChatStreamingParams { + maxIterations: number; + addMessageToSession: (sessionId: string, message: ChatMessage) => void; + updateLastMessage: (sessionId: string, updater: (msg: ChatMessage) => ChatMessage) => void; + updateMessageById: (sessionId: string, messageId: string, updater: (msg: ChatMessage) => ChatMessage) => void; + persistContextCompaction?: ( + sessionId: string, + compaction: import('../../infrastructure/ai/types').AISessionContextCompaction, + ) => void; +} + +export interface UseAIChatStreamingReturn { + streamingSessionIds: Set; + setStreamingForScope: (key: string, val: boolean) => void; + abortControllersRef: React.MutableRefObject>; + sendToCattyAgent: ( + sessionId: string, + sendScopeKey: string, + trimmed: string, + abortController: AbortController, + currentSession: AISession | undefined, + assistantMsgId: string, + context: SendToCattyContext, + attachments?: ChatMessageAttachment[], + ) => Promise; + sendToExternalAgent: ( + sessionId: string, + assistantMsgId: string, + trimmed: string, + agentConfig: ExternalAgentConfig, + abortController: AbortController, + attachedImages: Array<{ base64Data: string; mediaType: string; filename?: string; filePath?: string }>, + context: SendToExternalContext, + ) => Promise; + steerExternalAgent: (input: TurnSteerInput) => Promise; + reportStreamError: (sessionId: string, abortSignal: AbortSignal, err: unknown) => void; + activeCompaction: import('./useAgentCompactionUi').ActiveCompactionUi | null; +} + +export interface SendToCattyContext { + activeProvider: ProviderConfig | undefined; + activeModelId: string; + scopeType: 'terminal' | 'workspace'; + scopeTargetId?: string; + scopeLabel?: string; + globalPermissionMode: AIPermissionMode; + commandBlocklist?: string[]; + commandTimeout?: number; + terminalSessions: TerminalSessionInfo[]; + webSearchConfig?: WebSearchConfig | null; + getExecutorContext?: () => ExecutorContext; + autoTitleSession: (sessionId: string, text: string) => void; + titleText?: string; + selectedUserSkillSlugs?: string[]; + permissionMode?: AIPermissionMode; + forceCompaction?: boolean; +} + +export interface SendToExternalContext { + existingSessionId?: string; + updateExternalSessionId?: (sessionId: string, externalSessionId: string | undefined) => void; + historyMessages?: Array<{ role: 'user' | 'assistant'; content: string }>; + terminalSessions: TerminalSessionInfo[]; + defaultTargetSession?: DefaultTargetSessionHint; + providers: ProviderConfig[]; + selectedAgentModel?: string; + toolIntegrationMode: AIToolIntegrationMode; + selectedUserSkillSlugs?: string[]; + permissionMode: AIPermissionMode; +} + +export function useAIChatStreaming({ + maxIterations, + addMessageToSession, + updateLastMessage, + updateMessageById, + persistContextCompaction, +}: UseAIChatStreamingParams): UseAIChatStreamingReturn { + const [streamingSessionIds, setStreamingSessions] = useState>( + () => new Set(sharedStreamingSessionIds), + ); + + useEffect(() => { + const syncFromStore = () => { + setStreamingSessions(new Set(sharedStreamingSessionIds)); + }; + streamingSubscribers.add(syncFromStore); + syncFromStore(); + return () => { + streamingSubscribers.delete(syncFromStore); + }; + }, []); + + const setStreamingForScope = useCallback((key: string, val: boolean) => { + const hadKey = sharedStreamingSessionIds.has(key); + if (val) { + sharedStreamingSessionIds.add(key); + } else { + sharedStreamingSessionIds.delete(key); + } + if (hadKey !== val) { + emitStreamingStoreChange(); + } + }, []); + + const abortControllersRef = useRef>(sharedAbortControllers); + + const activeCompaction = useAgentCompactionUi(); + + const reportStreamError = useCallback(( + sessionId: string, + abortSignal: AbortSignal, + err: unknown, + ) => { + if (abortSignal.aborted) return; + console.error('[AIChatSidePanel] Stream error (full):', err); + const errorInfo = classifyError(err); + updateLastMessage(sessionId, msg => ({ + ...msg, + statusText: '', + executionStatus: msg.executionStatus === 'running' ? 'failed' : msg.executionStatus, + })); + addMessageToSession(sessionId, { + id: generateId(), + role: 'assistant', + content: '', + errorInfo, + timestamp: Date.now(), + }); + }, [updateLastMessage, addMessageToSession]); + + const uiCallbacks = useCallback(() => ({ + addMessageToSession, + updateLastMessage, + updateMessageById, + reportStreamError, + setStreamingForScope, + getLatestSession: (sessionId: string) => latestAISessionsSnapshot?.find(s => s.id === sessionId), + persistContextCompaction, + }), [addMessageToSession, updateLastMessage, updateMessageById, reportStreamError, setStreamingForScope, persistContextCompaction]); + + const sendToExternalAgent = useCallback(async ( + sessionId: string, + assistantMsgId: string, + trimmed: string, + agentConfig: ExternalAgentConfig, + abortController: AbortController, + attachedImages: Array<{ base64Data: string; mediaType: string; filename?: string; filePath?: string }>, + context: SendToExternalContext, + ) => { + const bridge = getNetcattyBridge(); + await getAgentRuntime().runTurn({ + backend: 'external-sdk', + chatSessionId: sessionId, + assistantMsgId, + userText: trimmed, + signal: abortController.signal, + agentConfig, + attachedImages, + context, + bridge, + ui: uiCallbacks(), + }); + }, [uiCallbacks]); + + const steerExternalAgent = useCallback(async (input: TurnSteerInput) => { + return getAgentRuntime().steerTurn(input); + }, []); + + const sendToCattyAgent = useCallback(async ( + sessionId: string, + sendScopeKey: string, + trimmed: string, + abortController: AbortController, + currentSession: AISession | undefined, + assistantMsgId: string, + context: SendToCattyContext, + attachments?: ChatMessageAttachment[], + ) => { + const bridge = getNetcattyBridge(); + try { + await getAgentRuntime().runTurn({ + backend: 'catty', + chatSessionId: sessionId, + sendScopeKey, + userText: trimmed, + signal: abortController.signal, + currentSession, + assistantMsgId, + context, + attachments, + maxIterations, + bridge, + ui: uiCallbacks(), + }); + } finally { + abortControllersRef.current.delete(sessionId); + } + }, [maxIterations, uiCallbacks]); + + return { + streamingSessionIds, + setStreamingForScope, + abortControllersRef, + sendToCattyAgent, + sendToExternalAgent, + steerExternalAgent, + reportStreamError, + activeCompaction, + }; +} diff --git a/application/state/useAgentCompactionUi.ts b/application/state/useAgentCompactionUi.ts new file mode 100644 index 000000000..2526d2e57 --- /dev/null +++ b/application/state/useAgentCompactionUi.ts @@ -0,0 +1,95 @@ +import { useEffect, useState } from 'react'; +import type { ContextPrepareTrigger } from '../../infrastructure/ai/harness/types'; +import { getAgentRuntime } from '../../infrastructure/ai/harness/globalAgentRuntime'; +import { CATTY_COMPACTION_STATUS_KEYS } from '../../infrastructure/ai/harness/compactionStatusKeys'; + +export interface ActiveCompactionUi { + sessionId: string; + trigger: ContextPrepareTrigger; +} + +export interface AgentContextUsage { + sessionId: string; + inputTokens: number; + contextWindow: number; + estimated: boolean; +} + +function statusKeyForTrigger(trigger: ContextPrepareTrigger): string { + switch (trigger) { + case 'step': + return CATTY_COMPACTION_STATUS_KEYS.step; + case '413-retry': + return CATTY_COMPACTION_STATUS_KEYS.retry; + default: + return CATTY_COMPACTION_STATUS_KEYS.preTurn; + } +} + +export function useAgentCompactionUi(): ActiveCompactionUi | null { + const [active, setActive] = useState(null); + + useEffect(() => { + const unsubscribe = getAgentRuntime().subscribe((event) => { + const sessionId = event.chatSessionId ?? event.sessionId; + if (event.type === 'compaction_start') { + setActive({ sessionId, trigger: event.trigger }); + return; + } + if (event.type === 'compaction' || event.type === 'turn_end') { + setActive((prev) => (prev?.sessionId === sessionId ? null : prev)); + } + }); + return unsubscribe; + }, []); + + return active; +} + +export function compactionStatusText( + trigger: ContextPrepareTrigger, + translate: (key: string, params?: Record) => string, +): string { + return translate(statusKeyForTrigger(trigger)); +} + +export function resolveCompactionStatusText( + statusText: string | undefined, + translate: (key: string) => string, +): string | undefined { + if (!statusText) return undefined; + if (statusText.startsWith('ai.')) return translate(statusText); + return statusText; +} + +export function useAgentContextUsage(sessionId: string | null | undefined): AgentContextUsage | null { + const [usage, setUsage] = useState(null); + + useEffect(() => { + if (!sessionId) { + setUsage(null); + return undefined; + } + + const unsubscribe = getAgentRuntime().subscribe((event) => { + const eventSessionId = event.chatSessionId ?? event.sessionId; + if (eventSessionId !== sessionId || event.type !== 'context_snapshot') return; + const snapshot = event.snapshot; + if ( + typeof snapshot.contextWindow !== 'number' + || typeof snapshot.estimatedInputTokens !== 'number' + ) { + return; + } + setUsage({ + sessionId, + inputTokens: Math.max(0, snapshot.estimatedInputTokens), + contextWindow: Math.max(1, snapshot.contextWindow), + estimated: true, + }); + }); + return unsubscribe; + }, [sessionId]); + + return usage?.sessionId === sessionId ? usage : null; +} diff --git a/application/state/useExternalMcpSessionSync.ts b/application/state/useExternalMcpSessionSync.ts index 7b6ece05f..910eea0d7 100644 --- a/application/state/useExternalMcpSessionSync.ts +++ b/application/state/useExternalMcpSessionSync.ts @@ -1,6 +1,6 @@ import { useEffect, useMemo, useRef, useState } from 'react'; -import { buildAITerminalSessionInfo } from '../../components/terminalLayer/TerminalLayerSupport'; +import { buildAITerminalSessionInfo } from '../../domain/buildAITerminalSessionInfo'; import { detectLocalOs } from '../../lib/localShell'; import type { Host, PortForwardingRule, TerminalSession } from '../../types'; import { STORAGE_KEY_AI_EXTERNAL_MCP_ENABLED } from '../../infrastructure/config/storageKeys'; diff --git a/application/state/useExternalMcpToggleState.ts b/application/state/useExternalMcpToggleState.ts index 0368919fa..84787993d 100644 --- a/application/state/useExternalMcpToggleState.ts +++ b/application/state/useExternalMcpToggleState.ts @@ -144,12 +144,26 @@ export function readExternalMcpMode(): ExternalMcpMode { return normalizeExternalMcpMode(localStorageAdapter.readString(STORAGE_KEY_AI_EXTERNAL_MCP_MODE)); } +export function writeExternalMcpMode(mode: ExternalMcpMode): ExternalMcpMode { + const normalized = normalizeExternalMcpMode(mode); + localStorageAdapter.writeString(STORAGE_KEY_AI_EXTERNAL_MCP_MODE, normalized); + emitAIStateChanged(STORAGE_KEY_AI_EXTERNAL_MCP_MODE); + return normalized; +} + export function readExternalMcpIdleTimeoutMinutes(): number { return normalizeExternalMcpIdleTimeoutMinutes( localStorageAdapter.readNumber(STORAGE_KEY_AI_EXTERNAL_MCP_IDLE_TIMEOUT_MINUTES), ); } +export function writeExternalMcpIdleTimeoutMinutes(minutes: number): number { + const normalized = normalizeExternalMcpIdleTimeoutMinutes(minutes); + localStorageAdapter.writeNumber(STORAGE_KEY_AI_EXTERNAL_MCP_IDLE_TIMEOUT_MINUTES, normalized); + emitAIStateChanged(STORAGE_KEY_AI_EXTERNAL_MCP_IDLE_TIMEOUT_MINUTES); + return normalized; +} + /** Whether host_open should surface/focus the main window. Defaults to true (existing behavior). */ export function readExternalMcpFocusOnHostOpen(): boolean { return localStorageAdapter.readBoolean(STORAGE_KEY_AI_EXTERNAL_MCP_FOCUS_ON_HOST_OPEN) ?? true; @@ -187,6 +201,13 @@ export function readSessionIdleTimeoutMinutes(): number { ); } +export function writeSessionIdleTimeoutMinutes(minutes: number): number { + const normalized = normalizeSessionIdleTimeoutMinutes(minutes); + localStorageAdapter.writeNumber(STORAGE_KEY_AI_SESSION_IDLE_TIMEOUT_MINUTES, normalized); + emitAIStateChanged(STORAGE_KEY_AI_SESSION_IDLE_TIMEOUT_MINUTES); + return normalized; +} + export function shouldStartExternalMcpOnStartup({ enabled, mode, diff --git a/application/state/usePortForwardHostKeyVerification.architecture.test.ts b/application/state/usePortForwardHostKeyVerification.architecture.test.ts new file mode 100644 index 000000000..d66a96e5b --- /dev/null +++ b/application/state/usePortForwardHostKeyVerification.architecture.test.ts @@ -0,0 +1,10 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; + +const source = readFileSync(new URL("./usePortForwardHostKeyVerification.ts", import.meta.url), "utf8"); + +test("usePortForwardHostKeyVerification stays below the UI layer", () => { + assert.doesNotMatch(source, /from ["'].*components\//); + assert.match(source, /from ["']\.\.\/\.\.\/domain\/portForwardHostKey["']/); +}); diff --git a/application/state/usePortForwardHostKeyVerification.ts b/application/state/usePortForwardHostKeyVerification.ts index 8e8aedaf0..e7b2f1d1b 100644 --- a/application/state/usePortForwardHostKeyVerification.ts +++ b/application/state/usePortForwardHostKeyVerification.ts @@ -1,7 +1,7 @@ import { useCallback, useEffect, useState } from "react"; import type { KnownHost } from "../../domain/models"; import { netcattyBridge } from "../../infrastructure/services/netcattyBridge"; -import type { HostKeyInfo } from "../../components/terminal/TerminalHostKeyVerification"; +import type { HostKeyInfo } from "../../domain/hostKey"; import { createKnownHostFromPortForwardHostKeyInfo, enqueuePortForwardHostKeyVerification, @@ -9,7 +9,7 @@ import { toPendingPortForwardHostKeyVerification, type PendingPortForwardHostKeyVerification, type PortForwardHostKeyRequest, -} from "../../components/port-forwarding/hostKeyVerification"; +} from "../../domain/portForwardHostKey"; export interface PortForwardHostKeyVerificationState { hostKeyInfo: HostKeyInfo; diff --git a/application/state/useServerStats.ts b/application/state/useServerStats.ts new file mode 100644 index 000000000..826d1aac4 --- /dev/null +++ b/application/state/useServerStats.ts @@ -0,0 +1,415 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { netcattyBridge } from '../../infrastructure/services/netcattyBridge'; + +export interface DiskInfo { + capacityKey?: string; // Filesystem or shared-pool identity for deduplication + mountPoint: string; + used: number; // Used in GB + total: number; // Total in GB + percent: number; // Usage percentage +} + +export interface NetInterfaceInfo { + name: string; // Interface name (e.g., eth0, ens33) + rxBytes: number; // Total received bytes + txBytes: number; // Total transmitted bytes + rxSpeed: number; // Receive speed (bytes/sec) + txSpeed: number; // Transmit speed (bytes/sec) +} + +export interface ProcessInfo { + pid: string; + memPercent: number; + command: string; +} + +export interface ServerStats { + hostname?: string; // Remote hostname + osName?: string; // Remote operating system name + kernelRelease?: string; // Remote kernel release + uptimeSeconds?: number | null;// Remote uptime in seconds + loadAverage?: number[]; // 1/5/15 minute load average + cpu: number | null; // CPU usage percentage (0-100) + cpuCores: number | null; // Number of CPU cores + cpuPerCore: number[]; // Per-core CPU usage array + memTotal: number | null; // Total memory in MB + memUsed: number | null; // Used memory in MB (excluding buffers/cache) + memFree: number | null; // Free memory in MB + memBuffers: number | null; // Buffers in MB + memCached: number | null; // Cached in MB + swapTotal: number | null; // Total swap in MB + swapUsed: number | null; // Used swap in MB + topProcesses: ProcessInfo[]; // Top 10 processes by memory + diskPercent: number | null; // Disk usage percentage for root partition + diskUsed: number | null; // Disk used in GB + diskTotal: number | null; // Total disk in GB + disks: DiskInfo[]; // All mounted disks + netRxSpeed: number; // Total network receive speed (bytes/sec) + netTxSpeed: number; // Total network transmit speed (bytes/sec) + latencyMs: number | null; // TCP connection establishment latency to the SSH endpoint + netInterfaces: NetInterfaceInfo[]; // Per-interface network stats + lastUpdated: number | null; // Timestamp of last successful update +} + +interface UseServerStatsOptions { + sessionId: string; + enabled: boolean; // Whether stats collection is enabled (from settings) + refreshInterval: number; // Refresh interval in seconds + isSupportedOs: boolean; // Only collect stats for Linux/macOS servers + isConnected: boolean; // Only collect when connected +} + +interface ServerStatsState { + stats: ServerStats; + isLoading: boolean; + error: string | null; +} + +interface ServerStatsClient { + enabled: boolean; + refreshInterval: number; + isSupportedOs: boolean; + isConnected: boolean; +} + +type ServerStatsListener = (state: ServerStatsState) => void; + +interface SharedServerStatsSession { + sessionId: string; + state: ServerStatsState; + listeners: Set; + clients: Map; + intervalRef: ReturnType | null; + initialTimerRef: ReturnType | null; + connectedAt: number; + hasFetched: boolean; + fetchGeneration: number; + consecutiveFailures: number; + givenUp: boolean; + pollIntervalMs: number | null; + pollingActive: boolean; + inflight: Promise | null; + inflightGeneration: number | null; +} + +const CONSECUTIVE_FAILURE_LIMIT = 3; +const serverStatsSessions = new Map(); +let nextClientId = 1; + +function createEmptyServerStats(): ServerStats { + return { + hostname: undefined, + osName: undefined, + kernelRelease: undefined, + uptimeSeconds: null, + loadAverage: [], + cpu: null, + cpuCores: null, + cpuPerCore: [], + memTotal: null, + memUsed: null, + memFree: null, + memBuffers: null, + memCached: null, + swapTotal: null, + swapUsed: null, + topProcesses: [], + diskPercent: null, + diskUsed: null, + diskTotal: null, + disks: [], + netRxSpeed: 0, + netTxSpeed: 0, + latencyMs: null, + netInterfaces: [], + lastUpdated: null, + }; +} + +function createInitialState(): ServerStatsState { + return { + stats: createEmptyServerStats(), + isLoading: false, + error: null, + }; +} + +function getSharedServerStatsSession(sessionId: string): SharedServerStatsSession { + const existing = serverStatsSessions.get(sessionId); + if (existing) return existing; + + const session: SharedServerStatsSession = { + sessionId, + state: createInitialState(), + listeners: new Set(), + clients: new Map(), + intervalRef: null, + initialTimerRef: null, + connectedAt: 0, + hasFetched: false, + fetchGeneration: 0, + consecutiveFailures: 0, + givenUp: false, + pollIntervalMs: null, + pollingActive: false, + inflight: null, + inflightGeneration: null, + }; + serverStatsSessions.set(sessionId, session); + return session; +} + +function emitServerStatsState(session: SharedServerStatsSession): void { + for (const listener of session.listeners) { + listener(session.state); + } +} + +function updateServerStatsState(session: SharedServerStatsSession, patch: Partial): void { + session.state = { ...session.state, ...patch }; + emitServerStatsState(session); +} + +function clearServerStatsTimers(session: SharedServerStatsSession): void { + if (session.initialTimerRef) { + clearTimeout(session.initialTimerRef); + session.initialTimerRef = null; + } + if (session.intervalRef) { + clearInterval(session.intervalRef); + session.intervalRef = null; + } + session.pollingActive = false; + session.pollIntervalMs = null; +} + +function resetServerStatsSession(session: SharedServerStatsSession): void { + clearServerStatsTimers(session); + session.connectedAt = 0; + session.hasFetched = false; + session.fetchGeneration += 1; + session.consecutiveFailures = 0; + session.givenUp = false; + updateServerStatsState(session, createInitialState()); +} + +function getActiveServerStatsClients(session: SharedServerStatsSession): ServerStatsClient[] { + return Array.from(session.clients.values()).filter((client) => ( + client.enabled && client.isSupportedOs && client.isConnected + )); +} + +function normalizeServerStats(stats: Partial): ServerStats { + return { + hostname: stats.hostname, + osName: stats.osName, + kernelRelease: stats.kernelRelease, + uptimeSeconds: Number.isFinite(stats.uptimeSeconds) ? Number(stats.uptimeSeconds) : null, + loadAverage: Array.isArray(stats.loadAverage) ? stats.loadAverage : [], + cpu: stats.cpu ?? null, + cpuCores: stats.cpuCores ?? null, + cpuPerCore: stats.cpuPerCore || [], + memTotal: stats.memTotal ?? null, + memUsed: stats.memUsed ?? null, + memFree: stats.memFree ?? null, + memBuffers: stats.memBuffers ?? null, + memCached: stats.memCached ?? null, + swapTotal: stats.swapTotal ?? null, + swapUsed: stats.swapUsed ?? null, + topProcesses: stats.topProcesses || [], + diskPercent: stats.diskPercent ?? null, + diskUsed: stats.diskUsed ?? null, + diskTotal: stats.diskTotal ?? null, + disks: stats.disks || [], + netRxSpeed: stats.netRxSpeed || 0, + netTxSpeed: stats.netTxSpeed || 0, + latencyMs: Number.isFinite(stats.latencyMs) ? Number(stats.latencyMs) : null, + netInterfaces: stats.netInterfaces || [], + lastUpdated: Date.now(), + }; +} + +function markServerStatsFailure(session: SharedServerStatsSession, message: string): void { + session.consecutiveFailures += 1; + updateServerStatsState(session, { error: message }); + if (session.consecutiveFailures >= CONSECUTIVE_FAILURE_LIMIT) { + // Stop polling this session. This covers network devices that advertise + // OpenSSH but do not support the POSIX stats shell command. + session.givenUp = true; + clearServerStatsTimers(session); + } +} + +async function fetchSharedServerStats(session: SharedServerStatsSession, force = false): Promise { + if (!session.sessionId) return; + if (session.inflight && session.inflightGeneration === session.fetchGeneration) { + await session.inflight; + return; + } + if (session.givenUp && !force) return; + if (getActiveServerStatsClients(session).length === 0) return; + + const bridge = netcattyBridge.get(); + if (!bridge?.getServerStats) return; + + if (force) { + session.givenUp = false; + session.consecutiveFailures = 0; + } + + const generation = session.fetchGeneration; + session.inflightGeneration = generation; + updateServerStatsState(session, { isLoading: true, error: null }); + + const request = (async () => { + try { + const result = await bridge.getServerStats(session.sessionId); + + // Discard stale responses from before a polling restart or reconnect. + if (generation !== session.fetchGeneration) return; + + if (result.pending) { + // Transient "not ready yet", e.g. a Mosh session whose SSH handshake + // has not finished. Do not count this toward the hard-failure cutoff. + return; + } + + if (result.success && result.stats) { + session.hasFetched = true; + session.consecutiveFailures = 0; + updateServerStatsState(session, { + stats: normalizeServerStats(result.stats), + error: null, + }); + } else if (result.error) { + markServerStatsFailure(session, result.error); + } else { + markServerStatsFailure(session, 'No stats returned'); + } + } catch (err) { + if (generation === session.fetchGeneration) { + markServerStatsFailure(session, err instanceof Error ? err.message : 'Unknown error'); + } + } finally { + if (generation === session.fetchGeneration) { + updateServerStatsState(session, { isLoading: false }); + } + } + })(); + + session.inflight = request; + try { + await request; + } finally { + if (session.inflight === request) { + session.inflight = null; + session.inflightGeneration = null; + } + } +} + +function reconcileSharedServerStatsSession(session: SharedServerStatsSession): void { + const activeClients = getActiveServerStatsClients(session); + + if (activeClients.length === 0) { + resetServerStatsSession(session); + return; + } + + if (session.connectedAt === 0) { + session.connectedAt = Date.now(); + } + + const intervalMs = Math.max(5, Math.min(...activeClients.map((client) => client.refreshInterval))) * 1000; + const shouldRestartPolling = !session.pollingActive || session.pollIntervalMs !== intervalMs; + if (!shouldRestartPolling) return; + if (session.givenUp) return; + + clearServerStatsTimers(session); + session.fetchGeneration += 1; + session.pollingActive = true; + session.pollIntervalMs = intervalMs; + + const connectionAge = Date.now() - session.connectedAt; + const needsWarmup = !session.hasFetched && connectionAge < 2000; + + session.initialTimerRef = setTimeout(() => { + session.initialTimerRef = null; + void fetchSharedServerStats(session); + }, needsWarmup ? 2000 : 0); + session.intervalRef = setInterval(() => { + void fetchSharedServerStats(session); + }, intervalMs); +} + +function maybeDisposeSharedServerStatsSession(session: SharedServerStatsSession): void { + if (session.clients.size > 0 || session.listeners.size > 0) return; + clearServerStatsTimers(session); + session.fetchGeneration += 1; + serverStatsSessions.delete(session.sessionId); +} + +export function useServerStats({ + sessionId, + enabled, + refreshInterval, + isSupportedOs, + isConnected, +}: UseServerStatsOptions) { + const clientIdRef = useRef(null); + if (clientIdRef.current === null) { + clientIdRef.current = nextClientId; + nextClientId += 1; + } + + const [state, setState] = useState(() => getSharedServerStatsSession(sessionId).state); + + useEffect(() => { + const session = getSharedServerStatsSession(sessionId); + const clientId = clientIdRef.current; + if (clientId === null) return; + + const listener: ServerStatsListener = (nextState) => { + setState(nextState); + }; + + session.listeners.add(listener); + setState(session.state); + + return () => { + session.listeners.delete(listener); + session.clients.delete(clientId); + reconcileSharedServerStatsSession(session); + maybeDisposeSharedServerStatsSession(session); + }; + }, [sessionId]); + + useEffect(() => { + const session = getSharedServerStatsSession(sessionId); + const clientId = clientIdRef.current; + if (clientId === null) return; + + session.clients.set(clientId, { + enabled, + refreshInterval, + isSupportedOs, + isConnected, + }); + setState(session.state); + reconcileSharedServerStatsSession(session); + }, [sessionId, enabled, refreshInterval, isSupportedOs, isConnected]); + + const refresh = useCallback(() => { + const session = getSharedServerStatsSession(sessionId); + void fetchSharedServerStats(session, true).finally(() => { + reconcileSharedServerStatsSession(session); + }); + }, [sessionId]); + + return { + stats: state.stats, + isLoading: state.isLoading, + error: state.error, + refresh, + }; +} diff --git a/application/state/useSessionState.ts b/application/state/useSessionState.ts index 7722031c9..a358f5ac2 100644 --- a/application/state/useSessionState.ts +++ b/application/state/useSessionState.ts @@ -619,17 +619,26 @@ export const useSessionState = ({ }); }, []); - const submitWorkspaceRename = useCallback(() => { + const submitWorkspaceRename = useCallback((workspaceId?: string, name?: string) => { + if (workspaceId !== undefined && name !== undefined) { + const trimmed = name.trim(); + if (!trimmed) return; + setWorkspaces(prev => prev.map(w => ( + w.id === workspaceId ? { ...w, title: trimmed, autoTitle: false } : w + ))); + return; + } + setWorkspaceRenameValue(prevValue => { - const name = prevValue.trim(); - if (!name) return prevValue; - + const trimmed = prevValue.trim(); + if (!trimmed) return prevValue; + setWorkspaceRenameTarget(prevTarget => { if (!prevTarget) return prevTarget; - setWorkspaces(prev => prev.map(w => w.id === prevTarget.id ? { ...w, title: name, autoTitle: false } : w)); + setWorkspaces(prev => prev.map(w => w.id === prevTarget.id ? { ...w, title: trimmed, autoTitle: false } : w)); return null; }); - + return ''; }); }, []); diff --git a/application/state/useSettingsState.ts b/application/state/useSettingsState.ts index 1142b1d1a..aa5c22bc3 100644 --- a/application/state/useSettingsState.ts +++ b/application/state/useSettingsState.ts @@ -1,6 +1,7 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type SetStateAction } from 'react'; import { runThemeTransition, type ThemeTransitionMode } from './themeTransition'; +import { publishAppearanceChromeSnapshot } from './appearanceChromeStore'; import { SyncConfig, TerminalSettings, HotkeyScheme, CustomKeyBindings, DEFAULT_KEY_BINDINGS, KeyBinding, UILanguage, SessionLogFormat, normalizeTerminalSettings } from '../../domain/models'; import { DEFAULT_HTTP_NETWORK_PROXY, @@ -967,6 +968,8 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable const persistedAppearanceChanged = previousAppearance === null || hasPersistedAppearanceChanged(previousAppearance, appearanceRender); previousAppearanceRenderRef.current = appearanceRender; + // Terminal leaves subscribe here so accent drag does not rebuild TerminalLayer. + publishAppearanceChromeSnapshot({ accentMode, customAccent }); const tokens = getUiThemeById(resolvedTheme, resolvedTheme === 'dark' ? darkUiThemeId : lightUiThemeId).tokens; const apply = () => applyThemeTokens(theme, resolvedTheme, tokens, accentMode, customAccent); const transitionMode = appearanceTransitionModeRef.current; @@ -1841,7 +1844,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable // Opaque version that changes when any synced setting changes, used by useAutoSync. // eslint-disable-next-line react-hooks/exhaustive-deps settingsVersion: useMemo(() => Math.random(), [ - theme, lightUiThemeId, darkUiThemeId, accentMode, customAccent, + theme, lightUiThemeId, darkUiThemeId, accentMode, uiFontFamilyId, uiLanguage, customCSS, terminalThemeId, terminalFontFamilyId, terminalFontSize, terminalSettings, customKeyBindings, editorWordWrap, diff --git a/application/state/useSftpState.ts b/application/state/useSftpState.ts index 67f2c7471..03d179fd5 100644 --- a/application/state/useSftpState.ts +++ b/application/state/useSftpState.ts @@ -399,14 +399,6 @@ export const useSftpState = ( [hosts, identities, keys, openPoolSftpSession, transferKnownHosts, transferPoolKeyCache, transferTerminalSettings], ); - /** - * @deprecated No-op. SSH transport idle park keeps connections warm; opening - * a background transfer channel is unnecessary and could re-trigger MFA. - */ - const warmTransferPoolForHost = useCallback(async (_hostId: string) => { - // Intentionally empty — unified transport registry owns keep-alive. - }, []); - /** True after browse channels were soft-closed while this owner stayed mounted. */ const browseParkedRef = useRef(false); const browseLifecycleGenRef = useRef(0); @@ -824,7 +816,6 @@ export const useSftpState = ( rejectHostKeyVerification, acceptHostKeyVerification, acceptAndSaveHostKeyVerification, - warmTransferPoolForHost, }; const methodsRef = useRef(currentMethods); methodsRef.current = currentMethods; @@ -907,8 +898,6 @@ export const useSftpState = ( rejectHostKeyVerification: () => methodsRef.current.rejectHostKeyVerification(), acceptHostKeyVerification: () => methodsRef.current.acceptHostKeyVerification(), acceptAndSaveHostKeyVerification: () => methodsRef.current.acceptAndSaveHostKeyVerification(), - warmTransferPoolForHost: (...args: Parameters) => - methodsRef.current.warmTransferPoolForHost(...args), activeFileWatchCountRef, }), [activeFileWatchCountRef]); // activeFileWatchCountRef is a stable ref diff --git a/application/state/useSystemManager.ts b/application/state/useSystemManager.ts new file mode 100644 index 000000000..25561139a --- /dev/null +++ b/application/state/useSystemManager.ts @@ -0,0 +1,326 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { useI18n } from '../i18n/I18nProvider'; +import type { I18nContextValue } from '../i18n/I18nProvider'; +import { sessionCapabilitiesStore } from './sessionCapabilitiesStore'; +import type { SessionCapabilities } from '../../domain/systemManager/types'; +import type { useSystemManagerBackend } from './useSystemManagerBackend'; +import { nextPollData } from '../../domain/systemManager/pollListStable'; + +type Backend = ReturnType; + +function delay(ms: number): Promise { + return new Promise((resolve) => window.setTimeout(resolve, ms)); +} + +function normalizePollingErrorMessage(error: unknown, t: I18nContextValue['t']): string { + const message = error instanceof Error ? error.message : String(error || 'Unknown error'); + const lower = message.toLowerCase(); + if (lower.includes('channel open failure') || lower.includes('unable to exec')) { + return t('systemManager.errors.sshChannelUnavailable'); + } + return message; +} + +/** Stable i18n ref so polling fetchers do not reset when locale re-renders. */ +export function useStableTranslate(): I18nContextValue['t'] { + const { t } = useI18n(); + const tRef = useRef(t); + tRef.current = t; + return useCallback( + (key, values) => tRef.current(key, values), + [], + ); +} + +export function useSessionCapabilities( + sessionId: string | null, + isConnected: boolean, + backend: Backend, + enabled: boolean, + capabilitiesTtlMs: number, +) { + const ttlMsRef = useRef(capabilitiesTtlMs); + ttlMsRef.current = capabilitiesTtlMs; + + const [capabilities, setCapabilities] = useState( + () => (sessionId ? sessionCapabilitiesStore.get(sessionId) : undefined), + ); + const [probing, setProbing] = useState(false); + + useEffect(() => { + if (!sessionId) return undefined; + return sessionCapabilitiesStore.subscribe(sessionId, () => { + setCapabilities(sessionCapabilitiesStore.get(sessionId)); + }); + }, [sessionId]); + + useEffect(() => { + if (!sessionId || isConnected) return undefined; + sessionCapabilitiesStore.delete(sessionId); + return undefined; + }, [sessionId, isConnected]); + + const probe = useCallback(async (force = false) => { + if (!sessionId || !isConnected) return; + if (!force && sessionCapabilitiesStore.get(sessionId)) return; + setProbing(true); + try { + const result = await backend.probeSystemCapabilities(sessionId); + if (result.success && result.capabilities) { + sessionCapabilitiesStore.set(sessionId, result.capabilities, ttlMsRef.current); + } + } finally { + setProbing(false); + } + }, [backend, isConnected, sessionId]); + + useEffect(() => { + if (!sessionId || !isConnected || !enabled) return undefined; + void probe(); + return undefined; + }, [enabled, sessionId, isConnected, probe]); + + return { capabilities, probing, refreshCapabilities: () => probe(true) }; +} + +/** Prefetch capabilities only for the given session ids (e.g. when System panel opens). */ +export function useSystemCapabilitiesWarmup( + sessionIds: string[], + backend: Backend, + enabled: boolean, + capabilitiesTtlMs: number, +) { + const backendRef = useRef(backend); + backendRef.current = backend; + const inflightRef = useRef(new Set()); + const ttlMsRef = useRef(capabilitiesTtlMs); + ttlMsRef.current = capabilitiesTtlMs; + + const sessionKey = enabled ? sessionIds.slice().sort().join(',') : ''; + + useEffect(() => { + if (!sessionKey) return undefined; + for (const sessionId of sessionKey.split(',')) { + if (!sessionId || sessionCapabilitiesStore.get(sessionId)) continue; + if (inflightRef.current.has(sessionId)) continue; + inflightRef.current.add(sessionId); + void backendRef.current.probeSystemCapabilities(sessionId).then((result) => { + inflightRef.current.delete(sessionId); + if (result.success && result.capabilities) { + sessionCapabilitiesStore.set(sessionId, result.capabilities, ttlMsRef.current); + } + }); + } + return undefined; + }, [sessionKey]); +} + +export function usePolling( + fetcher: () => Promise, + intervalMs: number, + enabled: boolean, + merge?: (prev: T | null, next: T) => T, + options?: { poll?: boolean; resetKey?: string }, +) { + const stableT = useStableTranslate(); + const resetKey = options?.resetKey ?? ''; + const [data, setData] = useState(null); + const [dataKey, setDataKey] = useState(resetKey); + const [error, setError] = useState(null); + const [errorKey, setErrorKey] = useState(resetKey); + const [loading, setLoading] = useState(false); + const [loadingKey, setLoadingKey] = useState(resetKey); + const failuresRef = useRef(0); + const hasDataRef = useRef(false); + const enabledRef = useRef(enabled); + const generationRef = useRef(0); + const runIdRef = useRef(0); + const loadingRunIdRef = useRef(0); + const inflightRef = useRef<{ generation: number; runId: number } | null>(null); + const queuedRunRef = useRef<{ + options?: { withLoading?: boolean; minLoadingMs?: number }; + resolve: () => void; + } | null>(null); + const fetcherRef = useRef(fetcher); + const mergeRef = useRef(merge); + const pollRef = useRef(options?.poll ?? true); + const resetKeyRef = useRef(resetKey); + const timerRef = useRef | null>(null); + + enabledRef.current = enabled; + fetcherRef.current = fetcher; + mergeRef.current = merge; + pollRef.current = options?.poll ?? true; + + const clearPollTimer = useCallback(() => { + if (timerRef.current !== null) { + clearTimeout(timerRef.current); + timerRef.current = null; + } + }, []); + + const pollDelayMs = useCallback(() => { + if (failuresRef.current >= 3) return intervalMs * 4; + return intervalMs; + }, [intervalMs]); + + const resolveQueuedRun = useCallback(() => { + queuedRunRef.current?.resolve(); + queuedRunRef.current = null; + }, []); + + const run = useCallback(async (options?: { withLoading?: boolean; minLoadingMs?: number }) => { + const generation = generationRef.current; + const runResetKey = resetKeyRef.current; + if (!enabledRef.current) return; + if (inflightRef.current?.generation === generation) { + if (options?.withLoading) { + queuedRunRef.current?.resolve(); + loadingRunIdRef.current = 0; + setLoadingKey(runResetKey); + setLoading(true); + return new Promise((resolve) => { + queuedRunRef.current = { options, resolve }; + }); + } + return; + } + const runId = ++runIdRef.current; + inflightRef.current = { generation, runId }; + const showLoading = options?.withLoading ?? !hasDataRef.current; + const startedAt = Date.now(); + const isCurrent = () => ( + generationRef.current === generation + && enabledRef.current + && inflightRef.current?.runId === runId + && resetKeyRef.current === runResetKey + ); + if (showLoading) { + loadingRunIdRef.current = runId; + setLoadingKey(runResetKey); + setLoading(true); + } + try { + const result = await fetcherRef.current(); + if (!isCurrent()) return; + if (result !== null) { + setDataKey(runResetKey); + setData((prev) => { + const mergeFn = mergeRef.current; + const next = mergeFn ? mergeFn(prev, result) : nextPollData(prev, result); + if (next !== prev) hasDataRef.current = true; + return next; + }); + setErrorKey(runResetKey); + setError(null); + failuresRef.current = 0; + } + } catch (err) { + if (!isCurrent()) return; + failuresRef.current += 1; + setDataKey(runResetKey); + setData(null); + hasDataRef.current = false; + setErrorKey(runResetKey); + setError(normalizePollingErrorMessage(err, stableT)); + } finally { + if (inflightRef.current?.runId === runId) { + inflightRef.current = null; + } + if (showLoading) { + const remaining = Math.max(0, (options?.minLoadingMs ?? 0) - (Date.now() - startedAt)); + if (remaining > 0) await delay(remaining); + if ( + generationRef.current === generation + && enabledRef.current + && resetKeyRef.current === runResetKey + && loadingRunIdRef.current === runId + ) { + loadingRunIdRef.current = 0; + setLoadingKey(runResetKey); + setLoading(false); + } + } + const queued = queuedRunRef.current; + if ( + queued + && generationRef.current === generation + && enabledRef.current + && resetKeyRef.current === runResetKey + ) { + queuedRunRef.current = null; + await run(queued.options); + queued.resolve(); + } + } + }, [stableT]); + + const scheduleNextPoll = useCallback(() => { + clearPollTimer(); + if (!enabledRef.current || !pollRef.current) return; + const generation = generationRef.current; + timerRef.current = setTimeout(() => { + void run({ withLoading: false }).finally(() => { + if (generationRef.current === generation) { + scheduleNextPoll(); + } + }); + }, pollDelayMs()); + }, [clearPollTimer, pollDelayMs, run]); + + useEffect(() => { + const resetChanged = resetKeyRef.current !== resetKey; + resetKeyRef.current = resetKey; + generationRef.current += 1; + inflightRef.current = null; + clearPollTimer(); + if (!enabled) { + resolveQueuedRun(); + loadingRunIdRef.current = 0; + setLoading(false); + setLoadingKey(resetKey); + setDataKey(resetKey); + setData(null); + setErrorKey(resetKey); + setError(null); + failuresRef.current = 0; + hasDataRef.current = false; + return undefined; + } + if (resetChanged) { + resolveQueuedRun(); + loadingRunIdRef.current = 0; + setLoading(false); + setLoadingKey(resetKey); + setDataKey(resetKey); + setData(null); + setErrorKey(resetKey); + setError(null); + failuresRef.current = 0; + hasDataRef.current = false; + } + const generation = generationRef.current; + void run({ withLoading: true }).finally(() => { + if (generationRef.current === generation && pollRef.current) scheduleNextPoll(); + }); + return () => { + generationRef.current += 1; + resolveQueuedRun(); + loadingRunIdRef.current = 0; + inflightRef.current = null; + clearPollTimer(); + }; + }, [clearPollTimer, enabled, intervalMs, options?.poll, resetKey, resolveQueuedRun, run, scheduleNextPoll]); + + const refresh = useCallback(async () => { + failuresRef.current = 0; + await run({ withLoading: true, minLoadingMs: 450 }); + }, [run]); + + return { + data: dataKey === resetKey ? data : null, + error: errorKey === resetKey ? error : null, + loading: loadingKey === resetKey ? loading : enabled, + refresh, + }; +} diff --git a/application/state/useTerminalAiContexts.architecture.test.ts b/application/state/useTerminalAiContexts.architecture.test.ts new file mode 100644 index 000000000..8309d3657 --- /dev/null +++ b/application/state/useTerminalAiContexts.architecture.test.ts @@ -0,0 +1,10 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; + +const source = readFileSync(new URL("./useTerminalAiContexts.ts", import.meta.url), "utf8"); + +test("useTerminalAiContexts imports AI context primitives from domain", () => { + assert.match(source, /from ['"]\.\.\/\.\.\/domain\/buildAITerminalSessionInfo['"]/); + assert.doesNotMatch(source, /from ['"].*components\//); +}); diff --git a/application/state/useTerminalAiContexts.ts b/application/state/useTerminalAiContexts.ts new file mode 100644 index 000000000..1ccbbc0d1 --- /dev/null +++ b/application/state/useTerminalAiContexts.ts @@ -0,0 +1,146 @@ +import type React from 'react'; +import { useCallback, useMemo, useRef } from 'react'; + +import { retainStableAiPanelContexts } from '../../domain/aiPanelContextsEqual'; +import { + buildAITerminalSessionInfo, + type AIPanelContext, +} from '../../domain/buildAITerminalSessionInfo'; +import { collectSessionIds } from '../../domain/workspace'; +import type { TerminalContextReader } from '../../domain/terminalContextRead'; +import { detectLocalOs } from '../../lib/localShell'; +import type { Host, PortForwardingRule, TerminalSession, Workspace } from '../../types'; + +interface UseTerminalAiContextsOptions { + hosts: Host[]; + hostsRef: React.MutableRefObject; + portForwardingRules: PortForwardingRule[]; + portForwardingRulesRef: React.MutableRefObject; + mountedAiTabIds: string[]; + sessionHostsMap: Map; + sessions: TerminalSession[]; + sessionsRef: React.MutableRefObject; + terminalContextReadersRef: React.MutableRefObject>; + workspaces: Workspace[]; + workspacesRef: React.MutableRefObject; +} + +export function useTerminalAiContexts({ + hosts, + hostsRef, + portForwardingRules, + portForwardingRulesRef, + mountedAiTabIds, + sessionHostsMap, + sessions, + sessionsRef, + terminalContextReadersRef, + workspaces, + workspacesRef, +}: UseTerminalAiContextsOptions) { + const previousAiContextsRef = useRef | null>(null); + const aiContextsByTabId = useMemo(() => { + const localOs = detectLocalOs(navigator.userAgent || navigator.platform); + const sessionById = new Map(sessions.map((session) => [session.id, session])); + const workspaceById = new Map(workspaces.map((workspace) => [workspace.id, workspace])); + const allHosts = hosts; + const tabIds = new Set(mountedAiTabIds); + + const contexts = new Map(); + + for (const tabId of tabIds) { + const workspace = workspaceById.get(tabId); + if (workspace) { + const sessionIds = collectSessionIds(workspace.root); + contexts.set(tabId, { + scopeType: 'workspace', + scopeTargetId: workspace.id, + scopeHostIds: sessionIds + .map((sessionId) => sessionById.get(sessionId)?.hostId) + .filter((hostId): hostId is string => !!hostId), + scopeLabel: workspace.title, + terminalSessions: sessionIds.map((sessionId) => + buildAITerminalSessionInfo( + sessionById.get(sessionId), + sessionHostsMap.get(sessionId), + localOs, + { allHosts, portForwardingRules }, + ), + ), + }); + continue; + } + + const session = sessionById.get(tabId); + if (!session) continue; + + contexts.set(tabId, { + scopeType: 'terminal', + scopeTargetId: session.id, + scopeHostIds: session.hostId ? [session.hostId] : [], + scopeLabel: session.hostLabel ?? '', + terminalSessions: [ + buildAITerminalSessionInfo( + session, + sessionHostsMap.get(session.id), + localOs, + { allHosts, portForwardingRules }, + ), + ], + }); + } + + const retained = retainStableAiPanelContexts(previousAiContextsRef.current, contexts); + previousAiContextsRef.current = retained; + return retained; + }, [sessions, workspaces, mountedAiTabIds, sessionHostsMap, hosts, portForwardingRules]); + + const resolveAIExecutorContext = useCallback((scope: { + type: 'terminal' | 'workspace'; + targetId?: string; + label?: string; + }) => { + const latestWorkspaces = workspacesRef.current; + const latestSessions = sessionsRef.current; + const latestHosts = hostsRef.current; + const localOs = detectLocalOs(navigator.userAgent || navigator.platform); + const sessionIds = scope.type === 'workspace' + ? (() => { + const workspace = scope.targetId ? latestWorkspaces.find((w) => w.id === scope.targetId) : undefined; + return workspace?.root ? collectSessionIds(workspace.root) : []; + })() + : scope.targetId ? [scope.targetId] : []; + + const workspaceName = scope.type === 'workspace' + ? latestWorkspaces.find((w) => w.id === scope.targetId)?.title ?? scope.label + : undefined; + + return { + sessions: sessionIds.map((sid) => { + const session = latestSessions.find((s) => s.id === sid); + const host = session ? sessionHostsMap.get(session.id) : undefined; + return buildAITerminalSessionInfo(session, host, localOs, { + allHosts: latestHosts, + portForwardingRules: portForwardingRulesRef.current, + }); + }), + workspaceId: scope.type === 'workspace' ? scope.targetId : undefined, + workspaceName, + readTerminalContext: (request: Parameters[0]) => { + const reader = terminalContextReadersRef.current.get(request.sessionId); + if (!reader) { + return Promise.resolve({ + ok: false as const, + error: `Terminal session "${request.sessionId}" has no readable terminal buffer.`, + }); + } + return reader(request); + }, + }; + }, [hostsRef, portForwardingRulesRef, sessionHostsMap, sessionsRef, terminalContextReadersRef, workspacesRef]); + + return { + aiContextsByTabId, + resolveAIExecutorContext, + }; +} diff --git a/application/state/useThemeRuntime.ts b/application/state/useThemeRuntime.ts index 20f4e3bd4..97996211b 100644 --- a/application/state/useThemeRuntime.ts +++ b/application/state/useThemeRuntime.ts @@ -1,4 +1,4 @@ -import { useCallback, useLayoutEffect, useMemo, useState } from 'react'; +import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react'; import type { TerminalTheme } from '../../domain/models'; import { @@ -42,7 +42,9 @@ export function useThemeRuntime(settings: ThemeRuntimeSettings) { const [userIntent, setUserIntent] = useState(idleThemeUserIntent()); - const appearanceSettings = useMemo((): TerminalAppearanceSettings => ({ + // Theme-id settings without accent — keeps resolveFocusedAppearance identity + // stable during color-picker drag (TerminalLayer memo depends on it). + const appearanceSettingsBase = useMemo((): Omit => ({ terminalThemeId, terminalThemeDarkId, terminalThemeLightId, @@ -50,8 +52,6 @@ export function useThemeRuntime(settings: ThemeRuntimeSettings) { resolvedTheme, lightUiThemeId, darkUiThemeId, - accentMode, - customAccent, }), [ terminalThemeId, terminalThemeDarkId, @@ -60,9 +60,17 @@ export function useThemeRuntime(settings: ThemeRuntimeSettings) { resolvedTheme, lightUiThemeId, darkUiThemeId, + ]); + + const accentRef = useRef({ accentMode, customAccent }); + accentRef.current = { accentMode, customAccent }; + + // Chrome / injection consumers need live accent on every settings change. + const appearanceSettings = useMemo((): TerminalAppearanceSettings => ({ + ...appearanceSettingsBase, accentMode, customAccent, - ]); + }), [appearanceSettingsBase, accentMode, customAccent]); const globalAppearance = useMemo(() => resolveGlobalTerminalAppearance({ userIntent, @@ -70,14 +78,21 @@ export function useThemeRuntime(settings: ThemeRuntimeSettings) { customThemes, }), [userIntent, appearanceSettings, customThemes]); + // Read accent from a ref so this callback identity does not churn on drag. + // Callers that invoke it after an accent-only update still get the latest + // accent; Terminal panes also re-apply appearanceChromeStore at the leaf. const resolveFocusedAppearance = useCallback((hostScope: TerminalAppearanceHostScope): ResolvedAppearance => ( resolveTerminalAppearance({ userIntent, - settings: appearanceSettings, + settings: { + ...appearanceSettingsBase, + accentMode: accentRef.current.accentMode, + customAccent: accentRef.current.customAccent, + }, hostScope, customThemes, }) - ), [userIntent, appearanceSettings, customThemes]); + ), [userIntent, appearanceSettingsBase, customThemes]); const applyFollowAppSettingsForPick = useCallback((themeId: string) => { const update = getFollowAppTerminalThemeSelectionUpdate(themeId); diff --git a/application/state/useVaultImportHandlers.architecture.test.ts b/application/state/useVaultImportHandlers.architecture.test.ts new file mode 100644 index 000000000..09e132253 --- /dev/null +++ b/application/state/useVaultImportHandlers.architecture.test.ts @@ -0,0 +1,12 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; + +const source = readFileSync(new URL("./useVaultImportHandlers.ts", import.meta.url), "utf8"); + +test("useVaultImportHandlers stays below the UI layer", () => { + assert.doesNotMatch(source, /from ["'].*components\//); + assert.doesNotMatch(source, /from ["'].*\/toast["']/); + assert.match(source, /notify: VaultImportNotifier/); + assert.match(source, /from ["']\.\/vaultImportOptions["']/); +}); diff --git a/application/state/useVaultImportHandlers.ts b/application/state/useVaultImportHandlers.ts new file mode 100644 index 000000000..911a013dd --- /dev/null +++ b/application/state/useVaultImportHandlers.ts @@ -0,0 +1,715 @@ +import { startTransition, useCallback, useEffect, useRef, useState } from "react"; + +import { + readRememberedKeyPassphrases, + rememberImportedKeyPassphrase, + resolveDefaultKeyPassphraseAliases, +} from "../defaultKeyPassphrases"; +import { + countVaultImportDuplicates, + ensureVaultImportPersisted, + mergeVaultImportedGroups, + rebaseVaultImportedHosts, + resolveUniqueManagedImportGroupName, + rollbackVaultImportedHosts, + waitForVaultImportProgressPaint, + type VaultHostPersistenceResult, + type VaultImportProgress, +} from "./vaultImportProgress"; +import { importVaultHostsInWorker } from "./vaultImportWorker"; +import { + type VaultLockHandle, + withVaultImportLock, +} from "./vaultManagedImportLock"; + +/** Exit the import lock so a concurrent host save can finish, then retry. */ +const RETRY_VAULT_IMPORT_AFTER_CONCURRENT_EDIT = Symbol("retry-vault-import-after-concurrent-edit"); +import { sanitizeHost } from "../../domain/host"; +import { + applyVaultImportDestination, + applyVaultHostImport, + buildVaultHostEndpointKey, + buildVaultHostMergeKey, + filterVaultImportKeyPassphrasesAgainstExisting, + mergeVaultImportIssues, + resolveVaultImportKeyPassphraseConflicts, + type VaultImportFormat, +} from "../../domain/vaultImport"; +import type { GroupConfig, Host, ManagedSource, SSHKey } from "../../types"; +import type { VaultImportNotifier, VaultImportOptions } from "./vaultImportOptions"; + +interface UseVaultImportHandlersOptions { + customGroups: string[]; + hosts: Host[]; + keys: SSHKey[]; + managedSources: ManagedSource[]; + notify: VaultImportNotifier; + onReadPersistedHosts: () => Promise; + onUpdateHosts: (hosts: Host[]) => VaultHostPersistenceResult | Promise; + onUpdateKeys: (keys: SSHKey[]) => void; + onReadPersistedManagedSources: () => ManagedSource[]; + onCommitVaultImportTransaction: ( + hosts: Host[], + updateGroups: (current: string[]) => string[], + updateSources: (current: ManagedSource[]) => ManagedSource[], + updateGroupConfigs?: (current: GroupConfig[]) => GroupConfig[], + expectedHosts?: Host[], + lock?: VaultLockHandle | null, + ) => Promise< + | { + status: "persisted"; + groups: string[]; + sources: ManagedSource[]; + groupConfigs: GroupConfig[]; + } + | { status: "superseded" } + >; + setIsImportOpen: (open: boolean) => void; + t: (key: string, values?: Record) => string; +} + +export function useVaultImportHandlers({ + customGroups, + hosts, + keys, + managedSources, + notify, + onReadPersistedHosts, + onUpdateHosts, + onUpdateKeys, + onReadPersistedManagedSources, + onCommitVaultImportTransaction, + setIsImportOpen, + t, +}: UseVaultImportHandlersOptions) { + const [importProgress, setImportProgress] = useState(null); + const customGroupsRef = useRef(customGroups); + const hostsRef = useRef(hosts); + const keysRef = useRef(keys); + const managedSourcesRef = useRef(managedSources); + const activeImportAbortRef = useRef(null); + const importCommitStartedRef = useRef(false); + const importInFlightRef = useRef(false); + customGroupsRef.current = customGroups; + hostsRef.current = hosts; + keysRef.current = keys; + managedSourcesRef.current = managedSources; + const resetImportProgress = useCallback(() => setImportProgress(null), []); + + useEffect(() => () => { + if (!importCommitStartedRef.current) activeImportAbortRef.current?.abort(); + activeImportAbortRef.current = null; + }, []); + + const cancelImport = useCallback(() => { + if (importCommitStartedRef.current) return; + activeImportAbortRef.current?.abort(); + activeImportAbortRef.current = null; + setImportProgress(null); + setIsImportOpen(false); + }, [setIsImportOpen]); + + const handleImportFileSelected = useCallback( + async (format: VaultImportFormat, files: File[], options?: VaultImportOptions) => { + const file = files[0]; + if (!file) return; + if (importInFlightRef.current) return; + importInFlightRef.current = true; + activeImportAbortRef.current?.abort(); + const abortController = new AbortController(); + activeImportAbortRef.current = abortController; + importCommitStartedRef.current = false; + const { signal } = abortController; + const throwIfCancelled = () => { + if (signal.aborted) { + throw new DOMException("Vault import cancelled.", "AbortError"); + } + }; + let rollbackSnapshot: { + baselineHosts: Host[]; + appliedHosts: Host[]; + } | null = null; + let rollbackPendingImport: () => Promise = async () => undefined; + const relativeRoot = file.webkitRelativePath?.split(/[\\/]+/).filter(Boolean)[0]; + const selectionName = files.length > 1 ? (relativeRoot || file.name) : file.name; + const formatLabel = + format === "putty" + ? "PuTTY" + : format === "mobaxterm" + ? "MobaXterm" + : format === "csv" + ? "CSV" + : format === "securecrt" + ? "SecureCRT" + : "ssh_config"; + const updateProgress = (next: Partial) => { + setImportProgress((current) => ({ + status: "running", + stage: "reading", + percent: 5, + formatLabel, + fileName: selectionName, + totalFiles: files.length, + ...current, + ...next, + })); + }; + + setIsImportOpen(false); + setImportProgress({ + status: "running", + stage: "reading", + percent: 5, + formatLabel, + fileName: selectionName, + completedFiles: 0, + totalFiles: files.length, + }); + + try { + let result = await importVaultHostsInWorker({ + format, + files, + encoding: options?.encoding, + signal, + onProgress: (progress) => { + if (!signal.aborted) updateProgress(progress); + }, + }); + throwIfCancelled(); + const isManaged = format === "ssh_config" && options?.managed === true; + if (!isManaged) { + result = applyVaultImportDestination( + result, + options?.destination ?? { mode: "preserve" }, + // SecureCRT keeps distinct session files that share an endpoint; + // only rewrite their group when the user picks an import location. + { collapseDuplicateEndpoints: format !== "securecrt" }, + ); + } + updateProgress({ stage: "preparing", percent: 70 }); + await waitForVaultImportProgressPaint(); + throwIfCancelled(); + updateProgress({ stage: "saving", percent: 85 }); + await waitForVaultImportProgressPaint(); + throwIfCancelled(); + + const currentCustomGroups = customGroupsRef.current; + const currentHosts = hostsRef.current; + const currentManagedSources = managedSourcesRef.current; + const persistHosts = async ( + nextHosts: Host[], + options?: { + baselineHosts?: Host[]; + persistAttempt?: ( + hosts: Host[], + baselineHosts: Host[], + ) => Promise; + prepareAttempt?: (attempt: { baselineHosts: Host[]; appliedHosts: Host[] }) => Host[]; + }, + ) => { + throwIfCancelled(); + importCommitStartedRef.current = true; + let baselineHosts = options?.baselineHosts ?? currentHosts; + let appliedHosts = nextHosts; + while (true) { + appliedHosts = options?.prepareAttempt?.({ baselineHosts, appliedHosts }) ?? appliedHosts; + rollbackSnapshot = { baselineHosts, appliedHosts }; + let persisted: VaultHostPersistenceResult; + if (options?.persistAttempt) { + persisted = await options.persistAttempt(appliedHosts, baselineHosts); + } else { + let hostUpdate: VaultHostPersistenceResult | Promise; + startTransition(() => { + hostUpdate = onUpdateHosts(appliedHosts); + }); + persisted = await hostUpdate!; + } + if (persisted !== "superseded") { + if (persisted !== false) rollbackSnapshot = null; + return persisted; + } + + // Locked import commits must release the shared lock before retrying + // so a concurrent host save queued behind that lock can finish first. + if (options?.persistAttempt) { + throw RETRY_VAULT_IMPORT_AFTER_CONCURRENT_EDIT; + } + + const latestHosts = hostsRef.current; + hostsRef.current = latestHosts; + appliedHosts = rebaseVaultImportedHosts({ + currentHosts: latestHosts, + baselineHosts, + appliedHosts, + }); + baselineHosts = latestHosts; + } + }; + + rollbackPendingImport = async () => { + const snapshot = rollbackSnapshot; + if (!snapshot) return; + while (true) { + const rollbackHosts = rollbackVaultImportedHosts({ + currentHosts: hostsRef.current, + ...snapshot, + }); + let rollbackUpdate: VaultHostPersistenceResult | Promise; + startTransition(() => { + rollbackUpdate = onUpdateHosts(rollbackHosts); + }); + const persisted = await rollbackUpdate!; + if (persisted === "superseded") continue; + if (persisted === false) { + throw new Error(t("vault.import.progress.persistFailed")); + } + rollbackSnapshot = null; + return; + } + }; + + const fileBaseName = file.name.replace(/\.[^/.]+$/, ""); + const requestedManagedGroup = options?.destination?.mode === "preserve" + ? null + : options?.destination?.group ?? null; + let managedGroupName = requestedManagedGroup ?? `${fileBaseName} - Managed`; + + // Check if this file is already managed + const bridge = (window as unknown as { netcatty?: { getPathForFile?: (file: File) => string | undefined } }).netcatty; + // Try bridge.getPathForFile first, then fall back to file.path (Electron legacy) + const filePath = bridge?.getPathForFile?.(file) || (file as File & { path?: string }).path; + + if (isManaged && !filePath) { + // Cannot proceed with managed import without a valid file path + const message = t("vault.import.sshConfig.noFilePathDesc"); + updateProgress({ + status: "error", + stage: "failed", + error: message, + }); + notify.error( + message, + t("vault.import.sshConfig.noFilePath"), + ); + return; + } + + if (isManaged) { + const existingSource = currentManagedSources.find(s => s.filePath === filePath); + if (existingSource) { + const message = t("vault.import.sshConfig.alreadyManagedDesc", { + group: existingSource.groupName, + }); + updateProgress({ + status: "error", + stage: "failed", + error: message, + }); + notify.error( + message, + t("vault.import.sshConfig.alreadyManaged"), + ); + return; + } + } + + // Managed ssh_config rematch is endpoint-only; CSV/other imports treat + // group as part of session identity so direct vs proxy copies can coexist. + const makeKey = isManaged ? buildVaultHostEndpointKey : buildVaultHostMergeKey; + + const existingKeys = new Set(currentHosts.map(makeKey)); + // Filter out duplicates for both managed and non-managed imports + let newHosts = format === "securecrt" + ? result.hosts + : result.hosts.filter((h) => !existingKeys.has(makeKey(h))); + + // For managed imports, also update existing hosts to be managed + let updatedExistingHosts: Host[] = []; + if (isManaged) { + const importedKeys = new Set(result.hosts.map(makeKey)); + updatedExistingHosts = currentHosts.filter((h) => importedKeys.has(makeKey(h))); + } + + if (isManaged && (newHosts.length > 0 || updatedExistingHosts.length > 0)) { + while (true) { + try { + await withVaultImportLock("vault", async (lock) => { + const latestPersistedSources = onReadPersistedManagedSources(); + managedSourcesRef.current = latestPersistedSources; + const sourceClaim = latestPersistedSources.find((source) => source.filePath === filePath); + if (sourceClaim) { + throw new Error(t("vault.import.sshConfig.alreadyManagedDesc", { + group: sourceClaim.groupName, + })); + } + const managedBaselineHosts = await onReadPersistedHosts(); + hostsRef.current = managedBaselineHosts; + const managedExistingKeys = new Set(managedBaselineHosts.map(makeKey)); + newHosts = result.hosts.filter((host) => !managedExistingKeys.has(makeKey(host))); + const managedImportedKeys = new Set(result.hosts.map(makeKey)); + updatedExistingHosts = managedBaselineHosts.filter((host) => ( + !host.managedSourceId && managedImportedKeys.has(makeKey(host)) + )); + if (newHosts.length === 0 && updatedExistingHosts.length === 0) return; + const sourceId = crypto.randomUUID(); + let newSource: ManagedSource = { + id: sourceId, + type: "ssh_config", + filePath: filePath, + groupName: managedGroupName, + lastSyncedAt: Date.now(), + }; + + newHosts = newHosts.map((h) => ({ + ...h, + group: managedGroupName, + // Only SSH hosts can be managed (SSH config only supports SSH) + managedSourceId: (!h.protocol || h.protocol === "ssh") ? sourceId : undefined, + })); + + // Update existing hosts to be managed (move to managed group) + const existingHostIds = new Set(updatedExistingHosts.map(h => h.id)); + const updatedHosts = managedBaselineHosts.map((h) => { + if (!existingHostIds.has(h.id)) return h; + const canBeManaged = !h.protocol || h.protocol === "ssh"; + return { + ...h, + group: managedGroupName, + managedSourceId: canBeManaged ? sourceId : undefined, + // Sanitize label for managed hosts + label: canBeManaged && h.label ? h.label.replace(/\s/g, '') : h.label, + }; + }); + + let nextGroups: string[] = []; + const ensureManagedSourceStillAvailable = () => { + const conflictingSource = managedSourcesRef.current.find((source) => ( + source.id !== sourceId && source.filePath === filePath + )); + if (conflictingSource) { + throw new Error(t("vault.import.sshConfig.alreadyManagedDesc", { + group: conflictingSource.groupName, + })); + } + }; + const prepareManagedAttempt = ({ + baselineHosts, + appliedHosts, + }: { + baselineHosts: Host[]; + appliedHosts: Host[]; + }) => { + ensureManagedSourceStillAvailable(); + managedGroupName = requestedManagedGroup ?? resolveUniqueManagedImportGroupName({ + baseName: fileBaseName, + customGroups: customGroupsRef.current, + hosts: baselineHosts, + managedSources: managedSourcesRef.current, + ownerSourceId: sourceId, + }); + newSource = { ...newSource, groupName: managedGroupName }; + nextGroups = Array.from(new Set([ + ...currentCustomGroups, + ...(requestedManagedGroup ? [] : result.groups), + managedGroupName, + ])); + return appliedHosts.map((host) => ( + host.managedSourceId === sourceId + ? { ...host, group: managedGroupName } + : host + )); + }; + const hostPersisted = await persistHosts( + [...updatedHosts, ...newHosts].map((host: Host) => sanitizeHost(host)), + { + baselineHosts: managedBaselineHosts, + prepareAttempt: prepareManagedAttempt, + persistAttempt: async (hostsToCommit, baselineHosts) => { + const transaction = await onCommitVaultImportTransaction( + hostsToCommit, + (latestPersistedGroups) => mergeVaultImportedGroups({ + currentGroups: latestPersistedGroups, + baselineGroups: currentCustomGroups, + appliedGroups: nextGroups, + }), + (latestPersistedSources) => { + const conflictingSource = latestPersistedSources.find((source) => ( + source.id !== sourceId && source.filePath === filePath + )); + if (conflictingSource) { + throw new Error(t("vault.import.sshConfig.alreadyManagedDesc", { + group: conflictingSource.groupName, + })); + } + return [ + ...latestPersistedSources.filter((source) => source.id !== newSource.id), + newSource, + ]; + }, + undefined, + baselineHosts, + lock, + ); + if (transaction.status === "superseded") return "superseded"; + customGroupsRef.current = transaction.groups; + managedSourcesRef.current = transaction.sources; + return true; + }, + }, + ); + await ensureVaultImportPersisted( + hostPersisted, + t("vault.import.progress.persistFailed"), + undefined, + rollbackPendingImport, + ); + }); + break; + } catch (error) { + if (error !== RETRY_VAULT_IMPORT_AFTER_CONCURRENT_EDIT) throw error; + // Drain concurrent locked writes outside the critical section. + hostsRef.current = await onReadPersistedHosts(); + } + } + } else if (newHosts.length > 0) { + let addedHostIds = new Set(); + let addedHostKeyPaths = new Map(); + while (true) { + try { + await withVaultImportLock("vault", async (lock) => { + const importBaselineHosts = await onReadPersistedHosts(); + hostsRef.current = importBaselineHosts; + const importBaselineGroups = customGroupsRef.current; + const merged = applyVaultHostImport( + importBaselineHosts, + importBaselineGroups, + result, + { skipDuplicates: format !== "securecrt" }, + ); + newHosts = merged.addedHosts; + addedHostIds = new Set(merged.addedHosts.map((host) => host.id)); + addedHostKeyPaths = new Map(merged.addedHosts.flatMap((host) => { + const keyPath = host.identityFilePaths?.find((path) => path.trim())?.trim(); + return keyPath ? [[host.id, keyPath] as const] : []; + })); + if (newHosts.length === 0) return; + const hostPersisted = await persistHosts(merged.hosts, { + baselineHosts: importBaselineHosts, + persistAttempt: async (hostsToCommit, baselineHosts) => { + const transaction = await onCommitVaultImportTransaction( + hostsToCommit, + (latestPersistedGroups) => mergeVaultImportedGroups({ + currentGroups: latestPersistedGroups, + baselineGroups: importBaselineGroups, + appliedGroups: merged.customGroups, + }), + (latestPersistedSources) => latestPersistedSources, + undefined, + baselineHosts, + lock, + ); + if (transaction.status === "superseded") return "superseded"; + customGroupsRef.current = transaction.groups; + managedSourcesRef.current = transaction.sources; + return true; + }, + }); + await ensureVaultImportPersisted( + hostPersisted, + t("vault.import.progress.persistFailed"), + undefined, + rollbackPendingImport, + ); + }); + break; + } catch (error) { + if (error !== RETRY_VAULT_IMPORT_AFTER_CONCURRENT_EDIT) throw error; + hostsRef.current = await onReadPersistedHosts(); + } + } + throwIfCancelled(); + const resolved = await resolveVaultImportKeyPassphraseConflicts( + result.keyPassphraseCandidates ?? result.keyPassphrases ?? [], + resolveDefaultKeyPassphraseAliases, + addedHostIds, + addedHostKeyPaths, + ); + throwIfCancelled(); + const checked = await filterVaultImportKeyPassphrasesAgainstExisting( + resolved.keyPassphrases, + (keyPath) => readRememberedKeyPassphrases(keyPath, keysRef.current), + ); + throwIfCancelled(); + result.issues = mergeVaultImportIssues( + result.issues, + resolved.issues, + checked.issues, + ); + for (const entry of checked.keyPassphrases) { + try { + const saved = await rememberImportedKeyPassphrase({ + keyPath: entry.keyPath, + passphrase: entry.passphrase, + keys: keysRef.current, + getKeys: () => keysRef.current, + updateKeys: onUpdateKeys, + setCurrentKeys: (updatedKeys) => { + keysRef.current = updatedKeys; + }, + }); + throwIfCancelled(); + if (saved === "conflict") { + result.issues.push({ + level: "warning", + message: `CSV passphrase conflicts with an existing saved passphrase for KeyPath "${entry.keyPath}"; the existing passphrase was kept.`, + }); + } else if (saved === "unreadable") { + result.issues.push({ + level: "warning", + message: `Could not verify the existing saved passphrase for KeyPath "${entry.keyPath}"; the imported passphrase was not saved.`, + }); + } + } catch (error) { + if (error instanceof DOMException && error.name === "AbortError") { + throw error; + } + result.issues.push({ + level: "warning", + message: `Could not save the passphrase for KeyPath "${entry.keyPath}".`, + }); + } + } + result.issues = mergeVaultImportIssues(result.issues); + } + + // Count total hosts affected (new + converted to managed) + const totalAffected = newHosts.length + (isManaged ? updatedExistingHosts.length : 0); + + const skipped = result.stats.skipped; + const duplicates = countVaultImportDuplicates({ + importedHostCount: result.hosts.length, + newHostCount: newHosts.length, + fileDuplicateCount: result.stats.duplicates, + managed: isManaged, + }); + const hasWarnings = skipped > 0 || duplicates > 0 || result.issues.length > 0; + + if (result.stats.parsed === 0 && totalAffected === 0) { + const message = t("vault.import.toast.noEntries", { format: formatLabel }); + updateProgress({ + status: "error", + stage: "failed", + error: message, + }); + notify.error( + message, + t("vault.import.toast.failedTitle"), + ); + return; + } + + if (totalAffected === 0) { + updateProgress({ + status: "complete", + stage: "complete", + percent: 100, + imported: 0, + skipped, + duplicates, + }); + notify.warning( + t("vault.import.toast.noNewHosts", { format: formatLabel }), + t("vault.import.toast.completedTitle"), + ); + return; + } + + throwIfCancelled(); + rollbackSnapshot = null; + + if (isManaged) { + notify.success( + t("vault.import.sshConfig.managedSuccess", { count: totalAffected }), + t("vault.import.toast.completedTitle"), + ); + } else { + const details = t("vault.import.toast.summary", { + count: totalAffected, + skipped, + duplicates, + }); + + if (hasWarnings) { + const firstIssue = result.issues[0]?.message; + notify.warning( + firstIssue ? `${details} ${t("vault.import.toast.firstIssue", { issue: firstIssue })}` : details, + t("vault.import.toast.completedTitle"), + ); + } else { + notify.success(details, t("vault.import.toast.completedTitle")); + } + } + updateProgress({ + status: "complete", + stage: "complete", + percent: 100, + imported: totalAffected, + skipped, + duplicates, + }); + } catch (err) { + let rollbackFailure: unknown; + if (rollbackSnapshot) { + try { + await rollbackPendingImport(); + } catch (rollbackError) { + rollbackFailure = rollbackError; + console.error("[vault import] Failed to rollback imported hosts.", rollbackError); + } + } + if ( + !rollbackFailure + && ( + signal.aborted + || (err instanceof DOMException && err.name === "AbortError") + ) + ) return; + const originalMessage = + err instanceof Error ? err.message : t("common.unknownError"); + const message = rollbackFailure + ? `${originalMessage} ${t("vault.import.progress.rollbackFailed")}` + : originalMessage; + updateProgress({ + status: "error", + stage: "failed", + error: message, + }); + notify.error(message, t("vault.import.toast.failedTitle")); + } finally { + if (activeImportAbortRef.current === abortController) { + activeImportAbortRef.current = null; + } + importCommitStartedRef.current = false; + importInFlightRef.current = false; + } + }, + [ + notify, + onReadPersistedHosts, + onCommitVaultImportTransaction, + onReadPersistedManagedSources, + onUpdateHosts, + onUpdateKeys, + setIsImportOpen, + t, + ], + ); + + return { + cancelImport, + handleImportFileSelected, + importProgress, + resetImportProgress, + }; +} diff --git a/application/state/useVaultState.ts b/application/state/useVaultState.ts index f133f1dbb..1e19c0b51 100644 --- a/application/state/useVaultState.ts +++ b/application/state/useVaultState.ts @@ -65,6 +65,10 @@ import { } from "../../domain/connectionLogTerminalData"; import { getNextVaultOrder, normalizeVaultOrder } from "../../domain/vaultOrder"; import { loadSanitizedShellHistory } from "./shellHistoryPersistence"; +import { + publishNotesSnapshot, + registerNotesActions, +} from "./notesStore"; import { publishShellHistorySnapshot } from "./shellHistoryStore"; import { setVaultInitialized } from "./vaultInitStore"; import { @@ -280,9 +284,13 @@ export const useVaultState = () => { const customGroupsRef = useRef([]); const managedSourcesRef = useRef([]); const hostsRef = useRef([]); + const notesRef = useRef([]); + const noteGroupsRef = useRef([]); customGroupsRef.current = customGroups; managedSourcesRef.current = managedSources; hostsRef.current = hosts; + notesRef.current = notes; + noteGroupsRef.current = noteGroups; // Write-version counters prevent out-of-order async writes from overwriting // newer data. Each update bumps the counter; the .then() callback only @@ -591,14 +599,20 @@ export const useVaultState = () => { const updateNotes = useCallback((data: Partial[]) => { const cleaned = normalizeVaultNotes(data); + notesRef.current = cleaned; setNotes(cleaned); localStorageAdapter.write(STORAGE_KEY_NOTES, cleaned); + // Publish synchronously so Notes→AI handoff does not read a stale catalog + // while React state is still committing (useLayoutEffect republishes too). + publishNotesSnapshot({ notes: cleaned, noteGroups: noteGroupsRef.current }); }, []); const updateNoteGroups = useCallback((data: unknown) => { const cleaned = normalizeNoteGroups(data); + noteGroupsRef.current = cleaned; setNoteGroups(cleaned); localStorageAdapter.write(STORAGE_KEY_NOTE_GROUPS, cleaned); + publishNotesSnapshot({ notes: notesRef.current, noteGroups: cleaned }); }, []); const updateCustomGroups = useCallback(( @@ -828,6 +842,18 @@ export const useVaultState = () => { publishShellHistorySnapshot(shellHistory); }, [shellHistory]); + // Notes catalog for Notes / AI side panels — keep TerminalLayer off the hot path. + useLayoutEffect(() => { + publishNotesSnapshot({ notes, noteGroups }); + }, [notes, noteGroups]); + + useLayoutEffect(() => { + registerNotesActions({ updateNotes, updateNoteGroups }); + return () => { + registerNotesActions(null); + }; + }, [updateNotes, updateNoteGroups]); + const addShellHistoryEntry = useCallback( (entry: Omit) => { setShellHistory((prev) => { @@ -1375,9 +1401,12 @@ export const useVaultState = () => { const updateHostLastConnected = useCallback((hostId: string) => { setHosts((prev) => { - const next = prev.map((h) => - h.id === hostId ? { ...h, lastConnectedAt: Date.now() } : h, - ); + const idx = prev.findIndex((h) => h.id === hostId); + if (idx < 0) return prev; + const now = Date.now(); + if (prev[idx].lastConnectedAt === now) return prev; + const next = prev.slice(); + next[idx] = { ...prev[idx], lastConnectedAt: now }; const ver = ++hostsWriteVersion.current; const encryptPromise = encryptHosts(next); hostsEncryptPendingRef.current = encryptPromise.then(() => undefined); diff --git a/application/state/vaultImportOptions.ts b/application/state/vaultImportOptions.ts new file mode 100644 index 000000000..0984f26fa --- /dev/null +++ b/application/state/vaultImportOptions.ts @@ -0,0 +1,17 @@ +import type { VaultImportDestination } from "../../domain/vaultImport"; +import type { VaultImportFileEncoding } from "./vaultImportFile"; + +/** Options for a vault host-file import (kept out of UI modules). */ +export type VaultImportOptions = { + managed?: boolean; + filePath?: string; + encoding?: VaultImportFileEncoding; + destination?: VaultImportDestination; +}; + +/** Notification sink so application/state hooks do not import UI toast. */ +export type VaultImportNotifier = { + success: (message: string, title?: string) => void; + error: (message: string, title?: string) => void; + warning: (message: string, title?: string) => void; +}; diff --git a/components/AIChatPanelContent.tsx b/components/AIChatPanelContent.tsx index 73ae19f05..fa245bea8 100644 --- a/components/AIChatPanelContent.tsx +++ b/components/AIChatPanelContent.tsx @@ -49,8 +49,8 @@ interface AIChatPanelContentProps { handleDeleteSession: (event: React.MouseEvent, sessionId: string) => void; messages: ChatMessage[]; isStreaming: boolean; - activeCompaction?: import('./ai/hooks/useAgentCompactionUi').ActiveCompactionUi | null; - contextUsage?: import('./ai/hooks/useAgentCompactionUi').AgentContextUsage | null; + activeCompaction?: import('../application/state/useAgentCompactionUi').ActiveCompactionUi | null; + contextUsage?: import('../application/state/useAgentCompactionUi').AgentContextUsage | null; inputValue: string; setInputValue: (value: string) => void; handleSend: () => void; diff --git a/components/AIChatSidePanel.tsx b/components/AIChatSidePanel.tsx index 295d95668..d737802dd 100644 --- a/components/AIChatSidePanel.tsx +++ b/components/AIChatSidePanel.tsx @@ -49,7 +49,7 @@ import { getNetcattyBridge, isAIChatSessionStreaming, type DefaultTargetSessionHint, -} from './ai/hooks/useAIChatStreaming'; +} from '../application/state/useAIChatStreaming'; import { getScopedHistorySessions } from './ai/scopedHistorySessions'; import { aiSessionIdSetEqual, exactScopeAISessionsEqual } from '../domain/aiSessionsForScope'; import { buildExternalAgentHistoryMessagesForBridge } from './ai/externalAgentHistory'; @@ -60,7 +60,7 @@ import { stopAgentTurn } from '../infrastructure/ai/harness/agentStop'; import { getAgentRuntime } from '../infrastructure/ai/harness/globalAgentRuntime'; import { useAIPermissionGrantsState } from '../application/state/useAIPermissionGrantsState'; import { useConversationExport } from './ai/hooks/useConversationExport'; -import { useAgentContextUsage } from './ai/hooks/useAgentCompactionUi'; +import { useAgentContextUsage } from '../application/state/useAgentCompactionUi'; import type { AIChatSidePanelProps } from './AIChatSidePanel.types'; import { buildCursorListModelsAgentEnv, diff --git a/components/SftpSidePanel.tsx b/components/SftpSidePanel.tsx index cec9dfa5c..bc6b9c2a9 100644 --- a/components/SftpSidePanel.tsx +++ b/components/SftpSidePanel.tsx @@ -27,7 +27,6 @@ import { useI18n } from "../application/i18n/I18nProvider"; import { useSftpState } from "../application/state/useSftpState"; import { useReportSftpTransferOwnerActivity, - useWarmSftpTransferPool, } from "../application/state/sftp/useSftpTransferLifecycle"; import { registerEditorSftpWriterScoped } from "../application/state/editorSftpBridge"; import { @@ -61,7 +60,7 @@ import { SftpContextProvider } from "./sftp"; import { useSftpViewPaneCallbacks } from "./sftp/hooks/useSftpViewPaneCallbacks"; import { useSftpViewTabs } from "./sftp/hooks/useSftpViewTabs"; import { useSftpKeyboardShortcuts } from "./sftp/hooks/useSftpKeyboardShortcuts"; -import { sftpFocusStore } from "./sftp/hooks/useSftpFocusedPane"; +import { sftpFocusStore } from "../application/state/sftp/sftpFocusStore"; import { keepOnlyPaneSelections } from "./sftp/hooks/selectionScope"; import { KeyBinding, HotkeyScheme } from "../domain/models"; import { @@ -300,12 +299,6 @@ const SftpSidePanelInner: React.FC = ({ const sftpRef = useRef(sftp); sftpRef.current = sftp; - useWarmSftpTransferPool({ - hostIds: connectedHosts.map((entry) => entry.host.id), - activeHostId: activeHost?.protocol === "serial" ? undefined : activeHost?.id, - warmTransferPoolForHost: sftp.warmTransferPoolForHost, - }); - const { getConnectionCacheKey, leftPane } = sftp; useEffect(() => { diff --git a/components/SftpView.tsx b/components/SftpView.tsx index 228619ed2..245cd93ff 100644 --- a/components/SftpView.tsx +++ b/components/SftpView.tsx @@ -29,7 +29,6 @@ import { Host, Identity, KnownHost, ProxyProfile, SSHKey, TransferTask } from ". import { resolveGroupDefaults, applyGroupDefaults } from "../domain/groupConfig"; import { materializeHostProxyProfile } from "../domain/proxyProfiles"; import { useSftpFileAssociations } from "../application/state/useSftpFileAssociations"; -import { useWarmSftpTransferPool } from "../application/state/sftp/useSftpTransferLifecycle"; import { registerEditorSftpWriterScoped } from "../application/state/editorSftpBridge"; import { toast } from "./ui/toast"; @@ -44,7 +43,7 @@ import { SftpContextProvider, activeTabStore } from "./sftp"; import { useSftpViewPaneCallbacks } from "./sftp/hooks/useSftpViewPaneCallbacks"; import { useSftpViewTabs } from "./sftp/hooks/useSftpViewTabs"; import { useSftpKeyboardShortcuts } from "./sftp/hooks/useSftpKeyboardShortcuts"; -import { sftpFocusStore, SftpFocusedSide, useSftpFocusedSide } from "./sftp/hooks/useSftpFocusedPane"; +import { sftpFocusStore, SftpFocusedSide, useSftpFocusedSide } from "../application/state/sftp/sftpFocusStore"; import { keepOnlyActivePaneSelections, keepOnlyPaneSelections } from "./sftp/hooks/selectionScope"; @@ -186,11 +185,6 @@ const SftpViewInner: React.FC = ({ const sftpRef = useRef(sftp); sftpRef.current = sftp; - useWarmSftpTransferPool({ - hostIds: connectedHosts.map((entry) => entry.host.id), - warmTransferPoolForHost: sftp.warmTransferPoolForHost, - }); - // Register this useSftpState's writeTextFileByConnection with the bridge so // the editor tab's save path can reach the active SFTP session. The bridge // supports multiple simultaneous writers (SftpSidePanel inside terminals diff --git a/components/Terminal.accentBase.test.ts b/components/Terminal.accentBase.test.ts new file mode 100644 index 000000000..03f2f9063 --- /dev/null +++ b/components/Terminal.accentBase.test.ts @@ -0,0 +1,24 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; + +const source = readFileSync(new URL("./Terminal.tsx", import.meta.url), "utf8"); + +test("Terminal re-resolves catalog theme before applying store accent", () => { + // appearanceTheme may still carry a baked custom accent while TerminalLayer + // memo ignores accent churn. Switching accentMode back to `theme` must clear + // cursor/selection by starting from the clean catalog theme id. + assert.match(source, /useAppearanceChromeStore\(\)/); + assert.match( + source, + /getBuiltinTerminalThemeById\(appearanceTheme\.id\)/, + ); + assert.match( + source, + /applyCustomAccentToTerminalTheme\(resolveBase\(\), accentMode, customAccent\)/, + ); + assert.doesNotMatch( + source, + /if \(appearanceTheme\) return appearanceTheme;/, + ); +}); diff --git a/components/Terminal.tsx b/components/Terminal.tsx index 37e65ca9c..e50b03306 100644 --- a/components/Terminal.tsx +++ b/components/Terminal.tsx @@ -66,6 +66,7 @@ import { useStoredBoolean } from "../application/state/useStoredBoolean"; import { readOptionalStoredStringValue, useStoredString } from "../application/state/useStoredString"; import { useSessionLogBackend } from "../application/state/useSessionLogBackend"; import { useTerminalLayoutSuppressActive } from "../application/state/terminalLayoutSuppressStore"; +import { useAppearanceChromeStore } from "../application/state/appearanceChromeStore"; import { shouldPublishPluginTerminalSessionMountLifecycle, usePluginTerminalSessionLifecycle, @@ -260,8 +261,6 @@ const TerminalComponent: React.FC = ({ fontSize, terminalTheme, followAppTerminalTheme = false, - accentMode = "theme", - customAccent = "", terminalSettings, sessionId, workspaceId, @@ -1264,22 +1263,31 @@ const TerminalComponent: React.FC = ({ }); }, [availableFonts, fontFamilyId, hasFontFamilyOverride, host.fontFamily, terminalSettings?.fallbackFont]); + const { accentMode, customAccent } = useAppearanceChromeStore(); + const baseEffectiveTheme = useMemo(() => { - if (appearanceTheme) return appearanceTheme; - if (followAppTerminalTheme) { - return applyCustomAccentToTerminalTheme(terminalTheme, accentMode, customAccent); - } - const themeId = resolveHostTerminalThemeId( - { theme: host.theme, themeOverride: host.themeOverride } as Pick, - terminalTheme.id, - ); - let baseTheme = terminalTheme; - if (themeId) { - const hostTheme = getBuiltinTerminalThemeById(themeId) - || customThemes.find((t) => t.id === themeId); - if (hostTheme) baseTheme = hostTheme; - } - return applyCustomAccentToTerminalTheme(baseTheme, accentMode, customAccent); + // Always re-apply appearanceChromeStore accent. appearanceTheme from the + // layer may still carry a previously baked custom accent while TerminalLayer + // memo ignores accent churn — re-resolve the catalog theme by id first. + const resolveBase = (): typeof terminalTheme => { + if (appearanceTheme) { + const clean = getBuiltinTerminalThemeById(appearanceTheme.id) + || customThemes.find((t) => t.id === appearanceTheme.id); + if (clean) return clean; + } + if (followAppTerminalTheme) return terminalTheme; + const themeId = resolveHostTerminalThemeId( + { theme: host.theme, themeOverride: host.themeOverride } as Pick, + terminalTheme.id, + ); + if (themeId) { + const hostTheme = getBuiltinTerminalThemeById(themeId) + || customThemes.find((t) => t.id === themeId); + if (hostTheme) return hostTheme; + } + return terminalTheme; + }; + return applyCustomAccentToTerminalTheme(resolveBase(), accentMode, customAccent); }, [accentMode, appearanceTheme, customAccent, customThemes, followAppTerminalTheme, host.theme, host.themeOverride, terminalTheme]); const resolvedChainHosts = diff --git a/components/TerminalLayer.memo.test.tsx b/components/TerminalLayer.memo.test.tsx index 2324973b8..650264cd4 100644 --- a/components/TerminalLayer.memo.test.tsx +++ b/components/TerminalLayer.memo.test.tsx @@ -217,6 +217,32 @@ test("TerminalLayer ignores shellHistory prop churn (reads shellHistoryStore ins ); }); +test("TerminalLayer ignores notes prop churn (reads notesStore instead)", () => { + assert.equal( + terminalLayerAreEqual( + baseProps as never, + { + ...baseProps, + notes: [{ id: "n1", title: "One", content: "body", tags: [], createdAt: 1, updatedAt: 1, order: 1000 }], + noteGroups: ["Ops"], + updateNotes: () => {}, + updateNoteGroups: () => {}, + } as never, + ), + true, + ); +}); + +test("TerminalLayer ignores customAccent prop churn (reads appearanceChromeStore instead)", () => { + assert.equal( + terminalLayerAreEqual( + baseProps as never, + { ...baseProps, accentMode: "custom", customAccent: "#ff00aa" } as never, + ), + true, + ); +}); + test("TerminalLayer ignores sessions dynamicTitle-only updates", () => { const sessionsA = [{ id: "s1", diff --git a/components/TerminalLayer.tsx b/components/TerminalLayer.tsx index 5ff1c4436..0c3742c7d 100644 --- a/components/TerminalLayer.tsx +++ b/components/TerminalLayer.tsx @@ -173,8 +173,6 @@ const TerminalLayerInner: React.FC = ({ identities, snippets, snippetPackages, - notes, - noteGroups, openNoteRequest, onOpenVaultNoteFromChat, onOpenVaultHostFromChat, @@ -237,8 +235,6 @@ const TerminalLayerInner: React.FC = ({ updateHosts, updateSnippets, updateSnippetPackages, - updateNotes, - updateNoteGroups, sftpDefaultViewMode, sftpDoubleClickBehavior, sftpAutoSync, @@ -2165,8 +2161,6 @@ const TerminalLayerInner: React.FC = ({ programmaticCommandLogRewriteHandlersRef, snippetPackages, snippets, - noteGroups, - notes, onOpenVaultHostFromChat, onOpenVaultNoteFromChat: handleOpenVaultNoteFromAiPanel, onOpenVaultSectionFromChat, @@ -2189,8 +2183,6 @@ const TerminalLayerInner: React.FC = ({ TooltipContent, TooltipTrigger, updateHosts, - updateNoteGroups, - updateNotes, updateSnippetPackages, updateSnippets, X, diff --git a/components/VaultView.memo.test.tsx b/components/VaultView.memo.test.tsx index 6e9ea53b6..221237b0c 100644 --- a/components/VaultView.memo.test.tsx +++ b/components/VaultView.memo.test.tsx @@ -1,29 +1,29 @@ import test from "node:test"; import assert from "node:assert/strict"; -import { vaultViewAreEqual } from "./VaultView.tsx"; +import { syncVaultViewMemoSection, vaultViewAreEqual } from "./VaultView.tsx"; + +const baseProps = { + hosts: [], + keys: [], + identities: [], + proxyProfiles: [], + snippets: [], + snippetPackages: [], + notes: [], + noteGroups: [], + customGroups: [], + knownHosts: [], + connectionLogs: [], + sessions: [], + managedSources: [], + groupConfigs: {}, + terminalThemeId: "default", + terminalFontSize: 14, + navigateToSection: null, +}; test("VaultView re-renders when an external section navigation request changes", () => { - const baseProps = { - hosts: [], - keys: [], - identities: [], - proxyProfiles: [], - snippets: [], - snippetPackages: [], - notes: [], - noteGroups: [], - customGroups: [], - knownHosts: [], - connectionLogs: [], - sessions: [], - managedSources: [], - groupConfigs: {}, - terminalThemeId: "default", - terminalFontSize: 14, - navigateToSection: null, - }; - assert.equal( vaultViewAreEqual( baseProps as never, @@ -34,26 +34,6 @@ test("VaultView re-renders when an external section navigation request changes", }); test("VaultView memo does not depend on shellHistory prop identity", () => { - const baseProps = { - hosts: [], - keys: [], - identities: [], - proxyProfiles: [], - snippets: [], - snippetPackages: [], - notes: [], - noteGroups: [], - customGroups: [], - knownHosts: [], - connectionLogs: [], - sessions: [], - managedSources: [], - groupConfigs: {}, - terminalThemeId: "default", - terminalFontSize: 14, - navigateToSection: null, - }; - // History-only updates must not be part of VaultView equality (store path). assert.equal( vaultViewAreEqual(baseProps as never, { ...baseProps } as never), true, @@ -65,26 +45,6 @@ test("VaultView memo does not depend on shellHistory prop identity", () => { }); test("VaultView re-renders when proxy profiles change", () => { - const baseProps = { - hosts: [], - keys: [], - identities: [], - proxyProfiles: [], - snippets: [], - snippetPackages: [], - notes: [], - noteGroups: [], - customGroups: [], - knownHosts: [], - connectionLogs: [], - sessions: [], - managedSources: [], - groupConfigs: {}, - terminalThemeId: "default", - terminalFontSize: 14, - navigateToSection: null, - }; - assert.equal( vaultViewAreEqual( baseProps as never, @@ -105,38 +65,12 @@ test("VaultView re-renders when proxy profiles change", () => { }); test("VaultView re-renders when host-key verification setting changes", () => { - const baseProps = { - hosts: [], - keys: [], - identities: [], - proxyProfiles: [], - snippets: [], - snippetPackages: [], - notes: [], - noteGroups: [], - customGroups: [], - knownHosts: [], - connectionLogs: [], - sessions: [], - managedSources: [], - groupConfigs: {}, - terminalThemeId: "default", - terminalFontSize: 14, - navigateToSection: null, - terminalSettings: { - verifyHostKeys: true, - keepaliveInterval: 30, - keepaliveCountMax: 10, - }, - }; - assert.equal( vaultViewAreEqual( baseProps as never, { ...baseProps, terminalSettings: { - ...baseProps.terminalSettings, verifyHostKeys: false, }, } as never, @@ -144,3 +78,35 @@ test("VaultView re-renders when host-key verification setting changes", () => { false, ); }); + +test("VaultView ignores connectionLogs identity when not on logs section", () => { + syncVaultViewMemoSection("hosts"); + const nextLogs = [{ id: "log-1" }]; + assert.equal( + vaultViewAreEqual( + baseProps as never, + { ...baseProps, connectionLogs: nextLogs } as never, + ), + true, + ); +}); + +test("VaultView compares connectionLogs identity when on logs section", () => { + syncVaultViewMemoSection("logs"); + const nextLogs = [{ id: "log-2" }]; + assert.equal( + vaultViewAreEqual( + baseProps as never, + { ...baseProps, connectionLogs: nextLogs } as never, + ), + false, + ); + assert.equal( + vaultViewAreEqual( + { ...baseProps, connectionLogs: nextLogs } as never, + { ...baseProps, connectionLogs: nextLogs } as never, + ), + true, + ); + syncVaultViewMemoSection("hosts"); +}); diff --git a/components/VaultView.tsx b/components/VaultView.tsx index 52dd5698c..fc7349bab 100644 --- a/components/VaultView.tsx +++ b/components/VaultView.tsx @@ -147,7 +147,7 @@ import { Badge } from "./ui/badge"; import { HotkeyScheme, KeyBinding } from "../domain/models"; import { VaultViewLayout } from "./vault/VaultViewLayout"; import { useVaultHostCollections } from "./vault/useVaultHostCollections"; -import { useVaultImportHandlers } from "./vault/useVaultImportHandlers"; +import { useVaultImportHandlers } from "../application/state/useVaultImportHandlers"; import { useVaultGroupDragHandlers } from "./vault/useVaultGroupDragHandlers"; const LazyProtocolSelectDialog = lazy(() => import("./ProtocolSelectDialog")); @@ -167,6 +167,16 @@ export type VaultSection = | "knownhosts" | "logs"; +/** Memo section tracker: areEqual ignores connectionLogs unless on logs. */ +let vaultViewMemoSection: VaultSection = "hosts"; +/** Always stashed from areEqual so skipped updates stay available when opening logs. */ +let vaultViewLatestConnectionLogs: ConnectionLog[] | null = null; + +/** Test/helper: sync the section used by vaultViewAreEqual. */ +export function syncVaultViewMemoSection(section: VaultSection): void { + vaultViewMemoSection = section; +} + const haveSameHostOrderResult = (previous: Host[], next: Host[]) => { if (previous.length !== next.length) return false; return next.every((host, index) => { @@ -365,6 +375,8 @@ const VaultViewInner: React.FC = ({ const hostsRef = useRef(hosts); hostsRef.current = hosts; const [currentSection, setCurrentSection] = useState("hosts"); + vaultViewMemoSection = currentSection; + const resolvedConnectionLogs = vaultViewLatestConnectionLogs ?? connectionLogs; const [search, setSearch] = useState(""); const [selectedGroupPath, setSelectedGroupPath] = useState( null, @@ -888,6 +900,7 @@ const VaultViewInner: React.FC = ({ hosts, keys, managedSources, + notify: toast, onReadPersistedHosts, onUpdateHosts, onUpdateKeys, @@ -1414,7 +1427,7 @@ const VaultViewInner: React.FC = ({ Clock, cn, commitInlineGroupRename, - connectionLogs, + connectionLogs: resolvedConnectionLogs, connectSelectedHosts, ContextMenu, ContextMenuContent, @@ -1667,6 +1680,11 @@ export const vaultViewAreEqual = ( prev: VaultViewProps, next: VaultViewProps, ): boolean => { + vaultViewLatestConnectionLogs = next.connectionLogs; + const connectionLogsEqual = + vaultViewMemoSection === "logs" + ? prev.connectionLogs === next.connectionLogs + : true; const isEqual = prev.hosts === next.hosts && prev.keys === next.keys && @@ -1679,7 +1697,7 @@ export const vaultViewAreEqual = ( prev.customGroups === next.customGroups && prev.knownHosts === next.knownHosts && // shellHistory is not a VaultView prop; SnippetsManager reads shellHistoryStore. - prev.connectionLogs === next.connectionLogs && + connectionLogsEqual && prev.sessionCount === next.sessionCount && prev.managedSources === next.managedSources && prev.groupConfigs === next.groupConfigs && diff --git a/components/ai/ChatInput.tsx b/components/ai/ChatInput.tsx index 5e413d990..61e4da3ed 100644 --- a/components/ai/ChatInput.tsx +++ b/components/ai/ChatInput.tsx @@ -37,7 +37,7 @@ import type { AgentModelPreset, AIPermissionMode, ProviderConfig, UploadedFile } import { ProviderIconBadge } from '../settings/tabs/ai/ProviderIconBadge'; import { VariableSizeVirtualList, type VariableSizeVirtualListHandle } from '../ui/VariableSizeVirtualList'; import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/tooltip'; -import type { AgentContextUsage } from './hooks/useAgentCompactionUi'; +import type { AgentContextUsage } from '../../application/state/useAgentCompactionUi'; import { CHAT_INPUT_DEFAULT_HEIGHT, CHAT_INPUT_MAX_HEIGHT, diff --git a/components/ai/ChatMessageList.test.tsx b/components/ai/ChatMessageList.test.tsx index 368406268..13163101a 100644 --- a/components/ai/ChatMessageList.test.tsx +++ b/components/ai/ChatMessageList.test.tsx @@ -38,16 +38,24 @@ test("resolved approval state retains only tool calls still present in messages" assert.deepEqual([...next], [["live-call", false]]); }); -test("assistant content stays plain only when markdown is hidden", () => { +test("assistant content stays plain when markdown is hidden or streaming", () => { assert.equal(shouldRenderAssistantAsPlainText({ hideMarkdown: false, }), false); assert.equal(shouldRenderAssistantAsPlainText({ hideMarkdown: true, }), true); + assert.equal(shouldRenderAssistantAsPlainText({ + hideMarkdown: false, + isStreaming: true, + }), true); + assert.equal(shouldRenderAssistantAsPlainText({ + hideMarkdown: false, + isStreaming: false, + }), false); }); -test("ChatMessageList renders markdown for the streaming assistant message", () => { +test("ChatMessageList renders plain text for the streaming assistant message", () => { const messages: ChatMessage[] = [ { id: "user-1", @@ -75,15 +83,16 @@ test("ChatMessageList renders markdown for the streaming assistant message", () ), ); - assert.match(markup, /data-ai-content="markdown"/); + assert.match(markup, /data-ai-content="plain"/); assert.match(markup, /streaming-body/); - assert.doesNotMatch(markup, /data-ai-content="plain"/); + assert.doesNotMatch(markup, /data-ai-content="markdown"/); }); -test("streaming markdown keeps the renderer in its animating mode", () => { +test("streaming assistant content skips Streamdown while the turn is live", () => { const source = readFileSync(new URL("./ChatMessageList.tsx", import.meta.url), "utf8"); - assert.match(source, /LazyMessageResponse isAnimating=\{!!isThisStreaming\}/); + assert.match(source, /isStreaming: !!isThisStreaming/); + assert.match(source, /shouldRenderAssistantAsPlainText\(\{[\s\S]*?isStreaming/); }); test("ChatMessageList hydrates markdown after streaming settles", () => { diff --git a/components/ai/ChatMessageList.tsx b/components/ai/ChatMessageList.tsx index 734b1928b..b197bf00b 100644 --- a/components/ai/ChatMessageList.tsx +++ b/components/ai/ChatMessageList.tsx @@ -67,7 +67,7 @@ import { compactionStatusText, resolveCompactionStatusText, type ActiveCompactionUi, -} from './hooks/useAgentCompactionUi'; +} from '../../application/state/useAgentCompactionUi'; import { getAIPanelDiagnosticHiddenParts, getAIPanelProfilerProps, @@ -113,8 +113,9 @@ export function shouldProvideVaultArtifactNavigation({ export function shouldRenderAssistantAsPlainText(options: { hideMarkdown: boolean; + isStreaming?: boolean; }): boolean { - return options.hideMarkdown; + return options.hideMarkdown || !!options.isStreaming; } const ASSISTANT_PLAIN_TEXT_CLASS = 'whitespace-pre-wrap break-words text-[13px] leading-[1.45]'; @@ -702,6 +703,7 @@ const ChatMessageList: React.FC = ({ ?
{message.content}
: shouldRenderAssistantAsPlainText({ hideMarkdown, + isStreaming: !!isThisStreaming, }) ? (
= ({ : (
- + {message.content}
diff --git a/components/ai/aiPanelDiagnostics.test.ts b/components/ai/aiPanelDiagnostics.test.ts index 087319400..6430b004a 100644 --- a/components/ai/aiPanelDiagnostics.test.ts +++ b/components/ai/aiPanelDiagnostics.test.ts @@ -2,14 +2,19 @@ import assert from 'node:assert/strict'; import test from 'node:test'; const storage = new Map(); +const localStorageStub = { + getItem: (key: string) => storage.get(key) ?? null, + setItem: (key: string, value: string) => { storage.set(key, value); }, + removeItem: (key: string) => { storage.delete(key); }, +}; +Object.defineProperty(globalThis, 'localStorage', { + configurable: true, + value: localStorageStub, +}); Object.defineProperty(globalThis, 'window', { configurable: true, value: { - localStorage: { - getItem: (key: string) => storage.get(key) ?? null, - setItem: (key: string, value: string) => storage.set(key, value), - removeItem: (key: string) => storage.delete(key), - }, + localStorage: localStorageStub, }, }); diff --git a/components/ai/aiPanelDiagnostics.ts b/components/ai/aiPanelDiagnostics.ts index 1e1d395d6..87351760e 100644 --- a/components/ai/aiPanelDiagnostics.ts +++ b/components/ai/aiPanelDiagnostics.ts @@ -1,81 +1,13 @@ -import type React from 'react'; - -export const AI_PANEL_DIAGNOSTIC_HIDE_KEY = 'netcatty.aiDebug.hide'; -export const AI_PANEL_DIAGNOSTIC_PROFILE_KEY = 'netcatty.aiDebug.profile'; -export const AI_PANEL_FORCE_HIDE_ALL_CONTENT = false; -export const AI_PANEL_FORCE_HIDE_SHELL = false; - -export type AIPanelDiagnosticPart = - | 'all' - | 'attachments' - | 'header' - | 'history' - | 'input' - | 'markdown' - | 'messages' - | 'recent' - | 'toolcalls'; - -function readLocalStorageValue(key: string): string { - if (typeof window === 'undefined') return ''; - try { - return window.localStorage.getItem(key) ?? ''; - } catch { - return ''; - } -} - -export function getAIPanelDiagnosticHiddenParts(): ReadonlySet { - if (AI_PANEL_FORCE_HIDE_ALL_CONTENT) { - return new Set(['all']); - } - const raw = readLocalStorageValue(AI_PANEL_DIAGNOSTIC_HIDE_KEY); - return new Set( - raw - .split(',') - .map((part) => part.trim().toLowerCase()) - .filter(Boolean), - ); -} - -export function isAIPanelDiagnosticPartHidden( - part: AIPanelDiagnosticPart, - hiddenParts = getAIPanelDiagnosticHiddenParts(), -): boolean { - return hiddenParts.has('all') || hiddenParts.has(part); -} - -export function isAIPanelDiagnosticsProfilingEnabled(): boolean { - const raw = readLocalStorageValue(AI_PANEL_DIAGNOSTIC_PROFILE_KEY).trim().toLowerCase(); - return raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on'; -} - -export function logAIPanelProfiler( - id: string, - phase: 'mount' | 'update' | 'nested-update', - actualDuration: number, - baseDuration: number, -): void { - if (!isAIPanelDiagnosticsProfilingEnabled()) return; - console.info( - `[AI panel profile] ${id} ${phase}: actual=${actualDuration.toFixed(1)}ms base=${baseDuration.toFixed(1)}ms`, - ); -} - -export function profileAIPanelCalculation(label: string, calculate: () => T): T { - if (!isAIPanelDiagnosticsProfilingEnabled()) return calculate(); - const startedAt = performance.now(); - try { - return calculate(); - } finally { - const elapsed = performance.now() - startedAt; - console.info(`[AI panel profile] ${label}: ${elapsed.toFixed(1)}ms`); - } -} - -export function getAIPanelProfilerProps(id: string): Pick { - return { - id, - onRender: logAIPanelProfiler, - }; -} +export { + AI_PANEL_DIAGNOSTIC_HIDE_KEY, + AI_PANEL_DIAGNOSTIC_PROFILE_KEY, + AI_PANEL_FORCE_HIDE_ALL_CONTENT, + AI_PANEL_FORCE_HIDE_SHELL, + getAIPanelDiagnosticHiddenParts, + getAIPanelProfilerProps, + isAIPanelDiagnosticPartHidden, + isAIPanelDiagnosticsProfilingEnabled, + logAIPanelProfiler, + profileAIPanelCalculation, + type AIPanelDiagnosticPart, +} from '../../application/state/aiPanelDiagnostics'; diff --git a/components/ai/hooks/aiChatStreamingSupport.ts b/components/ai/hooks/aiChatStreamingSupport.ts index 84096a33c..1602c5f98 100644 --- a/components/ai/hooks/aiChatStreamingSupport.ts +++ b/components/ai/hooks/aiChatStreamingSupport.ts @@ -1,288 +1,2 @@ -import type { NetcattyBridge } from '../../../infrastructure/ai/cattyAgent/executor'; -import type { - OpenAIChatAssistantFields, - ProviderContinuationOptions, - ProviderContinuationSource, -} from '../../../infrastructure/ai/providerContinuation'; - -/** Shape of a text/text-delta chunk from the Vercel AI SDK stream. */ -export interface TextDeltaChunk { - type: 'text' | 'text-delta'; - text?: string; - textDelta?: string; - providerMetadata?: unknown; -} - -/** Shape of a reasoning chunk from the Vercel AI SDK stream. */ -export interface ReasoningChunk { - type: 'reasoning' | 'reasoning-start' | 'reasoning-delta'; - text?: string; - textDelta?: string; - delta?: string; - providerMetadata?: unknown; -} - -/** Shape of a raw provider chunk from the Vercel AI SDK stream. */ -export interface RawChunk { - type: 'raw'; - rawValue: unknown; -} - -/** Shape of a tool-call chunk from the Vercel AI SDK stream. */ -export interface ToolCallChunk { - type: 'tool-call'; - toolCallId: string; - toolName: string; - input?: unknown; - args?: unknown; - providerMetadata?: unknown; -} - -/** Shape of a tool-result chunk from the Vercel AI SDK stream. */ -export interface ToolResultChunk { - type: 'tool-result'; - toolCallId: string; - output?: unknown; - result?: unknown; -} - -/** Shape of a tool-error chunk from the Vercel AI SDK stream. */ -export interface ToolErrorChunk { - type: 'tool-error'; - toolCallId: string; - toolName?: string; - error?: unknown; -} - -/** Shape of a tool-output-denied chunk from the Vercel AI SDK stream. */ -export interface ToolOutputDeniedChunk { - type: 'tool-output-denied'; - toolCallId: string; - toolName?: string; -} - -/** Nested tool call reference on approval stream chunks. */ -export interface StreamChunkToolCallRef { - toolCallId: string; - toolName: string; - input?: unknown; - args?: unknown; -} - -/** Shape of a tool-approval-response chunk from the Vercel AI SDK stream. */ -export interface ToolApprovalResponseChunk { - type: 'tool-approval-response'; - approvalId?: string; - approved?: boolean; - reason?: string; - toolCallId?: string; - toolName?: string; - toolCall?: StreamChunkToolCallRef; -} - -/** Resolve toolCallId from flat or nested approval/tool chunks. */ -export function resolveStreamChunkToolCallId(chunk: { - toolCallId?: string; - toolCall?: { toolCallId?: string }; -}): string | undefined { - return chunk.toolCallId ?? chunk.toolCall?.toolCallId; -} - -/** Format tool execution failures for model/UI consumption. */ -export function formatToolErrorContent(error: unknown, fallback = 'Tool execution failed.'): string { - if (error instanceof Error) return JSON.stringify({ error: error.message }); - if (typeof error === 'string') return JSON.stringify({ error }); - if (error != null && typeof error === 'object' && 'error' in error) { - return JSON.stringify(error); - } - return JSON.stringify({ error: fallback }); -} - -/** Detect tool results that represent errors/denials (e.g. `{ error: "..." }` or `{ ok: false }`) */ -export function isToolResultError(output: unknown): boolean { - if (output == null) return false; - - if (typeof output === 'object') { - const obj = output as Record; - // Check for explicit error objects - if ('error' in obj && typeof obj.error === 'string') return true; - if ('ok' in obj && obj.ok === false) return true; - } - - // Check stringified JSON (common for tool result wrapping) - if (typeof output === 'string') { - try { - const parsed = JSON.parse(output); - if (parsed && typeof parsed === 'object') { - const parsedObj = parsed as Record; - if ('error' in parsedObj && typeof parsedObj.error === 'string') return true; - if ('ok' in parsedObj && parsedObj.ok === false) return true; - } - } catch { /* not JSON, not an error */ } - } - - return false; -} - -/** Shape of an error chunk from the Vercel AI SDK stream. */ -export interface ErrorChunk { - type: 'error'; - error: unknown; -} - -/** Union of all stream chunk shapes we handle. */ -export type StreamChunk = - | TextDeltaChunk - | ReasoningChunk - | ToolCallChunk - | ToolResultChunk - | ToolErrorChunk - | ToolOutputDeniedChunk - | ToolApprovalResponseChunk - | ErrorChunk - | RawChunk - | { type: 'reasoning-end' | 'text-start' | 'text-end' | 'start' | 'finish' | 'start-step' | 'finish-step' | 'tool-approval-request'; approvalId?: string; toolCallId?: string; toolName?: string; approved?: boolean; toolCall?: StreamChunkToolCallRef; input?: unknown; args?: unknown }; - -/** Shape of the netcatty bridge exposed on `window` (panel-specific subset). */ -export interface PanelBridge extends NetcattyBridge { - credentialsDecrypt?: (value: string) => Promise; - aiSyncProviders?: (providers: Array<{ id: string; providerId: string; apiKey?: string; baseURL?: string; enabled: boolean }>) => Promise<{ ok: boolean }>; - aiSyncWebSearch?: (apiHost: string | null, apiKey: string | null) => Promise<{ ok: boolean }>; - aiMcpUpdateSessions?: (sessions: TerminalSessionInfo[], chatSessionId?: string) => Promise; - aiMcpUpdateAttachments?: ( - attachments: Array<{ base64Data?: string; mediaType?: string; filename?: string; filePath?: string }>, - chatSessionId?: string, - ) => Promise; - aiSdkAgentListModels?: ( - sdkBackend: string, - cwd?: string, - providerId?: string, - chatSessionId?: string, - agentEnv?: Record, - agentCommand?: string, - codexRuntime?: 'sdk' | 'app-server', - ) => Promise<{ ok: boolean; models?: Array<{ id: string; name: string; description?: string; thinkingLevels?: string[]; defaultThinkingLevel?: string }>; currentModelId?: string | null; warning?: string; error?: string }>; - aiCattyCancelExec?(chatSessionId: string): Promise; - aiSetChatSessionCancelled?(chatSessionId: string, cancelled?: boolean): Promise<{ ok: boolean; error?: string }>; - aiMcpSyncPermissionGrants?(grants: Array>): Promise<{ ok: boolean; count?: number; error?: string }>; - aiSdkAgentCancel?: (requestId: string, chatSessionId?: string) => Promise<{ ok: boolean; error?: string }>; - aiSdkAgentSteer?: ( - requestId: string, - chatSessionId: string, - prompt: string, - images: Array<{ base64Data: string; mediaType: string; filename?: string; filePath?: string }> | undefined, - clientUserMessageId: string, - ) => Promise<{ - status: 'accepted' | 'not-steerable' | 'busy' | 'inactive' | 'unsupported' | 'cancelled' | 'failed'; - message?: string; - turnKind?: 'review' | 'compact'; - }>; - aiSdkAgentCleanup?: (chatSessionId: string) => Promise<{ ok: boolean }>; - aiUserSkillsGetStatus?: () => Promise<{ - ok: boolean; - skills?: Array<{ - id: string; - slug: string; - name: string; - description: string; - status: 'ready' | 'warning'; - }>; - }>; - aiUserSkillsBuildContext?: (prompt: string, selectedSkillSlugs?: string[]) => Promise<{ ok: boolean; context?: string; error?: string }>; - [key: string]: ((...args: unknown[]) => unknown) | undefined; -} - -/** Terminal session info used throughout the streaming hooks. */ -export interface TerminalSessionInfo { - sessionId: string; - hostId: string; - hostname: string; - label: string; - os?: string; - username?: string; - protocol?: string; - shellType?: string; - deviceType?: string; - connected: boolean; - hostChain?: Array<{ hostId: string; label?: string; hostname?: string }>; - activePortForwards?: Array<{ - ruleId: string; - label?: string; - type?: string; - localPort?: number; - status?: string; - }>; -} - -export interface DefaultTargetSessionHint extends TerminalSessionInfo { - source: 'scope-target' | 'only-connected-in-scope'; -} - -export interface CattyProviderContinuationContext { - source: ProviderContinuationSource; - openAIChatAssistantFields: Array; -} - -export type AssistantContentPart = - | { type: 'reasoning'; text: string; providerOptions?: ProviderContinuationOptions } - | { type: 'text'; text: string; providerOptions?: ProviderContinuationOptions } - | { type: 'tool-call'; toolCallId: string; toolName: string; input: unknown; providerOptions?: ProviderContinuationOptions }; - -export function toAssistantModelContent(parts: AssistantContentPart[]): string | AssistantContentPart[] { - if (parts.length === 1 && parts[0].type === 'text' && !parts[0].providerOptions) { - return parts[0].text; - } - return parts; -} - -/** Typed accessor for the netcatty bridge on the window object. */ -export function getNetcattyBridge(): PanelBridge | undefined { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return (window as any).netcatty as PanelBridge | undefined; -} - -// ApprovalInfo and PendingApprovalContext removed — approval is now handled -// inside the tool's execute function via the approvalGate module. - -export function generateId(): string { - return `msg-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; -} - -const USER_SKILLS_CONTEXT_TIMEOUT_MS = 500; - -interface UserSkillsContextResult { - ok: boolean; - context?: string; - error?: string; -} - -function buildExplicitUserSkillsFallback(selectedUserSkillSlugs?: string[]): string { - if (!selectedUserSkillSlugs?.length) return ''; - return `The user explicitly selected these Netcatty user skills for this request: ${selectedUserSkillSlugs.map((slug) => `/${slug}`).join(', ')}. Honor those selections even if their expanded skill content is unavailable.`; -} - -export async function resolveUserSkillsContext( - bridge: PanelBridge | undefined, - prompt: string, - selectedUserSkillSlugs?: string[], -): Promise { - if (!bridge?.aiUserSkillsBuildContext) { - return buildExplicitUserSkillsFallback(selectedUserSkillSlugs); - } - - const buildContextPromise: Promise = bridge - .aiUserSkillsBuildContext(prompt, selectedUserSkillSlugs) - .catch(() => ({ ok: false, context: '' })); - - const hasExplicitSelections = (selectedUserSkillSlugs?.length ?? 0) > 0; - const result = hasExplicitSelections - ? await buildContextPromise - : await Promise.race([ - buildContextPromise, - new Promise((resolve) => - setTimeout(() => resolve({ ok: false, context: '' }), USER_SKILLS_CONTEXT_TIMEOUT_MS), - ), - ]); - - return result.context || buildExplicitUserSkillsFallback(selectedUserSkillSlugs); -} +/** @deprecated Import from `@/infrastructure/ai/aiChatStreamingSupport` instead. */ +export * from '../../../infrastructure/ai/aiChatStreamingSupport'; diff --git a/components/ai/hooks/useAIChatStreaming.ts b/components/ai/hooks/useAIChatStreaming.ts index ea041ce39..f07eab31d 100644 --- a/components/ai/hooks/useAIChatStreaming.ts +++ b/components/ai/hooks/useAIChatStreaming.ts @@ -1,268 +1,8 @@ -/** - * useAIChatStreaming — React UI layer for AI chat streaming. - * - * Turn orchestration lives in AgentRuntime + TurnDrivers; this hook only - * manages streaming state, abort controllers, and UI callbacks. - */ - -import React, { useCallback, useEffect, useRef, useState } from 'react'; -import type { - AIPermissionMode, - AIToolIntegrationMode, - AISession, - ChatMessage, - ChatMessageAttachment, - ExternalAgentConfig, - ProviderConfig, - WebSearchConfig, -} from '../../../infrastructure/ai/types'; -import type { ExecutorContext } from '../../../infrastructure/ai/cattyAgent/executor'; -import { getAgentRuntime } from '../../../infrastructure/ai/harness/globalAgentRuntime'; -import type { - TurnSteerInput, - TurnSteerResult, -} from '../../../infrastructure/ai/harness/turnDrivers/types'; -import { classifyError } from '../../../infrastructure/ai/errorClassifier'; -import { latestAISessionsSnapshot } from '../../../application/state/aiStateSnapshots'; -import { - generateId, +/** @deprecated Import from `@/application/state/useAIChatStreaming` instead. */ +export { + useAIChatStreaming, + isAIChatSessionStreaming, getNetcattyBridge, + type ActiveCompactionUi, type DefaultTargetSessionHint, - type TerminalSessionInfo, -} from './aiChatStreamingSupport'; -import { useAgentCompactionUi } from './useAgentCompactionUi'; - -export { getNetcattyBridge } from './aiChatStreamingSupport'; -export type { ActiveCompactionUi } from './useAgentCompactionUi'; -export type { DefaultTargetSessionHint } from './aiChatStreamingSupport'; - -const sharedStreamingSessionIds = new Set(); -const sharedAbortControllers = new Map(); -const streamingSubscribers = new Set<() => void>(); - -/** Whether a chat session still has an active stream (used to keep panel mounted while hidden). */ -export function isAIChatSessionStreaming(sessionId: string | null | undefined): boolean { - return !!sessionId && sharedStreamingSessionIds.has(sessionId); -} - -function emitStreamingStoreChange(): void { - streamingSubscribers.forEach(listener => { - try { - listener(); - } catch (err) { - console.error('[AIChatStreaming] Failed to notify streaming subscriber:', err); - } - }); -} - -export interface UseAIChatStreamingParams { - maxIterations: number; - addMessageToSession: (sessionId: string, message: ChatMessage) => void; - updateLastMessage: (sessionId: string, updater: (msg: ChatMessage) => ChatMessage) => void; - updateMessageById: (sessionId: string, messageId: string, updater: (msg: ChatMessage) => ChatMessage) => void; - persistContextCompaction?: ( - sessionId: string, - compaction: import('../../../infrastructure/ai/types').AISessionContextCompaction, - ) => void; -} - -export interface UseAIChatStreamingReturn { - streamingSessionIds: Set; - setStreamingForScope: (key: string, val: boolean) => void; - abortControllersRef: React.MutableRefObject>; - sendToCattyAgent: ( - sessionId: string, - sendScopeKey: string, - trimmed: string, - abortController: AbortController, - currentSession: AISession | undefined, - assistantMsgId: string, - context: SendToCattyContext, - attachments?: ChatMessageAttachment[], - ) => Promise; - sendToExternalAgent: ( - sessionId: string, - assistantMsgId: string, - trimmed: string, - agentConfig: ExternalAgentConfig, - abortController: AbortController, - attachedImages: Array<{ base64Data: string; mediaType: string; filename?: string; filePath?: string }>, - context: SendToExternalContext, - ) => Promise; - steerExternalAgent: (input: TurnSteerInput) => Promise; - reportStreamError: (sessionId: string, abortSignal: AbortSignal, err: unknown) => void; - activeCompaction: import('./useAgentCompactionUi').ActiveCompactionUi | null; -} - -export interface SendToCattyContext { - activeProvider: ProviderConfig | undefined; - activeModelId: string; - scopeType: 'terminal' | 'workspace'; - scopeTargetId?: string; - scopeLabel?: string; - globalPermissionMode: AIPermissionMode; - commandBlocklist?: string[]; - commandTimeout?: number; - terminalSessions: TerminalSessionInfo[]; - webSearchConfig?: WebSearchConfig | null; - getExecutorContext?: () => ExecutorContext; - autoTitleSession: (sessionId: string, text: string) => void; - titleText?: string; - selectedUserSkillSlugs?: string[]; - permissionMode?: AIPermissionMode; - forceCompaction?: boolean; -} - -export interface SendToExternalContext { - existingSessionId?: string; - updateExternalSessionId?: (sessionId: string, externalSessionId: string | undefined) => void; - historyMessages?: Array<{ role: 'user' | 'assistant'; content: string }>; - terminalSessions: TerminalSessionInfo[]; - defaultTargetSession?: DefaultTargetSessionHint; - providers: ProviderConfig[]; - selectedAgentModel?: string; - toolIntegrationMode: AIToolIntegrationMode; - selectedUserSkillSlugs?: string[]; - permissionMode: AIPermissionMode; -} - -export function useAIChatStreaming({ - maxIterations, - addMessageToSession, - updateLastMessage, - updateMessageById, - persistContextCompaction, -}: UseAIChatStreamingParams): UseAIChatStreamingReturn { - const [streamingSessionIds, setStreamingSessions] = useState>( - () => new Set(sharedStreamingSessionIds), - ); - - useEffect(() => { - const syncFromStore = () => { - setStreamingSessions(new Set(sharedStreamingSessionIds)); - }; - streamingSubscribers.add(syncFromStore); - syncFromStore(); - return () => { - streamingSubscribers.delete(syncFromStore); - }; - }, []); - - const setStreamingForScope = useCallback((key: string, val: boolean) => { - const hadKey = sharedStreamingSessionIds.has(key); - if (val) { - sharedStreamingSessionIds.add(key); - } else { - sharedStreamingSessionIds.delete(key); - } - if (hadKey !== val) { - emitStreamingStoreChange(); - } - }, []); - - const abortControllersRef = useRef>(sharedAbortControllers); - - const activeCompaction = useAgentCompactionUi(); - - const reportStreamError = useCallback(( - sessionId: string, - abortSignal: AbortSignal, - err: unknown, - ) => { - if (abortSignal.aborted) return; - console.error('[AIChatSidePanel] Stream error (full):', err); - const errorInfo = classifyError(err); - updateLastMessage(sessionId, msg => ({ - ...msg, - statusText: '', - executionStatus: msg.executionStatus === 'running' ? 'failed' : msg.executionStatus, - })); - addMessageToSession(sessionId, { - id: generateId(), - role: 'assistant', - content: '', - errorInfo, - timestamp: Date.now(), - }); - }, [updateLastMessage, addMessageToSession]); - - const uiCallbacks = useCallback(() => ({ - addMessageToSession, - updateLastMessage, - updateMessageById, - reportStreamError, - setStreamingForScope, - getLatestSession: (sessionId: string) => latestAISessionsSnapshot?.find(s => s.id === sessionId), - persistContextCompaction, - }), [addMessageToSession, updateLastMessage, updateMessageById, reportStreamError, setStreamingForScope, persistContextCompaction]); - - const sendToExternalAgent = useCallback(async ( - sessionId: string, - assistantMsgId: string, - trimmed: string, - agentConfig: ExternalAgentConfig, - abortController: AbortController, - attachedImages: Array<{ base64Data: string; mediaType: string; filename?: string; filePath?: string }>, - context: SendToExternalContext, - ) => { - const bridge = getNetcattyBridge(); - await getAgentRuntime().runTurn({ - backend: 'external-sdk', - chatSessionId: sessionId, - assistantMsgId, - userText: trimmed, - signal: abortController.signal, - agentConfig, - attachedImages, - context, - bridge, - ui: uiCallbacks(), - }); - }, [uiCallbacks]); - - const steerExternalAgent = useCallback(async (input: TurnSteerInput) => { - return getAgentRuntime().steerTurn(input); - }, []); - - const sendToCattyAgent = useCallback(async ( - sessionId: string, - sendScopeKey: string, - trimmed: string, - abortController: AbortController, - currentSession: AISession | undefined, - assistantMsgId: string, - context: SendToCattyContext, - attachments?: ChatMessageAttachment[], - ) => { - const bridge = getNetcattyBridge(); - try { - await getAgentRuntime().runTurn({ - backend: 'catty', - chatSessionId: sessionId, - sendScopeKey, - userText: trimmed, - signal: abortController.signal, - currentSession, - assistantMsgId, - context, - attachments, - maxIterations, - bridge, - ui: uiCallbacks(), - }); - } finally { - abortControllersRef.current.delete(sessionId); - } - }, [maxIterations, uiCallbacks]); - - return { - streamingSessionIds, - setStreamingForScope, - abortControllersRef, - sendToCattyAgent, - sendToExternalAgent, - steerExternalAgent, - reportStreamError, - activeCompaction, - }; -} +} from "../../../application/state/useAIChatStreaming"; diff --git a/components/ai/hooks/useAgentCompactionUi.ts b/components/ai/hooks/useAgentCompactionUi.ts index fcbb5fbea..15af6ae67 100644 --- a/components/ai/hooks/useAgentCompactionUi.ts +++ b/components/ai/hooks/useAgentCompactionUi.ts @@ -1,95 +1,9 @@ -import { useEffect, useState } from 'react'; -import type { ContextPrepareTrigger } from '../../../infrastructure/ai/harness/types'; -import { getAgentRuntime } from '../../../infrastructure/ai/harness/globalAgentRuntime'; -import { CATTY_COMPACTION_STATUS_KEYS } from '../../../infrastructure/ai/harness/compactionStatusKeys'; - -export interface ActiveCompactionUi { - sessionId: string; - trigger: ContextPrepareTrigger; -} - -export interface AgentContextUsage { - sessionId: string; - inputTokens: number; - contextWindow: number; - estimated: boolean; -} - -function statusKeyForTrigger(trigger: ContextPrepareTrigger): string { - switch (trigger) { - case 'step': - return CATTY_COMPACTION_STATUS_KEYS.step; - case '413-retry': - return CATTY_COMPACTION_STATUS_KEYS.retry; - default: - return CATTY_COMPACTION_STATUS_KEYS.preTurn; - } -} - -export function useAgentCompactionUi(): ActiveCompactionUi | null { - const [active, setActive] = useState(null); - - useEffect(() => { - const unsubscribe = getAgentRuntime().subscribe((event) => { - const sessionId = event.chatSessionId ?? event.sessionId; - if (event.type === 'compaction_start') { - setActive({ sessionId, trigger: event.trigger }); - return; - } - if (event.type === 'compaction' || event.type === 'turn_end') { - setActive((prev) => (prev?.sessionId === sessionId ? null : prev)); - } - }); - return unsubscribe; - }, []); - - return active; -} - -export function compactionStatusText( - trigger: ContextPrepareTrigger, - translate: (key: string, params?: Record) => string, -): string { - return translate(statusKeyForTrigger(trigger)); -} - -export function resolveCompactionStatusText( - statusText: string | undefined, - translate: (key: string) => string, -): string | undefined { - if (!statusText) return undefined; - if (statusText.startsWith('ai.')) return translate(statusText); - return statusText; -} - -export function useAgentContextUsage(sessionId: string | null | undefined): AgentContextUsage | null { - const [usage, setUsage] = useState(null); - - useEffect(() => { - if (!sessionId) { - setUsage(null); - return undefined; - } - - const unsubscribe = getAgentRuntime().subscribe((event) => { - const eventSessionId = event.chatSessionId ?? event.sessionId; - if (eventSessionId !== sessionId || event.type !== 'context_snapshot') return; - const snapshot = event.snapshot; - if ( - typeof snapshot.contextWindow !== 'number' - || typeof snapshot.estimatedInputTokens !== 'number' - ) { - return; - } - setUsage({ - sessionId, - inputTokens: Math.max(0, snapshot.estimatedInputTokens), - contextWindow: Math.max(1, snapshot.contextWindow), - estimated: true, - }); - }); - return unsubscribe; - }, [sessionId]); - - return usage?.sessionId === sessionId ? usage : null; -} +/** @deprecated Import from `@/application/state/useAgentCompactionUi` instead. */ +export { + useAgentCompactionUi, + useAgentContextUsage, + compactionStatusText, + resolveCompactionStatusText, + type ActiveCompactionUi, + type AgentContextUsage, +} from "../../../application/state/useAgentCompactionUi"; diff --git a/components/editor/UnsavedChangesDialog.test.ts b/components/editor/UnsavedChangesDialog.test.ts new file mode 100644 index 000000000..b082a61b4 --- /dev/null +++ b/components/editor/UnsavedChangesDialog.test.ts @@ -0,0 +1,16 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; + +const source = readFileSync(new URL("./UnsavedChangesDialog.tsx", import.meta.url), "utf8"); + +test("unsaved prompt singleton registers during render, not only in useEffect", () => { + // AppView close / Cmd+W call promptUnsavedChanges outside the render-prop. + // Assigning only in useEffect leaves a first-paint window where the + // singleton is null and dirty closes silently resolve to "cancel". + assert.match(source, /promptSingleton = prompt;/); + assert.doesNotMatch( + source, + /useEffect\(\(\) => \{\s*promptSingleton = prompt;/, + ); +}); diff --git a/components/editor/UnsavedChangesDialog.tsx b/components/editor/UnsavedChangesDialog.tsx index ee85ae00f..8a8773831 100644 --- a/components/editor/UnsavedChangesDialog.tsx +++ b/components/editor/UnsavedChangesDialog.tsx @@ -41,12 +41,12 @@ export const UnsavedChangesProvider: React.FC<{ [], ); - // Register the prompt function as the module-level singleton so it can be - // called from outside the React tree (e.g. useSftpViewPaneActions). - useEffect(() => { - promptSingleton = prompt; - return () => { promptSingleton = null; }; - }, [prompt]); + // Keep the singleton current during render so AppView close handlers and + // hotkeys never race the post-commit useEffect registration window. + promptSingleton = prompt; + useEffect(() => () => { + promptSingleton = null; + }, []); // On unmount, resolve any in-flight prompt as "cancel" so awaiting callers don't leak. useEffect(() => () => { diff --git a/components/notes/NotesManager.test.tsx b/components/notes/NotesManager.test.tsx index b33208b5c..d6050a645 100644 --- a/components/notes/NotesManager.test.tsx +++ b/components/notes/NotesManager.test.tsx @@ -246,12 +246,28 @@ test("NotesManager shows placeholder label for notes without titles", () => { assert.match(markup, /Note title/); }); +test("NotesManager flushes drafts on pagehide/beforeunload", () => { + const source = readFileSync(new URL("./NotesManager.tsx", import.meta.url), "utf8"); + assert.match(source, /addEventListener\("pagehide"/); + assert.match(source, /addEventListener\("beforeunload"/); + assert.match(source, /flushNoteDraft/); +}); + +test("NotesManager flushes drafts when retained mounts become inactive", () => { + const source = readFileSync(new URL("./NotesManager.tsx", import.meta.url), "utf8"); + assert.match(source, /isActive\?: boolean/); + assert.match(source, /if \(isActive\) return;/); + assert.match(source, /useLayoutEffect\(\(\) => \{\s*if \(isActive\) return;/); + assert.match(source, /visibilitychange/); +}); + test("NotesManager tree rename allows clearing note titles", () => { const source = readFileSync(new URL("./NotesManager.tsx", import.meta.url), "utf8"); const renameBlock = source.match(/onRenameCommit=\{\(name\) => \{[\s\S]*?\}\}/)?.[0] ?? ""; - assert.match(renameBlock, /saveNote\(\{ \.\.\.note, title: name\.trim\(\)/); + assert.match(renameBlock, /renameNoteFromTree\(note\.id, name\)/); assert.doesNotMatch(renameBlock, /if \(!title\) return/); + assert.match(source, /note\.id === noteId \? \{ \.\.\.note, title: nextTitle, updatedAt \}/); }); test("NotesManager sidebar mode renders list without editor by default", () => { diff --git a/components/notes/NotesManager.tsx b/components/notes/NotesManager.tsx index 70e883281..c41928048 100644 --- a/components/notes/NotesManager.tsx +++ b/components/notes/NotesManager.tsx @@ -15,7 +15,7 @@ import { Upload, X, } from "lucide-react"; -import React, { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react"; +import React, { lazy, Suspense, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { useI18n } from "../../application/i18n/I18nProvider"; import { useApplicationBackend } from "../../application/state/useApplicationBackend"; import { useStoredNumber } from "../../application/state/useStoredNumber"; @@ -121,6 +121,8 @@ export interface NotesManagerProps { onUpdateNoteGroups: (groups: string[]) => void; onOpenHost?: (host: Host, source?: { noteId: string }) => void; displayMode?: "full" | "sidebar"; + /** When false (hidden retained mount), flush any pending draft immediately. */ + isActive?: boolean; openNoteId?: string | null; openNoteRequestId?: number | null; /** Called after a one-shot openNoteId focus request has been applied. */ @@ -340,6 +342,7 @@ export const NotesManager: React.FC = ({ onUpdateNoteGroups, onOpenHost, displayMode = "full", + isActive = true, openNoteId = null, openNoteRequestId = null, onOpenNoteIdHandled, @@ -401,6 +404,97 @@ export const NotesManager: React.FC = ({ return cleaned; }, [onUpdateNotes]); + const NOTE_DRAFT_DEBOUNCE_MS = 300; + const draftNoteIdRef = useRef(null); + const draftTitleRef = useRef(null); + const draftContentRef = useRef(null); + const draftTimerRef = useRef(null); + const [draftNoteId, setDraftNoteId] = useState(null); + const [draftTitle, setDraftTitle] = useState(null); + const [draftContent, setDraftContent] = useState(null); + + const clearDraftTimer = useCallback(() => { + if (draftTimerRef.current !== null) { + window.clearTimeout(draftTimerRef.current); + draftTimerRef.current = null; + } + }, []); + + const flushNoteDraft = useCallback(() => { + clearDraftTimer(); + const noteId = draftNoteIdRef.current; + if (!noteId) return; + const title = draftTitleRef.current; + const content = draftContentRef.current; + draftNoteIdRef.current = null; + draftTitleRef.current = null; + draftContentRef.current = null; + setDraftNoteId(null); + setDraftTitle(null); + setDraftContent(null); + if (title === null && content === null) return; + commitNotes(sortedNotesRef.current.map((note) => { + if (note.id !== noteId) return note; + return { + ...note, + ...(title !== null ? { title } : {}), + ...(content !== null ? { content } : {}), + updatedAt: Date.now(), + }; + })); + }, [clearDraftTimer, commitNotes]); + + const scheduleNoteDraftFlush = useCallback(() => { + clearDraftTimer(); + draftTimerRef.current = window.setTimeout(() => { + draftTimerRef.current = null; + flushNoteDraft(); + }, NOTE_DRAFT_DEBOUNCE_MS); + }, [clearDraftTimer, flushNoteDraft]); + + const updateNoteDraft = useCallback((noteId: string, fields: { title?: string; content?: string }) => { + if (draftNoteIdRef.current && draftNoteIdRef.current !== noteId) { + flushNoteDraft(); + } + draftNoteIdRef.current = noteId; + setDraftNoteId(noteId); + if (fields.title !== undefined) { + draftTitleRef.current = fields.title; + setDraftTitle(fields.title); + } + if (fields.content !== undefined) { + draftContentRef.current = fields.content; + setDraftContent(fields.content); + } + scheduleNoteDraftFlush(); + }, [flushNoteDraft, scheduleNoteDraftFlush]); + + useEffect(() => () => { + flushNoteDraft(); + }, [flushNoteDraft]); + + useLayoutEffect(() => { + if (isActive) return; + flushNoteDraft(); + }, [flushNoteDraft, isActive]); + + useEffect(() => { + const flushOnTeardown = () => { + flushNoteDraft(); + }; + const flushOnHidden = () => { + if (document.visibilityState === "hidden") flushNoteDraft(); + }; + window.addEventListener("pagehide", flushOnTeardown); + window.addEventListener("beforeunload", flushOnTeardown); + document.addEventListener("visibilitychange", flushOnHidden); + return () => { + window.removeEventListener("pagehide", flushOnTeardown); + window.removeEventListener("beforeunload", flushOnTeardown); + document.removeEventListener("visibilitychange", flushOnHidden); + }; + }, [flushNoteDraft]); + const noteTree = useMemo(() => { const tree = buildNoteTree(groups, sortedNotes); return { @@ -410,6 +504,26 @@ export const NotesManager: React.FC = ({ }, [groupOrderByPath, groups, sortedNotes]); const selectedNote = getSelectedVaultNote(sortedNotes, selectedNoteId); const overlayNote = sortedNotes.find((note) => note.id === overlayNoteId) ?? null; + const selectedNoteView = selectedNote && draftNoteId === selectedNote.id + ? { + ...selectedNote, + ...(draftTitle !== null ? { title: draftTitle } : {}), + ...(draftContent !== null ? { content: draftContent } : {}), + } + : selectedNote; + const overlayNoteView = overlayNote && draftNoteId === overlayNote.id + ? { + ...overlayNote, + ...(draftTitle !== null ? { title: draftTitle } : {}), + ...(draftContent !== null ? { content: draftContent } : {}), + } + : overlayNote; + + useEffect(() => { + if (!draftNoteIdRef.current) return; + if (draftNoteIdRef.current === selectedNoteId || draftNoteIdRef.current === overlayNoteId) return; + flushNoteDraft(); + }, [flushNoteDraft, overlayNoteId, selectedNoteId]); useEffect(() => { const urls = activeDownloadUrlsRef.current; @@ -496,8 +610,28 @@ export const NotesManager: React.FC = ({ const expandAllGroups = () => setExpandedGroups(new Set(allGroupPaths)); const collapseAllGroups = () => setExpandedGroups(new Set()); - const saveNote = (nextNote: VaultNote) => { - commitNotes(sortedNotes.map((note) => (note.id === nextNote.id ? nextNote : note))); + /** Flush pending draft, then mutate from the post-flush ref snapshot. */ + const commitNotesAfterFlush = useCallback((mutator: (notes: VaultNote[]) => VaultNote[]) => { + flushNoteDraft(); + return commitNotes(mutator(sortedNotesRef.current)); + }, [commitNotes, flushNoteDraft]); + + /** Rename from the tree row: merge title into the post-flush note so an + * unflushed body edit is not discarded by a stale tree-row snapshot. */ + const renameNoteFromTree = (noteId: string, title: string) => { + const nextTitle = title.trim(); + const updatedAt = Date.now(); + commitNotesAfterFlush((notes) => notes.map((note) => ( + note.id === noteId ? { ...note, title: nextTitle, updatedAt } : note + ))); + }; + + const saveNoteTitleDraft = (note: VaultNote, title: string) => { + updateNoteDraft(note.id, { title }); + }; + + const saveNoteContentDraft = (note: VaultNote, content: string) => { + updateNoteDraft(note.id, { content }); }; const handleOpenHostFromNote = useCallback((host: Host, noteId: string) => { @@ -531,10 +665,14 @@ export const NotesManager: React.FC = ({ }; const addNoteToGroup = (group: string | null) => { - const note = createNote(group, getNextVaultOrder(sortedNotes)); - commitNotes([...sortedNotes, note]); + let created: VaultNote | null = null; + commitNotesAfterFlush((notes) => { + created = createNote(group, getNextVaultOrder(notes)); + return [...notes, created]; + }); + if (!created) return; if (group) expandPath(group); - const nextSelection = getNoteSelectionState(note, isSidebarMode); + const nextSelection = getNoteSelectionState(created, isSidebarMode); setSelectedNoteId(nextSelection.selectedNoteId); setSelectedGroup(nextSelection.selectedGroup); setOverlayNoteId(nextSelection.overlayNoteId); @@ -591,7 +729,10 @@ export const NotesManager: React.FC = ({ const result = importMarkdownPayloadsToVaultNotes( payloads, - sortedNotesRef.current, + (() => { + flushNoteDraft(); + return sortedNotesRef.current; + })(), targetGroup, ); @@ -623,6 +764,7 @@ export const NotesManager: React.FC = ({ }, [ isSidebarMode, commitNotes, + flushNoteDraft, selectedGroup, selectedNote, t, @@ -645,10 +787,12 @@ export const NotesManager: React.FC = ({ }, []); const exportNoteToMarkdown = useCallback((note: VaultNote) => { + flushNoteDraft(); + const latest = sortedNotesRef.current.find((item) => item.id === note.id) ?? note; try { - const fileName = `${sanitizeNoteExportFileNamePart(note.title, "note")}.md`; + const fileName = `${sanitizeNoteExportFileNamePart(latest.title, "note")}.md`; downloadNotesBlob( - new Blob([note.content], { type: "text/markdown;charset=utf-8" }), + new Blob([latest.content], { type: "text/markdown;charset=utf-8" }), fileName, ); toast.success(t("notes.export.toast.success", { count: 1 })); @@ -656,9 +800,10 @@ export const NotesManager: React.FC = ({ logger.error("Failed to export note:", err); toast.error(t("notes.export.toast.failed")); } - }, [downloadNotesBlob, t]); + }, [downloadNotesBlob, flushNoteDraft, t]); const exportNotesToZip = useCallback((scope: VaultNotesExportScope, fileNamePart: string) => { + flushNoteDraft(); try { const files = buildVaultNoteMarkdownExportFiles(sortedNotesRef.current, scope); if (files.length === 0) { @@ -674,7 +819,7 @@ export const NotesManager: React.FC = ({ logger.error("Failed to export notes:", err); toast.error(t("notes.export.toast.failed")); } - }, [downloadNotesBlob, t]); + }, [downloadNotesBlob, flushNoteDraft, t]); const exportAllNotes = useCallback(() => { exportNotesToZip({ type: "all" }, "all"); @@ -703,7 +848,8 @@ export const NotesManager: React.FC = ({ ); const duplicateNoteById = (noteId: string) => { - const source = sortedNotes.find((note) => note.id === noteId); + flushNoteDraft(); + const source = sortedNotesRef.current.find((note) => note.id === noteId); if (!source) return; const now = Date.now(); const copy: VaultNote = { @@ -712,9 +858,9 @@ export const NotesManager: React.FC = ({ title: `${source.title} (${t("action.copy")})`, createdAt: now, updatedAt: now, - order: getNextVaultOrder(sortedNotes), + order: getNextVaultOrder(sortedNotesRef.current), }; - commitNotes([...sortedNotes, copy]); + commitNotes([...sortedNotesRef.current, copy]); if (copy.group) expandPath(copy.group); const nextSelection = getNoteSelectionState(copy, isSidebarMode); setSelectedNoteId(nextSelection.selectedNoteId); @@ -723,8 +869,7 @@ export const NotesManager: React.FC = ({ }; const performDeleteNoteById = (noteId: string) => { - const next = sortedNotes.filter((note) => note.id !== noteId); - commitNotes(next); + const next = commitNotesAfterFlush((notes) => notes.filter((note) => note.id !== noteId)); if (selectedNoteId === noteId) { const nextSelection = getFallbackNoteSelectionState(next, isSidebarMode); setSelectedNoteId(nextSelection.selectedNoteId); @@ -772,12 +917,11 @@ export const NotesManager: React.FC = ({ const nextGroups = normalizeNoteGroups( groups.map((item) => replaceNoteGroupPrefix(item, group, nextPath) || ""), ); - const nextNotes = sortedNotes.map((note) => ({ + onUpdateNoteGroups(nextGroups); + commitNotesAfterFlush((notes) => notes.map((note) => ({ ...note, group: replaceNoteGroupPrefix(note.group, group, nextPath), - })); - onUpdateNoteGroups(nextGroups); - commitNotes(nextNotes); + }))); setExpandedGroups((current) => { const next = new Set(); current.forEach((item) => { @@ -794,7 +938,9 @@ export const NotesManager: React.FC = ({ const performDeleteGroup = (group: string) => { onUpdateNoteGroups(groups.filter((item) => !isNoteGroupInside(item, group))); - commitNotes(sortedNotes.map((note) => isNoteGroupInside(note.group, group) ? { ...note, group: undefined } : note)); + commitNotesAfterFlush((notes) => notes.map((note) => ( + isNoteGroupInside(note.group, group) ? { ...note, group: undefined } : note + ))); if (selectedGroup && isNoteGroupInside(selectedGroup, group)) setSelectedGroup(null); setEditingGroupPath(null); }; @@ -844,12 +990,13 @@ export const NotesManager: React.FC = ({ }; const moveNoteToGroup = (noteId: string, group: string | null) => { - const source = sortedNotes.find((note) => note.id === noteId); + flushNoteDraft(); + const source = sortedNotesRef.current.find((note) => note.id === noteId); if (!source) return; const nextGroup = group || undefined; if ((source.group || undefined) === nextGroup) return; - commitNotes(sortedNotes.map((note) => ( + commitNotes(sortedNotesRef.current.map((note) => ( note.id === noteId ? { ...note, group: nextGroup, updatedAt: Date.now() } : note ))); if (group) expandPath(group); @@ -858,29 +1005,31 @@ export const NotesManager: React.FC = ({ const reorderNoteToNote = (sourceId: string, targetNote: VaultNote, event: React.DragEvent) => { if (!sourceId || sourceId === targetNote.id) return; const position = getVaultDropPosition(event.currentTarget, event.clientX, event.clientY); - const movedNotes = sortedNotes.map((note) => ( - note.id === sourceId - ? { ...note, group: targetNote.group, updatedAt: Date.now() } - : note - )); - commitNotes(reorderVaultItems(movedNotes, sourceId, targetNote.id, position)); + commitNotesAfterFlush((notes) => { + const movedNotes = notes.map((note) => ( + note.id === sourceId + ? { ...note, group: targetNote.group, updatedAt: Date.now() } + : note + )); + return reorderVaultItems(movedNotes, sourceId, targetNote.id, position); + }); if (targetNote.group) expandPath(targetNote.group); }; const moveGroupToParent = (group: string, parent: string | null) => { + flushNoteDraft(); const knownGroups = normalizeNoteGroups([ ...groups, - ...sortedNotes.map((note) => note.group).filter((item): item is string => Boolean(item)), + ...sortedNotesRef.current.map((note) => note.group).filter((item): item is string => Boolean(item)), ]); const nextPath = resolveMovedNoteGroupPath(group, parent, knownGroups); if (!nextPath) return; const nextGroups = normalizeNoteGroups(groups.map((item) => replaceNoteGroupPrefix(item, group, nextPath) || "")); - const nextNotes = sortedNotes.map((note) => ({ + onUpdateNoteGroups(nextGroups); + commitNotes(sortedNotesRef.current.map((note) => ({ ...note, group: replaceNoteGroupPrefix(note.group, group, nextPath), - })); - onUpdateNoteGroups(nextGroups); - commitNotes(nextNotes); + }))); setExpandedGroups((current) => remapExpandedNoteGroupPaths(current, group, nextPath)); if (selectedGroup && isNoteGroupInside(selectedGroup, group)) { setSelectedGroup(replaceNoteGroupPrefix(selectedGroup, group, nextPath) ?? null); @@ -895,10 +1044,11 @@ export const NotesManager: React.FC = ({ if (!sourceGroup || !targetGroup || sourceGroup === targetGroup) return; if (targetGroup.startsWith(`${sourceGroup}/`)) return; + flushNoteDraft(); const targetParent = getNoteGroupParentPath(targetGroup); const knownGroups = normalizeNoteGroups([ ...groups, - ...sortedNotes.map((note) => note.group).filter((item): item is string => Boolean(item)), + ...sortedNotesRef.current.map((note) => note.group).filter((item): item is string => Boolean(item)), ]); const nextSourceGroup = getNoteGroupParentPath(sourceGroup) === targetParent ? cleanNoteGroupPath(sourceGroup) @@ -916,16 +1066,13 @@ export const NotesManager: React.FC = ({ targetGroup, position, ); - const nextNotes = nextSourceGroup === sourceGroup - ? sortedNotes - : sortedNotes.map((note) => ({ - ...note, - group: replaceNoteGroupPrefix(note.group, sourceGroup, nextSourceGroup), - })); onUpdateNoteGroups(nextGroups); if (nextSourceGroup !== sourceGroup) { - commitNotes(nextNotes); + commitNotes(sortedNotesRef.current.map((note) => ({ + ...note, + group: replaceNoteGroupPrefix(note.group, sourceGroup, nextSourceGroup), + }))); setExpandedGroups((current) => remapExpandedNoteGroupPaths(current, sourceGroup, nextSourceGroup)); if (selectedGroup && isNoteGroupInside(selectedGroup, sourceGroup)) { setSelectedGroup(replaceNoteGroupPrefix(selectedGroup, sourceGroup, nextSourceGroup) ?? null); @@ -1092,7 +1239,7 @@ export const NotesManager: React.FC = ({ editingInitialName={note.title} onRenameCommit={(name) => { setEditingNoteId(null); - saveNote({ ...note, title: name.trim(), updatedAt: Date.now() }); + renameNoteFromTree(note.id, name); }} onRenameCancel={() => setEditingNoteId(null)} icon={} @@ -1515,41 +1662,41 @@ export const NotesManager: React.FC = ({ {!isSidebarMode && (
- {selectedNote ? ( + {selectedNoteView ? ( <>
saveNote({ - ...selectedNote, - title: event.target.value, - updatedAt: Date.now(), - })} + onChange={(event) => saveNoteTitleDraft(selectedNoteView, event.target.value)} + onBlur={() => flushNoteDraft()} />
- {renderNoteExportButton(selectedNote)} + {renderNoteExportButton(selectedNoteView)} {renderNoteModeToggle()}
-
- +
{ + if (!event.currentTarget.contains(event.relatedTarget as Node | null)) { + flushNoteDraft(); + } + }} + > + }> saveNote({ - ...selectedNote, - content, - updatedAt: Date.now(), - })} + onChange={(content) => saveNoteContentDraft(selectedNoteView, content)} hosts={hosts} - onOpenHost={(host) => handleOpenHostFromNote(host, selectedNote.id)} + onOpenHost={(host) => handleOpenHostFromNote(host, selectedNoteView.id)} onOpenExternalLink={openExternal} /> @@ -1582,7 +1729,7 @@ export const NotesManager: React.FC = ({ )}
- {isSidebarMode && overlayNote && ( + {isSidebarMode && overlayNoteView && (
= ({ {t("common.back")}
- {overlayNote.title || t("notes.title.placeholder")} + {overlayNoteView.title || t("notes.title.placeholder")}
@@ -1610,35 +1757,35 @@ export const NotesManager: React.FC = ({
saveNote({ - ...overlayNote, - title: event.target.value, - updatedAt: Date.now(), - })} + onChange={(event) => saveNoteTitleDraft(overlayNoteView, event.target.value)} + onBlur={() => flushNoteDraft()} />
- {renderNoteExportButton(overlayNote)} + {renderNoteExportButton(overlayNoteView)} {renderNoteModeToggle()}
-
- +
{ + if (!event.currentTarget.contains(event.relatedTarget as Node | null)) { + flushNoteDraft(); + } + }} + > + }> saveNote({ - ...overlayNote, - content, - updatedAt: Date.now(), - })} + onChange={(content) => saveNoteContentDraft(overlayNoteView, content)} previewEmptyLabel={t("notes.preview.empty")} hosts={hosts} - onOpenHost={(host) => handleOpenHostFromNote(host, overlayNote.id)} + onOpenHost={(host) => handleOpenHostFromNote(host, overlayNoteView.id)} onOpenExternalLink={openExternal} /> diff --git a/components/port-forwarding/hostKeyVerification.ts b/components/port-forwarding/hostKeyVerification.ts index bbae439ca..d0e6d6cf1 100644 --- a/components/port-forwarding/hostKeyVerification.ts +++ b/components/port-forwarding/hostKeyVerification.ts @@ -1,56 +1,10 @@ -import type { KnownHost } from "../../domain/models"; -import { toHostKeyInfo, type HostKeyVerificationRequest } from "../terminal/hostKeyVerification"; -import type { HostKeyInfo } from "../terminal/TerminalHostKeyVerification"; - -export const isPortForwardHostKeySessionId = (sessionId?: string): boolean => { - return typeof sessionId === "string" && sessionId.startsWith("pf-"); -}; - -export type PortForwardHostKeyRequest = HostKeyVerificationRequest & { - requestId: string; - sessionId?: string; -}; - -export interface PendingPortForwardHostKeyVerification { - requestId: string; - hostKeyInfo: HostKeyInfo; -} - -export const toPendingPortForwardHostKeyVerification = ( - request: PortForwardHostKeyRequest, -): PendingPortForwardHostKeyVerification | null => { - if (!isPortForwardHostKeySessionId(request.sessionId)) return null; - return { - requestId: request.requestId, - hostKeyInfo: toHostKeyInfo(request), - }; -}; - -export const enqueuePortForwardHostKeyVerification = ( - queue: PendingPortForwardHostKeyVerification[], - pending: PendingPortForwardHostKeyVerification, -): PendingPortForwardHostKeyVerification[] => [...queue, pending]; - -export const removePortForwardHostKeyVerification = ( - queue: PendingPortForwardHostKeyVerification[], - requestId: string, -): PendingPortForwardHostKeyVerification[] => { - if (queue[0]?.requestId === requestId) { - return queue.slice(1); - } - return queue.filter((pending) => pending.requestId !== requestId); -}; - -export const createKnownHostFromPortForwardHostKeyInfo = ( - hostKeyInfo: HostKeyInfo, - now = Date.now(), - idSuffix = Math.random().toString(36).slice(2, 11), -): KnownHost => ({ - id: hostKeyInfo.knownHostId || `kh-${now}-${idSuffix}`, - hostname: hostKeyInfo.hostname, - port: hostKeyInfo.port || 22, - keyType: hostKeyInfo.keyType, - publicKey: hostKeyInfo.publicKey || `SHA256:${hostKeyInfo.fingerprint}`, - fingerprint: hostKeyInfo.fingerprint, - discoveredAt: now, -}); +/** @deprecated Import from `@/domain/portForwardHostKey` instead. */ +export { + createKnownHostFromPortForwardHostKeyInfo, + enqueuePortForwardHostKeyVerification, + isPortForwardHostKeySessionId, + removePortForwardHostKeyVerification, + toPendingPortForwardHostKeyVerification, + type PendingPortForwardHostKeyVerification, + type PortForwardHostKeyRequest, +} from "../../domain/portForwardHostKey"; diff --git a/components/settings/tabs/ai/ExternalMcpCard.tsx b/components/settings/tabs/ai/ExternalMcpCard.tsx index ae821965b..37411a3ea 100644 --- a/components/settings/tabs/ai/ExternalMcpCard.tsx +++ b/components/settings/tabs/ai/ExternalMcpCard.tsx @@ -2,26 +2,19 @@ import React, { useCallback, useEffect, useMemo, useState } from "react"; import { Check, Copy, HelpCircle, RefreshCw } from "lucide-react"; import { useI18n } from "../../../../application/i18n/I18nProvider"; import { - normalizeExternalMcpIdleTimeoutMinutes, - normalizeExternalMcpMode, - normalizeSessionIdleTimeoutMinutes, readExternalMcpFocusOnHostOpen, readExternalMcpIdleTimeoutMinutes, readExternalMcpMode, readExternalMcpSilentSessions, readSessionIdleTimeoutMinutes, writeExternalMcpFocusOnHostOpen, + writeExternalMcpIdleTimeoutMinutes, + writeExternalMcpMode, writeExternalMcpSilentSessions, + writeSessionIdleTimeoutMinutes, type ExternalMcpMode, useExternalMcpToggleState, } from "../../../../application/state/useExternalMcpToggleState"; -import { - STORAGE_KEY_AI_EXTERNAL_MCP_IDLE_TIMEOUT_MINUTES, - STORAGE_KEY_AI_EXTERNAL_MCP_MODE, - STORAGE_KEY_AI_SESSION_IDLE_TIMEOUT_MINUTES, -} from "../../../../infrastructure/config/storageKeys"; -import { localStorageAdapter } from "../../../../infrastructure/persistence/localStorageAdapter"; -import { emitAIStateChanged } from "../../../../application/state/aiStateEvents"; import { cn } from "../../../../lib/utils"; import { Button } from "../../../ui/button"; import { Tooltip, TooltipContent, TooltipTrigger } from "../../../ui/tooltip"; @@ -328,26 +321,20 @@ export const ExternalMcpCard: React.FC = () => { }, []); const setMode = useCallback((nextMode: ExternalMcpMode) => { - const normalized = normalizeExternalMcpMode(nextMode); + const normalized = writeExternalMcpMode(nextMode); setModeRaw(normalized); - localStorageAdapter.writeString(STORAGE_KEY_AI_EXTERNAL_MCP_MODE, normalized); - emitAIStateChanged(STORAGE_KEY_AI_EXTERNAL_MCP_MODE); pushConfig(normalized, idleTimeoutMinutes, sessionIdleTimeoutMinutes); }, [idleTimeoutMinutes, pushConfig, sessionIdleTimeoutMinutes]); const setIdleTimeoutMinutes = useCallback((minutes: number) => { - const normalized = normalizeExternalMcpIdleTimeoutMinutes(minutes); + const normalized = writeExternalMcpIdleTimeoutMinutes(minutes); setIdleTimeoutRaw(normalized); - localStorageAdapter.writeNumber(STORAGE_KEY_AI_EXTERNAL_MCP_IDLE_TIMEOUT_MINUTES, normalized); - emitAIStateChanged(STORAGE_KEY_AI_EXTERNAL_MCP_IDLE_TIMEOUT_MINUTES); pushConfig(mode, normalized, sessionIdleTimeoutMinutes); }, [mode, pushConfig, sessionIdleTimeoutMinutes]); const setSessionIdleTimeoutMinutes = useCallback((minutes: number) => { - const normalized = normalizeSessionIdleTimeoutMinutes(minutes); + const normalized = writeSessionIdleTimeoutMinutes(minutes); setSessionIdleTimeoutRaw(normalized); - localStorageAdapter.writeNumber(STORAGE_KEY_AI_SESSION_IDLE_TIMEOUT_MINUTES, normalized); - emitAIStateChanged(STORAGE_KEY_AI_SESSION_IDLE_TIMEOUT_MINUTES); pushConfig(mode, idleTimeoutMinutes, normalized); }, [idleTimeoutMinutes, mode, pushConfig]); diff --git a/components/sftp/SftpPaneFileList.tsx b/components/sftp/SftpPaneFileList.tsx index d0acc8598..39c08e2cb 100644 --- a/components/sftp/SftpPaneFileList.tsx +++ b/components/sftp/SftpPaneFileList.tsx @@ -14,7 +14,7 @@ import type { SftpFileEntry } from "../../types"; import type { SftpPane } from "../../application/state/sftp/types"; import type { SftpTransferSource } from "./SftpContext"; import { sftpListOrderStore } from "./hooks/useSftpListOrderStore"; -import type { UseSftpPaneSortingResult } from "./hooks/useSftpPaneSorting"; +import type { UseSftpPaneSortingResult } from "../../application/state/sftp/useSftpPaneSorting"; import { buildSftpColumnTemplate, isNavigableDirectory, isSftpColumnMenuKey } from "./utils"; import { isKnownBinaryFile } from "../../lib/sftpFileUtils"; import { SftpFileRow } from "./SftpFileRow"; diff --git a/components/sftp/SftpPaneTreeView.tsx b/components/sftp/SftpPaneTreeView.tsx index 41eed30e0..9a94ad043 100644 --- a/components/sftp/SftpPaneTreeView.tsx +++ b/components/sftp/SftpPaneTreeView.tsx @@ -12,7 +12,7 @@ import { getParentPath, isWindowsRoot, joinPath, resolveSftpWindowsPathOptions } import { buildSftpColumnTemplate, filterHiddenFiles, isNavigableDirectory, isSftpColumnMenuKey, sortSftpEntries } from './utils'; import type { SftpTransferSource } from './SftpContext'; import type { SftpPaneTreeViewProps } from './SftpPaneTreeView.types'; -import { sftpTreeSelectionStore, useSftpTreeSelectionState } from './hooks/useSftpTreeSelectionStore'; +import { sftpTreeSelectionStore, useSftpTreeSelectionState } from '../../application/state/sftp/sftpTreeSelectionStore'; import { sftpKeyboardSelectionStore, sftpTreeEnterStore } from './hooks/useSftpKeyboardShortcuts'; import { useI18n } from '../../application/i18n/I18nProvider'; import { SftpColumnMenuItems } from './SftpColumnMenuItems'; diff --git a/components/sftp/SftpPaneTreeView.types.ts b/components/sftp/SftpPaneTreeView.types.ts index 86604b59d..c89231c11 100644 --- a/components/sftp/SftpPaneTreeView.types.ts +++ b/components/sftp/SftpPaneTreeView.types.ts @@ -1,7 +1,7 @@ import type { SftpFileEntry } from '../../types'; import type { SftpPane } from '../../application/state/sftp/types'; import type { SftpTransferSource } from './SftpContext'; -import type { UseSftpPaneSortingResult } from './hooks/useSftpPaneSorting'; +import type { UseSftpPaneSortingResult } from '../../application/state/sftp/useSftpPaneSorting'; export interface SftpPaneTreeViewProps { pane: SftpPane; diff --git a/components/sftp/SftpPaneView.tsx b/components/sftp/SftpPaneView.tsx index f59025dcb..3a51253bd 100644 --- a/components/sftp/SftpPaneView.tsx +++ b/components/sftp/SftpPaneView.tsx @@ -25,16 +25,16 @@ import { useSftpPaneDialogs } from "./hooks/useSftpPaneDialogs"; import { useSftpPaneDragAndSelect } from "./hooks/useSftpPaneDragAndSelect"; import { useSftpPaneFiles } from "./hooks/useSftpPaneFiles"; import { useSftpPanePath } from "./hooks/useSftpPanePath"; -import { useSftpPaneSorting, type UseSftpPaneSortingResult } from "./hooks/useSftpPaneSorting"; +import { useSftpPaneSorting, type UseSftpPaneSortingResult } from "../../application/state/sftp/useSftpPaneSorting"; import { useSftpPaneVirtualList } from "./hooks/useSftpPaneVirtualList"; import { sftpPaneViewModeStore } from "../../application/state/sftp/sftpPaneViewModeStore"; -import { useSftpDialogActionHandler } from "./hooks/useSftpDialogAction"; +import { useSftpDialogActionHandler } from "../../application/state/sftp/sftpDialogActionStore"; import { useSftpBookmarks } from "./hooks/useSftpBookmarks"; -import { useLocalSftpBookmarks } from "./hooks/useLocalSftpBookmarks"; +import { useLocalSftpBookmarks } from "../../application/state/sftp/localSftpBookmarks"; import { useGlobalSftpBookmarks } from "./hooks/useGlobalSftpBookmarks"; -import { useSftpHostViewMode } from "./hooks/useSftpHostViewMode"; +import { useSftpHostViewMode } from "../../application/state/sftp/sftpHostViewModeStore"; import { sftpListOrderStore } from "./hooks/useSftpListOrderStore"; -import { sftpTreeSelectionStore } from "./hooks/useSftpTreeSelectionStore"; +import { sftpTreeSelectionStore } from "../../application/state/sftp/sftpTreeSelectionStore"; import { sftpClipboardUploadStore } from "./clipboardUpload"; interface TreeReloadRequest { diff --git a/components/sftp/hooks/selectionScope.ts b/components/sftp/hooks/selectionScope.ts index 23349aa46..763feb7da 100644 --- a/components/sftp/hooks/selectionScope.ts +++ b/components/sftp/hooks/selectionScope.ts @@ -1,5 +1,5 @@ import type { SftpStateApi } from "../../../application/state/useSftpState"; -import { sftpTreeSelectionStore } from "./useSftpTreeSelectionStore"; +import { sftpTreeSelectionStore } from "../../../application/state/sftp/sftpTreeSelectionStore"; export interface SftpSelectionTarget { side: "left" | "right"; diff --git a/components/sftp/hooks/useLocalSftpBookmarks.ts b/components/sftp/hooks/useLocalSftpBookmarks.ts index 2744609c5..438e3a69d 100644 --- a/components/sftp/hooks/useLocalSftpBookmarks.ts +++ b/components/sftp/hooks/useLocalSftpBookmarks.ts @@ -1,65 +1,8 @@ -import { useCallback, useMemo, useSyncExternalStore } from "react"; -import type { SftpBookmark } from "../../../domain/models"; -import { localStorageAdapter } from "../../../infrastructure/persistence/localStorageAdapter"; -import { STORAGE_KEY_SFTP_LOCAL_BOOKMARKS } from "../../../infrastructure/config/storageKeys"; -import { createSftpBookmark } from "../../../application/state/sftp/bookmarkHelpers"; - -// ── Shared external store so every hook instance sees the same bookmarks ── - -type Listener = () => void; -const listeners = new Set(); - -let snapshot: SftpBookmark[] = - localStorageAdapter.read(STORAGE_KEY_SFTP_LOCAL_BOOKMARKS) ?? []; - -function subscribe(listener: Listener) { - listeners.add(listener); - return () => { listeners.delete(listener); }; -} - -function getSnapshot() { - return snapshot; -} - -function setBookmarks(next: SftpBookmark[] | ((prev: SftpBookmark[]) => SftpBookmark[])) { - snapshot = typeof next === "function" ? next(snapshot) : next; - localStorageAdapter.write(STORAGE_KEY_SFTP_LOCAL_BOOKMARKS, snapshot); - for (const l of listeners) l(); -} - -// ── Hook ── - -interface UseLocalSftpBookmarksParams { - currentPath: string | undefined; -} - -export const useLocalSftpBookmarks = ({ - currentPath, -}: UseLocalSftpBookmarksParams) => { - const bookmarks = useSyncExternalStore(subscribe, getSnapshot, getSnapshot); - - const isCurrentPathBookmarked = useMemo( - () => !!currentPath && bookmarks.some((b) => b.path === currentPath), - [currentPath, bookmarks], - ); - - const toggleBookmark = useCallback(() => { - if (!currentPath) return; - if (isCurrentPathBookmarked) { - setBookmarks((prev) => prev.filter((b) => b.path !== currentPath)); - } else { - setBookmarks((prev) => [...prev, createSftpBookmark(currentPath)]); - } - }, [currentPath, isCurrentPathBookmarked]); - - const deleteBookmark = useCallback((id: string) => { - setBookmarks((prev) => prev.filter((b) => b.id !== id)); - }, []); - - return { - bookmarks, - isCurrentPathBookmarked, - toggleBookmark, - deleteBookmark, - }; -}; +/** @deprecated Import from `@/application/state/sftp/localSftpBookmarks` instead. */ +export { + useLocalSftpBookmarks, + subscribeLocalSftpBookmarks, + getLocalSftpBookmarksSnapshot, + rehydrateLocalSftpBookmarks, + setLocalSftpBookmarks, +} from "../../../application/state/sftp/localSftpBookmarks"; diff --git a/components/sftp/hooks/useSftpClipboard.ts b/components/sftp/hooks/useSftpClipboard.ts index 39b28fa0f..f92812805 100644 --- a/components/sftp/hooks/useSftpClipboard.ts +++ b/components/sftp/hooks/useSftpClipboard.ts @@ -1,124 +1,6 @@ -/** - * SFTP Clipboard Store - * - * Manages clipboard state for SFTP file operations (copy/cut/paste) - * This is a simple store that holds the clipboard state and operation type. - */ - -import { useSyncExternalStore } from "react"; - -type SftpClipboardOperation = "copy" | "cut"; - -export interface SftpClipboardFile { - name: string; - isDirectory: boolean; -} - -interface SftpClipboardState { - files: SftpClipboardFile[]; - sourcePath: string; - sourceConnectionId: string; - sourceSide: "left" | "right"; - operation: SftpClipboardOperation; -} - -type ClipboardListener = () => void; - -let clipboardState: SftpClipboardState | null = null; -const clipboardListeners = new Set(); - -const notifyListeners = () => { - clipboardListeners.forEach((listener) => listener()); -}; - -export const sftpClipboardStore = { - getSnapshot: (): SftpClipboardState | null => clipboardState, - - subscribe: (listener: ClipboardListener) => { - clipboardListeners.add(listener); - return () => clipboardListeners.delete(listener); - }, - - /** - * Copy files to clipboard - */ - copy: ( - files: SftpClipboardFile[], - sourcePath: string, - sourceConnectionId: string, - sourceSide: "left" | "right" - ) => { - clipboardState = { - files, - sourcePath, - sourceConnectionId, - sourceSide, - operation: "copy", - }; - notifyListeners(); - }, - - /** - * Cut files to clipboard - */ - cut: ( - files: SftpClipboardFile[], - sourcePath: string, - sourceConnectionId: string, - sourceSide: "left" | "right" - ) => { - clipboardState = { - files, - sourcePath, - sourceConnectionId, - sourceSide, - operation: "cut", - }; - notifyListeners(); - }, - - /** - * Clear clipboard (called after paste for cut operation) - */ - clear: () => { - clipboardState = null; - notifyListeners(); - }, - - /** - * Update clipboard file list (used for partial cut transfers) - */ - updateFiles: (files: SftpClipboardFile[]) => { - if (!clipboardState) return; - if (files.length === 0) { - clipboardState = null; - } else { - clipboardState = { - ...clipboardState, - files, - }; - } - notifyListeners(); - }, - - /** - * Check if there are files in the clipboard - */ - hasFiles: (): boolean => clipboardState !== null && clipboardState.files.length > 0, - - /** - * Get the clipboard state - */ - get: (): SftpClipboardState | null => clipboardState, -}; - -/** - * React hook to subscribe to clipboard state changes - */ -export const useSftpClipboard = (): SftpClipboardState | null => { - return useSyncExternalStore( - sftpClipboardStore.subscribe, - sftpClipboardStore.getSnapshot, - sftpClipboardStore.getSnapshot - ); -}; +/** @deprecated Import from `@/application/state/sftp/sftpClipboardStore` instead. */ +export { + sftpClipboardStore, + useSftpClipboard, + type SftpClipboardFile, +} from "../../../application/state/sftp/sftpClipboardStore"; diff --git a/components/sftp/hooks/useSftpDialogAction.ts b/components/sftp/hooks/useSftpDialogAction.ts index b63f7a802..2eb979878 100644 --- a/components/sftp/hooks/useSftpDialogAction.ts +++ b/components/sftp/hooks/useSftpDialogAction.ts @@ -1,124 +1,6 @@ -/** - * SFTP Dialog Action Store - * - * Manages dialog action triggers for SFTP operations. - * This store allows keyboard shortcuts to trigger dialogs in the appropriate pane. - */ - -import { useSyncExternalStore, useEffect } from "react"; -import { sftpFocusStore, SftpFocusedSide } from "./useSftpFocusedPane"; - -type SftpDialogActionType = "rename" | "delete" | "newFolder" | "newFile" | null; - -interface SftpDialogAction { - type: SftpDialogActionType; - targetSide: SftpFocusedSide; - targetScopeId: string; - targetFiles?: string[]; // For rename (single file) or delete (multiple files) - timestamp: number; // To distinguish different triggers of the same action -} - -type ActionListener = () => void; - -let dialogAction: SftpDialogAction | null = null; -const actionListeners = new Set(); - -const notifyListeners = () => { - actionListeners.forEach((listener) => listener()); -}; - -export const sftpDialogActionStore = { - getSnapshot: (): SftpDialogAction | null => dialogAction, - - subscribe: (listener: ActionListener) => { - actionListeners.add(listener); - return () => actionListeners.delete(listener); - }, - - /** - * Trigger a dialog action - */ - trigger: (type: SftpDialogActionType, targetScopeId: string, targetFiles?: string[]) => { - if (!type) { - dialogAction = null; - } else { - dialogAction = { - type, - targetSide: sftpFocusStore.getFocusedSide(), - targetScopeId, - targetFiles, - timestamp: Date.now(), - }; - } - notifyListeners(); - }, - - /** - * Clear the current action (called after a pane handles it) - */ - clear: () => { - dialogAction = null; - notifyListeners(); - }, - - /** - * Get the current action - */ - get: (): SftpDialogAction | null => dialogAction, -}; - -/** - * React hook to subscribe to dialog action changes - */ -export const useSftpDialogAction = (): SftpDialogAction | null => { - return useSyncExternalStore( - sftpDialogActionStore.subscribe, - sftpDialogActionStore.getSnapshot, - sftpDialogActionStore.getSnapshot - ); -}; - -/** - * React hook for a pane to respond to dialog actions - * Only the pane matching the targetSide will execute the callback - */ -export const useSftpDialogActionHandler = ( - side: SftpFocusedSide, - scopeId: string, - handlers: { - onRename?: (fileName: string) => void; - onDelete?: (fileNames: string[]) => void; - onNewFolder?: () => void; - onNewFile?: () => void; - }, - isActive = true -) => { - const action = useSftpDialogAction(); - - useEffect(() => { - if (!action || action.targetSide !== side || action.targetScopeId !== scopeId || !isActive) return; - - // Handle the action and clear it - switch (action.type) { - case "rename": - if (handlers.onRename && action.targetFiles?.[0]) { - handlers.onRename(action.targetFiles[0]); - } - break; - case "delete": - if (handlers.onDelete && action.targetFiles) { - handlers.onDelete(action.targetFiles); - } - break; - case "newFolder": - handlers.onNewFolder?.(); - break; - case "newFile": - handlers.onNewFile?.(); - break; - } - - // Clear the action after handling - sftpDialogActionStore.clear(); - }, [action, side, scopeId, handlers, isActive]); -}; +/** @deprecated Import from `@/application/state/sftp/sftpDialogActionStore` instead. */ +export { + sftpDialogActionStore, + useSftpDialogAction, + useSftpDialogActionHandler, +} from "../../../application/state/sftp/sftpDialogActionStore"; diff --git a/components/sftp/hooks/useSftpFocusedPane.ts b/components/sftp/hooks/useSftpFocusedPane.ts index 69f9bc50c..1a2128e1b 100644 --- a/components/sftp/hooks/useSftpFocusedPane.ts +++ b/components/sftp/hooks/useSftpFocusedPane.ts @@ -1,54 +1,6 @@ -/** - * SFTP Focused Pane Store - * - * Tracks which SFTP pane (left or right) is currently focused. - * This is used to determine which pane should receive keyboard shortcut actions. - */ - -import { useSyncExternalStore } from "react"; - -export type SftpFocusedSide = "left" | "right"; - -type FocusListener = () => void; - -let focusedSide: SftpFocusedSide = "left"; -const focusListeners = new Set(); - -const notifyListeners = () => { - focusListeners.forEach((listener) => listener()); -}; - -export const sftpFocusStore = { - getSnapshot: (): SftpFocusedSide => focusedSide, - - subscribe: (listener: FocusListener) => { - focusListeners.add(listener); - return () => focusListeners.delete(listener); - }, - - /** - * Set the focused side - */ - setFocusedSide: (side: SftpFocusedSide) => { - if (focusedSide !== side) { - focusedSide = side; - notifyListeners(); - } - }, - - /** - * Get the current focused side - */ - getFocusedSide: (): SftpFocusedSide => focusedSide, -}; - -/** - * React hook to subscribe to focused side changes - */ -export const useSftpFocusedSide = (): SftpFocusedSide => { - return useSyncExternalStore( - sftpFocusStore.subscribe, - sftpFocusStore.getSnapshot, - sftpFocusStore.getSnapshot - ); -}; +/** @deprecated Import from `@/application/state/sftp/sftpFocusStore` instead. */ +export { + sftpFocusStore, + useSftpFocusedSide, + type SftpFocusedSide, +} from "../../../application/state/sftp/sftpFocusStore"; diff --git a/components/sftp/hooks/useSftpHostViewMode.ts b/components/sftp/hooks/useSftpHostViewMode.ts index 2d1e8cbcd..1851fc775 100644 --- a/components/sftp/hooks/useSftpHostViewMode.ts +++ b/components/sftp/hooks/useSftpHostViewMode.ts @@ -1,70 +1,6 @@ -import { useCallback, useSyncExternalStore } from "react"; -import { localStorageAdapter } from "../../../infrastructure/persistence/localStorageAdapter"; -import { STORAGE_KEY_SFTP_HOST_VIEW_MODES } from "../../../infrastructure/config/storageKeys"; - -// ── Shared external store for per-host SFTP view mode preferences ── - -type ViewMode = 'list' | 'tree'; -type Listener = () => void; - -const listeners = new Set(); - -let snapshot: Record = - localStorageAdapter.read>(STORAGE_KEY_SFTP_HOST_VIEW_MODES) ?? {}; - -function subscribe(listener: Listener) { - listeners.add(listener); - return () => { listeners.delete(listener); }; -} - -function getSnapshot() { - return snapshot; -} - -function persist(next: Record) { - snapshot = next; - localStorageAdapter.write(STORAGE_KEY_SFTP_HOST_VIEW_MODES, snapshot); - for (const l of listeners) l(); -} - -// Sync across windows/tabs via storage events -if (typeof window !== 'undefined') { - window.addEventListener('storage', (e) => { - if (e.key !== STORAGE_KEY_SFTP_HOST_VIEW_MODES) return; - try { - snapshot = e.newValue - ? (JSON.parse(e.newValue) as Record) - : {}; - } catch { - snapshot = {}; - } - for (const l of listeners) l(); - }); -} - -/** Get the saved view mode for a specific host, or null if none saved. */ -export function getHostViewMode(hostId: string): ViewMode | null { - return snapshot[hostId] ?? null; -} - -/** Save the view mode preference for a specific host. */ -export function setHostViewMode(hostId: string, mode: ViewMode): void { - if (snapshot[hostId] === mode) return; - persist({ ...snapshot, [hostId]: mode }); -} - -// ── Hook ── - -export function useSftpHostViewMode(hostId: string | undefined) { - const store = useSyncExternalStore(subscribe, getSnapshot, getSnapshot); - - const mode: ViewMode | null = hostId ? (store[hostId] ?? null) : null; - - const setMode = useCallback((newMode: ViewMode) => { - if (hostId) { - setHostViewMode(hostId, newMode); - } - }, [hostId]); - - return { hostViewMode: mode, setHostViewMode: setMode }; -} +/** @deprecated Import from `@/application/state/sftp/sftpHostViewModeStore` instead. */ +export { + getHostViewMode, + setHostViewMode, + useSftpHostViewMode, +} from "../../../application/state/sftp/sftpHostViewModeStore"; diff --git a/components/sftp/hooks/useSftpKeyboardShortcuts.ts b/components/sftp/hooks/useSftpKeyboardShortcuts.ts index 798967a4e..56a93d0a2 100644 --- a/components/sftp/hooks/useSftpKeyboardShortcuts.ts +++ b/components/sftp/hooks/useSftpKeyboardShortcuts.ts @@ -10,10 +10,10 @@ import type { MutableRefObject } from "react"; import { KeyBinding, matchesKeyBinding } from "../../../domain/models"; import { getParentPath, joinPath, resolveSftpWindowsPathOptions } from "../../../application/state/sftp/utils"; import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge"; -import { sftpClipboardStore, SftpClipboardFile } from "./useSftpClipboard"; -import { sftpFocusStore } from "./useSftpFocusedPane"; -import { sftpDialogActionStore } from "./useSftpDialogAction"; -import { sftpTreeSelectionStore } from "./useSftpTreeSelectionStore"; +import { sftpClipboardStore, SftpClipboardFile } from "../../../application/state/sftp/sftpClipboardStore"; +import { sftpFocusStore } from "../../../application/state/sftp/sftpFocusStore"; +import { sftpDialogActionStore } from "../../../application/state/sftp/sftpDialogActionStore"; +import { sftpTreeSelectionStore } from "../../../application/state/sftp/sftpTreeSelectionStore"; import { sftpListOrderStore } from "./useSftpListOrderStore"; import { sftpPaneViewModeStore } from "../../../application/state/sftp/sftpPaneViewModeStore"; import { keepOnlyPaneSelections } from "./selectionScope"; diff --git a/components/sftp/hooks/useSftpPaneSorting.ts b/components/sftp/hooks/useSftpPaneSorting.ts index 65b33ca77..6ecb2cc0b 100644 --- a/components/sftp/hooks/useSftpPaneSorting.ts +++ b/components/sftp/hooks/useSftpPaneSorting.ts @@ -1,168 +1,5 @@ -import React, { useCallback, useEffect, useRef, useState } from "react"; -import { - DEFAULT_SFTP_COLUMN_VISIBILITY, - normalizeSftpColumnVisibility, - type ColumnWidths, - type SftpColumnVisibility, - type SortField, - type SortOrder, -} from "../utils"; -import { STORAGE_KEY_SFTP_VISIBLE_COLUMNS } from "../../../infrastructure/config/storageKeys"; -import { - LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, - localStorageAdapter, -} from "../../../infrastructure/persistence/localStorageAdapter"; -import { useSftpDirectoriesFirst } from "../../../application/state/sftp/useSftpDirectoriesFirst"; - -export interface UseSftpPaneSortingResult { - sortField: SortField; - sortOrder: SortOrder; - directoriesFirst: boolean; - columnWidths: ColumnWidths; - visibleColumns: SftpColumnVisibility; - handleSort: (field: SortField) => void; - handleResizeStart: (field: keyof ColumnWidths, e: React.MouseEvent) => void; - toggleColumnVisibility: (field: keyof ColumnWidths) => void; - toggleDirectoriesFirst: () => void; -} - -export const useSftpPaneSorting = (): UseSftpPaneSortingResult => { - const [sortField, setSortField] = useState("name"); - const [sortOrder, setSortOrder] = useState("asc"); - const { directoriesFirst, toggleDirectoriesFirst } = useSftpDirectoriesFirst(); - const [columnWidths, setColumnWidths] = useState({ - name: 56, - modified: 28, - size: 7, - type: 9, - }); - const [visibleColumns, setVisibleColumns] = useState(() => - normalizeSftpColumnVisibility( - localStorageAdapter.read>(STORAGE_KEY_SFTP_VISIBLE_COLUMNS), - ), - ); - - useEffect(() => { - const syncVisibleColumns = (event: Event) => { - if (event instanceof StorageEvent && event.key !== STORAGE_KEY_SFTP_VISIBLE_COLUMNS) return; - if (event instanceof CustomEvent && event.detail?.key !== STORAGE_KEY_SFTP_VISIBLE_COLUMNS) return; - const next = normalizeSftpColumnVisibility( - localStorageAdapter.read>(STORAGE_KEY_SFTP_VISIBLE_COLUMNS), - ); - setVisibleColumns(next); - }; - - window.addEventListener("storage", syncVisibleColumns); - window.addEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, syncVisibleColumns); - return () => { - window.removeEventListener("storage", syncVisibleColumns); - window.removeEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, syncVisibleColumns); - }; - }, []); - - useEffect(() => { - if (visibleColumns[sortField]) return; - setSortField("name"); - setSortOrder("asc"); - }, [sortField, visibleColumns]); - - const toggleColumnVisibility = useCallback((field: keyof ColumnWidths) => { - if (field === "name") return; - setVisibleColumns((current) => { - const next = { - ...DEFAULT_SFTP_COLUMN_VISIBILITY, - ...current, - name: true, - [field]: !current[field], - }; - localStorageAdapter.write(STORAGE_KEY_SFTP_VISIBLE_COLUMNS, next); - return next; - }); - }, []); - - const resizingRef = useRef<{ - field: keyof ColumnWidths; - startX: number; - startWidth: number; - } | null>(null); - - const handleSort = useCallback((field: SortField) => { - if (sortField === field) { - setSortOrder((prev) => (prev === "asc" ? "desc" : "asc")); - } else { - setSortField(field); - setSortOrder("asc"); - } - }, [sortField]); - - const rafIdRef = useRef(null); - const lastClientXRef = useRef(0); - - const applyColumnWidth = useCallback(() => { - if (!resizingRef.current) return; - const { field, startX, startWidth } = resizingRef.current; - const diff = lastClientXRef.current - startX; - const limits: Record = { - name: { min: 36, max: 78 }, - modified: { min: 18, max: 42 }, - size: { min: 5, max: 16 }, - type: { min: 6, max: 18 }, - }; - const { min, max } = limits[field]; - const newWidth = Math.max( - min, - Math.min(max, startWidth + diff / 8), - ); - setColumnWidths((prev) => ({ - ...prev, - [field]: newWidth, - })); - }, []); - - const handleResizeMove = useCallback((e: MouseEvent) => { - if (!resizingRef.current) return; - lastClientXRef.current = e.clientX; - if (rafIdRef.current !== null) return; - rafIdRef.current = requestAnimationFrame(() => { - rafIdRef.current = null; - applyColumnWidth(); - }); - }, [applyColumnWidth]); - - const handleResizeEnd = useCallback(() => { - if (rafIdRef.current !== null) cancelAnimationFrame(rafIdRef.current); - applyColumnWidth(); - rafIdRef.current = null; - resizingRef.current = null; - document.removeEventListener("mousemove", handleResizeMove); - document.removeEventListener("mouseup", handleResizeEnd); - }, [applyColumnWidth, handleResizeMove]); - - const handleResizeStart = ( - field: keyof ColumnWidths, - e: React.MouseEvent, - ) => { - e.preventDefault(); - e.stopPropagation(); - lastClientXRef.current = e.clientX; - resizingRef.current = { - field, - startX: e.clientX, - startWidth: columnWidths[field], - }; - document.addEventListener("mousemove", handleResizeMove); - document.addEventListener("mouseup", handleResizeEnd); - }; - - return { - sortField, - sortOrder, - directoriesFirst, - columnWidths, - visibleColumns, - handleSort, - handleResizeStart, - toggleColumnVisibility, - toggleDirectoriesFirst, - }; -}; +/** @deprecated Import from `@/application/state/sftp/useSftpPaneSorting` instead. */ +export { + useSftpPaneSorting, + type UseSftpPaneSortingResult, +} from "../../../application/state/sftp/useSftpPaneSorting"; diff --git a/components/sftp/hooks/useSftpTreeSelectionStore.ts b/components/sftp/hooks/useSftpTreeSelectionStore.ts index 4182b342b..5f2627a8e 100644 --- a/components/sftp/hooks/useSftpTreeSelectionStore.ts +++ b/components/sftp/hooks/useSftpTreeSelectionStore.ts @@ -1,153 +1,6 @@ -import { useCallback, useSyncExternalStore } from "react"; - -export interface SftpTreeSelectionItem { - path: string; - name: string; - isDirectory: boolean; - sourcePath: string; -} - -interface SftpTreeSelectionState { - visibleItems: SftpTreeSelectionItem[]; - visibleItemsByPath: Map; - visibleIndexByPath: Map; - visiblePathsSet: Set; - selectedPaths: Set; -} - -const EMPTY_PATHS = new Set(); - -const EMPTY_STATE: SftpTreeSelectionState = { - visibleItems: [], - visibleItemsByPath: new Map(), - visibleIndexByPath: new Map(), - visiblePathsSet: new Set(), - selectedPaths: EMPTY_PATHS, -}; - -type Listener = () => void; - -const paneStates = new Map(); -const paneListeners = new Map>(); - -const notifyPaneListeners = (paneId: string) => { - paneListeners.get(paneId)?.forEach((listener) => listener()); -}; - -const getPaneState = (paneId: string): SftpTreeSelectionState => - paneStates.get(paneId) ?? EMPTY_STATE; - -const setPaneState = ( - paneId: string, - updater: (state: SftpTreeSelectionState) => SftpTreeSelectionState, -) => { - const prev = getPaneState(paneId); - const next = updater(prev); - if (next === prev) return; - if (next.visibleItems.length === 0 && next.selectedPaths.size === 0) { - paneStates.delete(paneId); - } else { - paneStates.set(paneId, next); - } - notifyPaneListeners(paneId); -}; - -export const sftpTreeSelectionStore = { - getPaneState, - - getSelectedItems: (paneId: string): SftpTreeSelectionItem[] => { - const state = getPaneState(paneId); - const result: SftpTreeSelectionItem[] = []; - for (const path of state.selectedPaths) { - const item = state.visibleItemsByPath.get(path); - if (item) result.push(item); - } - return result; - }, - - setVisibleItems: (paneId: string, visibleItems: SftpTreeSelectionItem[]) => { - const visibleItemsByPath = new Map(); - const visibleIndexByPath = new Map(); - const visiblePathsSet = new Set(visibleItems.map((item) => item.path)); - visibleItems.forEach((item, index) => { - visibleItemsByPath.set(item.path, item); - visibleIndexByPath.set(item.path, index); - }); - setPaneState(paneId, (state) => { - const newSelected = new Set([...state.selectedPaths].filter((p) => visiblePathsSet.has(p))); - const changed = - newSelected.size !== state.selectedPaths.size || - [...newSelected].some((p) => !state.selectedPaths.has(p)); - return { - visibleItems, - visibleItemsByPath, - visibleIndexByPath, - visiblePathsSet, - selectedPaths: changed ? newSelected : state.selectedPaths, - }; - }); - }, - - setSelection: (paneId: string, selectedPaths: Iterable) => { - setPaneState(paneId, (state) => ({ - ...state, - selectedPaths: new Set(Array.from(selectedPaths).filter((path) => state.visiblePathsSet.has(path))), - })); - }, - - clearSelection: (paneId: string) => { - setPaneState(paneId, (state) => ({ ...state, selectedPaths: EMPTY_PATHS })); - }, - - clearAllExcept: (paneIdsToKeep?: Iterable) => { - const keep = new Set(paneIdsToKeep ?? []); - Array.from(paneStates.keys()).forEach((paneId) => { - if (keep.has(paneId)) return; - setPaneState(paneId, (state) => { - if (state.selectedPaths.size === 0) return state; - return { ...state, selectedPaths: EMPTY_PATHS }; - }); - }); - }, - - selectAllVisible: (paneId: string) => { - setPaneState(paneId, (state) => ({ - ...state, - selectedPaths: new Set( - state.visibleItems.map((item) => item.path), - ), - })); - }, - - clearPane: (paneId: string) => { - if (!paneStates.has(paneId)) return; - paneStates.delete(paneId); - notifyPaneListeners(paneId); - }, - - subscribe: (paneId: string, listener: Listener) => { - const listeners = paneListeners.get(paneId) ?? new Set(); - listeners.add(listener); - paneListeners.set(paneId, listeners); - return () => { - const current = paneListeners.get(paneId); - if (!current) return; - current.delete(listener); - if (current.size === 0) { - paneListeners.delete(paneId); - } - }; - }, -}; - -export const useSftpTreeSelectionState = (paneId: string): SftpTreeSelectionState => { - const subscribe = useCallback( - (listener: () => void) => sftpTreeSelectionStore.subscribe(paneId, listener), - [paneId], - ); - return useSyncExternalStore( - subscribe, - () => sftpTreeSelectionStore.getPaneState(paneId), - () => sftpTreeSelectionStore.getPaneState(paneId), - ); -}; +/** @deprecated Import from `@/application/state/sftp/sftpTreeSelectionStore` instead. */ +export { + sftpTreeSelectionStore, + useSftpTreeSelectionState, + type SftpTreeSelectionItem, +} from "../../../application/state/sftp/sftpTreeSelectionStore"; diff --git a/components/sftp/utils.ts b/components/sftp/utils.ts index 9a03dba42..0763a76f9 100644 --- a/components/sftp/utils.ts +++ b/components/sftp/utils.ts @@ -24,6 +24,16 @@ import { import React from 'react'; import type { LucideIcon } from 'lucide-react'; import { SftpFileEntry } from '../../types'; +import { + formatDate as formatDateFromState, + isNavigableDirectory, +} from '../../application/state/sftp/utils'; + +export { isNavigableDirectory }; + +/** Accept undefined timestamps from file-list rows. */ +export const formatDate = (timestamp: number | undefined): string => + formatDateFromState(timestamp ?? 0); // Pre-built icon maps for O(1) lookup in getFileIcon type IconDef = [LucideIcon, string?]; @@ -199,17 +209,6 @@ export const formatTransferBytes = (bytes: number): string => { return `${size.toFixed(i === 0 ? 0 : 1)} ${units[i]}`; }; -/** - * Format date as YYYY-MM-DD hh:mm in local timezone - */ -export const formatDate = (timestamp: number | undefined): string => { - if (!timestamp) return '--'; - const date = new Date(timestamp); - if (isNaN(date.getTime())) return '--'; - const pad = (n: number) => n.toString().padStart(2, '0'); - return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`; -}; - /** * Format speed with appropriate unit */ @@ -245,40 +244,15 @@ export const getFileIcon = (entry: SftpFileEntry): React.ReactElement => { return React.createElement(FileCode, { size: 14 }); }; -// Sort configuration types -export type SortField = 'name' | 'size' | 'modified' | 'type'; -export type SortOrder = 'asc' | 'desc'; - -// Column widths type -export interface ColumnWidths { - name: number; - modified: number; - size: number; - type: number; -} - -export type SftpColumnVisibility = Record; - -export const DEFAULT_SFTP_COLUMN_VISIBILITY: SftpColumnVisibility = { - name: true, - modified: true, - size: true, - type: true, -}; - -export const normalizeSftpColumnVisibility = (value: unknown): SftpColumnVisibility => { - if (!value || typeof value !== 'object' || Array.isArray(value)) { - return DEFAULT_SFTP_COLUMN_VISIBILITY; - } - - const stored = value as Partial>; - return { - name: true, - modified: stored.modified !== false, - size: stored.size !== false, - type: stored.type !== false, - }; -}; +// Sort / column layout — owned by application/state; re-exported for UI callers. +export { + DEFAULT_SFTP_COLUMN_VISIBILITY, + normalizeSftpColumnVisibility, + type ColumnWidths, + type SftpColumnVisibility, + type SortField, + type SortOrder, +} from '../../application/state/sftp/columnLayout'; export const isSftpColumnMenuKey = (key: string, shiftKey: boolean): boolean => key === 'ContextMenu' || (key === 'F10' && shiftKey); @@ -339,14 +313,6 @@ export const sortSftpEntries = ( return sorted; }; -/** - * Check if an entry is navigable like a directory - * This includes regular directories and symlinks that point to directories - */ -export const isNavigableDirectory = (entry: SftpFileEntry): boolean => { - return entry.type === 'directory' || (entry.type === 'symlink' && entry.linkTarget === 'directory'); -}; - /** * Check if a file is hidden * - Windows: checks the `hidden` attribute (set by localFsBridge) diff --git a/components/systemManager/DockerContainersPanel.tsx b/components/systemManager/DockerContainersPanel.tsx index 06ef83117..70b3d0734 100644 --- a/components/systemManager/DockerContainersPanel.tsx +++ b/components/systemManager/DockerContainersPanel.tsx @@ -27,8 +27,8 @@ import { SystemPanelToolbar, } from './SystemPanelUi'; import { SystemPanelConfirmDialog } from './SystemPanelConfirmDialog'; -import { useAsyncRecordCache } from './hooks/useAsyncRecordCache'; -import { usePolling, useStableTranslate } from './hooks/useSystemManager'; +import { useAsyncRecordCache } from '../../application/state/systemManager/useAsyncRecordCache'; +import { usePolling, useStableTranslate } from '../../application/state/useSystemManager'; import { openInteractiveTerminal } from './openInteractiveTerminal'; import { showSystemManagerError } from './systemManagerToast'; diff --git a/components/systemManager/DockerImagesPanel.tsx b/components/systemManager/DockerImagesPanel.tsx index 1816ef684..a0fe2b1f4 100644 --- a/components/systemManager/DockerImagesPanel.tsx +++ b/components/systemManager/DockerImagesPanel.tsx @@ -23,8 +23,8 @@ import { } from './SystemPanelUi'; import { SystemPanelConfirmDialog } from './SystemPanelConfirmDialog'; import { SystemPanelPromptDialog } from './SystemPanelPromptDialog'; -import { useAsyncRecordCache } from './hooks/useAsyncRecordCache'; -import { usePolling, useStableTranslate } from './hooks/useSystemManager'; +import { useAsyncRecordCache } from '../../application/state/systemManager/useAsyncRecordCache'; +import { usePolling, useStableTranslate } from '../../application/state/useSystemManager'; import { showSystemManagerError } from './systemManagerToast'; type Backend = ReturnType; diff --git a/components/systemManager/GpuManagerTab.tsx b/components/systemManager/GpuManagerTab.tsx index fefa8dcfe..1c6c91376 100644 --- a/components/systemManager/GpuManagerTab.tsx +++ b/components/systemManager/GpuManagerTab.tsx @@ -20,7 +20,7 @@ import { SystemPanelStatusBadge, SystemPanelToolbar, } from './SystemPanelUi'; -import { usePolling, useStableTranslate } from './hooks/useSystemManager'; +import { usePolling, useStableTranslate } from '../../application/state/useSystemManager'; type Backend = ReturnType; diff --git a/components/systemManager/ProcessManagerTab.tsx b/components/systemManager/ProcessManagerTab.tsx index 49205ea8c..a76602330 100644 --- a/components/systemManager/ProcessManagerTab.tsx +++ b/components/systemManager/ProcessManagerTab.tsx @@ -33,7 +33,7 @@ import { } from './SystemPanelUi'; import { SystemPanelConfirmDialog } from './SystemPanelConfirmDialog'; import { SystemPanelPromptDialog } from './SystemPanelPromptDialog'; -import { usePolling, useStableTranslate } from './hooks/useSystemManager'; +import { usePolling, useStableTranslate } from '../../application/state/useSystemManager'; import { getCachedProcessList, setCachedProcessList, diff --git a/components/systemManager/SystemManagerSidePanel.tsx b/components/systemManager/SystemManagerSidePanel.tsx index 1caf24502..73424b6ad 100644 --- a/components/systemManager/SystemManagerSidePanel.tsx +++ b/components/systemManager/SystemManagerSidePanel.tsx @@ -18,7 +18,7 @@ import { TmuxManagerTab } from './TmuxManagerTab'; import { WorkspaceSidebarHostHeader } from '../terminalLayer/WorkspaceSidebarHostHeader'; import { TERMINAL_SIDE_PANEL_INNER_HEADER_CLASS } from '../terminalLayer/terminalSidePanelChrome'; import { SystemPanelEmpty, SystemPanelShell } from './SystemPanelUi'; -import { useSessionCapabilities } from './hooks/useSystemManager'; +import { useSessionCapabilities } from '../../application/state/useSystemManager'; const SystemPanelChecking = memo(function SystemPanelChecking({ message, diff --git a/components/systemManager/SystemOverviewTab.tsx b/components/systemManager/SystemOverviewTab.tsx index f3a0131b8..726181cdb 100644 --- a/components/systemManager/SystemOverviewTab.tsx +++ b/components/systemManager/SystemOverviewTab.tsx @@ -10,7 +10,7 @@ import React, { memo, useEffect, useMemo, useState } from 'react'; import { useI18n } from '../../application/i18n/I18nProvider'; import { aggregateMountedDiskUsage } from '../../domain/systemDiskUsage'; import { cn } from '../../lib/utils'; -import { useServerStats } from '../terminal/hooks/useServerStats'; +import { useServerStats } from '../../application/state/useServerStats'; import { ResourceBar } from './ResourceBar'; import { SystemPanelEmpty, diff --git a/components/systemManager/TmuxManagerTab.tsx b/components/systemManager/TmuxManagerTab.tsx index 768a93066..993bdad8f 100644 --- a/components/systemManager/TmuxManagerTab.tsx +++ b/components/systemManager/TmuxManagerTab.tsx @@ -17,8 +17,8 @@ import { SystemPanelShell, SystemPanelToolbar, } from './SystemPanelUi'; -import { useAsyncRecordCache } from './hooks/useAsyncRecordCache'; -import { usePolling, useStableTranslate } from './hooks/useSystemManager'; +import { useAsyncRecordCache } from '../../application/state/systemManager/useAsyncRecordCache'; +import { usePolling, useStableTranslate } from '../../application/state/useSystemManager'; import { TmuxNewSessionModal } from './TmuxNewSessionModal'; import { TmuxSessionCard } from './TmuxSessionCard'; import { useStableListOrder, mergePollListByKey } from './listStable'; diff --git a/components/systemManager/TmuxSessionCard.tsx b/components/systemManager/TmuxSessionCard.tsx index 3121174d2..f7b77f19b 100644 --- a/components/systemManager/TmuxSessionCard.tsx +++ b/components/systemManager/TmuxSessionCard.tsx @@ -10,7 +10,7 @@ import type { TmuxSessionInfo, } from '../../domain/systemManager/types'; import type { TerminalSession } from '../../types'; -import type { AsyncRecordState } from './hooks/useAsyncRecordCache'; +import type { AsyncRecordState } from '../../application/state/systemManager/useAsyncRecordCache'; import type { TmuxSessionDetails } from './TmuxManagerTab'; import { SystemPanelCollapsible, diff --git a/components/systemManager/hooks/useAsyncRecordCache.ts b/components/systemManager/hooks/useAsyncRecordCache.ts index 48e980dda..e326969a4 100644 --- a/components/systemManager/hooks/useAsyncRecordCache.ts +++ b/components/systemManager/hooks/useAsyncRecordCache.ts @@ -1,269 +1,5 @@ -import { startTransition, useCallback, useEffect, useRef, useState } from 'react'; - -export interface AsyncRecordState { - data: T | null; - loading: boolean; - error: string | null; - updatedAt: number | null; -} - -type RecordMap = Record>; - -interface UseAsyncRecordCacheOptions { - items: TItem[]; - enabled: boolean; - getKey: (item: TItem) => string; - fetchRecord: (item: TItem) => Promise; - prefetchLimit?: number; - prefetchDelayMs?: number; - staleTimeMs?: number; -} - -function delay(ms: number): Promise { - return new Promise((resolve) => window.setTimeout(resolve, ms)); -} - -function scheduleIdleTask(callback: () => void): () => void { - if (typeof window.requestIdleCallback === 'function') { - const id = window.requestIdleCallback(callback, { timeout: 1200 }); - return () => window.cancelIdleCallback(id); - } - - const id = window.setTimeout(callback, 80); - return () => window.clearTimeout(id); -} - -function normalizeRecordError(error: unknown): string { - return error instanceof Error ? error.message : String(error || 'Unknown error'); -} - -function isRecordFresh(record: AsyncRecordState | undefined, staleTimeMs: number): boolean { - if (!record || record.error || record.updatedAt === null) return false; - if (!Number.isFinite(staleTimeMs)) return true; - return Date.now() - record.updatedAt < staleTimeMs; -} - -const EMPTY_RECORDS = {}; - -export function useAsyncRecordCache({ - items, - enabled, - getKey, - fetchRecord, - prefetchLimit = 64, - prefetchDelayMs = 16, - staleTimeMs = 30_000, -}: UseAsyncRecordCacheOptions) { - const [records, setRecords] = useState>(() => EMPTY_RECORDS); - const recordsRef = useRef>(records); - const enabledRef = useRef(enabled); - const inflightRef = useRef(new Set()); - const requestVersionRef = useRef(new Map()); - const queuedForceRef = useRef(new Set()); - const loadRecordRef = useRef<( - item: TItem, - options?: { force?: boolean; urgent?: boolean }, - ) => Promise>(async () => {}); - - recordsRef.current = records; - enabledRef.current = enabled; - - const commitRecords = useCallback(( - updater: (prev: RecordMap) => RecordMap, - urgent = false, - ) => { - const apply = () => { - setRecords((prev) => { - const next = updater(prev); - recordsRef.current = next; - return next; - }); - }; - - if (urgent) { - apply(); - return; - } - - startTransition(apply); - }, []); - - const loadRecord = useCallback(async ( - item: TItem, - options?: { force?: boolean; urgent?: boolean }, - ) => { - if (!enabledRef.current) return; - const key = getKey(item); - if (!key) return; - if (inflightRef.current.has(key)) { - if (options?.force) { - queuedForceRef.current.add(key); - requestVersionRef.current.set(key, (requestVersionRef.current.get(key) ?? 0) + 1); - } - return; - } - - const existing = recordsRef.current[key]; - if (!options?.force && isRecordFresh(existing, staleTimeMs)) { - return; - } - - const requestVersion = (requestVersionRef.current.get(key) ?? 0) + 1; - requestVersionRef.current.set(key, requestVersion); - inflightRef.current.add(key); - commitRecords((prev) => ({ - ...prev, - [key]: { - data: prev[key]?.data ?? null, - loading: true, - error: null, - updatedAt: prev[key]?.updatedAt ?? null, - }, - }), options?.urgent); - - try { - const data = await fetchRecord(item); - if (requestVersionRef.current.get(key) !== requestVersion) return; - commitRecords((prev) => ({ - ...prev, - [key]: { - data, - loading: false, - error: null, - updatedAt: Date.now(), - }, - })); - } catch (error) { - if (requestVersionRef.current.get(key) !== requestVersion) return; - commitRecords((prev) => ({ - ...prev, - [key]: { - data: prev[key]?.data ?? null, - loading: false, - error: normalizeRecordError(error), - updatedAt: prev[key]?.updatedAt ?? null, - }, - })); - } finally { - inflightRef.current.delete(key); - if (queuedForceRef.current.has(key)) { - if (enabledRef.current) { - queuedForceRef.current.delete(key); - void loadRecordRef.current(item, { force: true, urgent: options?.urgent }); - } else { - commitRecords((prev) => { - const current = prev[key]; - if (!current?.loading) return prev; - return { - ...prev, - [key]: { - ...current, - loading: false, - }, - }; - }, true); - } - } - } - }, [commitRecords, fetchRecord, getKey, staleTimeMs]); - - loadRecordRef.current = loadRecord; - - useEffect(() => { - const itemKeys = new Set(items.map(getKey).filter(Boolean)); - for (const key of queuedForceRef.current) { - if (!itemKeys.has(key)) { - queuedForceRef.current.delete(key); - } - } - commitRecords((prev) => { - let changed = false; - const next: RecordMap = {}; - for (const [key, value] of Object.entries(prev) as Array<[string, AsyncRecordState]>) { - if (!itemKeys.has(key)) { - changed = true; - continue; - } - next[key] = value; - } - return changed ? next : prev; - }); - }, [commitRecords, getKey, items]); - - useEffect(() => { - if (!enabled || queuedForceRef.current.size === 0) return; - for (const item of items) { - const key = getKey(item); - if (!key || !queuedForceRef.current.has(key)) continue; - queuedForceRef.current.delete(key); - void loadRecord(item, { force: true, urgent: true }); - } - }, [enabled, getKey, items, loadRecord]); - - useEffect(() => { - if (!enabled || items.length === 0 || prefetchLimit <= 0) return undefined; - - let cancelled = false; - const candidates = items.slice(0, prefetchLimit); - const cancelIdleTask = scheduleIdleTask(() => { - void (async () => { - for (const item of candidates) { - if (cancelled) return; - await loadRecord(item); - if (prefetchDelayMs > 0) { - await delay(prefetchDelayMs); - } - } - })(); - }); - - return () => { - cancelled = true; - cancelIdleTask(); - }; - }, [enabled, items, loadRecord, prefetchDelayMs, prefetchLimit]); - - const invalidateRecord = useCallback((key: string) => { - requestVersionRef.current.set(key, (requestVersionRef.current.get(key) ?? 0) + 1); - queuedForceRef.current.delete(key); - commitRecords((prev) => { - if (!(key in prev)) return prev; - const { [key]: _removed, ...next } = prev; - return next; - }, true); - }, [commitRecords]); - - const invalidateMatching = useCallback((matches: (key: string) => boolean) => { - for (const key of requestVersionRef.current.keys()) { - if (matches(key)) { - requestVersionRef.current.set(key, (requestVersionRef.current.get(key) ?? 0) + 1); - queuedForceRef.current.delete(key); - } - } - commitRecords((prev) => { - let changed = false; - const next: RecordMap = {}; - for (const [key, value] of Object.entries(prev) as Array<[string, AsyncRecordState]>) { - if (matches(key)) { - changed = true; - continue; - } - next[key] = value; - } - return changed ? next : prev; - }, true); - }, [commitRecords]); - - const refreshRecord = useCallback( - (item: TItem) => loadRecord(item, { force: true, urgent: true }), - [loadRecord], - ); - - return { - records, - loadRecord, - refreshRecord, - invalidateRecord, - invalidateMatching, - }; -} +/** @deprecated Import from `@/application/state/systemManager/useAsyncRecordCache` instead. */ +export { + useAsyncRecordCache, + type AsyncRecordState, +} from "../../../application/state/systemManager/useAsyncRecordCache"; diff --git a/components/systemManager/hooks/useSystemManager.ts b/components/systemManager/hooks/useSystemManager.ts index 7bea4e8f7..6f5fa47ac 100644 --- a/components/systemManager/hooks/useSystemManager.ts +++ b/components/systemManager/hooks/useSystemManager.ts @@ -1,326 +1,7 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; -import { useI18n } from '../../../application/i18n/I18nProvider'; -import type { I18nContextValue } from '../../../application/i18n/I18nProvider'; -import { sessionCapabilitiesStore } from '../../../application/state/sessionCapabilitiesStore'; -import type { SessionCapabilities } from '../../../domain/systemManager/types'; -import type { useSystemManagerBackend } from '../../../application/state/useSystemManagerBackend'; -import { nextPollData } from '../listStable'; - -type Backend = ReturnType; - -function delay(ms: number): Promise { - return new Promise((resolve) => window.setTimeout(resolve, ms)); -} - -function normalizePollingErrorMessage(error: unknown, t: I18nContextValue['t']): string { - const message = error instanceof Error ? error.message : String(error || 'Unknown error'); - const lower = message.toLowerCase(); - if (lower.includes('channel open failure') || lower.includes('unable to exec')) { - return t('systemManager.errors.sshChannelUnavailable'); - } - return message; -} - -/** Stable i18n ref so polling fetchers do not reset when locale re-renders. */ -export function useStableTranslate(): I18nContextValue['t'] { - const { t } = useI18n(); - const tRef = useRef(t); - tRef.current = t; - return useCallback( - (key, values) => tRef.current(key, values), - [], - ); -} - -export function useSessionCapabilities( - sessionId: string | null, - isConnected: boolean, - backend: Backend, - enabled: boolean, - capabilitiesTtlMs: number, -) { - const ttlMsRef = useRef(capabilitiesTtlMs); - ttlMsRef.current = capabilitiesTtlMs; - - const [capabilities, setCapabilities] = useState( - () => (sessionId ? sessionCapabilitiesStore.get(sessionId) : undefined), - ); - const [probing, setProbing] = useState(false); - - useEffect(() => { - if (!sessionId) return undefined; - return sessionCapabilitiesStore.subscribe(sessionId, () => { - setCapabilities(sessionCapabilitiesStore.get(sessionId)); - }); - }, [sessionId]); - - useEffect(() => { - if (!sessionId || isConnected) return undefined; - sessionCapabilitiesStore.delete(sessionId); - return undefined; - }, [sessionId, isConnected]); - - const probe = useCallback(async (force = false) => { - if (!sessionId || !isConnected) return; - if (!force && sessionCapabilitiesStore.get(sessionId)) return; - setProbing(true); - try { - const result = await backend.probeSystemCapabilities(sessionId); - if (result.success && result.capabilities) { - sessionCapabilitiesStore.set(sessionId, result.capabilities, ttlMsRef.current); - } - } finally { - setProbing(false); - } - }, [backend, isConnected, sessionId]); - - useEffect(() => { - if (!sessionId || !isConnected || !enabled) return undefined; - void probe(); - return undefined; - }, [enabled, sessionId, isConnected, probe]); - - return { capabilities, probing, refreshCapabilities: () => probe(true) }; -} - -/** Prefetch capabilities only for the given session ids (e.g. when System panel opens). */ -export function useSystemCapabilitiesWarmup( - sessionIds: string[], - backend: Backend, - enabled: boolean, - capabilitiesTtlMs: number, -) { - const backendRef = useRef(backend); - backendRef.current = backend; - const inflightRef = useRef(new Set()); - const ttlMsRef = useRef(capabilitiesTtlMs); - ttlMsRef.current = capabilitiesTtlMs; - - const sessionKey = enabled ? sessionIds.slice().sort().join(',') : ''; - - useEffect(() => { - if (!sessionKey) return undefined; - for (const sessionId of sessionKey.split(',')) { - if (!sessionId || sessionCapabilitiesStore.get(sessionId)) continue; - if (inflightRef.current.has(sessionId)) continue; - inflightRef.current.add(sessionId); - void backendRef.current.probeSystemCapabilities(sessionId).then((result) => { - inflightRef.current.delete(sessionId); - if (result.success && result.capabilities) { - sessionCapabilitiesStore.set(sessionId, result.capabilities, ttlMsRef.current); - } - }); - } - return undefined; - }, [sessionKey]); -} - -export function usePolling( - fetcher: () => Promise, - intervalMs: number, - enabled: boolean, - merge?: (prev: T | null, next: T) => T, - options?: { poll?: boolean; resetKey?: string }, -) { - const stableT = useStableTranslate(); - const resetKey = options?.resetKey ?? ''; - const [data, setData] = useState(null); - const [dataKey, setDataKey] = useState(resetKey); - const [error, setError] = useState(null); - const [errorKey, setErrorKey] = useState(resetKey); - const [loading, setLoading] = useState(false); - const [loadingKey, setLoadingKey] = useState(resetKey); - const failuresRef = useRef(0); - const hasDataRef = useRef(false); - const enabledRef = useRef(enabled); - const generationRef = useRef(0); - const runIdRef = useRef(0); - const loadingRunIdRef = useRef(0); - const inflightRef = useRef<{ generation: number; runId: number } | null>(null); - const queuedRunRef = useRef<{ - options?: { withLoading?: boolean; minLoadingMs?: number }; - resolve: () => void; - } | null>(null); - const fetcherRef = useRef(fetcher); - const mergeRef = useRef(merge); - const pollRef = useRef(options?.poll ?? true); - const resetKeyRef = useRef(resetKey); - const timerRef = useRef | null>(null); - - enabledRef.current = enabled; - fetcherRef.current = fetcher; - mergeRef.current = merge; - pollRef.current = options?.poll ?? true; - - const clearPollTimer = useCallback(() => { - if (timerRef.current !== null) { - clearTimeout(timerRef.current); - timerRef.current = null; - } - }, []); - - const pollDelayMs = useCallback(() => { - if (failuresRef.current >= 3) return intervalMs * 4; - return intervalMs; - }, [intervalMs]); - - const resolveQueuedRun = useCallback(() => { - queuedRunRef.current?.resolve(); - queuedRunRef.current = null; - }, []); - - const run = useCallback(async (options?: { withLoading?: boolean; minLoadingMs?: number }) => { - const generation = generationRef.current; - const runResetKey = resetKeyRef.current; - if (!enabledRef.current) return; - if (inflightRef.current?.generation === generation) { - if (options?.withLoading) { - queuedRunRef.current?.resolve(); - loadingRunIdRef.current = 0; - setLoadingKey(runResetKey); - setLoading(true); - return new Promise((resolve) => { - queuedRunRef.current = { options, resolve }; - }); - } - return; - } - const runId = ++runIdRef.current; - inflightRef.current = { generation, runId }; - const showLoading = options?.withLoading ?? !hasDataRef.current; - const startedAt = Date.now(); - const isCurrent = () => ( - generationRef.current === generation - && enabledRef.current - && inflightRef.current?.runId === runId - && resetKeyRef.current === runResetKey - ); - if (showLoading) { - loadingRunIdRef.current = runId; - setLoadingKey(runResetKey); - setLoading(true); - } - try { - const result = await fetcherRef.current(); - if (!isCurrent()) return; - if (result !== null) { - setDataKey(runResetKey); - setData((prev) => { - const mergeFn = mergeRef.current; - const next = mergeFn ? mergeFn(prev, result) : nextPollData(prev, result); - if (next !== prev) hasDataRef.current = true; - return next; - }); - setErrorKey(runResetKey); - setError(null); - failuresRef.current = 0; - } - } catch (err) { - if (!isCurrent()) return; - failuresRef.current += 1; - setDataKey(runResetKey); - setData(null); - hasDataRef.current = false; - setErrorKey(runResetKey); - setError(normalizePollingErrorMessage(err, stableT)); - } finally { - if (inflightRef.current?.runId === runId) { - inflightRef.current = null; - } - if (showLoading) { - const remaining = Math.max(0, (options?.minLoadingMs ?? 0) - (Date.now() - startedAt)); - if (remaining > 0) await delay(remaining); - if ( - generationRef.current === generation - && enabledRef.current - && resetKeyRef.current === runResetKey - && loadingRunIdRef.current === runId - ) { - loadingRunIdRef.current = 0; - setLoadingKey(runResetKey); - setLoading(false); - } - } - const queued = queuedRunRef.current; - if ( - queued - && generationRef.current === generation - && enabledRef.current - && resetKeyRef.current === runResetKey - ) { - queuedRunRef.current = null; - await run(queued.options); - queued.resolve(); - } - } - }, [stableT]); - - const scheduleNextPoll = useCallback(() => { - clearPollTimer(); - if (!enabledRef.current || !pollRef.current) return; - const generation = generationRef.current; - timerRef.current = setTimeout(() => { - void run({ withLoading: false }).finally(() => { - if (generationRef.current === generation) { - scheduleNextPoll(); - } - }); - }, pollDelayMs()); - }, [clearPollTimer, pollDelayMs, run]); - - useEffect(() => { - const resetChanged = resetKeyRef.current !== resetKey; - resetKeyRef.current = resetKey; - generationRef.current += 1; - inflightRef.current = null; - clearPollTimer(); - if (!enabled) { - resolveQueuedRun(); - loadingRunIdRef.current = 0; - setLoading(false); - setLoadingKey(resetKey); - setDataKey(resetKey); - setData(null); - setErrorKey(resetKey); - setError(null); - failuresRef.current = 0; - hasDataRef.current = false; - return undefined; - } - if (resetChanged) { - resolveQueuedRun(); - loadingRunIdRef.current = 0; - setLoading(false); - setLoadingKey(resetKey); - setDataKey(resetKey); - setData(null); - setErrorKey(resetKey); - setError(null); - failuresRef.current = 0; - hasDataRef.current = false; - } - const generation = generationRef.current; - void run({ withLoading: true }).finally(() => { - if (generationRef.current === generation && pollRef.current) scheduleNextPoll(); - }); - return () => { - generationRef.current += 1; - resolveQueuedRun(); - loadingRunIdRef.current = 0; - inflightRef.current = null; - clearPollTimer(); - }; - }, [clearPollTimer, enabled, intervalMs, options?.poll, resetKey, resolveQueuedRun, run, scheduleNextPoll]); - - const refresh = useCallback(async () => { - failuresRef.current = 0; - await run({ withLoading: true, minLoadingMs: 450 }); - }, [run]); - - return { - data: dataKey === resetKey ? data : null, - error: errorKey === resetKey ? error : null, - loading: loadingKey === resetKey ? loading : enabled, - refresh, - }; -} +/** @deprecated Import from `@/application/state/useSystemManager` instead. */ +export { + useStableTranslate, + useSessionCapabilities, + useSystemCapabilitiesWarmup, + usePolling, +} from "../../../application/state/useSystemManager"; diff --git a/components/systemManager/listStable.ts b/components/systemManager/listStable.ts index 1a1d0284c..bbd4a0c84 100644 --- a/components/systemManager/listStable.ts +++ b/components/systemManager/listStable.ts @@ -1,55 +1,9 @@ import { useMemo, useRef } from 'react'; -function pollSnapshotEqual(prev: T | null, next: T): boolean { - if (prev === next) return true; - if (prev === null) return false; - try { - return JSON.stringify(prev) === JSON.stringify(next); - } catch { - return false; - } -} - -function itemSnapshotEqual(a: T, b: T): boolean { - if (a === b) return true; - try { - return JSON.stringify(a) === JSON.stringify(b); - } catch { - return false; - } -} - -/** Skip React state updates when polled payload is unchanged. */ -export function nextPollData(prev: T | null, next: T): T { - return pollSnapshotEqual(prev, next) ? prev as T : next; -} - -/** - * Merge polled list rows by key, reusing previous item references when unchanged. - * Keeps React.memo row components from re-rendering when other rows update. - */ -export function mergePollListByKey( - prev: T[] | null, - next: T[], - getKey: (item: T) => K, - isEqual: (a: T, b: T) => boolean = itemSnapshotEqual, -): T[] { - if (prev === null) return next; - if (prev.length !== next.length) return next; - - const nextByKey = new Map(next.map((item) => [getKey(item), item])); - if (prev.some((item) => !nextByKey.has(getKey(item)))) return next; - if (next.some((item) => !prev.some((p) => getKey(p) === getKey(item)))) return next; - - let changed = false; - const merged = prev.map((oldItem) => { - const newItem = nextByKey.get(getKey(oldItem))!; - if (isEqual(oldItem, newItem)) return oldItem; - changed = true; - return newItem; - }); - return changed ? merged : prev; -} +export { + mergePollListByKey, + nextPollData, +} from '../../domain/systemManager/pollListStable'; /** * Keep list row order stable across poll refreshes. diff --git a/components/terminal/HostKeywordHighlightPopover.tsx b/components/terminal/HostKeywordHighlightPopover.tsx index 2761ee664..11adffece 100644 --- a/components/terminal/HostKeywordHighlightPopover.tsx +++ b/components/terminal/HostKeywordHighlightPopover.tsx @@ -4,7 +4,6 @@ */ import { Highlighter, Plus, Trash2, RotateCcw } from 'lucide-react'; import React, { useState, useCallback, useMemo } from 'react'; -import { v4 as uuidv4 } from 'uuid'; import { useI18n } from '../../application/i18n/I18nProvider'; import { Host, KeywordHighlightRule } from '../../types'; import { Button } from '../ui/button'; @@ -77,7 +76,7 @@ export const HostKeywordHighlightPopover: React.FC void; - -interface SharedServerStatsSession { - sessionId: string; - state: ServerStatsState; - listeners: Set; - clients: Map; - intervalRef: ReturnType | null; - initialTimerRef: ReturnType | null; - connectedAt: number; - hasFetched: boolean; - fetchGeneration: number; - consecutiveFailures: number; - givenUp: boolean; - pollIntervalMs: number | null; - pollingActive: boolean; - inflight: Promise | null; - inflightGeneration: number | null; -} - -const CONSECUTIVE_FAILURE_LIMIT = 3; -const serverStatsSessions = new Map(); -let nextClientId = 1; - -function createEmptyServerStats(): ServerStats { - return { - hostname: undefined, - osName: undefined, - kernelRelease: undefined, - uptimeSeconds: null, - loadAverage: [], - cpu: null, - cpuCores: null, - cpuPerCore: [], - memTotal: null, - memUsed: null, - memFree: null, - memBuffers: null, - memCached: null, - swapTotal: null, - swapUsed: null, - topProcesses: [], - diskPercent: null, - diskUsed: null, - diskTotal: null, - disks: [], - netRxSpeed: 0, - netTxSpeed: 0, - latencyMs: null, - netInterfaces: [], - lastUpdated: null, - }; -} - -function createInitialState(): ServerStatsState { - return { - stats: createEmptyServerStats(), - isLoading: false, - error: null, - }; -} - -function getSharedServerStatsSession(sessionId: string): SharedServerStatsSession { - const existing = serverStatsSessions.get(sessionId); - if (existing) return existing; - - const session: SharedServerStatsSession = { - sessionId, - state: createInitialState(), - listeners: new Set(), - clients: new Map(), - intervalRef: null, - initialTimerRef: null, - connectedAt: 0, - hasFetched: false, - fetchGeneration: 0, - consecutiveFailures: 0, - givenUp: false, - pollIntervalMs: null, - pollingActive: false, - inflight: null, - inflightGeneration: null, - }; - serverStatsSessions.set(sessionId, session); - return session; -} - -function emitServerStatsState(session: SharedServerStatsSession): void { - for (const listener of session.listeners) { - listener(session.state); - } -} - -function updateServerStatsState(session: SharedServerStatsSession, patch: Partial): void { - session.state = { ...session.state, ...patch }; - emitServerStatsState(session); -} - -function clearServerStatsTimers(session: SharedServerStatsSession): void { - if (session.initialTimerRef) { - clearTimeout(session.initialTimerRef); - session.initialTimerRef = null; - } - if (session.intervalRef) { - clearInterval(session.intervalRef); - session.intervalRef = null; - } - session.pollingActive = false; - session.pollIntervalMs = null; -} - -function resetServerStatsSession(session: SharedServerStatsSession): void { - clearServerStatsTimers(session); - session.connectedAt = 0; - session.hasFetched = false; - session.fetchGeneration += 1; - session.consecutiveFailures = 0; - session.givenUp = false; - updateServerStatsState(session, createInitialState()); -} - -function getActiveServerStatsClients(session: SharedServerStatsSession): ServerStatsClient[] { - return Array.from(session.clients.values()).filter((client) => ( - client.enabled && client.isSupportedOs && client.isConnected - )); -} - -function normalizeServerStats(stats: Partial): ServerStats { - return { - hostname: stats.hostname, - osName: stats.osName, - kernelRelease: stats.kernelRelease, - uptimeSeconds: Number.isFinite(stats.uptimeSeconds) ? Number(stats.uptimeSeconds) : null, - loadAverage: Array.isArray(stats.loadAverage) ? stats.loadAverage : [], - cpu: stats.cpu ?? null, - cpuCores: stats.cpuCores ?? null, - cpuPerCore: stats.cpuPerCore || [], - memTotal: stats.memTotal ?? null, - memUsed: stats.memUsed ?? null, - memFree: stats.memFree ?? null, - memBuffers: stats.memBuffers ?? null, - memCached: stats.memCached ?? null, - swapTotal: stats.swapTotal ?? null, - swapUsed: stats.swapUsed ?? null, - topProcesses: stats.topProcesses || [], - diskPercent: stats.diskPercent ?? null, - diskUsed: stats.diskUsed ?? null, - diskTotal: stats.diskTotal ?? null, - disks: stats.disks || [], - netRxSpeed: stats.netRxSpeed || 0, - netTxSpeed: stats.netTxSpeed || 0, - latencyMs: Number.isFinite(stats.latencyMs) ? Number(stats.latencyMs) : null, - netInterfaces: stats.netInterfaces || [], - lastUpdated: Date.now(), - }; -} - -function markServerStatsFailure(session: SharedServerStatsSession, message: string): void { - session.consecutiveFailures += 1; - updateServerStatsState(session, { error: message }); - if (session.consecutiveFailures >= CONSECUTIVE_FAILURE_LIMIT) { - // Stop polling this session. This covers network devices that advertise - // OpenSSH but do not support the POSIX stats shell command. - session.givenUp = true; - clearServerStatsTimers(session); - } -} - -async function fetchSharedServerStats(session: SharedServerStatsSession, force = false): Promise { - if (!session.sessionId) return; - if (session.inflight && session.inflightGeneration === session.fetchGeneration) { - await session.inflight; - return; - } - if (session.givenUp && !force) return; - if (getActiveServerStatsClients(session).length === 0) return; - - const bridge = netcattyBridge.get(); - if (!bridge?.getServerStats) return; - - if (force) { - session.givenUp = false; - session.consecutiveFailures = 0; - } - - const generation = session.fetchGeneration; - session.inflightGeneration = generation; - updateServerStatsState(session, { isLoading: true, error: null }); - - const request = (async () => { - try { - const result = await bridge.getServerStats(session.sessionId); - - // Discard stale responses from before a polling restart or reconnect. - if (generation !== session.fetchGeneration) return; - - if (result.pending) { - // Transient "not ready yet", e.g. a Mosh session whose SSH handshake - // has not finished. Do not count this toward the hard-failure cutoff. - return; - } - - if (result.success && result.stats) { - session.hasFetched = true; - session.consecutiveFailures = 0; - updateServerStatsState(session, { - stats: normalizeServerStats(result.stats), - error: null, - }); - } else if (result.error) { - markServerStatsFailure(session, result.error); - } else { - markServerStatsFailure(session, 'No stats returned'); - } - } catch (err) { - if (generation === session.fetchGeneration) { - markServerStatsFailure(session, err instanceof Error ? err.message : 'Unknown error'); - } - } finally { - if (generation === session.fetchGeneration) { - updateServerStatsState(session, { isLoading: false }); - } - } - })(); - - session.inflight = request; - try { - await request; - } finally { - if (session.inflight === request) { - session.inflight = null; - session.inflightGeneration = null; - } - } -} - -function reconcileSharedServerStatsSession(session: SharedServerStatsSession): void { - const activeClients = getActiveServerStatsClients(session); - - if (activeClients.length === 0) { - resetServerStatsSession(session); - return; - } - - if (session.connectedAt === 0) { - session.connectedAt = Date.now(); - } - - const intervalMs = Math.max(5, Math.min(...activeClients.map((client) => client.refreshInterval))) * 1000; - const shouldRestartPolling = !session.pollingActive || session.pollIntervalMs !== intervalMs; - if (!shouldRestartPolling) return; - if (session.givenUp) return; - - clearServerStatsTimers(session); - session.fetchGeneration += 1; - session.pollingActive = true; - session.pollIntervalMs = intervalMs; - - const connectionAge = Date.now() - session.connectedAt; - const needsWarmup = !session.hasFetched && connectionAge < 2000; - - session.initialTimerRef = setTimeout(() => { - session.initialTimerRef = null; - void fetchSharedServerStats(session); - }, needsWarmup ? 2000 : 0); - session.intervalRef = setInterval(() => { - void fetchSharedServerStats(session); - }, intervalMs); -} - -function maybeDisposeSharedServerStatsSession(session: SharedServerStatsSession): void { - if (session.clients.size > 0 || session.listeners.size > 0) return; - clearServerStatsTimers(session); - session.fetchGeneration += 1; - serverStatsSessions.delete(session.sessionId); -} - -export function useServerStats({ - sessionId, - enabled, - refreshInterval, - isSupportedOs, - isConnected, -}: UseServerStatsOptions) { - const clientIdRef = useRef(null); - if (clientIdRef.current === null) { - clientIdRef.current = nextClientId; - nextClientId += 1; - } - - const [state, setState] = useState(() => getSharedServerStatsSession(sessionId).state); - - useEffect(() => { - const session = getSharedServerStatsSession(sessionId); - const clientId = clientIdRef.current; - if (clientId === null) return; - - const listener: ServerStatsListener = (nextState) => { - setState(nextState); - }; - - session.listeners.add(listener); - setState(session.state); - - return () => { - session.listeners.delete(listener); - session.clients.delete(clientId); - reconcileSharedServerStatsSession(session); - maybeDisposeSharedServerStatsSession(session); - }; - }, [sessionId]); - - useEffect(() => { - const session = getSharedServerStatsSession(sessionId); - const clientId = clientIdRef.current; - if (clientId === null) return; - - session.clients.set(clientId, { - enabled, - refreshInterval, - isSupportedOs, - isConnected, - }); - setState(session.state); - reconcileSharedServerStatsSession(session); - }, [sessionId, enabled, refreshInterval, isSupportedOs, isConnected]); - - const refresh = useCallback(() => { - const session = getSharedServerStatsSession(sessionId); - void fetchSharedServerStats(session, true).finally(() => { - reconcileSharedServerStatsSession(session); - }); - }, [sessionId]); - - return { - stats: state.stats, - isLoading: state.isLoading, - error: state.error, - refresh, - }; -} +/** @deprecated Import from `@/application/state/useServerStats` instead. */ +export { + useServerStats, + type DiskInfo, + type NetInterfaceInfo, + type ProcessInfo, + type ServerStats, +} from "../../../application/state/useServerStats"; diff --git a/components/terminal/hostKeyVerification.ts b/components/terminal/hostKeyVerification.ts index 4e71ac733..09b6632a6 100644 --- a/components/terminal/hostKeyVerification.ts +++ b/components/terminal/hostKeyVerification.ts @@ -1,39 +1,17 @@ import type { Host, KnownHost } from "../../types"; -import type { HostKeyInfo } from "./TerminalHostKeyVerification"; +import type { HostKeyInfo } from "../../domain/hostKey"; +import { createKnownHostFromHostKeyInfo as createKnownHostFromHostKeyInfoDomain } from "../../domain/knownHosts"; -export type HostKeyVerificationRequest = { - hostname: string; - port?: number; - keyType: string; - fingerprint: string; - publicKey?: string; - status?: "unknown" | "changed"; - knownHostId?: string; - knownFingerprint?: string; -}; - -export const toHostKeyInfo = (request: HostKeyVerificationRequest): HostKeyInfo => ({ - hostname: request.hostname, - port: request.port, - keyType: request.keyType, - fingerprint: request.fingerprint, - publicKey: request.publicKey, - status: request.status, - knownHostId: request.knownHostId, - knownFingerprint: request.knownFingerprint, -}); +export type { HostKeyInfo, HostKeyVerificationRequest } from "../../domain/hostKey"; +export { toHostKeyInfo } from "../../domain/hostKey"; export const createKnownHostFromHostKeyInfo = ( hostKeyInfo: HostKeyInfo, host: Pick, now = Date.now(), idSuffix = Math.random().toString(36).slice(2, 11), -): KnownHost => ({ - id: hostKeyInfo.knownHostId || `kh-${now}-${idSuffix}`, - hostname: hostKeyInfo.hostname, - port: hostKeyInfo.port || host.port || 22, - keyType: hostKeyInfo.keyType, - publicKey: hostKeyInfo.publicKey || `SHA256:${hostKeyInfo.fingerprint}`, - fingerprint: hostKeyInfo.fingerprint, - discoveredAt: now, +): KnownHost => createKnownHostFromHostKeyInfoDomain(hostKeyInfo, { + defaultPort: host.port, + now, + idSuffix, }); diff --git a/components/terminal/runtime/terminalLineTimestamps.ts b/components/terminal/runtime/terminalLineTimestamps.ts index 09df93ba9..8cc9195ef 100644 --- a/components/terminal/runtime/terminalLineTimestamps.ts +++ b/components/terminal/runtime/terminalLineTimestamps.ts @@ -971,9 +971,6 @@ const resolveLastPaintBufferLine = ( export const getTerminalLineTimestampLedgerCount = (term: XTerm): number => getTimestampStore(term).ledger.length; -/** @deprecated No-op; paint reads the ledger directly. */ -export const materializeTimestampLedgerToMarkers = (_term: XTerm): number => 0; - const internTerminalLineTimestampLabel = ( store: TimestampStore, date: Date, diff --git a/components/terminal/terminalMemo.ts b/components/terminal/terminalMemo.ts index 8185f9240..852c77395 100644 --- a/components/terminal/terminalMemo.ts +++ b/components/terminal/terminalMemo.ts @@ -31,8 +31,7 @@ export const terminalPropsAreEqual = ( && prev.fontFamilyId === next.fontFamilyId && prev.fontSize === next.fontSize && prev.followAppTerminalTheme === next.followAppTerminalTheme - && prev.accentMode === next.accentMode - && prev.customAccent === next.customAccent + // accentMode / customAccent intentionally omitted — Terminal reads appearanceChromeStore. && prev.terminalSettings === next.terminalSettings && prev.sessionId === next.sessionId && prev.restoreState === next.restoreState diff --git a/components/terminal/useServerStats.test.ts b/components/terminal/useServerStats.test.ts index ba952f616..4a8d11d59 100644 --- a/components/terminal/useServerStats.test.ts +++ b/components/terminal/useServerStats.test.ts @@ -3,7 +3,7 @@ import { readFileSync } from "node:fs"; import test from "node:test"; test("server stats retry can restart polling after give-up", () => { - const source = readFileSync(new URL("./hooks/useServerStats.ts", import.meta.url), "utf8"); + const source = readFileSync(new URL("../../application/state/useServerStats.ts", import.meta.url), "utf8"); const reconcileStart = source.indexOf("function reconcileSharedServerStatsSession"); const shouldRestartCheck = source.indexOf("const shouldRestartPolling", reconcileStart); const givenUpCheck = source.indexOf("if (session.givenUp) return;", shouldRestartCheck); @@ -17,7 +17,7 @@ test("server stats retry can restart polling after give-up", () => { }); test("server stats stale requests do not block a fresh visible fetch", () => { - const source = readFileSync(new URL("./hooks/useServerStats.ts", import.meta.url), "utf8"); + const source = readFileSync(new URL("../../application/state/useServerStats.ts", import.meta.url), "utf8"); assert.match(source, /inflightGeneration: number \| null/); assert.match(source, /session\.inflight && session\.inflightGeneration === session\.fetchGeneration/); @@ -25,7 +25,7 @@ test("server stats stale requests do not block a fresh visible fetch", () => { }); test("server stats polling does not stop when its terminal is in the background", () => { - const source = readFileSync(new URL("./hooks/useServerStats.ts", import.meta.url), "utf8"); + const source = readFileSync(new URL("../../application/state/useServerStats.ts", import.meta.url), "utf8"); assert.doesNotMatch(source, /isVisible/); assert.doesNotMatch(source, /getVisibleServerStatsClients/); diff --git a/components/terminalLayer/TerminalLayerSupport.tsx b/components/terminalLayer/TerminalLayerSupport.tsx index fdc507ad2..97e58671a 100644 --- a/components/terminalLayer/TerminalLayerSupport.tsx +++ b/components/terminalLayer/TerminalLayerSupport.tsx @@ -12,9 +12,13 @@ import { getTopTabInsertionTarget, isPointInsideRect, WORKSPACE_SESSION_DRAG_TYP import { useAIState } from '../../application/state/useAIState'; import { useStoredBoolean } from '../../application/state/useStoredBoolean'; import { isSavedVaultHost } from '../../domain/ephemeralHosts'; -import { buildAITerminalSessionInfo, type AITerminalSessionInfo } from './buildAITerminalSessionInfo'; +import { + buildAITerminalSessionInfo, + type AIPanelContext, + type AITerminalSessionInfo, +} from '../../domain/buildAITerminalSessionInfo'; export { buildAITerminalSessionInfo }; -export type { AITerminalSessionInfo }; +export type { AIPanelContext, AITerminalSessionInfo }; import { collectSessionIds, SplitDirection } from '../../domain/workspace'; import { resolveSessionTabTitle } from '../../domain/sessionTabTitle'; import { terminalPaneSessionsEqual } from '../../domain/terminalPaneSessionsEqual'; @@ -238,14 +242,6 @@ export const filterTabsMap = (source: Map, validIds: Set) export { ChunkedEscapeFilter, hasNotifiableTerminalOutput } from './activityEscapeFilter'; -export type AIPanelContext = { - scopeType: 'terminal' | 'workspace'; - scopeTargetId?: string; - scopeHostIds: string[]; - scopeLabel: string; - terminalSessions: AITerminalSessionInfo[]; -}; - type AIStateValue = ReturnType; const AIStateContext = createContext(null); @@ -511,8 +507,6 @@ export interface TerminalLayerProps { identities: Identity[]; snippets: Snippet[]; snippetPackages: string[]; - notes: VaultNote[]; - noteGroups: string[]; openNoteRequest?: { tabId: string; noteId: string; requestId: number } | null; onOpenVaultNoteFromChat?: (noteId: string) => void; onOpenVaultHostFromChat?: (hostId: string) => void; @@ -581,8 +575,6 @@ export interface TerminalLayerProps { updateHosts: (hosts: Host[]) => void; updateSnippets?: (snippets: Snippet[]) => void; updateSnippetPackages?: (packages: string[]) => void; - updateNotes: (notes: VaultNote[]) => void; - updateNoteGroups: (groups: string[]) => void; sftpDefaultViewMode: 'list' | 'tree'; sftpDoubleClickBehavior: 'open' | 'transfer'; sftpAutoSync: boolean; @@ -761,8 +753,7 @@ const terminalPanePropsAreEqual = ( prev.fontSize === next.fontSize && prev.terminalTheme === next.terminalTheme && prev.followAppTerminalTheme === next.followAppTerminalTheme && - prev.accentMode === next.accentMode && - prev.customAccent === next.customAccent && + // accentMode / customAccent intentionally omitted — Terminal reads appearanceChromeStore. prev.terminalSettings === next.terminalSettings && prev.hotkeyScheme === next.hotkeyScheme && prev.disableTerminalFontZoom === next.disableTerminalFontZoom && @@ -1534,8 +1525,7 @@ const terminalPanesHostPropsAreEqual = ( if (prev.fontSize !== next.fontSize) return false; if (prev.terminalTheme !== next.terminalTheme) return false; if (prev.followAppTerminalTheme !== next.followAppTerminalTheme) return false; - if (prev.accentMode !== next.accentMode) return false; - if (prev.customAccent !== next.customAccent) return false; + // accentMode / customAccent intentionally omitted — Terminal reads appearanceChromeStore. if (prev.terminalSettings !== next.terminalSettings) return false; if (prev.hotkeyScheme !== next.hotkeyScheme) return false; if (prev.disableTerminalFontZoom !== next.disableTerminalFontZoom) return false; diff --git a/components/terminalLayer/TerminalLayerTabBridge.tsx b/components/terminalLayer/TerminalLayerTabBridge.tsx index 87a0c5391..7f135bd73 100644 --- a/components/terminalLayer/TerminalLayerTabBridge.tsx +++ b/components/terminalLayer/TerminalLayerTabBridge.tsx @@ -7,13 +7,13 @@ import { useSystemManagerBackend } from '../../application/state/useSystemManage import { canReuseTerminalConnection } from '../../application/state/terminalConnectionReuse'; import { resolveSystemSidebarSession } from '../../domain/systemManager/resolveSystemSession'; import type { TerminalContextReader } from '../../domain/terminalContextRead'; -import { useSystemCapabilitiesWarmup } from '../systemManager/hooks/useSystemManager'; +import { useSystemCapabilitiesWarmup } from '../../application/state/useSystemManager'; import { cn } from '../../lib/utils'; import type { Host, TerminalSession, Workspace } from '../../types'; import { resolveTerminalHibernateEnabled } from '../../domain/terminalHibernate'; import { shouldMeasureTerminalLayerLayout } from '../terminalPaneVisibility'; import { TerminalLayerView } from './TerminalLayerView'; -import { useTerminalAiContexts } from './useTerminalAiContexts'; +import { useTerminalAiContexts } from '../../application/state/useTerminalAiContexts'; import { useTerminalLayerEffects } from './useTerminalLayerEffects'; import { useTerminalThemePanelState } from './useTerminalThemePanelState'; import { useManualTerminalChromeSurfaceInjection } from '../../application/state/useManualTerminalChromeSurfaceInjection'; @@ -215,11 +215,9 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef }) }, [historySessionId, sessionHostsMap]); const themeState = useTerminalThemePanelState({ - accentMode: s.accentMode, activeSession, activeSidePanelTab: activeSidePanelTools.has('theme') ? 'theme' : activeSidePanelTab, activeWorkspace, - customAccent: s.customAccent, followAppTerminalTheme: s.followAppTerminalTheme, focusedSessionId, fontSize: s.fontSize, @@ -523,8 +521,6 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef }) notesMountedTabIds: s.notesMountedTabIds, notesOpenNoteByTab: s.notesOpenNoteByTab, NotesManager: s.NotesManager, - noteGroups: s.noteGroups, - notes: s.notes, scriptsMountedTabIds: s.scriptsMountedTabIds, systemMountedTabIds: s.systemMountedTabIds, themeMountedTabIds: s.themeMountedTabIds, @@ -595,8 +591,6 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef }) snippets: s.snippets, updateSnippetPackages: s.updateSnippetPackages, updateSnippets: s.updateSnippets, - updateNoteGroups: s.updateNoteGroups, - updateNotes: s.updateNotes, splitHorizontalHandlersRef: s.splitHorizontalHandlersRef, splitVerticalHandlersRef: s.splitVerticalHandlersRef, sshDebugLogsEnabled: s.sshDebugLogsEnabled, @@ -641,8 +635,6 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef }) focusedHost, focusedSessionId, s.restoreTerminalCwd, - s.notes, - s.noteGroups, handleWorkspaceDrop, handleTerminalContextReaderChange, hibernateHiddenTabs, diff --git a/components/terminalLayer/terminalLayerSidePanelSlots.tsx b/components/terminalLayer/terminalLayerSidePanelSlots.tsx index 036c0838a..579db6d03 100644 --- a/components/terminalLayer/terminalLayerSidePanelSlots.tsx +++ b/components/terminalLayer/terminalLayerSidePanelSlots.tsx @@ -8,6 +8,13 @@ import { getSidePanelLiveSnapshot, subscribeSidePanelLiveSnapshot, } from '../../application/state/sidePanelLiveStore'; +import { + getEmptyNotesSnapshot, + getNotesSnapshot, + subscribeNotes, + subscribeNotesNoop, + useNotesStore, +} from '../../application/state/notesStore'; import { getShellHistorySnapshot, subscribeShellHistory, @@ -399,14 +406,16 @@ function SidePanelNotesSlotInner({ isVisible: boolean; }) { const openNoteRequest = (ctx.notesOpenNoteByTab as Map).get(tabId) ?? null; + const { + notes, + noteGroups, + updateNotes, + updateNoteGroups, + } = useNotesStore(); const { NotesManager, - notes, - noteGroups, hosts, - updateNotes, - updateNoteGroups, handleOpenHostFromNotes, } = ctx; @@ -423,6 +432,7 @@ function SidePanelNotesSlotInner({ onUpdateNoteGroups={updateNoteGroups} onOpenHost={handleOpenHostFromNotes} displayMode="sidebar" + isActive={isVisible} openNoteId={openNoteRequest?.noteId ?? null} openNoteRequestId={openNoteRequest?.requestId ?? null} /> @@ -499,7 +509,6 @@ function SidePanelAiSlotInner({ resolveAIExecutorContext, pendingTerminalSelectionForAI, handlePendingTerminalSelectionConsumed, - notes, hosts, snippets, onOpenVaultNoteFromChat, @@ -509,6 +518,14 @@ function SidePanelAiSlotInner({ validAIScopeTargetIds, } = ctx; + // Gate notes subscription while AI is hidden so note edits do not re-render + // retained AI mounts (panel still mounts for fast reopen). + const notesSnapshot = useSyncExternalStore( + isVisible ? subscribeNotes : subscribeNotesNoop, + isVisible ? getNotesSnapshot : getEmptyNotesSnapshot, + isVisible ? getNotesSnapshot : getEmptyNotesSnapshot, + ); + if (mountedAiTabIds.length === 0) return null; const activeLayout = activeTabId ? (ctx.sidePanelLayouts as Map).get(activeTabId) @@ -522,6 +539,9 @@ function SidePanelAiSlotInner({ // Only the visible AI panel needs vault catalogs for artifact navigation. // Hidden retained panels keep session state without re-binding huge hosts/notes. const injectVaultCatalog = isVisible; + const notes = injectVaultCatalog + ? (notesSnapshot.notes as import('../../domain/models').VaultNote[]) + : EMPTY_VAULT_NOTES; return ( @@ -533,7 +553,7 @@ function SidePanelAiSlotInner({ resolveExecutorContext={resolveAIExecutorContext} pendingTerminalSelection={pendingTerminalSelectionForAI} onPendingTerminalSelectionConsumed={handlePendingTerminalSelectionConsumed} - notes={injectVaultCatalog ? notes : EMPTY_VAULT_NOTES} + notes={notes} hosts={injectVaultCatalog ? hosts : EMPTY_VAULT_HOSTS} snippets={injectVaultCatalog ? snippets : EMPTY_VAULT_SNIPPETS} onOpenVaultNoteFromChat={onOpenVaultNoteFromChat} diff --git a/components/terminalLayer/terminalLayerViewMemo.ts b/components/terminalLayer/terminalLayerViewMemo.ts index aa4549d89..c1a631a25 100644 --- a/components/terminalLayer/terminalLayerViewMemo.ts +++ b/components/terminalLayer/terminalLayerViewMemo.ts @@ -320,10 +320,7 @@ const SIDE_PANEL_STABLE_CTX_KEYS = [ 'validAIScopeTargetIds', 'AISidePanelStateRoot', 'NotesManager', - 'notes', - 'noteGroups', - 'updateNotes', - 'updateNoteGroups', + // notes / noteGroups / updateNotes / updateNoteGroups come from notesStore. 'onOpenVaultNoteFromChat', 'onOpenVaultHostFromChat', 'onOpenVaultSectionFromChat', @@ -362,8 +359,7 @@ const WORKSPACE_CTX_KEYS = [ 'fontSize', 'terminalTheme', 'followAppTerminalTheme', - 'accentMode', - 'customAccent', + // accentMode / customAccent come from appearanceChromeStore (Terminal leaf). 'terminalSettings', 'hotkeyScheme', 'disableTerminalFontZoom', diff --git a/components/terminalLayer/useTerminalAiContexts.ts b/components/terminalLayer/useTerminalAiContexts.ts index a5cb0af4f..7dde9e33a 100644 --- a/components/terminalLayer/useTerminalAiContexts.ts +++ b/components/terminalLayer/useTerminalAiContexts.ts @@ -1,143 +1,2 @@ -import type React from 'react'; -import { useCallback, useMemo, useRef } from 'react'; - -import { retainStableAiPanelContexts } from '../../domain/aiPanelContextsEqual'; -import { collectSessionIds } from '../../domain/workspace'; -import type { TerminalContextReader } from '../../domain/terminalContextRead'; -import { detectLocalOs } from '../../lib/localShell'; -import type { Host, PortForwardingRule, TerminalSession, Workspace } from '../../types'; -import { buildAITerminalSessionInfo, type AIPanelContext } from './TerminalLayerSupport'; - -interface UseTerminalAiContextsOptions { - hosts: Host[]; - hostsRef: React.MutableRefObject; - portForwardingRules: PortForwardingRule[]; - portForwardingRulesRef: React.MutableRefObject; - mountedAiTabIds: string[]; - sessionHostsMap: Map; - sessions: TerminalSession[]; - sessionsRef: React.MutableRefObject; - terminalContextReadersRef: React.MutableRefObject>; - workspaces: Workspace[]; - workspacesRef: React.MutableRefObject; -} - -export function useTerminalAiContexts({ - hosts, - hostsRef, - portForwardingRules, - portForwardingRulesRef, - mountedAiTabIds, - sessionHostsMap, - sessions, - sessionsRef, - terminalContextReadersRef, - workspaces, - workspacesRef, -}: UseTerminalAiContextsOptions) { - const previousAiContextsRef = useRef | null>(null); - const aiContextsByTabId = useMemo(() => { - const localOs = detectLocalOs(navigator.userAgent || navigator.platform); - const sessionById = new Map(sessions.map((session) => [session.id, session])); - const workspaceById = new Map(workspaces.map((workspace) => [workspace.id, workspace])); - const allHosts = hosts; - const tabIds = new Set(mountedAiTabIds); - - const contexts = new Map(); - - for (const tabId of tabIds) { - const workspace = workspaceById.get(tabId); - if (workspace) { - const sessionIds = collectSessionIds(workspace.root); - contexts.set(tabId, { - scopeType: 'workspace', - scopeTargetId: workspace.id, - scopeHostIds: sessionIds - .map((sessionId) => sessionById.get(sessionId)?.hostId) - .filter((hostId): hostId is string => !!hostId), - scopeLabel: workspace.title, - terminalSessions: sessionIds.map((sessionId) => - buildAITerminalSessionInfo( - sessionById.get(sessionId), - sessionHostsMap.get(sessionId), - localOs, - { allHosts, portForwardingRules }, - ), - ), - }); - continue; - } - - const session = sessionById.get(tabId); - if (!session) continue; - - contexts.set(tabId, { - scopeType: 'terminal', - scopeTargetId: session.id, - scopeHostIds: session.hostId ? [session.hostId] : [], - scopeLabel: session.hostLabel ?? '', - terminalSessions: [ - buildAITerminalSessionInfo( - session, - sessionHostsMap.get(session.id), - localOs, - { allHosts, portForwardingRules }, - ), - ], - }); - } - - const retained = retainStableAiPanelContexts(previousAiContextsRef.current, contexts); - previousAiContextsRef.current = retained; - return retained; - }, [sessions, workspaces, mountedAiTabIds, sessionHostsMap, hosts, portForwardingRules]); - - const resolveAIExecutorContext = useCallback((scope: { - type: 'terminal' | 'workspace'; - targetId?: string; - label?: string; - }) => { - const latestWorkspaces = workspacesRef.current; - const latestSessions = sessionsRef.current; - const latestHosts = hostsRef.current; - const localOs = detectLocalOs(navigator.userAgent || navigator.platform); - const sessionIds = scope.type === 'workspace' - ? (() => { - const workspace = scope.targetId ? latestWorkspaces.find((w) => w.id === scope.targetId) : undefined; - return workspace?.root ? collectSessionIds(workspace.root) : []; - })() - : scope.targetId ? [scope.targetId] : []; - - const workspaceName = scope.type === 'workspace' - ? latestWorkspaces.find((w) => w.id === scope.targetId)?.title ?? scope.label - : undefined; - - return { - sessions: sessionIds.map((sid) => { - const session = latestSessions.find((s) => s.id === sid); - const host = session ? sessionHostsMap.get(session.id) : undefined; - return buildAITerminalSessionInfo(session, host, localOs, { - allHosts: latestHosts, - portForwardingRules: portForwardingRulesRef.current, - }); - }), - workspaceId: scope.type === 'workspace' ? scope.targetId : undefined, - workspaceName, - readTerminalContext: (request: Parameters[0]) => { - const reader = terminalContextReadersRef.current.get(request.sessionId); - if (!reader) { - return Promise.resolve({ - ok: false as const, - error: `Terminal session "${request.sessionId}" has no readable terminal buffer.`, - }); - } - return reader(request); - }, - }; - }, [hostsRef, portForwardingRulesRef, sessionHostsMap, sessionsRef, terminalContextReadersRef, workspacesRef]); - - return { - aiContextsByTabId, - resolveAIExecutorContext, - }; -} +/** @deprecated Import from `@/application/state/useTerminalAiContexts` instead. */ +export { useTerminalAiContexts } from "../../application/state/useTerminalAiContexts"; diff --git a/components/terminalLayer/useTerminalThemePanelState.test.ts b/components/terminalLayer/useTerminalThemePanelState.test.ts index caa0446c2..f40c3792e 100644 --- a/components/terminalLayer/useTerminalThemePanelState.test.ts +++ b/components/terminalLayer/useTerminalThemePanelState.test.ts @@ -36,6 +36,12 @@ test("manual theme list selection reads focused appearance from runtime", () => assert.match(source, /resolvedPreviewTheme = focusedAppearance\.theme/); }); +test("focusedAppearance recomputes from appearanceChromeStore accent churn", () => { + assert.match(source, /useAppearanceChromeStore\(\)/); + assert.match(source, /appearanceChrome\.accentMode/); + assert.match(source, /appearanceChrome\.customAccent/); +}); + test("closing the theme tab clears runtime user intent", () => { assert.match(source, /if \(isSidePanelOpenForCurrentTab\)/); assert.match(source, /clearIntent\(\)/); diff --git a/components/terminalLayer/useTerminalThemePanelState.ts b/components/terminalLayer/useTerminalThemePanelState.ts index eb04dc0ff..e4b19aeda 100644 --- a/components/terminalLayer/useTerminalThemePanelState.ts +++ b/components/terminalLayer/useTerminalThemePanelState.ts @@ -1,5 +1,6 @@ import { startTransition, useCallback, useEffect, useMemo } from 'react'; +import { useAppearanceChromeStore } from '../../application/state/appearanceChromeStore'; import type { ResolvedAppearance, TerminalAppearanceHostScope } from '../../domain/terminalAppearanceRuntime'; import { clearHostFontFamilyOverride, @@ -24,12 +25,10 @@ import type { SidePanelTab } from './TerminalLayerSupport'; const navigatorPlatform = typeof navigator !== 'undefined' ? navigator.platform : ''; interface UseTerminalThemePanelStateOptions { - accentMode: 'theme' | 'custom'; activeSession: TerminalSession | undefined; activeSidePanelTab: SidePanelTab | null; activeWorkspace: Workspace | undefined; clearIntent: () => void; - customAccent: string; followAppTerminalTheme: boolean; focusedSessionId: string | undefined; fontSize: number; @@ -116,10 +115,23 @@ export function useTerminalThemePanelState({ isEphemeral: isFocusedHostEphemeral, }), [focusedHost, isFocusedHostEphemeral]); - const focusedAppearance = useMemo( - () => resolveFocusedAppearance(focusedHostScope), - [resolveFocusedAppearance, focusedHostScope], - ); + // Subscribe to accent store so compose-bar / manual chrome recompute when + // color-picker changes, even though resolveFocusedAppearance identity is + // intentionally stable across accent drag (and TerminalLayer memo ignores + // accent props). + const appearanceChrome = useAppearanceChromeStore(); + const focusedAppearance = useMemo(() => { + // resolveFocusedAppearance reads accent from the chrome store; pin these + // deps so compose-bar chrome updates while focusedHostScope stays stable. + void appearanceChrome.accentMode; + void appearanceChrome.customAccent; + return resolveFocusedAppearance(focusedHostScope); + }, [ + appearanceChrome.accentMode, + appearanceChrome.customAccent, + focusedHostScope, + resolveFocusedAppearance, + ]); const previewTargetSessionId = activeWorkspace?.focusedSessionId ?? activeSession?.id ?? null; diff --git a/components/terminalLayerMemo.ts b/components/terminalLayerMemo.ts index ee05c6e54..c792a2ef0 100644 --- a/components/terminalLayerMemo.ts +++ b/components/terminalLayerMemo.ts @@ -12,8 +12,8 @@ export const terminalLayerAreEqual = ( prev.keys === next.keys && prev.snippets === next.snippets && prev.snippetPackages === next.snippetPackages && - prev.notes === next.notes && - prev.noteGroups === next.noteGroups && + // notes / noteGroups / updateNotes / updateNoteGroups intentionally omitted — + // Notes + AI panels read notesStore. prev.openNoteRequest === next.openNoteRequest && prev.onOpenVaultNoteFromChat === next.onOpenVaultNoteFromChat && prev.onOpenVaultHostFromChat === next.onOpenVaultHostFromChat && @@ -32,8 +32,8 @@ export const terminalLayerAreEqual = ( prev.followAppTerminalTheme === next.followAppTerminalTheme && prev.pickTerminalTheme === next.pickTerminalTheme && prev.resolveSessionAppearance === next.resolveSessionAppearance && - prev.accentMode === next.accentMode && - prev.customAccent === next.customAccent && + // accentMode / customAccent intentionally omitted — Terminal reads + // appearanceChromeStore so accent drag does not rebuild TerminalLayer. prev.terminalSettings === next.terminalSettings && prev.fontSize === next.fontSize && prev.terminalFontFamilyId === next.terminalFontFamilyId && @@ -75,8 +75,6 @@ export const terminalLayerAreEqual = ( prev.onToggleBroadcast === next.onToggleBroadcast && prev.updateSnippets === next.updateSnippets && prev.updateSnippetPackages === next.updateSnippetPackages && - prev.updateNotes === next.updateNotes && - prev.updateNoteGroups === next.updateNoteGroups && prev.toggleScriptsSidePanelRef === next.toggleScriptsSidePanelRef && prev.toggleSidePanelRef === next.toggleSidePanelRef && prev.identities === next.identities diff --git a/components/ui/code-textarea.tsx b/components/ui/code-textarea.tsx deleted file mode 100644 index c46604c5e..000000000 --- a/components/ui/code-textarea.tsx +++ /dev/null @@ -1,99 +0,0 @@ -import * as React from "react"; -import { cn } from "@/lib/utils.ts"; - -export interface CodeTextareaProps - extends Omit, "spellCheck"> { - showLineNumbers?: boolean; - /** Applied to the outer bordered container when line numbers are shown. */ - wrapperClassName?: string; -} - -function countLines(value: string): number { - if (!value) return 1; - return value.split("\n").length; -} - -const CodeTextarea = React.forwardRef( - ({ className, wrapperClassName, value, showLineNumbers = true, onScroll, ...props }, ref) => { - const gutterRef = React.useRef(null); - const text = typeof value === "string" ? value : String(value ?? ""); - const lineCount = countLines(text); - const lineNumbers = React.useMemo( - () => Array.from({ length: lineCount }, (_, i) => i + 1), - [lineCount], - ); - const gutterWidthCh = Math.max(2, String(lineCount).length) + 1; - - const handleScroll = (e: React.UIEvent) => { - if (gutterRef.current) { - gutterRef.current.scrollTop = e.currentTarget.scrollTop; - } - onScroll?.(e); - }; - - const editorClass = cn( - "w-full flex-1 resize-none border-0 bg-transparent px-2 py-2 font-mono text-xs leading-5", - "placeholder:text-muted-foreground focus-visible:outline-none", - "whitespace-pre overflow-auto", - className, - ); - - if (!showLineNumbers) { - return ( -