fix(cloud): RA-11 Restart on a paired pane stops its host terminal first; success needs a new PTY

m4air (clean run, no other client): Restart showed 'Restarting Claude…', the pane took the queued
restart, but its PTY never changed and the old Claude kept running; the strip then cleared on the
'quiet relaunch counts' rule, a false success. An Orca Cloud pane is a paired web-host pane: the
desktop reconnect asks the host to ensure the pane's agent session, and the host hands back the live
terminal still running that session. Nothing on the remote path stopped it (local panes pass
replacesPtyId; remote ones had nothing).

Now a strip Restart on a remote-runtime pane resolves that pane's host PTY and stops exactly it
(terminal.stopExact, targetOnly), suppressing its exit, and only then reconnects with the resume
startup. A stop that fails shows 'Couldn't restart Claude' and never reconnects. Success needs proof:
the pane bound to a new PTY. The 'relaunched but quiet counts as restarted' rule is gone; anything
short of proof is 'Couldn't restart' at 10 s. Account-switch restarts are unchanged.
This commit is contained in:
Neil
2026-11-10 22:14:44 -08:00
parent 9802620b0d
commit 3f3ca73627
6 changed files with 246 additions and 31 deletions
@@ -2,7 +2,7 @@
// sign-in expires. Same component, place and height as #315's pre-launch strip; the terminal keeps
// running and refits below it, so its scrollback stays readable and selectable.
import type React from 'react'
import { useEffect, useRef } from 'react'
import { useEffect } from 'react'
import { createPortal } from 'react-dom'
import { useAppStore } from '@/store'
import { useTranslate } from '@/i18n/use-translate'
@@ -92,23 +92,15 @@ export function CloudRunningStripPortal({
const gate = useAgentSignInGate(paneKey)
const held = hold !== null || gate !== null
const attempt = cloudAgentRestartAttempt(paneKey, revision)
// Success: the relaunched agent's first status. The entry seen when the new PTY was asked for is
// the old agent's (or none); any later entry is the relaunched one. No clocks: the host stamps it.
const launchEntryRef = useRef<{ launchedAt: number; entry: unknown } | null>(null)
const launchedAt = attempt?.phase === 'restarting' ? attempt.launchedAt : null
// Success needs proof: the pane is bound to a new PTY after the relaunch was asked for (the old
// agent's terminal was replaced). Anything less turns into "Couldn't restart" at the timeout.
const launched = attempt?.phase === 'restarting' && attempt.launchedAt !== null
const attemptPtyId = attempt?.ptyId ?? null
useEffect(() => {
if (launchedAt === null) {
launchEntryRef.current = null
return
}
if (launchEntryRef.current?.launchedAt !== launchedAt) {
launchEntryRef.current = { launchedAt, entry }
return
}
if (entry !== null && entry !== launchEntryRef.current.entry) {
if (launched && ptyId !== null && ptyId !== attemptPtyId) {
settleCloudAgentRestart(paneKey)
}
}, [paneKey, launchedAt, entry])
}, [paneKey, launched, ptyId, attemptPtyId])
const restart = (args: { agent: HostAgentSignInAgent; resumable: boolean }): void => {
if (!ptyId) {
return
@@ -10,7 +10,8 @@ import {
beginCloudAgentRestart,
CLOUD_AGENT_RESTART_TIMEOUT_MS,
cloudAgentRestartAttempt,
resetCloudAgentRestartsForTest
resetCloudAgentRestartsForTest,
settleCloudAgentRestart
} from '@/lib/orca-cloud/cloud-agent-restart-attempt'
import { selectReadyAccountRestartPtyIds } from './pane-account-restart-readiness'
import { runReadyPaneAccountRestarts } from './use-ready-pane-account-restarts'
@@ -92,7 +93,8 @@ describe('RA-11 Restart through the account-restart runner', () => {
)
expect(useAppStore.getState().pendingPaneAccountRestarts).toEqual({})
expect(cloudAgentRestartAttempt(PANE_KEY, 0)?.launchedAt).not.toBeNull()
// Relaunched: the timeout never turns it into a failure.
// The strip settles it once the pane shows the new PTY (CloudRunningStripPortal).
expect(settleCloudAgentRestart(PANE_KEY)).toBe(true)
vi.advanceTimersByTime(CLOUD_AGENT_RESTART_TIMEOUT_MS)
expect(cloudAgentRestartAttempt(PANE_KEY, 0)).toBeNull()
})
@@ -133,3 +135,144 @@ describe('RA-11 Restart through the account-restart runner', () => {
expect(selectReadyAccountRestartPtyIds(useAppStore.getState(), TAB)).toEqual([])
})
})
// Orca Cloud panes are paired web-host panes: the host already runs a terminal there, so a reconnect
// alone reattaches to the old agent. The restart stops exactly that host terminal first.
describe('RA-11 Restart on a paired (remote) pane', () => {
const REMOTE = 'remote:env-1@@term_a'
const OTHER_TAB = 'tab-2'
const OTHER_LEAF = '22222222-2222-4222-8222-222222222222'
const OTHER = 'remote:env-1@@term_b'
const tab = (id: string, ptyId: string) => ({
id,
ptyId,
worktreeId: 'wt-1',
title: 'claude',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
})
const entry = (tabId: string, leafId: string): AgentStatusEntry => ({
paneKey: makePaneKey(tabId, leafId),
tabId,
state: 'blocked',
prompt: '',
updatedAt: 1,
stateStartedAt: 1,
stateHistory: [],
agentType: 'claude',
providerSession: { key: 'session_id', id: `sess-${tabId}` }
})
beforeEach(() => {
vi.useFakeTimers()
resetCloudRunningSignoutForTest()
resetCloudAgentRestartsForTest()
useAppStore.setState({
pendingPaneAccountRestarts: {},
suppressedPtyExitIds: {},
tabsByWorktree: { 'wt-1': [tab(TAB, REMOTE), tab(OTHER_TAB, OTHER)] },
terminalLayoutsByTabId: {
[TAB]: {
root: { type: 'leaf', leafId: LEAF },
activeLeafId: LEAF,
expandedLeafId: null,
ptyIdsByLeafId: { [LEAF]: REMOTE }
},
[OTHER_TAB]: {
root: { type: 'leaf', leafId: OTHER_LEAF },
activeLeafId: OTHER_LEAF,
expandedLeafId: null,
ptyIdsByLeafId: { [OTHER_LEAF]: OTHER }
}
},
agentStatusByPaneKey: {
[PANE_KEY]: entry(TAB, LEAF),
[makePaneKey(OTHER_TAB, OTHER_LEAF)]: entry(OTHER_TAB, OTHER_LEAF)
}
})
})
afterEach(() => {
resetCloudRunningSignoutForTest()
resetCloudAgentRestartsForTest()
useAppStore.setState({ pendingPaneAccountRestarts: {}, agentStatusByPaneKey: {} })
vi.useRealTimers()
})
function clickRemoteRestart(): void {
beginCloudAgentRestart(PANE_KEY, { agent: 'claude', resumable: true, ptyId: REMOTE }, () =>
useAppStore.getState().queuePaneAccountRestarts([REMOTE], 'claude')
)
}
function runRemote(stopRemotePane: (ptyId: string, worktreeId: string) => Promise<void>) {
const handleRestartPane = vi.fn()
runReadyPaneAccountRestarts({
panes: [{ id: 7, leafId: LEAF }],
ptyIdOf: () => REMOTE,
readyRestartPtyIds: selectReadyAccountRestartPtyIds(useAppStore.getState(), TAB),
tabId: TAB,
consumePendingPaneAccountRestart: useAppStore.getState().consumePendingPaneAccountRestart,
buildAccountRestartStartup: () => ({ command: 'claude --resume sess-tab-1' }),
handleRestartPane,
stopRemotePane
})
return handleRestartPane
}
it('stops only this pane’s host terminal, then reconnects with the resume startup', async () => {
clickRemoteRestart()
const stopRemotePane = vi.fn(() => Promise.resolve())
const handleRestartPane = runRemote(stopRemotePane)
// Not before the host confirms the old terminal stopped: else the reconnect reattaches to it.
expect(handleRestartPane).not.toHaveBeenCalled()
expect(cloudAgentRestartAttempt(PANE_KEY, 0)?.launchedAt).toBeNull()
await vi.waitFor(() => expect(handleRestartPane).toHaveBeenCalledTimes(1))
expect(stopRemotePane).toHaveBeenCalledTimes(1)
expect(stopRemotePane).toHaveBeenCalledWith(REMOTE, 'wt-1')
// The other Claude pane on the same account is untouched and keeps its status.
expect(stopRemotePane).not.toHaveBeenCalledWith(OTHER, expect.anything())
expect(
useAppStore.getState().agentStatusByPaneKey[makePaneKey(OTHER_TAB, OTHER_LEAF)]?.state
).toBe('blocked')
expect(handleRestartPane).toHaveBeenCalledWith(
7,
{ command: 'claude --resume sess-tab-1' },
{ focus: false }
)
expect(cloudAgentRestartAttempt(PANE_KEY, 0)?.launchedAt).not.toBeNull()
})
it('shows the failure and never reconnects when the host terminal could not be stopped', async () => {
clickRemoteRestart()
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
const handleRestartPane = runRemote(() =>
Promise.reject(new Error('terminal_exact_stop_failed'))
)
await vi.waitFor(() => expect(cloudAgentRestartAttempt(PANE_KEY, 0)?.phase).toBe('failed'))
warn.mockRestore()
expect(handleRestartPane).not.toHaveBeenCalled()
// Its exit suppression is withdrawn, so a later real exit still shows.
expect(useAppStore.getState().suppressedPtyExitIds[REMOTE]).toBeUndefined()
})
it('a reconnect that never binds a new PTY fails at the timeout', async () => {
clickRemoteRestart()
const handleRestartPane = runRemote(() => Promise.resolve())
await vi.waitFor(() => expect(handleRestartPane).toHaveBeenCalledTimes(1))
vi.advanceTimersByTime(CLOUD_AGENT_RESTART_TIMEOUT_MS)
expect(cloudAgentRestartAttempt(PANE_KEY, 0)?.phase).toBe('failed')
})
it('an account-switch restart on a remote pane does not stop the host terminal', () => {
useAppStore.setState({
agentStatusByPaneKey: { [PANE_KEY]: { ...entry(TAB, LEAF), state: 'done' } }
})
useAppStore.getState().queuePaneAccountRestarts([REMOTE], 'claude')
const stopRemotePane = vi.fn(() => Promise.resolve())
const handleRestartPane = runRemote(stopRemotePane)
expect(stopRemotePane).not.toHaveBeenCalled()
expect(handleRestartPane).toHaveBeenCalledTimes(1)
})
})
@@ -12,6 +12,8 @@ import {
} from '@/lib/orca-cloud/cloud-agent-restart-attempt'
import type { TerminalPaneCloseController } from '../layout/close/use-terminal-pane-close-actions'
import type { usePaneProcessRestart } from '../process-exit/use-pane-process-restart'
import { stopRemotePaneTerminalForRestart } from '@/lib/orca-cloud/cloud-pane-restart-stop'
import { isRemoteRuntimePtyId } from '../../../../../shared/remote-runtime/remote-runtime-pty-id'
import type { AccountRestartAgent } from '@/store/terminals/terminal-contracts'
import type { usePaneAccountRestartStartup } from './use-pane-account-restart-startup'
@@ -69,7 +71,16 @@ type ReadyRestartPane = { id: number; leafId: string }
* Run each of this tab's queued account restarts that may run now. An RA-11 Restart clicked on the
* Orca Cloud strip reports its outcome (launched, or failed) so the strip never vanishes silently.
*/
export function runReadyPaneAccountRestarts<Startup>(args: {
function worktreeIdForTab(tabId: string): string | null {
for (const [worktreeId, tabs] of Object.entries(useAppStore.getState().tabsByWorktree)) {
if (tabs.some((tab) => tab.id === tabId)) {
return worktreeId
}
}
return null
}
export function runReadyPaneAccountRestarts<Startup>(input: {
panes: readonly ReadyRestartPane[]
ptyIdOf: (paneId: number) => string | null
readyRestartPtyIds: readonly string[]
@@ -77,7 +88,10 @@ export function runReadyPaneAccountRestarts<Startup>(args: {
consumePendingPaneAccountRestart: (ptyId: string) => AccountRestartAgent | null
buildAccountRestartStartup: (agent: AccountRestartAgent, leafId: string) => Startup | null
handleRestartPane: (paneId: number, startup: Startup, options: { focus: boolean }) => void
/** Stops the one host terminal behind a paired pane before its restart reconnects. */
stopRemotePane?: (ptyId: string, worktreeId: string) => Promise<void>
}): void {
const args = { stopRemotePane: stopRemotePaneTerminalForRestart, ...input }
for (const pane of args.panes) {
const ptyId = args.ptyIdOf(pane.id)
if (
@@ -99,14 +113,33 @@ export function runReadyPaneAccountRestarts<Startup>(args: {
}
console.warn('[orca-cloud] restart startup failed:', err)
}
if (agent && startup) {
if (!agent || !startup) {
if (forced) {
failCloudAgentRestart(ptyId)
}
continue
}
const launchedStartup = startup
const launch = (): void => {
if (forced) {
noteCloudAgentRestartLaunched(ptyId)
}
// Why: one Claude switch restarts many panes at once; none was the one the user clicked.
args.handleRestartPane(pane.id, startup, { focus: agent === 'codex' })
} else if (forced) {
failCloudAgentRestart(ptyId)
args.handleRestartPane(pane.id, launchedStartup, { focus: agent === 'codex' })
}
const worktreeId = forced && isRemoteRuntimePtyId(ptyId) ? worktreeIdForTab(args.tabId) : null
if (!worktreeId) {
launch()
continue
}
// RA-11 on a paired pane: a reconnect alone reattaches to the running agent. Stop that one host
// terminal first (its exit is ours, not the pane's), then reconnect.
const store = useAppStore.getState()
store.suppressPtyExit(ptyId)
void args.stopRemotePane(ptyId, worktreeId).then(launch, (err: unknown) => {
console.warn('[orca-cloud] restart could not stop the pane’s host terminal:', err)
useAppStore.getState().consumeSuppressedPtyExit(ptyId)
failCloudAgentRestart(ptyId)
})
}
}
@@ -87,11 +87,11 @@ describe('Restart attempt (RA-11)', () => {
expect(cloudAgentRestartAttempt(PANE, 0)).toBeNull()
})
it('a relaunch with no status by the timeout counts as restarted, never as failed', () => {
it('a relaunch with no proof (no new PTY) by the timeout is a failure, never a quiet success', () => {
begin()
noteCloudAgentRestartLaunched(PTY)
vi.advanceTimersByTime(CLOUD_AGENT_RESTART_TIMEOUT_MS)
expect(cloudAgentRestartAttempt(PANE, 0)).toBeNull()
expect(cloudAgentRestartAttempt(PANE, 0)?.phase).toBe('failed')
})
it('ignores launches and failures of other PTYs', () => {
@@ -64,12 +64,8 @@ export function beginCloudAgentRestart(
return
}
forcedRestarts.delete(attempt.ptyId)
if (attempt.launchedAt !== null) {
// Relaunched but silent so far: the restart happened; the account read decides what shows.
restarts.delete(paneKey)
} else {
restarts.set(paneKey, { ...attempt, phase: 'failed' })
}
// No proof of a relaunch (a new PTY in the pane, or the relaunched agent's status) in time.
restarts.set(paneKey, { ...attempt, phase: 'failed' })
notifyCloudRunningStrips()
}, CLOUD_AGENT_RESTART_TIMEOUT_MS)
)
@@ -126,7 +122,8 @@ export function cloudAgentRestartAttempt(
}
/**
* Settle a launched attempt: the relaunched agent reported. Returns whether it settled. The strip
* Settle a launched attempt once there is proof it relaunched: the pane's PTY changed or the
* relaunched agent reported (the caller checks). Returns whether it settled. The strip
* then follows the account: gone, or state 1 if the sign-in is still bad.
*/
export function settleCloudAgentRestart(paneKey: string): boolean {
@@ -0,0 +1,50 @@
// RA-11: Restart on a paired (web-host) pane. The host already runs a terminal in that pane, so a
// desktop reconnect reattaches to it (ensureAgentSession hands back the live session) and nothing
// relaunches. Stop exactly that one host terminal first; the reconnect then starts the agent anew.
import { parseRemoteRuntimePtyId } from '../../../../shared/remote-runtime/remote-runtime-pty-id'
import type { RuntimeTerminalShow } from '../../../../shared/runtime-terminal-contracts'
import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call'
import { toRuntimeWorktreeSelector } from '@/runtime/rpc/targets/runtime-worktree-selector'
type StopExactResult = {
stoppedPtyIds?: string[]
postStopVerified?: boolean
postStopFailure?: string
}
/** Stop the host terminal behind one remote pane. Throws unless the host confirms it stopped. */
export async function stopRemotePaneTerminalForRestart(
ptyId: string,
worktreeId: string
): Promise<void> {
const parsed = parseRemoteRuntimePtyId(ptyId)
if (!parsed?.environmentId) {
throw new Error('restart_remote_pane_unowned')
}
const target = { kind: 'environment' as const, environmentId: parsed.environmentId }
// The pane names its terminal by handle; the host stops by its own PTY id.
const { terminal } = await callRuntimeRpc<{ terminal?: RuntimeTerminalShow }>(
target,
'terminal.show',
{ terminal: parsed.handle },
{ timeoutMs: 10_000 }
)
const hostPtyId = terminal?.ptyId
if (!hostPtyId) {
throw new Error('restart_remote_pane_not_live')
}
const result = await callRuntimeRpc<StopExactResult>(
target,
'terminal.stopExact',
{
worktree: toRuntimeWorktreeSelector(worktreeId),
expectedPtyIds: [hostPtyId],
// Only this pane: every other terminal in the workspace keeps running.
targetOnly: true
},
{ timeoutMs: 15_000 }
)
if (result.postStopVerified !== true || !result.stoppedPtyIds?.includes(hostPtyId)) {
throw new Error(result.postStopFailure ?? 'restart_remote_pane_stop_unverified')
}
}