diff --git a/mobile/src/host-screen/host-screen-header.tsx b/mobile/src/host-screen/host-screen-header.tsx index 322f1b2c8251..ec7b838475e2 100644 --- a/mobile/src/host-screen/host-screen-header.tsx +++ b/mobile/src/host-screen/host-screen-header.tsx @@ -16,6 +16,7 @@ import { } from 'lucide-react-native' import { StatusDot } from '../components/StatusDot' import { classifyConnection, type ConnectionVerdict } from '../transport/connection-health' +import { useCalmConnectionState } from '../transport/calm-connection-state' import { colors } from '../theme/mobile-theme' import { hostScreenStyles as styles } from './host-screen-styles' import type { HostScreenController } from './use-host-screen-controller' @@ -39,6 +40,8 @@ export function HostScreenHeader({ controller }: { controller: HostScreenControl relayRecovery, state } = controller + // Why: a drop healed in a few seconds must not flash the host dot amber. + const presentedConnState = useCalmConnectionState(connState, lastConnectedAt) return ( @@ -64,7 +67,11 @@ export function HostScreenHeader({ controller }: { controller: HostScreenControl <> - + {presentedConnState !== connState && !isErrorVerdict(headerVerdict) ? ( + + ) : ( + + )} {hostDisplay.title} diff --git a/mobile/src/session/MobileSessionHeader.tsx b/mobile/src/session/MobileSessionHeader.tsx index 12fd1c88f408..ba21c89a85e5 100644 --- a/mobile/src/session/MobileSessionHeader.tsx +++ b/mobile/src/session/MobileSessionHeader.tsx @@ -14,7 +14,7 @@ export function MobileSessionHeader({ controller }: { controller: MobileSessionC hostId, isFolderWorkspaceRoute, isFloatingWorkspaceRoute, - connState, + presentedConnState, forceReconnectHost, worktreeName, activePanel, @@ -66,7 +66,7 @@ export function MobileSessionHeader({ controller }: { controller: MobileSessionC accessibilityRole={showConnectionRetry ? 'button' : undefined} accessibilityLabel={showConnectionRetry ? 'Reconnect to desktop' : undefined} > - + {terminalSummary} diff --git a/mobile/src/session/use-mobile-session-presentation.ts b/mobile/src/session/use-mobile-session-presentation.ts index dca323343b07..cc335efd6ba1 100644 --- a/mobile/src/session/use-mobile-session-presentation.ts +++ b/mobile/src/session/use-mobile-session-presentation.ts @@ -4,6 +4,7 @@ import { useInitialSessionTerminalAutoCreate } from './use-initial-session-termi import { MOBILE_SESSION_STATUS_LABELS } from './mobile-session-route-helpers' import type { MobileSessionBulkCloseModel } from './use-mobile-session-bulk-close' import { hostOs } from '../platform/host-os' +import { useCalmConnectionState } from '../transport/calm-connection-state' export function useMobileSessionPresentation(scope: MobileSessionBulkCloseModel) { const { @@ -61,8 +62,10 @@ export function useMobileSessionPresentation(scope: MobileSessionBulkCloseModel) // Not on the page: the shell owns the connection and the tap could only do nothing. const showConnectionRetry = connectionEscalated && forceReconnectHost !== null + // Why: a drop the client heals in a few seconds must not flip the header to Reconnecting and back. + const presentedConnState = useCalmConnectionState(connState, lastConnectedAt) const terminalSummary = - connState === 'connected' + presentedConnState === 'connected' ? showLoadingState ? 'Loading tabs' : visibleTabs.length === 1 @@ -72,7 +75,7 @@ export function useMobileSessionPresentation(scope: MobileSessionBulkCloseModel) ? `${verdictDisplayLabel(connectionVerdict)} — tap to retry` : connectionEscalated ? verdictDisplayLabel(connectionVerdict) - : MOBILE_SESSION_STATUS_LABELS[connState] + : MOBILE_SESSION_STATUS_LABELS[presentedConnState] // Why: iOS keyboard height includes the home-indicator inset; Android IME height does not. const keyboardLift = @@ -91,6 +94,7 @@ export function useMobileSessionPresentation(scope: MobileSessionBulkCloseModel) transform: [{ translateY: -keyboardLift }] } return { + presentedConnState, showLoadingState, showEmptyState, connectionVerdict, diff --git a/mobile/src/transport/calm-connection-state.test.ts b/mobile/src/transport/calm-connection-state.test.ts new file mode 100644 index 000000000000..c5eee0647aa9 --- /dev/null +++ b/mobile/src/transport/calm-connection-state.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it } from 'vitest' +import { + CALM_STATUS_IDLE, + CALM_STATUS_REVEAL_DELAY_MS +} from '../../../src/shared/calm-status-reveal' +import { stepCalmConnectionState } from './calm-connection-state' +import type { ConnectionState } from './types' + +function present( + lastConnectedAt: number | null, + events: { at: number; state: ConnectionState }[] +): ConnectionState[] { + let reveal = CALM_STATUS_IDLE + return events.map(({ at, state }) => { + const step = stepCalmConnectionState(reveal, { state, lastConnectedAt, now: at }) + reveal = step.next + return step.presented + }) +} + +describe('stepCalmConnectionState', () => { + it('keeps the header connected through a reconnect that heals within the delay', () => { + expect( + present(0, [ + { at: 1_000, state: 'reconnecting' }, + { at: 2_000, state: 'handshaking' }, + { at: 3_500, state: 'connected' } + ]) + ).toEqual(['connected', 'connected', 'connected']) + }) + + it('says Reconnecting once the drop outlasts the delay', () => { + expect( + present(0, [ + { at: 1_000, state: 'reconnecting' }, + { at: 1_000 + CALM_STATUS_REVEAL_DELAY_MS, state: 'reconnecting' } + ]) + ).toEqual(['connected', 'reconnecting']) + }) + + it('shows the first connect and a refused pairing at once', () => { + expect(present(null, [{ at: 0, state: 'connecting' }])).toEqual(['connecting']) + expect(present(0, [{ at: 1_000, state: 'auth-failed' }])).toEqual(['auth-failed']) + }) + + it('shows a drop already under way when the screen opens long after the last connect', () => { + const step = stepCalmConnectionState(CALM_STATUS_IDLE, { + state: 'reconnecting', + lastConnectedAt: 0, + now: 10 * 60_000, + since: 0 + }) + expect(step.presented).toBe('reconnecting') + }) + + it('keeps a drop that just appeared on screen through its minimum time', () => { + let reveal = CALM_STATUS_IDLE + let shown: ConnectionState = 'connected' + const presented = [ + { at: 1_000, state: 'reconnecting' as const }, + { at: 1_000 + CALM_STATUS_REVEAL_DELAY_MS, state: 'reconnecting' as const }, + { at: 1_010 + CALM_STATUS_REVEAL_DELAY_MS, state: 'connected' as const } + ].map(({ at, state }) => { + const step = stepCalmConnectionState(reveal, { state, lastConnectedAt: 0, now: at, shown }) + reveal = step.next + shown = step.presented + return step.presented + }) + expect(presented).toEqual(['connected', 'reconnecting', 'reconnecting']) + }) +}) diff --git a/mobile/src/transport/calm-connection-state.ts b/mobile/src/transport/calm-connection-state.ts new file mode 100644 index 000000000000..e2ba9387e085 --- /dev/null +++ b/mobile/src/transport/calm-connection-state.ts @@ -0,0 +1,82 @@ +import { useEffect, useRef, useState } from 'react' +import { + CALM_STATUS_IDLE, + stepCalmStatusReveal, + type CalmStatusReveal +} from '../../../src/shared/calm-status-reveal' +import type { ConnectionState } from './types' + +/** + * What the header shows for a connection: a drop after this session was connected reads as + * connected until it outlasts a clean reconnect, the same schedule the desktop banner uses. + * The first connect and a refused pairing show at once. + */ +export function stepCalmConnectionState( + previous: CalmStatusReveal, + input: { + state: ConnectionState + lastConnectedAt: number | null + now: number + /** On mount the drop already happened unseen; it began no earlier than the last connect. */ + since?: number | null + /** What the header shows now; a drop on screen stays through its minimum time and hold. */ + shown?: ConnectionState + } +): { next: CalmStatusReveal; presented: ConnectionState; recheckInMs: number | null } { + // Why 'disconnected' waits too: an app suspend publishes it and the resume redials at once. + const healing = input.state !== 'auth-failed' && input.lastConnectedAt !== null + const step = stepCalmStatusReveal(previous, { + down: input.state !== 'connected', + immediate: !healing, + now: input.now, + since: input.since + }) + return { + next: step.next, + presented: !step.visible + ? 'connected' + : input.state !== 'connected' + ? input.state + : (input.shown ?? 'connected'), + recheckInMs: step.recheckInMs + } +} + +export function useCalmConnectionState( + state: ConnectionState, + lastConnectedAt: number | null +): ConnectionState { + const revealRef = useRef(CALM_STATUS_IDLE) + const [presented, setPresented] = useState( + () => + stepCalmConnectionState(CALM_STATUS_IDLE, { + state, + lastConnectedAt, + now: Date.now(), + since: lastConnectedAt + }).presented + ) + const [wake, setWake] = useState(0) + const observedRef = useRef(false) + const shownRef = useRef(presented) + useEffect(() => { + const step = stepCalmConnectionState(revealRef.current, { + state, + lastConnectedAt, + now: Date.now(), + // Why the last connect: the drop time is unseen on mount; erring early shows a real outage at once. + since: observedRef.current ? null : lastConnectedAt, + shown: shownRef.current + }) + observedRef.current = true + revealRef.current = step.next + shownRef.current = step.presented + setPresented(step.presented) + if (step.recheckInMs === null) { + return + } + const timer = setTimeout(() => setWake((count) => count + 1), Math.max(0, step.recheckInMs)) + return () => clearTimeout(timer) + }, [state, lastConnectedAt, wake]) + return presented +} diff --git a/src/renderer/src/components/terminal-pane/RemoteRuntimeRecoveryCard.tsx b/src/renderer/src/components/terminal-pane/RemoteRuntimeRecoveryCard.tsx new file mode 100644 index 000000000000..ba53cf4c144f --- /dev/null +++ b/src/renderer/src/components/terminal-pane/RemoteRuntimeRecoveryCard.tsx @@ -0,0 +1,95 @@ +import { useEffect, useState } from 'react' +import { Clock, KeyRound, ServerOff } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { LoadingSpinner } from '@/components/LoadingSpinner' +import { tailscalePingCommand } from '../../../../shared/remote-runtime/remote-runtime-tailscale-hint' +import { + remoteRuntimeDownForLabel, + remoteRuntimeTailscaleHintLabel +} from './remote-runtime-recovery-copy' + +function useNow(active: boolean): number { + const [now, setNow] = useState(() => Date.now()) + useEffect(() => { + if (!active) { + return + } + setNow(Date.now()) + const timer = setInterval(() => setNow(Date.now()), 1_000) + return () => clearInterval(timer) + }, [active]) + return now +} + +/** The one look for "this remote work is recovering", shared by the pane and server notices. */ +export function RemoteRuntimeRecoveryCard({ + icon, + title, + body, + downSince = null, + tailscaleHost = null, + action = null, + data +}: { + icon: 'retrying' | 'waiting' | 'sign-in' | 'stopped' + title: string + body: string + downSince?: number | null + tailscaleHost?: string | null + action?: { label: string; onClick: () => void } | null + data: Record<`data-${string}`, string> +}): React.JSX.Element { + const now = useNow(downSince !== null) + return ( +
+
+
+ {icon === 'retrying' ? ( + + ) : icon === 'sign-in' ? ( + + ) : icon === 'waiting' ? ( + + ) : ( + + )} +
+
+
+
{title}
+ {downSince !== null ? ( + // Why hidden: a per-second tick inside the live region would re-announce the whole card. + + ) : null} +
+
{body}
+ {tailscaleHost ? ( +
+ {remoteRuntimeTailscaleHintLabel()} + + {tailscalePingCommand(tailscaleHost)} + +
+ ) : null} +
+ {action ? ( + + ) : null} +
+
+ ) +} diff --git a/src/renderer/src/components/terminal-pane/RemoteServerOutageNotice.tsx b/src/renderer/src/components/terminal-pane/RemoteServerOutageNotice.tsx new file mode 100644 index 000000000000..effd02252eba --- /dev/null +++ b/src/renderer/src/components/terminal-pane/RemoteServerOutageNotice.tsx @@ -0,0 +1,44 @@ +import { useAppStore } from '@/store' +import type { CalmStatusView } from '@/hooks/use-calm-status-reveal' +import { RemoteRuntimeRecoveryCard } from './RemoteRuntimeRecoveryCard' +import { remoteRuntimeRecoveryCopy } from './remote-runtime-recovery-copy' +import { + selectRemoteServerOutageCause, + selectRuntimeServerName, + selectRuntimeServerTailscaleHost +} from './remote-server-outage' + +/** + * The one notice for a server whose shared connection dropped and is retrying, in place of a + * banner in every pane. The surface owns `reveal`, so its panes stay quiet for as long as this shows. + */ +export function RemoteServerOutageNotice({ + environmentId, + reveal +}: { + environmentId: string + reveal: CalmStatusView +}): React.JSX.Element | null { + const serverName = useAppStore((state) => selectRuntimeServerName(state, environmentId)) + const cause = useAppStore((state) => selectRemoteServerOutageCause(state, environmentId)) + const tailscaleHost = useAppStore((state) => + selectRuntimeServerTailscaleHost(state, environmentId) + ) + if (!reveal.visible) { + return null + } + const copy = remoteRuntimeRecoveryCopy(cause, serverName) + return ( + + ) +} diff --git a/src/renderer/src/components/terminal-pane/TerminalPaneRecoveryPortals.test.tsx b/src/renderer/src/components/terminal-pane/TerminalPaneRecoveryPortals.test.tsx new file mode 100644 index 000000000000..78b1628e1a0b --- /dev/null +++ b/src/renderer/src/components/terminal-pane/TerminalPaneRecoveryPortals.test.tsx @@ -0,0 +1,178 @@ +// @vitest-environment happy-dom + +import '@testing-library/jest-dom/vitest' +import { act, cleanup, render } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + CALM_STATUS_MIN_VISIBLE_MS, + CALM_STATUS_REVEAL_DELAY_MS +} from '../../../../shared/calm-status-reveal' +import type { TerminalPaneController } from './use-terminal-pane-controller' +import { resetRemoteServerNoticeClaimsForTests } from './remote-server-notice-claims' + +const outage = vi.hoisted((): { environmentId: string | null } => ({ environmentId: 'env-1' })) + +vi.mock('@/i18n/i18n', () => ({ + translate: (_key: string, fallback: string, options?: Record) => + fallback.replace(/\{\{(\w+)\}\}/g, (_match, name: string) => options?.[name] ?? ''), + getIntlLocale: () => 'en-US' +})) +vi.mock('@/store', () => ({ useAppStore: (selector: (state: unknown) => unknown) => selector({}) })) +vi.mock('./use-wsl-host-unavailable-reason', () => ({ useWslHostUnavailableReason: () => null })) +vi.mock('./use-managed-pairing-refused', () => ({ + useManagedPairingRefusedEnvironmentId: () => null +})) +vi.mock('./remote-server-outage', () => ({ + useWorkspaceRuntimeEnvironmentId: () => 'env-1', + useRetryingOutageEnvironmentId: () => outage.environmentId, + selectRuntimeServerName: () => 'Desk', + selectRuntimeServerTailscaleHost: () => null, + selectRemoteServerOutageCause: () => 'connection-lost' +})) + +afterEach(() => { + outage.environmentId = 'env-1' + cleanup() + resetRemoteServerNoticeClaimsForTests() + document.body.innerHTML = '' + vi.useRealTimers() +}) + +function controllerFor(panes: HTMLElement[]): TerminalPaneController { + const transport = { getRuntimeEnvironmentId: () => 'env-1' } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the recovery portals read only these fields of the pane controller. + return { + managedPanes: panes.map((container, index) => ({ id: index + 1, container })), + ptyRecoveryStatesByPaneId: Object.fromEntries( + panes.map((_, index) => [index + 1, { phase: 'backoff', epoch: 1, attempt: 1 }]) + ), + paneTransportsRef: { current: new Map(panes.map((_, index) => [index + 1, transport])) }, + showSshReconnectOverlay: false, + worktreeId: 'wt-1', + isVisible: true, + isolatedPaneKey: null + } as unknown as TerminalPaneController +} + +describe('TerminalPaneRecoveryPortals', () => { + it('says a server-wide drop once for the tab and keeps every split pane quiet', async () => { + vi.useFakeTimers() + const { TerminalPaneRecoveryPortals } = await import('./TerminalPaneRecoveryPortals') + const panes = [document.createElement('div'), document.createElement('div')] + panes.forEach((pane) => document.body.appendChild(pane)) + const view = render() + + act(() => vi.advanceTimersByTime(CALM_STATUS_REVEAL_DELAY_MS)) + + expect(view.container.querySelectorAll('[data-remote-server-outage-notice]')).toHaveLength(1) + expect( + document.querySelectorAll('[data-terminal-remote-runtime-reconnect-banner]') + ).toHaveLength(0) + }) + + it('keeps every surface on the server quiet through the notice hold, then lets a still-down pane speak', async () => { + vi.useFakeTimers() + const { TerminalPaneRecoveryPortals } = await import('./TerminalPaneRecoveryPortals') + const leftPane = document.createElement('div') + const rightPane = document.createElement('div') + document.body.append(leftPane, rightPane) + const left = controllerFor([leftPane]) + const right = controllerFor([rightPane]) + const surfaces = (l: TerminalPaneController, r: TerminalPaneController) => ( + <> + + + + ) + const view = render(surfaces(left, right)) + act(() => vi.advanceTimersByTime(CALM_STATUS_REVEAL_DELAY_MS * 2)) + const notices = () => view.container.querySelectorAll('[data-remote-server-outage-notice]') + const paneBanners = () => + document.querySelectorAll('[data-terminal-remote-runtime-reconnect-banner]') + expect(notices()).toHaveLength(1) + + outage.environmentId = null + view.rerender(surfaces({ ...left }, { ...right })) + expect(notices()).toHaveLength(1) + expect(paneBanners()).toHaveLength(0) + + act(() => vi.advanceTimersByTime(CALM_STATUS_MIN_VISIBLE_MS)) + expect(notices()).toHaveLength(0) + expect(paneBanners()).toHaveLength(2) + }) + + it('lets a pane waiting for SSH sign-in say so at once instead of a server notice', async () => { + vi.useFakeTimers() + const { TerminalPaneRecoveryPortals } = await import('./TerminalPaneRecoveryPortals') + const pane = document.createElement('div') + document.body.append(pane) + const base = controllerFor([pane]) + const controller = { + ...base, + ptyRecoveryStatesByPaneId: { + 1: { phase: 'backoff' as const, epoch: 1, attempt: 1, reason: 'ssh-sign-in' as const } + } + } + const view = render() + + expect( + document.querySelectorAll('[data-terminal-remote-runtime-reconnect-banner="ssh-sign-in"]') + ).toHaveLength(1) + act(() => vi.advanceTimersByTime(CALM_STATUS_REVEAL_DELAY_MS * 2)) + expect(view.container.querySelectorAll('[data-remote-server-outage-notice]')).toHaveLength(0) + }) + + it('drops a visible notice at once when a pane starts waiting for SSH sign-in', async () => { + vi.useFakeTimers() + const { TerminalPaneRecoveryPortals } = await import('./TerminalPaneRecoveryPortals') + const pane = document.createElement('div') + document.body.append(pane) + const controller = controllerFor([pane]) + const view = render() + act(() => vi.advanceTimersByTime(CALM_STATUS_REVEAL_DELAY_MS * 2)) + expect(view.container.querySelectorAll('[data-remote-server-outage-notice]')).toHaveLength(1) + + view.rerender( + + ) + + expect(view.container.querySelectorAll('[data-remote-server-outage-notice]')).toHaveLength(0) + expect( + document.querySelectorAll('[data-terminal-remote-runtime-reconnect-banner="ssh-sign-in"]') + ).toHaveLength(1) + }) + + it('never shows two notices when the speaker hides and returns during an ongoing outage', async () => { + vi.useFakeTimers() + const { TerminalPaneRecoveryPortals } = await import('./TerminalPaneRecoveryPortals') + const leftPane = document.createElement('div') + const rightPane = document.createElement('div') + document.body.append(leftPane, rightPane) + const left = controllerFor([leftPane]) + const right = controllerFor([rightPane]) + const surfaces = (l: TerminalPaneController) => ( + <> + + + + ) + const view = render(surfaces(left)) + act(() => vi.advanceTimersByTime(CALM_STATUS_REVEAL_DELAY_MS * 2)) + const notices = () => view.container.querySelectorAll('[data-remote-server-outage-notice]') + + view.rerender(surfaces({ ...left, isVisible: false })) + view.rerender(surfaces({ ...left, isVisible: true })) + expect(notices()).toHaveLength(1) + + outage.environmentId = null + view.rerender(surfaces({ ...left, isVisible: true })) + expect(notices()).toHaveLength(1) + }) +}) diff --git a/src/renderer/src/components/terminal-pane/TerminalPaneRecoveryPortals.tsx b/src/renderer/src/components/terminal-pane/TerminalPaneRecoveryPortals.tsx new file mode 100644 index 000000000000..cae86d0cad30 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/TerminalPaneRecoveryPortals.tsx @@ -0,0 +1,155 @@ +import { useState } from 'react' +import { createPortal } from 'react-dom' +import type { PtyTransport } from './pty-transport-types' +import { useWslHostUnavailableReason } from './use-wsl-host-unavailable-reason' +import { useManagedPairingRefusedEnvironmentId } from './use-managed-pairing-refused' +import { CalmRemoteRuntimeReconnectBanner } from './TerminalRemoteRuntimeReconnectBanner' +import { + useRetryingOutageEnvironmentId, + useWorkspaceRuntimeEnvironmentId +} from './remote-server-outage' +import { + usePublishRemoteServerNoticeShowing, + useRemoteServerNoticeClaim +} from './remote-server-notice-claims' +import { RemoteServerOutageNotice } from './RemoteServerOutageNotice' +import { useCalmStatusReveal } from '@/hooks/use-calm-status-reveal' +import type { TerminalPaneController } from './use-terminal-pane-controller' + +/** + * What a pane's Reconnect does: pair again first when the server refused us, sign in first when + * the SSH host waits for it, and otherwise retry the pane. + */ +export function createPaneRecoveryReconnect( + getTransport: () => PtyTransport | undefined, + pairingRefusedEnvironmentId: string | null, + awaitingSignIn = false +): () => void { + return () => { + const retry = (): void => { + getTransport()?.retryRecovery?.() + } + // Why connect first: it asks Orca to pair again, which a pane retry alone does not. + if (pairingRefusedEnvironmentId) { + void window.api.runtimeEnvironments + .connect({ selector: pairingRefusedEnvironmentId }) + .catch(() => undefined) + .finally(retry) + return + } + const signInEnvironmentId = awaitingSignIn ? getTransport()?.getRuntimeEnvironmentId?.() : null + if (signInEnvironmentId) { + // Why no retry on failure: a rejected password must not re-dial into a second prompt; + // the control-ready revival starts the pane once sign-in succeeds. + void window.api.runtimeEnvironments + .connect({ selector: signInEnvironmentId }) + .then((response) => { + if (response.ok) { + retry() + } + }) + .catch(() => undefined) + return + } + retry() + } +} + +export function TerminalPaneRecoveryPortals({ + controller +}: { + controller: TerminalPaneController +}): React.JSX.Element | null { + const { managedPanes, paneTransportsRef, ptyRecoveryStatesByPaneId, showSshReconnectOverlay } = + controller + const wslHostUnavailable = useWslHostUnavailableReason(controller.worktreeId) + const pairingRefusedEnvironmentId = useManagedPairingRefusedEnvironmentId(controller.worktreeId) + const ownerEnvironmentId = useWorkspaceRuntimeEnvironmentId(controller.worktreeId) + const retryingOutageEnvironmentId = useRetryingOutageEnvironmentId(controller.worktreeId) + const isolated = controller.isolatedPaneKey !== null + // Why: a pane waiting for SSH sign-in says so itself; "reconnecting" over it would be false. + const awaitingSignInHere = managedPanes.some( + (pane) => ptyRecoveryStatesByPaneId[pane.id]?.reason === 'ssh-sign-in' + ) + // Why not isolated panes: an Activity thread shows one pane away from this tab's surface. + const canSpeak = + controller.isVisible && + !isolated && + !showSshReconnectOverlay && + !awaitingSignInHere && + !wslHostUnavailable && + pairingRefusedEnvironmentId === null + const serverDown = retryingOutageEnvironmentId !== null + const notice = useRemoteServerNoticeClaim(ownerEnvironmentId, serverDown, canSpeak) + const [noticeEnvironmentId, setNoticeEnvironmentId] = useState(null) + if (notice.speaks && ownerEnvironmentId !== noticeEnvironmentId) { + setNoticeEnvironmentId(ownerEnvironmentId) + } + const revealed = useCalmStatusReveal(notice.speaks, false, notice.since) + // Why gated on canSpeak: the hold is for a server that answered, not for a surface that lost its + // turn (hidden, sign-in, WSL), whose own cards must not land under a lingering notice. + // Why: a surface that lost the lead while the server is still down handed its notice to + // another; only the leader when the outage ends may hold, so a handoff never shows two. + const [handedOff, setHandedOff] = useState(false) + if (notice.speaks && handedOff) { + setHandedOff(false) + } else if (!notice.speaks && serverDown && revealed.visible && !handedOff) { + setHandedOff(true) + } + const noticeReveal = + canSpeak && !handedOff && (notice.speaks || !serverDown) + ? revealed + : { visible: false, downSince: null } + usePublishRemoteServerNoticeShowing(noticeEnvironmentId, noticeReveal.visible) + if (showSshReconnectOverlay) { + return null + } + return ( + <> + {noticeEnvironmentId ? ( + + ) : null} + {managedPanes.map((pane) => { + const recoveryState = ptyRecoveryStatesByPaneId[pane.id] + const awaitingSignIn = recoveryState?.reason === 'ssh-sign-in' + const transport = paneTransportsRef.current.get(pane.id) + // Why only when unknown: a bridged pane reports null on purpose and must not borrow the owner's server. + const paneEnvironmentId = transport?.getRuntimeEnvironmentId + ? transport.getRuntimeEnvironmentId() + : ownerEnvironmentId + // Why mounted with no recovery: the banner's minimum time and hold outlive the recovery itself. + return createPortal( + paneTransportsRef.current.get(pane.id), + pairingRefusedEnvironmentId, + awaitingSignIn + )} + wslHostUnavailable={wslHostUnavailable} + pairingRefused={pairingRefusedEnvironmentId !== null} + awaitingSignIn={awaitingSignIn} + />, + pane.container, + `remote-runtime-reconnect-${pane.id}` + ) + })} + + ) +} diff --git a/src/renderer/src/components/terminal-pane/TerminalPaneRuntimePortals.tsx b/src/renderer/src/components/terminal-pane/TerminalPaneRuntimePortals.tsx index 158040ff4858..40860e5de326 100644 --- a/src/renderer/src/components/terminal-pane/TerminalPaneRuntimePortals.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalPaneRuntimePortals.tsx @@ -7,9 +7,6 @@ import { ClaudeDiffPanelNoticeBanner } from './ClaudeDiffPanelNoticeBanner' import { NewerDaemonHoldBanner } from './NewerDaemonHoldBanner' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' import { TerminalSshReconnectOverlay } from './TerminalSshReconnectOverlay' -import { useWslHostUnavailableReason } from './use-wsl-host-unavailable-reason' -import { useManagedPairingRefusedEnvironmentId } from './use-managed-pairing-refused' -import { DelayedRemoteRuntimeReconnectBanner } from './TerminalRemoteRuntimeReconnectBanner' import { TerminalProcessExitOverlay } from './TerminalProcessExitOverlay' import { MobileDriverOverlay } from './MobileDriverOverlay' import { getDriverForPty } from '@/lib/pane-manager/mobile-driver-state' @@ -18,6 +15,8 @@ import { shouldShowMobileDriverOverlay } from './mobile-driver-overlay-visibilit import { shouldChatTakeOverMobileSurface } from '../native-chat/native-chat-send-eligibility' import type { TerminalPaneController } from './use-terminal-pane-controller' +export { TerminalPaneRecoveryPortals } from './TerminalPaneRecoveryPortals' + export function TerminalPaneCodexRestartPortals({ controller }: { @@ -170,74 +169,6 @@ export function TerminalPaneSshReconnectPortals({ ) } -export function TerminalPaneRecoveryPortals({ - controller -}: { - controller: TerminalPaneController -}): React.JSX.Element | null { - const { managedPanes, paneTransportsRef, ptyRecoveryStatesByPaneId, showSshReconnectOverlay } = - controller - const wslHostUnavailable = useWslHostUnavailableReason(controller.worktreeId) - const pairingRefusedEnvironmentId = useManagedPairingRefusedEnvironmentId(controller.worktreeId) - if (showSshReconnectOverlay) { - return null - } - return ( - <> - {managedPanes.map((pane) => { - const recoveryState = ptyRecoveryStatesByPaneId[pane.id] - if (!recoveryState || recoveryState.reason === 'ownership') { - return null - } - const awaitingSignIn = recoveryState.reason === 'ssh-sign-in' - return createPortal( - { - const retry = (): void => { - paneTransportsRef.current.get(pane.id)?.retryRecovery?.() - } - // Why connect first: it asks Orca to pair again, which a pane retry alone does not. - if (pairingRefusedEnvironmentId) { - void window.api.runtimeEnvironments - .connect({ selector: pairingRefusedEnvironmentId }) - .catch(() => undefined) - .finally(retry) - return - } - const signInEnvironmentId = awaitingSignIn - ? paneTransportsRef.current.get(pane.id)?.getRuntimeEnvironmentId?.() - : null - if (signInEnvironmentId) { - // Why no retry on failure: a rejected password must not re-dial into a second prompt; - // the control-ready revival starts the pane once sign-in succeeds. - void window.api.runtimeEnvironments - .connect({ selector: signInEnvironmentId }) - .then((response) => { - if (response.ok) { - retry() - } - }) - .catch(() => undefined) - return - } - retry() - }} - wslHostUnavailable={wslHostUnavailable} - pairingRefused={pairingRefusedEnvironmentId !== null} - awaitingSignIn={awaitingSignIn} - />, - pane.container, - `remote-runtime-reconnect-${pane.id}` - ) - })} - - ) -} - export function TerminalPaneMobileDriverPortals({ controller }: { diff --git a/src/renderer/src/components/terminal-pane/TerminalRemoteRuntimeReconnectBanner.test.tsx b/src/renderer/src/components/terminal-pane/TerminalRemoteRuntimeReconnectBanner.test.tsx index 3065f0ca677c..ee5035b639d9 100644 --- a/src/renderer/src/components/terminal-pane/TerminalRemoteRuntimeReconnectBanner.test.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalRemoteRuntimeReconnectBanner.test.tsx @@ -5,13 +5,33 @@ import { act, cleanup, render, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { afterEach, describe, expect, it, vi } from 'vitest' import { - DelayedRemoteRuntimeReconnectBanner, - REMOTE_RUNTIME_RECOVERY_BANNER_DELAY_MS, + CalmRemoteRuntimeReconnectBanner, TerminalRemoteRuntimeReconnectBanner } from './TerminalRemoteRuntimeReconnectBanner' +import { + CALM_STATUS_MIN_VISIBLE_MS, + CALM_STATUS_REVEAL_DELAY_MS +} from '../../../../shared/calm-status-reveal' vi.mock('@/i18n/i18n', () => ({ - translate: (_key: string, fallback: string) => fallback + translate: (_key: string, fallback: string, options?: Record) => + fallback.replace(/\{\{(\w+)\}\}/g, (_match, name: string) => options?.[name] ?? ''), + getIntlLocale: () => 'en-US' +})) + +vi.mock('@/store', () => ({ + useAppStore: (selector: (state: unknown) => unknown) => + selector({ + settings: {}, + runtimeEnvironments: [ + { + id: 'env-1', + name: 'Desk', + preferredEndpointId: 'ws', + endpoints: [{ id: 'ws', endpoint: 'ws://100.101.102.103:6768' }] + } + ] + }) })) afterEach(() => { @@ -20,41 +40,81 @@ afterEach(() => { }) describe('TerminalRemoteRuntimeReconnectBanner', () => { - it('shows quiet bounded automatic recovery without a manual action', () => { - render() + it('names the server and the cause while retrying, without a manual action', () => { + render( + + ) - expect(screen.getByText('Reconnecting to remote runtime')).toBeInTheDocument() - expect(screen.getByText(/retrying automatically/)).toBeInTheDocument() + expect(screen.getByText('Terminal stopped responding')).toBeInTheDocument() + expect(screen.getByText(/Desk stopped sending/)).toBeInTheDocument() expect(screen.queryByRole('button')).not.toBeInTheDocument() }) - it('offers one explicit reconnect action after automatic recovery stops', async () => { + it('stays neutral when nothing shows the connection dropped, such as a capacity refusal', () => { + render( + + ) + + expect(screen.getByText('Reattaching terminal')).toBeInTheDocument() + expect(screen.queryByText(/connection to the server dropped/)).not.toBeInTheDocument() + expect(screen.queryByText(/tailscale ping/)).not.toBeInTheDocument() + }) + + it('never claims a parked pane is retrying, and offers to try now', async () => { const onReconnect = vi.fn() const user = userEvent.setup() - render() + render( + + ) - expect(screen.getByText('Remote runtime disconnected')).toBeInTheDocument() + expect(screen.getByText('Waiting for Desk')).toBeInTheDocument() + expect(screen.queryByText(/retrying/i)).not.toBeInTheDocument() await user.click(screen.getByRole('button', { name: 'Reconnect' })) expect(onReconnect).toHaveBeenCalledOnce() }) - it('says the host refused this computer instead of spinning, even mid-recovery', async () => { + it('offers one explicit reconnect action after automatic recovery stops', async () => { const onReconnect = vi.fn() const user = userEvent.setup() render( ) - expect(screen.getByText('This host no longer accepts this computer')).toBeInTheDocument() - expect(screen.getByText(/couldn't pair with it again over SSH/)).toBeInTheDocument() - expect(screen.queryByText('Reconnecting to remote runtime')).not.toBeInTheDocument() + expect(screen.getByText('Remote runtime disconnected')).toBeInTheDocument() await user.click(screen.getByRole('button', { name: 'Reconnect' })) expect(onReconnect).toHaveBeenCalledOnce() }) + + it('says the host refused this computer instead of spinning, even mid-recovery', () => { + render( + + ) + + expect(screen.getByText('This host no longer accepts this computer')).toBeInTheDocument() + expect(screen.queryByText('Reconnecting to Desk')).not.toBeInTheDocument() + }) }) describe('SSH sign-in wait', () => { @@ -64,9 +124,10 @@ describe('SSH sign-in wait', () => { const onReconnect = vi.fn() const user = userEvent.setup() render( - @@ -80,32 +141,123 @@ describe('SSH sign-in wait', () => { ) }) -describe('DelayedRemoteRuntimeReconnectBanner', () => { - it('keeps a brief resubscribe from flashing the retrying banner', () => { +describe('CalmRemoteRuntimeReconnectBanner', () => { + it('drops a resolved sign-in card at once instead of holding stale copy', () => { vi.useFakeTimers() + const props = { environmentId: 'env-1', heldByServer: false, onReconnect: vi.fn() } const { rerender } = render( - + ) - act(() => vi.advanceTimersByTime(REMOTE_RUNTIME_RECOVERY_BANNER_DELAY_MS - 1)) + expect(screen.getByText('Waiting for SSH sign-in')).toBeInTheDocument() + + rerender() + + expect(screen.queryByRole('status')).not.toBeInTheDocument() + }) + + it('stays quiet through a reconnect a 400 ms relay finishes, then says it with a Tailscale hint', () => { + vi.useFakeTimers() + const { rerender } = render( + + ) + act(() => vi.advanceTimersByTime(CALM_STATUS_REVEAL_DELAY_MS - 1)) rerender( - + ) expect(screen.queryByRole('status')).not.toBeInTheDocument() act(() => vi.advanceTimersByTime(1)) - expect(screen.getByText('Reconnecting to remote runtime')).toBeInTheDocument() + expect(screen.getByText('Reconnecting to Desk')).toBeInTheDocument() + expect(screen.getByText('tailscale ping 100.101.102.103')).toBeInTheDocument() }) - it('shows a stopped recovery at once and keeps it up through a manual reconnect', () => { + it('shows a stopped recovery at once', () => { vi.useFakeTimers() - const { rerender } = render( - + render( + ) expect(screen.getByText('Remote runtime disconnected')).toBeInTheDocument() + }) + it('keeps a manual Reconnect from hiding the banner it was clicked on', () => { + vi.useFakeTimers() + const { rerender } = render( + + ) + rerender( + + ) + expect(screen.getByText('Reconnecting to Desk')).toBeInTheDocument() + }) + + it('holds a banner that just appeared long enough to read, then lets it go', () => { + vi.useFakeTimers() + const props = { environmentId: 'env-1', heldByServer: false, onReconnect: vi.fn() } + const { rerender } = render( + + ) + act(() => vi.advanceTimersByTime(CALM_STATUS_REVEAL_DELAY_MS + 100)) + rerender() + expect(screen.getByRole('status')).toBeInTheDocument() + + act(() => vi.advanceTimersByTime(CALM_STATUS_MIN_VISIBLE_MS)) + expect(screen.queryByRole('status')).not.toBeInTheDocument() + }) + + it('leaves a server-wide drop to the server notice', () => { + vi.useFakeTimers() + render( + + ) + act(() => vi.advanceTimersByTime(CALM_STATUS_REVEAL_DELAY_MS * 2)) + expect(screen.queryByRole('status')).not.toBeInTheDocument() + }) + + it('speaks at once for a pane still down when the server notice ends', () => { + vi.useFakeTimers() + const props = { environmentId: 'env-1', onReconnect: vi.fn() } + const recovery = { phase: 'backoff' as const, cause: 'stream-stalled' as const } + const { rerender } = render( + + ) + act(() => vi.advanceTimersByTime(CALM_STATUS_REVEAL_DELAY_MS * 2)) rerender( - + ) - expect(screen.getByText('Reconnecting to remote runtime')).toBeInTheDocument() + expect(screen.getByText('Terminal stopped responding')).toBeInTheDocument() }) }) diff --git a/src/renderer/src/components/terminal-pane/TerminalRemoteRuntimeReconnectBanner.tsx b/src/renderer/src/components/terminal-pane/TerminalRemoteRuntimeReconnectBanner.tsx index bd0c9502187c..244adb319308 100644 --- a/src/renderer/src/components/terminal-pane/TerminalRemoteRuntimeReconnectBanner.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalRemoteRuntimeReconnectBanner.tsx @@ -1,164 +1,187 @@ -import { useEffect, useState } from 'react' -import { KeyRound, Loader2, ServerOff } from 'lucide-react' -import { Button } from '@/components/ui/button' +import { useLayoutEffect, useState } from 'react' import { translate } from '@/i18n/i18n' -import type { PtyTransportRecoveryState } from './pty-transport-types' +import { useCalmStatusReveal } from '@/hooks/use-calm-status-reveal' +import type { VisiblePtyRecoveryState } from './terminal-remote-runtime-recovery-ui-state' import type { WslHostUnavailableReason } from './use-wsl-host-unavailable-reason' import { WslHostUnavailableBanner } from './WslHostUnavailableBanner' +import { RemoteRuntimeRecoveryCard } from './RemoteRuntimeRecoveryCard' +import { + fallbackRemoteServerName, + paneRecoveryCause, + remoteRuntimeRecoveryCopy +} from './remote-runtime-recovery-copy' +import { selectRuntimeServerName, selectRuntimeServerTailscaleHost } from './remote-server-outage' +import { useAppStore } from '@/store' -type VisibleRecoveryPhase = Extract< - PtyTransportRecoveryState['phase'], - 'recovering' | 'backoff' | 'disconnected' -> - -// Why: a resubscribe that lands on its first backoff step plus an SSH round trip is -// invisible to the user, so announcing it only flashes a banner. -export const REMOTE_RUNTIME_RECOVERY_BANNER_DELAY_MS = 1_000 +type BannerProps = { + recovery: Pick + serverName: string + onReconnect: () => void + downSince?: number | null + tailscaleHost?: string | null + /** The pane's WSL host cannot run: nothing is retrying, so say why instead. */ + wslHostUnavailable?: WslHostUnavailableReason | null + /** The pane's managed server refuses this desktop and pairing again over SSH failed. */ + pairingRefused?: boolean + /** Main refused because the SSH host is waiting for the user to sign in; it resumes after. */ + awaitingSignIn?: boolean +} -/** Shows retrying recovery only once it outlasts the delay; anything needing action shows at once. */ -export function useRemoteRuntimeRecoveryBannerRevealed(needsAction: boolean): boolean { - const [revealed, setRevealed] = useState(needsAction) - if (needsAction && !revealed) { - setRevealed(true) +function reconnectAction(onReconnect: () => void): { label: string; onClick: () => void } { + return { + label: translate( + 'auto.components.terminal.pane.TerminalRemoteRuntimeReconnectBanner.reconnectButton', + 'Reconnect' + ), + onClick: onReconnect } - useEffect(() => { - if (revealed) { - return - } - const timer = window.setTimeout( - () => setRevealed(true), - REMOTE_RUNTIME_RECOVERY_BANNER_DELAY_MS - ) - return () => window.clearTimeout(timer) - }, [revealed]) - return revealed } export function TerminalRemoteRuntimeReconnectBanner({ - phase, + recovery, + serverName, onReconnect, + downSince = null, + tailscaleHost = null, wslHostUnavailable = null, pairingRefused = false, awaitingSignIn = false -}: { - phase: VisibleRecoveryPhase - onReconnect: () => void - /** The pane's WSL host cannot run: nothing is retrying, so say why instead. */ - wslHostUnavailable?: WslHostUnavailableReason | null - /** The pane's managed server refuses this desktop and pairing again over SSH failed. */ - pairingRefused?: boolean - /** Main refused because the SSH host is waiting for the user to sign in; it resumes after. */ - awaitingSignIn?: boolean -}): React.JSX.Element { +}: BannerProps): React.JSX.Element { if (wslHostUnavailable) { return } - const signingIn = awaitingSignIn && !pairingRefused - const retrying = phase !== 'disconnected' && !pairingRefused && !signingIn - const reconnectLabel = translate( - 'auto.components.terminal.pane.TerminalRemoteRuntimeReconnectBanner.reconnectButton', - 'Reconnect' - ) - const copy = pairingRefused - ? { - bannerState: 'pairing-refused', - title: translate( + if (pairingRefused) { + return ( + + ) + } + if (awaitingSignIn) { + return ( + + ) + } + if (recovery.phase === 'disconnected') { + return ( + + ) + } + const cause = paneRecoveryCause(recovery) + const copy = remoteRuntimeRecoveryCopy(cause, serverName) return ( -
-
-
- {retrying ? ( - - ) : signingIn ? ( - - ) : ( - - )} -
-
-
{copy.title}
-
{copy.body}
-
- {copy.action ? ( - - ) : null} -
-
+ ) } -/** Keyed per pane: holds a retrying banner back until recovery outlasts the delay. */ -export function DelayedRemoteRuntimeReconnectBanner({ - epoch, +/** + * A pane's recovery, said only once it outlasts a clean reconnect; anything needing action shows + * at once. Stays mounted with no recovery so its minimum time and hold can run out. + * `heldByServer`: the server's own notice covers this drop, so the pane stays quiet. + */ +export function CalmRemoteRuntimeReconnectBanner({ + recovery, + heldByServer, + environmentId, ...props -}: Parameters[0] & { - epoch: number +}: Omit & { + recovery: BannerProps['recovery'] | null + heldByServer: boolean + environmentId: string | null }): React.JSX.Element | null { - const revealed = useRemoteRuntimeRecoveryBannerRevealed( - props.phase === 'disconnected' || + const serverName = useAppStore((state) => + environmentId ? selectRuntimeServerName(state, environmentId) : fallbackRemoteServerName() + ) + const tailscaleHost = useAppStore((state) => + environmentId ? selectRuntimeServerTailscaleHost(state, environmentId) : null + ) + const [lastRecovery, setLastRecovery] = useState(recovery) + if (recovery && recovery !== lastRecovery) { + setLastRecovery(recovery) + } + const [lastNeededAction, setLastNeededAction] = useState(false) + const active = recovery !== null + const [recoveringSince, setRecoveringSince] = useState(null) + useLayoutEffect(() => { + setRecoveringSince(active ? Date.now() : null) + }, [active]) + const needsAction = + active && + (recovery.phase === 'disconnected' || Boolean(props.awaitingSignIn) || Boolean(props.wslHostUnavailable) || - Boolean(props.pairingRefused) + Boolean(props.pairingRefused)) + if (active && needsAction !== lastNeededAction) { + setLastNeededAction(needsAction) + } + // Why the pane's own start: a pane still down when the server notice ends speaks at once. + const reveal = useCalmStatusReveal(active && !heldByServer, needsAction, recoveringSince) + const shown = recovery ?? lastRecovery + // Why a resolved action card goes at once: its copy would describe a state that no longer holds. + if (heldByServer || !reveal.visible || !shown || (!active && lastNeededAction)) { + return null + } + return ( + ) - return revealed ? : null } diff --git a/src/renderer/src/components/terminal-pane/pty-transport-types.ts b/src/renderer/src/components/terminal-pane/pty-transport-types.ts index 88bc9a8b5445..a40cb95936cb 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport-types.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport-types.ts @@ -153,8 +153,14 @@ type PtyCallbacks = { onSpawnDeferred?: (reason: SpawnDeferralReason) => void } +/** What started a pane's recovery: the server connection, or only this pane's stream. */ +export type PtyRecoveryCause = 'connection' | 'stream-stalled' | 'stream-ended' + export type PtyTransportRecoveryState = { reason?: 'ownership' | 'ssh-sign-in' + cause?: PtyRecoveryCause + /** A retry is parked for an outside trigger; nothing retries on its own until then. */ + waiting?: true phase: | 'connecting' | 'connected' diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-control-ready-revivers.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-control-ready-revivers.ts new file mode 100644 index 000000000000..08d094ee6839 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-control-ready-revivers.ts @@ -0,0 +1,37 @@ +// Why: a route that returns without an OS `online` event (Tailscale, VPN, a re-keyed link) fires no +// trigger, so a pane latched past its window stayed dead over a working link. The environment's +// control socket answering again is positive reachability evidence, as good as a Reconnect click. +const controlReadyRevivers = new Map boolean>>() + +export function registerRemoteRuntimePtyControlReadyReviver( + environmentId: string, + revive: () => boolean +): () => void { + let revivers = controlReadyRevivers.get(environmentId) + if (!revivers) { + revivers = new Set() + controlReadyRevivers.set(environmentId, revivers) + } + revivers.add(revive) + return () => { + const current = controlReadyRevivers.get(environmentId) + current?.delete(revive) + if (current?.size === 0) { + controlReadyRevivers.delete(environmentId) + } + } +} + +export function getControlReadyReviverCountForTests(environmentId: string): number { + return controlReadyRevivers.get(environmentId)?.size ?? 0 +} + +export function reviveRemoteRuntimePtyRecoveriesForEnvironment(environmentId: string): number { + let revived = 0 + for (const revive of Array.from(controlReadyRevivers.get(environmentId) ?? [])) { + if (revive()) { + revived += 1 + } + } + return revived +} diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-recovery-state.test.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-recovery-state.test.ts index 1c7c0ab8c433..f9e45d998754 100644 --- a/src/renderer/src/components/terminal-pane/remote-runtime-pty-recovery-state.test.ts +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-recovery-state.test.ts @@ -252,6 +252,20 @@ describe('RemoteRuntimePtyRecoveryState', () => { state.dispose() }) + it('reports a parked retry as waiting, not retrying, until a trigger fires it', () => { + const onChange = vi.fn() + const state = new RemoteRuntimePtyRecoveryState(onChange) + const epoch = state.begin() + onChange.mockClear() + expect(state.parkRetryForExternalTrigger(epoch, vi.fn())).toBe(true) + + expect(state.awaitingExternalTrigger).toBe(true) + expect(onChange).toHaveBeenCalledOnce() + state.retryNow() + expect(state.awaitingExternalTrigger).toBe(false) + state.dispose() + }) + it('refuses to park over an armed backoff or a stale epoch', () => { vi.useFakeTimers() const state = new RemoteRuntimePtyRecoveryState() diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-recovery-state.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-recovery-state.ts index 788687d76fad..44b963002fc0 100644 --- a/src/renderer/src/components/terminal-pane/remote-runtime-pty-recovery-state.ts +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-recovery-state.ts @@ -5,6 +5,7 @@ import { REMOTE_RUNTIME_RECOVERY_DELAYS_MS } from './remote-runtime-pty-recovery-limits' export * from './remote-runtime-pty-recovery-limits' +export * from './remote-runtime-pty-control-ready-revivers' export type RemoteRuntimePtyRecoveryPhase = | 'idle' @@ -31,44 +32,6 @@ export function retryAllRemoteRuntimePtyRecoveriesNow(): number { return advanced } -// Why: a route that returns without an OS `online` event (Tailscale, VPN, a re-keyed link) fires no -// trigger, so a pane latched past its window stayed dead over a working link. The environment's -// control socket answering again is positive reachability evidence, as good as a Reconnect click. -const controlReadyRevivers = new Map boolean>>() - -export function registerRemoteRuntimePtyControlReadyReviver( - environmentId: string, - revive: () => boolean -): () => void { - let revivers = controlReadyRevivers.get(environmentId) - if (!revivers) { - revivers = new Set() - controlReadyRevivers.set(environmentId, revivers) - } - revivers.add(revive) - return () => { - const current = controlReadyRevivers.get(environmentId) - current?.delete(revive) - if (current?.size === 0) { - controlReadyRevivers.delete(environmentId) - } - } -} - -export function getControlReadyReviverCountForTests(environmentId: string): number { - return controlReadyRevivers.get(environmentId)?.size ?? 0 -} - -export function reviveRemoteRuntimePtyRecoveriesForEnvironment(environmentId: string): number { - let revived = 0 - for (const revive of Array.from(controlReadyRevivers.get(environmentId) ?? [])) { - if (revive()) { - revived += 1 - } - } - return revived -} - export class RemoteRuntimePtyRecoveryState { // Caller settlement does not restore this epoch's spent owner-refresh allowance. private ownerRefresh: { @@ -109,6 +72,11 @@ export class RemoteRuntimePtyRecoveryState { return this.deadlineExpired } + /** A retry is parked for online/resume/control-ready or a host publish; nothing is in flight. */ + get awaitingExternalTrigger(): boolean { + return this.phase === 'recovering' && this.pendingRetry !== null && this.retryTimer === null + } + get hasOwnerRefresh(): boolean { return this.ownerRefresh !== null } @@ -211,7 +179,12 @@ export class RemoteRuntimePtyRecoveryState { // Why: a wait that ends with no liveness evidence arms no timer, so park a retry or online/resume/reconnect find nothing to revive. parkRetryForExternalTrigger(epoch: number, retry: (epoch: number) => void): boolean { - return this.isCurrent(epoch) && this.parkRetry(retry) + if (!this.isCurrent(epoch) || !this.parkRetry(retry)) { + return false + } + // Why: the phase stays 'recovering', but the pane must now say it waits rather than retries. + this.onChange?.() + return true } // Why: the deadline can latch while an attempt is still in flight, before schedule() parked anything, diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-pane-binding-ownership.test.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-pane-binding-ownership.test.ts index b75e15c9ada1..298d7ec2a32d 100644 --- a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-pane-binding-ownership.test.ts +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-pane-binding-ownership.test.ts @@ -1,6 +1,5 @@ import { LEAF_1, LEAF_2, unboundSplitLayout } from './terminal-pane-tab-detach-fixture' import type { AppState } from '@/store/types' -import type { TerminalPaneController } from './use-terminal-pane-controller' import type { ConnectPanePtySession } from './pty-connection/connect-pane-pty-session' import { REMOTE_RUNTIME_AUTO_RECOVERY_TIMEOUT_MS } from './remote-runtime-pty-recovery-state' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -320,26 +319,13 @@ describe('remote runtime pane binding ownership', () => { if (contactLoss) { expect(await connecting).toBeUndefined() await vi.advanceTimersByTimeAsync(REMOTE_RUNTIME_AUTO_RECOVERY_TIMEOUT_MS + 1) - vi.doMock('react-dom', () => ({ createPortal: (element: unknown) => element })) - vi.doMock('./use-wsl-host-unavailable-reason', () => ({ - useWslHostUnavailableReason: () => null - })) - const { TerminalPaneRecoveryPortals } = await import('./TerminalPaneRuntimePortals') - const portals = TerminalPaneRecoveryPortals({ - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only recovery fields are read; the portal and WSL hook are inert rendering dependencies. - controller: { - managedPanes: [{ id: 1 }], - ptyRecoveryStatesByPaneId: { 1: transport.getRecoveryState?.() }, - paneTransportsRef: { current: new Map([[1, transport]]) } - } as unknown as TerminalPaneController - }) - const banner = portals?.props.children[0] - expect(banner?.props.phase).toBe('disconnected') + expect(transport.getRecoveryState?.().phase).toBe('disconnected') + const { createPaneRecoveryReconnect } = await import('./TerminalPaneRecoveryPortals') reachable = true const retryRecovery = transport.retryRecovery let accepted: boolean | undefined transport.retryRecovery = () => (accepted = retryRecovery?.() ?? false) - banner?.props.onReconnect() + createPaneRecoveryReconnect(() => transport, null)() expect(accepted).toBe(true) } await vi.waitFor(() => expect(latestSubscribePayload().terminal).toBe('terminal-1')) diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts index 7ab12c647ecf..d994cb439525 100644 --- a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts @@ -10,6 +10,7 @@ import { type MultiplexSubscriptionCallbacks } from './remote-runtime-pty-transport-test-harness' import { REMOTE_RUNTIME_AUTO_RECOVERY_TIMEOUT_MS } from './remote-runtime-pty-recovery-state' +import type { PtyTransportRecoveryState } from './pty-transport-types' // These transport fixtures never read abandoned-launch ownership from the app store. const appStore = vi.hoisted(() => ({ @@ -572,6 +573,42 @@ describe('createRemoteRuntimePtyTransport', () => { } }) + it('says a shared connection drop caused the recovery, and forgets it once healthy', async () => { + const callbacksByConnection: NonNullable[] = [] + runtimeSubscribe.mockImplementation( + async (_args: unknown, callbacks: NonNullable) => { + callbacksByConnection.push(callbacks) + subscriptionCallbacks = callbacks + queueMicrotask(() => callbacks.onResponse({ ok: true, result: { type: 'ready' } })) + return { unsubscribe: vi.fn(), sendBinary: subscriptionSendBinary } + } + ) + const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') + const recoveryStates: PtyTransportRecoveryState[] = [] + const transport = createRemoteRuntimePtyTransport('env-1', { + worktreeId: 'wt-1', + tabId: 'tab-1', + leafId: 'pane:1' + }) + transport.attach({ + existingPtyId: 'remote:env-1@@terminal-1', + callbacks: { onRecoveryStateChange: (state) => recoveryStates.push(state) } + }) + await vi.waitFor(() => expect(subscriptionSendBinary).toHaveBeenCalled()) + emitSnapshot(latestSubscribePayload().streamId, 'before drop') + + callbacksByConnection[0].onClose?.() + + await vi.waitFor(() => + expect(recoveryStates.some((state) => state.cause === 'connection')).toBe(true) + ) + await vi.waitFor(() => expect(subscribeFrameCount()).toBe(2)) + emitSnapshot(latestSubscribePayload().streamId, 'after drop') + await vi.waitFor(() => expect(transport.getRecoveryState?.().phase).toBe('connected')) + expect(transport.getRecoveryState?.().cause).toBeUndefined() + transport.destroy?.() + }) + // #25783/#9092: a route returning without `online` (Tailscale, VPN) left a latched pane dead. it('revives a pane latched past its window when its environment answers again', async () => { vi.useFakeTimers() diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts index 08a34afeb01f..f93200b1f957 100644 --- a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts @@ -44,6 +44,7 @@ import { import type { IpcPtyTransportOptions, PtyConnectResult, + PtyRecoveryCause, PtyTransport, PtyTransportRecoveryState } from './pty-transport-types' @@ -413,6 +414,7 @@ export function createRemoteRuntimePtyTransport( settleSignInConnectWait() } if (recovery.currentPhase === 'idle') { + recoveryCause = null autoRecoveryWindowSpent = false // Why before the reset: input that outlived the grace must not release into the recovered pane. discardExpiredDisconnectedInput() @@ -428,6 +430,7 @@ export function createRemoteRuntimePtyTransport( emitRecoveryState() }) let lastRecoveryStateKey = '' + let recoveryCause: PtyRecoveryCause | null = null let pendingViewportClaim = false // Why: recovery holds viewport sends, so the intent must survive to the stream that releases typing. let recoveryDeferredViewport: 'claim' | 'resize' | null = null @@ -652,6 +655,8 @@ export function createRemoteRuntimePtyTransport( phase, epoch: recovery.currentEpoch, attempt: recovery.attemptCount, + ...(recoveryCause && recovery.currentPhase !== 'idle' ? { cause: recoveryCause } : {}), + ...(recovery.awaitingExternalTrigger ? { waiting: true as const } : {}), ...(ownership ? { reason: 'ownership' as const } : awaitingSignIn @@ -662,7 +667,7 @@ export function createRemoteRuntimePtyTransport( function emitRecoveryState(force = false): void { const state = getRecoveryState() - const key = `${state.phase}:${state.epoch}:${state.attempt}:${state.reason ?? ''}` + const key = `${state.phase}:${state.epoch}:${state.attempt}:${state.reason ?? ''}:${state.cause ?? ''}:${state.waiting ?? ''}` if (!force && key === lastRecoveryStateKey) { return } @@ -2541,6 +2546,7 @@ export function createRemoteRuntimePtyTransport( // Why: reconnect can re-mint a pane handle while its host coordinates live; keep xterm state mounted while re-resolving. const refusedHandle = handle closeMultiplexedStream() + recoveryCause = 'stream-ended' scheduleResubscribeAfterTransportClose('require-replacement') if (refusedHandle) { retireIfHostRecordsExit(refusedHandle, remotePtyId) @@ -3038,6 +3044,7 @@ export function createRemoteRuntimePtyTransport( multiplexedStream = null multiplexedStreamHandle = null clearPendingViewportClaim() + recoveryCause = 'stream-ended' // Why: a legacy bare end or waiter failure proves only attachment loss; reuse the same handle, pacing flaps. const flapDelayMs = sameHandleEndFlapDelayMs(subscribedHandle) if (flapDelayMs === null) { @@ -3104,12 +3111,14 @@ export function createRemoteRuntimePtyTransport( inputJournal.acknowledge(appliedSeq, kind) } }, - onTransportClose: ({ recoverable, retryWithBackoff }) => { + onTransportClose: ({ recoverable, retryWithBackoff, stalled }) => { const current = isCurrentSubscription() transportClosed = true if (!current) { return } + // Why no cause for a backoff: a capacity refusal arrives over a healthy connection. + recoveryCause = stalled ? 'stream-stalled' : retryWithBackoff ? null : 'connection' multiplexedStream = null multiplexedStreamHandle = null setAttachmentReady(false) diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-recovery-copy.ts b/src/renderer/src/components/terminal-pane/remote-runtime-recovery-copy.ts new file mode 100644 index 000000000000..ed50945c6a5e --- /dev/null +++ b/src/renderer/src/components/terminal-pane/remote-runtime-recovery-copy.ts @@ -0,0 +1,146 @@ +import { getIntlLocale, translate } from '@/i18n/i18n' +import type { VisiblePtyRecoveryState } from './terminal-remote-runtime-recovery-ui-state' + +/** Why recovery is happening, as far as this client has evidence for it. */ +export type RemoteRuntimeRecoveryCause = + | 'connection-lost' + | 'server-restarting' + | 'stream-stalled' + | 'session-ended' + | 'waiting-for-server' + | 'reattaching' + +export type RemoteRuntimeRecoveryCopy = { title: string; body: string; retrying: boolean } + +export function paneRecoveryCause( + state: Pick +): RemoteRuntimeRecoveryCause { + // Why first: a parked retry has nothing in flight, so no cause may claim it is retrying. + if (state.waiting) { + return 'waiting-for-server' + } + if (state.cause === 'stream-stalled') { + return 'stream-stalled' + } + if (state.cause === 'stream-ended') { + return 'session-ended' + } + // Why neutral without a cause: claiming a dropped connection needs evidence of one. + return state.cause === 'connection' ? 'connection-lost' : 'reattaching' +} + +export function remoteRuntimeRecoveryCopy( + cause: RemoteRuntimeRecoveryCause, + serverName: string +): RemoteRuntimeRecoveryCopy { + const server = { server: serverName } + switch (cause) { + case 'connection-lost': + return { + retrying: true, + title: translate( + 'auto.components.terminal.pane.TerminalRemoteRuntimeReconnectBanner.connectionLostTitle', + 'Reconnecting to {{server}}', + server + ), + body: translate( + 'auto.components.terminal.pane.TerminalRemoteRuntimeReconnectBanner.connectionLostBody', + 'The connection to the server dropped. Orca is retrying automatically, and terminals resume when it returns.' + ) + } + case 'server-restarting': + return { + retrying: true, + title: translate( + 'auto.components.terminal.pane.TerminalRemoteRuntimeReconnectBanner.serverRestartingTitle', + '{{server}} is restarting', + server + ), + body: translate( + 'auto.components.terminal.pane.TerminalRemoteRuntimeReconnectBanner.serverRestartingBody', + 'Orca reconnects when the server is back, and terminals resume then.' + ) + } + case 'stream-stalled': + return { + retrying: true, + title: translate( + 'auto.components.terminal.pane.TerminalRemoteRuntimeReconnectBanner.streamStalledTitle', + 'Terminal stopped responding' + ), + body: translate( + 'auto.components.terminal.pane.TerminalRemoteRuntimeReconnectBanner.streamStalledBody', + "{{server}} stopped sending this terminal's output. Orca is reattaching it automatically.", + server + ) + } + case 'session-ended': + return { + retrying: true, + title: translate( + 'auto.components.terminal.pane.TerminalRemoteRuntimeReconnectBanner.sessionEndedTitle', + 'Reattaching terminal' + ), + body: translate( + 'auto.components.terminal.pane.TerminalRemoteRuntimeReconnectBanner.sessionEndedBody', + "{{server}} closed this terminal's stream. Orca is reattaching it automatically.", + server + ) + } + case 'reattaching': + return { + retrying: true, + title: translate( + 'auto.components.terminal.pane.TerminalRemoteRuntimeReconnectBanner.sessionEndedTitle', + 'Reattaching terminal' + ), + body: translate( + 'auto.components.terminal.pane.TerminalRemoteRuntimeReconnectBanner.reattachingBody', + 'Orca is reattaching this terminal to {{server}} automatically.', + server + ) + } + case 'waiting-for-server': + return { + retrying: false, + title: translate( + 'auto.components.terminal.pane.TerminalRemoteRuntimeReconnectBanner.waitingTitle', + 'Waiting for {{server}}', + server + ), + body: translate( + 'auto.components.terminal.pane.TerminalRemoteRuntimeReconnectBanner.waitingBody', + 'Orca reattaches this terminal when the server offers it again or the connection changes. Reconnect to try now.' + ) + } + } +} + +export function remoteRuntimeDownForLabel(downForMs: number): string { + const seconds = Math.max(0, Math.floor(downForMs / 1000)) + const [value, unit] = seconds < 60 ? [seconds, 'second'] : [Math.floor(seconds / 60), 'minute'] + const duration = new Intl.NumberFormat(getIntlLocale(), { + style: 'unit', + unit, + unitDisplay: 'short' + }).format(value) + return translate( + 'auto.components.terminal.pane.TerminalRemoteRuntimeReconnectBanner.downFor', + 'Down for {{duration}}', + { duration } + ) +} + +export function remoteRuntimeTailscaleHintLabel(): string { + return translate( + 'auto.components.terminal.pane.TerminalRemoteRuntimeReconnectBanner.tailscaleHint', + 'Check the Tailscale path:' + ) +} + +export function fallbackRemoteServerName(): string { + return translate( + 'auto.components.terminal.pane.TerminalRemoteRuntimeReconnectBanner.fallbackServerName', + 'the server' + ) +} diff --git a/src/renderer/src/components/terminal-pane/remote-server-notice-claims.test.tsx b/src/renderer/src/components/terminal-pane/remote-server-notice-claims.test.tsx new file mode 100644 index 000000000000..932ecdd3da79 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/remote-server-notice-claims.test.tsx @@ -0,0 +1,73 @@ +// @vitest-environment happy-dom + +import { act, cleanup, render } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + resetRemoteServerNoticeClaimsForTests, + useRemoteServerNoticeClaim, + type RemoteServerNoticeClaim +} from './remote-server-notice-claims' + +const seen = new Map() + +function Surface({ + name, + environmentId, + visible = true +}: { + name: string + environmentId: string | null + visible?: boolean +}) { + seen.set(name, useRemoteServerNoticeClaim(environmentId, environmentId !== null, visible)) + return null +} + +afterEach(() => { + cleanup() + resetRemoteServerNoticeClaimsForTests() + seen.clear() + vi.useRealTimers() +}) + +describe('useRemoteServerNoticeClaim', () => { + it('lets one visible surface speak for a dropped server while the rest stay quiet', () => { + render( + <> + + + + + + ) + + expect(seen.get('hidden')).toMatchObject({ speaks: false, quiet: true }) + expect(seen.get('left')).toMatchObject({ speaks: true, quiet: true }) + expect(seen.get('right')).toMatchObject({ speaks: false, quiet: true }) + expect(seen.get('local')).toMatchObject({ speaks: false, quiet: false }) + }) + + it('keeps the outage start from a hidden tab when another tab becomes the speaker', () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + const view = render( + <> + + + + ) + expect(seen.get('front')).toMatchObject({ quiet: false, since: 1_000 }) + vi.setSystemTime(9_000) + + act(() => + view.rerender( + <> + + + + ) + ) + + expect(seen.get('front')).toMatchObject({ speaks: true, since: 1_000 }) + }) +}) diff --git a/src/renderer/src/components/terminal-pane/remote-server-notice-claims.ts b/src/renderer/src/components/terminal-pane/remote-server-notice-claims.ts new file mode 100644 index 000000000000..230fcea612b6 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/remote-server-notice-claims.ts @@ -0,0 +1,158 @@ +import { useEffect, useId, useSyncExternalStore } from 'react' +import { CALM_STATUS_HEALTHY_HOLD_MS } from '../../../../shared/calm-status-reveal' + +/** + * One record per server whose shared connection dropped, shared by every terminal surface on it. + * - Observers: every mounted surface while the server is down, hidden or not, so the outage start + * survives a tab switch and the notice neither re-waits nor resets its clock. + * - Speakers: visible surfaces able to show the notice; the first one shows it. + * - Showers: surfaces whose notice is on screen, including its hold after the server answers. + * Panes on the server stay quiet while anyone speaks or shows, so no surface's pane banners + * overlap a notice that is still up. + */ +type ServerOutage = { + observers: Set + speakers: string[] + showers: Set + since: number + releaseTimer: number | null +} + +const outages = new Map() +const listeners = new Set<() => void>() + +function notify(): void { + for (const listener of listeners) { + listener() + } +} + +function subscribe(listener: () => void): () => void { + listeners.add(listener) + return () => listeners.delete(listener) +} + +function outageFor(environmentId: string): ServerOutage { + let outage = outages.get(environmentId) + if (!outage) { + outage = { + observers: new Set(), + speakers: [], + showers: new Set(), + since: Date.now(), + releaseTimer: null + } + outages.set(environmentId, outage) + } + if (outage.releaseTimer !== null) { + window.clearTimeout(outage.releaseTimer) + outage.releaseTimer = null + } + return outage +} + +function releaseWhenUnused(environmentId: string): void { + const outage = outages.get(environmentId) + if (!outage || outage.observers.size > 0 || outage.showers.size > 0) { + return + } + if (outage.releaseTimer !== null) { + return + } + // Why held briefly: a tab switch unmounts one observer before the next mounts. + outage.releaseTimer = window.setTimeout(() => { + const current = outages.get(environmentId) + if (current && current.observers.size === 0 && current.showers.size === 0) { + outages.delete(environmentId) + notify() + } + }, CALM_STATUS_HEALTHY_HOLD_MS) +} + +function join(environmentId: string, member: string, role: 'observers' | 'showers'): () => void { + outageFor(environmentId)[role].add(member) + notify() + return () => { + outages.get(environmentId)?.[role].delete(member) + releaseWhenUnused(environmentId) + notify() + } +} + +function speak(environmentId: string, speaker: string): () => void { + const outage = outageFor(environmentId) + outage.speakers = [...outage.speakers, speaker] + notify() + return () => { + const current = outages.get(environmentId) + if (current) { + current.speakers = current.speakers.filter((entry) => entry !== speaker) + } + releaseWhenUnused(environmentId) + notify() + } +} + +export type RemoteServerNoticeClaim = { + /** This surface shows the server's notice. */ + speaks: boolean + /** A notice for this server is up or about to be, so its panes stay quiet. */ + quiet: boolean + /** When any mounted surface first saw the outage. */ + since: number | null +} + +const NO_CLAIM: RemoteServerNoticeClaim = { speaks: false, quiet: false, since: null } + +/** `environmentId` is the surface's server; `down` is whether its shared connection is down. */ +export function useRemoteServerNoticeClaim( + environmentId: string | null, + down: boolean, + canSpeak: boolean +): RemoteServerNoticeClaim { + const surface = useId() + useEffect( + () => (environmentId === null || !down ? undefined : join(environmentId, surface, 'observers')), + [down, environmentId, surface] + ) + useEffect( + () => + environmentId === null || !down || !canSpeak ? undefined : speak(environmentId, surface), + [canSpeak, down, environmentId, surface] + ) + const leader = useSyncExternalStore(subscribe, () => + environmentId === null ? null : (outages.get(environmentId)?.speakers[0] ?? null) + ) + const showing = useSyncExternalStore(subscribe, () => + environmentId === null ? false : (outages.get(environmentId)?.showers.size ?? 0) > 0 + ) + const since = useSyncExternalStore(subscribe, () => + environmentId === null ? null : (outages.get(environmentId)?.since ?? null) + ) + if (environmentId === null) { + return NO_CLAIM + } + return { speaks: leader === surface, quiet: leader !== null || showing, since } +} + +/** Publishes that this surface's notice is on screen, so every surface's panes wait it out. */ +export function usePublishRemoteServerNoticeShowing( + environmentId: string | null, + showing: boolean +): void { + const surface = useId() + useEffect( + () => + environmentId === null || !showing ? undefined : join(environmentId, surface, 'showers'), + [environmentId, showing, surface] + ) +} + +export function resetRemoteServerNoticeClaimsForTests(): void { + for (const outage of outages.values()) { + if (outage.releaseTimer !== null) { + window.clearTimeout(outage.releaseTimer) + } + } + outages.clear() +} diff --git a/src/renderer/src/components/terminal-pane/remote-server-outage.ts b/src/renderer/src/components/terminal-pane/remote-server-outage.ts new file mode 100644 index 000000000000..0dde8d5722d8 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/remote-server-outage.ts @@ -0,0 +1,71 @@ +import { useAppStore } from '@/store' +import type { AppState } from '@/store/types' +import { parseExecutionHostId, toRuntimeExecutionHostId } from '../../../../shared/execution-host' +import { tailscaleHostOfEndpoint } from '../../../../shared/remote-runtime/remote-runtime-tailscale-hint' +import { selectExecutionHostDisplayLabel } from '@/lib/execution-host-display-label' +import { workspaceOwnerHostId } from '@/lib/workspace-row-owner-host' +import { runtimeHostConnectionStateForEntry } from '@/runtime/runtime-host-connection-state' +import type { RemoteRuntimeRecoveryCause } from './remote-runtime-recovery-copy' + +/** + * The server owning this workspace while its shared connection is down and retrying on its own. + * One server-level reading, so its panes stay quiet instead of each announcing the same drop. + */ +export function selectRetryingOutageEnvironmentId( + state: AppState, + worktreeId: string | null | undefined +): string | null { + const environmentId = selectWorkspaceRuntimeEnvironmentId(state, worktreeId) + if (!environmentId) { + return null + } + // Why only 'reconnecting': it is the transport-down verdict. 'checking' and a failed status + // probe over a live socket are not a dropped connection, and must not be announced as one. + const entry = state.runtimeStatusByEnvironmentId.get(environmentId) + return runtimeHostConnectionStateForEntry(entry) === 'reconnecting' ? environmentId : null +} + +export function selectWorkspaceRuntimeEnvironmentId( + state: AppState, + worktreeId: string | null | undefined +): string | null { + const host = worktreeId ? parseExecutionHostId(workspaceOwnerHostId(state, worktreeId)) : null + return host?.kind === 'runtime' ? host.environmentId : null +} + +export function selectRemoteServerOutageCause( + state: AppState, + environmentId: string +): Extract { + // Why only the updater: a server stop terminates sockets without a close code, so its own restart is the only evidence. + return state.remoteServerUpdates.get(environmentId)?.phase === 'restarting' + ? 'server-restarting' + : 'connection-lost' +} + +export function selectRuntimeServerName(state: AppState, environmentId: string): string { + return selectExecutionHostDisplayLabel(state, toRuntimeExecutionHostId(environmentId)) +} + +export function selectRuntimeServerTailscaleHost( + state: AppState, + environmentId: string +): string | null { + const environment = state.runtimeEnvironments.find((entry) => entry.id === environmentId) + const endpoint = + environment?.endpoints.find((entry) => entry.id === environment.preferredEndpointId) ?? + environment?.endpoints[0] + return tailscaleHostOfEndpoint(endpoint?.endpoint) +} + +export function useRetryingOutageEnvironmentId( + worktreeId: string | null | undefined +): string | null { + return useAppStore((state) => selectRetryingOutageEnvironmentId(state, worktreeId)) +} + +export function useWorkspaceRuntimeEnvironmentId( + worktreeId: string | null | undefined +): string | null { + return useAppStore((state) => selectWorkspaceRuntimeEnvironmentId(state, worktreeId)) +} diff --git a/src/renderer/src/hooks/use-calm-status-reveal.ts b/src/renderer/src/hooks/use-calm-status-reveal.ts new file mode 100644 index 000000000000..b840fde66291 --- /dev/null +++ b/src/renderer/src/hooks/use-calm-status-reveal.ts @@ -0,0 +1,42 @@ +import { useLayoutEffect, useRef, useState } from 'react' +import { + CALM_STATUS_IDLE, + stepCalmStatusReveal, + type CalmStatusReveal +} from '../../../shared/calm-status-reveal' + +export type CalmStatusView = { visible: boolean; downSince: number | null } + +const HIDDEN: CalmStatusView = { visible: false, downSince: null } + +/** Says a self-healing outage only once it outlasts a reconnect, and never as a flash. */ +export function useCalmStatusReveal( + down: boolean, + immediate: boolean, + since: number | null = null +): CalmStatusView { + const revealRef = useRef(CALM_STATUS_IDLE) + const [view, setView] = useState(HIDDEN) + const [wake, setWake] = useState(0) + // Why layout: an immediate notice must not paint one frame late. + useLayoutEffect(() => { + const step = stepCalmStatusReveal(revealRef.current, { + down, + immediate, + now: Date.now(), + since + }) + revealRef.current = step.next + setView((previous) => + previous.visible === step.visible && previous.downSince === step.next.downSince + ? previous + : { visible: step.visible, downSince: step.next.downSince } + ) + if (step.recheckInMs === null) { + return + } + const timer = setTimeout(() => setWake((count) => count + 1), Math.max(0, step.recheckInMs)) + return () => clearTimeout(timer) + }, [down, immediate, since, wake]) + return view +} diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 66fc56761793..ee55b0940d87 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -3823,16 +3823,28 @@ "removeWorkspaceButton": "Remove workspace" }, "TerminalRemoteRuntimeReconnectBanner": { - "retryingTitle": "Reconnecting to remote runtime", "pairingRefusedTitle": "This host no longer accepts this computer", "pairingRefusedBody": "Orca couldn't pair with it again over SSH. Nothing on the host was stopped. Reconnect to try again.", "disconnectedTitle": "Remote runtime disconnected", - "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", "signInTitle": "Waiting for SSH sign-in", "signInBody": "This terminal continues by itself once you sign in to the host.", - "signInButton": "Sign in" + "signInButton": "Sign in", + "serverRestartingTitle": "{{server}} is restarting", + "serverRestartingBody": "Orca reconnects when the server is back, and terminals resume then.", + "streamStalledTitle": "Terminal stopped responding", + "streamStalledBody": "{{server}} stopped sending this terminal's output. Orca is reattaching it automatically.", + "sessionEndedTitle": "Reattaching terminal", + "sessionEndedBody": "{{server}} closed this terminal's stream. Orca is reattaching it automatically.", + "waitingTitle": "Waiting for {{server}}", + "waitingBody": "Orca reattaches this terminal when the server offers it again or the connection changes. Reconnect to try now.", + "downFor": "Down for {{duration}}", + "tailscaleHint": "Check the Tailscale path:", + "fallbackServerName": "the server", + "connectionLostTitle": "Reconnecting to {{server}}", + "connectionLostBody": "The connection to the server dropped. Orca is retrying automatically, and terminals resume when it returns.", + "reattachingBody": "Orca is reattaching this terminal to {{server}} automatically." }, "TerminalQuickCommandsSubmenu": { "3ccc7981bb": "Host unavailable", diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 055f5bb9ec09..e83e26e28758 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -3520,16 +3520,28 @@ "removeWorkspaceButton": "Eliminar espacio de trabajo" }, "TerminalRemoteRuntimeReconnectBanner": { - "retryingTitle": "Reconectando con el entorno de ejecución remoto", "pairingRefusedTitle": "Este host ya no acepta este equipo", "pairingRefusedBody": "Orca no pudo volver a emparejarse con él por SSH. No se detuvo nada en el host. Vuelve a conectar para intentarlo de nuevo.", "disconnectedTitle": "Remote runtime disconnected", - "retryingBody": "Orca está reintentando automáticamente. Este terminal se reanudará si vuelve la conexión.", "disconnectedBody": "Se detuvieron los reintentos automáticos. Vuelva a conectarse para reanudar esta sesión de terminal.", - "reconnectButton": "Reconnect", + "reconnectButton": "Reconectar", "signInTitle": "Esperando el inicio de sesión SSH", "signInBody": "Este terminal continuará por sí solo cuando inicie sesión en el host.", - "signInButton": "Iniciar sesión" + "signInButton": "Iniciar sesión", + "serverRestartingTitle": "{{server}} se está reiniciando", + "serverRestartingBody": "Orca se reconectará cuando el servidor vuelva, y los terminales se reanudarán entonces.", + "streamStalledTitle": "El terminal dejó de responder", + "streamStalledBody": "{{server}} dejó de enviar la salida de este terminal. Orca lo está reconectando automáticamente.", + "sessionEndedTitle": "Reconectando el terminal", + "sessionEndedBody": "{{server}} cerró el flujo de este terminal. Orca lo está reconectando automáticamente.", + "waitingTitle": "Esperando a {{server}}", + "waitingBody": "Orca reconectará este terminal cuando el servidor vuelva a ofrecerlo o cambie la conexión. Pulsa Reconectar para intentarlo ahora.", + "downFor": "Sin conexión desde hace {{duration}}", + "tailscaleHint": "Comprueba la ruta de Tailscale:", + "fallbackServerName": "el servidor", + "connectionLostTitle": "Reconectando con {{server}}", + "connectionLostBody": "Se perdió la conexión con el servidor. Orca está reintentando automáticamente y los terminales se reanudarán cuando vuelva.", + "reattachingBody": "Orca está reconectando automáticamente este terminal a {{server}}." }, "TerminalRestoringPlaceholder": { "restoring": "Restaurando terminal…" diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index ded65607d613..c3533c6dc35f 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -3689,16 +3689,28 @@ "removeWorkspaceButton": "Supprimer l'espace de travail" }, "TerminalRemoteRuntimeReconnectBanner": { - "retryingTitle": "Reconnexion au runtime distant", "pairingRefusedTitle": "Cet hôte n'accepte plus cet ordinateur", "pairingRefusedBody": "Orca n'a pas pu s'associer de nouveau à lui via SSH. Rien n'a été arrêté sur l'hôte. Reconnectez-vous pour réessayer.", "disconnectedTitle": "Runtime distant déconnecté", - "retryingBody": "Orca réessaie automatiquement. Ce terminal reprendra si la connexion revient.", "disconnectedBody": "Les tentatives automatiques sont interrompues. Reconnectez-vous pour reprendre cette session de terminal.", "reconnectButton": "Reconnecter", "signInTitle": "En attente de la connexion SSH", "signInBody": "Ce terminal reprend tout seul dès que vous vous connectez à l’hôte.", - "signInButton": "Se connecter" + "signInButton": "Se connecter", + "serverRestartingTitle": "{{server}} redémarre", + "serverRestartingBody": "Orca se reconnectera au retour du serveur, et les terminaux reprendront alors.", + "streamStalledTitle": "Le terminal ne répond plus", + "streamStalledBody": "{{server}} n'envoie plus la sortie de ce terminal. Orca le reconnecte automatiquement.", + "sessionEndedTitle": "Reconnexion du terminal", + "sessionEndedBody": "{{server}} a fermé le flux de ce terminal. Orca le reconnecte automatiquement.", + "waitingTitle": "En attente de {{server}}", + "waitingBody": "Orca reconnectera ce terminal quand le serveur le proposera de nouveau ou que la connexion changera. Cliquez sur Reconnecter pour réessayer maintenant.", + "downFor": "Coupé depuis {{duration}}", + "tailscaleHint": "Vérifiez le chemin Tailscale :", + "fallbackServerName": "le serveur", + "connectionLostTitle": "Reconnexion à {{server}}", + "connectionLostBody": "La connexion au serveur a été perdue. Orca réessaie automatiquement et les terminaux reprendront à son retour.", + "reattachingBody": "Orca reconnecte automatiquement ce terminal à {{server}}." }, "TerminalQuickCommandsSubmenu": { "3ccc7981bb": "Hôte indisponible", diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index eecdc39af6d8..b0fa73c32413 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -3505,16 +3505,28 @@ "removeWorkspaceButton": "ワークスペースを削除" }, "TerminalRemoteRuntimeReconnectBanner": { - "retryingTitle": "リモートランタイムに再接続中", "pairingRefusedTitle": "このホストはこのコンピューターを受け付けなくなりました", "pairingRefusedBody": "Orca は SSH 経由で再ペアリングできませんでした。ホスト上では何も停止していません。再接続してもう一度お試しください。", "disconnectedTitle": "リモートランタイムが切断されました", - "retryingBody": "Orca は自動的に再試行します。接続が復元されると、このターミナルが再開されます。", "disconnectedBody": "自動再試行が停止しました。このターミナルセッションを再開するには再接続してください。", "reconnectButton": "再接続", "signInTitle": "SSH のサインインを待っています", "signInBody": "ホストにサインインすると、このターミナルは自動的に続行します。", - "signInButton": "サインイン" + "signInButton": "サインイン", + "serverRestartingTitle": "{{server}} を再起動しています", + "serverRestartingBody": "サーバーが復帰すると Orca が再接続し、ターミナルも再開します。", + "streamStalledTitle": "ターミナルが応答していません", + "streamStalledBody": "{{server}} からこのターミナルの出力が届かなくなりました。Orca が自動的に再接続しています。", + "sessionEndedTitle": "ターミナルを再接続しています", + "sessionEndedBody": "{{server}} がこのターミナルのストリームを閉じました。Orca が自動的に再接続しています。", + "waitingTitle": "{{server}} を待っています", + "waitingBody": "サーバーがこのターミナルを再び提供するか接続が変わると、Orca が再接続します。今すぐ試すには「再接続」を押してください。", + "downFor": "切断から {{duration}}", + "tailscaleHint": "Tailscale の経路を確認:", + "fallbackServerName": "サーバー", + "connectionLostTitle": "{{server}} に再接続しています", + "connectionLostBody": "サーバーとの接続が切断されました。Orca が自動的に再試行しており、接続が戻るとターミナルは再開します。", + "reattachingBody": "Orca がこのターミナルを {{server}} に自動的に再接続しています。" }, "TerminalLinkActionPopover": { "openLink": "リンクを開く", diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index dc332e230d8c..63e440c6080e 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -3505,16 +3505,28 @@ "removeWorkspaceButton": "워크트리 제거" }, "TerminalRemoteRuntimeReconnectBanner": { - "retryingTitle": "원격 런타임에 다시 연결 중", "pairingRefusedTitle": "이 호스트가 더 이상 이 컴퓨터를 허용하지 않습니다", "pairingRefusedBody": "Orca가 SSH로 다시 페어링하지 못했습니다. 호스트에서는 아무것도 중지되지 않았습니다. 다시 연결하여 재시도하세요.", "disconnectedTitle": "원격 런타임 연결 끊김", - "retryingBody": "Orca가 자동으로 재시도합니다. 연결이 복원되면 이 터미널이 재개됩니다.", "disconnectedBody": "자동 재시도가 중지되었습니다. 이 터미널 세션을 재개하려면 다시 연결하세요.", "reconnectButton": "다시 연결", "signInTitle": "SSH 로그인 대기 중", "signInBody": "호스트에 로그인하면 이 터미널이 자동으로 계속됩니다.", - "signInButton": "로그인" + "signInButton": "로그인", + "serverRestartingTitle": "{{server}} 다시 시작 중", + "serverRestartingBody": "서버가 돌아오면 Orca가 다시 연결하고 터미널도 재개됩니다.", + "streamStalledTitle": "터미널이 응답하지 않음", + "streamStalledBody": "{{server}}에서 이 터미널의 출력을 더 이상 보내지 않습니다. Orca가 자동으로 다시 연결하고 있습니다.", + "sessionEndedTitle": "터미널 다시 연결 중", + "sessionEndedBody": "{{server}}에서 이 터미널의 스트림을 닫았습니다. Orca가 자동으로 다시 연결하고 있습니다.", + "waitingTitle": "{{server}} 응답 대기 중", + "waitingBody": "서버가 이 터미널을 다시 제공하거나 연결이 바뀌면 Orca가 다시 연결합니다. 지금 시도하려면 다시 연결을 누르세요.", + "downFor": "연결 끊김 {{duration}}", + "tailscaleHint": "Tailscale 경로 확인:", + "fallbackServerName": "서버", + "connectionLostTitle": "{{server}}에 다시 연결하는 중", + "connectionLostBody": "서버와의 연결이 끊겼습니다. Orca가 자동으로 다시 시도하고 있으며, 연결이 복구되면 터미널이 재개됩니다.", + "reattachingBody": "Orca가 이 터미널을 {{server}}에 자동으로 다시 연결하고 있습니다." }, "TerminalLinkActionPopover": { "openLink": "링크 열기", diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index 2f316a217f78..669514f31abf 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -15647,16 +15647,28 @@ "c337c9d75c": "Fechar" }, "TerminalRemoteRuntimeReconnectBanner": { - "retryingTitle": "Reconectando ao runtime remoto", "disconnectedTitle": "Runtime remoto desconectado", - "retryingBody": "O Orca vai tentar novamente por até um minuto. Este terminal vai retomar se a conexão voltar.", "disconnectedBody": "As tentativas automáticas foram interrompidas. Reconecte para retomar esta sessão de terminal.", "reconnectButton": "Reconectar", "pairingRefusedTitle": "Este host não aceita mais este computador", "pairingRefusedBody": "O Orca não conseguiu parear com ele novamente via SSH. Nada no host foi interrompido. Reconecte para tentar novamente.", "signInTitle": "Aguardando login SSH", "signInBody": "Este terminal continua sozinho quando você entrar no host.", - "signInButton": "Entrar" + "signInButton": "Entrar", + "serverRestartingTitle": "{{server}} está reiniciando", + "serverRestartingBody": "O Orca se reconecta quando o servidor voltar, e os terminais são retomados nesse momento.", + "streamStalledTitle": "O terminal parou de responder", + "streamStalledBody": "{{server}} parou de enviar a saída deste terminal. O Orca está reconectando-o automaticamente.", + "sessionEndedTitle": "Reconectando o terminal", + "sessionEndedBody": "{{server}} fechou o fluxo deste terminal. O Orca está reconectando-o automaticamente.", + "waitingTitle": "Aguardando {{server}}", + "waitingBody": "O Orca reconecta este terminal quando o servidor o oferecer de novo ou a conexão mudar. Clique em Reconectar para tentar agora.", + "downFor": "Sem conexão há {{duration}}", + "tailscaleHint": "Verifique o caminho do Tailscale:", + "fallbackServerName": "o servidor", + "connectionLostTitle": "Reconectando a {{server}}", + "connectionLostBody": "A conexão com o servidor caiu. O Orca está tentando novamente de forma automática, e os terminais serão retomados quando ela voltar.", + "reattachingBody": "O Orca está reconectando este terminal a {{server}} automaticamente." }, "TerminalPane": { "ac112e9036": "Remover título", diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 60f4a3b54d16..2cedcf90f86c 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -3505,16 +3505,28 @@ "removeWorkspaceButton": "移除工作区" }, "TerminalRemoteRuntimeReconnectBanner": { - "retryingTitle": "正在重新连接到远程运行时", "pairingRefusedTitle": "此主机不再接受这台电脑", "pairingRefusedBody": "Orca 无法通过 SSH 重新与其配对。主机上没有任何内容被停止。请重新连接以重试。", "disconnectedTitle": "远程运行时已断开连接", - "retryingBody": "Orca 正在自动重试。如果连接恢复,此终端将恢复。", "disconnectedBody": "自动重试已停止。重新连接以恢复此终端会话。", "reconnectButton": "重新连接", "signInTitle": "正在等待 SSH 登录", "signInBody": "登录到主机后,此终端会自动继续。", - "signInButton": "登录" + "signInButton": "登录", + "serverRestartingTitle": "{{server}} 正在重启", + "serverRestartingBody": "服务器恢复后,Orca 会自动重新连接,终端也会随之继续运行。", + "streamStalledTitle": "终端无响应", + "streamStalledBody": "{{server}} 已停止发送此终端的输出。Orca 正在自动重新连接该终端。", + "sessionEndedTitle": "正在重新连接终端", + "sessionEndedBody": "{{server}} 关闭了此终端的数据流。Orca 正在自动重新连接该终端。", + "waitingTitle": "正在等待 {{server}}", + "waitingBody": "服务器重新提供此终端或网络连接变化时,Orca 会重新连接它。点击“重新连接”可立即重试。", + "downFor": "已断开 {{duration}}", + "tailscaleHint": "检查 Tailscale 链路:", + "fallbackServerName": "服务器", + "connectionLostTitle": "正在重新连接 {{server}}", + "connectionLostBody": "与服务器的连接已断开。Orca 正在自动重试,连接恢复后终端会继续运行。", + "reattachingBody": "Orca 正在自动将此终端重新连接到 {{server}}。" }, "TerminalLinkActionPopover": { "openLink": "打开链接", diff --git a/src/renderer/src/runtime/remote-runtime-terminal-frame-drop-resync.test.ts b/src/renderer/src/runtime/remote-runtime-terminal-frame-drop-resync.test.ts index c97c5a08db7d..5e18d8dbf398 100644 --- a/src/renderer/src/runtime/remote-runtime-terminal-frame-drop-resync.test.ts +++ b/src/renderer/src/runtime/remote-runtime-terminal-frame-drop-resync.test.ts @@ -552,7 +552,7 @@ describe('remote terminal frame-drop resync', () => { expect(onTransportClose).not.toHaveBeenCalled() await vi.advanceTimersByTimeAsync(10_000) - expect(onTransportClose).toHaveBeenCalledWith({ recoverable: true }) + expect(onTransportClose).toHaveBeenCalledWith({ recoverable: true, stalled: true }) } finally { vi.useRealTimers() } diff --git a/src/renderer/src/runtime/remote-runtime-terminal-multiplexer-types.ts b/src/renderer/src/runtime/remote-runtime-terminal-multiplexer-types.ts index 9a6af8dc9c9b..d356e76d96cc 100644 --- a/src/renderer/src/runtime/remote-runtime-terminal-multiplexer-types.ts +++ b/src/renderer/src/runtime/remote-runtime-terminal-multiplexer-types.ts @@ -75,7 +75,14 @@ export type RemoteRuntimeMultiplexedTerminalCallbacks = { onWriteUnavailable?: () => void /** Cumulative host ack of sequenced input through `appliedSeq` (negotiated streams only). */ onInputAck?: (appliedSeq: number, kind: TerminalInputAckKind) => void - onTransportClose?: (event: { recoverable: boolean; retryWithBackoff?: boolean }) => void + onTransportClose?: (event: RemoteTerminalTransportCloseEvent) => void +} + +export type RemoteTerminalTransportCloseEvent = { + recoverable: boolean + retryWithBackoff?: boolean + /** This stream stopped answering while the shared connection may be healthy. */ + stalled?: true } export type RemoteRuntimeSnapshotImage = { diff --git a/src/renderer/src/runtime/remote-runtime-terminal-snapshot-controller.ts b/src/renderer/src/runtime/remote-runtime-terminal-snapshot-controller.ts index cf2896714087..99afeae43d2b 100644 --- a/src/renderer/src/runtime/remote-runtime-terminal-snapshot-controller.ts +++ b/src/renderer/src/runtime/remote-runtime-terminal-snapshot-controller.ts @@ -279,7 +279,7 @@ export abstract class RemoteRuntimeTerminalSnapshotController extends RemoteRunt this.streams.delete(stream.streamId) this.sendFrame(stream.streamId, TerminalStreamOpcode.Unsubscribe) if (stream.callbacks.onTransportClose) { - stream.callbacks.onTransportClose({ recoverable: true }) + stream.callbacks.onTransportClose({ recoverable: true, stalled: true }) } else { stream.callbacks.onError?.('Remote terminal stream stopped responding.') } diff --git a/src/renderer/src/runtime/remote-runtime-terminal-stall-recovery.test.ts b/src/renderer/src/runtime/remote-runtime-terminal-stall-recovery.test.ts index 7ba6f3711b9e..4e36a9d9f3a6 100644 --- a/src/renderer/src/runtime/remote-runtime-terminal-stall-recovery.test.ts +++ b/src/renderer/src/runtime/remote-runtime-terminal-stall-recovery.test.ts @@ -86,7 +86,7 @@ describe('remote terminal stalled stream recovery', () => { await vi.advanceTimersByTimeAsync(REMOTE_TERMINAL_DELIVERY_STALL_TIMEOUT_MS) - expect(onTransportClose).toHaveBeenCalledWith({ recoverable: true }) + expect(onTransportClose).toHaveBeenCalledWith({ recoverable: true, stalled: true }) expect(sentUnsubscribeStreamIds()).toEqual([stalled.streamId]) expect(unsubscribe).not.toHaveBeenCalled() expect(recordBreadcrumb).toHaveBeenCalledWith({ @@ -169,7 +169,7 @@ describe('remote terminal stalled stream recovery', () => { expect(onTransportClose).not.toHaveBeenCalled() await vi.advanceTimersByTimeAsync(5_000) - expect(onTransportClose).toHaveBeenCalledWith({ recoverable: true }) + expect(onTransportClose).toHaveBeenCalledWith({ recoverable: true, stalled: true }) expect(sentUnsubscribeStreamIds()).toEqual([stream.streamId]) }) @@ -193,7 +193,7 @@ describe('remote terminal stalled stream recovery', () => { expect(sentFrames(TerminalStreamOpcode.SnapshotRequest)).toHaveLength(1) await vi.advanceTimersByTimeAsync(REMOTE_TERMINAL_SNAPSHOT_REQUEST_TIMEOUT_MS) - expect(onTransportClose).toHaveBeenCalledWith({ recoverable: true }) + expect(onTransportClose).toHaveBeenCalledWith({ recoverable: true, stalled: true }) expect(sentUnsubscribeStreamIds()).toEqual([stream.streamId]) expect(recordBreadcrumb).toHaveBeenCalledWith({ name: 'remote_terminal_stream_stall_recovery', @@ -284,7 +284,7 @@ describe('remote terminal stalled stream recovery', () => { await vi.advanceTimersByTimeAsync(0) expect(onData).toHaveBeenCalledOnce() - expect(onTransportClose).toHaveBeenCalledWith({ recoverable: true }) + expect(onTransportClose).toHaveBeenCalledWith({ recoverable: true, stalled: true }) expect(sentUnsubscribeStreamIds()).toEqual([stream.streamId]) }) @@ -364,7 +364,7 @@ describe('remote terminal stalled stream recovery', () => { emitSnapshot(stream.streamId, advancedPayload?.requestId ?? 0, 'second-output', 25) await vi.advanceTimersByTimeAsync(0) - expect(onTransportClose).toHaveBeenCalledWith({ recoverable: true }) + expect(onTransportClose).toHaveBeenCalledWith({ recoverable: true, stalled: true }) expect(sentUnsubscribeStreamIds()).toEqual([stream.streamId]) }) diff --git a/src/renderer/src/runtime/runtime-terminal-stream.ts b/src/renderer/src/runtime/runtime-terminal-stream.ts index 3c96b4f94112..36786d1a1ffe 100644 --- a/src/renderer/src/runtime/runtime-terminal-stream.ts +++ b/src/renderer/src/runtime/runtime-terminal-stream.ts @@ -1,6 +1,7 @@ import { RuntimeRpcCallError } from './runtime-rpc-result' import { getRemoteRuntimeTerminalMultiplexer } from './remote-runtime-terminal-multiplexer' import { parseRemoteRuntimePtyId } from '../../../shared/remote-runtime-pty-id' +import type { RemoteTerminalTransportCloseEvent } from './remote-runtime-terminal-multiplexer-types' const LIVE_TAIL_SUBSCRIPTION_TIMEOUT_MS = 10_000 @@ -9,7 +10,7 @@ export type RuntimeTerminalDataSubscriptionOptions = { onSnapshot?: (data: string, meta?: { pendingEscapeTailAnsi?: string }) => void onEnd?: () => void onError?: (message: string) => void - onTransportClose?: (event: { recoverable: boolean; retryWithBackoff?: boolean }) => void + onTransportClose?: (event: RemoteTerminalTransportCloseEvent) => void } export function getRemoteRuntimeTerminalHandle(ptyId: string): string | null { diff --git a/src/shared/calm-status-reveal.test.ts b/src/shared/calm-status-reveal.test.ts new file mode 100644 index 000000000000..60485634663e --- /dev/null +++ b/src/shared/calm-status-reveal.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from 'vitest' +import { + CALM_STATUS_HEALTHY_HOLD_MS, + CALM_STATUS_IDLE, + CALM_STATUS_MIN_VISIBLE_MS, + CALM_STATUS_REVEAL_DELAY_MS, + stepCalmStatusReveal, + type CalmStatusReveal +} from './calm-status-reveal' + +function run( + events: { at: number; down: boolean; immediate?: boolean; since?: number }[] +): boolean[] { + let state: CalmStatusReveal = CALM_STATUS_IDLE + return events.map(({ at, down, immediate = false, since }) => { + const step = stepCalmStatusReveal(state, { down, immediate, now: at, since }) + state = step.next + return step.visible + }) +} + +describe('stepCalmStatusReveal', () => { + it('keeps a clean reconnect on a 400 ms link silent', () => { + expect( + run([ + { at: 0, down: true }, + { at: 4_100, down: true }, + { at: 4_200, down: false }, + { at: 4_200 + CALM_STATUS_HEALTHY_HOLD_MS, down: false } + ]) + ).toEqual([false, false, false, false]) + }) + + it('says an outage that outlasts the delay, and holds it long enough to read', () => { + const shownAt = CALM_STATUS_REVEAL_DELAY_MS + expect( + run([ + { at: 0, down: true }, + { at: shownAt, down: true }, + { at: shownAt + 100, down: false }, + { at: shownAt + CALM_STATUS_MIN_VISIBLE_MS - 1, down: false }, + { at: shownAt + CALM_STATUS_MIN_VISIBLE_MS, down: false } + ]) + ).toEqual([false, true, true, true, false]) + }) + + it('treats a link that answers and drops again inside the hold as one outage', () => { + const shownAt = CALM_STATUS_REVEAL_DELAY_MS + expect( + run([ + { at: 0, down: true }, + { at: shownAt, down: true }, + { at: shownAt + 3_000, down: false }, + { at: shownAt + 3_500, down: true }, + { at: shownAt + 3_600, down: false }, + { at: shownAt + 3_600 + CALM_STATUS_HEALTHY_HOLD_MS, down: false } + ]) + ).toEqual([false, true, true, true, true, false]) + }) + + it('counts a flapping link toward one delay instead of restarting it on every blip', () => { + expect( + run([ + { at: 0, down: true }, + { at: 3_000, down: false }, + { at: 3_500, down: true }, + { at: CALM_STATUS_REVEAL_DELAY_MS, down: true } + ]) + ).toEqual([false, false, false, true]) + }) + + it('shows anything needing action at once', () => { + expect(run([{ at: 0, down: true, immediate: true }])).toEqual([true]) + }) + + it('continues an outage clock another surface already started', () => { + expect(run([{ at: 10_000, down: true, since: 10_000 - CALM_STATUS_REVEAL_DELAY_MS }])).toEqual([ + true + ]) + }) +}) diff --git a/src/shared/calm-status-reveal.ts b/src/shared/calm-status-reveal.ts new file mode 100644 index 000000000000..589e7185b333 --- /dev/null +++ b/src/shared/calm-status-reveal.ts @@ -0,0 +1,75 @@ +/** + * When a self-healing outage is worth announcing, and for how long. Pure and clock-driven so the + * desktop banner and the mobile header share one schedule and tests need no wall clock. + */ + +// Why 5 s: measured drop-to-resubscribed for the shared control socket through a delay proxy was +// ~0.3 s + 5.5 RTT (1.4 s at 200 ms RTT, 2.5 s at 400 ms). A pane's own resubscribe and snapshot +// add ~2 RTT, and a relay's TLS ~2 more: ~4.1 s for one clean reconnect at 400 ms. Anything +// longer means an attempt failed, which is an outage worth saying. +export const CALM_STATUS_REVEAL_DELAY_MS = 5_000 + +// Why: shorter than this reads as a flash; long enough to finish reading a title. +export const CALM_STATUS_MIN_VISIBLE_MS = 2_000 + +// Why: a link that answers and drops again inside this window is one outage, not two. +export const CALM_STATUS_HEALTHY_HOLD_MS = 1_000 + +export type CalmStatusReveal = { + downSince: number | null + shownAt: number | null + healthySince: number | null +} + +export const CALM_STATUS_IDLE: CalmStatusReveal = { + downSince: null, + shownAt: null, + healthySince: null +} + +export type CalmStatusStep = { + next: CalmStatusReveal + visible: boolean + /** When the answer can next change on its own; null when only new input can change it. */ + recheckInMs: number | null +} + +export function stepCalmStatusReveal( + previous: CalmStatusReveal, + input: { + down: boolean + immediate: boolean + now: number + /** An outage start another observer already saw; the clock continues from it. */ + since?: number | null + } +): CalmStatusStep { + const { now } = input + if (input.down) { + const downSince = previous.downSince ?? Math.min(input.since ?? now, now) + const shownAt = + previous.shownAt ?? + (input.immediate || now - downSince >= CALM_STATUS_REVEAL_DELAY_MS ? now : null) + return { + next: { downSince, shownAt, healthySince: null }, + visible: shownAt !== null, + recheckInMs: shownAt === null ? downSince + CALM_STATUS_REVEAL_DELAY_MS - now : null + } + } + if (previous.downSince === null) { + return { next: CALM_STATUS_IDLE, visible: false, recheckInMs: null } + } + const healthySince = previous.healthySince ?? now + const hideAt = Math.max( + healthySince + CALM_STATUS_HEALTHY_HOLD_MS, + previous.shownAt === null ? 0 : previous.shownAt + CALM_STATUS_MIN_VISIBLE_MS + ) + if (now >= hideAt) { + return { next: CALM_STATUS_IDLE, visible: false, recheckInMs: null } + } + return { + next: { ...previous, healthySince }, + visible: previous.shownAt !== null, + recheckInMs: hideAt - now + } +} diff --git a/src/shared/remote-runtime/remote-runtime-tailscale-hint.test.ts b/src/shared/remote-runtime/remote-runtime-tailscale-hint.test.ts index 8bf3e1004206..db290df6d382 100644 --- a/src/shared/remote-runtime/remote-runtime-tailscale-hint.test.ts +++ b/src/shared/remote-runtime/remote-runtime-tailscale-hint.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it } from 'vitest' import { isTailscaleEndpoint, + tailscaleHostOfEndpoint, + tailscalePingCommand, withRemoteRuntimeTailscaleHint } from './remote-runtime-tailscale-hint' @@ -86,3 +88,12 @@ describe('withRemoteRuntimeTailscaleHint', () => { expect(twice).toBe(once) }) }) + +describe('tailscaleHostOfEndpoint', () => { + it('returns a pasteable host only when it is plain DNS or IP syntax', () => { + expect(tailscaleHostOfEndpoint('ws://desk.tail1234.ts.net:6768')).toBe('desk.tail1234.ts.net') + expect(tailscaleHostOfEndpoint('ws://[fd7a:115c:a1e0::1]:6768')).toBe('fd7a:115c:a1e0::1') + expect(tailscaleHostOfEndpoint('ws://$(id).ts.net:6768')).toBeNull() + expect(tailscalePingCommand('100.101.102.103')).toBe('tailscale ping 100.101.102.103') + }) +}) diff --git a/src/shared/remote-runtime/remote-runtime-tailscale-hint.ts b/src/shared/remote-runtime/remote-runtime-tailscale-hint.ts index 6dcccbb9e123..b85a00a3b17f 100644 --- a/src/shared/remote-runtime/remote-runtime-tailscale-hint.ts +++ b/src/shared/remote-runtime/remote-runtime-tailscale-hint.ts @@ -24,6 +24,8 @@ const TAILSCALE_CGNAT_RE = /^100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./ // Tailscale also assigns each node an IPv6 address from the fd7a:115c:a1e0::/48 ULA // block, and pairing endpoints can carry an IPv6 literal (see resolvePairingEndpoint). const TAILSCALE_IPV6_RE = /^fd7a:115c:a1e0:/i +const SAFE_HOST_RE = + /^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*|[0-9a-f:]+)$/i function extractHost(endpoint: string): string | null { let host: string | null @@ -42,19 +44,27 @@ function extractHost(endpoint: string): string | null { return host.replace(/^\[|\]$/g, '').replace(/\.$/, '') || null } -export function isTailscaleEndpoint(endpoint: string | null | undefined): boolean { - if (!endpoint) { - return false - } - const host = extractHost(endpoint) - if (!host) { - return false +/** The endpoint's host when it is a Tailscale address (what `tailscale ping` takes); else null. */ +export function tailscaleHostOfEndpoint(endpoint: string | null | undefined): string | null { + const host = endpoint ? extractHost(endpoint) : null + // Why strict: the host is pasted into a shell, so only DNS-label or IP-literal characters pass. + if (!host || !SAFE_HOST_RE.test(host)) { + return null } - return ( - TAILSCALE_MAGIC_DNS_SUFFIX_RE.test(host) || + return TAILSCALE_MAGIC_DNS_SUFFIX_RE.test(host) || (IPV4_LITERAL_RE.test(host) && TAILSCALE_CGNAT_RE.test(host)) || TAILSCALE_IPV6_RE.test(host) - ) + ? host + : null +} + +/** A command, never translated: the user pastes it into a shell. */ +export function tailscalePingCommand(host: string): string { + return `tailscale ping ${host}` +} + +export function isTailscaleEndpoint(endpoint: string | null | undefined): boolean { + return tailscaleHostOfEndpoint(endpoint) !== null } /**