From 17fa55bedc9d2b39fe49482b9a4879afa0e916ec Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:12:57 +0800 Subject: [PATCH] fix(terminal): sync vaultInitialized with VaultHost props to avoid stale key boot (#4428) --- application/app/AppView.tsx | 3 +- application/app/hosts/VaultHost.tsx | 2 + .../app/vaultInitTerminalSync.test.tsx | 233 ++++++++++++++++++ components/TerminalLayer.tsx | 2 + .../terminalLayer/TerminalLayerSupport.tsx | 7 + .../TerminalLayerWorkspaceSection.tsx | 2 + .../terminalLayer/terminalLayerViewMemo.ts | 1 + components/terminalLayerMemo.ts | 1 + 8 files changed, 250 insertions(+), 1 deletion(-) create mode 100644 application/app/vaultInitTerminalSync.test.tsx diff --git a/application/app/AppView.tsx b/application/app/AppView.tsx index 3d306b0f0..c5005480e 100644 --- a/application/app/AppView.tsx +++ b/application/app/AppView.tsx @@ -281,7 +281,7 @@ function AppViewInner({ domains }: AppViewProps) { handleEndSessionDrag, handleFollowAppTerminalThemeChange, handleHostConnectWithProtocolCheck, handleHotkeyAction, handleKeyboardInteractiveCancel, handleKeyboardInteractiveSubmit, handleOpenHostFromVaultNote, handleOpenQuickSwitcher, handleOpenSettings, handleOpenVaultHostFromChat, handleOpenVaultNoteFromChat, handleOpenVaultSectionFromChat, handleOpenVaultSnippetFromChat, handleRootContextMenu, handlePassphraseCancel, handlePassphraseSkip, handlePassphraseSubmit, handleFidoPromptSubmit, handleFidoPromptCancel, handleProtocolSelect, handleRequestCloseEditorTabRef, handleSessionStatusChange, handleSyncNowManual, handleTerminalDataCapture, handleUpdateHostFromTerminal, - hostById, hosts, terminalHosts, updateTerminalHosts, hotkeyScheme, identities, importOrReuseKey, isBroadcastEnabled, isComposeSendToAll, onToggleComposeSendTarget, isGlobalBroadcastEnabled, isGlobalComposeSendToAll, onToggleGlobalBroadcast, onToggleGlobalComposeSendTarget, canUseGlobalBroadcast, isCreateWorkspaceOpen, isMacClient, isQuickSwitcherOpen, + hostById, hosts, terminalHosts, updateTerminalHosts, hotkeyScheme, identities, importOrReuseKey, isVaultInitialized, isBroadcastEnabled, isComposeSendToAll, onToggleComposeSendTarget, isGlobalBroadcastEnabled, isGlobalComposeSendToAll, onToggleGlobalBroadcast, onToggleGlobalComposeSendTarget, canUseGlobalBroadcast, isCreateWorkspaceOpen, isMacClient, isQuickSwitcherOpen, keyBindings, keyboardInteractiveQueue, keys, logViews, managedSources, navigateToSection, openLogView, openNoteRequest, orderedTabsWithEditors, orphanSessions, passphraseQueue, fidoPromptQueue, protocolSelectHost, proxyProfiles, portForwardingRules, removeSessionFromWorkspace, reorderWorkTabs, reorderWorkspaceSessions, resolveEmptyVaultConflict, resolveSessionAppearance, runSnippet, sessionLogsDir, sessionLogsEnabled, sessionLogsFormat, sessionLogsTimestampsEnabled, sessionRenameTarget, sshDebugLogsEnabled, @@ -734,6 +734,7 @@ function AppViewInner({ domains }: AppViewProps) { /> (); +Object.defineProperty(globalThis, 'localStorage', { + configurable: true, + value: { + getItem: (key: string) => storageBacking.get(key) ?? null, + setItem: (key: string, value: string) => { + storageBacking.set(key, value); + }, + removeItem: (key: string) => { + storageBacking.delete(key); + }, + clear: () => { + storageBacking.clear(); + }, + }, +}); + +const { VaultHost } = await import('./hosts/VaultHost.tsx'); + +test('VaultHost keeps isVaultInitialized synchronized with hydrated hosts, keys, and identities for Terminal boot (#4428)', async () => { + const dom = new JSDOM('
'); + const prevWindow = globalThis.window; + const prevDocument = globalThis.document; + const prevActEnv = (globalThis as Record).IS_REACT_ACT_ENVIRONMENT; + + (globalThis as Record).window = dom.window; + (globalThis as Record).document = dom.window.document; + (globalThis as Record).IS_REACT_ACT_ENVIRONMENT = true; + + const host: Host = { + id: 'host-1', + label: 'test-myhost', + hostname: '10.243.2.249', + port: 22, + username: 'user1', + authMethod: 'key', + identityFileId: 'key-1', + tags: [], + createdAt: 0, + }; + const key: SSHKey = { + id: 'key-1', + label: 'Imported Key', + type: 'ED25519', + privateKey: '-----BEGIN OPENSSH PRIVATE KEY-----\ntest\n-----END OPENSSH PRIVATE KEY-----', + publicKey: 'ssh-ed25519 AAAA test', + passphrase: 'secret', + source: 'imported', + category: 'key', + created: 0, + }; + const identity: Identity = { + id: 'id-1', + label: 'User Identity', + username: 'user1', + authMethod: 'key', + keyId: 'key-1', + createdAt: 0, + }; + + publishVaultSnapshot(EMPTY_VAULT_SNAPSHOT); + registerAppHandlers({} as never); + + // Mirror TerminalHost's layout-effect slice publication order (sibling after VaultHost). + function TerminalHostMirror() { + const vault = useVaultSnapshot(); + useLayoutEffect(() => { + publishAppShellDomainSlice('terminal', { terminalHosts: vault.hosts }); + }, [vault.hosts]); + return null; + } + + const syncedBoots: Array<{ + hostCount: number; + keyCount: number; + identityCount: number; + hasPrivateKey: boolean; + }> = []; + + function SyncedTerminal({ + vaultInitializedOverride, + hosts, + keys, + identities, + }: { + vaultInitializedOverride: boolean; + hosts: readonly Host[]; + keys: readonly SSHKey[]; + identities: readonly Identity[]; + }) { + const sharedVaultInitialized = useVaultSnapshotField('isVaultInitialized'); + const vaultInitialized = resolveTerminalVaultInitialized( + sharedVaultInitialized, + vaultInitializedOverride, + ); + + useEffect(() => { + if (!vaultInitialized) return; + syncedBoots.push({ + hostCount: hosts.length, + keyCount: keys.length, + identityCount: identities.length, + hasPrivateKey: Boolean(keys[0]?.privateKey), + }); + // Intentionally matches useTerminalEffects' boot effect dep shape (gated on vaultInitialized, not keys). + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [vaultInitialized]); + + return null; + } + + function ShellHarness() { + const { domains } = useAppShellProps(); + const vaultDomain = domains?.vault as + | { isVaultInitialized?: boolean; keys?: readonly SSHKey[]; identities?: readonly Identity[] } + | undefined; + const terminalDomain = domains?.terminal as + | { terminalHosts?: readonly Host[] } + | undefined; + + return React.createElement( + React.Fragment, + null, + React.createElement(VaultHost), + React.createElement(TerminalHostMirror), + vaultDomain && terminalDomain + ? React.createElement(SyncedTerminal, { + vaultInitializedOverride: vaultDomain.isVaultInitialized ?? false, + hosts: terminalDomain.terminalHosts ?? [], + keys: vaultDomain.keys ?? [], + identities: vaultDomain.identities ?? [], + }) + : null, + ); + } + + const root = createRoot(dom.window.document.getElementById('root')!); + try { + await React.act(async () => { + root.render(React.createElement(ShellHarness)); + }); + assert.equal(syncedBoots.length, 0, 'restored terminal must not boot before vault hydration'); + + // Publish hydrated hosts, keys, identities, and isVaultInitialized together. + await React.act(async () => { + publishVaultSnapshot({ + ...EMPTY_VAULT_SNAPSHOT, + isVaultInitialized: true, + hosts: [host], + keys: [key], + identities: [identity], + }); + }); + + assert.deepEqual(syncedBoots, [ + { + hostCount: 1, + keyCount: 1, + identityCount: 1, + hasPrivateKey: true, + }, + ]); + } finally { + await React.act(async () => { + root.unmount(); + }); + publishVaultSnapshot(EMPTY_VAULT_SNAPSHOT); + registerAppHandlers(null); + (globalThis as Record).window = prevWindow; + (globalThis as Record).document = prevDocument; + (globalThis as Record).IS_REACT_ACT_ENVIRONMENT = prevActEnv; + } +}); + +test('terminal layer memo comparators propagate isVaultInitialized changes', () => { + const baseLayerProps = { + isVaultInitialized: false, + hosts: [], + sessions: [], + }; + assert.equal( + terminalLayerAreEqual(baseLayerProps, { ...baseLayerProps, isVaultInitialized: true }), + false, + ); + assert.equal( + terminalLayerWorkspaceCtxEqual( + { isVaultInitialized: false }, + { isVaultInitialized: true }, + ), + false, + ); + assert.equal( + terminalLayerViewCtxEqual( + { isVaultInitialized: false }, + { isVaultInitialized: true }, + ), + false, + ); + + const appViewSource = readFileSync(new URL('./AppView.tsx', import.meta.url), 'utf8'); + const supportSource = readFileSync( + new URL('../../components/terminalLayer/TerminalLayerSupport.tsx', import.meta.url), + 'utf8', + ); + assert.match(appViewSource, / = ({ + isVaultInitialized, hosts, portForwardingRules = [], customGroups, @@ -2802,6 +2803,7 @@ const TerminalLayerInner: React.FC = ({ onToggleGlobalComposeSendTarget, canUseGlobalBroadcast, isComposeBarOpen, + isVaultInitialized, keyBindings, keys, knownHosts, diff --git a/components/terminalLayer/TerminalLayerSupport.tsx b/components/terminalLayer/TerminalLayerSupport.tsx index bed750fb8..53d38d4d2 100644 --- a/components/terminalLayer/TerminalLayerSupport.tsx +++ b/components/terminalLayer/TerminalLayerSupport.tsx @@ -683,6 +683,7 @@ export const AIChatPanelsHost = memo(AIChatPanelsHostInner, aiChatPanelsHostAreE AIChatPanelsHost.displayName = 'AIChatPanelsHost'; export interface TerminalLayerProps { + isVaultInitialized?: boolean; hosts: Host[]; portForwardingRules?: import('../../domain/models').PortForwardingRule[]; customGroups: string[]; @@ -822,6 +823,7 @@ interface TerminalPaneProps { splitVerticalHandlersRef: React.MutableRefObject void>>; resolveSessionAppearance: (hostScope: TerminalAppearanceHostScope) => ResolvedAppearance; hostMap: Map; + isVaultInitialized?: boolean; keys: SSHKey[]; identities: Identity[]; snippets: Snippet[]; @@ -961,6 +963,7 @@ const terminalPanePropsAreEqual = ( prev.splitHorizontalHandlersRef === next.splitHorizontalHandlersRef && prev.splitVerticalHandlersRef === next.splitVerticalHandlersRef && getPaneAppearanceThemeId(prev) === getPaneAppearanceThemeId(next) && + prev.isVaultInitialized === next.isVaultInitialized && prev.keys === next.keys && prev.identities === next.identities && prev.snippets === next.snippets && @@ -1253,6 +1256,7 @@ const TerminalPane: React.FC = memo(({ splitVerticalHandlersRef, resolveSessionAppearance, hostMap, + isVaultInitialized, keys, identities, snippets, @@ -1680,6 +1684,7 @@ const TerminalPane: React.FC = memo(({ sessionId={session.id} workspaceId={session.workspaceId} restoreState={session.restoreState} + vaultInitializedOverride={isVaultInitialized} pendingInitialCwd={session.pendingInitialCwd} shellType={session.shellType} lastCwd={session.lastCwd} @@ -1776,6 +1781,7 @@ interface TerminalPanesHostProps { splitVerticalHandlersRef: React.MutableRefObject void>>; resolveSessionAppearance: (hostScope: TerminalAppearanceHostScope) => ResolvedAppearance; hostMap: Map; + isVaultInitialized?: boolean; keys: SSHKey[]; identities: Identity[]; snippets: Snippet[]; @@ -1871,6 +1877,7 @@ const terminalPanesHostPropsAreEqual = ( if (prev.splitVerticalHandlersRef !== next.splitVerticalHandlersRef) return false; if (prev.resolveSessionAppearance !== next.resolveSessionAppearance) return false; if (prev.hostMap !== next.hostMap) return false; + if (prev.isVaultInitialized !== next.isVaultInitialized) return false; if (prev.keys !== next.keys) return false; if (prev.identities !== next.identities) return false; if (prev.snippets !== next.snippets) return false; diff --git a/components/terminalLayer/TerminalLayerWorkspaceSection.tsx b/components/terminalLayer/TerminalLayerWorkspaceSection.tsx index 10051624c..6a7447800 100644 --- a/components/terminalLayer/TerminalLayerWorkspaceSection.tsx +++ b/components/terminalLayer/TerminalLayerWorkspaceSection.tsx @@ -62,6 +62,7 @@ function TerminalLayerWorkspaceSectionInner({ ctx }: { ctx: WorkspaceContext }) splitVerticalHandlersRef, resolveSessionAppearance, hostMap, + isVaultInitialized, keys, identities, snippets, @@ -230,6 +231,7 @@ function TerminalLayerWorkspaceSectionInner({ ctx }: { ctx: WorkspaceContext }) splitVerticalHandlersRef={splitVerticalHandlersRef} resolveSessionAppearance={resolveSessionAppearance} hostMap={hostMap} + isVaultInitialized={isVaultInitialized} keys={keys} identities={identities} snippets={snippets} diff --git a/components/terminalLayer/terminalLayerViewMemo.ts b/components/terminalLayer/terminalLayerViewMemo.ts index 97a8fb65d..38e756197 100644 --- a/components/terminalLayer/terminalLayerViewMemo.ts +++ b/components/terminalLayer/terminalLayerViewMemo.ts @@ -383,6 +383,7 @@ const WORKSPACE_CTX_KEYS = [ 'splitVerticalHandlersRef', 'resolveSessionAppearance', 'hostMap', + 'isVaultInitialized', 'keys', 'identities', 'snippets', diff --git a/components/terminalLayerMemo.ts b/components/terminalLayerMemo.ts index 1d51394d3..d6bed97d3 100644 --- a/components/terminalLayerMemo.ts +++ b/components/terminalLayerMemo.ts @@ -4,6 +4,7 @@ export const terminalLayerAreEqual = ( prev: Record, next: Record, ): boolean => ( + prev.isVaultInitialized === next.isVaultInitialized && prev.hosts === next.hosts && prev.customGroups === next.customGroups && prev.groupConfigs === next.groupConfigs &&