Skip to content
Merged
84 changes: 44 additions & 40 deletions src/renderer/src/components/TerminalLegacyTerminalPanes.tsx
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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 ? <TerminalRestoringPlaceholder key={tab.id} /> : 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 = (
<TerminalPane
key={`${tab.id}-${tab.generation ?? 0}`}
tabId={tab.id}
worktreeId={workspace.id}
cwd={tab.startupCwd ?? workspace.path}
isActive={isActiveTerminalTab || activityTerminalPortal?.active === true}
isVisible={isActiveTerminalTab || isActivityPortalTab}
isWorktreeActive={isVisible || isActivityPortalTab}
isolatedPaneKey={activityTerminalPortal?.paneKey ?? null}
onPtyExit={(ptyId, exitCode) => 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 = (
<TerminalPane
key={`${tab.id}-${tab.generation ?? 0}`}
tabId={tab.id}
worktreeId={workspace.id}
cwd={tab.startupCwd ?? workspace.path}
isActive={isActiveTerminalTab || activityTerminalPortal?.active === true}
isVisible={isActiveTerminalTab || isActivityPortalTab}
isWorktreeActive={isVisible || isActivityPortalTab}
isolatedPaneKey={activityTerminalPortal?.paneKey ?? null}
onPtyExit={(ptyId, exitCode) => handlePtyExit(tab.id, ptyId, exitCode)}
onCloseTab={() => handleCloseTab(tab.id)}
/>
)
if (activityTerminalPortal) {
return createPortal(
terminalPane,
activityTerminalPortal.target,
`activity-terminal-${tab.id}`
)
}
return terminalPane
})}
}
return terminalPane
})}
</div>
)
})}
Expand Down
10 changes: 7 additions & 3 deletions src/renderer/src/components/TerminalSplitWorkspaceSurfaces.tsx
Original file line number Diff line number Diff line change
@@ -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({
Expand All @@ -21,6 +22,7 @@ export function TerminalSplitWorkspaceSurfaces({
measurableBackgroundWorktreeIdsRef,
mountedWorktreeIdsRef,
renderedActiveWorktreeId,
startupTerminalTabHold,
workspaceSurfaces
} = controller
// Why: this and TerminalSurface are both strict ancestors of every browser <webview>, so a
Expand Down Expand Up @@ -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
)}
/>
)
})}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
// @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'
import type { SshConnectionStatus } from '../../../../shared/ssh-types'

const mocks = vi.hoisted(() => {
const hostConnection: WorktreeHostConnection = {
phase: 'connecting',
targetId: 'target-a',
environmentId: null,
status: 'connecting',
connectedEpoch: 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))
})

const STATUS_BY_PHASE: Record<WorktreeHostConnection['phase'], SshConnectionStatus | null> = {
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',
environmentId: null,
status: STATUS_BY_PHASE[phase],
connectedEpoch: phase === 'connected' ? `target-a:${connectionGeneration}` : null
}
}

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')
})
})
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -64,6 +65,23 @@ export function useSshWorkspaceBrowserRoute(
const [state, setState] = useState<SshWorkspaceBrowserRouteState>(
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?.connectedEpoch ?? 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);
Expand All @@ -74,8 +92,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,
Expand All @@ -100,7 +123,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
Expand All @@ -109,7 +132,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 {
Expand Down
18 changes: 18 additions & 0 deletions src/renderer/src/components/editor/local-host-test-fixture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
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,
environmentId: null,
status: null,
connectedEpoch: null
}

export function selectWorktreeHostConnectionPhase(): WorktreeHostConnection {
return LOCAL_HOST_CONNECTION
}

export function useWorktreeHostConnection(): WorktreeHostConnection {
return LOCAL_HOST_CONNECTION
}
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}))
Expand Down
Loading
Loading