From 3f65d6fecddfca99dff5c650f85ad1e69d445974 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 01:47:18 -0700 Subject: [PATCH 1/8] fix(workspace): a restored workspace paints before its terminals reconnect MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After a restart the workspace content area stayed blank — no tab strip, no pane — until the whole startup chain (SSH reconnect, PTY reconnect, legacy worker recovery) had finished, even though the restored tab model had been in the store for seconds. Only terminal panes need that chain, because a pane binds a PTY on mount. The workbench now mounts the active workspace from its hydrated tab model, and holds its terminal tabs unadmitted (an empty admitted-tab restriction with no deferral entry) until startup restoration has published PTY ownership; the activation plan then replaces the hold. Chat, browser and editor panes mount immediately. Carried from #22293 (922c1c26264), renderer terminal files only. --- .../components/terminal-cold-activation.ts | 19 +- ...background-terminal-worktree-mount.test.ts | 10 +- .../background-terminal-worktree-mount.ts | 9 +- .../startup-terminal-tab-hold.test.ts | 272 ++++++++++++++++++ .../terminal/startup-terminal-tab-hold.ts | 44 +++ 5 files changed, 346 insertions(+), 8 deletions(-) create mode 100644 src/renderer/src/components/terminal/startup-terminal-tab-hold.test.ts create mode 100644 src/renderer/src/components/terminal/startup-terminal-tab-hold.ts diff --git a/src/renderer/src/components/terminal-cold-activation.ts b/src/renderer/src/components/terminal-cold-activation.ts index 8b6e96467eef..7b8ee127be2d 100644 --- a/src/renderer/src/components/terminal-cold-activation.ts +++ b/src/renderer/src/components/terminal-cold-activation.ts @@ -1,11 +1,12 @@ import { useAppStore } from '../store' import { + canAdmitTerminalTabsForStartup, canDeferColdActivationTabsForHost, - canMountTerminalWorkspaceForStartup, planColdActivationTabDeferral, pruneClosedBackgroundMountTabs, revealActivationDeferredTabs } from './terminal/background-terminal-worktree-mount' +import { holdTerminalTabsForStartup } from './terminal/startup-terminal-tab-hold' import { hasRegisteredRuntimeTerminalTab } from '../runtime/sync-runtime-graph' import { anyMountedWorktreeHasLayout as computeAnyMountedWorktreeHasLayout } from './terminal/split-group-mount' import { isParkRestorableTerminalPty } from './terminal-pane/terminal-hidden-view-parking' @@ -40,14 +41,28 @@ export function applyTerminalColdActivation(controller: TerminalParkingFoundatio workspaceSurfaceIds, workspaceSurfaceIdSet } = controller + // Why the surface mounts on the tab model alone: the hydrated tabs, groups, and layout are + // everything the tab strip and the chat, browser, and editor panes need. Only terminal + // panes wait, held below, for startup restoration to publish PTY ownership — gating the + // whole surface on that chain left a restored session blank until its last step. if ( renderedActiveWorktreeId && - canMountTerminalWorkspaceForStartup({ + !canAdmitTerminalTabsForStartup({ workspaceSessionReady, hydrationSucceeded, startupWorktreeRefreshCompleted }) ) { + // Why null: the gate opening must run the activation plan, which replaces the hold. + lastActivationWorktreeIdRef.current = null + holdTerminalTabsForStartup( + backgroundMountTabIdsByWorktreeRef.current, + activationDeferredMountTabIdsByWorktreeRef.current, + mountedWorktreeIdsRef.current, + renderedActiveWorktreeId + ) + mountedWorktreeIdsRef.current.add(renderedActiveWorktreeId) + } else if (renderedActiveWorktreeId) { const worktreeTabs = tabsByWorktree[renderedActiveWorktreeId] ?? [] const coldActivationDeferralEnabled = terminalParkingEnabled && terminalTitleSnapshotAuthorityEnabled diff --git a/src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts b/src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts index 0978393bba7f..117f049978ee 100644 --- a/src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts +++ b/src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts @@ -11,7 +11,7 @@ import { addBackgroundMountedTerminalWorktree, applyBackgroundMountTabRestriction, canDeferColdActivationTabsForHost, - canMountTerminalWorkspaceForStartup, + canAdmitTerminalTabsForStartup, collectDeferredMountTabIds, hasRequestedBackgroundTerminalWorktreeMount, planColdActivationTabDeferral, @@ -23,24 +23,24 @@ import { shouldMountBackgroundWorktreeTab } from './background-terminal-worktree-mount' -describe('terminal workspace startup mount gate', () => { +describe('startup terminal tab admission gate', () => { it('waits for hydration unless startup entered degraded mode', () => { expect( - canMountTerminalWorkspaceForStartup({ + canAdmitTerminalTabsForStartup({ workspaceSessionReady: true, hydrationSucceeded: false, startupWorktreeRefreshCompleted: false }) ).toBe(false) expect( - canMountTerminalWorkspaceForStartup({ + canAdmitTerminalTabsForStartup({ workspaceSessionReady: true, hydrationSucceeded: true, startupWorktreeRefreshCompleted: false }) ).toBe(true) expect( - canMountTerminalWorkspaceForStartup({ + canAdmitTerminalTabsForStartup({ workspaceSessionReady: true, hydrationSucceeded: false, startupWorktreeRefreshCompleted: true diff --git a/src/renderer/src/components/terminal/background-terminal-worktree-mount.ts b/src/renderer/src/components/terminal/background-terminal-worktree-mount.ts index 8f8bf4461b0f..4f4214e07fc1 100644 --- a/src/renderer/src/components/terminal/background-terminal-worktree-mount.ts +++ b/src/renderer/src/components/terminal/background-terminal-worktree-mount.ts @@ -150,7 +150,14 @@ export function shouldMountBackgroundWorktreeTab( // working set (and later tab switches) ends up exactly where it was before. export const COLD_ACTIVATION_TAB_DEFER_THRESHOLD = 0 -export function canMountTerminalWorkspaceForStartup(args: { +/** + * Whether restored terminal tabs may mount their panes. Why this fences panes and not the + * workspace surface: a pane binds a PTY on mount, and until startup restoration has fenced + * the daemon provider, reconnected SSH targets, and published PTY ownership, that bind would + * attach to a not-yet-restored session or spawn a duplicate shell. The tab strip and the + * chat, browser, and editor panes bind nothing, so they mount from the hydrated tab model. + */ +export function canAdmitTerminalTabsForStartup(args: { workspaceSessionReady: boolean hydrationSucceeded: boolean startupWorktreeRefreshCompleted: boolean diff --git a/src/renderer/src/components/terminal/startup-terminal-tab-hold.test.ts b/src/renderer/src/components/terminal/startup-terminal-tab-hold.test.ts new file mode 100644 index 000000000000..0b3f8b265328 --- /dev/null +++ b/src/renderer/src/components/terminal/startup-terminal-tab-hold.test.ts @@ -0,0 +1,272 @@ +// @vitest-environment happy-dom + +/** + * Defect under test: the restored workspace surface used to wait for the whole + * startup chain (SSH reconnect, PTY reconnect, legacy worker recovery) before it + * mounted, so a session whose tab model had been in the store for seconds painted + * nothing at all. Only terminal panes need that chain — they bind a PTY on mount. + * The surface now mounts on the tab model, and terminal tabs are held unadmitted + * until the gate opens and the activation plan replaces the hold. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, renderHook } from '@testing-library/react' +import { useRef, useState } from 'react' +import { useAppStore } from '@/store' +import { applyTerminalColdActivation } from '../terminal-cold-activation' +import { useActivationDeferredTabAdmission } from './use-activation-deferred-tab-admission' +import { + pruneClosedBackgroundMountTabs, + revealActivationDeferredTabs, + shouldMountBackgroundWorktreeTab +} from './background-terminal-worktree-mount' +import { holdTerminalTabsForStartup } from './startup-terminal-tab-hold' +import type { TabGroup, TabGroupLayoutNode } from '../../../../shared/tab-types' +import type { TerminalTab } from '../../../../shared/terminal-tab-types' +import type { TerminalParkingFoundation } from '../use-terminal-parking-foundation' + +const WORKTREE_ID = 'repo::/worktree' +const OTHER_WORKTREE_ID = 'repo::/other-worktree' +const TAB_1 = 'tab-1' +const TAB_2 = 'tab-2' +const GROUP_ID = 'group-1' +const SURFACE_IDS = [WORKTREE_ID, OTHER_WORKTREE_ID] + +const initialState = useAppStore.getInitialState() +const originalRequestIdle = globalThis.requestIdleCallback +const originalCancelIdle = globalThis.cancelIdleCallback + +function terminalTab(id: string, worktreeId: string): TerminalTab { + return { + id, + ptyId: `${worktreeId}@@${id}`, + worktreeId, + title: id, + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } +} + +function leafLayout(worktreeId: string): { + groups: TabGroup[] + layout: TabGroupLayoutNode +} { + return { + groups: [ + { id: GROUP_ID, worktreeId, activeTabId: TAB_1, tabOrder: [TAB_1, TAB_2], recentTabIds: [] } + ], + layout: { type: 'leaf', groupId: GROUP_ID } + } +} + +type HarnessProps = { worktreeId: string | null; gateOpen: boolean } + +/** Mirrors use-terminal-controller.ts: cold activation during render, then admission. */ +function useStartupHoldHarness(props: HarnessProps) { + const backgroundMountTabIdsByWorktreeRef = useRef(new Map>()) + const activationDeferredMountTabIdsByWorktreeRef = useRef(new Map>()) + const lastActivationWorktreeIdRef = useRef(null) + const mountedWorktreeIdsRef = useRef(new Set()) + const activationDeferralPlanRevisionRef = useRef(0) + const [backgroundMountRevision, setBackgroundMountRevision] = useState(0) + const restored = leafLayout(props.worktreeId ?? WORKTREE_ID) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: applyTerminalColdActivation and the admission hook read only the fields listed here; the rest of the foundation is render machinery this harness never exercises. + const foundation = { + activationDeferralPlanRevisionRef, + activationDeferredMountTabIdsByWorktreeRef, + activeGroupIdByWorktree: props.worktreeId ? { [props.worktreeId]: GROUP_ID } : {}, + activeTabId: TAB_1, + activeTabIdByWorktree: props.worktreeId ? { [props.worktreeId]: TAB_1 } : {}, + activeWorktreeDeferralHostId: 'local', + activityTerminalPortals: [], + backgroundMountRevision, + backgroundMountTabIdsByWorktreeRef, + groupsByWorktree: props.worktreeId ? { [props.worktreeId]: restored.groups } : {}, + hydrationSucceeded: props.gateOpen, + lastActivationWorktreeIdRef, + layoutByWorktree: props.worktreeId ? { [props.worktreeId]: restored.layout } : {}, + mountedWorktreeIdsRef, + pairedRuntimeParkingEnvironmentIds: new Set(), + pendingStartupByTabId: {}, + renderedActiveWorktreeId: props.worktreeId, + setBackgroundMountRevision, + startupWorktreeRefreshCompleted: props.gateOpen, + tabsByWorktree: useAppStore.getState().tabsByWorktree, + terminalParkingEnabled: true, + terminalTitleSnapshotAuthorityEnabled: true, + workspaceSessionReady: props.gateOpen, + workspaceSurfaceIds: SURFACE_IDS, + workspaceSurfaceIdSet: new Set(SURFACE_IDS) + } as unknown as TerminalParkingFoundation + const coldActivation = Object.assign(foundation, applyTerminalColdActivation(foundation)) + useActivationDeferredTabAdmission(coldActivation) + return { + activationDeferredMountTabIdsByWorktreeRef, + anyMountedWorktreeHasLayout: coldActivation.anyMountedWorktreeHasLayout, + backgroundMountTabIdsByWorktreeRef, + mountedWorktreeIdsRef + } +} + +function admits( + restrictions: Map>, + worktreeId: string, + tabId: string +): boolean { + return shouldMountBackgroundWorktreeTab(restrictions.get(worktreeId) ?? null, tabId) +} + +describe('startup terminal tab hold', () => { + beforeEach(() => { + useAppStore.setState(initialState, true) + useAppStore.setState({ + tabsByWorktree: { + [WORKTREE_ID]: [terminalTab(TAB_1, WORKTREE_ID), terminalTab(TAB_2, WORKTREE_ID)], + [OTHER_WORKTREE_ID]: [terminalTab(TAB_1, OTHER_WORKTREE_ID)] + } + }) + // Deterministic drain: force scheduleActivationDeferredAdmission onto timers. + // @ts-expect-error -- exercising the no-requestIdleCallback environment + globalThis.requestIdleCallback = undefined + // @ts-expect-error -- exercising the no-requestIdleCallback environment + globalThis.cancelIdleCallback = undefined + vi.useFakeTimers() + }) + + afterEach(() => { + cleanup() + vi.useRealTimers() + globalThis.requestIdleCallback = originalRequestIdle + globalThis.cancelIdleCallback = originalCancelIdle + useAppStore.setState(initialState, true) + }) + + it('mounts the restored surface before the gate opens and holds every terminal tab', () => { + const { result, rerender } = renderHook(useStartupHoldHarness, { + initialProps: { worktreeId: WORKTREE_ID, gateOpen: false } + }) + const restrictions = result.current.backgroundMountTabIdsByWorktreeRef.current + + // The surface mounts from the tab model alone... + expect(result.current.mountedWorktreeIdsRef.current.has(WORKTREE_ID)).toBe(true) + expect(result.current.anyMountedWorktreeHasLayout).toBe(true) + // ...while no terminal pane may bind a PTY yet, and none is idle-admission work. + expect(admits(restrictions, WORKTREE_ID, TAB_1)).toBe(false) + expect(admits(restrictions, WORKTREE_ID, TAB_2)).toBe(false) + expect(result.current.activationDeferredMountTabIdsByWorktreeRef.current.has(WORKTREE_ID)).toBe( + false + ) + act(() => { + vi.advanceTimersByTime(1_000) + }) + expect(admits(restrictions, WORKTREE_ID, TAB_1)).toBe(false) + + // The gate opening runs the activation plan, which replaces the hold. + rerender({ worktreeId: WORKTREE_ID, gateOpen: true }) + expect(result.current.mountedWorktreeIdsRef.current.has(WORKTREE_ID)).toBe(true) + expect(admits(restrictions, WORKTREE_ID, TAB_1)).toBe(true) + expect(admits(restrictions, WORKTREE_ID, TAB_2)).toBe(true) + }) + + it('returns a workspace switched away from mid-startup to the unmounted world', () => { + const { result, rerender } = renderHook(useStartupHoldHarness, { + initialProps: { worktreeId: WORKTREE_ID, gateOpen: false } + }) + expect(result.current.mountedWorktreeIdsRef.current.has(WORKTREE_ID)).toBe(true) + + rerender({ worktreeId: OTHER_WORKTREE_ID, gateOpen: false }) + const restrictions = result.current.backgroundMountTabIdsByWorktreeRef.current + expect(result.current.mountedWorktreeIdsRef.current.has(WORKTREE_ID)).toBe(false) + expect(restrictions.has(WORKTREE_ID)).toBe(false) + expect(result.current.mountedWorktreeIdsRef.current.has(OTHER_WORKTREE_ID)).toBe(true) + expect(admits(restrictions, OTHER_WORKTREE_ID, TAB_1)).toBe(false) + + rerender({ worktreeId: OTHER_WORKTREE_ID, gateOpen: true }) + expect(admits(restrictions, OTHER_WORKTREE_ID, TAB_1)).toBe(true) + }) + + it('does not mount a surface with no active workspace', () => { + const { result } = renderHook(useStartupHoldHarness, { + initialProps: { worktreeId: null, gateOpen: false } + }) + expect(result.current.mountedWorktreeIdsRef.current.size).toBe(0) + expect(result.current.backgroundMountTabIdsByWorktreeRef.current.size).toBe(0) + }) +}) + +describe('holdTerminalTabsForStartup', () => { + it('admits no terminal tab of a worktree that has not mounted yet', () => { + const restrictions = new Map>() + const deferred = new Map>() + const mounted = new Set() + + holdTerminalTabsForStartup(restrictions, deferred, mounted, 'wt-active') + + expect(restrictions.get('wt-active')).toEqual(new Set()) + expect(shouldMountBackgroundWorktreeTab(restrictions.get('wt-active') ?? null, 'tab-1')).toBe( + false + ) + expect(deferred.has('wt-active')).toBe(false) + }) + + it('keeps a targeted background mount that landed first and never narrows a full mount', () => { + const restrictions = new Map>([['wt-active', new Set(['tab-1'])]]) + const deferred = new Map>() + const mounted = new Set(['wt-full']) + + holdTerminalTabsForStartup(restrictions, deferred, mounted, 'wt-active') + expect(restrictions.get('wt-active')).toEqual(new Set(['tab-1'])) + + holdTerminalTabsForStartup(restrictions, deferred, mounted, 'wt-full') + expect(restrictions.has('wt-full')).toBe(false) + }) + + it('survives prune and reveal passes untouched', () => { + const restrictions = new Map>() + const deferred = new Map>() + const mounted = new Set() + holdTerminalTabsForStartup(restrictions, deferred, mounted, 'wt-active') + mounted.add('wt-active') + + expect( + pruneClosedBackgroundMountTabs( + restrictions, + mounted, + { 'wt-active': [{ id: 'tab-1' }] }, + deferred + ) + ).toBe(false) + revealActivationDeferredTabs({ + restrictions, + deferredMountTabIdsByWorktree: deferred, + worktreeId: 'wt-active', + allTabIds: ['tab-1'], + immediateTabIds: new Set(['tab-1']) + }) + expect(restrictions.get('wt-active')).toEqual(new Set()) + expect(mounted.has('wt-active')).toBe(true) + }) + + it('releases holds on other worktrees but leaves targeted and activation restrictions alone', () => { + const restrictions = new Map>([ + ['wt-previous', new Set()], + ['wt-targeted', new Set(['tab-wake'])], + ['wt-activation', new Set()] + ]) + const deferred = new Map>([ + ['wt-activation', new Set(['tab-deferred'])] + ]) + const mounted = new Set(['wt-previous', 'wt-targeted', 'wt-activation']) + + holdTerminalTabsForStartup(restrictions, deferred, mounted, 'wt-active') + + expect(restrictions.has('wt-previous')).toBe(false) + expect(mounted.has('wt-previous')).toBe(false) + expect(restrictions.get('wt-targeted')).toEqual(new Set(['tab-wake'])) + expect(restrictions.get('wt-activation')).toEqual(new Set()) + expect(mounted.has('wt-targeted')).toBe(true) + expect(mounted.has('wt-activation')).toBe(true) + expect(restrictions.get('wt-active')).toEqual(new Set()) + }) +}) diff --git a/src/renderer/src/components/terminal/startup-terminal-tab-hold.ts b/src/renderer/src/components/terminal/startup-terminal-tab-hold.ts new file mode 100644 index 000000000000..a09b12ac26f8 --- /dev/null +++ b/src/renderer/src/components/terminal/startup-terminal-tab-hold.ts @@ -0,0 +1,44 @@ +import { applyBackgroundMountTabRestriction } from './background-terminal-worktree-mount' + +/** A hold is the one restriction shape nothing else produces: no admitted tabs and no + * deferral entry. Prune drops an emptied targeted restriction outright, and an activation + * restriction emptied by closes keeps its deferral entry. */ +function isStartupTerminalTabHold( + restrictions: ReadonlyMap>, + deferredMountTabIdsByWorktree: ReadonlyMap>, + worktreeId: string +): boolean { + return restrictions.get(worktreeId)?.size === 0 && !deferredMountTabIdsByWorktree.has(worktreeId) +} + +/** + * Keeps every terminal tab of the active worktree unmounted while startup restoration is + * still publishing PTY ownership, so the workspace surface can mount from the hydrated tab + * model without a pane binding a PTY early. Must run before the worktree joins + * `mountedWorktreeIds`, like any restriction. + * + * Why an empty admitted set and no deferral entry: reveal and idle admission act only on + * worktrees with a deferral entry, and prune leaves an unchanged restriction alone, so the + * hold survives every render pass until the startup gate opens and the activation plan + * replaces it. A targeted background mount that lands meanwhile widens the hold to its + * tabs, exactly as it would widen any restriction. Holds on other worktrees are released — + * nothing was mounted under them — so a workspace switched away from mid-startup returns + * to the unmounted world where parked watchers cover it. + */ +export function holdTerminalTabsForStartup( + restrictions: Map>, + deferredMountTabIdsByWorktree: ReadonlyMap>, + mountedWorktreeIds: Set, + worktreeId: string +): void { + for (const [heldWorktreeId] of restrictions) { + if ( + heldWorktreeId !== worktreeId && + isStartupTerminalTabHold(restrictions, deferredMountTabIdsByWorktree, heldWorktreeId) + ) { + restrictions.delete(heldWorktreeId) + mountedWorktreeIds.delete(heldWorktreeId) + } + } + applyBackgroundMountTabRestriction(restrictions, mountedWorktreeIds, worktreeId, []) +} From 51f891f3a070bcad97f02bbc00a282d207a15e7e Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 01:47:22 -0700 Subject: [PATCH 2/8] fix(workspace): track the startup terminal hold explicitly and keep its tabs watched The startup hold was inferred from the restriction map's shape and released only when a new hold was installed, so a workspace left for no workspace mid-startup stayed mounted with no terminal panes and no background watchers. Track the held workspace explicitly, release it on any pass where it is no longer held, apply it after prune, and count held tabs as parked so their bells, titles, and completions are still observed during the window. Carried from #22293 (3fd421c41f4), renderer terminal files only. --- .../TerminalSplitWorkspaceSurfaces.tsx | 10 +- .../components/terminal-cold-activation.ts | 37 ++++-- ...minal-parked-watcher-sync-entries.test.tsx | 15 +++ .../terminal-workspace-surface-ids.test.tsx | 2 + ...cold-activation-deferral-stranding.test.ts | 4 + ...nitial-terminal-structured-launch.test.tsx | 1 + .../startup-terminal-tab-hold.test.ts | 125 ++++++++++++++---- .../terminal/startup-terminal-tab-hold.ts | 93 ++++++++----- .../use-terminal-parking-foundation.ts | 3 + .../use-terminal-watcher-effects.ts | 10 +- 10 files changed, 231 insertions(+), 69 deletions(-) diff --git a/src/renderer/src/components/TerminalSplitWorkspaceSurfaces.tsx b/src/renderer/src/components/TerminalSplitWorkspaceSurfaces.tsx index 5c3145360f65..cfe381ccce9f 100644 --- a/src/renderer/src/components/TerminalSplitWorkspaceSurfaces.tsx +++ b/src/renderer/src/components/TerminalSplitWorkspaceSurfaces.tsx @@ -1,5 +1,6 @@ import { useAnyBrowserGuestNeedsPaint } from './browser-pane/host-guest/browser-guest-paint-retention' import { WorktreeSplitSurface } from './TerminalWorktreeSplitSurface' +import { selectParkedEquivalentMountTabIds } from './terminal/startup-terminal-tab-hold' import type { TerminalController } from './use-terminal-controller' export function TerminalSplitWorkspaceSurfaces({ @@ -21,6 +22,7 @@ export function TerminalSplitWorkspaceSurfaces({ measurableBackgroundWorktreeIdsRef, mountedWorktreeIdsRef, renderedActiveWorktreeId, + startupTerminalTabHold, workspaceSurfaces } = controller // Why: this and TerminalSurface are both strict ancestors of every browser , so a @@ -69,9 +71,11 @@ export function TerminalSplitWorkspaceSurfaces({ backgroundMountTabIds={ backgroundMountTabIdsByWorktreeRef.current.get(workspace.id) ?? null } - activationDeferredMountTabIds={ - activationDeferredMountTabIdsByWorktreeRef.current.get(workspace.id) ?? null - } + activationDeferredMountTabIds={selectParkedEquivalentMountTabIds( + activationDeferredMountTabIdsByWorktreeRef.current.get(workspace.id), + startupTerminalTabHold, + workspace.id + )} /> ) })} diff --git a/src/renderer/src/components/terminal-cold-activation.ts b/src/renderer/src/components/terminal-cold-activation.ts index 7b8ee127be2d..ac54b125afe6 100644 --- a/src/renderer/src/components/terminal-cold-activation.ts +++ b/src/renderer/src/components/terminal-cold-activation.ts @@ -6,7 +6,10 @@ import { pruneClosedBackgroundMountTabs, revealActivationDeferredTabs } from './terminal/background-terminal-worktree-mount' -import { holdTerminalTabsForStartup } from './terminal/startup-terminal-tab-hold' +import { + holdTerminalTabsForStartup, + releaseStartupTerminalTabHold +} from './terminal/startup-terminal-tab-hold' import { hasRegisteredRuntimeTerminalTab } from '../runtime/sync-runtime-graph' import { anyMountedWorktreeHasLayout as computeAnyMountedWorktreeHasLayout } from './terminal/split-group-mount' import { isParkRestorableTerminalPty } from './terminal-pane/terminal-hidden-view-parking' @@ -33,6 +36,7 @@ export function applyTerminalColdActivation(controller: TerminalParkingFoundatio pairedRuntimeParkingEnvironmentIds, pendingStartupByTabId, renderedActiveWorktreeId, + startupTerminalTabHoldRef, startupWorktreeRefreshCompleted, tabsByWorktree, terminalParkingEnabled, @@ -45,23 +49,24 @@ export function applyTerminalColdActivation(controller: TerminalParkingFoundatio // everything the tab strip and the chat, browser, and editor panes need. Only terminal // panes wait, held below, for startup restoration to publish PTY ownership — gating the // whole surface on that chain left a restored session blank until its last step. - if ( + const startupHeldWorktreeId = renderedActiveWorktreeId && !canAdmitTerminalTabsForStartup({ workspaceSessionReady, hydrationSucceeded, startupWorktreeRefreshCompleted }) - ) { + ? renderedActiveWorktreeId + : null + releaseStartupTerminalTabHold( + startupTerminalTabHoldRef, + backgroundMountTabIdsByWorktreeRef.current, + mountedWorktreeIdsRef.current, + startupHeldWorktreeId + ) + if (startupHeldWorktreeId) { // Why null: the gate opening must run the activation plan, which replaces the hold. lastActivationWorktreeIdRef.current = null - holdTerminalTabsForStartup( - backgroundMountTabIdsByWorktreeRef.current, - activationDeferredMountTabIdsByWorktreeRef.current, - mountedWorktreeIdsRef.current, - renderedActiveWorktreeId - ) - mountedWorktreeIdsRef.current.add(renderedActiveWorktreeId) } else if (renderedActiveWorktreeId) { const worktreeTabs = tabsByWorktree[renderedActiveWorktreeId] ?? [] const coldActivationDeferralEnabled = @@ -172,6 +177,15 @@ export function applyTerminalColdActivation(controller: TerminalParkingFoundatio tabsByWorktree, activationDeferredMountTabIdsByWorktreeRef.current ) + if (startupHeldWorktreeId) { + holdTerminalTabsForStartup( + startupTerminalTabHoldRef, + backgroundMountTabIdsByWorktreeRef.current, + mountedWorktreeIdsRef.current, + startupHeldWorktreeId, + (tabsByWorktree[startupHeldWorktreeId] ?? []).map((tab) => tab.id) + ) + } for (const id of mountedWorktreeIdsRef.current) { if (!workspaceSurfaceIdSet.has(id)) { mountedWorktreeIdsRef.current.delete(id) @@ -188,7 +202,8 @@ export function applyTerminalColdActivation(controller: TerminalParkingFoundatio ) return { anyMountedWorktreeHasLayout, - activationDeferralPlanRevision: activationDeferralPlanRevisionRef.current + activationDeferralPlanRevision: activationDeferralPlanRevisionRef.current, + startupTerminalTabHold: startupTerminalTabHoldRef.current } } diff --git a/src/renderer/src/components/terminal-parked-watcher-sync-entries.test.tsx b/src/renderer/src/components/terminal-parked-watcher-sync-entries.test.tsx index efcc2fb8d448..37b40a20053d 100644 --- a/src/renderer/src/components/terminal-parked-watcher-sync-entries.test.tsx +++ b/src/renderer/src/components/terminal-parked-watcher-sync-entries.test.tsx @@ -80,6 +80,7 @@ function renderWatcherEffects(overrides: Partial = {}): Promi pendingStartupByTabId: {}, // Another workspace is on screen, so the mounted one is hidden and parks. renderedActiveWorktreeId: 'repo-1::/worktree-9', + startupTerminalTabHold: null, tabsByWorktree: { [PARKED_WORKTREE_ID]: [ terminalTab('tab-parked', PARKED_WORKTREE_ID), @@ -127,6 +128,20 @@ describe('parked terminal watcher sync entries', () => { expect([...(parkedEntry?.parkedTabIds ?? [])]).toEqual(['tab-parked']) }) + it('watches the tabs a startup hold keeps unmounted on the visible workspace', async () => { + const heldWorktreeId = surfaceIds[9] + const tab = terminalTab('held-agent', heldWorktreeId, 'live-pty') + await renderWatcherEffects({ + mountedWorktreeIdsRef: { current: new Set([heldWorktreeId]) }, + startupTerminalTabHold: { worktreeId: heldWorktreeId, heldTabIds: new Set([tab.id]) }, + tabsByWorktree: { [heldWorktreeId]: [tab] } + }) + + const entry = lastSyncEntries().get(heldWorktreeId) + expect([...entry!.parkedTabIds]).toEqual([tab.id]) + expect([...entry!.restoreTitleOnStartTabIds!]).toEqual([tab.id]) + }) + it('does not allocate a parked-tab-id set per unmounted surface', async () => { await renderWatcherEffects() diff --git a/src/renderer/src/components/terminal-workspace-surface-ids.test.tsx b/src/renderer/src/components/terminal-workspace-surface-ids.test.tsx index f93b06a3b052..d21b878c2184 100644 --- a/src/renderer/src/components/terminal-workspace-surface-ids.test.tsx +++ b/src/renderer/src/components/terminal-workspace-surface-ids.test.tsx @@ -77,6 +77,7 @@ describe('workspace surface ids', () => { it('does not rebuild a surface-id array or set on a cold-activation render', () => { const ids = Array.from({ length: 423 }, (_, index) => `repo::/worktree-${index}`) const { surfaces, mapCalls } = countingSurfaces(ids) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: applyTerminalColdActivation reads only the fields listed here; the rest of the foundation is render machinery this test never exercises. const controller = { activationDeferralPlanRevisionRef: { current: 0 }, activationDeferredMountTabIdsByWorktreeRef: { current: new Map() }, @@ -89,6 +90,7 @@ describe('workspace surface ids', () => { groupsByWorktree: {}, hydrationSucceeded: false, lastActivationWorktreeIdRef: { current: null }, + startupTerminalTabHoldRef: { current: null }, layoutByWorktree: {}, mountedWorktreeIdsRef: { current: new Set(['repo::/worktree-0', 'repo::/gone']) }, pairedRuntimeParkingEnvironmentIds: new Set(), diff --git a/src/renderer/src/components/terminal/cold-activation-deferral-stranding.test.ts b/src/renderer/src/components/terminal/cold-activation-deferral-stranding.test.ts index 89737f429916..40ab1847a4e3 100644 --- a/src/renderer/src/components/terminal/cold-activation-deferral-stranding.test.ts +++ b/src/renderer/src/components/terminal/cold-activation-deferral-stranding.test.ts @@ -31,6 +31,7 @@ import { import { capturedPanesByTabId } from '../terminal-pane/terminal-parked-watcher-registry' import type { TerminalTab } from '../../../../shared/terminal-tab-types' import type { TerminalParkingFoundation } from '../use-terminal-parking-foundation' +import type { StartupTerminalTabHold } from './startup-terminal-tab-hold' const WORKTREE_ID = 'repo::/worktree' const OTHER_WORKTREE_ID = 'repo::/other-worktree' @@ -82,9 +83,11 @@ function useStrandingHarness(props: HarnessProps) { const backgroundMountTabIdsByWorktreeRef = useRef(new Map>()) const activationDeferredMountTabIdsByWorktreeRef = useRef(new Map>()) const lastActivationWorktreeIdRef = useRef(null) + const startupTerminalTabHoldRef = useRef(null) const mountedWorktreeIdsRef = useRef(new Set()) const activationDeferralPlanRevisionRef = useRef(0) const [backgroundMountRevision, setBackgroundMountRevision] = useState(0) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: applyTerminalColdActivation and the admission hook read only the fields listed here; the rest of the foundation is render machinery this harness never exercises. const foundation = { activationDeferralPlanRevisionRef, activationDeferredMountTabIdsByWorktreeRef, @@ -98,6 +101,7 @@ function useStrandingHarness(props: HarnessProps) { groupsByWorktree: {}, hydrationSucceeded: props.gateOpen, lastActivationWorktreeIdRef, + startupTerminalTabHoldRef, layoutByWorktree: {}, mountedWorktreeIdsRef, pairedRuntimeParkingEnvironmentIds: new Set(), diff --git a/src/renderer/src/components/terminal/initial-terminal-structured-launch.test.tsx b/src/renderer/src/components/terminal/initial-terminal-structured-launch.test.tsx index ec897d479da4..8d7611101371 100644 --- a/src/renderer/src/components/terminal/initial-terminal-structured-launch.test.tsx +++ b/src/renderer/src/components/terminal/initial-terminal-structured-launch.test.tsx @@ -72,6 +72,7 @@ function Watcher({ restored = true, hydrated = false, worktreeId = 'wt-1' } = {} pairedRuntimeParkingEnvironmentIds: new Set(), pendingStartupByTabId: {}, renderedActiveWorktreeId: worktreeId, + startupTerminalTabHold: null, terminalParkingEnabled: false, terminalProviderSnapshotCapabilityRevision: 0, terminalSshParkingEnabled: false, diff --git a/src/renderer/src/components/terminal/startup-terminal-tab-hold.test.ts b/src/renderer/src/components/terminal/startup-terminal-tab-hold.test.ts index 0b3f8b265328..d49d4a511cd8 100644 --- a/src/renderer/src/components/terminal/startup-terminal-tab-hold.test.ts +++ b/src/renderer/src/components/terminal/startup-terminal-tab-hold.test.ts @@ -19,7 +19,12 @@ import { revealActivationDeferredTabs, shouldMountBackgroundWorktreeTab } from './background-terminal-worktree-mount' -import { holdTerminalTabsForStartup } from './startup-terminal-tab-hold' +import { + holdTerminalTabsForStartup, + releaseStartupTerminalTabHold, + selectParkedEquivalentMountTabIds, + type StartupTerminalTabHold +} from './startup-terminal-tab-hold' import type { TabGroup, TabGroupLayoutNode } from '../../../../shared/tab-types' import type { TerminalTab } from '../../../../shared/terminal-tab-types' import type { TerminalParkingFoundation } from '../use-terminal-parking-foundation' @@ -67,6 +72,7 @@ function useStartupHoldHarness(props: HarnessProps) { const backgroundMountTabIdsByWorktreeRef = useRef(new Map>()) const activationDeferredMountTabIdsByWorktreeRef = useRef(new Map>()) const lastActivationWorktreeIdRef = useRef(null) + const startupTerminalTabHoldRef = useRef(null) const mountedWorktreeIdsRef = useRef(new Set()) const activationDeferralPlanRevisionRef = useRef(0) const [backgroundMountRevision, setBackgroundMountRevision] = useState(0) @@ -91,6 +97,7 @@ function useStartupHoldHarness(props: HarnessProps) { pendingStartupByTabId: {}, renderedActiveWorktreeId: props.worktreeId, setBackgroundMountRevision, + startupTerminalTabHoldRef, startupWorktreeRefreshCompleted: props.gateOpen, tabsByWorktree: useAppStore.getState().tabsByWorktree, terminalParkingEnabled: true, @@ -105,7 +112,8 @@ function useStartupHoldHarness(props: HarnessProps) { activationDeferredMountTabIdsByWorktreeRef, anyMountedWorktreeHasLayout: coldActivation.anyMountedWorktreeHasLayout, backgroundMountTabIdsByWorktreeRef, - mountedWorktreeIdsRef + mountedWorktreeIdsRef, + startupTerminalTabHold: coldActivation.startupTerminalTabHold } } @@ -157,6 +165,11 @@ describe('startup terminal tab hold', () => { expect(result.current.activationDeferredMountTabIdsByWorktreeRef.current.has(WORKTREE_ID)).toBe( false ) + // Held tabs stay parked-equivalent, so watchers own their bells, titles, and completions. + expect(result.current.startupTerminalTabHold).toEqual({ + worktreeId: WORKTREE_ID, + heldTabIds: new Set([TAB_1, TAB_2]) + }) act(() => { vi.advanceTimersByTime(1_000) }) @@ -167,6 +180,7 @@ describe('startup terminal tab hold', () => { expect(result.current.mountedWorktreeIdsRef.current.has(WORKTREE_ID)).toBe(true) expect(admits(restrictions, WORKTREE_ID, TAB_1)).toBe(true) expect(admits(restrictions, WORKTREE_ID, TAB_2)).toBe(true) + expect(result.current.startupTerminalTabHold).toBeNull() }) it('returns a workspace switched away from mid-startup to the unmounted world', () => { @@ -186,6 +200,42 @@ describe('startup terminal tab hold', () => { expect(admits(restrictions, OTHER_WORKTREE_ID, TAB_1)).toBe(true) }) + it('returns a workspace left for no workspace mid-startup to the unmounted world', () => { + const initialProps: HarnessProps = { worktreeId: WORKTREE_ID, gateOpen: false } + const { result, rerender } = renderHook(useStartupHoldHarness, { initialProps }) + expect(result.current.mountedWorktreeIdsRef.current.has(WORKTREE_ID)).toBe(true) + + rerender({ worktreeId: null, gateOpen: false }) + expect(result.current.mountedWorktreeIdsRef.current.has(WORKTREE_ID)).toBe(false) + expect(result.current.backgroundMountTabIdsByWorktreeRef.current.has(WORKTREE_ID)).toBe(false) + expect(result.current.startupTerminalTabHold).toBeNull() + + rerender({ worktreeId: null, gateOpen: true }) + expect(result.current.mountedWorktreeIdsRef.current.size).toBe(0) + }) + + it('keeps holding a widened hold whose targeted tab closed', () => { + const { result, rerender } = renderHook(useStartupHoldHarness, { + initialProps: { worktreeId: WORKTREE_ID, gateOpen: false } + }) + const restrictions = result.current.backgroundMountTabIdsByWorktreeRef.current + // A targeted background mount widens the hold to its tab. + restrictions.set(WORKTREE_ID, new Set([TAB_1])) + act(() => { + useAppStore.setState({ + tabsByWorktree: { + ...useAppStore.getState().tabsByWorktree, + [WORKTREE_ID]: [terminalTab(TAB_2, WORKTREE_ID)] + } + }) + }) + rerender({ worktreeId: WORKTREE_ID, gateOpen: false }) + + expect(result.current.mountedWorktreeIdsRef.current.has(WORKTREE_ID)).toBe(true) + expect(admits(restrictions, WORKTREE_ID, TAB_2)).toBe(false) + expect(result.current.startupTerminalTabHold?.heldTabIds).toEqual(new Set([TAB_2])) + }) + it('does not mount a surface with no active workspace', () => { const { result } = renderHook(useStartupHoldHarness, { initialProps: { worktreeId: null, gateOpen: false } @@ -197,37 +247,53 @@ describe('startup terminal tab hold', () => { describe('holdTerminalTabsForStartup', () => { it('admits no terminal tab of a worktree that has not mounted yet', () => { + const hold: { current: StartupTerminalTabHold | null } = { current: null } const restrictions = new Map>() - const deferred = new Map>() const mounted = new Set() - holdTerminalTabsForStartup(restrictions, deferred, mounted, 'wt-active') + holdTerminalTabsForStartup(hold, restrictions, mounted, 'wt-active', ['tab-1']) expect(restrictions.get('wt-active')).toEqual(new Set()) + expect(mounted.has('wt-active')).toBe(true) expect(shouldMountBackgroundWorktreeTab(restrictions.get('wt-active') ?? null, 'tab-1')).toBe( false ) - expect(deferred.has('wt-active')).toBe(false) + expect(hold.current).toEqual({ worktreeId: 'wt-active', heldTabIds: new Set(['tab-1']) }) }) it('keeps a targeted background mount that landed first and never narrows a full mount', () => { + const hold: { current: StartupTerminalTabHold | null } = { current: null } const restrictions = new Map>([['wt-active', new Set(['tab-1'])]]) - const deferred = new Map>() const mounted = new Set(['wt-full']) - holdTerminalTabsForStartup(restrictions, deferred, mounted, 'wt-active') + holdTerminalTabsForStartup(hold, restrictions, mounted, 'wt-active', ['tab-1', 'tab-2']) expect(restrictions.get('wt-active')).toEqual(new Set(['tab-1'])) + expect(hold.current?.heldTabIds).toEqual(new Set(['tab-2'])) - holdTerminalTabsForStartup(restrictions, deferred, mounted, 'wt-full') + releaseStartupTerminalTabHold(hold, restrictions, mounted, 'wt-full') + holdTerminalTabsForStartup(hold, restrictions, mounted, 'wt-full', ['tab-1']) expect(restrictions.has('wt-full')).toBe(false) + expect(hold.current?.heldTabIds).toEqual(new Set()) + }) + + it('keeps the held set identity while the hold is unchanged', () => { + const hold: { current: StartupTerminalTabHold | null } = { current: null } + const restrictions = new Map>() + const mounted = new Set() + holdTerminalTabsForStartup(hold, restrictions, mounted, 'wt-active', ['tab-1']) + const first = hold.current + + holdTerminalTabsForStartup(hold, restrictions, mounted, 'wt-active', ['tab-1']) + + expect(hold.current).toBe(first) }) it('survives prune and reveal passes untouched', () => { + const hold: { current: StartupTerminalTabHold | null } = { current: null } const restrictions = new Map>() const deferred = new Map>() const mounted = new Set() - holdTerminalTabsForStartup(restrictions, deferred, mounted, 'wt-active') - mounted.add('wt-active') + holdTerminalTabsForStartup(hold, restrictions, mounted, 'wt-active', ['tab-1']) expect( pruneClosedBackgroundMountTabs( @@ -248,25 +314,36 @@ describe('holdTerminalTabsForStartup', () => { expect(mounted.has('wt-active')).toBe(true) }) - it('releases holds on other worktrees but leaves targeted and activation restrictions alone', () => { - const restrictions = new Map>([ - ['wt-previous', new Set()], - ['wt-targeted', new Set(['tab-wake'])], - ['wt-activation', new Set()] - ]) - const deferred = new Map>([ - ['wt-activation', new Set(['tab-deferred'])] - ]) - const mounted = new Set(['wt-previous', 'wt-targeted', 'wt-activation']) + it('releases an unwidened hold and leaves a widened one as a targeted restriction', () => { + const hold: { current: StartupTerminalTabHold | null } = { current: null } + const restrictions = new Map>() + const mounted = new Set() + holdTerminalTabsForStartup(hold, restrictions, mounted, 'wt-previous', ['tab-1']) - holdTerminalTabsForStartup(restrictions, deferred, mounted, 'wt-active') + releaseStartupTerminalTabHold(hold, restrictions, mounted, 'wt-previous') + expect(hold.current?.worktreeId).toBe('wt-previous') + releaseStartupTerminalTabHold(hold, restrictions, mounted, null) expect(restrictions.has('wt-previous')).toBe(false) expect(mounted.has('wt-previous')).toBe(false) + expect(hold.current).toBeNull() + + holdTerminalTabsForStartup(hold, restrictions, mounted, 'wt-targeted', ['tab-wake', 'tab-2']) + restrictions.set('wt-targeted', new Set(['tab-wake'])) + releaseStartupTerminalTabHold(hold, restrictions, mounted, 'wt-active') expect(restrictions.get('wt-targeted')).toEqual(new Set(['tab-wake'])) - expect(restrictions.get('wt-activation')).toEqual(new Set()) expect(mounted.has('wt-targeted')).toBe(true) - expect(mounted.has('wt-activation')).toBe(true) - expect(restrictions.get('wt-active')).toEqual(new Set()) + }) +}) + +describe('selectParkedEquivalentMountTabIds', () => { + const hold: StartupTerminalTabHold = { worktreeId: 'wt-held', heldTabIds: new Set(['tab-1']) } + + it('prefers the activation deferral, then the hold, for the held worktree only', () => { + const deferred = new Set(['tab-deferred']) + expect(selectParkedEquivalentMountTabIds(deferred, hold, 'wt-held')).toBe(deferred) + expect(selectParkedEquivalentMountTabIds(undefined, hold, 'wt-held')).toBe(hold.heldTabIds) + expect(selectParkedEquivalentMountTabIds(undefined, hold, 'wt-other')).toBeNull() + expect(selectParkedEquivalentMountTabIds(undefined, null, 'wt-held')).toBeNull() }) }) diff --git a/src/renderer/src/components/terminal/startup-terminal-tab-hold.ts b/src/renderer/src/components/terminal/startup-terminal-tab-hold.ts index a09b12ac26f8..6398911e5c3b 100644 --- a/src/renderer/src/components/terminal/startup-terminal-tab-hold.ts +++ b/src/renderer/src/components/terminal/startup-terminal-tab-hold.ts @@ -1,44 +1,77 @@ -import { applyBackgroundMountTabRestriction } from './background-terminal-worktree-mount' +import { + applyBackgroundMountTabRestriction, + collectDeferredMountTabIds +} from './background-terminal-worktree-mount' -/** A hold is the one restriction shape nothing else produces: no admitted tabs and no - * deferral entry. Prune drops an emptied targeted restriction outright, and an activation - * restriction emptied by closes keeps its deferral entry. */ -function isStartupTerminalTabHold( - restrictions: ReadonlyMap>, - deferredMountTabIdsByWorktree: ReadonlyMap>, +export type StartupTerminalTabHold = { worktreeId: string -): boolean { - return restrictions.get(worktreeId)?.size === 0 && !deferredMountTabIdsByWorktree.has(worktreeId) + /** Tabs the hold keeps unmounted — parked-equivalent, so watchers own their side effects. */ + heldTabIds: ReadonlySet } /** - * Keeps every terminal tab of the active worktree unmounted while startup restoration is - * still publishing PTY ownership, so the workspace surface can mount from the hydrated tab - * model without a pane binding a PTY early. Must run before the worktree joins - * `mountedWorktreeIds`, like any restriction. + * Ends the hold unless `nextHeldWorktreeId` is still the held worktree. Must run before the + * activation plan, which would otherwise read the hold as a plan it had installed. + * + * Why an unwidened hold unmounts: nothing but the surface was mounted under it, so a worktree + * switched away from — or left for no workspace — mid-startup returns to the unmounted world + * where parked watchers cover it. A hold a targeted background mount widened keeps that mount's + * tabs, like any targeted restriction. + */ +export function releaseStartupTerminalTabHold( + hold: { current: StartupTerminalTabHold | null }, + restrictions: Map>, + mountedWorktreeIds: Set, + nextHeldWorktreeId: string | null +): void { + const held = hold.current + if (!held || held.worktreeId === nextHeldWorktreeId) { + return + } + hold.current = null + if (restrictions.get(held.worktreeId)?.size === 0) { + restrictions.delete(held.worktreeId) + mountedWorktreeIds.delete(held.worktreeId) + } +} + +/** + * Keeps the worktree's terminal tabs unmounted while startup restoration is still publishing + * PTY ownership, so the workspace surface can mount from the hydrated tab model without a pane + * binding a PTY early. Runs after prune, so no prune pass can drop the hold before render. * * Why an empty admitted set and no deferral entry: reveal and idle admission act only on - * worktrees with a deferral entry, and prune leaves an unchanged restriction alone, so the - * hold survives every render pass until the startup gate opens and the activation plan - * replaces it. A targeted background mount that lands meanwhile widens the hold to its - * tabs, exactly as it would widen any restriction. Holds on other worktrees are released — - * nothing was mounted under them — so a workspace switched away from mid-startup returns - * to the unmounted world where parked watchers cover it. + * worktrees with a deferral entry, so nothing admits a held tab until the startup gate opens + * and the activation plan replaces the hold. A targeted background mount widens it to its + * tabs, as it widens any restriction; a worktree already fully mounted is never narrowed. */ export function holdTerminalTabsForStartup( + hold: { current: StartupTerminalTabHold | null }, restrictions: Map>, - deferredMountTabIdsByWorktree: ReadonlyMap>, mountedWorktreeIds: Set, - worktreeId: string + worktreeId: string, + tabIds: readonly string[] ): void { - for (const [heldWorktreeId] of restrictions) { - if ( - heldWorktreeId !== worktreeId && - isStartupTerminalTabHold(restrictions, deferredMountTabIdsByWorktree, heldWorktreeId) - ) { - restrictions.delete(heldWorktreeId) - mountedWorktreeIds.delete(heldWorktreeId) - } - } applyBackgroundMountTabRestriction(restrictions, mountedWorktreeIds, worktreeId, []) + mountedWorktreeIds.add(worktreeId) + const heldTabIds = collectDeferredMountTabIds(restrictions.get(worktreeId) ?? null, tabIds) + const previous = hold.current + // Why reuse: the set feeds a memoized surface prop, so an unchanged hold keeps its identity. + if ( + previous?.worktreeId === worktreeId && + previous.heldTabIds.size === heldTabIds.size && + Array.from(heldTabIds).every((tabId) => previous.heldTabIds.has(tabId)) + ) { + return + } + hold.current = { worktreeId, heldTabIds } +} + +/** The watcher-coverage set for a mounted worktree: activation-deferred tabs, else held tabs. */ +export function selectParkedEquivalentMountTabIds( + activationDeferredMountTabIds: ReadonlySet | undefined, + hold: StartupTerminalTabHold | null, + worktreeId: string +): ReadonlySet | null { + return activationDeferredMountTabIds ?? (hold?.worktreeId === worktreeId ? hold.heldTabIds : null) } diff --git a/src/renderer/src/components/use-terminal-parking-foundation.ts b/src/renderer/src/components/use-terminal-parking-foundation.ts index c368b299471e..3123a881d209 100644 --- a/src/renderer/src/components/use-terminal-parking-foundation.ts +++ b/src/renderer/src/components/use-terminal-parking-foundation.ts @@ -12,6 +12,7 @@ import { takeAllPendingBackgroundTerminalWorktreeMounts, takePendingBackgroundTerminalWorktreeMount } from './terminal/background-terminal-worktree-mount' +import type { StartupTerminalTabHold } from './terminal/startup-terminal-tab-hold' import { combineTerminalWorktreeParkIds, useManualTerminalWorktreeParking @@ -68,6 +69,7 @@ export function useTerminalParkingFoundation(controller: TerminalEditorCloseCont const backgroundMountTabIdsByWorktreeRef = useRef(new Map>()) const activationDeferredMountTabIdsByWorktreeRef = useRef(new Map>()) const lastActivationWorktreeIdRef = useRef(null) + const startupTerminalTabHoldRef = useRef(null) // Why a ref, not state: the cold-activation pass runs during render, where a // setState would be a render-phase update; the pass returns the count instead. const activationDeferralPlanRevisionRef = useRef(0) @@ -167,6 +169,7 @@ export function useTerminalParkingFoundation(controller: TerminalEditorCloseCont backgroundMountTabIdsByWorktreeRef, activationDeferredMountTabIdsByWorktreeRef, lastActivationWorktreeIdRef, + startupTerminalTabHoldRef, activationDeferralPlanRevisionRef } } diff --git a/src/renderer/src/components/use-terminal-watcher-effects.ts b/src/renderer/src/components/use-terminal-watcher-effects.ts index e840c3f9ba05..61c3c0600613 100644 --- a/src/renderer/src/components/use-terminal-watcher-effects.ts +++ b/src/renderer/src/components/use-terminal-watcher-effects.ts @@ -15,6 +15,7 @@ import { createWorkspaceTerminalHostAuthoritySelector } from '@/lib/workspace-te import { getStructuredAgentLaunchStatus } from '@/lib/structured-agent-session-launch' import { AGENT_SESSION_PROVIDER_HANDLE_PROVIDERS } from '../../../shared/agent-session-provider-handle' import type { TerminalColdActivationController } from './terminal-cold-activation' +import { selectParkedEquivalentMountTabIds } from './terminal/startup-terminal-tab-hold' // Why shared: surfaces without watchable live tabs need no per-pass allocation. const NO_PARKED_TAB_IDS: ReadonlySet = new Set() @@ -41,6 +42,7 @@ type TerminalWatcherController = Pick< | 'pendingStartupByTabId' | 'reconcileWorktreeTabModel' | 'renderedActiveWorktreeId' + | 'startupTerminalTabHold' | 'tabsByWorktree' | 'terminalParkingEnabled' | 'terminalProviderSnapshotCapabilityRevision' @@ -73,6 +75,7 @@ export function useTerminalWatcherEffects(controller: TerminalWatcherController) pendingStartupByTabId, reconcileWorktreeTabModel, renderedActiveWorktreeId, + startupTerminalTabHold, tabsByWorktree, terminalParkingEnabled, terminalProviderSnapshotCapabilityRevision, @@ -118,7 +121,11 @@ export function useTerminalWatcherEffects(controller: TerminalWatcherController) } } } - deferredTabIds = activationDeferredMountTabIdsByWorktreeRef.current.get(workspaceId) ?? null + deferredTabIds = selectParkedEquivalentMountTabIds( + activationDeferredMountTabIdsByWorktreeRef.current.get(workspaceId), + startupTerminalTabHold, + workspaceId + ) for (const tab of tabs) { if ( deferredTabIds?.has(tab.id) && @@ -172,6 +179,7 @@ export function useTerminalWatcherEffects(controller: TerminalWatcherController) pairedRuntimeParkingEnvironmentIds, pendingStartupByTabId, renderedActiveWorktreeId, + startupTerminalTabHold, tabsByWorktree, terminalParkingEnabled, terminalProviderSnapshotCapabilityRevision, From f43a9bd3ceb9b1e6b51d64349bb47fe73136edfa Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 02:20:25 -0700 Subject: [PATCH 3/8] test(workspace): cover the split surfaces' held-tab watcher wiring and fold the held branch A held worktree now falls through to the existing else, which already resets the activation marker. --- .../components/terminal-cold-activation.ts | 5 +- ...t-workspace-surfaces-startup-hold.test.tsx | 86 +++++++++++++++++++ 2 files changed, 87 insertions(+), 4 deletions(-) create mode 100644 src/renderer/src/components/terminal-split-workspace-surfaces-startup-hold.test.tsx diff --git a/src/renderer/src/components/terminal-cold-activation.ts b/src/renderer/src/components/terminal-cold-activation.ts index ac54b125afe6..2d8cf075b572 100644 --- a/src/renderer/src/components/terminal-cold-activation.ts +++ b/src/renderer/src/components/terminal-cold-activation.ts @@ -64,10 +64,7 @@ export function applyTerminalColdActivation(controller: TerminalParkingFoundatio mountedWorktreeIdsRef.current, startupHeldWorktreeId ) - if (startupHeldWorktreeId) { - // Why null: the gate opening must run the activation plan, which replaces the hold. - lastActivationWorktreeIdRef.current = null - } else if (renderedActiveWorktreeId) { + if (renderedActiveWorktreeId && !startupHeldWorktreeId) { const worktreeTabs = tabsByWorktree[renderedActiveWorktreeId] ?? [] const coldActivationDeferralEnabled = terminalParkingEnabled && terminalTitleSnapshotAuthorityEnabled diff --git a/src/renderer/src/components/terminal-split-workspace-surfaces-startup-hold.test.tsx b/src/renderer/src/components/terminal-split-workspace-surfaces-startup-hold.test.tsx new file mode 100644 index 000000000000..b8e1040995ee --- /dev/null +++ b/src/renderer/src/components/terminal-split-workspace-surfaces-startup-hold.test.tsx @@ -0,0 +1,86 @@ +// @vitest-environment happy-dom +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { TerminalSplitWorkspaceSurfaces } from './TerminalSplitWorkspaceSurfaces' +import type { StartupTerminalTabHold } from './terminal/startup-terminal-tab-hold' +import type { TerminalController } from './use-terminal-controller' + +const mocks = vi.hoisted(() => ({ + surfaceProps: new Map | null>() +})) +vi.mock('./TerminalWorktreeSplitSurface', () => ({ + WorktreeSplitSurface: (props: { + worktreeId: string + activationDeferredMountTabIds: ReadonlySet | null + }) => { + mocks.surfaceProps.set(props.worktreeId, props.activationDeferredMountTabIds) + return null + } +})) +vi.mock('./browser-pane/host-guest/browser-guest-paint-retention', () => ({ + useAnyBrowserGuestNeedsPaint: () => false +})) +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) + +const HELD_WORKTREE_ID = 'repo::/held' +const DEFERRED_WORKTREE_ID = 'repo::/deferred' +const OTHER_WORKTREE_ID = 'repo::/other' +const WORKTREE_IDS = [HELD_WORKTREE_ID, DEFERRED_WORKTREE_ID, OTHER_WORKTREE_ID] + +let root: Root | undefined +afterEach(async () => { + await act(async () => root?.unmount()) + root = undefined + mocks.surfaceProps.clear() +}) + +async function renderSurfaces( + hold: StartupTerminalTabHold | null, + deferred: Map> +): Promise { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: TerminalSplitWorkspaceSurfaces reads only the fields listed here; the rest of the controller is machinery this render never touches. + const controller = { + activationDeferredMountTabIdsByWorktreeRef: { current: deferred }, + activeGroupIdByWorktree: {}, + activeView: 'terminal', + activityTerminalPortals: [], + anyMountedWorktreeHasLayout: true, + backgroundMountTabIdsByWorktreeRef: { current: new Map() }, + effectiveActiveLayout: { type: 'leaf', groupId: 'group-1' }, + effectiveParkedTerminalWorktreeIds: new Set(), + forceParkedTerminalWorktreeIds: new Set(), + getEffectiveLayoutForWorktree: () => ({ type: 'leaf', groupId: 'group-1' }), + measurableBackgroundWorktreeIdsRef: { current: new Set() }, + mountedWorktreeIdsRef: { current: new Set(WORKTREE_IDS) }, + renderedActiveWorktreeId: HELD_WORKTREE_ID, + startupTerminalTabHold: hold, + workspaceSurfaces: WORKTREE_IDS.map((id) => ({ id, path: `/${id}` })) + } as unknown as TerminalController + const container = document.createElement('div') + root = createRoot(container) + await act(async () => root?.render()) +} + +describe('split workspace surfaces under a startup terminal hold', () => { + it('hands each surface its parked-equivalent tabs: deferral set, else held tabs, else none', async () => { + const hold: StartupTerminalTabHold = { + worktreeId: HELD_WORKTREE_ID, + heldTabIds: new Set(['held-tab']) + } + const deferredTabIds = new Set(['deferred-tab']) + + await renderSurfaces(hold, new Map([[DEFERRED_WORKTREE_ID, deferredTabIds]])) + + // Held tabs render no pane, so the surface must hand them to parked watchers. + expect(mocks.surfaceProps.get(HELD_WORKTREE_ID)).toBe(hold.heldTabIds) + expect(mocks.surfaceProps.get(DEFERRED_WORKTREE_ID)).toBe(deferredTabIds) + expect(mocks.surfaceProps.get(OTHER_WORKTREE_ID)).toBeNull() + }) + + it('passes no held tabs once the hold is released', async () => { + await renderSurfaces(null, new Map()) + + expect(mocks.surfaceProps.get(HELD_WORKTREE_ID)).toBeNull() + }) +}) From 55e0e81d6b7ac6f9853adad956e3dd8be49638f4 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 10:47:44 -0700 Subject: [PATCH 4/8] fix(workspace): browser and editor panes wait for a connecting SSH host A restored SSH workspace now mounts its panes before the host reconnects. Derive one per-worktree host phase from the published SSH state, treating a target startup restoration has not dialed yet as connecting. The browser route holds its prepare until the host connects and re-derives a failed route on connect or a new connection generation; the editor shows the connecting state instead of a dropped connection and reloads once the host connects. --- ...ace-browser-route.host-connection.test.tsx | 126 +++++++++++ .../use-ssh-workspace-browser-route.ts | 32 ++- .../editor/local-host-test-fixture.ts | 16 ++ .../useEditorPanelContentState.test.tsx | 2 + .../editor/useEditorPanelFileContentLoader.ts | 23 +- ...anelFileLoadRetry.host-connection.test.tsx | 202 ++++++++++++++++++ .../editor/useEditorPanelFileLoadRetry.ts | 86 +++++--- ...orPanelHostUnresolvedContentState.test.tsx | 2 + ...torPanelRemoteSiblingContentState.test.tsx | 2 + ...EditorPanelVisibilityContentState.test.tsx | 2 + .../terminal-pane/terminal-pane-host-state.ts | 10 +- .../worktree-host-connection-phase.test.ts | 171 +++++++++++++++ .../src/lib/worktree-host-connection-phase.ts | 106 +++++++++ .../runtime-environment-ssh-selectors.ts | 18 ++ .../store/slices/runtime-environment-ssh.ts | 1 + 15 files changed, 759 insertions(+), 40 deletions(-) create mode 100644 src/renderer/src/components/browser-pane/use-ssh-workspace-browser-route.host-connection.test.tsx create mode 100644 src/renderer/src/components/editor/local-host-test-fixture.ts create mode 100644 src/renderer/src/components/editor/useEditorPanelFileLoadRetry.host-connection.test.tsx create mode 100644 src/renderer/src/lib/worktree-host-connection-phase.test.ts create mode 100644 src/renderer/src/lib/worktree-host-connection-phase.ts diff --git a/src/renderer/src/components/browser-pane/use-ssh-workspace-browser-route.host-connection.test.tsx b/src/renderer/src/components/browser-pane/use-ssh-workspace-browser-route.host-connection.test.tsx new file mode 100644 index 000000000000..3fa0b5293323 --- /dev/null +++ b/src/renderer/src/components/browser-pane/use-ssh-workspace-browser-route.host-connection.test.tsx @@ -0,0 +1,126 @@ +// @vitest-environment happy-dom +import { act, cleanup, renderHook } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { WorktreeHostConnection } from '@/lib/worktree-host-connection-phase' + +const mocks = vi.hoisted(() => { + const hostConnection: WorktreeHostConnection = { + phase: 'connecting', + targetId: 'target-a', + connectionGeneration: null + } + return { hostConnection, prepare: vi.fn() } +}) + +vi.mock('@/lib/worktree-runtime-owner', () => ({ + getExecutionHostIdForWorktree: () => 'ssh:target-a' +})) +vi.mock('@/lib/worktree-host-connection-phase', () => ({ + selectWorktreeHostConnectionPhase: () => mocks.hostConnection, + useWorktreeHostConnection: () => mocks.hostConnection +})) + +import { useSshWorkspaceBrowserRoute } from './use-ssh-workspace-browser-route' + +const READY_PARTITION = 'persist:orca-browser-v1-routed' + +const settle = () => + act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)) + }) + +function setHost( + phase: WorktreeHostConnection['phase'], + connectionGeneration: number | null = null +): void { + mocks.hostConnection = { phase, targetId: 'target-a', connectionGeneration } +} + +describe('useSshWorkspaceBrowserRoute under a reconnecting SSH host', () => { + beforeEach(() => { + mocks.prepare.mockReset() + Object.defineProperty(window, 'api', { + configurable: true, + value: { browser: { prepareSshWorkspacePartition: mocks.prepare } } + }) + }) + afterEach(() => cleanup()) + + it('waits while the host connects, then prepares exactly once when it connects', async () => { + setHost('connecting') + mocks.prepare.mockResolvedValue({ partition: READY_PARTITION }) + const { result, rerender } = renderHook(() => useSshWorkspaceBrowserRoute('wt-1', null)) + await settle() + expect(result.current.state).toEqual({ kind: 'preparing' }) + expect(mocks.prepare).not.toHaveBeenCalled() + + setHost('connected', 1) + rerender() + await settle() + expect(mocks.prepare).toHaveBeenCalledOnce() + expect(result.current.state).toEqual({ + kind: 'ready', + partition: READY_PARTITION, + targetId: 'target-a' + }) + }) + + it('re-derives an ssh-unavailable error without Retry once the host connects', async () => { + setHost('unavailable') + mocks.prepare.mockRejectedValueOnce(new Error('browser_local_route_ssh_unavailable')) + mocks.prepare.mockResolvedValueOnce({ partition: READY_PARTITION }) + const { result, rerender } = renderHook(() => useSshWorkspaceBrowserRoute('wt-1', null)) + await settle() + expect(result.current.state.kind).toBe('error') + + setHost('connecting') + rerender() + await settle() + // Why: the card must say it is connecting, not show the failure, while the host dials. + expect(result.current.state).toEqual({ kind: 'preparing' }) + expect(mocks.prepare).toHaveBeenCalledOnce() + + setHost('connected', 1) + rerender() + await settle() + expect(mocks.prepare).toHaveBeenCalledTimes(2) + expect(result.current.state.kind).toBe('ready') + }) + + it('re-prepares a failed route when the host reconnects under a new generation', async () => { + setHost('connected', 1) + mocks.prepare.mockRejectedValueOnce(new Error('browser_local_route_ssh_unavailable')) + mocks.prepare.mockResolvedValueOnce({ partition: READY_PARTITION }) + const { result, rerender } = renderHook(() => useSshWorkspaceBrowserRoute('wt-1', null)) + await settle() + expect(result.current.state.kind).toBe('error') + + setHost('connected', 2) + rerender() + await settle() + expect(mocks.prepare).toHaveBeenCalledTimes(2) + expect(result.current.state.kind).toBe('ready') + }) + + it('prepares once while connected and keeps a ready page mounted across a reconnect', async () => { + setHost('connected', 1) + mocks.prepare.mockResolvedValue({ partition: READY_PARTITION }) + const { result, rerender } = renderHook(() => useSshWorkspaceBrowserRoute('wt-1', null)) + await settle() + rerender() + rerender() + await settle() + expect(mocks.prepare).toHaveBeenCalledOnce() + + setHost('connecting', 1) + rerender() + await settle() + expect(result.current.state.kind).toBe('ready') + + setHost('connected', 2) + rerender() + await settle() + expect(mocks.prepare).toHaveBeenCalledOnce() + expect(result.current.state.kind).toBe('ready') + }) +}) diff --git a/src/renderer/src/components/browser-pane/use-ssh-workspace-browser-route.ts b/src/renderer/src/components/browser-pane/use-ssh-workspace-browser-route.ts index b7a1e432664f..5a06100052de 100644 --- a/src/renderer/src/components/browser-pane/use-ssh-workspace-browser-route.ts +++ b/src/renderer/src/components/browser-pane/use-ssh-workspace-browser-route.ts @@ -1,6 +1,7 @@ import { useEffect, useState } from 'react' import { useAppStore } from '@/store' import { getExecutionHostIdForWorktree } from '@/lib/worktree-runtime-owner' +import { useWorktreeHostConnection } from '@/lib/worktree-host-connection-phase' import { resolveSshWorkspaceBrowserRouteEligibility } from '@/lib/ssh-workspace-browser-route-eligibility' export type SshWorkspaceBrowserRouteErrorKind = 'forwarding-blocked' | 'ssh-unavailable' | 'unknown' @@ -64,6 +65,24 @@ export function useSshWorkspaceBrowserRoute( const [state, setState] = useState( targetId ? { kind: 'preparing' } : { kind: 'unrouted' } ) + const hostConnection = useWorktreeHostConnection(worktreeId) + const routeHost = + targetId !== null && hostConnection.targetId === targetId ? hostConnection : null + // Why a ready route is exempt: its mounted page survives a reconnect, and re-preparing + // would unmount it. Only a route still waiting on, or failed by, its host follows the host. + const routeReady = state.kind === 'ready' && state.targetId === targetId + const awaitingHost = routeHost?.phase === 'connecting' && !routeReady + const connectedHostEpoch = + routeHost?.phase === 'connected' ? `connected:${routeHost.connectionGeneration ?? ''}` : null + const [seenConnectedHostEpoch, setSeenConnectedHostEpoch] = useState(connectedHostEpoch) + if (connectedHostEpoch !== seenConnectedHostEpoch) { + setSeenConnectedHostEpoch(connectedHostEpoch) + // Why: a host that connects — or reconnects under a new generation — re-derives a route + // it failed or held, the same as Retry, but keeps the user's probe choice. + if (connectedHostEpoch !== null && !routeReady) { + setAttempt((current) => ({ ...current, count: current.count + 1 })) + } + } // Why: a persisted "Try anyway" means the user vouched for this host once // (e.g. PermitOpen allows their sites while the loopback probe is refused); @@ -74,8 +93,13 @@ export function useSshWorkspaceBrowserRoute( setState({ kind: 'unrouted' }) return } - let cancelled = false setState({ kind: 'preparing' }) + // Why: the SSH connection is still being established, so prepare could only fail with + // ssh-unavailable; the connected transition above restarts it. + if (awaitingHost) { + return + } + let cancelled = false window.api.browser .prepareSshWorkspacePartition({ targetId, @@ -100,7 +124,7 @@ export function useSshWorkspaceBrowserRoute( return () => { cancelled = true } - }, [targetId, browserProfileId, attempt, skipProbe]) + }, [targetId, browserProfileId, attempt, skipProbe, awaitingHost]) // Why (review P1-1): `state` lags one commit behind a targetId transition on // an already-mounted instance; returning stale 'unrouted' (or a stale @@ -109,7 +133,9 @@ export function useSshWorkspaceBrowserRoute( // routed/unrouted decision must be derived from targetId in-render. const effectiveState: SshWorkspaceBrowserRouteState = !targetId ? { kind: 'unrouted' } - : state.kind === 'unrouted' || (state.kind === 'ready' && state.targetId !== targetId) + : awaitingHost || + state.kind === 'unrouted' || + (state.kind === 'ready' && state.targetId !== targetId) ? { kind: 'preparing' } : state return { diff --git a/src/renderer/src/components/editor/local-host-test-fixture.ts b/src/renderer/src/components/editor/local-host-test-fixture.ts new file mode 100644 index 000000000000..d803d87133cd --- /dev/null +++ b/src/renderer/src/components/editor/local-host-test-fixture.ts @@ -0,0 +1,16 @@ +import type { WorktreeHostConnection } from '@/lib/worktree-host-connection-phase' + +/** Stands in for the host-connection module in suites that mock the store: every worktree is local. */ +const LOCAL_HOST_CONNECTION: WorktreeHostConnection = { + phase: 'local', + targetId: null, + connectionGeneration: null +} + +export function selectWorktreeHostConnectionPhase(): WorktreeHostConnection { + return LOCAL_HOST_CONNECTION +} + +export function useWorktreeHostConnection(): WorktreeHostConnection { + return LOCAL_HOST_CONNECTION +} diff --git a/src/renderer/src/components/editor/useEditorPanelContentState.test.tsx b/src/renderer/src/components/editor/useEditorPanelContentState.test.tsx index 14b704650873..6df420f6abca 100644 --- a/src/renderer/src/components/editor/useEditorPanelContentState.test.tsx +++ b/src/renderer/src/components/editor/useEditorPanelContentState.test.tsx @@ -41,6 +41,8 @@ vi.mock('@/lib/connection-context', () => ({ isWorktreeConnectionResolved: mocks.isWorktreeConnectionResolved })) +vi.mock('@/lib/worktree-host-connection-phase', () => import('./local-host-test-fixture')) + vi.mock('@/lib/runtime-workspace-file-route', () => ({ findWorkspaceFileRoute: vi.fn(() => null) })) diff --git a/src/renderer/src/components/editor/useEditorPanelFileContentLoader.ts b/src/renderer/src/components/editor/useEditorPanelFileContentLoader.ts index 005887aca11e..e7fdfc88754e 100644 --- a/src/renderer/src/components/editor/useEditorPanelFileContentLoader.ts +++ b/src/renderer/src/components/editor/useEditorPanelFileContentLoader.ts @@ -6,6 +6,7 @@ import { getDiskBaselineSignature } from './diff-content-signature' import { getRuntimeFileReadScope, readRuntimeFileContent } from '@/runtime/runtime-file-client' import { RuntimeRpcCallError, settingsForRuntimeOwner } from '@/runtime/runtime-rpc-client' import { findWorkspaceFileRoute } from '@/lib/runtime-workspace-file-route' +import { selectWorktreeHostConnectionPhase } from '@/lib/worktree-host-connection-phase' import { LOCAL_EXECUTION_HOST_ID, toRuntimeExecutionHostId, @@ -81,6 +82,7 @@ export function useEditorPanelFileContentLoader({ fileReadGenerationCounterRef.current = generation fileReadGenerationRef.current[id] = generation outstandingFileReadsRef.current[id] = generation + let readConnectionId: string | undefined try { const resolvedConnectionId = getConnectionIdForFile(worktreeId ?? null, filePath) const connectionId = resolvedConnectionId ?? undefined @@ -94,7 +96,7 @@ export function useEditorPanelFileContentLoader({ // worktree's SSH owner must never be inferred for them (a stamp still routes). const isLiveTailLogTab = restoredOpenFile?.readOnly === true && restoredOpenFile.liveTail === true - let readConnectionId = connectionId + readConnectionId = connectionId let readWorktreeId = worktreeId let readRelativePath = restoredOpenFile?.relativePath ?? relativePath if ( @@ -204,10 +206,25 @@ export function useEditorPanelFileContentLoader({ if (fileReadGenerationRef.current[id] !== generation) { return } - const message = err instanceof Error ? err.message : String(err) + const hostConnection = selectWorktreeHostConnectionPhase( + useAppStore.getState(), + worktreeId ?? null + ) + // Why: a read through an SSH host that is still connecting failed on the connection, + // not the file; the retry gate waits for it rather than showing "connection dropped". + const hostConnecting = + hostConnection.phase === 'connecting' && + readConnectionId !== undefined && + readConnectionId === hostConnection.targetId + const message = hostConnecting + ? WORKTREE_OWNER_NOT_READY_ERROR + : err instanceof Error + ? err.message + : String(err) // Why: a host may put prose on the message and the machine token on `.code`; // classifiers downstream must see the token, not only its rendering (#21041). - const loadErrorCode = err instanceof RuntimeRpcCallError ? err.code : undefined + const loadErrorCode = + !hostConnecting && err instanceof RuntimeRpcCallError ? err.code : undefined setFileContents((prev) => ({ ...prev, [id]: { diff --git a/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.host-connection.test.tsx b/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.host-connection.test.tsx new file mode 100644 index 000000000000..c974be650bd5 --- /dev/null +++ b/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.host-connection.test.tsx @@ -0,0 +1,202 @@ +// @vitest-environment happy-dom + +import { act, type Dispatch, type SetStateAction } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { OpenFile } from '@/store/slices/editor' +import type { WorktreeHostConnection } from '@/lib/worktree-host-connection-phase' +import { + WORKTREE_OWNER_NOT_READY_ERROR, + WORKTREE_OWNER_UNREACHABLE_ERROR, + type FileContent +} from './editor-panel-content-types' + +const mocks = vi.hoisted(() => { + const hostConnection: WorktreeHostConnection = { + phase: 'connecting', + targetId: 'ssh-a', + connectionGeneration: null + } + return { hostConnection, readRuntimeFileContent: vi.fn() } +}) + +vi.mock('@/lib/worktree-host-connection-phase', () => ({ + selectWorktreeHostConnectionPhase: () => mocks.hostConnection, + useWorktreeHostConnection: () => mocks.hostConnection +})) +vi.mock('@/lib/connection-context', () => ({ + getConnectionIdForFile: () => 'ssh-a', + isWorktreeConnectionResolved: () => true +})) +vi.mock('@/runtime/runtime-file-client', () => ({ + getRuntimeFileReadScope: (_settings: unknown, connectionId: string | undefined) => + connectionId ?? 'local', + readRuntimeFileContent: mocks.readRuntimeFileContent +})) + +import { + OWNER_NOT_READY_RETRY_DELAY_MS, + useEditorPanelFileLoadRetry +} from './useEditorPanelFileLoadRetry' +import { + useEditorPanelFileContentLoader, + type EditorPanelFileContentLoader +} from './useEditorPanelFileContentLoader' + +const SSH_PROVIDER_UNAVAILABLE = + 'Remote connection dropped. Click Reconnect on the SSH target before retrying.' + +function setHost( + phase: WorktreeHostConnection['phase'], + connectionGeneration: number | null = null +): void { + mocks.hostConnection = { phase, targetId: 'ssh-a', connectionGeneration } +} + +const file: OpenFile = { + id: 'tab-1', + filePath: '/home/user/project/src/index.ts', + relativePath: 'src/index.ts', + worktreeId: 'repo-ssh::/home/user/project', + language: 'typescript', + isDirty: false, + mode: 'edit' +} +const OPEN_FILES_REF = { current: [file] } + +function RetryHarness({ + fileContents, + attemptsRef, + loadFileContent, + setFileContents +}: { + fileContents: Record + attemptsRef: { current: Record } + loadFileContent: () => Promise + setFileContents: Dispatch>> +}): null { + useEditorPanelFileLoadRetry({ + activeFile: file, + fileContents, + fileLoadRetryAttemptsRef: attemptsRef, + loadFileContent, + openFilesRef: OPEN_FILES_REF, + setFileContents + }) + return null +} + +describe('editor file loads while the SSH host connects', () => { + let container: HTMLDivElement + let root: Root + + beforeEach(() => { + vi.useFakeTimers() + mocks.readRuntimeFileContent.mockReset() + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) + }) + + afterEach(() => { + act(() => root.unmount()) + container.remove() + vi.useRealTimers() + }) + + it('shows the connecting copy, not "connection dropped", for a read that failed mid-connect', async () => { + setHost('connecting') + mocks.readRuntimeFileContent.mockRejectedValue(new Error(SSH_PROVIDER_UNAVAILABLE)) + let fileContents: Record = {} + let load: EditorPanelFileContentLoader | null = null + function LoaderHarness(): null { + load = useEditorPanelFileContentLoader({ + fileLoadRetryAttemptsRef: { current: {} }, + fileReadGenerationCounterRef: { current: 0 }, + fileReadGenerationRef: { current: {} }, + openFilesRef: OPEN_FILES_REF, + outstandingFileReadsRef: { current: {} }, + setFileContents: (updater) => { + fileContents = typeof updater === 'function' ? updater(fileContents) : updater + } + }) + return null + } + act(() => root.render()) + await act(async () => load?.(file.filePath, file.id, file.worktreeId, file.relativePath)) + expect(fileContents[file.id]?.loadError).toBe(WORKTREE_OWNER_NOT_READY_ERROR) + + setHost('unavailable') + await act(async () => load?.(file.filePath, file.id, file.worktreeId, file.relativePath)) + expect(fileContents[file.id]?.loadError).toBe(SSH_PROVIDER_UNAVAILABLE) + }) + + it('spends no retry budget while connecting, then reloads exactly once when the host connects', () => { + setHost('connecting') + const attemptsRef: { current: Record } = { current: {} } + let fileContents: Record = { + [file.id]: { content: '', isBinary: false, loadError: WORKTREE_OWNER_NOT_READY_ERROR } + } + const setFileContents: Dispatch>> = (updater) => { + fileContents = typeof updater === 'function' ? updater(fileContents) : updater + } + const loadFileContent = vi.fn(async () => undefined) + const render = (): void => + act(() => + root.render( + + ) + ) + + render() + act(() => vi.advanceTimersByTime(OWNER_NOT_READY_RETRY_DELAY_MS * 10)) + expect(loadFileContent).not.toHaveBeenCalled() + expect(attemptsRef.current[file.id]).toBeUndefined() + + setHost('connected', 1) + render() + expect(loadFileContent).toHaveBeenCalledOnce() + expect(attemptsRef.current[file.id]).toBe(0) + expect(fileContents[file.id]).toBeUndefined() + + render() + act(() => vi.advanceTimersByTime(OWNER_NOT_READY_RETRY_DELAY_MS * 10)) + expect(loadFileContent).toHaveBeenCalledOnce() + }) + + it('re-arms an exhausted budget when the host reconnects under a new generation', () => { + setHost('connected', 1) + const attemptsRef: { current: Record } = { current: { [file.id]: 3 } } + let fileContents: Record = { + [file.id]: { content: '', isBinary: false, loadError: WORKTREE_OWNER_UNREACHABLE_ERROR } + } + const setFileContents: Dispatch>> = (updater) => { + fileContents = typeof updater === 'function' ? updater(fileContents) : updater + } + const loadFileContent = vi.fn(async () => undefined) + const render = (): void => + act(() => + root.render( + + ) + ) + + render() + expect(loadFileContent).not.toHaveBeenCalled() + + setHost('connected', 2) + render() + expect(loadFileContent).toHaveBeenCalledOnce() + expect(attemptsRef.current[file.id]).toBe(0) + }) +}) diff --git a/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.ts b/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.ts index 571ccf548c05..c6f98871535d 100644 --- a/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.ts +++ b/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.ts @@ -1,5 +1,6 @@ -import { useEffect, type Dispatch, type MutableRefObject, type SetStateAction } from 'react' +import { useEffect, useRef, type Dispatch, type MutableRefObject, type SetStateAction } from 'react' import type { OpenFile } from '@/store/slices/editor' +import { useWorktreeHostConnection } from '@/lib/worktree-host-connection-phase' import { hasRuntimeRpcErrorCode } from '../../../../shared/runtime-rpc-error-code' import { WORKTREE_HOST_SELECTOR_NOT_FOUND_CODE, @@ -79,13 +80,62 @@ export function useEditorPanelFileLoadRetry({ const activeFileLoadErrorCode = activeFileLoadRetryId ? fileContents[activeFileLoadRetryId]?.loadErrorCode : undefined + const hostConnection = useWorktreeHostConnection(activeFile?.worktreeId ?? null) + const hostTargetId = hostConnection.targetId + const hostConnecting = hostConnection.phase === 'connecting' + const connectedHostEpoch = + hostConnection.phase === 'connected' ? `${hostConnection.connectionGeneration ?? ''}` : null + const seenHostRef = useRef({ targetId: hostTargetId, connectedEpoch: connectedHostEpoch }) useEffect(() => { + // Why the same target: switching to a file on another host is not that host connecting. + const hostJustConnected = + connectedHostEpoch !== null && + seenHostRef.current.targetId === hostTargetId && + seenHostRef.current.connectedEpoch !== connectedHostEpoch + seenHostRef.current = { targetId: hostTargetId, connectedEpoch: connectedHostEpoch } + if (!activeFileLoadRetryId || !activeFileLoadError) { + return + } + const reload = (nextRetryCount: number): void => { + const currentFile = openFilesRef.current.find((file) => file.id === activeFileLoadRetryId) + if ( + !currentFile || + (currentFile.mode !== 'edit' && currentFile.mode !== 'markdown-preview') + ) { + return + } + fileLoadRetryAttemptsRef.current[activeFileLoadRetryId] = nextRetryCount + setFileContents((prev) => { + if (prev[currentFile.id]?.loadError !== activeFileLoadError) { + return prev + } + const next = { ...prev } + delete next[currentFile.id] + return next + }) + void loadFileContent( + currentFile.filePath, + currentFile.id, + currentFile.worktreeId, + currentFile.relativePath + ) + } + // Why: the connected transition below re-arms the read, so waiting spends no budget. + if (hostConnecting) { + return + } + // Why: a host that just connected (or reconnected) can serve a read a lost connection + // failed — including one whose budget already ran out — so reload once on a fresh budget. if ( - !activeFileLoadRetryId || - !activeFileLoadError || - !shouldRetryFileLoadError(activeFileLoadError, activeFileLoadErrorCode) + hostJustConnected && + (activeFileLoadError === WORKTREE_OWNER_UNREACHABLE_ERROR || + shouldRetryFileLoadError(activeFileLoadError, activeFileLoadErrorCode)) ) { + reload(0) + return + } + if (!shouldRetryFileLoadError(activeFileLoadError, activeFileLoadErrorCode)) { return } const ownerNotReady = isOwnerNotReadyError(activeFileLoadError) @@ -127,35 +177,15 @@ export function useEditorPanelFileLoadRetry({ const delayMs = ownerNotReady ? OWNER_NOT_READY_RETRY_DELAY_MS : (FILE_LOAD_RETRY_DELAYS_MS[retryCount] ?? FILE_LOAD_RETRY_DELAYS_MS[0]) - const timeoutId = window.setTimeout(() => { - const currentFile = openFilesRef.current.find((file) => file.id === activeFileLoadRetryId) - if ( - !currentFile || - (currentFile.mode !== 'edit' && currentFile.mode !== 'markdown-preview') - ) { - return - } - fileLoadRetryAttemptsRef.current[activeFileLoadRetryId] = retryCount + 1 - setFileContents((prev) => { - if (prev[currentFile.id]?.loadError !== activeFileLoadError) { - return prev - } - const next = { ...prev } - delete next[currentFile.id] - return next - }) - void loadFileContent( - currentFile.filePath, - currentFile.id, - currentFile.worktreeId, - currentFile.relativePath - ) - }, delayMs) + const timeoutId = window.setTimeout(() => reload(retryCount + 1), delayMs) return () => window.clearTimeout(timeoutId) }, [ activeFileLoadRetryId, activeFileLoadError, activeFileLoadErrorCode, + connectedHostEpoch, + hostConnecting, + hostTargetId, fileLoadRetryAttemptsRef, loadFileContent, openFilesRef, diff --git a/src/renderer/src/components/editor/useEditorPanelHostUnresolvedContentState.test.tsx b/src/renderer/src/components/editor/useEditorPanelHostUnresolvedContentState.test.tsx index ddd9938c42e8..c6ff09f8c97a 100644 --- a/src/renderer/src/components/editor/useEditorPanelHostUnresolvedContentState.test.tsx +++ b/src/renderer/src/components/editor/useEditorPanelHostUnresolvedContentState.test.tsx @@ -33,6 +33,8 @@ vi.mock('@/lib/connection-context', () => ({ isWorktreeConnectionResolved: vi.fn(() => true) })) +vi.mock('@/lib/worktree-host-connection-phase', () => import('./local-host-test-fixture')) + vi.mock('@/lib/runtime-workspace-file-route', () => ({ findWorkspaceFileRoute: vi.fn(() => null) })) diff --git a/src/renderer/src/components/editor/useEditorPanelRemoteSiblingContentState.test.tsx b/src/renderer/src/components/editor/useEditorPanelRemoteSiblingContentState.test.tsx index 6666302d0a9d..08fcc4df79a3 100644 --- a/src/renderer/src/components/editor/useEditorPanelRemoteSiblingContentState.test.tsx +++ b/src/renderer/src/components/editor/useEditorPanelRemoteSiblingContentState.test.tsx @@ -37,6 +37,8 @@ vi.mock('@/lib/connection-context', () => ({ isWorktreeConnectionResolved: vi.fn(() => true) })) +vi.mock('@/lib/worktree-host-connection-phase', () => import('./local-host-test-fixture')) + vi.mock('@/lib/runtime-workspace-file-route', () => ({ findWorkspaceFileRoute: mocks.findWorkspaceFileRoute })) diff --git a/src/renderer/src/components/editor/useEditorPanelVisibilityContentState.test.tsx b/src/renderer/src/components/editor/useEditorPanelVisibilityContentState.test.tsx index 317fa6257793..818f50107beb 100644 --- a/src/renderer/src/components/editor/useEditorPanelVisibilityContentState.test.tsx +++ b/src/renderer/src/components/editor/useEditorPanelVisibilityContentState.test.tsx @@ -32,6 +32,8 @@ vi.mock('@/lib/connection-context', () => ({ isWorktreeConnectionResolved: vi.fn(() => true) })) +vi.mock('@/lib/worktree-host-connection-phase', () => import('./local-host-test-fixture')) + vi.mock('@/lib/runtime-workspace-file-route', () => ({ findWorkspaceFileRoute: vi.fn(() => null) })) diff --git a/src/renderer/src/components/terminal-pane/terminal-pane-host-state.ts b/src/renderer/src/components/terminal-pane/terminal-pane-host-state.ts index 6b40bdf379cd..967f78b2e820 100644 --- a/src/renderer/src/components/terminal-pane/terminal-pane-host-state.ts +++ b/src/renderer/src/components/terminal-pane/terminal-pane-host-state.ts @@ -1,6 +1,6 @@ import type { AppState } from '@/store/types' import { getConnectionIdFromState } from '@/lib/connection-context' -import { getExplicitRuntimeEnvironmentIdForWorktree } from '@/lib/worktree-runtime-owner' +import { resolveWorktreeSshTarget } from '@/lib/worktree-host-connection-phase' import { isNativeChatTranscriptLocalReadable } from '@/lib/native-chat-transcript-readability' import { selectRuntimeAwareSshError, @@ -8,7 +8,6 @@ import { selectRuntimeAwareSshTargetLabel, selectRuntimeAwareSshTargetRemoved } from '@/store/slices/runtime-environment-ssh' -import { isRuntimeOwnedSshTargetId } from '../../../../shared/execution-host' export type TerminalPaneHostState = { nativeChatTranscriptIsLocalReadable: boolean @@ -25,9 +24,8 @@ function computeTerminalPaneHostState(state: AppState, worktreeId: string): Term const connectionId = getConnectionIdFromState(state, worktreeId) const nativeChatTranscriptIsLocalReadableResult = isNativeChatTranscriptLocalReadable(connectionId) - const sshReconnectTargetId = - connectionId && !isRuntimeOwnedSshTargetId(connectionId) ? connectionId : null - if (!sshReconnectTargetId) { + const sshTarget = resolveWorktreeSshTarget(state, worktreeId, connectionId) + if (!sshTarget) { return { nativeChatTranscriptIsLocalReadable: nativeChatTranscriptIsLocalReadableResult, sshReconnectEnvironmentId: null, @@ -38,7 +36,7 @@ function computeTerminalPaneHostState(state: AppState, worktreeId: string): Term sshReconnectTargetRemoved: false } } - const sshReconnectEnvironmentId = getExplicitRuntimeEnvironmentIdForWorktree(state, worktreeId) + const { targetId: sshReconnectTargetId, environmentId: sshReconnectEnvironmentId } = sshTarget return { nativeChatTranscriptIsLocalReadable: nativeChatTranscriptIsLocalReadableResult, sshReconnectEnvironmentId, diff --git a/src/renderer/src/lib/worktree-host-connection-phase.test.ts b/src/renderer/src/lib/worktree-host-connection-phase.test.ts new file mode 100644 index 000000000000..7bfde90a4e35 --- /dev/null +++ b/src/renderer/src/lib/worktree-host-connection-phase.test.ts @@ -0,0 +1,171 @@ +import { describe, expect, it } from 'vitest' +import type { AppState } from '@/store/types' +import type { SshConnectionStatus } from '../../../shared/ssh-types' +import { selectWorktreeHostConnectionPhase } from './worktree-host-connection-phase' + +function makeState(overrides: Record): AppState { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the phase selector reads only the repo, worktree, runtime, and SSH fields set here. + return { + activeWorktreeId: null, + detectedWorktreesByRepo: {}, + folderWorkspaces: [], + projectGroups: [], + removedSshTargetLabels: new Map(), + repos: [], + runtimeStatusByEnvironmentId: new Map(), + sshConnectionStates: new Map(), + sshStateByEnvironment: new Map(), + sshTargetLabels: new Map(), + sshTargetsHydrated: true, + terminalStartupRestorationReady: true, + worktreesByRepo: {}, + ...overrides + } as unknown as AppState +} + +function makeSshState( + status: SshConnectionStatus | null, + overrides: Record = {} +): AppState { + return makeState({ + repos: [{ id: 'repo-ssh', connectionId: 'ssh-a' }], + sshConnectionStates: new Map( + status + ? [ + [ + 'ssh-a', + { + targetId: 'ssh-a', + status, + error: null, + reconnectAttempt: 0, + connectionGeneration: 7 + } + ] + ] + : [] + ), + worktreesByRepo: { 'repo-ssh': [{ id: 'wt-ssh', repoId: 'repo-ssh' }] }, + ...overrides + }) +} + +describe('selectWorktreeHostConnectionPhase', () => { + it('reports a local workspace, and no worktree, as local', () => { + const state = makeState({ + repos: [{ id: 'repo-local' }], + worktreesByRepo: { 'repo-local': [{ id: 'wt-local', repoId: 'repo-local' }] } + }) + + const local = { phase: 'local', targetId: null, connectionGeneration: null } + expect(selectWorktreeHostConnectionPhase(state, 'wt-local')).toEqual(local) + expect(selectWorktreeHostConnectionPhase(state, null)).toEqual(local) + }) + + it('reports a runtime-owned target as local: this client never dials it', () => { + const state = makeState({ + repos: [{ id: 'repo-ephemeral', connectionId: 'runtime-ssh-vm-a' }], + worktreesByRepo: { 'repo-ephemeral': [{ id: 'wt-ephemeral', repoId: 'repo-ephemeral' }] } + }) + + expect(selectWorktreeHostConnectionPhase(state, 'wt-ephemeral').phase).toBe('local') + }) + + it('reads an unpublished target as connecting only until startup restoration finishes', () => { + expect( + selectWorktreeHostConnectionPhase( + makeSshState(null, { terminalStartupRestorationReady: false }), + 'wt-ssh' + ) + ).toEqual({ phase: 'connecting', targetId: 'ssh-a', connectionGeneration: null }) + expect(selectWorktreeHostConnectionPhase(makeSshState(null), 'wt-ssh')).toEqual({ + phase: 'unavailable', + targetId: 'ssh-a', + connectionGeneration: null + }) + }) + + it('maps published statuses and carries the connection generation', () => { + expect(selectWorktreeHostConnectionPhase(makeSshState('connecting'), 'wt-ssh')).toEqual({ + phase: 'connecting', + targetId: 'ssh-a', + connectionGeneration: 7 + }) + expect(selectWorktreeHostConnectionPhase(makeSshState('reconnecting'), 'wt-ssh').phase).toBe( + 'connecting' + ) + expect(selectWorktreeHostConnectionPhase(makeSshState('deploying-relay'), 'wt-ssh').phase).toBe( + 'connecting' + ) + expect(selectWorktreeHostConnectionPhase(makeSshState('connected'), 'wt-ssh')).toEqual({ + phase: 'connected', + targetId: 'ssh-a', + connectionGeneration: 7 + }) + }) + + it('reports failed and disconnected targets as unavailable once restoration is done', () => { + for (const status of ['reconnection-failed', 'disconnected', 'auth-failed', 'error'] as const) { + expect(selectWorktreeHostConnectionPhase(makeSshState(status), 'wt-ssh').phase).toBe( + 'unavailable' + ) + } + }) + + it('keeps a published failure unavailable even before restoration finishes', () => { + expect( + selectWorktreeHostConnectionPhase( + makeSshState('auth-failed', { terminalStartupRestorationReady: false }), + 'wt-ssh' + ).phase + ).toBe('unavailable') + }) + + it("reads a runtime environment's nested target from that environment's SSH state", () => { + const state = makeState({ + repos: [{ id: 'repo-runtime', connectionId: 'ssh-nested', executionHostId: 'runtime:env-a' }], + runtimeStatusByEnvironmentId: new Map([ + ['env-a', { status: { runtimeId: 'runtime-a' }, checkedAt: 1 }] + ]), + sshStateByEnvironment: new Map([ + [ + 'env-a', + { + connectionStates: new Map([ + [ + 'ssh-nested', + { + targetId: 'ssh-nested', + status: 'connected', + error: null, + reconnectAttempt: 0, + connectionGeneration: 3 + } + ] + ]), + targetLabels: new Map([['ssh-nested', 'build box']]), + removedTargetLabels: new Map(), + targetsHydrated: true + } + ] + ]), + terminalStartupRestorationReady: false, + worktreesByRepo: { + 'repo-runtime': [ + { + id: 'wt-runtime', + repoId: 'repo-runtime', + hostId: 'runtime:env-a', + runtimeOwnerEnvironmentId: 'env-a' + } + ] + } + }) + + expect(selectWorktreeHostConnectionPhase(state, 'wt-runtime')).toEqual({ + phase: 'connected', + targetId: 'ssh-nested', + connectionGeneration: 3 + }) + }) +}) diff --git a/src/renderer/src/lib/worktree-host-connection-phase.ts b/src/renderer/src/lib/worktree-host-connection-phase.ts new file mode 100644 index 000000000000..ada4428df03a --- /dev/null +++ b/src/renderer/src/lib/worktree-host-connection-phase.ts @@ -0,0 +1,106 @@ +import { useShallow } from 'zustand/react/shallow' +import { useAppStore } from '@/store' +import type { AppState } from '@/store/types' +import { getConnectionIdFromState } from '@/lib/connection-context' +import { getExplicitRuntimeEnvironmentIdForWorktree } from '@/lib/worktree-runtime-owner' +import { + selectRuntimeAwareSshConnectionGeneration, + selectRuntimeAwareSshStatus +} from '@/store/slices/runtime-environment-ssh' +import { isConnectingSshStatus } from '@/ssh/ssh-connection-recoverability' +import { isRuntimeOwnedSshTargetId } from '../../../shared/execution-host' + +/** + * `local`: no SSH target this client dials for the worktree — a local workspace, a + * runtime-owned target, or an owner that has not resolved yet. + */ +export type WorktreeHostConnectionPhase = 'local' | 'connecting' | 'connected' | 'unavailable' + +export type WorktreeHostConnection = { + phase: WorktreeHostConnectionPhase + targetId: string | null + /** Bumps on every reconnect, so a consumer can re-derive what it prepared on the old one. */ + connectionGeneration: number | null +} + +export type WorktreeSshTarget = { + targetId: string + /** The remote runtime whose mirrored SSH state owns the target; null for this client's own. */ + environmentId: string | null +} + +const LOCAL_HOST_CONNECTION: WorktreeHostConnection = { + phase: 'local', + targetId: null, + connectionGeneration: null +} + +/** The SSH target a worktree's panes reach through, or null when this client dials none. */ +export function resolveWorktreeSshTarget( + state: AppState, + worktreeId: string, + connectionId: string | null | undefined +): WorktreeSshTarget | null { + if (!connectionId || isRuntimeOwnedSshTargetId(connectionId)) { + return null + } + return { + targetId: connectionId, + environmentId: getExplicitRuntimeEnvironmentIdForWorktree(state, worktreeId) + } +} + +function deriveSshTargetPhase( + state: AppState, + target: WorktreeSshTarget +): WorktreeHostConnectionPhase { + const status = selectRuntimeAwareSshStatus(state, target.environmentId, target.targetId) + if (status === 'connected') { + return 'connected' + } + if (isConnectingSshStatus(status)) { + return 'connecting' + } + // Why: startup restoration dials the targets that were live at shutdown; until it publishes, + // a missing entry means "not dialed yet", not "disconnected". Restoration finishing (or + // degrading) ends this on its own. + if ( + target.environmentId === null && + !state.terminalStartupRestorationReady && + !state.sshConnectionStates.has(target.targetId) + ) { + return 'connecting' + } + return 'unavailable' +} + +/** Whether a worktree's SSH host is reachable yet, derived from the published SSH state. */ +export function selectWorktreeHostConnectionPhase( + state: AppState, + worktreeId: string | null +): WorktreeHostConnection { + if (!worktreeId) { + return LOCAL_HOST_CONNECTION + } + const target = resolveWorktreeSshTarget( + state, + worktreeId, + getConnectionIdFromState(state, worktreeId) + ) + if (!target) { + return LOCAL_HOST_CONNECTION + } + return { + phase: deriveSshTargetPhase(state, target), + targetId: target.targetId, + connectionGeneration: selectRuntimeAwareSshConnectionGeneration( + state, + target.environmentId, + target.targetId + ) + } +} + +export function useWorktreeHostConnection(worktreeId: string | null): WorktreeHostConnection { + return useAppStore(useShallow((state) => selectWorktreeHostConnectionPhase(state, worktreeId))) +} diff --git a/src/renderer/src/store/slices/runtime-environment-ssh-selectors.ts b/src/renderer/src/store/slices/runtime-environment-ssh-selectors.ts index 7cd1942db3a1..90f092220997 100644 --- a/src/renderer/src/store/slices/runtime-environment-ssh-selectors.ts +++ b/src/renderer/src/store/slices/runtime-environment-ssh-selectors.ts @@ -60,6 +60,24 @@ export function selectRuntimeAwareSshError( return bucket.connectionStates.get(targetId)?.error ?? null } +export function selectRuntimeAwareSshConnectionGeneration( + state: RuntimeAwareSshReadState, + environmentId: string | null, + targetId: string +): number | null { + if (environmentId === null) { + return state.sshConnectionStates.get(targetId)?.connectionGeneration ?? null + } + if (!isEnvironmentReachable(state, environmentId)) { + return null + } + const bucket = state.sshStateByEnvironment.get(environmentId) + if (!bucket?.targetsHydrated) { + return null + } + return bucket.connectionStates.get(targetId)?.connectionGeneration ?? null +} + export function selectRuntimeAwareSshTargetLabel( state: RuntimeAwareSshReadState, environmentId: string | null, diff --git a/src/renderer/src/store/slices/runtime-environment-ssh.ts b/src/renderer/src/store/slices/runtime-environment-ssh.ts index 3efbf0e78053..e6b2f30db615 100644 --- a/src/renderer/src/store/slices/runtime-environment-ssh.ts +++ b/src/renderer/src/store/slices/runtime-environment-ssh.ts @@ -4,6 +4,7 @@ import type { SshConnectionState, SshTargetSummary } from '../../../../shared/ss import { sanitizeSshTargetGeneration } from '../../../../shared/ssh-target-generation' import { sshConnectionStatesEqual, sshTargetLabelsEqual } from './ssh-target-cleanup' export { + selectRuntimeAwareSshConnectionGeneration, selectRuntimeAwareSshError, selectRuntimeAwareSshStatus, selectRuntimeAwareSshTargetLabel, From 0c40d85e0a6ce5c3f72a322e4be0a6eaf5a0900a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 10:47:55 -0700 Subject: [PATCH 5/8] fix(workspace): a held terminal tab shows that it is restoring While startup restoration holds terminal panes unmounted, the visible tab's slot was blank. Fill the slot of a visible held tab, including one created during the hold, with a restoring state until its pane mounts. --- .../TerminalLegacyTerminalPanes.tsx | 84 +++---- .../TerminalPaneOverlayLayer.tsx | 74 +++--- .../TerminalRestoringPlaceholder.tsx | 20 ++ ...terminal-startup-hold-placeholder.test.tsx | 222 ++++++++++++++++++ src/renderer/src/i18n/locales/en.json | 3 + src/renderer/src/i18n/locales/es.json | 3 + src/renderer/src/i18n/locales/fr.json | 3 + src/renderer/src/i18n/locales/ja.json | 3 + src/renderer/src/i18n/locales/ko.json | 3 + src/renderer/src/i18n/locales/zh.json | 3 + 10 files changed, 347 insertions(+), 71 deletions(-) create mode 100644 src/renderer/src/components/terminal-pane/TerminalRestoringPlaceholder.tsx create mode 100644 src/renderer/src/components/terminal-startup-hold-placeholder.test.tsx diff --git a/src/renderer/src/components/TerminalLegacyTerminalPanes.tsx b/src/renderer/src/components/TerminalLegacyTerminalPanes.tsx index f095b77e0e17..b054a05b7172 100644 --- a/src/renderer/src/components/TerminalLegacyTerminalPanes.tsx +++ b/src/renderer/src/components/TerminalLegacyTerminalPanes.tsx @@ -1,5 +1,6 @@ import { createPortal } from 'react-dom' import TerminalPane from './terminal-pane/TerminalPane' +import { TerminalRestoringPlaceholder } from './terminal-pane/TerminalRestoringPlaceholder' import { findActivityTerminalPortal } from './activity/activity-terminal-portal' import { shouldMountBackgroundWorktreeTab } from './terminal/background-terminal-worktree-mount' import type { TerminalController } from './use-terminal-controller' @@ -59,51 +60,54 @@ export function TerminalLegacyTerminalPanes({ } aria-hidden={!isVisible} > - {(tabsByWorktree[workspace.id] ?? []) - .filter((tab) => - shouldMountBackgroundWorktreeTab( + {(tabsByWorktree[workspace.id] ?? []).map((tab) => { + const isActiveTerminalTab = + isVisible && tab.id === activeTabId && activeTabType === 'terminal' + if ( + !shouldMountBackgroundWorktreeTab( backgroundMountTabIdsByWorktreeRef.current.get(workspace.id) ?? null, tab.id ) + ) { + // Why only the startup hold lands here visible: reveal admits every other + // visible deferred tab in the same render pass. + return isActiveTerminalTab ? : null + } + const activityTerminalPortal = findActivityTerminalPortal(activityTerminalPortals, { + worktreeId: workspace.id, + tabId: tab.id + }) + const isActivityPortalTab = activityTerminalPortal !== null + if ( + shouldColdParkTerminalPanes && + !isActivityPortalTab && + !evictionExemptTerminalTabIds.has(tab.id) + ) { + return null + } + const terminalPane = ( + handlePtyExit(tab.id, ptyId, exitCode)} + onCloseTab={() => handleCloseTab(tab.id)} + /> ) - .map((tab) => { - const activityTerminalPortal = findActivityTerminalPortal( - activityTerminalPortals, - { worktreeId: workspace.id, tabId: tab.id } + if (activityTerminalPortal) { + return createPortal( + terminalPane, + activityTerminalPortal.target, + `activity-terminal-${tab.id}` ) - const isActivityPortalTab = activityTerminalPortal !== null - const isActiveTerminalTab = - isVisible && tab.id === activeTabId && activeTabType === 'terminal' - if ( - shouldColdParkTerminalPanes && - !isActivityPortalTab && - !evictionExemptTerminalTabIds.has(tab.id) - ) { - return null - } - const terminalPane = ( - handlePtyExit(tab.id, ptyId, exitCode)} - onCloseTab={() => handleCloseTab(tab.id)} - /> - ) - if (activityTerminalPortal) { - return createPortal( - terminalPane, - activityTerminalPortal.target, - `activity-terminal-${tab.id}` - ) - } - return terminalPane - })} + } + return terminalPane + })} ) })} diff --git a/src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx b/src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx index 2cb20783f53e..63e75e9cdd57 100644 --- a/src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx @@ -9,7 +9,9 @@ import { } from '../activity/activity-terminal-portal' import { shouldMountBackgroundWorktreeTab } from '../terminal/background-terminal-worktree-mount' import { useNativeChatToggleShortcut } from '../native-chat/use-native-chat-toggle-shortcut' +import { RetainedPaneHost } from '../tab-group/RetainedPaneHost' import { TerminalOverlaySlot } from './TerminalOverlaySlot' +import { TerminalRestoringPlaceholder } from './TerminalRestoringPlaceholder' import { useTerminalTabColdParking } from './use-terminal-tab-cold-parking' type TerminalOverlayAssignment = { @@ -132,40 +134,50 @@ const TerminalPaneOverlayLayer = memo(function TerminalPaneOverlayLayer({ return ( <> - {terminalTabs - .filter((terminalTab) => - shouldMountBackgroundWorktreeTab(backgroundMountTabIds, terminalTab.id) - ) - .map((terminalTab) => { - const assignment = assignments.get(terminalTab.id) - const isVisible = Boolean(isWorktreeActive && assignment?.isActiveInGroup) - const isActive = Boolean(isVisible && assignment?.groupId === activeGroupId) - const activityTerminalPortal = findActivityTerminalPortal(activityTerminalPortals, { - worktreeId, - tabId: terminalTab.id - }) - if (parkedTerminalTabIds.has(terminalTab.id)) { - return null - } - return ( - { + const assignment = assignments.get(terminalTab.id) + const isVisible = Boolean(isWorktreeActive && assignment?.isActiveInGroup) + if (!shouldMountBackgroundWorktreeTab(backgroundMountTabIds, terminalTab.id)) { + // Why only the startup hold lands here visible: reveal admits every other visible + // deferred tab in the same render pass. + return isVisible ? ( + - ) - })} + > + + + ) : null + } + const isActive = Boolean(isVisible && assignment?.groupId === activeGroupId) + const activityTerminalPortal = findActivityTerminalPortal(activityTerminalPortals, { + worktreeId, + tabId: terminalTab.id + }) + if (parkedTerminalTabIds.has(terminalTab.id)) { + return null + } + return ( + + ) + })} ) }) diff --git a/src/renderer/src/components/terminal-pane/TerminalRestoringPlaceholder.tsx b/src/renderer/src/components/terminal-pane/TerminalRestoringPlaceholder.tsx new file mode 100644 index 000000000000..4a2bb775e0d2 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/TerminalRestoringPlaceholder.tsx @@ -0,0 +1,20 @@ +import { Loader2 } from 'lucide-react' +import { translate } from '@/i18n/i18n' + +/** Fills a terminal tab's slot while startup restoration holds its pane unmounted. */ +export function TerminalRestoringPlaceholder(): React.JSX.Element { + return ( +
+ + {translate( + 'auto.components.terminal.pane.TerminalRestoringPlaceholder.restoring', + 'Restoring terminal…' + )} +
+ ) +} diff --git a/src/renderer/src/components/terminal-startup-hold-placeholder.test.tsx b/src/renderer/src/components/terminal-startup-hold-placeholder.test.tsx new file mode 100644 index 000000000000..be648b543b48 --- /dev/null +++ b/src/renderer/src/components/terminal-startup-hold-placeholder.test.tsx @@ -0,0 +1,222 @@ +// @vitest-environment happy-dom +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { Tab, TabGroup } from '../../../shared/tab-types' +import type { TerminalTab } from '../../../shared/terminal-tab-types' +import type { TerminalController } from './use-terminal-controller' + +vi.mock('../store', async () => { + const { create } = await import('zustand') + const activeGroupIdByWorktree: Record = {} + const groupsByWorktree: Record = {} + const tabsByWorktree: Record = {} + const unifiedTabsByWorktree: Record = {} + const useAppStore = create(() => ({ + activeGroupIdByWorktree, + groupsByWorktree, + tabsByWorktree, + unifiedTabsByWorktree, + consumeSuppressedPtyExit: () => false, + focusGroup: () => {}, + reconcileWorktreeTabModel: () => ({ renderableTabCount: 1 }), + setActiveWorktree: () => {} + })) + return { useAppStore } +}) +vi.mock('./native-chat/use-native-chat-toggle-shortcut', () => ({ + useNativeChatToggleShortcut: () => {} +})) +vi.mock('./terminal-pane/use-terminal-tab-cold-parking', () => ({ + useTerminalTabColdParking: () => new Set() +})) +vi.mock('./terminal-pane/TerminalOverlaySlot', () => ({ + TerminalOverlaySlot: (props: { terminalTabId: string }) => ( +
+ ) +})) +vi.mock('./terminal-pane/TerminalPane', () => ({ + default: (props: { tabId: string }) =>
+})) +vi.mock('./tab-group/RetainedPaneHost', () => ({ + RetainedPaneHost: (props: { groupId?: string; children: React.ReactNode }) => ( +
{props.children}
+ ) +})) + +import { useAppStore } from '../store' +import TerminalPaneOverlayLayer from './terminal-pane/TerminalPaneOverlayLayer' +import { TerminalLegacyTerminalPanes } from './TerminalLegacyTerminalPanes' + +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) + +const WORKTREE_ID = 'repo::/held' +const GROUP_ID = 'group-a' +const NO_ADMITTED_TABS: ReadonlySet = new Set() + +function terminalTab(id: string): TerminalTab { + return { + id, + worktreeId: WORKTREE_ID, + ptyId: null, + title: id, + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 0, + generation: 0 + } +} + +function unifiedTerminalTab(id: string): Tab { + return { + id: `unified-${id}`, + entityId: id, + worktreeId: WORKTREE_ID, + groupId: GROUP_ID, + contentType: 'terminal', + label: id, + customLabel: null, + color: null, + sortOrder: 0, + createdAt: 0 + } +} + +function setTabs(tabIds: string[], activeTabId: string): void { + const group: TabGroup = { + id: GROUP_ID, + worktreeId: WORKTREE_ID, + activeTabId: `unified-${activeTabId}`, + tabOrder: tabIds.map((tabId) => `unified-${tabId}`) + } + useAppStore.setState({ + activeGroupIdByWorktree: { [WORKTREE_ID]: GROUP_ID }, + groupsByWorktree: { [WORKTREE_ID]: [group] }, + tabsByWorktree: { [WORKTREE_ID]: tabIds.map(terminalTab) }, + unifiedTabsByWorktree: { [WORKTREE_ID]: tabIds.map(unifiedTerminalTab) } + }) +} + +let container: HTMLDivElement +let root: Root + +beforeEach(() => { + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) +}) +afterEach(() => { + act(() => root.unmount()) + container.remove() +}) + +function placeholders(): Element[] { + return [...container.querySelectorAll('[data-terminal-restoring-placeholder]')] +} + +function mountedPaneTabIds(): string[] { + return [...container.querySelectorAll('[data-terminal-pane-tab-id]')].map( + (element) => element.getAttribute('data-terminal-pane-tab-id') ?? '' + ) +} + +describe('overlay layer under the startup terminal hold', () => { + function renderOverlay(backgroundMountTabIds: ReadonlySet | null): void { + act(() => + root.render( + + ) + ) + } + + it('fills the visible held tab slot, including a tab created under the hold, until the gate opens', () => { + setTabs(['tab-a', 'tab-b'], 'tab-a') + renderOverlay(NO_ADMITTED_TABS) + // Only the visible tab gets a placeholder; the hidden held tab renders nothing. + expect(placeholders()).toHaveLength(1) + expect(placeholders()[0].parentElement?.getAttribute('data-retained-pane-group-id')).toBe( + GROUP_ID + ) + expect(mountedPaneTabIds()).toEqual([]) + + setTabs(['tab-a', 'tab-b', 'tab-new'], 'tab-new') + renderOverlay(NO_ADMITTED_TABS) + expect(placeholders()).toHaveLength(1) + expect(mountedPaneTabIds()).toEqual([]) + + renderOverlay(null) + expect(placeholders()).toHaveLength(0) + expect(mountedPaneTabIds()).toEqual(['tab-a', 'tab-b', 'tab-new']) + }) + + it('renders no placeholder while the held worktree is not the active one', () => { + setTabs(['tab-a'], 'tab-a') + act(() => + root.render( + + ) + ) + expect(placeholders()).toHaveLength(0) + }) +}) + +describe('legacy terminal panes under the startup terminal hold', () => { + function renderLegacy( + tabIds: string[], + activeTabId: string, + restriction: ReadonlySet | null + ): void { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: TerminalLegacyTerminalPanes reads only the fields listed here. + const controller = { + activeTabId, + activeTabType: 'terminal', + activeView: 'terminal', + activityTerminalPortals: [], + backgroundMountTabIdsByWorktreeRef: { + current: new Map(restriction ? [[WORKTREE_ID, restriction]] : []) + }, + effectiveParkedTerminalWorktreeIds: new Set(), + evictionExemptTerminalTabIds: new Set(), + handleCloseTab: () => {}, + handlePtyExit: () => {}, + measurableBackgroundWorktreeIdsRef: { current: new Set() }, + mountedWorktreeIdsRef: { current: new Set([WORKTREE_ID]) }, + renderedActiveWorktreeId: WORKTREE_ID, + tabsByWorktree: { [WORKTREE_ID]: tabIds.map(terminalTab) }, + worktreeBrowserTabs: [], + worktreeFiles: [], + workspaceSurfaces: [{ id: WORKTREE_ID, path: '/held' }] + } as unknown as TerminalController + act(() => root.render()) + } + + it('fills the active held tab, including a tab created under the hold, until the gate opens', () => { + renderLegacy(['tab-a', 'tab-b'], 'tab-a', NO_ADMITTED_TABS) + expect(placeholders()).toHaveLength(1) + expect(mountedPaneTabIds()).toEqual([]) + + renderLegacy(['tab-a', 'tab-b', 'tab-new'], 'tab-new', NO_ADMITTED_TABS) + expect(placeholders()).toHaveLength(1) + + renderLegacy(['tab-a', 'tab-b', 'tab-new'], 'tab-new', null) + expect(placeholders()).toHaveLength(0) + expect(mountedPaneTabIds()).toEqual(['tab-a', 'tab-b', 'tab-new']) + }) + + it('renders no placeholder when the active tab is not a held one', () => { + renderLegacy(['tab-a', 'tab-b'], 'tab-a', new Set(['tab-a'])) + expect(placeholders()).toHaveLength(0) + expect(mountedPaneTabIds()).toEqual(['tab-a']) + }) +}) diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 683d82c35781..692615152473 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -3386,6 +3386,9 @@ "TerminalQuickCommandsSubmenu": { "3ccc7981bb": "Host unavailable", "54f29b7c0d": "Loading host…" + }, + "TerminalRestoringPlaceholder": { + "restoring": "Restoring terminal…" } } }, diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 3cfa6967d4f1..d970c303b571 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -2916,6 +2916,9 @@ "retryingBody": "Orca is retrying automatically. This terminal will resume if the connection returns.", "disconnectedBody": "Automatic retries stopped. Reconnect to resume this terminal session.", "reconnectButton": "Reconnect" + }, + "TerminalRestoringPlaceholder": { + "restoring": "Restaurando terminal…" } } }, diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 0147111e3de6..dc3b1085865e 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -3333,6 +3333,9 @@ "TerminalQuickCommandsSubmenu": { "3ccc7981bb": "Hôte indisponible", "54f29b7c0d": "Chargement de l'hôte…" + }, + "TerminalRestoringPlaceholder": { + "restoring": "Restauration du terminal…" } } }, diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index dae80d521e49..bb1c0300c358 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -3230,6 +3230,9 @@ "TerminalQuickCommandsSubmenu": { "3ccc7981bb": "ホストが利用不可", "54f29b7c0d": "ホストを読み込み中…" + }, + "TerminalRestoringPlaceholder": { + "restoring": "ターミナルを復元中…" } } }, diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 0386126ae396..edcf72a33379 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -3230,6 +3230,9 @@ "TerminalQuickCommandsSubmenu": { "3ccc7981bb": "호스트를 사용할 수 없음", "54f29b7c0d": "호스트 로드 중…" + }, + "TerminalRestoringPlaceholder": { + "restoring": "터미널 복원 중…" } } }, diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index b88637923cd6..a5f012044b3f 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -3230,6 +3230,9 @@ "TerminalQuickCommandsSubmenu": { "3ccc7981bb": "主机不可用", "54f29b7c0d": "正在加载主机..." + }, + "TerminalRestoringPlaceholder": { + "restoring": "正在恢复终端…" } } }, From f56bbf9e23126e670327c732fb3dd600100d1523 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 11:26:26 -0700 Subject: [PATCH 6/8] refactor(workspace): every pane reads one shared host-connection signal The terminal host state now reads its SSH status from the same per-worktree signal as the browser route and the editor, instead of resolving it on its own. The signal carries the resolved status (an undialed target during startup restoration reads as connecting), the owning environment, and a connection epoch that changes on every reconnect, so no pane re-derives the no-entry case or the reconnect generation. A nested target whose runtime cannot be seen is reported as unverifiable rather than unavailable. --- ...ace-browser-route.host-connection.test.tsx | 21 +++- .../use-ssh-workspace-browser-route.ts | 3 +- .../editor/local-host-test-fixture.ts | 4 +- ...anelFileLoadRetry.host-connection.test.tsx | 21 +++- .../editor/useEditorPanelFileLoadRetry.ts | 3 +- .../terminal-pane-host-state.test.ts | 19 +++ .../terminal-pane/terminal-pane-host-state.ts | 20 ++-- .../worktree-host-connection-phase.test.ts | 72 ++++++++++-- .../src/lib/worktree-host-connection-phase.ts | 109 ++++++++++-------- 9 files changed, 194 insertions(+), 78 deletions(-) diff --git a/src/renderer/src/components/browser-pane/use-ssh-workspace-browser-route.host-connection.test.tsx b/src/renderer/src/components/browser-pane/use-ssh-workspace-browser-route.host-connection.test.tsx index 3fa0b5293323..3953d5c61069 100644 --- a/src/renderer/src/components/browser-pane/use-ssh-workspace-browser-route.host-connection.test.tsx +++ b/src/renderer/src/components/browser-pane/use-ssh-workspace-browser-route.host-connection.test.tsx @@ -2,12 +2,15 @@ import { act, cleanup, renderHook } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { WorktreeHostConnection } from '@/lib/worktree-host-connection-phase' +import type { SshConnectionStatus } from '../../../../shared/ssh-types' const mocks = vi.hoisted(() => { const hostConnection: WorktreeHostConnection = { phase: 'connecting', targetId: 'target-a', - connectionGeneration: null + environmentId: null, + status: 'connecting', + connectedEpoch: null } return { hostConnection, prepare: vi.fn() } }) @@ -29,11 +32,25 @@ const settle = () => await new Promise((resolve) => setTimeout(resolve, 0)) }) +const STATUS_BY_PHASE: Record = { + local: null, + connecting: 'connecting', + connected: 'connected', + unavailable: 'disconnected', + unverifiable: null +} + function setHost( phase: WorktreeHostConnection['phase'], connectionGeneration: number | null = null ): void { - mocks.hostConnection = { phase, targetId: 'target-a', connectionGeneration } + mocks.hostConnection = { + phase, + targetId: 'target-a', + environmentId: null, + status: STATUS_BY_PHASE[phase], + connectedEpoch: phase === 'connected' ? `target-a:${connectionGeneration}` : null + } } describe('useSshWorkspaceBrowserRoute under a reconnecting SSH host', () => { diff --git a/src/renderer/src/components/browser-pane/use-ssh-workspace-browser-route.ts b/src/renderer/src/components/browser-pane/use-ssh-workspace-browser-route.ts index 5a06100052de..16af5b7896e4 100644 --- a/src/renderer/src/components/browser-pane/use-ssh-workspace-browser-route.ts +++ b/src/renderer/src/components/browser-pane/use-ssh-workspace-browser-route.ts @@ -72,8 +72,7 @@ export function useSshWorkspaceBrowserRoute( // would unmount it. Only a route still waiting on, or failed by, its host follows the host. const routeReady = state.kind === 'ready' && state.targetId === targetId const awaitingHost = routeHost?.phase === 'connecting' && !routeReady - const connectedHostEpoch = - routeHost?.phase === 'connected' ? `connected:${routeHost.connectionGeneration ?? ''}` : null + const connectedHostEpoch = routeHost?.connectedEpoch ?? null const [seenConnectedHostEpoch, setSeenConnectedHostEpoch] = useState(connectedHostEpoch) if (connectedHostEpoch !== seenConnectedHostEpoch) { setSeenConnectedHostEpoch(connectedHostEpoch) diff --git a/src/renderer/src/components/editor/local-host-test-fixture.ts b/src/renderer/src/components/editor/local-host-test-fixture.ts index d803d87133cd..585839597eb8 100644 --- a/src/renderer/src/components/editor/local-host-test-fixture.ts +++ b/src/renderer/src/components/editor/local-host-test-fixture.ts @@ -4,7 +4,9 @@ import type { WorktreeHostConnection } from '@/lib/worktree-host-connection-phas const LOCAL_HOST_CONNECTION: WorktreeHostConnection = { phase: 'local', targetId: null, - connectionGeneration: null + environmentId: null, + status: null, + connectedEpoch: null } export function selectWorktreeHostConnectionPhase(): WorktreeHostConnection { diff --git a/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.host-connection.test.tsx b/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.host-connection.test.tsx index c974be650bd5..6d2048012c17 100644 --- a/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.host-connection.test.tsx +++ b/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.host-connection.test.tsx @@ -5,6 +5,7 @@ import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { OpenFile } from '@/store/slices/editor' import type { WorktreeHostConnection } from '@/lib/worktree-host-connection-phase' +import type { SshConnectionStatus } from '../../../../shared/ssh-types' import { WORKTREE_OWNER_NOT_READY_ERROR, WORKTREE_OWNER_UNREACHABLE_ERROR, @@ -15,7 +16,9 @@ const mocks = vi.hoisted(() => { const hostConnection: WorktreeHostConnection = { phase: 'connecting', targetId: 'ssh-a', - connectionGeneration: null + environmentId: null, + status: 'connecting', + connectedEpoch: null } return { hostConnection, readRuntimeFileContent: vi.fn() } }) @@ -46,11 +49,25 @@ import { const SSH_PROVIDER_UNAVAILABLE = 'Remote connection dropped. Click Reconnect on the SSH target before retrying.' +const STATUS_BY_PHASE: Record = { + local: null, + connecting: 'connecting', + connected: 'connected', + unavailable: 'disconnected', + unverifiable: null +} + function setHost( phase: WorktreeHostConnection['phase'], connectionGeneration: number | null = null ): void { - mocks.hostConnection = { phase, targetId: 'ssh-a', connectionGeneration } + mocks.hostConnection = { + phase, + targetId: 'ssh-a', + environmentId: null, + status: STATUS_BY_PHASE[phase], + connectedEpoch: phase === 'connected' ? `ssh-a:${connectionGeneration}` : null + } } const file: OpenFile = { diff --git a/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.ts b/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.ts index c6f98871535d..4f3057e7b1ad 100644 --- a/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.ts +++ b/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.ts @@ -83,8 +83,7 @@ export function useEditorPanelFileLoadRetry({ const hostConnection = useWorktreeHostConnection(activeFile?.worktreeId ?? null) const hostTargetId = hostConnection.targetId const hostConnecting = hostConnection.phase === 'connecting' - const connectedHostEpoch = - hostConnection.phase === 'connected' ? `${hostConnection.connectionGeneration ?? ''}` : null + const connectedHostEpoch = hostConnection.connectedEpoch const seenHostRef = useRef({ targetId: hostTargetId, connectedEpoch: connectedHostEpoch }) useEffect(() => { diff --git a/src/renderer/src/components/terminal-pane/terminal-pane-host-state.test.ts b/src/renderer/src/components/terminal-pane/terminal-pane-host-state.test.ts index c9614690e4bf..df5c07c68f98 100644 --- a/src/renderer/src/components/terminal-pane/terminal-pane-host-state.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-pane-host-state.test.ts @@ -161,4 +161,23 @@ describe('selectTerminalPaneHostState', () => { sshReconnectTargetRemoved: false }) }) + + // Shares the workspace host signal with the other panes: a target startup restoration has + // not dialed yet reads as connecting, then follows the published status once it connects. + it('follows the shared host signal from connecting to connected', () => { + const repos = [{ id: 'repo-ssh', connectionId: 'ssh-a' }] + const worktreesByRepo = { 'repo-ssh': [{ id: 'wt-ssh', repoId: 'repo-ssh' }] } + const undialed = makeState({ repos, worktreesByRepo, terminalStartupRestorationReady: false }) + const connected = makeState({ + repos, + worktreesByRepo, + terminalStartupRestorationReady: false, + sshConnectionStates: new Map([ + ['ssh-a', { targetId: 'ssh-a', status: 'connected', error: null, reconnectAttempt: 0 }] + ]) + }) + + expect(selectTerminalPaneHostState(undialed, 'wt-ssh').sshReconnectStatus).toBe('connecting') + expect(selectTerminalPaneHostState(connected, 'wt-ssh').sshReconnectStatus).toBe('connected') + }) }) diff --git a/src/renderer/src/components/terminal-pane/terminal-pane-host-state.ts b/src/renderer/src/components/terminal-pane/terminal-pane-host-state.ts index 967f78b2e820..f82fa61206dc 100644 --- a/src/renderer/src/components/terminal-pane/terminal-pane-host-state.ts +++ b/src/renderer/src/components/terminal-pane/terminal-pane-host-state.ts @@ -1,10 +1,12 @@ import type { AppState } from '@/store/types' import { getConnectionIdFromState } from '@/lib/connection-context' -import { resolveWorktreeSshTarget } from '@/lib/worktree-host-connection-phase' +import { + resolveWorktreeHostConnection, + type WorktreeHostConnection +} from '@/lib/worktree-host-connection-phase' import { isNativeChatTranscriptLocalReadable } from '@/lib/native-chat-transcript-readability' import { selectRuntimeAwareSshError, - selectRuntimeAwareSshStatus, selectRuntimeAwareSshTargetLabel, selectRuntimeAwareSshTargetRemoved } from '@/store/slices/runtime-environment-ssh' @@ -14,7 +16,7 @@ export type TerminalPaneHostState = { sshReconnectEnvironmentId: string | null /** The failure detail behind the status; the overlay shows only a canned sentence without it. */ sshReconnectError: string | null - sshReconnectStatus: ReturnType + sshReconnectStatus: WorktreeHostConnection['status'] sshReconnectTargetId: string | null sshReconnectTargetLabel: string sshReconnectTargetRemoved: boolean @@ -24,8 +26,8 @@ function computeTerminalPaneHostState(state: AppState, worktreeId: string): Term const connectionId = getConnectionIdFromState(state, worktreeId) const nativeChatTranscriptIsLocalReadableResult = isNativeChatTranscriptLocalReadable(connectionId) - const sshTarget = resolveWorktreeSshTarget(state, worktreeId, connectionId) - if (!sshTarget) { + const host = resolveWorktreeHostConnection(state, worktreeId, connectionId) + if (!host.targetId) { return { nativeChatTranscriptIsLocalReadable: nativeChatTranscriptIsLocalReadableResult, sshReconnectEnvironmentId: null, @@ -36,7 +38,7 @@ function computeTerminalPaneHostState(state: AppState, worktreeId: string): Term sshReconnectTargetRemoved: false } } - const { targetId: sshReconnectTargetId, environmentId: sshReconnectEnvironmentId } = sshTarget + const { targetId: sshReconnectTargetId, environmentId: sshReconnectEnvironmentId } = host return { nativeChatTranscriptIsLocalReadable: nativeChatTranscriptIsLocalReadableResult, sshReconnectEnvironmentId, @@ -45,11 +47,7 @@ function computeTerminalPaneHostState(state: AppState, worktreeId: string): Term sshReconnectEnvironmentId, sshReconnectTargetId ), - sshReconnectStatus: selectRuntimeAwareSshStatus( - state, - sshReconnectEnvironmentId, - sshReconnectTargetId - ), + sshReconnectStatus: host.status, sshReconnectTargetId, sshReconnectTargetLabel: selectRuntimeAwareSshTargetLabel( state, diff --git a/src/renderer/src/lib/worktree-host-connection-phase.test.ts b/src/renderer/src/lib/worktree-host-connection-phase.test.ts index 7bfde90a4e35..2285364b199c 100644 --- a/src/renderer/src/lib/worktree-host-connection-phase.test.ts +++ b/src/renderer/src/lib/worktree-host-connection-phase.test.ts @@ -57,7 +57,13 @@ describe('selectWorktreeHostConnectionPhase', () => { worktreesByRepo: { 'repo-local': [{ id: 'wt-local', repoId: 'repo-local' }] } }) - const local = { phase: 'local', targetId: null, connectionGeneration: null } + const local = { + phase: 'local', + targetId: null, + environmentId: null, + status: null, + connectedEpoch: null + } expect(selectWorktreeHostConnectionPhase(state, 'wt-local')).toEqual(local) expect(selectWorktreeHostConnectionPhase(state, null)).toEqual(local) }) @@ -77,19 +83,21 @@ describe('selectWorktreeHostConnectionPhase', () => { makeSshState(null, { terminalStartupRestorationReady: false }), 'wt-ssh' ) - ).toEqual({ phase: 'connecting', targetId: 'ssh-a', connectionGeneration: null }) - expect(selectWorktreeHostConnectionPhase(makeSshState(null), 'wt-ssh')).toEqual({ + ).toMatchObject({ phase: 'connecting', targetId: 'ssh-a', status: 'connecting' }) + expect(selectWorktreeHostConnectionPhase(makeSshState(null), 'wt-ssh')).toMatchObject({ phase: 'unavailable', targetId: 'ssh-a', - connectionGeneration: null + status: 'disconnected' }) }) - it('maps published statuses and carries the connection generation', () => { + it('maps published statuses; only a connected host names its connection', () => { expect(selectWorktreeHostConnectionPhase(makeSshState('connecting'), 'wt-ssh')).toEqual({ phase: 'connecting', targetId: 'ssh-a', - connectionGeneration: 7 + environmentId: null, + status: 'connecting', + connectedEpoch: null }) expect(selectWorktreeHostConnectionPhase(makeSshState('reconnecting'), 'wt-ssh').phase).toBe( 'connecting' @@ -100,7 +108,9 @@ describe('selectWorktreeHostConnectionPhase', () => { expect(selectWorktreeHostConnectionPhase(makeSshState('connected'), 'wt-ssh')).toEqual({ phase: 'connected', targetId: 'ssh-a', - connectionGeneration: 7 + environmentId: null, + status: 'connected', + connectedEpoch: 'ssh-a:7' }) }) @@ -165,7 +175,53 @@ describe('selectWorktreeHostConnectionPhase', () => { expect(selectWorktreeHostConnectionPhase(state, 'wt-runtime')).toEqual({ phase: 'connected', targetId: 'ssh-nested', - connectionGeneration: 3 + environmentId: 'env-a', + status: 'connected', + connectedEpoch: 'ssh-nested:3' + }) + }) + + it('names a new connection on every reconnect', () => { + const connected = makeSshState('connected') + const reconnected = makeSshState('connected', { + sshConnectionStates: new Map([ + [ + 'ssh-a', + { + targetId: 'ssh-a', + status: 'connected', + error: null, + reconnectAttempt: 0, + connectionGeneration: 8 + } + ] + ]) + }) + + expect(selectWorktreeHostConnectionPhase(reconnected, 'wt-ssh').connectedEpoch).not.toBe( + selectWorktreeHostConnectionPhase(connected, 'wt-ssh').connectedEpoch + ) + }) + + it('reports a nested target whose runtime is unreachable as unverifiable, not down', () => { + const state = makeState({ + repos: [{ id: 'repo-runtime', connectionId: 'ssh-nested', executionHostId: 'runtime:env-a' }], + worktreesByRepo: { + 'repo-runtime': [ + { + id: 'wt-runtime', + repoId: 'repo-runtime', + hostId: 'runtime:env-a', + runtimeOwnerEnvironmentId: 'env-a' + } + ] + } + }) + + expect(selectWorktreeHostConnectionPhase(state, 'wt-runtime')).toMatchObject({ + phase: 'unverifiable', + targetId: 'ssh-nested', + status: null }) }) }) diff --git a/src/renderer/src/lib/worktree-host-connection-phase.ts b/src/renderer/src/lib/worktree-host-connection-phase.ts index ada4428df03a..bb266376432b 100644 --- a/src/renderer/src/lib/worktree-host-connection-phase.ts +++ b/src/renderer/src/lib/worktree-host-connection-phase.ts @@ -8,73 +8,94 @@ import { selectRuntimeAwareSshStatus } from '@/store/slices/runtime-environment-ssh' import { isConnectingSshStatus } from '@/ssh/ssh-connection-recoverability' +import type { SshConnectionStatus } from '../../../shared/ssh-types' import { isRuntimeOwnedSshTargetId } from '../../../shared/execution-host' /** * `local`: no SSH target this client dials for the worktree — a local workspace, a * runtime-owned target, or an owner that has not resolved yet. + * `unverifiable`: the owning remote runtime is unreachable or has not published its SSH + * state, so this client cannot see the target — not evidence that it is down. */ -export type WorktreeHostConnectionPhase = 'local' | 'connecting' | 'connected' | 'unavailable' +export type WorktreeHostConnectionPhase = + | 'local' + | 'connecting' + | 'connected' + | 'unavailable' + | 'unverifiable' export type WorktreeHostConnection = { phase: WorktreeHostConnectionPhase targetId: string | null - /** Bumps on every reconnect, so a consumer can re-derive what it prepared on the old one. */ - connectionGeneration: number | null -} - -export type WorktreeSshTarget = { - targetId: string /** The remote runtime whose mirrored SSH state owns the target; null for this client's own. */ environmentId: string | null + /** The status behind `phase`; null when local or unverifiable. */ + status: SshConnectionStatus | null + /** Names the live connection: null unless connected, and new on every reconnect. */ + connectedEpoch: string | null } const LOCAL_HOST_CONNECTION: WorktreeHostConnection = { phase: 'local', targetId: null, - connectionGeneration: null -} - -/** The SSH target a worktree's panes reach through, or null when this client dials none. */ -export function resolveWorktreeSshTarget( - state: AppState, - worktreeId: string, - connectionId: string | null | undefined -): WorktreeSshTarget | null { - if (!connectionId || isRuntimeOwnedSshTargetId(connectionId)) { - return null - } - return { - targetId: connectionId, - environmentId: getExplicitRuntimeEnvironmentIdForWorktree(state, worktreeId) - } + environmentId: null, + status: null, + connectedEpoch: null } -function deriveSshTargetPhase( +function selectTargetStatus( state: AppState, - target: WorktreeSshTarget -): WorktreeHostConnectionPhase { - const status = selectRuntimeAwareSshStatus(state, target.environmentId, target.targetId) - if (status === 'connected') { - return 'connected' - } - if (isConnectingSshStatus(status)) { - return 'connecting' - } + targetId: string, + environmentId: string | null +): SshConnectionStatus | null { // Why: startup restoration dials the targets that were live at shutdown; until it publishes, // a missing entry means "not dialed yet", not "disconnected". Restoration finishing (or // degrading) ends this on its own. if ( - target.environmentId === null && + environmentId === null && !state.terminalStartupRestorationReady && - !state.sshConnectionStates.has(target.targetId) + !state.sshConnectionStates.has(targetId) ) { return 'connecting' } - return 'unavailable' + return selectRuntimeAwareSshStatus(state, environmentId, targetId) +} + +function phaseForStatus(status: SshConnectionStatus | null): WorktreeHostConnectionPhase { + if (status === null) { + return 'unverifiable' + } + if (status === 'connected') { + return 'connected' + } + return isConnectingSshStatus(status) ? 'connecting' : 'unavailable' +} + +/** The shared signal for a caller that already resolved the worktree's connection id. */ +export function resolveWorktreeHostConnection( + state: AppState, + worktreeId: string, + targetId: string | null | undefined +): WorktreeHostConnection { + if (!targetId || isRuntimeOwnedSshTargetId(targetId)) { + return LOCAL_HOST_CONNECTION + } + const environmentId = getExplicitRuntimeEnvironmentIdForWorktree(state, worktreeId) + const status = selectTargetStatus(state, targetId, environmentId) + const generation = selectRuntimeAwareSshConnectionGeneration(state, environmentId, targetId) + return { + phase: phaseForStatus(status), + targetId, + environmentId, + status, + connectedEpoch: status === 'connected' ? `${targetId}:${generation ?? ''}` : null + } } -/** Whether a worktree's SSH host is reachable yet, derived from the published SSH state. */ +/** + * The one reading of a worktree's SSH host that every pane shares, derived from the + * published SSH state. Panes must not re-derive status or reconnect identity themselves. + */ export function selectWorktreeHostConnectionPhase( state: AppState, worktreeId: string | null @@ -82,23 +103,11 @@ export function selectWorktreeHostConnectionPhase( if (!worktreeId) { return LOCAL_HOST_CONNECTION } - const target = resolveWorktreeSshTarget( + return resolveWorktreeHostConnection( state, worktreeId, getConnectionIdFromState(state, worktreeId) ) - if (!target) { - return LOCAL_HOST_CONNECTION - } - return { - phase: deriveSshTargetPhase(state, target), - targetId: target.targetId, - connectionGeneration: selectRuntimeAwareSshConnectionGeneration( - state, - target.environmentId, - target.targetId - ) - } } export function useWorktreeHostConnection(worktreeId: string | null): WorktreeHostConnection { From 5a0ac9582378fedba1c9b13e03f314acfbf94c36 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 11:38:42 -0700 Subject: [PATCH 7/8] fix(workspace): the terminal names the published SSH status from the shared signal The shared host signal now carries the published status separately from its phase. Only the phase reads a target startup restoration has not dialed yet as connecting, so the terminal's reconnect overlay and error ownership keep reporting what the host published, while the browser and editor still wait. Tests pin that window for the terminal and pin that a host the client cannot verify never holds the browser or editor. --- ...ace-browser-route.host-connection.test.tsx | 13 +++- .../editor/local-host-test-fixture.ts | 2 +- ...anelFileLoadRetry.host-connection.test.tsx | 42 ++++++++++- .../terminal-pane-host-state.test.ts | 75 +++++++++++++++---- .../terminal-pane/terminal-pane-host-state.ts | 4 +- .../worktree-host-connection-phase.test.ts | 14 ++-- .../src/lib/worktree-host-connection-phase.ts | 46 ++++++------ 7 files changed, 148 insertions(+), 48 deletions(-) diff --git a/src/renderer/src/components/browser-pane/use-ssh-workspace-browser-route.host-connection.test.tsx b/src/renderer/src/components/browser-pane/use-ssh-workspace-browser-route.host-connection.test.tsx index 3953d5c61069..5e689c46e355 100644 --- a/src/renderer/src/components/browser-pane/use-ssh-workspace-browser-route.host-connection.test.tsx +++ b/src/renderer/src/components/browser-pane/use-ssh-workspace-browser-route.host-connection.test.tsx @@ -9,7 +9,7 @@ const mocks = vi.hoisted(() => { phase: 'connecting', targetId: 'target-a', environmentId: null, - status: 'connecting', + publishedStatus: 'connecting', connectedEpoch: null } return { hostConnection, prepare: vi.fn() } @@ -48,7 +48,7 @@ function setHost( phase, targetId: 'target-a', environmentId: null, - status: STATUS_BY_PHASE[phase], + publishedStatus: STATUS_BY_PHASE[phase], connectedEpoch: phase === 'connected' ? `target-a:${connectionGeneration}` : null } } @@ -140,4 +140,13 @@ describe('useSshWorkspaceBrowserRoute under a reconnecting SSH host', () => { expect(mocks.prepare).toHaveBeenCalledOnce() expect(result.current.state.kind).toBe('ready') }) + + it('prepares normally for a host it cannot verify instead of waiting on it', async () => { + setHost('unverifiable') + mocks.prepare.mockResolvedValue({ partition: READY_PARTITION }) + const { result } = renderHook(() => useSshWorkspaceBrowserRoute('wt-1', null)) + await settle() + expect(mocks.prepare).toHaveBeenCalledOnce() + expect(result.current.state.kind).toBe('ready') + }) }) diff --git a/src/renderer/src/components/editor/local-host-test-fixture.ts b/src/renderer/src/components/editor/local-host-test-fixture.ts index 585839597eb8..d6ef4f7128a4 100644 --- a/src/renderer/src/components/editor/local-host-test-fixture.ts +++ b/src/renderer/src/components/editor/local-host-test-fixture.ts @@ -5,7 +5,7 @@ const LOCAL_HOST_CONNECTION: WorktreeHostConnection = { phase: 'local', targetId: null, environmentId: null, - status: null, + publishedStatus: null, connectedEpoch: null } diff --git a/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.host-connection.test.tsx b/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.host-connection.test.tsx index 6d2048012c17..ad6b4cb012a0 100644 --- a/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.host-connection.test.tsx +++ b/src/renderer/src/components/editor/useEditorPanelFileLoadRetry.host-connection.test.tsx @@ -17,7 +17,7 @@ const mocks = vi.hoisted(() => { phase: 'connecting', targetId: 'ssh-a', environmentId: null, - status: 'connecting', + publishedStatus: 'connecting', connectedEpoch: null } return { hostConnection, readRuntimeFileContent: vi.fn() } @@ -65,7 +65,7 @@ function setHost( phase, targetId: 'ssh-a', environmentId: null, - status: STATUS_BY_PHASE[phase], + publishedStatus: STATUS_BY_PHASE[phase], connectedEpoch: phase === 'connected' ? `ssh-a:${connectionGeneration}` : null } } @@ -216,4 +216,42 @@ describe('editor file loads while the SSH host connects', () => { expect(loadFileContent).toHaveBeenCalledOnce() expect(attemptsRef.current[file.id]).toBe(0) }) + + it('keeps retrying for a host it cannot verify, then reloads once it connects', () => { + setHost('unverifiable') + const attemptsRef: { current: Record } = { current: {} } + let fileContents: Record = { + [file.id]: { content: '', isBinary: false, loadError: WORKTREE_OWNER_NOT_READY_ERROR } + } + const setFileContents: Dispatch>> = (updater) => { + fileContents = typeof updater === 'function' ? updater(fileContents) : updater + } + const loadFileContent = vi.fn(async () => { + fileContents = { + [file.id]: { content: '', isBinary: false, loadError: WORKTREE_OWNER_NOT_READY_ERROR } + } + }) + const render = (): void => + act(() => + root.render( + + ) + ) + + // Unverifiable is not "connecting": the ordinary owner-not-ready poll keeps running. + render() + act(() => vi.advanceTimersByTime(OWNER_NOT_READY_RETRY_DELAY_MS)) + expect(loadFileContent).toHaveBeenCalledOnce() + expect(attemptsRef.current[file.id]).toBe(1) + + setHost('connected', 1) + render() + expect(loadFileContent).toHaveBeenCalledTimes(2) + expect(attemptsRef.current[file.id]).toBe(0) + }) }) diff --git a/src/renderer/src/components/terminal-pane/terminal-pane-host-state.test.ts b/src/renderer/src/components/terminal-pane/terminal-pane-host-state.test.ts index df5c07c68f98..fef6ce122247 100644 --- a/src/renderer/src/components/terminal-pane/terminal-pane-host-state.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-pane-host-state.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest' import type { AppState } from '@/store/types' +import { selectWorktreeHostConnectionPhase } from '@/lib/worktree-host-connection-phase' import { selectTerminalPaneHostState } from './terminal-pane-host-state' function makeState(overrides: Record): AppState { @@ -162,22 +163,70 @@ describe('selectTerminalPaneHostState', () => { }) }) - // Shares the workspace host signal with the other panes: a target startup restoration has - // not dialed yet reads as connecting, then follows the published status once it connects. - it('follows the shared host signal from connecting to connected', () => { + // The terminal reads the shared host signal but names the published status: an undialed + // target during startup restoration stays "disconnected" here (the overlay and error + // ownership are unchanged) even though the other panes read that window as connecting. + it('reports the published status through the shared signal, across startup and connect', () => { const repos = [{ id: 'repo-ssh', connectionId: 'ssh-a' }] const worktreesByRepo = { 'repo-ssh': [{ id: 'wt-ssh', repoId: 'repo-ssh' }] } - const undialed = makeState({ repos, worktreesByRepo, terminalStartupRestorationReady: false }) - const connected = makeState({ - repos, - worktreesByRepo, - terminalStartupRestorationReady: false, - sshConnectionStates: new Map([ - ['ssh-a', { targetId: 'ssh-a', status: 'connected', error: null, reconnectAttempt: 0 }] - ]) + const withStatus = (status: string | null): AppState => + makeState({ + repos, + worktreesByRepo, + terminalStartupRestorationReady: false, + sshConnectionStates: new Map( + status ? [['ssh-a', { targetId: 'ssh-a', status, error: null, reconnectAttempt: 0 }]] : [] + ) + }) + + expect(selectWorktreeHostConnectionPhase(withStatus(null), 'wt-ssh').phase).toBe('connecting') + expect(selectTerminalPaneHostState(withStatus(null), 'wt-ssh').sshReconnectStatus).toBe( + 'disconnected' + ) + expect(selectTerminalPaneHostState(withStatus('connecting'), 'wt-ssh').sshReconnectStatus).toBe( + 'connecting' + ) + expect(selectTerminalPaneHostState(withStatus('connected'), 'wt-ssh').sshReconnectStatus).toBe( + 'connected' + ) + }) + + // An owning runtime that has not published its SSH state is unverifiable, not down: the + // terminal keeps reporting no status, so it shows no reconnect overlay for it. + it('reports no status for a nested target whose runtime has not published its SSH state', () => { + const state = makeState({ + repos: [{ id: 'repo-runtime', connectionId: 'ssh-nested', executionHostId: 'runtime:env-a' }], + runtimeStatusByEnvironmentId: new Map([ + ['env-a', { status: { runtimeId: 'runtime-a' }, checkedAt: 1 }] + ]), + sshStateByEnvironment: new Map([ + [ + 'env-a', + { + connectionStates: new Map(), + targetLabels: new Map(), + removedTargetLabels: new Map(), + targetsHydrated: false + } + ] + ]), + worktreesByRepo: { + 'repo-runtime': [ + { + id: 'wt-runtime', + repoId: 'repo-runtime', + hostId: 'runtime:env-a', + runtimeOwnerEnvironmentId: 'env-a' + } + ] + } }) - expect(selectTerminalPaneHostState(undialed, 'wt-ssh').sshReconnectStatus).toBe('connecting') - expect(selectTerminalPaneHostState(connected, 'wt-ssh').sshReconnectStatus).toBe('connected') + expect(selectWorktreeHostConnectionPhase(state, 'wt-runtime').phase).toBe('unverifiable') + expect(selectTerminalPaneHostState(state, 'wt-runtime')).toMatchObject({ + sshReconnectEnvironmentId: 'env-a', + sshReconnectStatus: null, + sshReconnectTargetId: 'ssh-nested' + }) }) }) diff --git a/src/renderer/src/components/terminal-pane/terminal-pane-host-state.ts b/src/renderer/src/components/terminal-pane/terminal-pane-host-state.ts index f82fa61206dc..dd843849942a 100644 --- a/src/renderer/src/components/terminal-pane/terminal-pane-host-state.ts +++ b/src/renderer/src/components/terminal-pane/terminal-pane-host-state.ts @@ -16,7 +16,7 @@ export type TerminalPaneHostState = { sshReconnectEnvironmentId: string | null /** The failure detail behind the status; the overlay shows only a canned sentence without it. */ sshReconnectError: string | null - sshReconnectStatus: WorktreeHostConnection['status'] + sshReconnectStatus: WorktreeHostConnection['publishedStatus'] sshReconnectTargetId: string | null sshReconnectTargetLabel: string sshReconnectTargetRemoved: boolean @@ -47,7 +47,7 @@ function computeTerminalPaneHostState(state: AppState, worktreeId: string): Term sshReconnectEnvironmentId, sshReconnectTargetId ), - sshReconnectStatus: host.status, + sshReconnectStatus: host.publishedStatus, sshReconnectTargetId, sshReconnectTargetLabel: selectRuntimeAwareSshTargetLabel( state, diff --git a/src/renderer/src/lib/worktree-host-connection-phase.test.ts b/src/renderer/src/lib/worktree-host-connection-phase.test.ts index 2285364b199c..ab7b3cdeeb7d 100644 --- a/src/renderer/src/lib/worktree-host-connection-phase.test.ts +++ b/src/renderer/src/lib/worktree-host-connection-phase.test.ts @@ -61,7 +61,7 @@ describe('selectWorktreeHostConnectionPhase', () => { phase: 'local', targetId: null, environmentId: null, - status: null, + publishedStatus: null, connectedEpoch: null } expect(selectWorktreeHostConnectionPhase(state, 'wt-local')).toEqual(local) @@ -83,11 +83,11 @@ describe('selectWorktreeHostConnectionPhase', () => { makeSshState(null, { terminalStartupRestorationReady: false }), 'wt-ssh' ) - ).toMatchObject({ phase: 'connecting', targetId: 'ssh-a', status: 'connecting' }) + ).toMatchObject({ phase: 'connecting', targetId: 'ssh-a', publishedStatus: 'disconnected' }) expect(selectWorktreeHostConnectionPhase(makeSshState(null), 'wt-ssh')).toMatchObject({ phase: 'unavailable', targetId: 'ssh-a', - status: 'disconnected' + publishedStatus: 'disconnected' }) }) @@ -96,7 +96,7 @@ describe('selectWorktreeHostConnectionPhase', () => { phase: 'connecting', targetId: 'ssh-a', environmentId: null, - status: 'connecting', + publishedStatus: 'connecting', connectedEpoch: null }) expect(selectWorktreeHostConnectionPhase(makeSshState('reconnecting'), 'wt-ssh').phase).toBe( @@ -109,7 +109,7 @@ describe('selectWorktreeHostConnectionPhase', () => { phase: 'connected', targetId: 'ssh-a', environmentId: null, - status: 'connected', + publishedStatus: 'connected', connectedEpoch: 'ssh-a:7' }) }) @@ -176,7 +176,7 @@ describe('selectWorktreeHostConnectionPhase', () => { phase: 'connected', targetId: 'ssh-nested', environmentId: 'env-a', - status: 'connected', + publishedStatus: 'connected', connectedEpoch: 'ssh-nested:3' }) }) @@ -221,7 +221,7 @@ describe('selectWorktreeHostConnectionPhase', () => { expect(selectWorktreeHostConnectionPhase(state, 'wt-runtime')).toMatchObject({ phase: 'unverifiable', targetId: 'ssh-nested', - status: null + publishedStatus: null }) }) }) diff --git a/src/renderer/src/lib/worktree-host-connection-phase.ts b/src/renderer/src/lib/worktree-host-connection-phase.ts index bb266376432b..8a0d39d4b1cf 100644 --- a/src/renderer/src/lib/worktree-host-connection-phase.ts +++ b/src/renderer/src/lib/worktree-host-connection-phase.ts @@ -29,8 +29,12 @@ export type WorktreeHostConnection = { targetId: string | null /** The remote runtime whose mirrored SSH state owns the target; null for this client's own. */ environmentId: string | null - /** The status behind `phase`; null when local or unverifiable. */ - status: SshConnectionStatus | null + /** + * The status as published, before `phase` reads an undialed startup target as connecting. + * Surfaces that name the status itself (the terminal's reconnect overlay) read this; null + * when local or unverifiable. + */ + publishedStatus: SshConnectionStatus | null /** Names the live connection: null unless connected, and new on every reconnect. */ connectedEpoch: string | null } @@ -39,15 +43,25 @@ const LOCAL_HOST_CONNECTION: WorktreeHostConnection = { phase: 'local', targetId: null, environmentId: null, - status: null, + publishedStatus: null, connectedEpoch: null } -function selectTargetStatus( +function derivePhase( state: AppState, targetId: string, - environmentId: string | null -): SshConnectionStatus | null { + environmentId: string | null, + publishedStatus: SshConnectionStatus | null +): WorktreeHostConnectionPhase { + if (publishedStatus === null) { + return 'unverifiable' + } + if (publishedStatus === 'connected') { + return 'connected' + } + if (isConnectingSshStatus(publishedStatus)) { + return 'connecting' + } // Why: startup restoration dials the targets that were live at shutdown; until it publishes, // a missing entry means "not dialed yet", not "disconnected". Restoration finishing (or // degrading) ends this on its own. @@ -58,17 +72,7 @@ function selectTargetStatus( ) { return 'connecting' } - return selectRuntimeAwareSshStatus(state, environmentId, targetId) -} - -function phaseForStatus(status: SshConnectionStatus | null): WorktreeHostConnectionPhase { - if (status === null) { - return 'unverifiable' - } - if (status === 'connected') { - return 'connected' - } - return isConnectingSshStatus(status) ? 'connecting' : 'unavailable' + return 'unavailable' } /** The shared signal for a caller that already resolved the worktree's connection id. */ @@ -81,14 +85,14 @@ export function resolveWorktreeHostConnection( return LOCAL_HOST_CONNECTION } const environmentId = getExplicitRuntimeEnvironmentIdForWorktree(state, worktreeId) - const status = selectTargetStatus(state, targetId, environmentId) + const publishedStatus = selectRuntimeAwareSshStatus(state, environmentId, targetId) const generation = selectRuntimeAwareSshConnectionGeneration(state, environmentId, targetId) return { - phase: phaseForStatus(status), + phase: derivePhase(state, targetId, environmentId, publishedStatus), targetId, environmentId, - status, - connectedEpoch: status === 'connected' ? `${targetId}:${generation ?? ''}` : null + publishedStatus, + connectedEpoch: publishedStatus === 'connected' ? `${targetId}:${generation ?? ''}` : null } } From 849d58d9188183d0e3dcbce37cf04ebf89246c59 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 25 Sep 2026 11:58:02 -0700 Subject: [PATCH 8/8] fix(startup): a degraded boot releases terminal startup restoration after reconnect The degraded recovery path's successful reconnect set workspaceSessionReady but never terminalStartupRestorationReady; only its failure branches did. Every reader waiting on restoration then waited for the whole session: no fallback terminal, no structured tab sync, the activation gate timing out, and an SSH target never dialed at startup reading as connecting forever. Release the flag once the reconnect finishes, unless a newer startup pass has taken over. --- .../startup/startup-degraded-recovery.test.ts | 74 +++++++++++++++++++ .../src/startup/startup-degraded-recovery.ts | 5 ++ 2 files changed, 79 insertions(+) create mode 100644 src/renderer/src/startup/startup-degraded-recovery.test.ts diff --git a/src/renderer/src/startup/startup-degraded-recovery.test.ts b/src/renderer/src/startup/startup-degraded-recovery.test.ts new file mode 100644 index 000000000000..a3f0fb44f261 --- /dev/null +++ b/src/renderer/src/startup/startup-degraded-recovery.test.ts @@ -0,0 +1,74 @@ +// @vitest-environment happy-dom +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('sonner', () => ({ toast: { error: vi.fn() } })) +vi.mock('../components/terminal/terminal-provider-snapshot-capability', () => ({ + collectTerminalProviderSnapshotPtyIds: () => [], + refreshTerminalProviderSnapshotCapabilities: async () => undefined +})) +vi.mock('../store', async () => { + const { create } = await import('zustand') + const useAppStore = create(() => ({ + startupWorktreeRefreshCompleted: false, + terminalStartupRestorationReady: false, + workspaceSessionReady: false + })) + return { useAppStore } +}) + +import { useAppStore } from '../store' +import { recoverFromDegradedStartup } from './startup-degraded-recovery' + +function recover(args: { + isCancelled: () => boolean + reconnectPersistedTerminals: () => Promise +}): Promise { + return recoverFromDegradedStartup({ + error: new Error('hydration failed'), + uiHydrated: true, + reconnectStarted: false, + hydratePersistedUI: vi.fn(), + abortSignal: new AbortController().signal, + ...args + }) +} + +describe('recoverFromDegradedStartup', () => { + beforeEach(() => { + vi.spyOn(console, 'error').mockImplementation(() => undefined) + useAppStore.setState({ terminalStartupRestorationReady: false, workspaceSessionReady: false }) + Object.defineProperty(window, 'api', { + configurable: true, + value: { + app: { + awaitFirstWindowStartupServices: async () => undefined, + recoverLegacyWorkerTerminalsForRendererStartup: async () => undefined, + relaunch: vi.fn() + } + } + }) + }) + + it('releases terminal startup restoration once the degraded reconnect succeeds', async () => { + await recover({ + isCancelled: () => false, + reconnectPersistedTerminals: async () => { + useAppStore.setState({ workspaceSessionReady: true }) + } + }) + + expect(useAppStore.getState().terminalStartupRestorationReady).toBe(true) + }) + + it('leaves the flag to the newer pass when this one was cancelled mid-reconnect', async () => { + let cancelled = false + await recover({ + isCancelled: () => cancelled, + reconnectPersistedTerminals: async () => { + cancelled = true + } + }) + + expect(useAppStore.getState().terminalStartupRestorationReady).toBe(false) + }) +}) diff --git a/src/renderer/src/startup/startup-degraded-recovery.ts b/src/renderer/src/startup/startup-degraded-recovery.ts index 987a74a8341e..c5570af27173 100644 --- a/src/renderer/src/startup/startup-degraded-recovery.ts +++ b/src/renderer/src/startup/startup-degraded-recovery.ts @@ -93,6 +93,11 @@ export async function recoverFromDegradedStartup(args: DegradedStartupRecoveryAr ) await reconnectPersistedTerminals(abortSignal) await window.api.app.recoverLegacyWorkerTerminalsForRendererStartup() + // Why: reconnect set workspaceSessionReady but not this flag, which the success chain sets + // last; without it a degraded boot keeps every restoration reader waiting for good. + if (!isCancelled()) { + useAppStore.setState({ terminalStartupRestorationReady: true }) + } } catch (reconnectErr) { console.error('[startup] reconnectPersistedTerminals failed in error path:', reconnectErr) // Why (issue #1158): the await may have run during StrictMode teardown; re-check cancellation so a cancelled pass 1 doesn't stomp pass 2's hydration.