Merge pull request #330 from nwparker/cloud/ra11-running-strip

feat(cloud): RA-11 — strip over a running Orca Cloud agent whose sign-in expires; strip reserves its height
This commit is contained in:
Neil
2026-11-10 23:23:37 -08:00
committed by GitHub
28 changed files with 2238 additions and 52 deletions
@@ -0,0 +1,45 @@
import { describe, expect, it, vi } from 'vitest'
const runtimes = vi.hoisted((): { list: unknown[] } => ({ list: [] }))
vi.mock('../../shared/ephemeral-vm-runtime-store', () => ({
listEphemeralVmRuntimes: () => runtimes.list
}))
vi.mock('../environment-providers/environment-provider-recipe-adapter', () => ({
environmentHandleFromRecipeResult: (result: { sandboxId?: string } | undefined) =>
result?.sandboxId ? { environmentId: result.sandboxId } : null
}))
const { orcaCloudSandboxIdFor } = await import('./orca-cloud-sandbox-id')
describe('orcaCloudSandboxIdFor', () => {
it('resolves composer-created cloud workspaces whose recipe has no provider (RA-11)', () => {
runtimes.list = [
{
runtimeEnvironmentId: 'env-a',
recipe: { id: 'cloud' },
recipeResult: { sandboxId: 'sbx_a' }
},
{
runtimeEnvironmentId: 'env-b',
recipe: { id: 'cloud', provider: 'orca-cloud' },
recipeResult: { sandboxId: 'sbx_b' }
}
]
expect(orcaCloudSandboxIdFor('/u', 'env-a')).toBe('sbx_a')
expect(orcaCloudSandboxIdFor('/u', 'env-b')).toBe('sbx_b')
})
it('never resolves another provider, an unknown runtime, or one without a hosted-sandbox handle', () => {
runtimes.list = [
{
runtimeEnvironmentId: 'env-c',
recipe: { provider: 'custom' },
recipeResult: { sandboxId: 'x' }
},
{ runtimeEnvironmentId: 'env-d', recipe: { id: 'cloud' }, recipeResult: {} }
]
expect(orcaCloudSandboxIdFor('/u', 'env-c')).toBeNull()
expect(orcaCloudSandboxIdFor('/u', 'env-d')).toBeNull()
expect(orcaCloudSandboxIdFor('/u', 'env-zzz')).toBeNull()
})
})
@@ -12,7 +12,9 @@ export function orcaCloudSandboxIdFor(
const runtime = listEphemeralVmRuntimes(userDataPath).find(
(record) =>
record.runtimeEnvironmentId === runtimeEnvironmentId &&
record.recipe?.provider === 'orca-cloud'
// Composer-created cloud workspaces store the recipe without a provider (like
// cloud-desktop-keys); the hosted-sandbox handle below is what proves it is Orca Cloud.
(record.recipe?.provider === 'orca-cloud' || record.recipe?.provider === undefined)
)
const handle = runtime?.recipeResult
? environmentHandleFromRecipeResult(runtime.recipeResult, HOSTED_SANDBOX_DRIVER_ID)
@@ -11,6 +11,9 @@ import {
type CloudStripActions
} from './CloudAgentSignInStrip'
import { cloudAgentStripModel } from './cloud-agent-strip-model'
import { cloudRestartAttemptModel, cloudRunningStripModel } from './cloud-running-strip-model'
import type { CloudAgentRestartAttempt } from '@/lib/orca-cloud/cloud-agent-restart-attempt'
import type { CloudRunningStrip } from '@/lib/orca-cloud/cloud-running-agent-signout'
const noop = (): void => {}
const ACTIONS: CloudStripActions = {
@@ -24,29 +27,39 @@ const ACTIONS: CloudStripActions = {
const PROMPT = 'Fix the flaky auth test and open a PR'
function Pane({
reason,
reason = 'accountExpired',
view = null,
agent = 'claude',
width = 900
width = 900,
running,
restart
}: {
reason: CloudAgentStripReason
reason?: CloudAgentStripReason
view?: AgentSignInGateView | null
agent?: HostAgentSignInAgent
width?: number
/** RA-11: the strip over a running agent instead of a held launch. */
running?: CloudRunningStrip
/** RA-11: a Restart in flight, or one that failed. */
restart?: CloudAgentRestartAttempt
}): React.JSX.Element {
const model = cloudAgentStripModel({
agent,
reason,
view,
hostLabel: translate('agentSignInStrip.sandbox', 'the sandbox'),
t: translate
})
const model = restart
? cloudRestartAttemptModel(restart, translate)
: running
? cloudRunningStripModel(running, translate)
: cloudAgentStripModel({
agent,
reason,
view,
hostLabel: translate('agentSignInStrip.sandbox', 'the sandbox'),
t: translate
})
return (
<div className="bg-background p-4">
{/* Stands in for a terminal pane: its title row (split, close) stays above the strip. */}
<div
data-strip-pane
className="relative h-[220px] overflow-hidden rounded-md border border-border bg-background"
className="pane relative h-[220px] overflow-hidden rounded-md border border-border bg-background"
style={{ width }}
>
<div className="pane-title-overlay-layer">
@@ -64,14 +77,21 @@ function Pane({
<CloudStripLayer>
<CloudAgentSignInStrip
model={model}
prompt={PROMPT}
prompt={running ? null : PROMPT}
width={cloudStripWidth(width)}
actions={ACTIONS}
/>
</CloudStripLayer>
<pre className="absolute inset-x-0 bottom-0 top-20 p-3 font-mono text-xs text-muted-foreground">
~/acme/web $
</pre>
{/* The terminal: it starts below the strip (reserved, never covered) and keeps its rows. */}
<div className="xterm-container overflow-hidden font-mono text-xs leading-4 text-muted-foreground">
{running ? (
<>
<div>⏺ Reading src/auth/session.ts…</div>
<div>⏺ API Error: 401 · Not logged in · Run /login</div>
</>
) : null}
<div data-terminal-last-row>~/acme/web $</div>
</div>
</div>
</div>
)
@@ -128,3 +148,37 @@ export const waitingNarrow = fixture({
export const needExpiredNarrow = fixture({ reason: 'accountExpired', width: 520 })
/** Below 360 px: one line and Renew; the detail stays the region's description. */
export const needExpiredCompact = fixture({ reason: 'accountExpired', width: 320 })
/** RA-11 state 1: Claude was running when its Orca-account sign-in expired. */
export const runningExpired = fixture({ running: { phase: 'expired', agent: 'claude' } })
export const runningExpiredCompact = fixture({
running: { phase: 'expired', agent: 'claude' },
width: 320
})
/** RA-11 state 2: renewed; this pane's agent still needs a restart (resumes its conversation). */
export const runningRenewed = fixture({
running: { phase: 'renewed', agent: 'claude', resumable: true }
})
/** RA-11 state 2 when the session can't be resumed. */
export const runningRenewedFresh = fixture({
running: { phase: 'renewed', agent: 'claude', resumable: false }
})
export const runningRenewedNarrow = fixture({
running: { phase: 'renewed', agent: 'claude', resumable: true },
width: 520
})
/** RA-11 after Restart: the strip stays, spinner, button disabled, until the agent reports. */
export const runningRestarting = fixture({
restart: { phase: 'restarting', agent: 'claude', resumable: true, ptyId: 'p', launchedAt: null }
})
/** RA-11: nothing relaunched in time. */
export const runningRestartFailed = fixture({
restart: {
phase: 'failed',
agent: 'claude',
resumable: true,
ptyId: 'p',
launchedAt: null,
failure: 'hostUnresponsive'
}
})
@@ -23,6 +23,7 @@ import {
} from '@/components/ui/dropdown-menu'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { cn } from '@/lib/utils'
import { useReservePaneTopSpace } from '../terminal-pane/appearance/pane-top-banner/PaneTopWarningBanner'
import type {
CloudStripModel,
CloudStripPrimary,
@@ -69,11 +70,15 @@ function useLiveStripWidth(
* buttons stay visible and clickable while it shows (RA-1). The pane and its fixture share it.
*/
export function CloudStripLayer({ children }: { children: React.ReactNode }): React.JSX.Element {
// A pane-top banner (RA-11): the pane reserves its height and the terminal refits below it, so
// no row sits under the strip. The spacer keeps it below a chromeless pane's title-row buttons.
const ref = useReservePaneTopSpace()
return (
<div
data-cloud-strip-layer
className="absolute inset-x-0 top-[var(--orca-pane-title-height,24px)] z-20"
>
<div ref={ref} data-cloud-strip-layer className="pane-top-banner">
<div
aria-hidden
className="pointer-events-none h-[var(--orca-pane-title-height,24px)] [.pane[data-has-title]_&]:hidden"
/>
{children}
</div>
)
@@ -237,6 +242,10 @@ export function CloudAgentSignInStrip({
{primary ? (
<Button
type="button"
// The short label still names what it does for a screen reader.
aria-label={
(width === 'tiny' || compact) && primary.narrowLabel ? primary.label : undefined
}
size="xs"
variant={model.status === 'error' ? 'outline' : 'default'}
aria-busy={primary.busy || undefined}
@@ -281,13 +290,17 @@ export function CloudAgentSignInStrip({
</DropdownMenuContent>
</DropdownMenu>
) : null}
{/* Renew is the whole action and the strip leaves on its own; Escape still cancels. */}
{model.status === 'done' || primary?.action.kind === 'renew' ? null : (
{/* Renew and Restart are the whole action and the strip leaves on its own; Escape still cancels. */}
{model.noClose ||
(!model.dismiss &&
(model.status === 'done' ||
primary?.action.kind === 'renew' ||
primary?.action.kind === 'restart')) ? null : (
<Button
type="button"
variant="ghost"
size="icon-xs"
aria-label={t('agentSignInStrip.cancel', 'Cancel sign-in (Esc)')}
aria-label={model.dismiss ?? t('agentSignInStrip.cancel', 'Cancel sign-in (Esc)')}
onClick={actions.cancel}
>
<X aria-hidden />
@@ -33,6 +33,7 @@ import {
type CloudStripActions
} from './CloudAgentSignInStrip'
import { cloudAgentStripModel } from './cloud-agent-strip-model'
import { CloudRunningStripPortal } from './CloudRunningStripPortal'
const ABANDON_CHECK_MS = 1_000
@@ -118,6 +119,10 @@ function CloudStripPortal({
const gateActions = agentSignInCardActions(paneKey)
const actions: CloudStripActions = {
primary: (action) => {
// RA-11's restart belongs to the running-pane strip; a held launch never offers it.
if (action.kind === 'restart') {
return
}
switch (action.kind) {
case 'renew':
openOrcaCloudSignInSheet()
@@ -168,7 +173,14 @@ export function CloudAgentSignInStripPortals({
return (
<>
{controller.managedPanes.map((pane, index) => (
<CloudStripPortal key={pane.id} pane={pane} tabId={controller.tabId} first={index === 0} />
<React.Fragment key={pane.id}>
<CloudStripPortal pane={pane} tabId={controller.tabId} first={index === 0} />
<CloudRunningStripPortal
pane={pane}
tabId={controller.tabId}
worktreeId={controller.worktreeId}
/>
</React.Fragment>
))}
</>
)
@@ -0,0 +1,185 @@
// RA-11: the strip over an Orca Cloud pane whose agent is already running when its Orca-account
// 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 } from 'react'
import { createPortal } from 'react-dom'
import { useAppStore } from '@/store'
import { useTranslate } from '@/i18n/use-translate'
import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id'
import { parseRemoteRuntimePtyId } from '../../../../shared/remote-runtime/remote-runtime-pty-id'
import type { ManagedPane } from '@/lib/pane-manager/pane-manager-types'
import type { HostAgentSignInAgent } from '../../../../shared/host-agent-sign-in-status'
import { useAgentSignInGate } from '@/lib/agent-sign-in/agent-sign-in-gate-store'
import { useCloudAgentHold } from '@/lib/orca-cloud/cloud-agent-launch-hold'
import {
orcaCloudAgentAccountsLoadedAt,
useOrcaCloudAgentAccounts
} from '@/lib/orca-cloud/orca-cloud-agent-accounts-store'
import { isOrcaCloudEnvironmentId } from '@/lib/orca-cloud/orca-cloud-environment-id'
import { runtimeEnvironmentIdOrLocalUnlessTwin } from '@/lib/workspace/ownership/worktree-runtime-owner'
import {
clearCloudRunningSignout,
cloudRunningStrip,
useCloudRunningAccountReads,
useCloudRunningSignoutVersion,
useWorkspaceUsesAccount
} from '@/lib/orca-cloud/cloud-running-agent-signout'
import {
beginCloudAgentRestart,
cloudAgentRestartAttempt,
dismissCloudAgentRestart,
settleCloudAgentRestart
} from '@/lib/orca-cloud/cloud-agent-restart-attempt'
import {
CloudAgentSignInStrip,
CloudStripLayer,
cloudStripWidth,
type CloudStripActions
} from './CloudAgentSignInStrip'
import { watchCloudAgentRestartPane } from '@/lib/orca-cloud/cloud-agent-restart-pane-watch'
import { cloudRestartAttemptModel, cloudRunningStripModel } from './cloud-running-strip-model'
function openAccounts(): void {
const store = useAppStore.getState()
store.openSettingsTarget({ pane: 'accounts', repoId: null, sectionId: 'orca-cloud' })
store.openSettingsPage()
}
export function CloudRunningStripPortal({
pane,
tabId,
worktreeId
}: {
pane: ManagedPane
tabId: string
worktreeId: string
}): React.JSX.Element | null {
const t = useTranslate()
const paneKey = makePaneKey(tabId, pane.leafId)
const revision = useCloudRunningSignoutVersion()
const ptyId = useAppStore(
(state) => state.terminalLayoutsByTabId[tabId]?.ptyIdsByLeafId?.[pane.leafId] ?? null
)
const environmentId = useAppStore(
(state) =>
(ptyId ? parseRemoteRuntimePtyId(ptyId)?.environmentId : null) ??
runtimeEnvironmentIdOrLocalUnlessTwin(state, worktreeId)
)
const cloud = environmentId !== null && isOrcaCloudEnvironmentId(environmentId)
const entry = useAppStore((state) =>
cloud ? (state.agentStatusByPaneKey[paneKey] ?? null) : null
)
const running = cloud && (entry?.agentType === 'claude' || entry?.agentType === 'codex')
useCloudRunningAccountReads(running)
const accounts = useOrcaCloudAgentAccounts(running)
const agentType = entry?.agentType
const agent: HostAgentSignInAgent | null =
agentType === 'claude' ? 'claude' : agentType === 'codex' ? 'codex' : null
// D13: only a workspace that runs the agent on the person's own account (never shared or keyed).
const expired =
agent !== null &&
accounts.load.kind === 'ready' &&
accounts.load.status.credentials[agent].state !== 'active' &&
accounts.load.status.credentials[agent].state !== 'expiring' &&
accounts.load.status.credentials[agent].state !== 'none'
const usesAccount = useWorkspaceUsesAccount(
running ? environmentId : null,
agent,
expired,
orcaCloudAgentAccountsLoadedAt()
)
const hold = useCloudAgentHold(paneKey)
const gate = useAgentSignInGate(paneKey)
const held = hold !== null || gate !== null
const attempt = cloudAgentRestartAttempt(paneKey, revision)
// 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 (launched && ptyId !== null && ptyId !== attemptPtyId) {
settleCloudAgentRestart(paneKey)
}
}, [paneKey, launched, ptyId, attemptPtyId])
const restart = (args: { agent: HostAgentSignInAgent; resumable: boolean }): void => {
if (!ptyId) {
return
}
// Never automatic: the person asked. The pane's own session resumes when it has one.
beginCloudAgentRestart(paneKey, { ...args, ptyId }, () =>
useAppStore.getState().queuePaneAccountRestarts([ptyId], args.agent)
)
watchCloudAgentRestartPane(paneKey, worktreeId, args.agent)
}
// A Restart in flight (or failed) owns the strip even while the pane has no agent status.
if (attempt && cloud) {
const attemptActions: CloudStripActions = {
primary: (action) => {
if (action.kind === 'restart' && attempt.phase === 'failed') {
restart({ agent: attempt.agent, resumable: attempt.resumable })
}
},
submitCode: () => undefined,
pasteCode: () => undefined,
useCode: () => undefined,
useApiKey: () => undefined,
cancel: () => (attempt.phase === 'failed' ? dismissCloudAgentRestart(paneKey) : undefined)
}
return createPortal(
<CloudStripLayer>
<CloudAgentSignInStrip
model={cloudRestartAttemptModel(attempt, t)}
prompt={null}
width={cloudStripWidth(pane.container.clientWidth)}
actions={attemptActions}
/>
</CloudStripLayer>,
pane.container,
`cloud-running-strip-${pane.id}`
)
}
if (!running) {
return null
}
// The read that showed the renewal dates it (a pure read, never the render clock).
const strip = cloudRunningStrip({
paneKey,
entry,
accounts,
held,
now: orcaCloudAgentAccountsLoadedAt(),
usesAccount,
revision
})
if (!strip) {
return null
}
const actions: CloudStripActions = {
primary: (action) => {
if (action.kind === 'renew') {
openAccounts()
} else if (action.kind === 'restart' && strip.phase === 'renewed') {
restart({ agent: strip.agent, resumable: strip.resumable })
}
},
submitCode: () => undefined,
pasteCode: () => undefined,
useCode: () => undefined,
useApiKey: () => undefined,
// State 2's ×; state 1 has none (Renew is the action) and Escape leaves it showing.
cancel: () => (strip.phase === 'renewed' ? clearCloudRunningSignout(paneKey) : undefined)
}
return createPortal(
<CloudStripLayer>
<CloudAgentSignInStrip
model={cloudRunningStripModel(strip, t)}
prompt={null}
width={cloudStripWidth(pane.container.clientWidth)}
actions={actions}
/>
</CloudStripLayer>,
pane.container,
`cloud-running-strip-${pane.id}`
)
}
@@ -17,6 +17,8 @@ export type CloudStripPrimary =
| { kind: 'submitCode' }
| { kind: 'retry' }
| { kind: 'useDeviceCode' }
/** RA-11: restart the running agent in its pane, resuming its conversation when it can. */
| { kind: 'restart' }
export type CloudStripModel = {
status: CloudStripStatus
@@ -35,6 +37,10 @@ export type CloudStripModel = {
otherWays: boolean
/** Already on a code: ⋯ offers the paste fallback and Cancel instead of "Use a code". */
codeStep?: boolean
/** RA-11 state 2: a dismiss × with this label (the strip otherwise drops its × on Renew). */
dismiss?: string
/** RA-11 "Restarting…": nothing to close; the strip leaves with the result. */
noClose?: boolean
/** One sentence for the polite region. */
announcement: string
}
@@ -0,0 +1,42 @@
import { describe, expect, it } from 'vitest'
import { translate } from '@/i18n/i18n'
import { cloudRestartAttemptModel } from './cloud-running-strip-model'
const attempt = { agent: 'claude' as const, resumable: true, ptyId: 'p', launchedAt: null }
describe('RA-11 Restart feedback copy', () => {
it('restarting: spinner and words only, no button and nothing to close', () => {
const model = cloudRestartAttemptModel({ ...attempt, phase: 'restarting' }, translate)
expect(model).toMatchObject({
status: 'busy',
title: 'Restarting Claude…',
detail: 'Picking up where you left off.',
primary: null,
noClose: true
})
expect(model.dismiss).toBeUndefined()
const fresh = cloudRestartAttemptModel(
{ ...attempt, resumable: false, phase: 'restarting' },
translate
)
expect(fresh.detail).toBe('Starts a new conversation.')
})
it('failed: says so once, the reason when known, and offers Try again and a dismiss', () => {
const unresponsive = cloudRestartAttemptModel(
{ ...attempt, phase: 'failed', failure: 'hostUnresponsive' },
translate
)
expect(unresponsive.detail).toBe('The workspace didn’t respond.')
const model = cloudRestartAttemptModel({ ...attempt, phase: 'failed' }, translate)
expect(model).toMatchObject({
status: 'error',
title: 'Couldn’t restart Claude',
detail: '',
primary: { label: 'Try again', action: { kind: 'restart' } },
dismiss: 'Dismiss',
announcement: 'Couldn’t restart Claude. Try again.'
})
expect(model.primary?.busy).toBeUndefined()
})
})
@@ -0,0 +1,102 @@
// RA-11 copy (design-squad): the strip over an Orca Cloud pane whose agent was already running when
// its Orca-account sign-in expired. Same words as #315's pre-launch strip, then the per-pane restart.
import type { Translate } from '@/i18n/use-translate'
import type { CloudRunningStrip } from '@/lib/orca-cloud/cloud-running-agent-signout'
import type { CloudAgentRestartAttempt } from '@/lib/orca-cloud/cloud-agent-restart-attempt'
import { HOST_AGENT_SIGN_IN_AGENT_NAME } from '../../../../shared/host-agent-sign-in-status'
import type { CloudStripModel } from './cloud-agent-strip-model'
export function cloudRunningStripModel(strip: CloudRunningStrip, t: Translate): CloudStripModel {
const agent = HOST_AGENT_SIGN_IN_AGENT_NAME[strip.agent]
const base = { code: null, paste: null, otherWays: false, description: null }
if (strip.phase === 'expired') {
return {
...base,
status: 'warning',
title: t('agentSignInStrip.expired', 'Your {{agent}} sign-in expired', { agent }),
compactTitle: t('agentSignInStrip.expiredCompact', '{{agent}} sign-in expired', { agent }),
detail: t(
'agentSignInStrip.runningExpiredDetail',
'Renew to keep working. Your conversation is kept.'
),
primary: { label: t('agentSignInStrip.renew', 'Renew'), action: { kind: 'renew' } },
announcement: t(
'agentSignInStrip.runningExpiredAnnounce',
'Your {{agent}} sign-in expired. Renew to keep working. Your conversation is kept.',
{ agent }
)
}
}
const restart = t('agentSignInStrip.restartAgent', 'Restart {{agent}}', { agent })
return {
...base,
status: 'done',
title: t('agentSignInStrip.renewed', '{{agent}} sign-in renewed', { agent }),
compactTitle: t('agentSignInStrip.renewed', '{{agent}} sign-in renewed', { agent }),
detail: strip.resumable
? t('agentSignInStrip.renewedResume', 'Restart {{agent}} to pick up where you left off.', {
agent
})
: t('agentSignInStrip.renewedFresh', 'Starts a new conversation.'),
primary: {
label: restart,
narrowLabel: t('agentSignInStrip.restart', 'Restart'),
action: { kind: 'restart' }
},
dismiss: t('agentSignInStrip.dismiss', 'Dismiss'),
announcement: t(
'agentSignInStrip.renewedAnnounce',
'{{agent}} sign-in renewed. Restart {{agent}} to use it.',
{ agent }
)
}
}
/** The strip while a Restart runs ("Restarting…", button disabled) or after it failed (Try again). */
export function cloudRestartAttemptModel(
attempt: CloudAgentRestartAttempt,
t: Translate
): CloudStripModel {
const agent = HOST_AGENT_SIGN_IN_AGENT_NAME[attempt.agent]
const base = { code: null, paste: null, otherWays: false, description: null }
if (attempt.phase === 'restarting') {
const title = t('agentSignInStrip.restarting', 'Restarting {{agent}}…', { agent })
return {
...base,
status: 'busy',
title,
compactTitle: title,
detail: attempt.resumable
? t('agentSignInStrip.restartingResume', 'Picking up where you left off.')
: t('agentSignInStrip.renewedFresh', 'Starts a new conversation.'),
// The spinner and the words are the whole state: no button to click twice.
primary: null,
noClose: true,
announcement: title
}
}
const title = t('agentSignInStrip.restartFailed', 'Couldn’t restart {{agent}}', { agent })
return {
...base,
status: 'error',
title,
compactTitle: title,
// Never "Try again." twice: the body names the reason when one is known, else stays empty.
detail:
attempt.failure === 'hostUnresponsive'
? t('agentSignInStrip.restartHostUnresponsive', 'The workspace didn’t respond.')
: '',
primary: {
label: t('agentSignInStrip.tryAgain', 'Try again'),
action: { kind: 'restart' }
},
dismiss: t('agentSignInStrip.dismiss', 'Dismiss'),
announcement: t(
'agentSignInStrip.restartFailedAnnounce',
'Couldn’t restart {{agent}}. Try again.',
{
agent
}
)
}
}
@@ -0,0 +1,342 @@
// RA-11 Restart end to end through the real store: the strip's click queues a Claude restart on a
// pane whose signed-out Claude reports 'blocked' (which the account-restart path reads as mid-turn),
// the mounted pane's runner relaunches it in place, and the strip learns the outcome.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useAppStore } from '@/store/index'
import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id'
import type { AgentStatusEntry } from '../../../../../shared/agent-status/contracts/agent-status-types'
import { resetCloudRunningSignoutForTest } from '@/lib/orca-cloud/cloud-running-agent-signout'
import {
beginCloudAgentRestart,
CLOUD_AGENT_RESTART_TIMEOUT_MS,
cloudAgentRestartAttempt,
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'
const TAB = 'tab-1'
const LEAF = '11111111-1111-4111-8111-111111111111'
const PTY = 'env-1@@pty-1'
const PANE_KEY = makePaneKey(TAB, LEAF)
function seed(state: AgentStatusEntry['state']): void {
useAppStore.setState({
pendingPaneAccountRestarts: {},
terminalLayoutsByTabId: {
[TAB]: {
root: { type: 'leaf', leafId: LEAF },
activeLeafId: LEAF,
expandedLeafId: null,
ptyIdsByLeafId: { [LEAF]: PTY }
}
},
agentStatusByPaneKey: {
[PANE_KEY]: {
paneKey: PANE_KEY,
tabId: TAB,
state,
prompt: '',
updatedAt: 1,
stateStartedAt: 1,
stateHistory: [],
agentType: 'claude',
providerSession: { key: 'session_id', id: 'sess-1' }
}
}
})
}
function clickRestart(): void {
beginCloudAgentRestart(PANE_KEY, { agent: 'claude', resumable: true, ptyId: PTY }, () =>
useAppStore.getState().queuePaneAccountRestarts([PTY], 'claude')
)
}
function runPane(build: (agent: string) => { command: string } | null) {
const handleRestartPane = vi.fn()
runReadyPaneAccountRestarts({
panes: [{ id: 7, leafId: LEAF }],
ptyIdOf: () => PTY,
readyRestartPtyIds: selectReadyAccountRestartPtyIds(useAppStore.getState(), TAB),
tabId: TAB,
consumePendingPaneAccountRestart: useAppStore.getState().consumePendingPaneAccountRestart,
buildAccountRestartStartup: build,
handleRestartPane
})
return handleRestartPane
}
describe('RA-11 Restart through the account-restart runner', () => {
beforeEach(() => {
vi.useFakeTimers()
resetCloudRunningSignoutForTest()
resetCloudAgentRestartsForTest()
})
afterEach(() => {
resetCloudRunningSignoutForTest()
resetCloudAgentRestartsForTest()
useAppStore.setState({ pendingPaneAccountRestarts: {}, agentStatusByPaneKey: {} })
vi.useRealTimers()
})
it('relaunches a blocked Claude in place, with the resume startup, and reports it launched', () => {
seed('blocked')
clickRestart()
expect(cloudAgentRestartAttempt(PANE_KEY, 0)?.phase).toBe('restarting')
const handleRestartPane = runPane(() => ({ command: 'claude --resume sess-1' }))
expect(handleRestartPane).toHaveBeenCalledWith(
7,
{ command: 'claude --resume sess-1' },
{ focus: false }
)
expect(useAppStore.getState().pendingPaneAccountRestarts).toEqual({})
expect(cloudAgentRestartAttempt(PANE_KEY, 0)?.launchedAt).not.toBeNull()
// 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()
})
it('an account-switch restart (not the strip) still waits out a blocked Claude', () => {
seed('blocked')
useAppStore.getState().queuePaneAccountRestarts([PTY], 'claude')
const handleRestartPane = runPane(() => ({ command: 'claude --resume sess-1' }))
expect(handleRestartPane).not.toHaveBeenCalled()
expect(useAppStore.getState().pendingPaneAccountRestarts).toEqual({ [PTY]: 'claude' })
})
it('shows the failure at once when the pane has no startup to launch', () => {
seed('blocked')
clickRestart()
const handleRestartPane = runPane(() => null)
expect(handleRestartPane).not.toHaveBeenCalled()
expect(cloudAgentRestartAttempt(PANE_KEY, 0)?.phase).toBe('failed')
})
it('shows the failure when the startup throws, without breaking the pane', () => {
seed('blocked')
clickRestart()
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
runPane(() => {
throw new Error('no claude command')
})
warn.mockRestore()
expect(cloudAgentRestartAttempt(PANE_KEY, 0)?.phase).toBe('failed')
})
it('shows the failure after the timeout when no mounted pane ran it', () => {
seed('blocked')
clickRestart()
vi.advanceTimersByTime(CLOUD_AGENT_RESTART_TIMEOUT_MS)
expect(cloudAgentRestartAttempt(PANE_KEY, 0)?.phase).toBe('failed')
// And the stale queued restart no longer jumps the mid-turn rule.
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()
// Never closes a tab or pane: the same tab and leaf are there after the restart.
const state = useAppStore.getState()
expect(state.tabsByWorktree['wt-1']?.map((t) => t.id)).toEqual([TAB, OTHER_TAB])
expect(state.terminalLayoutsByTabId[TAB]?.root).toEqual({ type: 'leaf', leafId: LEAF })
expect(state.terminalLayoutsByTabId[OTHER_TAB]?.ptyIdsByLeafId).toEqual({ [OTHER_LEAF]: OTHER })
})
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 resumable pane is relaunched on its own conversation in the same pane, after the stop', async () => {
clickRemoteRestart()
const order: string[] = []
const providerSession = { key: 'session_id' as const, id: 'sess-tab-1' }
const resumeRemotePane = vi.fn(async () => {
order.push('resume')
})
const handleRestartPane = vi.fn(() => order.push('reconnect'))
runReadyPaneAccountRestarts({
panes: [{ id: 7, leafId: LEAF }],
ptyIdOf: () => REMOTE,
readyRestartPtyIds: selectReadyAccountRestartPtyIds(useAppStore.getState(), TAB),
tabId: TAB,
consumePendingPaneAccountRestart: useAppStore.getState().consumePendingPaneAccountRestart,
buildAccountRestartStartup: () => ({
command: 'claude',
resumeProviderSession: providerSession
}),
handleRestartPane,
stopRemotePane: async () => {
order.push('stop')
},
resumeRemotePane
})
await vi.waitFor(() => expect(handleRestartPane).toHaveBeenCalledTimes(1))
expect(order).toEqual(['stop', 'resume', 'reconnect'])
expect(resumeRemotePane).toHaveBeenCalledWith({
ptyId: REMOTE,
worktreeId: 'wt-1',
tabId: TAB,
leafId: LEAF,
agent: 'claude',
providerSession
})
})
it('a failed resume on the host shows the failure and never reconnects', async () => {
clickRemoteRestart()
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
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',
resumeProviderSession: { key: 'session_id' as const, id: 'sess-tab-1' }
}),
handleRestartPane,
stopRemotePane: () => Promise.resolve(),
resumeRemotePane: () => Promise.reject(new Error('agent_session_resume_failed'))
})
await vi.waitFor(() => expect(cloudAgentRestartAttempt(PANE_KEY, 0)?.phase).toBe('failed'))
warn.mockRestore()
expect(handleRestartPane).not.toHaveBeenCalled()
})
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)
})
})
@@ -1,5 +1,7 @@
import type { AppState } from '@/store/types'
import { isClaudePaneMidTurn } from '@/lib/agent-session/accounts/claude/claude-session-account-move'
// RA-11: a Restart clicked on the Orca Cloud sign-in strip runs even though Claude reports 'blocked'.
import { isForcedCloudAgentRestart } from '@/lib/orca-cloud/cloud-agent-restart-attempt'
import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id'
/** PTYs whose queued account restart can run now: Codex at once, this tab's Claude once its turn ends. */
@@ -8,7 +10,10 @@ export function selectReadyAccountRestartPtyIds(state: AppState, tabId: string):
const ready = Object.keys(pending).filter((ptyId) => pending[ptyId] === 'codex')
const ptyIdsByLeafId = state.terminalLayoutsByTabId[tabId]?.ptyIdsByLeafId ?? {}
for (const [leafId, ptyId] of Object.entries(ptyIdsByLeafId)) {
if (pending[ptyId] === 'claude' && !isClaudePaneMidTurn(state, makePaneKey(tabId, leafId))) {
if (
pending[ptyId] === 'claude' &&
(!isClaudePaneMidTurn(state, makePaneKey(tabId, leafId)) || isForcedCloudAgentRestart(ptyId))
) {
ready.push(ptyId)
}
}
@@ -25,6 +30,7 @@ export function isAccountRestartReady(
const queued = state.pendingPaneAccountRestarts[ptyId]
return (
queued === 'codex' ||
(queued === 'claude' && !isClaudePaneMidTurn(state, makePaneKey(tabId, leafId)))
(queued === 'claude' &&
(!isClaudePaneMidTurn(state, makePaneKey(tabId, leafId)) || isForcedCloudAgentRestart(ptyId)))
)
}
@@ -5,8 +5,20 @@ import {
isAccountRestartReady,
selectReadyAccountRestartPtyIds
} from './pane-account-restart-readiness'
import {
failCloudAgentRestart,
isForcedCloudAgentRestart,
noteCloudAgentRestartLaunched
} 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 {
resumeRemotePaneAgent,
stopRemotePaneTerminalForRestart
} from '@/lib/orca-cloud/cloud-pane-restart-stop'
import type { AgentProviderSessionMetadata } from '../../../../../shared/agent-session/lifecycle/agent-session-resume'
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'
export function useReadyPaneAccountRestarts({
@@ -36,22 +48,15 @@ export function useReadyPaneAccountRestarts({
if (!manager || readyRestartPtyIds.length === 0) {
return
}
for (const pane of manager.getPanes()) {
const ptyId = paneTransportsRef.current.get(pane.id)?.getPtyId()
if (
!ptyId ||
!readyRestartPtyIds.includes(ptyId) ||
!isAccountRestartReady(useAppStore.getState(), tabId, pane.leafId, ptyId)
) {
continue
}
const agent = consumePendingPaneAccountRestart(ptyId)
const startup = agent ? buildAccountRestartStartup(agent, pane.leafId) : null
if (agent && startup) {
// Why: one Claude switch restarts many panes at once; none was the one the user clicked.
handleRestartPane(pane.id, startup, { focus: agent === 'codex' })
}
}
runReadyPaneAccountRestarts({
panes: manager.getPanes(),
ptyIdOf: (paneId) => paneTransportsRef.current.get(paneId)?.getPtyId() ?? null,
readyRestartPtyIds,
tabId,
consumePendingPaneAccountRestart,
buildAccountRestartStartup,
handleRestartPane
})
}, [
buildAccountRestartStartup,
consumePendingPaneAccountRestart,
@@ -63,3 +68,105 @@ export function useReadyPaneAccountRestarts({
tabId
])
}
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.
*/
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 extends { resumeProviderSession?: AgentProviderSessionMetadata }
>(input: {
panes: readonly ReadyRestartPane[]
ptyIdOf: (paneId: number) => string | null
readyRestartPtyIds: readonly string[]
tabId: string
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>
/** Relaunches the paired pane's agent on its own conversation, in the same pane. */
resumeRemotePane?: typeof resumeRemotePaneAgent
}): void {
const args = {
stopRemotePane: stopRemotePaneTerminalForRestart,
resumeRemotePane: resumeRemotePaneAgent,
...input
}
for (const pane of args.panes) {
const ptyId = args.ptyIdOf(pane.id)
if (
!ptyId ||
!args.readyRestartPtyIds.includes(ptyId) ||
!isAccountRestartReady(useAppStore.getState(), args.tabId, pane.leafId, ptyId)
) {
continue
}
const forced = isForcedCloudAgentRestart(ptyId)
const agent = args.consumePendingPaneAccountRestart(ptyId)
let startup: Startup | null = null
try {
startup = agent ? args.buildAccountRestartStartup(agent, pane.leafId) : null
} catch (err) {
// RA-11: a Restart clicked on the strip reports this; any other caller keeps its old behavior.
if (!forced) {
throw err
}
console.warn('[orca-cloud] restart startup failed:', err)
}
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, 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)
const providerSession = launchedStartup.resumeProviderSession ?? null
void args
.stopRemotePane(ptyId, worktreeId)
.then(() =>
providerSession
? args.resumeRemotePane({
ptyId,
worktreeId,
tabId: args.tabId,
leafId: pane.leafId,
agent,
providerSession
})
: undefined
)
.then(launch, (err: unknown) => {
console.warn('[orca-cloud] restart could not relaunch the pane’s agent on its host:', err)
useAppStore.getState().consumeSuppressedPtyExit(ptyId)
failCloudAgentRestart(ptyId)
})
}
}
@@ -25,7 +25,7 @@ function layoutPaneTopBanners(pane: HTMLElement, leaving?: HTMLElement): void {
}
/** Reserves the banner's height at the top of its pane so the terminal refits below it. */
function useReservePaneTopSpace(): React.RefObject<HTMLDivElement | null> {
export function useReservePaneTopSpace(): React.RefObject<HTMLDivElement | null> {
const ref = useRef<HTMLDivElement>(null)
useLayoutEffect(() => {
const banner = ref.current
+17 -1
View File
@@ -28150,7 +28150,23 @@
"cancelSignIn": "Cancel sign-in",
"copyAndOpen": "Copy code and open",
"cancelledToast": "The agent didn’t start. The shell is still open.",
"expiredCompact": "{{agent}} sign-in expired"
"expiredCompact": "{{agent}} sign-in expired",
"runningExpiredDetail": "Renew to keep working. Your conversation is kept.",
"runningExpiredAnnounce": "Your {{agent}} sign-in expired. Renew to keep working. Your conversation is kept.",
"restartAgent": "Restart {{agent}}",
"renewed": "{{agent}} sign-in renewed",
"renewedResume": "Restart {{agent}} to pick up where you left off.",
"renewedFresh": "Starts a new conversation.",
"restart": "Restart",
"dismiss": "Dismiss",
"renewedAnnounce": "{{agent}} sign-in renewed. Restart {{agent}} to use it.",
"restarting": "Restarting {{agent}}…",
"restartingResume": "Picking up where you left off.",
"restartFailed": "Couldn’t restart {{agent}}",
"restartHostUnresponsive": "The workspace didn’t respond.",
"restartFailedAnnounce": "Couldn’t restart {{agent}}. Try again.",
"restartFailedIn": "Couldn’t restart {{agent}} in {{workspace}}.",
"openWorkspace": "Open workspace"
},
"cloudSetupPage": {
"back": "Back",
@@ -18,6 +18,11 @@ let projectRuntimeContext: ProjectExecutionRuntimeResolution | undefined
vi.mock('@/lib/agent-session/resume/agent-resume-launch-target', { spy: true })
const cloud = vi.hoisted(() => ({ on: false }))
vi.mock('@/lib/orca-cloud/orca-cloud-environment-id', () => ({
isOrcaCloudEnvironmentId: () => cloud.on
}))
vi.mock('@/lib/local-preflight-context', async (importOriginal) => ({
...(await importOriginal<typeof localPreflightContext>()),
getLocalProjectExecutionRuntimeContext: () => projectRuntimeContext
@@ -186,3 +191,55 @@ describe('buildPaneAccountRestartStartup for Claude', () => {
}
})
})
// RA-11: Restart on an Orca Cloud pane refreshes the shell's session env, and a Claude pane with no
// session to resume starts a new conversation instead of doing nothing.
describe('buildPaneAccountRestartStartup on Orca Cloud', () => {
const pane = { tabId: TAB_ID, leafId: LEAF_ID, worktreeId: WORKTREE_ID }
const REFRESH = 'eval "$(orca-env 2>/dev/null)"; '
beforeEach(() => {
cloud.on = true
projectRuntimeContext = undefined
useAppStore.setState({
settings: getDefaultSettings('/home/dev'),
tabsByWorktree: {},
worktreesByRepo: {},
terminalLayoutsByTabId: {
[TAB_ID]: {
root: { type: 'leaf', leafId: LEAF_ID },
activeLeafId: LEAF_ID,
expandedLeafId: null,
ptyIdsByLeafId: { [LEAF_ID]: 'remote:env-cloud@@term_1' }
}
}
})
})
it('resume: refreshes the session env, then resumes the pane’s own session', () => {
seedAgentStatus({
agentType: 'claude',
providerSession: { key: 'session_id', id: SESSION_ID }
})
const startup = buildPaneAccountRestartStartup('claude', pane)
expect(startup?.command.startsWith(REFRESH)).toBe(true)
expect(startup?.command).toContain(`'--resume' '${SESSION_ID}'`)
})
it('fresh: with no session to resume it starts a new Claude conversation (after the refresh)', () => {
seedAgentStatus({ agentType: 'claude' })
const startup = buildPaneAccountRestartStartup('claude', pane)
expect(startup).toMatchObject({ launchAgent: 'claude', startupCommandDelivery: 'shell-ready' })
expect(startup?.command.startsWith(REFRESH)).toBe(true)
expect(startup?.command).not.toContain('--resume')
expect(startup?.command).toMatch(/claude/)
})
it('off Orca Cloud a Claude pane with no session still has no restart, and nothing is prefixed', () => {
cloud.on = false
seedAgentStatus({ agentType: 'claude' })
expect(buildPaneAccountRestartStartup('claude', pane)).toBeNull()
seedAgentStatus({ agentType: 'codex' })
expect(buildPaneAccountRestartStartup('codex', pane)?.command.startsWith(REFRESH)).toBe(false)
})
})
@@ -24,6 +24,10 @@ import { resolveResumeLaunchRecipe } from '../../../../../shared/agent-launch/ch
import type { AccountRestartAgent } from '@/store/terminals/terminal-contracts'
import type { ProjectExecutionRuntimeResolution } from '../../../../../shared/execution-host/project-execution-runtime'
import { resolveAgentLaunchCommand } from '../../../../../shared/agent-launch/startup/tui-agent-launch-command'
import {
isOrcaCloudPane,
withOrcaCloudSessionEnv
} from '@/lib/orca-cloud/cloud-restart-session-env'
import { resolveStartupShell } from '../../../../../shared/agent-launch/startup/tui-agent-startup-shell'
export type AgentAccountRestartStartup = {
@@ -131,11 +135,22 @@ export function buildPaneAccountRestartStartup(
) {
return null
}
return resume ?? (agent === 'codex' ? buildCodexAccountRestartStartup(args) : null)
// RA-11: on Orca Cloud a Claude pane with no session to resume starts a new conversation.
const fresh = agent === 'codex' || isOrcaCloudPane(args)
const startup = resume ?? (fresh ? buildFreshAccountRestartStartup(agent, args) : null)
// Orca Cloud: refresh the shell's session env first, so a renewed account reaches the agent.
return startup ? withOrcaCloudSessionEnv(startup, args) : null
}
export function buildCodexAccountRestartStartup(
args: AccountRestartTarget
): AgentAccountRestartStartup {
return buildFreshAccountRestartStartup('codex', args)
}
function buildFreshAccountRestartStartup(
agent: AccountRestartAgent,
args: AccountRestartTarget
): AgentAccountRestartStartup {
const state = useAppStore.getState()
const target = resolveAccountRestartLaunchTarget(
@@ -144,7 +159,7 @@ export function buildCodexAccountRestartStartup(
getLocalProjectExecutionRuntimeContext(state, args.worktreeId)
)
const command = resolveAgentLaunchCommand({
agent: 'codex',
agent,
cmdOverrides: state.settings?.agentCmdOverrides ?? {},
platform: target.platform,
agentHostPlatform: target.agentHostPlatform,
@@ -156,7 +171,7 @@ export function buildCodexAccountRestartStartup(
return {
command: command.command,
startupCommandDelivery: 'shell-ready',
launchAgent: 'codex'
launchAgent: agent
}
}
@@ -0,0 +1,113 @@
// RA-11 Restart feedback: "Restarting…" until the relaunched agent reports, "Couldn't restart" when
// nothing relaunched within the timeout. The strip never vanishes without a result.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { resetCloudRunningSignoutForTest } from './cloud-running-agent-signout'
import {
beginCloudAgentRestart,
CLOUD_AGENT_RESTART_TIMEOUT_MS,
cloudAgentRestartAttempt,
dismissCloudAgentRestart,
failCloudAgentRestart,
isForcedCloudAgentRestart,
noteCloudAgentRestartLaunched,
settleCloudAgentRestart,
resetCloudAgentRestartsForTest
} from './cloud-agent-restart-attempt'
const PANE = 'tab:leaf'
const PTY = 'env@@pty-1'
function begin(queue: () => void = () => undefined): void {
beginCloudAgentRestart(PANE, { agent: 'claude', resumable: true, ptyId: PTY }, queue)
}
describe('Restart attempt (RA-11)', () => {
beforeEach(() => {
vi.useFakeTimers()
resetCloudRunningSignoutForTest()
resetCloudAgentRestartsForTest()
})
afterEach(() => {
resetCloudRunningSignoutForTest()
resetCloudAgentRestartsForTest()
vi.useRealTimers()
})
it('shows restarting at once, queues the restart and marks it forced past the mid-turn wait', () => {
const queue = vi.fn()
begin(queue)
expect(queue).toHaveBeenCalledTimes(1)
expect(cloudAgentRestartAttempt(PANE, 0)).toMatchObject({
phase: 'restarting',
launchedAt: null
})
expect(isForcedCloudAgentRestart(PTY)).toBe(true)
})
it('fails when nothing relaunched within the timeout, and Try again restarts it', () => {
begin()
vi.advanceTimersByTime(CLOUD_AGENT_RESTART_TIMEOUT_MS - 1)
expect(cloudAgentRestartAttempt(PANE, 0)?.phase).toBe('restarting')
vi.advanceTimersByTime(1)
expect(cloudAgentRestartAttempt(PANE, 0)?.phase).toBe('failed')
// The queued-but-stuck restart no longer jumps the mid-turn rule.
expect(isForcedCloudAgentRestart(PTY)).toBe(false)
const queue = vi.fn()
begin(queue)
expect(queue).toHaveBeenCalledTimes(1)
expect(cloudAgentRestartAttempt(PANE, 0)?.phase).toBe('restarting')
})
it('fails at once when the pane could not build a startup', () => {
begin()
failCloudAgentRestart(PTY)
expect(cloudAgentRestartAttempt(PANE, 0)?.phase).toBe('failed')
// The timer is gone: a late timeout never flips a later attempt.
begin()
vi.advanceTimersByTime(CLOUD_AGENT_RESTART_TIMEOUT_MS - 1)
expect(cloudAgentRestartAttempt(PANE, 0)?.phase).toBe('restarting')
})
it('fails when queueing throws', () => {
begin(() => {
throw new Error('boom')
})
expect(cloudAgentRestartAttempt(PANE, 0)?.phase).toBe('failed')
})
it('settles only after the relaunch ran; then the strip follows the account', () => {
begin()
expect(settleCloudAgentRestart(PANE)).toBe(false)
noteCloudAgentRestartLaunched(PTY, 5)
expect(cloudAgentRestartAttempt(PANE, 0)).toMatchObject({ phase: 'restarting', launchedAt: 5 })
expect(isForcedCloudAgentRestart(PTY)).toBe(false)
expect(settleCloudAgentRestart(PANE)).toBe(true)
expect(cloudAgentRestartAttempt(PANE, 0)).toBeNull()
vi.advanceTimersByTime(CLOUD_AGENT_RESTART_TIMEOUT_MS)
expect(cloudAgentRestartAttempt(PANE, 0)).toBeNull()
})
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)?.phase).toBe('failed')
})
it('ignores launches and failures of other PTYs', () => {
begin()
noteCloudAgentRestartLaunched('other')
failCloudAgentRestart('other')
expect(cloudAgentRestartAttempt(PANE, 0)).toMatchObject({
phase: 'restarting',
launchedAt: null
})
})
it('dismiss clears a failed attempt', () => {
begin()
failCloudAgentRestart(PTY)
dismissCloudAgentRestart(PANE)
expect(cloudAgentRestartAttempt(PANE, 0)).toBeNull()
})
})
@@ -0,0 +1,165 @@
// RA-11 Restart on the Orca Cloud strip: the attempt the strip shows ("Restarting…", then a result)
// and the mark that lets it run while the signed-out agent reports 'blocked'.
import type { HostAgentSignInAgent } from '../../../../shared/host-agent-sign-in-status'
import { clearCloudRunningSignout, notifyCloudRunningStrips } from './cloud-running-agent-signout'
/**
* RA-11 Restart the person clicked on a signed-out cloud pane. Its Claude reports 'blocked' after the
* failed turn, which the account-restart path otherwise reads as mid-turn and waits on forever.
*/
const forcedRestarts = new Set<string>()
/** Whether a queued restart on this PTY was asked for on the RA-11 strip (and may run now). */
export function isForcedCloudAgentRestart(ptyId: string): boolean {
return forcedRestarts.has(ptyId)
}
/**
* A Restart in flight on a pane: the strip shows "Restarting…" until the relaunched agent reports,
* or "Couldn't restart" when nothing relaunched in time. Never vanishes without a result.
*/
export type CloudAgentRestartAttempt = {
phase: 'restarting' | 'failed'
agent: HostAgentSignInAgent
resumable: boolean
ptyId: string
/** Set when the pane's restart actually ran (a new PTY was asked for). */
launchedAt: number | null
/** Why it failed, when known: the workspace's host did not do what was asked. */
failure?: 'hostUnresponsive'
}
export const CLOUD_AGENT_RESTART_TIMEOUT_MS = 10_000
const restarts = new Map<string, CloudAgentRestartAttempt>()
const restartTimers = new Map<string, ReturnType<typeof setTimeout>>()
function stopRestartTimer(paneKey: string): void {
const timer = restartTimers.get(paneKey)
if (timer !== undefined) {
clearTimeout(timer)
restartTimers.delete(paneKey)
}
}
/** The person clicked Restart (or Try again): queue it through `queue` and track the outcome. */
export function beginCloudAgentRestart(
paneKey: string,
args: { agent: HostAgentSignInAgent; resumable: boolean; ptyId: string },
queue: () => void
): void {
stopRestartTimer(paneKey)
clearCloudRunningSignout(paneKey)
restarts.set(paneKey, {
phase: 'restarting',
agent: args.agent,
resumable: args.resumable,
ptyId: args.ptyId,
launchedAt: null
})
forcedRestarts.add(args.ptyId)
restartTimers.set(
paneKey,
setTimeout(() => {
restartTimers.delete(paneKey)
const attempt = restarts.get(paneKey)
if (attempt?.phase !== 'restarting') {
return
}
forcedRestarts.delete(attempt.ptyId)
// 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)
)
notifyCloudRunningStrips()
try {
queue()
} catch (err) {
console.warn('[orca-cloud] restart could not be queued:', err)
failCloudAgentRestart(args.ptyId)
}
}
function attemptKeyForPty(ptyId: string): string | null {
for (const [paneKey, attempt] of restarts) {
if (attempt.ptyId === ptyId && attempt.phase === 'restarting') {
return paneKey
}
}
return null
}
/** The pane's restart ran (the account-restart path asked for a new PTY in place of `ptyId`). */
export function noteCloudAgentRestartLaunched(ptyId: string, now = Date.now()): void {
forcedRestarts.delete(ptyId)
const paneKey = attemptKeyForPty(ptyId)
const attempt = paneKey ? restarts.get(paneKey) : undefined
if (paneKey && attempt) {
restarts.set(paneKey, { ...attempt, launchedAt: now })
notifyCloudRunningStrips()
}
}
/** The pane's restart could not run (no startup to launch, or it threw). */
export function failCloudAgentRestart(
ptyId: string,
failure?: CloudAgentRestartAttempt['failure']
): void {
forcedRestarts.delete(ptyId)
const paneKey = attemptKeyForPty(ptyId)
const attempt = paneKey ? restarts.get(paneKey) : undefined
if (paneKey && attempt) {
stopRestartTimer(paneKey)
restarts.set(paneKey, { ...attempt, phase: 'failed', ...(failure ? { failure } : {}) })
notifyCloudRunningStrips()
}
}
/**
* The pane's attempt, if any. `revision` (useCloudRunningSignoutVersion) is an input so the React
* Compiler re-reads it when this module's memory changes.
*/
export function cloudAgentRestartAttempt(
paneKey: string,
_revision: number
): CloudAgentRestartAttempt | null {
return restarts.get(paneKey) ?? null
}
/**
* 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 {
const attempt = restarts.get(paneKey)
if (attempt?.phase !== 'restarting' || attempt.launchedAt === null) {
return false
}
stopRestartTimer(paneKey)
restarts.delete(paneKey)
notifyCloudRunningStrips()
return true
}
/** The person closed the "Couldn't restart" strip. */
export function dismissCloudAgentRestart(paneKey: string): void {
stopRestartTimer(paneKey)
const attempt = restarts.get(paneKey)
if (attempt) {
forcedRestarts.delete(attempt.ptyId)
restarts.delete(paneKey)
}
clearCloudRunningSignout(paneKey)
notifyCloudRunningStrips()
}
/** Tests only. */
export function resetCloudAgentRestartsForTest(): void {
forcedRestarts.clear()
for (const timer of restartTimers.values()) {
clearTimeout(timer)
}
restartTimers.clear()
restarts.clear()
}
@@ -0,0 +1,101 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const toastError = vi.fn()
vi.mock('sonner', () => ({ toast: { error: (...args: unknown[]) => toastError(...args) } }))
const activate = vi.fn()
vi.mock('@/lib/workspace/activation/worktree-activation', () => ({
activateAndRevealWorktree: (id: string) => activate(id)
}))
const { useAppStore } = await import('@/store')
const { makePaneKey } = await import('../../../../shared/workspace-layout/stable-pane-id')
const attempts = await import('./cloud-agent-restart-attempt')
const { restartPaneExists, watchCloudAgentRestartPane } =
await import('./cloud-agent-restart-pane-watch')
const TAB = 'tab-1'
const LEAF = '11111111-1111-4111-8111-111111111111'
const PANE = makePaneKey(TAB, LEAF)
const PTY = 'remote:env-1@@term_a'
function seed(): void {
useAppStore.setState({
tabsByWorktree: {
'wt-1': [
{
id: TAB,
ptyId: PTY,
worktreeId: 'wt-1',
title: 'claude',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
terminalLayoutsByTabId: {
[TAB]: {
root: { type: 'leaf', leafId: LEAF },
activeLeafId: LEAF,
expandedLeafId: null,
ptyIdsByLeafId: { [LEAF]: PTY }
}
}
})
}
describe('RA-11 Restart when its pane goes away', () => {
beforeEach(() => {
vi.useFakeTimers()
toastError.mockClear()
activate.mockClear()
attempts.resetCloudAgentRestartsForTest()
seed()
attempts.beginCloudAgentRestart(
PANE,
{ agent: 'claude', resumable: true, ptyId: PTY },
() => undefined
)
})
afterEach(() => {
attempts.resetCloudAgentRestartsForTest()
vi.useRealTimers()
})
it('a restart rebinding the leaf’s PTY keeps the pane: same tab, same leaf, no toast', () => {
watchCloudAgentRestartPane(PANE, 'wt-1', 'claude')
useAppStore.setState({
terminalLayoutsByTabId: {
[TAB]: {
root: { type: 'leaf', leafId: LEAF },
activeLeafId: LEAF,
expandedLeafId: null,
ptyIdsByLeafId: {}
}
}
})
expect(restartPaneExists(useAppStore.getState(), PANE)).toBe(true)
expect(toastError).not.toHaveBeenCalled()
expect(attempts.cloudAgentRestartAttempt(PANE, 0)?.phase).toBe('restarting')
})
it('the tab closing mid-restart ends the attempt with a toast naming the workspace', () => {
watchCloudAgentRestartPane(PANE, 'wt-1', 'claude')
useAppStore.setState({ tabsByWorktree: { 'wt-1': [] }, terminalLayoutsByTabId: {} })
expect(attempts.cloudAgentRestartAttempt(PANE, 0)).toBeNull()
expect(toastError).toHaveBeenCalledTimes(1)
const [title, options] = toastError.mock.calls[0]
expect(title).toBe('Couldn’t restart Claude in wt-1.')
options.action.onClick()
expect(activate).toHaveBeenCalledWith('wt-1')
})
it('stops watching once the attempt settled', () => {
const stop = watchCloudAgentRestartPane(PANE, 'wt-1', 'claude')
attempts.dismissCloudAgentRestart(PANE)
useAppStore.setState({ tabsByWorktree: { 'wt-1': [] } })
expect(toastError).not.toHaveBeenCalled()
stop()
})
})
@@ -0,0 +1,74 @@
// RA-11: a Restart must never vanish without a result. If its pane goes away while the restart runs
// (or after it failed), the strip has nowhere to show; say so in a toast that names the workspace.
import { toast } from 'sonner'
import { translate } from '@/i18n/i18n'
import { useAppStore } from '@/store'
import type { AppState } from '@/store/types'
import { activateAndRevealWorktree } from '@/lib/workspace/activation/worktree-activation'
import { resolveWorktreeDisplayName } from '@/lib/worktree-default-display-name'
import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id'
import type { TerminalPaneLayoutNode } from '../../../../shared/workspace-layout/terminal-tab-types'
import {
HOST_AGENT_SIGN_IN_AGENT_NAME,
type HostAgentSignInAgent
} from '../../../../shared/host-agent-sign-in-status'
import { cloudAgentRestartAttempt, dismissCloudAgentRestart } from './cloud-agent-restart-attempt'
function hasLeaf(node: TerminalPaneLayoutNode | null | undefined, leafId: string): boolean {
if (!node) {
return false
}
return node.type === 'leaf'
? node.leafId === leafId
: hasLeaf(node.first, leafId) || hasLeaf(node.second, leafId)
}
/** Whether the pane (its tab and its leaf) still exists. A restart only rebinds the leaf's PTY. */
export function restartPaneExists(state: AppState, paneKey: string): boolean {
const parsed = parsePaneKey(paneKey)
if (!parsed) {
return false
}
const tabExists = Object.values(state.tabsByWorktree).some((tabs) =>
tabs.some((tab) => tab.id === parsed.tabId)
)
return tabExists && hasLeaf(state.terminalLayoutsByTabId[parsed.tabId]?.root, parsed.leafId)
}
/** Watch the pane for the attempt's life; returns the unsubscribe. */
export function watchCloudAgentRestartPane(
paneKey: string,
worktreeId: string,
agent: HostAgentSignInAgent
): () => void {
const unsubscribe = useAppStore.subscribe((state) => {
if (!cloudAgentRestartAttempt(paneKey, 0)) {
unsubscribe()
return
}
if (restartPaneExists(state, paneKey)) {
return
}
unsubscribe()
dismissCloudAgentRestart(paneKey)
const worktree = state.getKnownWorktreeById(worktreeId)
const workspace = worktree ? resolveWorktreeDisplayName(worktree) : worktreeId
toast.error(
translate(
'agentSignInStrip.restartFailedIn',
'Couldn’t restart {{agent}} in {{workspace}}.',
{
agent: HOST_AGENT_SIGN_IN_AGENT_NAME[agent],
workspace
}
),
{
action: {
label: translate('agentSignInStrip.openWorkspace', 'Open workspace'),
onClick: () => activateAndRevealWorktree(worktreeId)
}
}
)
})
return unsubscribe
}
@@ -0,0 +1,83 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const calls: { method: string; params: unknown; environmentId: string }[] = []
let showPtyId: string | null = 'host-pty-7'
let stopResult: Record<string, unknown> = {}
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({
callRuntimeRpc: async (target: { environmentId: string }, method: string, params: unknown) => {
calls.push({ method, params, environmentId: target.environmentId })
return method === 'terminal.show' ? { terminal: { ptyId: showPtyId } } : stopResult
}
}))
vi.mock(
'@/runtime/hosted-terminals/creation/agent-launch/agent-session-ensure-provider-session',
() => ({ agentProviderSessionForHostEnsure: async (_env: string, session: unknown) => session })
)
const { resumeRemotePaneAgent, stopRemotePaneTerminalForRestart } =
await import('./cloud-pane-restart-stop')
describe('stopRemotePaneTerminalForRestart (RA-11 paired pane)', () => {
beforeEach(() => {
calls.length = 0
showPtyId = 'host-pty-7'
stopResult = { stoppedPtyIds: ['host-pty-7'], postStopVerified: true }
})
it('puts exactly that one host terminal to sleep (reversible, target only), never a close', async () => {
await stopRemotePaneTerminalForRestart('remote:env-1@@term_a', 'wt-1')
expect(calls.map((c) => c.method)).toEqual(['terminal.show', 'terminal.stopExact'])
expect(calls[0]).toMatchObject({ environmentId: 'env-1', params: { terminal: 'term_a' } })
expect(calls[1]).toMatchObject({
environmentId: 'env-1',
params: { expectedPtyIds: ['host-pty-7'], keepHistory: true, targetOnly: true }
})
})
it('throws when the host has no live terminal for the pane, or does not confirm the stop', async () => {
showPtyId = null
await expect(stopRemotePaneTerminalForRestart('remote:env-1@@term_a', 'wt-1')).rejects.toThrow(
'restart_remote_pane_not_live'
)
showPtyId = 'host-pty-7'
stopResult = { stoppedPtyIds: ['host-pty-7'], postStopVerified: false }
await expect(stopRemotePaneTerminalForRestart('remote:env-1@@term_a', 'wt-1')).rejects.toThrow()
})
it('refuses a pane id without an owning environment', async () => {
await expect(stopRemotePaneTerminalForRestart('remote:term_a', 'wt-1')).rejects.toThrow(
'restart_remote_pane_unowned'
)
expect(calls).toEqual([])
})
})
describe('resumeRemotePaneAgent (RA-11 paired pane)', () => {
beforeEach(() => {
calls.length = 0
})
it('ensures the agent on its own session, placed in the same host tab and leaf', async () => {
await resumeRemotePaneAgent({
ptyId: 'remote:env-1@@term_a',
worktreeId: 'wt-1',
tabId: 'web-terminal-host-tab%3A%3Aleaf',
leafId: 'leaf-1',
agent: 'claude',
providerSession: { key: 'session_id', id: 'sess-1' }
})
expect(calls).toHaveLength(1)
expect(calls[0]).toMatchObject({
method: 'terminal.ensureAgentSession',
environmentId: 'env-1',
params: {
kind: 'explicit',
agent: 'claude',
providerSession: { key: 'session_id', id: 'sess-1' },
placement: { tabId: 'host-tab::leaf', leafId: 'leaf-1' }
}
})
})
})
@@ -0,0 +1,91 @@
// 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. Put exactly that one host terminal to sleep first (the reversible stop the pane-sleep
// path uses: the leaf stays, as a sleeping surface); the reconnect then wakes it with --resume.
// A plain stop is a close: the host drops the tab and there is nothing left to relaunch into.
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'
import { agentProviderSessionForHostEnsure } from '@/runtime/hosted-terminals/creation/agent-launch/agent-session-ensure-provider-session'
import { toHostSessionTabId } from '../../../../shared/workspace-layout/terminal-surface-id'
import type { AgentProviderSessionMetadata } from '../../../../shared/agent-session/lifecycle/agent-session-resume'
import type { AccountRestartAgent } from '@/store/terminals/terminal-contracts'
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],
// Reversible: the host keeps the pane (and its scrollback) for the wake.
keepHistory: true,
// 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')
}
}
/**
* Relaunch the pane's agent on its own conversation, in the same pane. Without this the host wakes
* the sleeping pane with its original launch (a new conversation). Only for a resumable session;
* a pane with none takes the host's fresh launch, which is what "Starts a new conversation" says.
*/
export async function resumeRemotePaneAgent(args: {
ptyId: string
worktreeId: string
tabId: string
leafId: string
agent: AccountRestartAgent
providerSession: AgentProviderSessionMetadata
}): Promise<void> {
const environmentId = parseRemoteRuntimePtyId(args.ptyId)?.environmentId
if (!environmentId) {
throw new Error('restart_remote_pane_unowned')
}
await callRuntimeRpc(
{ kind: 'environment', environmentId },
'terminal.ensureAgentSession',
{
kind: 'explicit',
worktree: toRuntimeWorktreeSelector(args.worktreeId),
agent: args.agent,
providerSession: await agentProviderSessionForHostEnsure(environmentId, args.providerSession),
// The same pane: the host tab and leaf the stopped terminal lived in.
placement: { tabId: toHostSessionTabId(args.tabId), leafId: args.leafId },
presentation: 'background'
},
{ timeoutMs: 15_000 }
)
}
@@ -0,0 +1,38 @@
import { describe, expect, it, vi } from 'vitest'
const state = vi.hoisted((): { cloud: boolean; ptyId: string | null } => ({
cloud: true,
ptyId: 'remote:env-1@@term_1'
}))
vi.mock('@/store', () => ({
useAppStore: {
getState: () => ({
terminalLayoutsByTabId: { t1: { ptyIdsByLeafId: { l1: state.ptyId } } }
})
}
}))
vi.mock('./orca-cloud-environment-id', () => ({ isOrcaCloudEnvironmentId: () => state.cloud }))
const { withOrcaCloudSessionEnv, ORCA_CLOUD_SESSION_ENV_REFRESH } =
await import('./cloud-restart-session-env')
const PANE = { tabId: 't1', leafId: 'l1' }
describe('withOrcaCloudSessionEnv (RA-11 restart)', () => {
it('refreshes the cloud shell’s session env before the relaunch, once', () => {
const out = withOrcaCloudSessionEnv({ command: "claude '--resume' 's1'", x: 1 }, PANE)
expect(out).toEqual({
command: `${ORCA_CLOUD_SESSION_ENV_REFRESH}claude '--resume' 's1'`,
x: 1
})
expect(withOrcaCloudSessionEnv(out, PANE)).toBe(out)
})
it('leaves other hosts and local panes alone', () => {
state.cloud = false
const startup = { command: 'claude' }
expect(withOrcaCloudSessionEnv(startup, PANE)).toBe(startup)
state.cloud = true
state.ptyId = null
expect(withOrcaCloudSessionEnv(startup, PANE)).toBe(startup)
})
})
@@ -0,0 +1,30 @@
// RA-11: an account restart types its launch command into the pane's existing shell, whose env was
// captured before the account was stored or renewed. On an Orca Cloud VM the image's `orca-env`
// prints the current session env (placeholders, never real values), so the relaunched agent picks
// up the renewed account. Other hosts: unchanged.
import { useAppStore } from '@/store'
import { parseRemoteRuntimePtyId } from '../../../../shared/remote-runtime/remote-runtime-pty-id'
import { isOrcaCloudEnvironmentId } from './orca-cloud-environment-id'
/** The prefix that refreshes a cloud shell's session env before the command; quiet off-cloud. */
export const ORCA_CLOUD_SESSION_ENV_REFRESH = 'eval "$(orca-env 2>/dev/null)"; '
/** True when this pane's terminal runs on an Orca Cloud sandbox. */
export function isOrcaCloudPane(pane: { tabId: string; leafId: string }): boolean {
const ptyId =
useAppStore.getState().terminalLayoutsByTabId[pane.tabId]?.ptyIdsByLeafId?.[pane.leafId] ?? null
const environmentId = ptyId ? parseRemoteRuntimePtyId(ptyId)?.environmentId : null
return Boolean(environmentId && isOrcaCloudEnvironmentId(environmentId))
}
export function withOrcaCloudSessionEnv<T extends { command: string }>(
startup: T,
pane: { tabId: string; leafId: string }
): T {
if (!isOrcaCloudPane(pane)) {
return startup
}
return startup.command.startsWith(ORCA_CLOUD_SESSION_ENV_REFRESH)
? startup
: { ...startup, command: `${ORCA_CLOUD_SESSION_ENV_REFRESH}${startup.command}` }
}
@@ -0,0 +1,159 @@
import { beforeEach, describe, expect, it } from 'vitest'
import type { OrcaCloudAgentsStatus } from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire'
import type { OrcaCloudAgentAccountsState } from './orca-cloud-agent-accounts-store'
import {
clearCloudRunningSignout,
cloudRunningStrip,
resetCloudRunningSignoutForTest,
workspaceUsesAccount
} from './cloud-running-agent-signout'
function accounts(
claude: OrcaCloudAgentsStatus['credentials']['claude'],
extra: Partial<OrcaCloudAgentsStatus['credentials']> = {}
): Pick<OrcaCloudAgentAccountsState, 'load' | 'keyKinds'> {
return {
load: {
kind: 'ready',
status: {
credentials: {
claude,
codex: { state: 'none' },
providerEnabled: { claude: true, codex: true },
...extra
},
sources: { defaults: {}, coveredByKey: { claude: false, codex: false } }
}
},
keyKinds: { claude: null, codex: null }
}
}
const RUNNING = { agentType: 'claude', state: 'working' as const, providerSession: { id: 's1' } }
const strip = (
account: ReturnType<typeof accounts>,
entry: Parameters<typeof cloudRunningStrip>[0]['entry'] = RUNNING,
now = 1_000,
paneKey = 'tab:a',
usesAccount: boolean | null = true
) =>
cloudRunningStrip({
paneKey,
entry,
accounts: account,
held: false,
now,
usesAccount,
revision: 0
})
describe('cloudRunningStrip (RA-11)', () => {
beforeEach(resetCloudRunningSignoutForTest)
it('shows nothing while the account works, and state 1 once it expires or is revoked', () => {
expect(strip(accounts({ state: 'active' }))).toBeNull()
expect(strip(accounts({ state: 'revoked' }))).toEqual({ phase: 'expired', agent: 'claude' })
expect(strip(accounts({ state: 'expired' }), RUNNING, 1_000, 'tab:b')).toEqual({
phase: 'expired',
agent: 'claude'
})
})
it('after Renew the panes that showed state 1 move to state 2, resumable when the pane has a session', () => {
strip(accounts({ state: 'revoked' }))
expect(strip(accounts({ state: 'active' }))).toEqual({
phase: 'renewed',
agent: 'claude',
resumable: true
})
// A pane that never showed state 1 gets nothing.
expect(strip(accounts({ state: 'active' }), RUNNING, 1_000, 'tab:other')).toBeNull()
strip(
accounts({ state: 'revoked' }),
{ ...RUNNING, providerSession: undefined },
1_000,
'tab:c'
)
expect(
strip(
accounts({ state: 'active' }),
{ ...RUNNING, providerSession: undefined },
1_000,
'tab:c'
)
).toMatchObject({ phase: 'renewed', resumable: false })
})
it('never auto-restarts: state 2 stays until Restart or dismiss; a clean turn after renewal clears it', () => {
strip(accounts({ state: 'revoked' }))
expect(strip(accounts({ state: 'active' }), RUNNING, 2_000)?.phase).toBe('renewed')
expect(strip(accounts({ state: 'active' }), RUNNING, 9_000)?.phase).toBe('renewed')
// The agent's next call succeeded through egress: its turn ended cleanly after the renewal.
const recovered = { ...RUNNING, state: 'done' as const, turnEndedAt: 3_000 }
expect(strip(accounts({ state: 'active' }), recovered, 9_000)).toBeNull()
strip(accounts({ state: 'revoked' }), RUNNING, 1_000, 'tab:d')
strip(accounts({ state: 'active' }), RUNNING, 2_000, 'tab:d')
clearCloudRunningSignout('tab:d')
expect(strip(accounts({ state: 'active' }), RUNNING, 3_000, 'tab:d')).toBeNull()
})
it('shows nothing new under the kill switch, for a held launch, or without a running account agent', () => {
expect(
strip(
accounts(
{ state: 'revoked' },
{
providerEnabled: { claude: false, codex: true },
providerState: { claude: 'disabled', codex: 'on' }
}
)
)
).toBeNull()
expect(
cloudRunningStrip({
paneKey: 'tab:e',
entry: RUNNING,
accounts: accounts({ state: 'revoked' }),
held: true,
now: 1,
usesAccount: true,
revision: 0
})
).toBeNull()
expect(strip(accounts({ state: 'revoked' }), { ...RUNNING, agentType: 'gemini' })).toBeNull()
expect(strip(accounts({ state: 'revoked' }), null)).toBeNull()
})
})
describe('D13: only workspaces that run the agent on the person’s own account', () => {
beforeEach(resetCloudRunningSignoutForTest)
const view = (extra: Record<string, unknown> = {}) => ({
defaults: {},
coveredByKey: { claude: false, codex: false },
...extra
})
it('reads the workspace Source: shared and key-sourced workspaces never use the account', () => {
expect(workspaceUsesAccount(view({ sharedWorkspace: true }), 'claude')).toBe(false)
expect(workspaceUsesAccount(view({ effective: { claude: { source: 'key' } } }), 'claude')).toBe(
false
)
expect(workspaceUsesAccount(view({ defaults: { claude: 'key' } }), 'claude')).toBe(false)
// Nothing chosen and a key covers the agent: the key wins.
expect(
workspaceUsesAccount(view({ coveredByKey: { claude: true, codex: false } }), 'claude')
).toBe(false)
expect(
workspaceUsesAccount(view({ effective: { claude: { source: 'sign-in' } } }), 'claude')
).toBe(true)
expect(workspaceUsesAccount(view(), 'claude')).toBe(true)
})
it('shows no strip for a shared or keyed workspace, nor while the Source is unread (fail quiet)', () => {
expect(strip(accounts({ state: 'revoked' }), RUNNING, 1_000, 'tab:s', false)).toBeNull()
expect(strip(accounts({ state: 'revoked' }), RUNNING, 1_000, 'tab:u', null)).toBeNull()
expect(strip(accounts({ state: 'revoked' }), RUNNING, 1_000, 'tab:y', true)?.phase).toBe(
'expired'
)
})
})
@@ -0,0 +1,252 @@
// RA-11: an Orca Cloud pane whose agent is already running when its Orca-account sign-in expires or
// is revoked. State 1 ("expired") shows on every such pane; one Renew (S0) clears it everywhere and
// the panes that showed it move to state 2 ("renewed": Restart, never automatic) until restarted,
// dismissed, or the agent's next turn ends cleanly on its own. Decided from the Orca account (the
// same read the build sheet uses), never from terminal output.
import { useEffect, useSyncExternalStore } from 'react'
import type { HostAgentSignInAgent } from '../../../../shared/host-agent-sign-in-status'
import type { AgentSourcesView } from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire'
import { agentTurnEndedUncleanly } from '../../../../shared/agent-status/lifecycle/agent-main-agent-verdict'
import type { AgentStatusEntry } from '../../../../shared/agent-status/contracts/agent-status-types'
import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval'
import { orcaCloudAgentCoverage } from './orca-cloud-agent-accounts-model'
import {
ensureFreshOrcaCloudAgentAccounts,
type OrcaCloudAgentAccountsState
} from './orca-cloud-agent-accounts-store'
export type CloudRunningStrip =
| { phase: 'expired'; agent: HostAgentSignInAgent }
| { phase: 'renewed'; agent: HostAgentSignInAgent; resumable: boolean }
/** Panes that showed state 1, and when their account came back (state 2). */
const signedOut = new Map<string, { agent: HostAgentSignInAgent; renewedAt: number | null }>()
const listeners = new Set<() => void>()
let version = 0
/** Re-render the strips: this module's or the restart attempt's memory changed. */
export function notifyCloudRunningStrips(): void {
notify()
}
function notify(): void {
version += 1
for (const listener of listeners) {
listener()
}
}
function subscribe(listener: () => void): () => void {
listeners.add(listener)
return () => listeners.delete(listener)
}
/** Re-renders when a pane's remembered state changes (dismiss, restart). */
export function useCloudRunningSignoutVersion(): number {
return useSyncExternalStore(
subscribe,
() => version,
() => version
)
}
/** Forget a pane: dismissed, restarted, or its agent went away. */
export function clearCloudRunningSignout(paneKey: string): void {
if (signedOut.delete(paneKey)) {
notify()
}
}
function isAccountAgent(agent: unknown): agent is HostAgentSignInAgent {
return agent === 'claude' || agent === 'codex'
}
/**
* What a running Orca Cloud pane shows, or null. `entry` is the pane's agent status (the agent is
* running); `held` is true while #315's launch hold or the per-workspace gate owns the pane.
*/
export function cloudRunningStrip(args: {
paneKey: string
entry:
| (Pick<
AgentStatusEntry,
'agentType' | 'state' | 'turnEndedAt' | 'mainAgent' | 'interrupted'
> & {
providerSession?: unknown
})
| null
accounts: Pick<OrcaCloudAgentAccountsState, 'load' | 'keyKinds'>
held: boolean
now: number
/**
* D13: does this pane's workspace run the agent on the person's own account? false for a shared
* workspace or a key-sourced one, null while unread or unreadable (then no strip: fail quiet).
*/
usesAccount: boolean | null
/**
* useCloudRunningSignoutVersion(): passed in so a dismiss or restart (which only changes this
* module's memory) re-decides; the React Compiler memoizes this call on its inputs.
*/
revision: number
}): CloudRunningStrip | null {
const { paneKey, entry, accounts } = args
const remembered = signedOut.get(paneKey)
const agent = entry?.agentType
if (args.held || !isAccountAgent(agent) || accounts.load.kind !== 'ready') {
return null
}
const coverage = orcaCloudAgentCoverage(agent, accounts.load.status, accounts.keyKinds[agent])
switch (coverage.kind) {
case 'expired':
if (args.usesAccount !== true) {
return null
}
if (!remembered || remembered.renewedAt !== null) {
signedOut.set(paneKey, { agent, renewedAt: null })
}
return { phase: 'expired', agent }
case 'account':
case 'key': {
if (!remembered) {
return null
}
const renewedAt = remembered.renewedAt ?? args.now
if (remembered.renewedAt === null) {
signedOut.set(paneKey, { agent, renewedAt })
}
// Recovered on its own: a turn that ended cleanly after the renewal needs no restart.
if (
entry &&
entry.state === 'done' &&
(entry.turnEndedAt ?? 0) > renewedAt &&
!agentTurnEndedUncleanly(entry)
) {
signedOut.delete(paneKey)
return null
}
return { phase: 'renewed', agent, resumable: Boolean(entry?.providerSession) }
}
// Kill switch, never offered, not set up: nothing new on a running pane.
case 'killSwitch':
case 'unavailable':
case 'notSetUp':
return null
}
}
let liveReaders = 0
let stopInterval: (() => void) | null = null
const LIVE_READ_MS = 60_000
function readNow(): void {
void ensureFreshOrcaCloudAgentAccounts().catch(() => undefined)
}
/**
* While any running Orca Cloud agent pane is mounted, keep the account read fresh: on window focus
* and at most once a minute while the window is visible (the read itself is cached for 30 s). The
* desktop gets no push for a revoke, so this read is how the strip learns. One timer per window.
*/
export function useCloudRunningAccountReads(active: boolean): void {
useEffect(() => {
if (!active) {
return
}
liveReaders += 1
if (liveReaders === 1) {
window.addEventListener('focus', readNow)
stopInterval = installWindowVisibilityInterval({
run: readNow,
intervalMs: LIVE_READ_MS,
slowWhileUnfocused: true
})
readNow()
}
return () => {
liveReaders -= 1
if (liveReaders === 0) {
window.removeEventListener('focus', readNow)
stopInterval?.()
stopInterval = null
}
}
}, [active])
}
type SourceRead = { usesAccount: boolean | null; at: number } | 'pending'
const sourceReads = new Map<string, SourceRead>()
const SOURCE_READ_MS = 10 * 60_000
/** Pure: whether a workspace's Sources view runs the agent on the person's own account (D13). */
export function workspaceUsesAccount(view: AgentSourcesView, agent: HostAgentSignInAgent): boolean {
if (view.sharedWorkspace === true) {
return false
}
const source = view.effective?.[agent]?.source ?? view.defaults[agent] ?? null
if (source !== null) {
return source === 'sign-in'
}
// Nothing chosen: a key that covers the agent wins, otherwise the account is the source.
return !view.coveredByKey[agent]
}
/**
* The pane's workspace Source for the agent, read once per workspace (cached 10 min) and only while
* `wanted` (the account just went expired). Never polled; a failed read stays null (no strip).
*/
export function useWorkspaceUsesAccount(
runtimeEnvironmentId: string | null,
agent: HostAgentSignInAgent | null,
wanted: boolean,
/** Changes on every account read; a failed Source read retries then (never on its own). */
retryToken: number
): boolean | null {
const key = runtimeEnvironmentId && agent ? `${runtimeEnvironmentId}:${agent}` : null
// Through the store snapshot, never a plain map read: the React Compiler would memoize that read
// on `key` and keep the first (unread) answer for good.
const usesAccount = useSyncExternalStore(
subscribe,
() => readUsesAccount(key),
() => null
)
useEffect(() => {
if (!wanted || !key || !runtimeEnvironmentId || !agent) {
return
}
const read = sourceReads.get(key)
// A good answer holds for 10 min; a failed one (e.g. right after start, before main knows the
// sandbox) is retried on the next account read.
if (
read === 'pending' ||
(read && read.usesAccount !== null && Date.now() - read.at < SOURCE_READ_MS)
) {
return
}
const api = window.api.orcaCloudAgents
if (!api) {
return
}
sourceReads.set(key, 'pending')
const settle = (usesAccount: boolean | null): void => {
sourceReads.set(key, { usesAccount, at: Date.now() })
notify()
}
void api
.workspaceSources({ runtimeEnvironmentId })
.then((result) => settle(result.ok ? workspaceUsesAccount(result.value, agent) : null))
.catch(() => settle(null))
}, [wanted, key, runtimeEnvironmentId, agent, retryToken])
return usesAccount
}
function readUsesAccount(key: string | null): boolean | null {
const read = key ? sourceReads.get(key) : undefined
return read && read !== 'pending' ? read.usesAccount : null
}
/** Tests only. */
export function resetCloudRunningSignoutForTest(): void {
signedOut.clear()
sourceReads.clear()
notify()
}
@@ -186,6 +186,11 @@ export function subscribeOrcaCloudAgentAccounts(listener: () => void): () => voi
}
/** Reads again when the last read is stale or missing, for a launch about to decide. */
/** When the current account view was read (ms); 0 before the first read. */
export function orcaCloudAgentAccountsLoadedAt(): number {
return loadedAt
}
/** A ready read from within the last 30 s; older reads may miss a revoke (RA-1). */
export function isOrcaCloudAgentAccountsFresh(): boolean {
return state.load.kind === 'ready' && Date.now() - loadedAt <= FRESH_MS
@@ -33,7 +33,7 @@ async function boxes(page: Page, id: string) {
strip: await box('[data-cloud-sign-in-strip]'),
text: await box('[data-strip-text]'),
actions: await box('[data-strip-actions]'),
terminalTop: (await box('pre')).y
terminalTop: (await box('.xterm-container')).y
}
}
@@ -69,10 +69,12 @@ test('narrowing the pane after mount re-lays the strip out; the title stays read
}
}, width)
await expect(strip).toHaveAttribute('data-strip-width', layout)
const titleBox = await strip.getByText(title, { exact: true }).boundingBox()
// Readable: at least ~10 characters wide, never collapsed to one letter.
await page.screenshot({ path: `/tmp/vdrv/strip-${width}.png` })
expect(titleBox?.width ?? 0, `${width}px`).toBeGreaterThan(70)
const titleLine = strip.locator('[data-strip-text] > span').first()
await expect(titleLine).toHaveText(title)
// Readable: at least ~10 characters wide, never collapsed to one letter (once laid out).
await expect
.poll(async () => (await titleLine.boundingBox())?.width ?? 0, { message: `${width}px` })
.toBeGreaterThan(70)
expect((await strip.boundingBox())?.height).toBe(56)
await expect(strip.getByRole('button', { name: 'Renew' })).toBeVisible()
}
@@ -97,3 +99,72 @@ test('the pane’s split and close buttons stay hit-testable above the strip', a
}
}
})
// RA-11 + #315 P2: the strip reserves its height; the terminal refits below it, so no row (and not
// the last one) ever sits under the strip, held launch or running agent alike.
test('the terminal starts below the strip and its last row stays visible', async ({ page }) => {
for (const id of [
'needExpired',
'runningExpired',
'runningRenewed',
'runningExpiredCompact',
'runningRestarting',
'runningRestartFailed'
]) {
await page.goto(`/fixtures.html?id=agent-sign-in-strip/CloudAgentSignInStrip:${id}`)
await expect(page.locator('html')).toHaveAttribute('data-fixture-state', 'ready')
const strip = await page.locator('[data-cloud-sign-in-strip]').boundingBox()
const terminal = await page.locator('.xterm-container').boundingBox()
const lastRow = await page.locator('[data-terminal-last-row]').boundingBox()
const pane = await page.locator('[data-strip-pane]').boundingBox()
if (!strip || !terminal || !lastRow || !pane) {
throw new Error(`missing bounds in ${id}`)
}
expect(terminal.y, id).toBeGreaterThanOrEqual(strip.y + strip.height)
expect(lastRow.y, id).toBeGreaterThanOrEqual(strip.y + strip.height)
expect(lastRow.y + lastRow.height, id).toBeLessThanOrEqual(pane.y + pane.height)
}
})
test('RA-11: state 1 offers Renew only; state 2 offers Restart and a dismiss clear of the pane buttons', async ({
page
}) => {
await page.goto('/fixtures.html?id=agent-sign-in-strip/CloudAgentSignInStrip:runningExpired')
await expect(page.locator('html')).toHaveAttribute('data-fixture-state', 'ready')
const strip = page.locator('[data-cloud-sign-in-strip]')
await expect(strip).toContainText('Renew to keep working. Your conversation is kept.')
await expect(strip.getByRole('button')).toHaveCount(1)
await page.goto('/fixtures.html?id=agent-sign-in-strip/CloudAgentSignInStrip:runningRenewed')
await expect(page.locator('html')).toHaveAttribute('data-fixture-state', 'ready')
await expect(strip).toContainText('Restart Claude to pick up where you left off.')
await expect(strip.getByRole('button', { name: 'Restart Claude' })).toBeVisible()
const dismiss = await strip.getByRole('button', { name: 'Dismiss' }).boundingBox()
const close = await page.getByRole('button', { name: 'Close pane', exact: true }).boundingBox()
if (!dismiss || !close) {
throw new Error('missing bounds')
}
// Not stacked next to the pane's ×: the strip sits a whole title row lower.
expect(dismiss.y).toBeGreaterThanOrEqual(close.y + close.height)
})
test('RA-11 Restart: "Restarting Claude…" is the spinner and words only; a failure offers Try again once', async ({
page
}) => {
await page.goto('/fixtures.html?id=agent-sign-in-strip/CloudAgentSignInStrip:runningRestarting')
await expect(page.locator('html')).toHaveAttribute('data-fixture-state', 'ready')
const strip = page.locator('[data-cloud-sign-in-strip]')
await expect(strip).toContainText('Restarting Claude…')
await expect(strip).toContainText('Picking up where you left off.')
// Nothing to click twice, nothing to close: the strip leaves with a result.
await expect(strip.getByRole('button')).toHaveCount(0)
await page.goto(
'/fixtures.html?id=agent-sign-in-strip/CloudAgentSignInStrip:runningRestartFailed'
)
await expect(page.locator('html')).toHaveAttribute('data-fixture-state', 'ready')
await expect(strip).toContainText('Couldn’t restart Claude')
// The visible body is the reason, never a second "Try again." (the polite region may repeat it).
const body = strip.locator('[data-strip-text] > span').nth(1)
await expect(body).toHaveText('The workspace didn’t respond.')
await expect(strip.getByRole('button', { name: 'Try again' })).toBeEnabled()
await expect(strip.getByRole('button', { name: 'Dismiss' })).toBeVisible()
})