From 5b3f73376969ab73fbc98bd92a8339ccc790c3e4 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 15:25:59 -0800 Subject: [PATCH 001/149] fix(cloud): sidebar agent row shows Not signed in instead of Done for an unsigned cloud agent A cloud Claude/Codex that starts without a sign-in reports SessionStart (done, sessionBoundary) and then sits at its own login screen, so the compact row read "Done - Claude". For an Orca Cloud workspace row that has not finished a turn, the row now reads the sandbox's sign-in report and the Orca account's Agent accounts coverage and shows "Not signed in" or "Sign-in expired" with the attention dot. Local, SSH and paired hosts are unchanged. --- .../orca-cloud/use-cloud-agent-row-sign-in.ts | 82 ++++++++ ...d-compact-agent-row.cloud-sign-in.test.tsx | 178 ++++++++++++++++++ .../worktree-card-compact-agent-row.tsx | 11 +- src/renderer/src/i18n/locales/en.json | 2 + .../lib/orca-cloud/cloud-agent-row-sign-in.ts | 65 +++++++ 5 files changed, 336 insertions(+), 2 deletions(-) create mode 100644 src/renderer/src/components/orca-cloud/use-cloud-agent-row-sign-in.ts create mode 100644 src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx create mode 100644 src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts diff --git a/src/renderer/src/components/orca-cloud/use-cloud-agent-row-sign-in.ts b/src/renderer/src/components/orca-cloud/use-cloud-agent-row-sign-in.ts new file mode 100644 index 00000000000..446f8cb5415 --- /dev/null +++ b/src/renderer/src/components/orca-cloud/use-cloud-agent-row-sign-in.ts @@ -0,0 +1,82 @@ +import { useEffect, useSyncExternalStore } from 'react' +import { useAppStore } from '@/store' +import type { AppState } from '@/store/types' +import type { AgentDotState } from '@/components/AgentStateDot' +import type { DashboardAgentRow } from '@/components/dashboard/useDashboardData' +import { findWorktreeById } from '@/store/github/refresh/worktree-refresh' +import { resolveWorktreeRowOpenInRuntimeOwner } from '@/lib/workspace/ownership/worktree-row-open-in-owner' +import { + cloudAgentRowSignIn, + cloudRowSignInAgent, + isCloudRowSignInCandidate, + type CloudAgentRowSignIn +} from '@/lib/orca-cloud/cloud-agent-row-sign-in' +import { + ensureFreshOrcaCloudAgentAccounts, + readOrcaCloudAgentAccounts, + subscribeOrcaCloudAgentAccounts +} from '@/lib/orca-cloud/orca-cloud-agent-accounts-store' +import { + hostAgentSignInEntry, + precheckHostAgentSignIn, + readHostAgentSignInReport, + subscribeHostAgentSignInReports +} from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client' +import { isOrcaCloudRuntimeEnvironment } from '../../../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' + +const subscribeNothing = (): (() => void) => () => {} + +function orcaCloudEnvironmentIdForWorktree(state: AppState, worktreeId: string): string | null { + const worktree = findWorktreeById(state, worktreeId) + if (!worktree) { + return null + } + const environmentId = resolveWorktreeRowOpenInRuntimeOwner(state, worktree).runtimeEnvironmentId + const environment = environmentId + ? state.runtimeEnvironments?.find((entry) => entry.id === environmentId) + : undefined + return environment && isOrcaCloudRuntimeEnvironment(environment) ? environment.id : null +} + +/** + * Why a cloud agent row that never ran a turn is not "Done": its agent isn't signed in. + * Null for local, SSH and paired hosts, and for any row that has finished a turn. + */ +export function useCloudAgentRowSignIn( + agent: Pick, + dotState: AgentDotState +): CloudAgentRowSignIn | null { + const candidate = isCloudRowSignInCandidate({ + agentType: agent.agentType, + dotState, + sessionBoundary: agent.entry.sessionBoundary, + isChildRow: agent.childRow !== undefined + }) + const worktreeId = agent.tab.worktreeId + // Non-candidates skip the worktree lookup, so local rows pay nothing per store change. + const environmentId = useAppStore((s) => + candidate ? orcaCloudEnvironmentIdForWorktree(s, worktreeId) : null + ) + const accounts = useSyncExternalStore( + environmentId ? subscribeOrcaCloudAgentAccounts : subscribeNothing, + readOrcaCloudAgentAccounts, + readOrcaCloudAgentAccounts + ) + const report = useSyncExternalStore( + environmentId ? subscribeHostAgentSignInReports : subscribeNothing, + () => (environmentId ? readHostAgentSignInReport(environmentId) : null), + () => null + ) + useEffect(() => { + if (!environmentId) { + return + } + void ensureFreshOrcaCloudAgentAccounts().catch(() => undefined) + precheckHostAgentSignIn(environmentId) + }, [environmentId]) + const signInAgent = cloudRowSignInAgent(agent.agentType) + if (!environmentId || !signInAgent) { + return null + } + return cloudAgentRowSignIn(signInAgent, accounts, hostAgentSignInEntry(report, signInAgent)) +} diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx new file mode 100644 index 00000000000..98a8f4c3b5a --- /dev/null +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx @@ -0,0 +1,178 @@ +/** @vitest-environment happy-dom */ +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { DashboardAgentRow as DashboardAgentRowData } from '@/components/dashboard/useDashboardData' +import { TooltipProvider } from '@/components/ui/tooltip' +import { useAppStore } from '@/store' +import type { OrcaCloudAgentsStatus } from '../../../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' +import { + setOrcaCloudAgentAccountsStateForTest, + type OrcaCloudAgentAccountsState +} from '@/lib/orca-cloud/orca-cloud-agent-accounts-store' +import { + _resetHostAgentSignInReportsForTest, + rememberHostAgentSignInReport +} from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client' +import type * as HostAgentSignInClient from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client' +import type { PublicKnownRuntimeEnvironment } from '../../../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { makeTabWithIds } from '@/components/activity/ActivityPrototypePage-test-fixtures' +import { CompactAgentRow } from './worktree-card-compact-agent-row' + +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) + +const CLOUD_ENV = 'env-cloud' +const LOCAL_WORKTREE = 'wt-local' +const CLOUD_WORKTREE = 'wt-cloud' + +vi.mock('@/components/dashboard/use-agent-row-conversation-name', () => ({ + useAgentRowConversationName: () => null +})) + +vi.mock('./CacheTimer', () => ({ + default: () => null, + usePromptCacheCountdownForPane: () => null +})) + +vi.mock('@/store/github/refresh/worktree-refresh', () => ({ + findWorktreeById: (_state: unknown, worktreeId: string) => + worktreeId === CLOUD_WORKTREE || worktreeId === LOCAL_WORKTREE ? { id: worktreeId } : null +})) + +vi.mock('@/lib/workspace/ownership/worktree-row-open-in-owner', () => ({ + resolveWorktreeRowOpenInRuntimeOwner: (_state: unknown, worktree: { id: string }) => ({ + runtimeEnvironmentId: worktree.id === CLOUD_WORKTREE ? CLOUD_ENV : null, + connectionId: null, + ownerUnresolved: false + }) +})) + +vi.mock('@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client', async (load) => ({ + ...(await load()), + // No RPC in tests; reports come from rememberHostAgentSignInReport. + precheckHostAgentSignIn: () => {} +})) + +function accounts( + claude: OrcaCloudAgentsStatus['credentials']['claude'] +): OrcaCloudAgentAccountsState { + return { + load: { + kind: 'ready', + status: { + credentials: { + claude, + codex: { state: 'none' }, + providerEnabled: { claude: true, codex: true } + }, + sources: { defaults: {}, coveredByKey: { claude: false, codex: false } } + } + }, + setups: { claude: { phase: 'idle' }, codex: { phase: 'idle' } }, + keyKinds: { claude: null, codex: null }, + queue: { agents: [], index: 0 } + } +} + +function makeAgent(worktreeId: string, sessionBoundary: boolean): DashboardAgentRowData { + return { + paneKey: 'tab-1:leaf-1', + tab: makeTabWithIds('tab-1', worktreeId), + agentType: 'claude', + state: 'done', + startedAt: 500, + entry: { + prompt: '', + state: 'done', + stateStartedAt: 1000, + stateHistory: [], + sessionBoundary, + paneKey: 'tab-1:leaf-1', + updatedAt: 1000 + } + } +} + +// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the row reads only id, name and source. +const cloudEnvironment = { + id: CLOUD_ENV, + name: 'orca sandbox abcd1234', + source: 'ephemeral-vm' +} as unknown as PublicKnownRuntimeEnvironment + +let root: Root | undefined + +beforeEach(() => { + useAppStore.setState({ runtimeEnvironments: [cloudEnvironment] }) + setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'none' })) +}) + +afterEach(() => { + act(() => root?.unmount()) + document.body.replaceChildren() + _resetHostAgentSignInReportsForTest() +}) + +function renderRow(agent: DashboardAgentRowData): HTMLElement { + const container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) + act(() => { + root!.render( + + {}} /> + + ) + }) + return container +} + +describe('CompactAgentRow on an Orca Cloud workspace whose agent is not signed in', () => { + it('shows Not signed in instead of Done when Claude is not set up', () => { + const container = renderRow(makeAgent(CLOUD_WORKTREE, true)) + expect(container.textContent).toContain('Not signed in - Claude') + expect(container.textContent).not.toContain('Done') + }) + + it('shows Sign-in expired when the Orca account sign-in expired', () => { + setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'expired' })) + const container = renderRow(makeAgent(CLOUD_WORKTREE, true)) + expect(container.textContent).toContain('Sign-in expired - Claude') + }) + + it('trusts the sandbox report: signedOut shows Not signed in even when the account covers it', () => { + setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'active' })) + rememberHostAgentSignInReport(CLOUD_ENV, { + checkedAt: 1, + agents: [{ agent: 'claude', state: 'signedOut' }] + }) + const container = renderRow(makeAgent(CLOUD_WORKTREE, true)) + expect(container.textContent).toContain('Not signed in - Claude') + }) + + it('keeps Done when the sandbox reports Claude signed in (a /login there)', () => { + rememberHostAgentSignInReport(CLOUD_ENV, { + checkedAt: 1, + agents: [{ agent: 'claude', state: 'signedIn', method: 'cliLogin' }] + }) + const container = renderRow(makeAgent(CLOUD_WORKTREE, true)) + expect(container.textContent).toContain('Done - Claude') + }) + + it('keeps Done for a covered agent idle after a turn', () => { + setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'active' })) + const container = renderRow(makeAgent(CLOUD_WORKTREE, false)) + expect(container.textContent).toContain('Done - Claude') + }) + + it('keeps Done after a finished turn even when the account is not set up', () => { + const container = renderRow(makeAgent(CLOUD_WORKTREE, false)) + expect(container.textContent).toContain('Done - Claude') + }) + + it('leaves a local workspace unchanged', () => { + const container = renderRow(makeAgent(LOCAL_WORKTREE, true)) + expect(container.textContent).toContain('Done - Claude') + expect(container.textContent).not.toContain('Not signed in') + }) +}) diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.tsx index 372e2a9dfc8..aca5784b074 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.tsx @@ -26,6 +26,8 @@ import { } from '../../../../../../shared/program-status/presentation' import { resolveRowProgramStatus } from '@/lib/program-status/agent-row-presentation' import { useTranslate, type Translate } from '@/i18n/use-translate' +import { useCloudAgentRowSignIn } from '@/components/orca-cloud/use-cloud-agent-row-sign-in' +import { cloudAgentRowSignInLabel } from '@/lib/orca-cloud/cloud-agent-row-sign-in' function getCompactAgentPrimary( agent: DashboardAgentRowData, @@ -139,9 +141,14 @@ export const CompactAgentRow = React.memo(function CompactAgentRow({ // Child agentType contains its name, not a provider; nesting conveys identity without a misleading letter icon. const hideIcon = hideIdentityIcon || agent.rowSource === 'subagent' const { presentation, dotStateOverride } = resolveRowProgramStatus(agent) - const dotState = dotStateOverride ?? getAgentDotState(agent) + const reportedDotState = dotStateOverride ?? getAgentDotState(agent) + // Orca Cloud only: an agent that started without a sign-in never ran, so it is not "Done". + const cloudSignIn = useCloudAgentRowSignIn(agent, reportedDotState) + const dotState = cloudSignIn ? 'permission' : reportedDotState const conversationName = useAgentRowConversationName(agent) - const primary = getCompactAgentPrimary(agent, conversationName) + const primary = cloudSignIn + ? cloudAgentRowSignInLabel(cloudSignIn, t) + : getCompactAgentPrimary(agent, conversationName) const isLineageChild = agent.lineage?.depth === 1 // Hold assistant text per positive turn clock; commit in an effect so discarded renders cannot cache messages. const turn = agent.entry.stateStartedAt diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 99611446974..b47e1a82da6 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -27963,6 +27963,8 @@ } }, "agentSignInStrip": { + "rowNotSignedIn": "Not signed in", + "rowExpired": "Sign-in expired", "sandbox": "the sandbox", "queued": "Queued prompt: {{prompt}}", "pasteLabel": "Code from claude.ai", diff --git a/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts b/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts new file mode 100644 index 00000000000..1045faf50da --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts @@ -0,0 +1,65 @@ +// Private layer, Orca Cloud only: a cloud Claude/Codex pane that started without a sign-in sits at +// its own "Not logged in" screen, but SessionStart reports it as done. The sidebar row says why +// instead of "Done", using the Orca account's Agent accounts and the sandbox's own sign-in report. +import type { AgentDotState } from '@/components/AgentStateDot' +import type { Translate } from '@/i18n/use-translate' +import { + HOST_AGENT_SIGN_IN_AGENTS, + type HostAgentSignInAgent, + type HostAgentSignInEntry +} from '../../../../shared/host-agent-sign-in-status' +import { orcaCloudAgentCoverage } from './orca-cloud-agent-accounts-model' +import type { OrcaCloudAgentAccountsState } from './orca-cloud-agent-accounts-store' + +export type CloudAgentRowSignIn = 'notSignedIn' | 'expired' + +export function cloudRowSignInAgent(agentType: string): HostAgentSignInAgent | null { + return HOST_AGENT_SIGN_IN_AGENTS.find((agent) => agent === agentType) ?? null +} + +/** + * Only a row that has not finished a turn this session can be waiting on sign-in: a finished + * turn proves the agent reached its provider, so its Done stays. + */ +export function isCloudRowSignInCandidate(row: { + agentType: string + dotState: AgentDotState + sessionBoundary: boolean | undefined + isChildRow: boolean +}): boolean { + return ( + !row.isChildRow && + row.sessionBoundary === true && + (row.dotState === 'done' || row.dotState === 'idle') && + cloudRowSignInAgent(row.agentType) !== null + ) +} + +/** The sandbox's own verdict wins; without one, the Orca account's coverage decides. */ +export function cloudAgentRowSignIn( + agent: HostAgentSignInAgent, + accounts: Pick, + hostEntry: HostAgentSignInEntry | null +): CloudAgentRowSignIn | null { + // Signed in on the sandbox (account placeholder, key or a /login there): nothing to show. + if (hostEntry?.state === 'signedIn' || hostEntry?.state === 'notInstalled') { + return null + } + const coverage = + accounts.load.kind === 'ready' + ? orcaCloudAgentCoverage(agent, accounts.load.status, accounts.keyKinds[agent]).kind + : null + if (coverage === 'expired') { + return 'expired' + } + if (hostEntry?.state === 'signedOut' || coverage === 'notSetUp') { + return 'notSignedIn' + } + return null +} + +export function cloudAgentRowSignInLabel(signIn: CloudAgentRowSignIn, t: Translate): string { + return signIn === 'expired' + ? t('agentSignInStrip.rowExpired', 'Sign-in expired') + : t('agentSignInStrip.rowNotSignedIn', 'Not signed in') +} From c70440f1acfb46eaf791f997e75291abf6e72244 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 15:35:45 -0800 Subject: [PATCH 002/149] test(cloud): fixture for the cloud agent row's sign-in states --- .../CompactAgentRowCloudSignIn.fixture.tsx | 133 ++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 src/renderer/src/components/sidebar/workspace-card/activity/CompactAgentRowCloudSignIn.fixture.tsx diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/CompactAgentRowCloudSignIn.fixture.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/CompactAgentRowCloudSignIn.fixture.tsx new file mode 100644 index 00000000000..eb17f85c0f7 --- /dev/null +++ b/src/renderer/src/components/sidebar/workspace-card/activity/CompactAgentRowCloudSignIn.fixture.tsx @@ -0,0 +1,133 @@ +import { defineFixture } from '../../../../component-fixtures/component-fixture' +import type { DashboardAgentRow } from '@/components/dashboard/useDashboardData' +import { + setOrcaCloudAgentAccountsStateForTest, + type OrcaCloudAgentAccountsState +} from '@/lib/orca-cloud/orca-cloud-agent-accounts-store' +import type { Repo } from '../../../../../../shared/repo-types' +import type { Worktree } from '../../../../../../shared/worktree/types' +import type { AgentType } from '../../../../../../shared/agent-status/contracts/agent-status-types' +import type { OrcaCloudAgentsStatus } from '../../../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' +import type { PublicKnownRuntimeEnvironment } from '../../../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { makeTabWithIds } from '@/components/activity/ActivityPrototypePage-test-fixtures' +import { CompactAgentRow } from './worktree-card-compact-agent-row' + +const ENVIRONMENT_ID = 'env-cloud' +const now = 1_792_983_600_000 + +const repo: Repo = { + id: 'orca', + path: '/vercel/sandbox/project', + displayName: 'orca', + badgeColor: '', + addedAt: 1 +} + +const worktree: Worktree = { + id: 'orca::/vercel/orca/workspaces/project/fix-login', + repoId: repo.id, + hostId: `runtime:${ENVIRONMENT_ID}`, + runtimeOwnerEnvironmentId: ENVIRONMENT_ID, + instanceId: 'fix-login', + path: '/vercel/orca/workspaces/project/fix-login', + displayName: 'Fix login bug', + branch: 'fix-login', + head: 'abc123', + isBare: false, + isMainWorktree: false, + comment: '', + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 1 +} + +// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the row reads only id, name and source. +const environment = { + id: ENVIRONMENT_ID, + name: 'orca sandbox abcd1234', + source: 'ephemeral-vm' +} as unknown as PublicKnownRuntimeEnvironment + +type Credential = OrcaCloudAgentsStatus['credentials']['claude'] + +function accounts(claude: Credential, codex: Credential): OrcaCloudAgentAccountsState { + return { + load: { + kind: 'ready', + status: { + credentials: { claude, codex, providerEnabled: { claude: true, codex: true } }, + sources: { defaults: {}, coveredByKey: { claude: false, codex: false } } + } + }, + setups: { claude: { phase: 'idle' }, codex: { phase: 'idle' } }, + keyKinds: { claude: null, codex: null }, + queue: { agents: [], index: 0 } + } +} + +function row(agentType: AgentType, prompt: string | null): DashboardAgentRow { + const paneKey = `cloud-${agentType}:11111111-1111-4111-8111-111111111111` + return { + paneKey, + tab: makeTabWithIds(`cloud-${agentType}`, worktree.id, prompt ?? ''), + agentType, + state: 'done', + startedAt: now - 2 * 60_000, + entry: { + paneKey, + agentType, + prompt: prompt ?? '', + state: 'done', + stateStartedAt: now - 2 * 60_000, + updatedAt: now - 2 * 60_000, + stateHistory: [], + // No prompt yet: only SessionStart has reported, so no turn has finished. + sessionBoundary: prompt === null + } + } +} + +function cloudRowFixture(state: OrcaCloudAgentAccountsState, agent: DashboardAgentRow) { + return defineFixture({ + width: 300, + store: { + repos: [repo], + worktreesByRepo: { [repo.id]: [worktree] }, + runtimeEnvironments: [environment] + }, + setup: () => setOrcaCloudAgentAccountsStateForTest(state), + render: () => ( +
+ {}} /> +
+ ) + }) +} + +/** Cloud Claude started without an Orca-account sign-in: it sits at its login screen. */ +export const claudeNotSignedIn = cloudRowFixture( + accounts({ state: 'none' }, { state: 'none' }), + row('claude', null) +) + +/** The Orca account's Claude sign-in expired and no key covers it. */ +export const claudeSignInExpired = cloudRowFixture( + accounts({ state: 'expired' }, { state: 'none' }), + row('claude', null) +) + +export const codexNotSignedIn = cloudRowFixture( + accounts({ state: 'active' }, { state: 'none' }), + row('codex', null) +) + +/** For comparison: a covered Claude idle after a finished turn keeps Done. */ +export const claudeCoveredDone = cloudRowFixture( + accounts({ state: 'active' }, { state: 'active' }), + row('claude', 'Fix the login redirect') +) From b7ad99872ba3dadb89f4a3acec5db508b6b4ab09 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 16:03:23 -0800 Subject: [PATCH 003/149] fix(cloud): dashboard full agent row shows the cloud sign-in state too Reuses useCloudAgentRowSignIn so the full row reads "Not signed in" / "Sign-in expired" with the attention dot for an Orca Cloud agent that never ran a turn. Adds full-row tests and fixtures; local rows are unchanged. --- .../dashboard/DashboardAgentRow.tsx | 10 ++++- .../CompactAgentRowCloudSignIn.fixture.tsx | 45 +++++++++++++++++-- ...d-compact-agent-row.cloud-sign-in.test.tsx | 43 ++++++++++++++++++ 3 files changed, 93 insertions(+), 5 deletions(-) diff --git a/src/renderer/src/components/dashboard/DashboardAgentRow.tsx b/src/renderer/src/components/dashboard/DashboardAgentRow.tsx index 7d676e65533..c0ecb1b8f8d 100644 --- a/src/renderer/src/components/dashboard/DashboardAgentRow.tsx +++ b/src/renderer/src/components/dashboard/DashboardAgentRow.tsx @@ -47,6 +47,8 @@ import { } from '@/components/agent-child-row-text' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' +import { useCloudAgentRowSignIn } from '@/components/orca-cloud/use-cloud-agent-row-sign-in' +import { cloudAgentRowSignInLabel } from '@/lib/orca-cloud/cloud-agent-row-sign-in' import { useUiLanguageRevision } from '@/i18n/use-ui-language-revision' function formatTimeAgo(ts: number, now: number, t: Translate = translate): string { @@ -175,7 +177,7 @@ const DashboardAgentRow = React.memo(function DashboardAgentRow({ const conversationName = useAgentRowConversationName(agent) const prompt = conversationName ?? getAgentRowPrimaryText(agent.entry) // Why: prompt is '' when unknown, so fall back to the state label to keep the row labeled. - const displayLabel = + const promptLabel = prompt || agentStateLabel( agent.childRow?.displayState ?? asDotState(agent.state, agent.entry.workingMode) @@ -214,7 +216,11 @@ const DashboardAgentRow = React.memo(function DashboardAgentRow({ ) : [formatAgentTypeLabel(agent.agentType), model].filter(Boolean).join(' · ') // Surface failed main-agent outcomes even while subagents continue running. - const dotState: AgentDotState = dotStateOverride ?? agentRowDisplayDotState(agent) + const reportedDotState: AgentDotState = dotStateOverride ?? agentRowDisplayDotState(agent) + // Orca Cloud only: an agent that started without a sign-in never ran, so it is not "Done". + const cloudSignIn = useCloudAgentRowSignIn(agent, reportedDotState) + const dotState: AgentDotState = cloudSignIn ? 'permission' : reportedDotState + const displayLabel = cloudSignIn ? cloudAgentRowSignInLabel(cloudSignIn, t) : promptLabel const dotTooltipLabel = agentStateProgressLabel( dotState, presentation.progress, diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/CompactAgentRowCloudSignIn.fixture.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/CompactAgentRowCloudSignIn.fixture.tsx index eb17f85c0f7..a687568af92 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/CompactAgentRowCloudSignIn.fixture.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/activity/CompactAgentRowCloudSignIn.fixture.tsx @@ -10,6 +10,7 @@ import type { AgentType } from '../../../../../../shared/agent-status/contracts/ import type { OrcaCloudAgentsStatus } from '../../../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' import type { PublicKnownRuntimeEnvironment } from '../../../../../../shared/remote-runtime/host-catalog/runtime-environments' import { makeTabWithIds } from '@/components/activity/ActivityPrototypePage-test-fixtures' +import DashboardAgentRowView from '@/components/dashboard/DashboardAgentRow' import { CompactAgentRow } from './worktree-card-compact-agent-row' const ENVIRONMENT_ID = 'env-cloud' @@ -92,9 +93,13 @@ function row(agentType: AgentType, prompt: string | null): DashboardAgentRow { } } -function cloudRowFixture(state: OrcaCloudAgentAccountsState, agent: DashboardAgentRow) { +function cloudRowFixture( + state: OrcaCloudAgentAccountsState, + agent: DashboardAgentRow, + variant: 'compact' | 'full' = 'compact' +) { return defineFixture({ - width: 300, + width: variant === 'full' ? 360 : 300, store: { repos: [repo], worktreesByRepo: { [repo.id]: [worktree] }, @@ -103,7 +108,16 @@ function cloudRowFixture(state: OrcaCloudAgentAccountsState, agent: DashboardAge setup: () => setOrcaCloudAgentAccountsStateForTest(state), render: () => (
- {}} /> + {variant === 'full' ? ( + {}} + onDismiss={() => {}} + /> + ) : ( + {}} /> + )}
) }) @@ -131,3 +145,28 @@ export const claudeCoveredDone = cloudRowFixture( accounts({ state: 'active' }, { state: 'active' }), row('claude', 'Fix the login redirect') ) + +// The dashboard's full row reads the same sign-in state. +export const fullClaudeNotSignedIn = cloudRowFixture( + accounts({ state: 'none' }, { state: 'none' }), + row('claude', null), + 'full' +) + +export const fullClaudeSignInExpired = cloudRowFixture( + accounts({ state: 'expired' }, { state: 'none' }), + row('claude', null), + 'full' +) + +export const fullCodexNotSignedIn = cloudRowFixture( + accounts({ state: 'active' }, { state: 'none' }), + row('codex', null), + 'full' +) + +export const fullClaudeCoveredDone = cloudRowFixture( + accounts({ state: 'active' }, { state: 'active' }), + row('claude', 'Fix the login redirect'), + 'full' +) diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx index 98a8f4c3b5a..6b2da8710c9 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx @@ -17,6 +17,7 @@ import { import type * as HostAgentSignInClient from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client' import type { PublicKnownRuntimeEnvironment } from '../../../../../../shared/remote-runtime/host-catalog/runtime-environments' import { makeTabWithIds } from '@/components/activity/ActivityPrototypePage-test-fixtures' +import DashboardAgentRow from '@/components/dashboard/DashboardAgentRow' import { CompactAgentRow } from './worktree-card-compact-agent-row' Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) @@ -176,3 +177,45 @@ describe('CompactAgentRow on an Orca Cloud workspace whose agent is not signed i expect(container.textContent).not.toContain('Not signed in') }) }) + +function renderFullRow(agent: DashboardAgentRowData): HTMLElement { + const container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) + act(() => { + root!.render( + + {}} onDismiss={() => {}} /> + + ) + }) + return container +} + +function fullRowLabel(container: HTMLElement): string | null { + return container.querySelector('span.flex-1[title]')?.textContent ?? null +} + +describe('DashboardAgentRow (full row) on an Orca Cloud workspace', () => { + it('shows Not signed in instead of Done when Claude is not set up', () => { + const container = renderFullRow(makeAgent(CLOUD_WORKTREE, true)) + expect(fullRowLabel(container)).toBe('Not signed in') + expect(container.querySelector('[aria-label="Needs attention"]')).not.toBeNull() + }) + + it('shows Sign-in expired when the Orca account sign-in expired', () => { + setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'expired' })) + expect(fullRowLabel(renderFullRow(makeAgent(CLOUD_WORKTREE, true)))).toBe('Sign-in expired') + }) + + it('keeps Done for a covered agent idle after a turn', () => { + setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'active' })) + expect(fullRowLabel(renderFullRow(makeAgent(CLOUD_WORKTREE, false)))).toBe('Done') + }) + + it('leaves a local workspace unchanged', () => { + const container = renderFullRow(makeAgent(LOCAL_WORKTREE, true)) + expect(fullRowLabel(container)).toBe('Done') + expect(container.textContent).not.toContain('Not signed in') + }) +}) From a6a3da898d5af729688f8bb03badf91ba3db03a7 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 16:25:12 -0800 Subject: [PATCH 004/149] fix(cloud): agent row sign-in status says Needs sign-in and opens Agent accounts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Design decisions for #310: "Needs sign-in" replaces "Not signed in" ("Sign-in expired" stays), the status tooltip names the fix (Set up once / Renew in Settings → Agent accounts), and clicking the status dot or text opens Settings → Agent accounts via the composer's openOrcaCloudAgentAccounts target. The rest of the row still activates the pane; send-target mode keeps row clicks. Applies to the compact and full rows. --- .../dashboard/DashboardAgentRow.tsx | 88 ++++++++++-------- .../orca-cloud/CloudAgentRowSignInTarget.tsx | 90 +++++++++++++++++++ .../orca-cloud/use-cloud-agent-row-sign-in.ts | 29 ++++++ .../CompactAgentRowCloudSignIn.fixture.tsx | 8 +- ...d-compact-agent-row.cloud-sign-in.test.tsx | 83 ++++++++++++++--- .../worktree-card-compact-agent-row.tsx | 44 +++++---- src/renderer/src/i18n/locales/en.json | 4 +- .../lib/orca-cloud/cloud-agent-row-sign-in.ts | 9 +- 8 files changed, 285 insertions(+), 70 deletions(-) create mode 100644 src/renderer/src/components/orca-cloud/CloudAgentRowSignInTarget.tsx diff --git a/src/renderer/src/components/dashboard/DashboardAgentRow.tsx b/src/renderer/src/components/dashboard/DashboardAgentRow.tsx index c0ecb1b8f8d..dd3c9ff2a86 100644 --- a/src/renderer/src/components/dashboard/DashboardAgentRow.tsx +++ b/src/renderer/src/components/dashboard/DashboardAgentRow.tsx @@ -47,8 +47,11 @@ import { } from '@/components/agent-child-row-text' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' -import { useCloudAgentRowSignIn } from '@/components/orca-cloud/use-cloud-agent-row-sign-in' -import { cloudAgentRowSignInLabel } from '@/lib/orca-cloud/cloud-agent-row-sign-in' +import { useCloudAgentRowStatus } from '@/components/orca-cloud/use-cloud-agent-row-sign-in' +import { + CloudAgentRowSignInDot, + CloudAgentRowSignInLabel +} from '@/components/orca-cloud/CloudAgentRowSignInTarget' import { useUiLanguageRevision } from '@/i18n/use-ui-language-revision' function formatTimeAgo(ts: number, now: number, t: Translate = translate): string { @@ -218,9 +221,10 @@ const DashboardAgentRow = React.memo(function DashboardAgentRow({ // Surface failed main-agent outcomes even while subagents continue running. const reportedDotState: AgentDotState = dotStateOverride ?? agentRowDisplayDotState(agent) // Orca Cloud only: an agent that started without a sign-in never ran, so it is not "Done". - const cloudSignIn = useCloudAgentRowSignIn(agent, reportedDotState) - const dotState: AgentDotState = cloudSignIn ? 'permission' : reportedDotState - const displayLabel = cloudSignIn ? cloudAgentRowSignInLabel(cloudSignIn, t) : promptLabel + const cloudStatus = useCloudAgentRowStatus(agent, reportedDotState, sendTargetStatus) + const dotState: AgentDotState = cloudStatus?.dotState ?? reportedDotState + const displayLabel = cloudStatus?.label ?? promptLabel + const signInTooltip = cloudStatus?.tooltip ?? null const dotTooltipLabel = agentStateProgressLabel( dotState, presentation.progress, @@ -308,24 +312,28 @@ const DashboardAgentRow = React.memo(function DashboardAgentRow({ ) : null}
{/* Why: state dot sits in the leading gutter so the eye can scan one column for row state. */} - - - - - - - - {dotTooltipLabel} - - + {signInTooltip ? ( + + ) : ( + + + + + + + + {dotTooltipLabel} + + + )} {/* Why: subagent rows skip the icon — agentType holds a child's name, which AgentTypeIcon would draw as a misleading letter; nesting conveys identity. */} {!hideIdentityIcon && agent.rowSource !== 'subagent' && ( @@ -333,19 +341,27 @@ const DashboardAgentRow = React.memo(function DashboardAgentRow({ )} {/* Why: interpolate-size:allow-keywords is the only way to animate height to/from auto without measuring in JS; falls back to an instant swap where unsupported. */} - - {displayLabel} - + {signInTooltip ? ( + + ) : ( + + {displayLabel} + + )} {showModel && model && ( { + e.stopPropagation() + openCloudAgentAccountsSettings() + }, []) + return ( + + ) +} + +/** The full row's status dot: the attention dot, opening Agent accounts. */ +export function CloudAgentRowSignInDot({ + tooltip, + size +}: { + tooltip: string + size: 'sm' | 'md' +}): React.JSX.Element { + return ( + + + + ) +} + +/** The full row's label slot: the text links to Agent accounts; the rest of the slot opens the pane. */ +export function CloudAgentRowSignInLabel({ + label, + tooltip, + emphasis +}: { + label: string + tooltip: string + /** Matches the full row's label: bold when unvisited, brighter on the selected-row fill. */ + emphasis: 'unvisited' | 'highlighted' | 'muted' +}): React.JSX.Element { + return ( + + + {label} + + + ) +} diff --git a/src/renderer/src/components/orca-cloud/use-cloud-agent-row-sign-in.ts b/src/renderer/src/components/orca-cloud/use-cloud-agent-row-sign-in.ts index 446f8cb5415..e3718060b87 100644 --- a/src/renderer/src/components/orca-cloud/use-cloud-agent-row-sign-in.ts +++ b/src/renderer/src/components/orca-cloud/use-cloud-agent-row-sign-in.ts @@ -5,8 +5,11 @@ import type { AgentDotState } from '@/components/AgentStateDot' import type { DashboardAgentRow } from '@/components/dashboard/useDashboardData' import { findWorktreeById } from '@/store/github/refresh/worktree-refresh' import { resolveWorktreeRowOpenInRuntimeOwner } from '@/lib/workspace/ownership/worktree-row-open-in-owner' +import { useTranslate } from '@/i18n/use-translate' import { cloudAgentRowSignIn, + cloudAgentRowSignInLabel, + cloudAgentRowSignInTooltip, cloudRowSignInAgent, isCloudRowSignInCandidate, type CloudAgentRowSignIn @@ -80,3 +83,29 @@ export function useCloudAgentRowSignIn( } return cloudAgentRowSignIn(signInAgent, accounts, hostAgentSignInEntry(report, signInAgent)) } + +export type CloudAgentRowStatus = { + dotState: AgentDotState + label: string + /** Null in send-target mode, which owns row clicks; otherwise the status links to Settings. */ + tooltip: string | null +} + +/** What a sign-in-needed cloud row shows in place of its state: attention dot, label and link tooltip. */ +export function useCloudAgentRowStatus( + agent: Pick, + dotState: AgentDotState, + /** Set while send-target mode owns row clicks. */ + sendTargetStatus: string | undefined +): CloudAgentRowStatus | null { + const t = useTranslate() + const signIn = useCloudAgentRowSignIn(agent, dotState) + if (!signIn) { + return null + } + return { + dotState: 'permission', + label: cloudAgentRowSignInLabel(signIn, t), + tooltip: sendTargetStatus ? null : cloudAgentRowSignInTooltip(signIn, t) + } +} diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/CompactAgentRowCloudSignIn.fixture.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/CompactAgentRowCloudSignIn.fixture.tsx index a687568af92..d2aac025eff 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/CompactAgentRowCloudSignIn.fixture.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/activity/CompactAgentRowCloudSignIn.fixture.tsx @@ -124,7 +124,7 @@ function cloudRowFixture( } /** Cloud Claude started without an Orca-account sign-in: it sits at its login screen. */ -export const claudeNotSignedIn = cloudRowFixture( +export const claudeNeedsSignIn = cloudRowFixture( accounts({ state: 'none' }, { state: 'none' }), row('claude', null) ) @@ -135,7 +135,7 @@ export const claudeSignInExpired = cloudRowFixture( row('claude', null) ) -export const codexNotSignedIn = cloudRowFixture( +export const codexNeedsSignIn = cloudRowFixture( accounts({ state: 'active' }, { state: 'none' }), row('codex', null) ) @@ -147,7 +147,7 @@ export const claudeCoveredDone = cloudRowFixture( ) // The dashboard's full row reads the same sign-in state. -export const fullClaudeNotSignedIn = cloudRowFixture( +export const fullClaudeNeedsSignIn = cloudRowFixture( accounts({ state: 'none' }, { state: 'none' }), row('claude', null), 'full' @@ -159,7 +159,7 @@ export const fullClaudeSignInExpired = cloudRowFixture( 'full' ) -export const fullCodexNotSignedIn = cloudRowFixture( +export const fullCodexNeedsSignIn = cloudRowFixture( accounts({ state: 'active' }, { state: 'none' }), row('codex', null), 'full' diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx index 6b2da8710c9..c51011913cb 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx @@ -114,14 +114,14 @@ afterEach(() => { _resetHostAgentSignInReportsForTest() }) -function renderRow(agent: DashboardAgentRowData): HTMLElement { +function renderRow(agent: DashboardAgentRowData, onActivate = () => {}): HTMLElement { const container = document.createElement('div') document.body.appendChild(container) root = createRoot(container) act(() => { root!.render( - {}} /> + ) }) @@ -129,9 +129,9 @@ function renderRow(agent: DashboardAgentRowData): HTMLElement { } describe('CompactAgentRow on an Orca Cloud workspace whose agent is not signed in', () => { - it('shows Not signed in instead of Done when Claude is not set up', () => { + it('shows Needs sign-in instead of Done when Claude is not set up', () => { const container = renderRow(makeAgent(CLOUD_WORKTREE, true)) - expect(container.textContent).toContain('Not signed in - Claude') + expect(container.textContent).toContain('Needs sign-in - Claude') expect(container.textContent).not.toContain('Done') }) @@ -141,14 +141,14 @@ describe('CompactAgentRow on an Orca Cloud workspace whose agent is not signed i expect(container.textContent).toContain('Sign-in expired - Claude') }) - it('trusts the sandbox report: signedOut shows Not signed in even when the account covers it', () => { + it('trusts the sandbox report: signedOut shows Needs sign-in even when the account covers it', () => { setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'active' })) rememberHostAgentSignInReport(CLOUD_ENV, { checkedAt: 1, agents: [{ agent: 'claude', state: 'signedOut' }] }) const container = renderRow(makeAgent(CLOUD_WORKTREE, true)) - expect(container.textContent).toContain('Not signed in - Claude') + expect(container.textContent).toContain('Needs sign-in - Claude') }) it('keeps Done when the sandbox reports Claude signed in (a /login there)', () => { @@ -174,18 +174,18 @@ describe('CompactAgentRow on an Orca Cloud workspace whose agent is not signed i it('leaves a local workspace unchanged', () => { const container = renderRow(makeAgent(LOCAL_WORKTREE, true)) expect(container.textContent).toContain('Done - Claude') - expect(container.textContent).not.toContain('Not signed in') + expect(container.textContent).not.toContain('Needs sign-in') }) }) -function renderFullRow(agent: DashboardAgentRowData): HTMLElement { +function renderFullRow(agent: DashboardAgentRowData, onActivate = () => {}): HTMLElement { const container = document.createElement('div') document.body.appendChild(container) root = createRoot(container) act(() => { root!.render( - {}} onDismiss={() => {}} /> + {}} /> ) }) @@ -193,13 +193,13 @@ function renderFullRow(agent: DashboardAgentRowData): HTMLElement { } function fullRowLabel(container: HTMLElement): string | null { - return container.querySelector('span.flex-1[title]')?.textContent ?? null + return container.querySelector('span.flex-1')?.textContent ?? null } describe('DashboardAgentRow (full row) on an Orca Cloud workspace', () => { - it('shows Not signed in instead of Done when Claude is not set up', () => { + it('shows Needs sign-in instead of Done when Claude is not set up', () => { const container = renderFullRow(makeAgent(CLOUD_WORKTREE, true)) - expect(fullRowLabel(container)).toBe('Not signed in') + expect(fullRowLabel(container)).toBe('Needs sign-in') expect(container.querySelector('[aria-label="Needs attention"]')).not.toBeNull() }) @@ -216,6 +216,63 @@ describe('DashboardAgentRow (full row) on an Orca Cloud workspace', () => { it('leaves a local workspace unchanged', () => { const container = renderFullRow(makeAgent(LOCAL_WORKTREE, true)) expect(fullRowLabel(container)).toBe('Done') - expect(container.textContent).not.toContain('Not signed in') + expect(container.textContent).not.toContain('Needs sign-in') + expect(container.querySelector('button[title*="Agent accounts"]')).toBeNull() + }) +}) + +function click(element: Element): void { + act(() => { + element.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) +} + +describe.each([ + ['compact', renderRow], + ['full', renderFullRow] +] as const)('%s row: the sign-in status links to Settings → Agent accounts', (_name, render) => { + beforeEach(() => { + useAppStore.setState({ activeView: 'terminal', settingsNavigationTarget: null }) + }) + + it('names where to set up, and clicking the status opens Agent accounts, not the pane', () => { + const onActivate = vi.fn() + const container = render(makeAgent(CLOUD_WORKTREE, true), onActivate) + const text = container.querySelector('button[title]') + expect(text?.getAttribute('title')).toBe('Set up once in Settings → Agent accounts') + expect(text?.textContent).toBe('Needs sign-in') + click(text!) + expect(onActivate).not.toHaveBeenCalled() + expect(useAppStore.getState().activeView).toBe('settings') + expect(useAppStore.getState().settingsNavigationTarget).toMatchObject({ + pane: 'agent-accounts', + sectionId: 'orca-cloud' + }) + }) + + it('opens Agent accounts from the dot too', () => { + const onActivate = vi.fn() + const container = render(makeAgent(CLOUD_WORKTREE, true), onActivate) + const dot = container.querySelector('button:not([title])') + expect(dot).not.toBeNull() + click(dot!) + expect(onActivate).not.toHaveBeenCalled() + expect(useAppStore.getState().activeView).toBe('settings') + }) + + it('tells an expired sign-in to renew', () => { + setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'expired' })) + const container = render(makeAgent(CLOUD_WORKTREE, true)) + expect(container.querySelector('button[title]')?.getAttribute('title')).toBe( + 'Renew in Settings → Agent accounts' + ) + }) + + it('still activates the pane when the rest of the row is clicked', () => { + const onActivate = vi.fn() + const container = render(makeAgent(CLOUD_WORKTREE, true), onActivate) + click(container.firstElementChild!) + expect(onActivate).toHaveBeenCalledWith('tab-1', 'tab-1:leaf-1') + expect(useAppStore.getState().activeView).toBe('terminal') }) }) diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.tsx index aca5784b074..3a32d1ecc15 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.tsx @@ -26,8 +26,8 @@ import { } from '../../../../../../shared/program-status/presentation' import { resolveRowProgramStatus } from '@/lib/program-status/agent-row-presentation' import { useTranslate, type Translate } from '@/i18n/use-translate' -import { useCloudAgentRowSignIn } from '@/components/orca-cloud/use-cloud-agent-row-sign-in' -import { cloudAgentRowSignInLabel } from '@/lib/orca-cloud/cloud-agent-row-sign-in' +import { useCloudAgentRowStatus } from '@/components/orca-cloud/use-cloud-agent-row-sign-in' +import { CloudAgentRowSignInTarget } from '@/components/orca-cloud/CloudAgentRowSignInTarget' function getCompactAgentPrimary( agent: DashboardAgentRowData, @@ -143,12 +143,11 @@ export const CompactAgentRow = React.memo(function CompactAgentRow({ const { presentation, dotStateOverride } = resolveRowProgramStatus(agent) const reportedDotState = dotStateOverride ?? getAgentDotState(agent) // Orca Cloud only: an agent that started without a sign-in never ran, so it is not "Done". - const cloudSignIn = useCloudAgentRowSignIn(agent, reportedDotState) - const dotState = cloudSignIn ? 'permission' : reportedDotState + const cloudStatus = useCloudAgentRowStatus(agent, reportedDotState, sendTargetStatus) + const dotState = cloudStatus?.dotState ?? reportedDotState const conversationName = useAgentRowConversationName(agent) - const primary = cloudSignIn - ? cloudAgentRowSignInLabel(cloudSignIn, t) - : getCompactAgentPrimary(agent, conversationName) + const primary = cloudStatus?.label ?? getCompactAgentPrimary(agent, conversationName) + const signInTooltip = cloudStatus?.tooltip ?? null const isLineageChild = agent.lineage?.depth === 1 // Hold assistant text per positive turn clock; commit in an effect so discarded renders cannot cache messages. const turn = agent.entry.stateStartedAt @@ -241,13 +240,19 @@ export const CompactAgentRow = React.memo(function CompactAgentRow({ ) : ( <> {/* Show the actionable disabled reason over every hit area. */} - + {signInTooltip ? ( + + + + ) : ( + + )} {!hideIcon && ( @@ -257,7 +262,16 @@ export const CompactAgentRow = React.memo(function CompactAgentRow({ className="min-w-0 flex-1 truncate" title={sendTargetDisabledReason ? undefined : rowTitle} > - {leadingText} + {signInTooltip ? ( + + {leadingText} + + ) : ( + {leadingText} + )} {trailingText && ( {' '} diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index b47e1a82da6..8ea2e188235 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -27963,8 +27963,10 @@ } }, "agentSignInStrip": { - "rowNotSignedIn": "Not signed in", + "rowNeedsSignIn": "Needs sign-in", + "rowNeedsSignInTooltip": "Set up once in Settings → Agent accounts", "rowExpired": "Sign-in expired", + "rowExpiredTooltip": "Renew in Settings → Agent accounts", "sandbox": "the sandbox", "queued": "Queued prompt: {{prompt}}", "pasteLabel": "Code from claude.ai", diff --git a/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts b/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts index 1045faf50da..6a57a190050 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts @@ -61,5 +61,12 @@ export function cloudAgentRowSignIn( export function cloudAgentRowSignInLabel(signIn: CloudAgentRowSignIn, t: Translate): string { return signIn === 'expired' ? t('agentSignInStrip.rowExpired', 'Sign-in expired') - : t('agentSignInStrip.rowNotSignedIn', 'Not signed in') + : t('agentSignInStrip.rowNeedsSignIn', 'Needs sign-in') +} + +/** Where the fix lives; the row's status opens it (Settings → Agent accounts). */ +export function cloudAgentRowSignInTooltip(signIn: CloudAgentRowSignIn, t: Translate): string { + return signIn === 'expired' + ? t('agentSignInStrip.rowExpiredTooltip', 'Renew in Settings → Agent accounts') + : t('agentSignInStrip.rowNeedsSignInTooltip', 'Set up once in Settings → Agent accounts') } From c0c7f1374c2ce3d9475b190872b32f6b74413159 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 16:46:59 -0800 Subject: [PATCH 005/149] fix(cloud): sign-in row state also triggers for rows mirrored from the cloud host On a real cloud workspace the row is mirrored from the host and carries no sessionBoundary: the host projects a bare title-derived done once Claude's title is newer than its SessionStart hook. The candidate test now means "no finished turn": sessionBoundary, or an empty prompt with no reply, no state history and no turn end. A finished turn still keeps Done. Adds tests with the mirrored entry shape seen on m4air. --- .../orca-cloud/use-cloud-agent-row-sign-in.ts | 2 +- ...d-compact-agent-row.cloud-sign-in.test.tsx | 63 ++++++++++++++++++- .../lib/orca-cloud/cloud-agent-row-sign-in.ts | 32 +++++++++- 3 files changed, 92 insertions(+), 5 deletions(-) diff --git a/src/renderer/src/components/orca-cloud/use-cloud-agent-row-sign-in.ts b/src/renderer/src/components/orca-cloud/use-cloud-agent-row-sign-in.ts index e3718060b87..e2c7ce22b73 100644 --- a/src/renderer/src/components/orca-cloud/use-cloud-agent-row-sign-in.ts +++ b/src/renderer/src/components/orca-cloud/use-cloud-agent-row-sign-in.ts @@ -52,7 +52,7 @@ export function useCloudAgentRowSignIn( const candidate = isCloudRowSignInCandidate({ agentType: agent.agentType, dotState, - sessionBoundary: agent.entry.sessionBoundary, + entry: agent.entry, isChildRow: agent.childRow !== undefined }) const worktreeId = agent.tab.worktreeId diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx index c51011913cb..5b1f8b3a2be 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx @@ -75,6 +75,7 @@ function accounts( } } +/** `true`: only SessionStart has reported. `false`: a turn ran and ended (history and turn end). */ function makeAgent(worktreeId: string, sessionBoundary: boolean): DashboardAgentRowData { return { paneKey: 'tab-1:leaf-1', @@ -86,7 +87,8 @@ function makeAgent(worktreeId: string, sessionBoundary: boolean): DashboardAgent prompt: '', state: 'done', stateStartedAt: 1000, - stateHistory: [], + stateHistory: sessionBoundary ? [] : [{ state: 'working', prompt: '', startedAt: 600 }], + ...(sessionBoundary ? {} : { turnEndedAt: 1000 }), sessionBoundary, paneKey: 'tab-1:leaf-1', updatedAt: 1000 @@ -94,6 +96,28 @@ function makeAgent(worktreeId: string, sessionBoundary: boolean): DashboardAgent } } +/** The row a real cloud workspace mirrors from its host (m4air "crayfish"): no sessionBoundary. */ +function makeMirroredAgent(worktreeId: string): DashboardAgentRowData { + return { + paneKey: 'tab-1:leaf-1', + tab: makeTabWithIds('tab-1', worktreeId), + agentType: 'claude', + state: 'done', + startedAt: 500, + entry: { + prompt: '', + state: 'done', + stateStartedAt: 1000, + stateHistory: [], + agentType: 'claude', + launchAttested: true, + mirroredEvidenceReceivedAt: 1500, + paneKey: 'tab-1:leaf-1', + updatedAt: 1000 + } + } +} + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the row reads only id, name and source. const cloudEnvironment = { id: CLOUD_ENV, @@ -176,6 +200,39 @@ describe('CompactAgentRow on an Orca Cloud workspace whose agent is not signed i expect(container.textContent).toContain('Done - Claude') expect(container.textContent).not.toContain('Needs sign-in') }) + + it('shows Needs sign-in for the row mirrored from the cloud host (no sessionBoundary)', () => { + const container = renderRow(makeMirroredAgent(CLOUD_WORKTREE)) + expect(container.textContent).toContain('Needs sign-in - Claude') + expect(container.textContent).not.toContain('Done') + }) + + it('keeps Done for a mirrored row with a finished turn', () => { + const mirrored = makeMirroredAgent(CLOUD_WORKTREE) + const container = renderRow({ + ...mirrored, + entry: { + ...mirrored.entry, + stateHistory: [{ state: 'working', prompt: '', startedAt: 600 }], + turnEndedAt: 1000 + } + }) + expect(container.textContent).toContain('Done - Claude') + }) + + it('keeps Done for a mirrored row once the prompt ran', () => { + const mirrored = makeMirroredAgent(CLOUD_WORKTREE) + const container = renderRow({ + ...mirrored, + entry: { ...mirrored.entry, prompt: 'Fix the login redirect' } + }) + expect(container.textContent).not.toContain('Needs sign-in') + }) + + it('leaves the same mirrored shape on a local workspace unchanged', () => { + const container = renderRow(makeMirroredAgent(LOCAL_WORKTREE)) + expect(container.textContent).toContain('Done - Claude') + }) }) function renderFullRow(agent: DashboardAgentRowData, onActivate = () => {}): HTMLElement { @@ -213,6 +270,10 @@ describe('DashboardAgentRow (full row) on an Orca Cloud workspace', () => { expect(fullRowLabel(renderFullRow(makeAgent(CLOUD_WORKTREE, false)))).toBe('Done') }) + it('shows Needs sign-in for the row mirrored from the cloud host', () => { + expect(fullRowLabel(renderFullRow(makeMirroredAgent(CLOUD_WORKTREE)))).toBe('Needs sign-in') + }) + it('leaves a local workspace unchanged', () => { const container = renderFullRow(makeAgent(LOCAL_WORKTREE, true)) expect(fullRowLabel(container)).toBe('Done') diff --git a/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts b/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts index 6a57a190050..9408d5164ef 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts @@ -3,6 +3,7 @@ // instead of "Done", using the Orca account's Agent accounts and the sandbox's own sign-in report. import type { AgentDotState } from '@/components/AgentStateDot' import type { Translate } from '@/i18n/use-translate' +import type { AgentStatusEntry } from '../../../../shared/agent-status/contracts/agent-status-types' import { HOST_AGENT_SIGN_IN_AGENTS, type HostAgentSignInAgent, @@ -17,6 +18,31 @@ export function cloudRowSignInAgent(agentType: string): HostAgentSignInAgent | n return HOST_AGENT_SIGN_IN_AGENTS.find((agent) => agent === agentType) ?? null } +/** The entry fields that show whether this session has finished a turn. */ +export type CloudRowTurnEvidence = Pick< + AgentStatusEntry, + 'sessionBoundary' | 'prompt' | 'lastAssistantMessage' | 'stateHistory' | 'turnEndedAt' +> + +/** + * True when nothing shows a finished turn. A local hook row says so with `sessionBoundary`. A row + * mirrored from a cloud host can arrive without it: once the agent's title is newer than the + * SessionStart hook (or the hook goes stale), the host projects a bare title-derived `done` + * (runtime-mobile-agent-status-builder's last branch). So an empty prompt, no reply, no history + * and no turn end count too. + */ +export function hasNoFinishedTurn(entry: CloudRowTurnEvidence): boolean { + if (entry.sessionBoundary === true) { + return true + } + return ( + !entry.prompt?.trim() && + !entry.lastAssistantMessage?.trim() && + (entry.stateHistory?.length ?? 0) === 0 && + entry.turnEndedAt === undefined + ) +} + /** * Only a row that has not finished a turn this session can be waiting on sign-in: a finished * turn proves the agent reached its provider, so its Done stays. @@ -24,14 +50,14 @@ export function cloudRowSignInAgent(agentType: string): HostAgentSignInAgent | n export function isCloudRowSignInCandidate(row: { agentType: string dotState: AgentDotState - sessionBoundary: boolean | undefined + entry: CloudRowTurnEvidence isChildRow: boolean }): boolean { return ( !row.isChildRow && - row.sessionBoundary === true && (row.dotState === 'done' || row.dotState === 'idle') && - cloudRowSignInAgent(row.agentType) !== null + cloudRowSignInAgent(row.agentType) !== null && + hasNoFinishedTurn(row.entry) ) } From e4ab41d3868d1fe89b48d356bc6e1a2c177fc6c1 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 16:59:16 -0800 Subject: [PATCH 006/149] fix(cloud): agent row sign-in keyed off Agent accounts and turn evidence; app tooltip - Needs sign-in / Sign-in expired come from the Agent accounts state (credential state and providerState via the new shared orcaCloudAgentCoverageFromAccounts selector, which cloudAgentStripReason now uses too) combined with "no turn finished" (no stateHistory, no turnEndedAt, no assistant reply). sessionBoundary is no longer read. The sandbox report can still clear it (signedIn). - Rows that render before the accounts read lands (or before the cloud environment is known) pick the state up when it does. - The status dot and text use the app Tooltip (StateIndicatorTooltip) instead of a native title; keyboard focus opens it. - Tests query the tooltip content; fixtures add focused-tooltip shots. --- .../dashboard/DashboardAgentRow.tsx | 12 +- .../orca-cloud/CloudAgentRowSignInTarget.tsx | 72 +++++++---- .../CompactAgentRowCloudSignIn.fixture.tsx | 20 +++ ...d-compact-agent-row.cloud-sign-in.test.tsx | 118 ++++++++++++++---- .../worktree-card-compact-agent-row.tsx | 18 +-- .../lib/orca-cloud/cloud-agent-launch-hold.ts | 9 +- .../lib/orca-cloud/cloud-agent-row-sign-in.ts | 58 +++++---- .../orca-cloud-agent-accounts-model.ts | 18 +++ 8 files changed, 228 insertions(+), 97 deletions(-) diff --git a/src/renderer/src/components/dashboard/DashboardAgentRow.tsx b/src/renderer/src/components/dashboard/DashboardAgentRow.tsx index dd3c9ff2a86..10a436f21b3 100644 --- a/src/renderer/src/components/dashboard/DashboardAgentRow.tsx +++ b/src/renderer/src/components/dashboard/DashboardAgentRow.tsx @@ -224,7 +224,8 @@ const DashboardAgentRow = React.memo(function DashboardAgentRow({ const cloudStatus = useCloudAgentRowStatus(agent, reportedDotState, sendTargetStatus) const dotState: AgentDotState = cloudStatus?.dotState ?? reportedDotState const displayLabel = cloudStatus?.label ?? promptLabel - const signInTooltip = cloudStatus?.tooltip ?? null + // Send-target mode owns row clicks, so only outside it is the status a link to Settings. + const signIn = cloudStatus?.tooltip ? cloudStatus : null const dotTooltipLabel = agentStateProgressLabel( dotState, presentation.progress, @@ -312,8 +313,8 @@ const DashboardAgentRow = React.memo(function DashboardAgentRow({ ) : null}
{/* Why: state dot sits in the leading gutter so the eye can scan one column for row state. */} - {signInTooltip ? ( - + {signIn ? ( + ) : ( @@ -341,10 +342,9 @@ const DashboardAgentRow = React.memo(function DashboardAgentRow({ )} {/* Why: interpolate-size:allow-keywords is the only way to animate height to/from auto without measuring in JS; falls back to an instant swap where unsupported. */} - {signInTooltip ? ( + {signIn ? ( ) : ( diff --git a/src/renderer/src/components/orca-cloud/CloudAgentRowSignInTarget.tsx b/src/renderer/src/components/orca-cloud/CloudAgentRowSignInTarget.tsx index 6eccced62e5..3a666db9a8b 100644 --- a/src/renderer/src/components/orca-cloud/CloudAgentRowSignInTarget.tsx +++ b/src/renderer/src/components/orca-cloud/CloudAgentRowSignInTarget.tsx @@ -4,21 +4,34 @@ import React, { useCallback } from 'react' import { useAppStore } from '@/store' import { cn } from '@/lib/utils' import { AgentStateDot } from '@/components/AgentStateDot' +import { + StateIndicatorTooltip, + type StateIndicatorTooltipSide +} from '@/components/StateIndicatorTooltip' import { openOrcaCloudAgentAccounts } from '@/components/new-workspace/OrcaCloudAgentSetupRow' +/** What the status shows: its label, and the tooltip naming the fix. */ +export type CloudAgentRowStatusText = { label: string; tooltip: string | null } + /** The composer's "Set up once" target, plus opening Settings, which the sidebar has closed. */ export function openCloudAgentAccountsSettings(): void { openOrcaCloudAgentAccounts() useAppStore.getState().openSettingsPage() } +/** A focusable status button: the app tooltip names the fix on hover and on keyboard focus. */ export function CloudAgentRowSignInTarget({ tooltip, + tooltipSide = 'top', + ariaLabel, className, children }: { - /** Native title; null when the child (a state dot) draws its own tooltip. */ + /** Null shows no tooltip (StateIndicatorTooltip passes the button through). */ tooltip: string | null + tooltipSide?: StateIndicatorTooltipSide + /** For the dot, whose button has no text of its own. */ + ariaLabel?: string className?: string children: React.ReactNode }): React.JSX.Element { @@ -27,53 +40,60 @@ export function CloudAgentRowSignInTarget({ openCloudAgentAccountsSettings() }, []) return ( - + + + ) } -/** The full row's status dot: the attention dot, opening Agent accounts. */ +/** The status dot: the attention dot, opening Agent accounts. Its tooltip is the button's. */ export function CloudAgentRowSignInDot({ - tooltip, + status, + tooltipSide, size }: { - tooltip: string + status: CloudAgentRowStatusText + tooltipSide?: StateIndicatorTooltipSide size: 'sm' | 'md' }): React.JSX.Element { return ( - - + + ) } /** The full row's label slot: the text links to Agent accounts; the rest of the slot opens the pane. */ export function CloudAgentRowSignInLabel({ - label, - tooltip, + status, emphasis }: { - label: string - tooltip: string + status: CloudAgentRowStatusText /** Matches the full row's label: bold when unvisited, brighter on the selected-row fill. */ emphasis: 'unvisited' | 'highlighted' | 'muted' }): React.JSX.Element { return ( - {label} + {status.label} ) diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/CompactAgentRowCloudSignIn.fixture.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/CompactAgentRowCloudSignIn.fixture.tsx index d2aac025eff..090ba4b61de 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/CompactAgentRowCloudSignIn.fixture.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/activity/CompactAgentRowCloudSignIn.fixture.tsx @@ -170,3 +170,23 @@ export const fullClaudeCoveredDone = cloudRowFixture( row('claude', 'Fix the login redirect'), 'full' ) + +/** Keyboard focus on the status text opens the app tooltip that names the fix. */ +function focusStatusText(frame: HTMLElement): void { + frame.querySelectorAll('[data-cloud-sign-in-status]')[1]?.focus() +} + +export const claudeNeedsSignInTooltip = defineFixture({ + ...cloudRowFixture(accounts({ state: 'none' }, { state: 'none' }), row('claude', null)), + width: 360, + interact: focusStatusText +}) + +export const fullClaudeSignInExpiredTooltip = defineFixture({ + ...cloudRowFixture( + accounts({ state: 'expired' }, { state: 'none' }), + row('claude', null), + 'full' + ), + interact: focusStatusText +}) diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx index 5b1f8b3a2be..12ef1abd242 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx @@ -220,15 +220,41 @@ describe('CompactAgentRow on an Orca Cloud workspace whose agent is not signed i expect(container.textContent).toContain('Done - Claude') }) - it('keeps Done for a mirrored row once the prompt ran', () => { + it('keeps Done for a mirrored row with an assistant reply', () => { const mirrored = makeMirroredAgent(CLOUD_WORKTREE) const container = renderRow({ ...mirrored, - entry: { ...mirrored.entry, prompt: 'Fix the login redirect' } + entry: { ...mirrored.entry, lastAssistantMessage: 'Fixed the redirect.' } }) expect(container.textContent).not.toContain('Needs sign-in') }) + it('ignores sessionBoundary: turn evidence alone decides', () => { + const finished = makeAgent(CLOUD_WORKTREE, false) + const container = renderRow({ + ...finished, + entry: { ...finished.entry, sessionBoundary: true } + }) + expect(container.textContent).toContain('Done - Claude') + }) + + it('shows Sign-in expired for a revoked Orca account sign-in', () => { + setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'revoked' })) + const container = renderRow(makeMirroredAgent(CLOUD_WORKTREE)) + expect(container.textContent).toContain('Sign-in expired - Claude') + }) + + it('shows nothing extra while the Orca account path is paused (providerState disabled)', () => { + const paused = accounts({ state: 'none' }) + if (paused.load.kind === 'ready') { + paused.load.status.credentials.providerEnabled = { claude: false, codex: true } + paused.load.status.credentials.providerState = { claude: 'disabled', codex: 'on' } + } + setOrcaCloudAgentAccountsStateForTest(paused) + const container = renderRow(makeMirroredAgent(CLOUD_WORKTREE)) + expect(container.textContent).toContain('Done - Claude') + }) + it('leaves the same mirrored shape on a local workspace unchanged', () => { const container = renderRow(makeMirroredAgent(LOCAL_WORKTREE)) expect(container.textContent).toContain('Done - Claude') @@ -278,7 +304,35 @@ describe('DashboardAgentRow (full row) on an Orca Cloud workspace', () => { const container = renderFullRow(makeAgent(LOCAL_WORKTREE, true)) expect(fullRowLabel(container)).toBe('Done') expect(container.textContent).not.toContain('Needs sign-in') - expect(container.querySelector('button[title*="Agent accounts"]')).toBeNull() + expect(container.querySelector('[data-cloud-sign-in-status]')).toBeNull() + }) +}) + +describe('a row that renders before the Agent accounts read lands', () => { + it('picks up Needs sign-in once the accounts load (restored row)', () => { + setOrcaCloudAgentAccountsStateForTest({ + ...accounts({ state: 'none' }), + load: { kind: 'loading' } + }) + const container = renderRow(makeMirroredAgent(CLOUD_WORKTREE)) + expect(container.textContent).toContain('Done - Claude') + act(() => setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'none' }))) + expect(container.textContent).toContain('Needs sign-in - Claude') + }) + + it('picks it up once the cloud environment is known', () => { + useAppStore.setState({ runtimeEnvironments: [] }) + const container = renderFullRow(makeMirroredAgent(CLOUD_WORKTREE)) + expect(fullRowLabel(container)).toBe('Done') + act(() => useAppStore.setState({ runtimeEnvironments: [cloudEnvironment] })) + expect(fullRowLabel(container)).toBe('Needs sign-in') + }) + + it('goes back to Done when Claude is set up', () => { + const container = renderRow(makeMirroredAgent(CLOUD_WORKTREE)) + expect(container.textContent).toContain('Needs sign-in - Claude') + act(() => setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'active' }))) + expect(container.textContent).toContain('Done - Claude') }) }) @@ -288,6 +342,16 @@ function click(element: Element): void { }) } +function statusButtons(container: HTMLElement): HTMLButtonElement[] { + return Array.from(container.querySelectorAll('[data-cloud-sign-in-status]')) +} + +/** Keyboard focus opens the app tooltip; read its content, not a title attribute. */ +function focusTooltip(button: HTMLButtonElement): string | null { + act(() => button.focus()) + return document.body.querySelector('[role="tooltip"]')?.textContent ?? null +} + describe.each([ ['compact', renderRow], ['full', renderFullRow] @@ -296,13 +360,33 @@ describe.each([ useAppStore.setState({ activeView: 'terminal', settingsNavigationTarget: null }) }) - it('names where to set up, and clicking the status opens Agent accounts, not the pane', () => { + it('has a focusable dot and text, with no native title', () => { + const [dot, text] = statusButtons(render(makeAgent(CLOUD_WORKTREE, true))) + expect(dot.getAttribute('aria-label')).toBe('Needs sign-in') + expect(text.textContent).toBe('Needs sign-in') + expect(dot.hasAttribute('title') || text.hasAttribute('title')).toBe(false) + }) + + it('shows the app tooltip on keyboard focus of the text', () => { + const [, text] = statusButtons(render(makeAgent(CLOUD_WORKTREE, true))) + expect(focusTooltip(text)).toBe('Set up once in Settings → Agent accounts') + }) + + it('shows the app tooltip on keyboard focus of the dot', () => { + const [dot] = statusButtons(render(makeAgent(CLOUD_WORKTREE, true))) + expect(focusTooltip(dot)).toBe('Set up once in Settings → Agent accounts') + }) + + it('tells an expired sign-in to renew', () => { + setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'expired' })) + const [, text] = statusButtons(render(makeAgent(CLOUD_WORKTREE, true))) + expect(focusTooltip(text)).toBe('Renew in Settings → Agent accounts') + }) + + it('clicking the text opens Agent accounts, not the pane', () => { const onActivate = vi.fn() - const container = render(makeAgent(CLOUD_WORKTREE, true), onActivate) - const text = container.querySelector('button[title]') - expect(text?.getAttribute('title')).toBe('Set up once in Settings → Agent accounts') - expect(text?.textContent).toBe('Needs sign-in') - click(text!) + const [, text] = statusButtons(render(makeAgent(CLOUD_WORKTREE, true), onActivate)) + click(text) expect(onActivate).not.toHaveBeenCalled() expect(useAppStore.getState().activeView).toBe('settings') expect(useAppStore.getState().settingsNavigationTarget).toMatchObject({ @@ -311,24 +395,14 @@ describe.each([ }) }) - it('opens Agent accounts from the dot too', () => { + it('clicking the dot opens Agent accounts too', () => { const onActivate = vi.fn() - const container = render(makeAgent(CLOUD_WORKTREE, true), onActivate) - const dot = container.querySelector('button:not([title])') - expect(dot).not.toBeNull() - click(dot!) + const [dot] = statusButtons(render(makeAgent(CLOUD_WORKTREE, true), onActivate)) + click(dot) expect(onActivate).not.toHaveBeenCalled() expect(useAppStore.getState().activeView).toBe('settings') }) - it('tells an expired sign-in to renew', () => { - setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'expired' })) - const container = render(makeAgent(CLOUD_WORKTREE, true)) - expect(container.querySelector('button[title]')?.getAttribute('title')).toBe( - 'Renew in Settings → Agent accounts' - ) - }) - it('still activates the pane when the rest of the row is clicked', () => { const onActivate = vi.fn() const container = render(makeAgent(CLOUD_WORKTREE, true), onActivate) diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.tsx index 3a32d1ecc15..96b080d7b46 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.tsx @@ -27,7 +27,10 @@ import { import { resolveRowProgramStatus } from '@/lib/program-status/agent-row-presentation' import { useTranslate, type Translate } from '@/i18n/use-translate' import { useCloudAgentRowStatus } from '@/components/orca-cloud/use-cloud-agent-row-sign-in' -import { CloudAgentRowSignInTarget } from '@/components/orca-cloud/CloudAgentRowSignInTarget' +import { + CloudAgentRowSignInDot, + CloudAgentRowSignInTarget +} from '@/components/orca-cloud/CloudAgentRowSignInTarget' function getCompactAgentPrimary( agent: DashboardAgentRowData, @@ -147,7 +150,8 @@ export const CompactAgentRow = React.memo(function CompactAgentRow({ const dotState = cloudStatus?.dotState ?? reportedDotState const conversationName = useAgentRowConversationName(agent) const primary = cloudStatus?.label ?? getCompactAgentPrimary(agent, conversationName) - const signInTooltip = cloudStatus?.tooltip ?? null + // Send-target mode owns row clicks, so only outside it is the status a link to Settings. + const signIn = cloudStatus?.tooltip ? cloudStatus : null const isLineageChild = agent.lineage?.depth === 1 // Hold assistant text per positive turn clock; commit in an effect so discarded renders cannot cache messages. const turn = agent.entry.stateStartedAt @@ -240,10 +244,8 @@ export const CompactAgentRow = React.memo(function CompactAgentRow({ ) : ( <> {/* Show the actionable disabled reason over every hit area. */} - {signInTooltip ? ( - - - + {signIn ? ( + ) : ( - {signInTooltip ? ( + {signIn ? ( {leadingText} diff --git a/src/renderer/src/lib/orca-cloud/cloud-agent-launch-hold.ts b/src/renderer/src/lib/orca-cloud/cloud-agent-launch-hold.ts index 370a134ebf8..bd114f73f2c 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-agent-launch-hold.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-agent-launch-hold.ts @@ -4,7 +4,7 @@ // offered: no hold here; the per-workspace sign-in (#40228's gate) runs and the strip shows it. import { useSyncExternalStore } from 'react' import type { HostAgentSignInAgent } from '../../../../shared/host-agent-sign-in-status' -import { orcaCloudAgentCoverage } from './orca-cloud-agent-accounts-model' +import { orcaCloudAgentCoverageFromAccounts } from './orca-cloud-agent-accounts-model' import { ensureFreshOrcaCloudAgentAccounts, readOrcaCloudAgentAccounts, @@ -19,10 +19,9 @@ export function cloudAgentStripReason( agent: HostAgentSignInAgent, accounts: Pick ): CloudAgentStripReason | null { - if (accounts.load.kind !== 'ready') { - return null - } - switch (orcaCloudAgentCoverage(agent, accounts.load.status, accounts.keyKinds[agent]).kind) { + switch (orcaCloudAgentCoverageFromAccounts(agent, accounts)?.kind) { + case undefined: + return null case 'expired': return 'accountExpired' case 'killSwitch': diff --git a/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts b/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts index 9408d5164ef..447b9dd4f94 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts @@ -1,6 +1,8 @@ -// Private layer, Orca Cloud only: a cloud Claude/Codex pane that started without a sign-in sits at -// its own "Not logged in" screen, but SessionStart reports it as done. The sidebar row says why -// instead of "Done", using the Orca account's Agent accounts and the sandbox's own sign-in report. +// Private layer, Orca Cloud only: a cloud Claude/Codex pane whose agent isn't signed in sits at its +// own "Not logged in" screen, yet its row would read "Done". The row says why instead. The source of +// truth is the Orca account's Agent accounts (credential state and providerState, via the shared +// coverage selector), combined with "no turn finished"; the sandbox's own sign-in report can +// clear it (signedIn) or add to it (signedOut). import type { AgentDotState } from '@/components/AgentStateDot' import type { Translate } from '@/i18n/use-translate' import type { AgentStatusEntry } from '../../../../shared/agent-status/contracts/agent-status-types' @@ -9,43 +11,38 @@ import { type HostAgentSignInAgent, type HostAgentSignInEntry } from '../../../../shared/host-agent-sign-in-status' -import { orcaCloudAgentCoverage } from './orca-cloud-agent-accounts-model' -import type { OrcaCloudAgentAccountsState } from './orca-cloud-agent-accounts-store' +import { + orcaCloudAgentCoverageFromAccounts, + type OrcaCloudAgentAccountsRead +} from './orca-cloud-agent-accounts-model' -export type CloudAgentRowSignIn = 'notSignedIn' | 'expired' +export type CloudAgentRowSignIn = 'needsSignIn' | 'expired' export function cloudRowSignInAgent(agentType: string): HostAgentSignInAgent | null { return HOST_AGENT_SIGN_IN_AGENTS.find((agent) => agent === agentType) ?? null } -/** The entry fields that show whether this session has finished a turn. */ +/** The turn evidence on a row: what only a turn that ran and ended leaves behind. */ export type CloudRowTurnEvidence = Pick< AgentStatusEntry, - 'sessionBoundary' | 'prompt' | 'lastAssistantMessage' | 'stateHistory' | 'turnEndedAt' + 'lastAssistantMessage' | 'stateHistory' | 'turnEndedAt' > /** - * True when nothing shows a finished turn. A local hook row says so with `sessionBoundary`. A row - * mirrored from a cloud host can arrive without it: once the agent's title is newer than the - * SessionStart hook (or the hook goes stale), the host projects a bare title-derived `done` - * (runtime-mobile-agent-status-builder's last branch). So an empty prompt, no reply, no history - * and no turn end count too. + * True when no turn has finished: no state history, no turn end and no assistant reply. Hook + * markers such as sessionBoundary are not used: a row mirrored from a cloud host can lack them. */ export function hasNoFinishedTurn(entry: CloudRowTurnEvidence): boolean { - if (entry.sessionBoundary === true) { - return true - } return ( - !entry.prompt?.trim() && - !entry.lastAssistantMessage?.trim() && (entry.stateHistory?.length ?? 0) === 0 && - entry.turnEndedAt === undefined + entry.turnEndedAt === undefined && + !entry.lastAssistantMessage?.trim() ) } /** - * Only a row that has not finished a turn this session can be waiting on sign-in: a finished - * turn proves the agent reached its provider, so its Done stays. + * Only a row that has not finished a turn can be waiting on sign-in: a finished turn proves the + * agent reached its provider, so its Done stays. */ export function isCloudRowSignInCandidate(row: { agentType: string @@ -61,25 +58,26 @@ export function isCloudRowSignInCandidate(row: { ) } -/** The sandbox's own verdict wins; without one, the Orca account's coverage decides. */ +/** + * Agent accounts decide: not set up -> needsSignIn, expired or revoked -> expired. A sandbox that + * reports the agent signedIn (an account placeholder, a key, or a /login there) clears the row; + * one that reports signedOut needs sign-in too. A paused or never-offered provider, or a read + * not ready yet, shows nothing; the row updates when the read lands. + */ export function cloudAgentRowSignIn( agent: HostAgentSignInAgent, - accounts: Pick, + accounts: OrcaCloudAgentAccountsRead, hostEntry: HostAgentSignInEntry | null ): CloudAgentRowSignIn | null { - // Signed in on the sandbox (account placeholder, key or a /login there): nothing to show. if (hostEntry?.state === 'signedIn' || hostEntry?.state === 'notInstalled') { return null } - const coverage = - accounts.load.kind === 'ready' - ? orcaCloudAgentCoverage(agent, accounts.load.status, accounts.keyKinds[agent]).kind - : null + const coverage = orcaCloudAgentCoverageFromAccounts(agent, accounts)?.kind if (coverage === 'expired') { return 'expired' } - if (hostEntry?.state === 'signedOut' || coverage === 'notSetUp') { - return 'notSignedIn' + if (coverage === 'notSetUp' || hostEntry?.state === 'signedOut') { + return 'needsSignIn' } return null } diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-model.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-model.ts index 7b463b0d10c..9373ba48686 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-model.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-model.ts @@ -10,6 +10,7 @@ import { type OrcaCloudAgentSetupFailure, type OrcaCloudAgentsStatus } from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' +import type { OrcaCloudAgentAccountsState } from './orca-cloud-agent-accounts-store' /** The names that make a key cover an agent, as the control plane counts them (coveredByKey). */ const KEY_NAMES: Record = { @@ -148,3 +149,20 @@ export function orcaCloudAgentCoverage( ? { kind: 'expired' } : { kind: 'notSetUp' } } + +/** The renderer's one Agent accounts read, as the coverage selectors take it. */ +export type OrcaCloudAgentAccountsRead = Pick + +/** + * One agent's coverage from the shared Agent accounts read; null until that read is ready. + * The single selector for every cloud surface that reacts to it: the launch hold and strip + * (cloudAgentStripReason) and the sidebar/dashboard agent rows (cloudAgentRowSignIn). + */ +export function orcaCloudAgentCoverageFromAccounts( + agent: OrcaCloudAccountAgent, + accounts: OrcaCloudAgentAccountsRead +): OrcaCloudAgentCoverage | null { + return accounts.load.kind === 'ready' + ? orcaCloudAgentCoverage(agent, accounts.load.status, accounts.keyKinds[agent]) + : null +} From 67bdb68ed656bb8dca735e4b824f73a9307dc762 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 17:51:48 -0800 Subject: [PATCH 007/149] fix(cloud): sign-in row state sticks while Agent accounts say not set up, expired or revoked design-squad P1-P3 on #310 from the m4air run: - P1: after a restart leatherback fell back to the title-derived row ("Claude Code - Idle": prompt = title label, lastAssistantMessage = "Idle"), whose message made "no turn finished" false. While Agent accounts say not set up / expired / revoked, the sign-in state now wins over every done/idle/unverifiable row shape; only a sign-in made on the sandbox (cliLogin) clears it, not the Orca-account placeholder the sandbox reports as an API key. Covered accounts with a signed-out sandbox clear once a turn ends after the account became active (first covered read). - P2: sign-in rows use the catalog name (Claude/Codex), never the title or a stale reply. - P2: the tooltip opens below, aligned to the start, so the workspace name stays visible. - P3: the full row reads "Needs sign-in - Claude" / "Sign-in expired - Claude" and drops the stale message line. --- .../dashboard/DashboardAgentRow.tsx | 2 +- .../orca-cloud/CloudAgentRowSignInTarget.tsx | 78 +++--- .../orca-cloud/use-cloud-agent-row-sign-in.ts | 18 +- .../CompactAgentRowCloudSignIn.fixture.tsx | 30 +++ ...d-compact-agent-row.cloud-sign-in.test.tsx | 247 +++++++++++------- .../worktree-card-compact-agent-row.tsx | 6 +- .../cloud-agent-account-active-since.ts | 47 ++++ .../lib/orca-cloud/cloud-agent-row-sign-in.ts | 78 +++--- 8 files changed, 324 insertions(+), 182 deletions(-) create mode 100644 src/renderer/src/lib/orca-cloud/cloud-agent-account-active-since.ts diff --git a/src/renderer/src/components/dashboard/DashboardAgentRow.tsx b/src/renderer/src/components/dashboard/DashboardAgentRow.tsx index 10a436f21b3..1e867dcc7d1 100644 --- a/src/renderer/src/components/dashboard/DashboardAgentRow.tsx +++ b/src/renderer/src/components/dashboard/DashboardAgentRow.tsx @@ -423,7 +423,7 @@ const DashboardAgentRow = React.memo(function DashboardAgentRow({ expanded={expanded} isInterrupted={isInterrupted} stoppedByUser={agentMainAgentVerdict(agent.entry) === 'cancellation'} - lastAssistantMessage={lastAssistantMessage} + lastAssistantMessage={cloudStatus ? '' : lastAssistantMessage} />
) diff --git a/src/renderer/src/components/orca-cloud/CloudAgentRowSignInTarget.tsx b/src/renderer/src/components/orca-cloud/CloudAgentRowSignInTarget.tsx index 3a666db9a8b..daba491c714 100644 --- a/src/renderer/src/components/orca-cloud/CloudAgentRowSignInTarget.tsx +++ b/src/renderer/src/components/orca-cloud/CloudAgentRowSignInTarget.tsx @@ -4,14 +4,12 @@ import React, { useCallback } from 'react' import { useAppStore } from '@/store' import { cn } from '@/lib/utils' import { AgentStateDot } from '@/components/AgentStateDot' -import { - StateIndicatorTooltip, - type StateIndicatorTooltipSide -} from '@/components/StateIndicatorTooltip' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { STATE_INDICATOR_TOOLTIP_DELAY_MS } from '@/components/StateIndicatorTooltip' import { openOrcaCloudAgentAccounts } from '@/components/new-workspace/OrcaCloudAgentSetupRow' -/** What the status shows: its label, and the tooltip naming the fix. */ -export type CloudAgentRowStatusText = { label: string; tooltip: string | null } +/** What the status shows: its label, the agent's catalog name, and the tooltip naming the fix. */ +export type CloudAgentRowStatusText = { label: string; agentName: string; tooltip: string | null } /** The composer's "Set up once" target, plus opening Settings, which the sidebar has closed. */ export function openCloudAgentAccountsSettings(): void { @@ -19,17 +17,18 @@ export function openCloudAgentAccountsSettings(): void { useAppStore.getState().openSettingsPage() } -/** A focusable status button: the app tooltip names the fix on hover and on keyboard focus. */ +/** + * A focusable status button: the app tooltip names the fix on hover and on keyboard focus. It + * opens below, from the row's start, so the workspace name above the row stays visible. + */ export function CloudAgentRowSignInTarget({ tooltip, - tooltipSide = 'top', ariaLabel, className, children }: { - /** Null shows no tooltip (StateIndicatorTooltip passes the button through). */ + /** Null shows no tooltip. */ tooltip: string | null - tooltipSide?: StateIndicatorTooltipSide /** For the dot, whose button has no text of its own. */ ariaLabel?: string className?: string @@ -39,49 +38,58 @@ export function CloudAgentRowSignInTarget({ e.stopPropagation() openCloudAgentAccountsSettings() }, []) + const button = ( + + ) + if (tooltip === null) { + return button + } return ( - - - + + {button} + + {tooltip} + + ) } /** The status dot: the attention dot, opening Agent accounts. Its tooltip is the button's. */ export function CloudAgentRowSignInDot({ status, - tooltipSide, size }: { status: CloudAgentRowStatusText - tooltipSide?: StateIndicatorTooltipSide size: 'sm' | 'md' }): React.JSX.Element { return ( ) } -/** The full row's label slot: the text links to Agent accounts; the rest of the slot opens the pane. */ +/** + * The full row's label slot: "Needs sign-in - Claude", the status linking to Agent accounts and the + * agent's catalog name after it; the rest of the slot opens the pane. + */ export function CloudAgentRowSignInLabel({ status, emphasis @@ -105,6 +113,12 @@ export function CloudAgentRowSignInLabel({ > {status.label} + + {' - '} + {status.agentName} +
) } diff --git a/src/renderer/src/components/orca-cloud/use-cloud-agent-row-sign-in.ts b/src/renderer/src/components/orca-cloud/use-cloud-agent-row-sign-in.ts index e2c7ce22b73..98464fe0292 100644 --- a/src/renderer/src/components/orca-cloud/use-cloud-agent-row-sign-in.ts +++ b/src/renderer/src/components/orca-cloud/use-cloud-agent-row-sign-in.ts @@ -25,6 +25,8 @@ import { readHostAgentSignInReport, subscribeHostAgentSignInReports } from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client' +import { cloudAgentAccountActiveSince } from '@/lib/orca-cloud/cloud-agent-account-active-since' +import { HOST_AGENT_SIGN_IN_AGENT_NAME } from '../../../../shared/host-agent-sign-in-status' import { isOrcaCloudRuntimeEnvironment } from '../../../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' const subscribeNothing = (): (() => void) => () => {} @@ -42,8 +44,8 @@ function orcaCloudEnvironmentIdForWorktree(state: AppState, worktreeId: string): } /** - * Why a cloud agent row that never ran a turn is not "Done": its agent isn't signed in. - * Null for local, SSH and paired hosts, and for any row that has finished a turn. + * Why a cloud agent row at rest is not "Done" or "Idle": its agent isn't signed in. + * Null for local, SSH and paired hosts, and for working or waiting rows. */ export function useCloudAgentRowSignIn( agent: Pick, @@ -52,7 +54,6 @@ export function useCloudAgentRowSignIn( const candidate = isCloudRowSignInCandidate({ agentType: agent.agentType, dotState, - entry: agent.entry, isChildRow: agent.childRow !== undefined }) const worktreeId = agent.tab.worktreeId @@ -81,12 +82,17 @@ export function useCloudAgentRowSignIn( if (!environmentId || !signInAgent) { return null } - return cloudAgentRowSignIn(signInAgent, accounts, hostAgentSignInEntry(report, signInAgent)) + return cloudAgentRowSignIn(signInAgent, accounts, hostAgentSignInEntry(report, signInAgent), { + turnEndedAt: agent.entry.turnEndedAt, + activeSince: cloudAgentAccountActiveSince(signInAgent) + }) } export type CloudAgentRowStatus = { dotState: AgentDotState label: string + /** The catalog name ("Claude", "Codex"), never a terminal title such as "Claude Code". */ + agentName: string /** Null in send-target mode, which owns row clicks; otherwise the status links to Settings. */ tooltip: string | null } @@ -100,12 +106,14 @@ export function useCloudAgentRowStatus( ): CloudAgentRowStatus | null { const t = useTranslate() const signIn = useCloudAgentRowSignIn(agent, dotState) - if (!signIn) { + const signInAgent = cloudRowSignInAgent(agent.agentType) + if (!signIn || !signInAgent) { return null } return { dotState: 'permission', label: cloudAgentRowSignInLabel(signIn, t), + agentName: HOST_AGENT_SIGN_IN_AGENT_NAME[signInAgent], tooltip: sendTargetStatus ? null : cloudAgentRowSignInTooltip(signIn, t) } } diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/CompactAgentRowCloudSignIn.fixture.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/CompactAgentRowCloudSignIn.fixture.tsx index 090ba4b61de..d19e8522a1a 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/CompactAgentRowCloudSignIn.fixture.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/activity/CompactAgentRowCloudSignIn.fixture.tsx @@ -190,3 +190,33 @@ export const fullClaudeSignInExpiredTooltip = defineFixture({ ), interact: focusStatusText }) + +/** After a restart the pane can fall back to its title-derived row ("Claude Code - Idle"). */ +function titleDerivedRow(): DashboardAgentRow { + const base = row('claude', null) + return { + ...base, + state: 'idle', + startedAt: 0, + entry: { + ...base.entry, + state: 'working', + prompt: 'Claude Code', + lastAssistantMessage: 'Idle', + stateStartedAt: now, + updatedAt: now + } + } +} + +/** Revoked account, title-derived row after a restart: still "Sign-in expired - Claude". */ +export const claudeRevokedAfterRestart = cloudRowFixture( + accounts({ state: 'revoked' }, { state: 'none' }), + titleDerivedRow() +) + +export const fullClaudeRevokedAfterRestart = cloudRowFixture( + accounts({ state: 'revoked' }, { state: 'none' }), + titleDerivedRow(), + 'full' +) diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx index 12ef1abd242..9d5bee296d6 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx @@ -18,6 +18,7 @@ import type * as HostAgentSignInClient from '@/runtime/provider-accounts/sign-in import type { PublicKnownRuntimeEnvironment } from '../../../../../../shared/remote-runtime/host-catalog/runtime-environments' import { makeTabWithIds } from '@/components/activity/ActivityPrototypePage-test-fixtures' import DashboardAgentRow from '@/components/dashboard/DashboardAgentRow' +import { _resetCloudAgentAccountActiveSinceForTest } from '@/lib/orca-cloud/cloud-agent-account-active-since' import { CompactAgentRow } from './worktree-card-compact-agent-row' Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) @@ -118,6 +119,41 @@ function makeMirroredAgent(worktreeId: string): DashboardAgentRowData { } } +/** + * The row leatherback showed 30 s after a restart ("Claude Code - Idle", grey dot, "now"): the + * title-derived fallback row (worktree-title-derived-agent-rows), built when no hook entry is + * live. Its prompt is the title label and its message the translated "Idle". + */ +function makeTitleDerivedAgent(worktreeId: string): DashboardAgentRowData { + return { + paneKey: 'tab-1:leaf-1', + tab: makeTabWithIds('tab-1', worktreeId), + agentType: 'claude', + rowSource: 'live', + state: 'idle', + startedAt: 0, + entry: { + paneKey: 'tab-1:leaf-1', + state: 'working', + prompt: 'Claude Code', + updatedAt: 2000, + stateStartedAt: 2000, + stateHistory: [], + agentType: 'claude', + terminalTitle: '✳ Claude Code', + lastAssistantMessage: 'Idle', + observation: { + origin: 'title', + authorityId: 'title-derived', + incarnation: 0, + revision: 2000, + observedAt: 2000, + kind: 'snapshot' + } + } + } +} + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the row reads only id, name and source. const cloudEnvironment = { id: CLOUD_ENV, @@ -136,12 +172,18 @@ afterEach(() => { act(() => root?.unmount()) document.body.replaceChildren() _resetHostAgentSignInReportsForTest() + _resetCloudAgentAccountActiveSinceForTest() }) function renderRow(agent: DashboardAgentRowData, onActivate = () => {}): HTMLElement { const container = document.createElement('div') document.body.appendChild(container) root = createRoot(container) + rerenderRow(agent, onActivate) + return container +} + +function rerenderRow(agent: DashboardAgentRowData, onActivate = () => {}): void { act(() => { root!.render( @@ -149,99 +191,106 @@ function renderRow(agent: DashboardAgentRowData, onActivate = () => {}): HTMLEle ) }) - return container } -describe('CompactAgentRow on an Orca Cloud workspace whose agent is not signed in', () => { +function signedIn(method: 'apiKey' | 'cliLogin' | 'orcaAccount'): void { + rememberHostAgentSignInReport(CLOUD_ENV, { + checkedAt: 1, + agents: [{ agent: 'claude', state: 'signedIn', method }] + }) +} + +function signedOut(): void { + rememberHostAgentSignInReport(CLOUD_ENV, { + checkedAt: 1, + agents: [{ agent: 'claude', state: 'signedOut' }] + }) +} + +describe('CompactAgentRow on an Orca Cloud workspace: Agent accounts decide', () => { it('shows Needs sign-in instead of Done when Claude is not set up', () => { const container = renderRow(makeAgent(CLOUD_WORKTREE, true)) expect(container.textContent).toContain('Needs sign-in - Claude') expect(container.textContent).not.toContain('Done') }) - it('shows Sign-in expired when the Orca account sign-in expired', () => { + it('shows Sign-in expired for an expired or revoked Orca account sign-in', () => { setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'expired' })) const container = renderRow(makeAgent(CLOUD_WORKTREE, true)) expect(container.textContent).toContain('Sign-in expired - Claude') + act(() => setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'revoked' }))) + expect(container.textContent).toContain('Sign-in expired - Claude') + }) + + it('wins over the title-derived idle row seen after a restart, and never says "Claude Code"', () => { + setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'revoked' })) + const container = renderRow(makeTitleDerivedAgent(CLOUD_WORKTREE)) + expect(container.textContent).toContain('Sign-in expired - Claude') + expect(container.textContent).not.toContain('Claude Code') + expect(container.textContent).not.toContain('Idle') + }) + + it('sticks across the row shapes that follow a restart', () => { + setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'revoked' })) + const container = renderRow(makeMirroredAgent(CLOUD_WORKTREE)) + expect(container.textContent).toContain('Sign-in expired - Claude') + rerenderRow(makeTitleDerivedAgent(CLOUD_WORKTREE)) + expect(container.textContent).toContain('Sign-in expired - Claude') + rerenderRow(makeAgent(CLOUD_WORKTREE, false)) + expect(container.textContent).toContain('Sign-in expired - Claude') + rerenderRow({ ...makeMirroredAgent(CLOUD_WORKTREE), state: 'unverifiable' }) + expect(container.textContent).toContain('Sign-in expired - Claude') + }) + + it('wins over turn evidence while the account is not set up', () => { + const container = renderRow(makeAgent(CLOUD_WORKTREE, false)) + expect(container.textContent).toContain('Needs sign-in - Claude') + }) + + it('is not cleared by the sandbox reporting the Orca-account placeholder as signed in', () => { + setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'revoked' })) + signedIn('apiKey') + const container = renderRow(makeAgent(CLOUD_WORKTREE, true)) + expect(container.textContent).toContain('Sign-in expired - Claude') }) - it('trusts the sandbox report: signedOut shows Needs sign-in even when the account covers it', () => { - setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'active' })) - rememberHostAgentSignInReport(CLOUD_ENV, { - checkedAt: 1, - agents: [{ agent: 'claude', state: 'signedOut' }] - }) - const container = renderRow(makeAgent(CLOUD_WORKTREE, true)) - expect(container.textContent).toContain('Needs sign-in - Claude') + it('is cleared by a sign-in made on the sandbox itself (/login there)', () => { + signedIn('cliLogin') + expect(renderRow(makeAgent(CLOUD_WORKTREE, true)).textContent).toContain('Done - Claude') }) - it('keeps Done when the sandbox reports Claude signed in (a /login there)', () => { - rememberHostAgentSignInReport(CLOUD_ENV, { - checkedAt: 1, - agents: [{ agent: 'claude', state: 'signedIn', method: 'cliLogin' }] - }) - const container = renderRow(makeAgent(CLOUD_WORKTREE, true)) - expect(container.textContent).toContain('Done - Claude') + it('clears when the account becomes active', () => { + setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'revoked' })) + const container = renderRow(makeTitleDerivedAgent(CLOUD_WORKTREE)) + expect(container.textContent).toContain('Sign-in expired - Claude') + act(() => setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'active' }))) + expect(container.textContent).toContain('Claude Code - Idle') }) it('keeps Done for a covered agent idle after a turn', () => { setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'active' })) + expect(renderRow(makeAgent(CLOUD_WORKTREE, false)).textContent).toContain('Done - Claude') + }) + + it('covered but the sandbox is signed out: needs sign-in until a turn ends after the account became active', () => { + setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'active' })) + signedOut() const container = renderRow(makeAgent(CLOUD_WORKTREE, false)) - expect(container.textContent).toContain('Done - Claude') - }) - - it('keeps Done after a finished turn even when the account is not set up', () => { - const container = renderRow(makeAgent(CLOUD_WORKTREE, false)) - expect(container.textContent).toContain('Done - Claude') - }) - - it('leaves a local workspace unchanged', () => { - const container = renderRow(makeAgent(LOCAL_WORKTREE, true)) - expect(container.textContent).toContain('Done - Claude') - expect(container.textContent).not.toContain('Needs sign-in') - }) - - it('shows Needs sign-in for the row mirrored from the cloud host (no sessionBoundary)', () => { - const container = renderRow(makeMirroredAgent(CLOUD_WORKTREE)) expect(container.textContent).toContain('Needs sign-in - Claude') - expect(container.textContent).not.toContain('Done') - }) - - it('keeps Done for a mirrored row with a finished turn', () => { - const mirrored = makeMirroredAgent(CLOUD_WORKTREE) - const container = renderRow({ - ...mirrored, - entry: { - ...mirrored.entry, - stateHistory: [{ state: 'working', prompt: '', startedAt: 600 }], - turnEndedAt: 1000 - } - }) - expect(container.textContent).toContain('Done - Claude') - }) - - it('keeps Done for a mirrored row with an assistant reply', () => { - const mirrored = makeMirroredAgent(CLOUD_WORKTREE) - const container = renderRow({ - ...mirrored, - entry: { ...mirrored.entry, lastAssistantMessage: 'Fixed the redirect.' } - }) - expect(container.textContent).not.toContain('Needs sign-in') - }) - - it('ignores sessionBoundary: turn evidence alone decides', () => { const finished = makeAgent(CLOUD_WORKTREE, false) - const container = renderRow({ - ...finished, - entry: { ...finished.entry, sessionBoundary: true } - }) + rerenderRow({ ...finished, entry: { ...finished.entry, turnEndedAt: Date.now() + 60_000 } }) expect(container.textContent).toContain('Done - Claude') }) - it('shows Sign-in expired for a revoked Orca account sign-in', () => { + it('leaves working rows alone', () => { setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'revoked' })) - const container = renderRow(makeMirroredAgent(CLOUD_WORKTREE)) - expect(container.textContent).toContain('Sign-in expired - Claude') + const working = makeAgent(CLOUD_WORKTREE, true) + const container = renderRow({ + ...working, + state: 'working', + entry: { ...working.entry, state: 'working', prompt: 'Fix the login redirect' } + }) + expect(container.textContent).not.toContain('Sign-in expired') }) it('shows nothing extra while the Orca account path is paused (providerState disabled)', () => { @@ -251,13 +300,15 @@ describe('CompactAgentRow on an Orca Cloud workspace whose agent is not signed i paused.load.status.credentials.providerState = { claude: 'disabled', codex: 'on' } } setOrcaCloudAgentAccountsStateForTest(paused) - const container = renderRow(makeMirroredAgent(CLOUD_WORKTREE)) - expect(container.textContent).toContain('Done - Claude') + expect(renderRow(makeMirroredAgent(CLOUD_WORKTREE)).textContent).toContain('Done - Claude') }) - it('leaves the same mirrored shape on a local workspace unchanged', () => { - const container = renderRow(makeMirroredAgent(LOCAL_WORKTREE)) + it('leaves a local workspace unchanged, whatever the row shape', () => { + setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'revoked' })) + const container = renderRow(makeAgent(LOCAL_WORKTREE, true)) expect(container.textContent).toContain('Done - Claude') + rerenderRow(makeTitleDerivedAgent(LOCAL_WORKTREE)) + expect(container.textContent).toContain('Claude Code - Idle') }) }) @@ -280,15 +331,18 @@ function fullRowLabel(container: HTMLElement): string | null { } describe('DashboardAgentRow (full row) on an Orca Cloud workspace', () => { - it('shows Needs sign-in instead of Done when Claude is not set up', () => { + it('reads "Needs sign-in - Claude" when Claude is not set up', () => { const container = renderFullRow(makeAgent(CLOUD_WORKTREE, true)) - expect(fullRowLabel(container)).toBe('Needs sign-in') + expect(fullRowLabel(container)).toBe('Needs sign-in - Claude') expect(container.querySelector('[aria-label="Needs attention"]')).not.toBeNull() }) - it('shows Sign-in expired when the Orca account sign-in expired', () => { - setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'expired' })) - expect(fullRowLabel(renderFullRow(makeAgent(CLOUD_WORKTREE, true)))).toBe('Sign-in expired') + it('reads "Sign-in expired - Claude" over the title-derived idle row', () => { + setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'revoked' })) + const container = renderFullRow(makeTitleDerivedAgent(CLOUD_WORKTREE)) + expect(fullRowLabel(container)).toBe('Sign-in expired - Claude') + expect(container.textContent).not.toContain('Claude Code') + expect(container.textContent).not.toContain('Idle') }) it('keeps Done for a covered agent idle after a turn', () => { @@ -296,28 +350,23 @@ describe('DashboardAgentRow (full row) on an Orca Cloud workspace', () => { expect(fullRowLabel(renderFullRow(makeAgent(CLOUD_WORKTREE, false)))).toBe('Done') }) - it('shows Needs sign-in for the row mirrored from the cloud host', () => { - expect(fullRowLabel(renderFullRow(makeMirroredAgent(CLOUD_WORKTREE)))).toBe('Needs sign-in') - }) - it('leaves a local workspace unchanged', () => { const container = renderFullRow(makeAgent(LOCAL_WORKTREE, true)) expect(fullRowLabel(container)).toBe('Done') - expect(container.textContent).not.toContain('Needs sign-in') expect(container.querySelector('[data-cloud-sign-in-status]')).toBeNull() }) }) describe('a row that renders before the Agent accounts read lands', () => { - it('picks up Needs sign-in once the accounts load (restored row)', () => { + it('picks up the sign-in state once the accounts load (restored row)', () => { setOrcaCloudAgentAccountsStateForTest({ ...accounts({ state: 'none' }), load: { kind: 'loading' } }) - const container = renderRow(makeMirroredAgent(CLOUD_WORKTREE)) - expect(container.textContent).toContain('Done - Claude') - act(() => setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'none' }))) - expect(container.textContent).toContain('Needs sign-in - Claude') + const container = renderRow(makeTitleDerivedAgent(CLOUD_WORKTREE)) + expect(container.textContent).toContain('Claude Code - Idle') + act(() => setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'revoked' }))) + expect(container.textContent).toContain('Sign-in expired - Claude') }) it('picks it up once the cloud environment is known', () => { @@ -325,14 +374,7 @@ describe('a row that renders before the Agent accounts read lands', () => { const container = renderFullRow(makeMirroredAgent(CLOUD_WORKTREE)) expect(fullRowLabel(container)).toBe('Done') act(() => useAppStore.setState({ runtimeEnvironments: [cloudEnvironment] })) - expect(fullRowLabel(container)).toBe('Needs sign-in') - }) - - it('goes back to Done when Claude is set up', () => { - const container = renderRow(makeMirroredAgent(CLOUD_WORKTREE)) - expect(container.textContent).toContain('Needs sign-in - Claude') - act(() => setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'active' }))) - expect(container.textContent).toContain('Done - Claude') + expect(fullRowLabel(container)).toBe('Needs sign-in - Claude') }) }) @@ -347,9 +389,9 @@ function statusButtons(container: HTMLElement): HTMLButtonElement[] { } /** Keyboard focus opens the app tooltip; read its content, not a title attribute. */ -function focusTooltip(button: HTMLButtonElement): string | null { +function focusTooltip(button: HTMLButtonElement): Element | null { act(() => button.focus()) - return document.body.querySelector('[role="tooltip"]')?.textContent ?? null + return document.body.querySelector('[role="tooltip"]') } describe.each([ @@ -362,25 +404,28 @@ describe.each([ it('has a focusable dot and text, with no native title', () => { const [dot, text] = statusButtons(render(makeAgent(CLOUD_WORKTREE, true))) - expect(dot.getAttribute('aria-label')).toBe('Needs sign-in') + expect(dot.getAttribute('aria-label')).toBe('Needs sign-in - Claude') expect(text.textContent).toBe('Needs sign-in') expect(dot.hasAttribute('title') || text.hasAttribute('title')).toBe(false) }) - it('shows the app tooltip on keyboard focus of the text', () => { + it('shows the app tooltip below and from the start on keyboard focus, clear of the name above', () => { const [, text] = statusButtons(render(makeAgent(CLOUD_WORKTREE, true))) - expect(focusTooltip(text)).toBe('Set up once in Settings → Agent accounts') + expect(focusTooltip(text)?.textContent).toBe('Set up once in Settings → Agent accounts') + const content = document.body.querySelector('[data-side]') + expect(content?.getAttribute('data-side')).toBe('bottom') + expect(content?.getAttribute('data-align')).toBe('start') }) it('shows the app tooltip on keyboard focus of the dot', () => { const [dot] = statusButtons(render(makeAgent(CLOUD_WORKTREE, true))) - expect(focusTooltip(dot)).toBe('Set up once in Settings → Agent accounts') + expect(focusTooltip(dot)?.textContent).toBe('Set up once in Settings → Agent accounts') }) it('tells an expired sign-in to renew', () => { setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'expired' })) const [, text] = statusButtons(render(makeAgent(CLOUD_WORKTREE, true))) - expect(focusTooltip(text)).toBe('Renew in Settings → Agent accounts') + expect(focusTooltip(text)?.textContent).toBe('Renew in Settings → Agent accounts') }) it('clicking the text opens Agent accounts, not the pane', () => { diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.tsx index 96b080d7b46..fc337f0c942 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.tsx @@ -168,7 +168,9 @@ export const CompactAgentRow = React.memo(function CompactAgentRow({ const held = heldMessageRef.current const stableMessage = turnHoldable && !currentMessage && held?.turn === turn ? held.message : undefined - const secondary = getCompactAgentSecondary(agent, now, stableMessage, presentation, t) + // A sign-in row names its agent by catalog name, never a stale reply or a title like "Claude Code". + const secondary = + cloudStatus?.agentName ?? getCompactAgentSecondary(agent, now, stableMessage, presentation, t) const { leadingText, trailingText } = getCompactAgentLineOrder( agent, dotState, @@ -245,7 +247,7 @@ export const CompactAgentRow = React.memo(function CompactAgentRow({ <> {/* Show the actionable disabled reason over every hit area. */} {signIn ? ( - + ) : ( () +let watching = false + +function observe(): void { + const accounts = readOrcaCloudAgentAccounts() + if (accounts.load.kind !== 'ready') { + return + } + for (const agent of HOST_AGENT_SIGN_IN_AGENTS) { + const kind = orcaCloudAgentCoverageFromAccounts(agent, accounts)?.kind + if (kind === 'account' || kind === 'key') { + if (!activeSince.has(agent)) { + activeSince.set(agent, Date.now()) + } + } else { + activeSince.delete(agent) + } + } +} + +/** Null until this renderer has seen the agent covered. */ +export function cloudAgentAccountActiveSince(agent: HostAgentSignInAgent): number | null { + if (!watching) { + watching = true + subscribeOrcaCloudAgentAccounts(observe) + } + observe() + return activeSince.get(agent) ?? null +} + +/** Tests only. */ +export function _resetCloudAgentAccountActiveSinceForTest(): void { + activeSince.clear() +} diff --git a/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts b/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts index 447b9dd4f94..e9308be89c3 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-agent-row-sign-in.ts @@ -1,11 +1,10 @@ // Private layer, Orca Cloud only: a cloud Claude/Codex pane whose agent isn't signed in sits at its -// own "Not logged in" screen, yet its row would read "Done". The row says why instead. The source of -// truth is the Orca account's Agent accounts (credential state and providerState, via the shared -// coverage selector), combined with "no turn finished"; the sandbox's own sign-in report can -// clear it (signedIn) or add to it (signedOut). +// own "Not logged in" screen, yet its row would read "Done" or "Idle". The row says why instead. +// The source of truth is the Orca account's Agent accounts (credential state and providerState, via +// the shared coverage selector). While they say not set up, expired or revoked, the sign-in state +// wins over every idle/done row shape (hook, mirrored or title-derived). import type { AgentDotState } from '@/components/AgentStateDot' import type { Translate } from '@/i18n/use-translate' -import type { AgentStatusEntry } from '../../../../shared/agent-status/contracts/agent-status-types' import { HOST_AGENT_SIGN_IN_AGENTS, type HostAgentSignInAgent, @@ -22,64 +21,61 @@ export function cloudRowSignInAgent(agentType: string): HostAgentSignInAgent | n return HOST_AGENT_SIGN_IN_AGENTS.find((agent) => agent === agentType) ?? null } -/** The turn evidence on a row: what only a turn that ran and ended leaves behind. */ -export type CloudRowTurnEvidence = Pick< - AgentStatusEntry, - 'lastAssistantMessage' | 'stateHistory' | 'turnEndedAt' -> +/** Row states that claim nothing live: a sign-in state replaces them. Working and waiting keep theirs. */ +const SIGN_IN_OVERRIDABLE_DOTS: ReadonlySet = new Set([ + 'done', + 'idle', + 'unverifiable', + 'unconfirmed' +]) -/** - * True when no turn has finished: no state history, no turn end and no assistant reply. Hook - * markers such as sessionBoundary are not used: a row mirrored from a cloud host can lack them. - */ -export function hasNoFinishedTurn(entry: CloudRowTurnEvidence): boolean { - return ( - (entry.stateHistory?.length ?? 0) === 0 && - entry.turnEndedAt === undefined && - !entry.lastAssistantMessage?.trim() - ) -} - -/** - * Only a row that has not finished a turn can be waiting on sign-in: a finished turn proves the - * agent reached its provider, so its Done stays. - */ +/** A main Claude/Codex row at rest; whether it is on Orca Cloud is checked after. */ export function isCloudRowSignInCandidate(row: { agentType: string dotState: AgentDotState - entry: CloudRowTurnEvidence isChildRow: boolean }): boolean { return ( !row.isChildRow && - (row.dotState === 'done' || row.dotState === 'idle') && - cloudRowSignInAgent(row.agentType) !== null && - hasNoFinishedTurn(row.entry) + SIGN_IN_OVERRIDABLE_DOTS.has(row.dotState) && + cloudRowSignInAgent(row.agentType) !== null ) } /** - * Agent accounts decide: not set up -> needsSignIn, expired or revoked -> expired. A sandbox that - * reports the agent signedIn (an account placeholder, a key, or a /login there) clears the row; - * one that reports signedOut needs sign-in too. A paused or never-offered provider, or a read - * not ready yet, shows nothing; the row updates when the read lands. + * Agent accounts decide. + * - Not set up -> needsSignIn; expired or revoked -> expired. These win over the row's turn + * evidence and over the sandbox reporting an Orca-account placeholder or key as signed in; only + * a sign-in made on the sandbox itself (cliLogin) clears them. + * - Covered (account or key): normal, unless the sandbox reports signedOut, and then only until a + * turn ends after the account became active (`activeSince`). + * - Paused or never offered: only a sandbox signedOut shows needsSignIn. A read not ready yet + * shows nothing; the row updates when it lands. */ export function cloudAgentRowSignIn( agent: HostAgentSignInAgent, accounts: OrcaCloudAgentAccountsRead, - hostEntry: HostAgentSignInEntry | null + hostEntry: HostAgentSignInEntry | null, + turn: { turnEndedAt?: number; activeSince: number | null } ): CloudAgentRowSignIn | null { - if (hostEntry?.state === 'signedIn' || hostEntry?.state === 'notInstalled') { + if (hostEntry?.state === 'notInstalled') { return null } const coverage = orcaCloudAgentCoverageFromAccounts(agent, accounts)?.kind - if (coverage === 'expired') { - return 'expired' + if (coverage === 'expired' || coverage === 'notSetUp') { + if (hostEntry?.state === 'signedIn' && hostEntry.method === 'cliLogin') { + return null + } + return coverage === 'expired' ? 'expired' : 'needsSignIn' } - if (coverage === 'notSetUp' || hostEntry?.state === 'signedOut') { - return 'needsSignIn' + if (hostEntry?.state !== 'signedOut') { + return null } - return null + const turnEndedSinceActive = + turn.activeSince !== null && + turn.turnEndedAt !== undefined && + turn.turnEndedAt > turn.activeSince + return turnEndedSinceActive ? null : 'needsSignIn' } export function cloudAgentRowSignInLabel(signIn: CloudAgentRowSignIn, t: Translate): string { From dfa89326446f798cb5bd9b4d4d35c5f82bac76e0 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 17:55:11 -0800 Subject: [PATCH 008/149] test(cloud): fixed clock for the turn-ended-after-active row test (no wall clock) --- ...d-compact-agent-row.cloud-sign-in.test.tsx | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx index 9d5bee296d6..78b0bfdc032 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx @@ -273,13 +273,19 @@ describe('CompactAgentRow on an Orca Cloud workspace: Agent accounts decide', () }) it('covered but the sandbox is signed out: needs sign-in until a turn ends after the account became active', () => { - setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'active' })) - signedOut() - const container = renderRow(makeAgent(CLOUD_WORKTREE, false)) - expect(container.textContent).toContain('Needs sign-in - Claude') - const finished = makeAgent(CLOUD_WORKTREE, false) - rerenderRow({ ...finished, entry: { ...finished.entry, turnEndedAt: Date.now() + 60_000 } }) - expect(container.textContent).toContain('Done - Claude') + // A fixed clock: the account is first seen covered at 5000; the row's own turn ended at 1000. + vi.useFakeTimers({ now: 5_000, toFake: ['Date'] }) + try { + setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'active' })) + signedOut() + const container = renderRow(makeAgent(CLOUD_WORKTREE, false)) + expect(container.textContent).toContain('Needs sign-in - Claude') + const finished = makeAgent(CLOUD_WORKTREE, false) + rerenderRow({ ...finished, entry: { ...finished.entry, turnEndedAt: 6_000 } }) + expect(container.textContent).toContain('Done - Claude') + } finally { + vi.useRealTimers() + } }) it('leaves working rows alone', () => { From 3ee0b3f818242fca55818a82dfd7769f3fc55dd8 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 17:58:16 -0800 Subject: [PATCH 009/149] test(cloud): row click asserts the composer's Set up once target, which cloud/integration moved to the accounts pane --- ...ee-card-compact-agent-row.cloud-sign-in.test.tsx | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx index 78b0bfdc032..790de860441 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.cloud-sign-in.test.tsx @@ -18,6 +18,7 @@ import type * as HostAgentSignInClient from '@/runtime/provider-accounts/sign-in import type { PublicKnownRuntimeEnvironment } from '../../../../../../shared/remote-runtime/host-catalog/runtime-environments' import { makeTabWithIds } from '@/components/activity/ActivityPrototypePage-test-fixtures' import DashboardAgentRow from '@/components/dashboard/DashboardAgentRow' +import { openOrcaCloudAgentAccounts } from '@/components/new-workspace/OrcaCloudAgentSetupRow' import { _resetCloudAgentAccountActiveSinceForTest } from '@/lib/orca-cloud/cloud-agent-account-active-since' import { CompactAgentRow } from './worktree-card-compact-agent-row' @@ -434,16 +435,18 @@ describe.each([ expect(focusTooltip(text)?.textContent).toBe('Renew in Settings → Agent accounts') }) - it('clicking the text opens Agent accounts, not the pane', () => { + it('clicking the text opens Agent accounts (the composer\'s "Set up once" target), not the pane', () => { + // The target is whatever the composer's "Set up once" opens; settings may move it. + openOrcaCloudAgentAccounts() + const setUpOnceTarget = useAppStore.getState().settingsNavigationTarget + useAppStore.setState({ settingsNavigationTarget: null }) const onActivate = vi.fn() const [, text] = statusButtons(render(makeAgent(CLOUD_WORKTREE, true), onActivate)) click(text) expect(onActivate).not.toHaveBeenCalled() expect(useAppStore.getState().activeView).toBe('settings') - expect(useAppStore.getState().settingsNavigationTarget).toMatchObject({ - pane: 'agent-accounts', - sectionId: 'orca-cloud' - }) + expect(useAppStore.getState().settingsNavigationTarget).toEqual(setUpOnceTarget) + expect(setUpOnceTarget).toMatchObject({ sectionId: 'orca-cloud' }) }) it('clicking the dot opens Agent accounts too', () => { From 2642b1ba92f4b05742802bc3adf92201a83f9099 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 18:07:57 -0800 Subject: [PATCH 010/149] fix(cloud): asleep workspace's terminal shows a calm line with Wake, not a reconnect toast; setup-script check waits until it's awake (RA-12) --- .../offline/CloudAsleepTerminalNotice.tsx | 36 ++++++++++ ...use-cloud-terminal-error-override.test.tsx | 7 +- .../use-cloud-terminal-error-override.ts | 33 +++++++++ .../use-cloud-terminal-error-override.tsx | 56 --------------- .../sidebar/SetupScriptPromptCard.tsx | 5 ++ .../errors/TerminalErrorToast.tsx | 4 +- .../recovery/TerminalPaneRecoveryPortals.tsx | 13 +++- .../src/i18n/en-runtime-required.json | 4 ++ src/renderer/src/i18n/locales/en.json | 3 +- .../use-cloud-recovery-context.test.ts | 68 +++++++++++++++++++ .../orca-cloud/use-cloud-recovery-context.ts | 17 ++++- 11 files changed, 180 insertions(+), 66 deletions(-) create mode 100644 src/renderer/src/components/orca-cloud/offline/CloudAsleepTerminalNotice.tsx create mode 100644 src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.ts delete mode 100644 src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.tsx create mode 100644 src/renderer/src/lib/orca-cloud/use-cloud-recovery-context.test.ts diff --git a/src/renderer/src/components/orca-cloud/offline/CloudAsleepTerminalNotice.tsx b/src/renderer/src/components/orca-cloud/offline/CloudAsleepTerminalNotice.tsx new file mode 100644 index 00000000000..e6a970f8fdd --- /dev/null +++ b/src/renderer/src/components/orca-cloud/offline/CloudAsleepTerminalNotice.tsx @@ -0,0 +1,36 @@ +import React from 'react' +import { Play } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { useTranslate } from '@/i18n/use-translate' +import { wakeCloudWorkspace } from '../cloud-workspace-actions' + +/** + * A terminal pane of an Orca Cloud workspace that is asleep (RA-12): nothing dropped and nothing to + * retry, so a calm line and Wake instead of a reconnect toast with a "Down for" counter, or a red + * error. The pane keeps its scrollback underneath. + */ +export function CloudAsleepTerminalNotice({ + workspaceId +}: { + workspaceId: string +}): React.JSX.Element { + const t = useTranslate() + return ( +
+ + {t( + 'orcaCloudWorkspace.terminal.asleepHistoryKept', + 'This workspace is asleep. Your terminal history is kept.' + )} + + +
+ ) +} diff --git a/src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.test.tsx b/src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.test.tsx index 700d28be851..1269ffd960e 100644 --- a/src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.test.tsx +++ b/src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.test.tsx @@ -52,18 +52,15 @@ describe('terminal error toast on an Orca Cloud workspace that sleeps', () => { expect(container.textContent).toBe('') }) - it('asleep: a neutral line, no red error and no "file an issue" (also for the old "VM" wording)', () => { + it('asleep: no red toast either (the pane shows the calm asleep line), also for the old "VM" wording', () => { seed('sleeping') for (const error of [ RUNTIME_ENVIRONMENT_ASLEEP_MESSAGE, "This workspace's VM is asleep. Open the workspace to wake it." ]) { const { container, unmount } = render(toast('ws', error)) - expect(container.querySelector('[data-cloud-asleep-terminal-notice]')?.textContent).toBe( - 'This workspace is asleep. Open it to wake it.' - ) - expect(container.textContent).not.toContain('file an issue') expect(container.querySelector('[data-terminal-error-toast]')).toBeNull() + expect(container.textContent).not.toContain('file an issue') unmount() } }) diff --git a/src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.ts b/src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.ts new file mode 100644 index 00000000000..c440050fe51 --- /dev/null +++ b/src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.ts @@ -0,0 +1,33 @@ +import { + RUNTIME_ENVIRONMENT_ASLEEP_MESSAGE, + RUNTIME_ENVIRONMENT_WAKE_FAILED_MESSAGE, + RUNTIME_ENVIRONMENT_WAKING_MESSAGE +} from '../../../../shared/remote-runtime/recipe-vm-wake' +import { useCloudWorkspaceView } from './use-cloud-workspace-view' + +// Older builds' wording too: a terminal error saved before this change still reads "VM". +const SLEEP_PATTERNS = [ + RUNTIME_ENVIRONMENT_ASLEEP_MESSAGE, + RUNTIME_ENVIRONMENT_WAKING_MESSAGE, + RUNTIME_ENVIRONMENT_WAKE_FAILED_MESSAGE, + "This workspace's VM is asleep", + "This workspace's VM could not wake up" +] + +function isSleepTerminalError(error: string): boolean { + return SLEEP_PATTERNS.some((pattern) => error.includes(pattern)) +} + +/** + * The terminal's error toast for an Orca Cloud workspace that is asleep or waking: never shown. + * Waking, the waking pill owns the state; asleep, the pane's recovery slot shows one calm line with + * Wake (CloudAsleepTerminalNotice, RA-12), so a red "file an issue" toast would only repeat it. + * Other errors, and other hosts, keep the regular toast. + */ +export function useCloudTerminalErrorOverride( + worktreeId: string, + error: string | null | undefined +): 'hide' | null { + const view = useCloudWorkspaceView(worktreeId) + return view.isCloud && error && isSleepTerminalError(error) ? 'hide' : null +} diff --git a/src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.tsx b/src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.tsx deleted file mode 100644 index 828b29c5f87..00000000000 --- a/src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.tsx +++ /dev/null @@ -1,56 +0,0 @@ -import React from 'react' -import { useAppStore } from '@/store' -import { useTranslate } from '@/i18n/use-translate' -import { findWorktreeById } from '@/store/github/refresh/worktree-refresh' -import { - RUNTIME_ENVIRONMENT_ASLEEP_MESSAGE, - RUNTIME_ENVIRONMENT_WAKE_FAILED_MESSAGE, - RUNTIME_ENVIRONMENT_WAKING_MESSAGE -} from '../../../../shared/remote-runtime/recipe-vm-wake' -import { useCloudWorkspaceView } from './use-cloud-workspace-view' - -// Older builds' wording too: a terminal error saved before this change still reads "VM". -const SLEEP_PATTERNS = [ - RUNTIME_ENVIRONMENT_ASLEEP_MESSAGE, - RUNTIME_ENVIRONMENT_WAKING_MESSAGE, - RUNTIME_ENVIRONMENT_WAKE_FAILED_MESSAGE, - "This workspace's VM is asleep", - "This workspace's VM could not wake up" -] - -function isSleepTerminalError(error: string): boolean { - return SLEEP_PATTERNS.some((pattern) => error.includes(pattern)) -} - -/** - * The terminal's error toast for an Orca Cloud workspace that is asleep or waking (RA-10 follow-up). - * While it wakes, the waking pill owns the state, so no toast at all. Asleep, a neutral line - * instead of a red error with "file an issue". Other errors, and other hosts, are left alone. - */ -export function useCloudTerminalErrorOverride( - worktreeId: string, - error: string | null | undefined -): 'hide' | React.JSX.Element | null { - const t = useTranslate() - const view = useCloudWorkspaceView(worktreeId) - const name = useAppStore((state) => findWorktreeById(state, worktreeId)?.displayName ?? null) - if (!view.isCloud || !error || !isSleepTerminalError(error)) { - return null - } - if (view.state === 'waking' || view.state === 'starting' || view.state === 'running') { - return 'hide' - } - return ( -
- {name - ? t('orcaCloudWorkspace.terminal.asleepNamed', '{{name}} is asleep. Open it to wake it.', { - name - }) - : t('orcaCloudWorkspace.terminal.asleep', 'This workspace is asleep. Open it to wake it.')} -
- ) -} diff --git a/src/renderer/src/components/sidebar/SetupScriptPromptCard.tsx b/src/renderer/src/components/sidebar/SetupScriptPromptCard.tsx index 4b1f8cfcdf6..8361dd84216 100644 --- a/src/renderer/src/components/sidebar/SetupScriptPromptCard.tsx +++ b/src/renderer/src/components/sidebar/SetupScriptPromptCard.tsx @@ -1,4 +1,5 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { useCloudRecoveryContext } from '@/lib/orca-cloud/use-cloud-recovery-context' import { toast } from 'sonner' import { useAppStore } from '@/store' import { track } from '@/lib/telemetry' @@ -67,8 +68,12 @@ function SetupScriptPromptCard(): React.JSX.Element | null { [activeRepoId, activeWorktree, repos, settings] ) const activeRepoHostIdentity = activeRepo ? getRepoHostIdentity(activeRepo) : null + // An asleep Orca Cloud workspace can't be inspected: wait until it's awake instead of showing + // "Couldn't verify this repo's setup script" with Retry (RA-12). + const asleepCloud = useCloudRecoveryContext(activeWorktreeId)?.asleep === true const isDismissed = provisionedByEnvironmentBuild || + asleepCloud || (activeRepoHostIdentity ? isSetupScriptPromptDismissed(activeRepoHostIdentity, dismissedRepoIds) : false) diff --git a/src/renderer/src/components/terminal-pane/errors/TerminalErrorToast.tsx b/src/renderer/src/components/terminal-pane/errors/TerminalErrorToast.tsx index 7cf01e6fb52..b0a31624168 100644 --- a/src/renderer/src/components/terminal-pane/errors/TerminalErrorToast.tsx +++ b/src/renderer/src/components/terminal-pane/errors/TerminalErrorToast.tsx @@ -116,8 +116,8 @@ export function TerminalErrorToast({ } } - if (cloudOverride) { - return cloudOverride === 'hide' ? null : cloudOverride + if (cloudOverride === 'hide') { + return null } return (
(null) @@ -192,6 +195,14 @@ export function TerminalPaneRecoveryPortals({ `wsl-host-stopped-${pane.id}` ) } + // Asleep: nothing to reconnect to; one calm line with Wake instead of a reconnect card (RA-12). + if (cloudAsleep) { + return createPortal( + , + pane.container, + `cloud-asleep-${pane.id}` + ) + } // Why mounted with no recovery: the banner's minimum time and hold outlive the recovery itself. return createPortal( ({ + state, + metrics: null, + uptimeMs: null, + usage: { totalMs: 0, centsPerHour: 100, costCents: 0 }, + archive: null, + checkedAt: T0 +}) + +function seed(state: HostedWorkspaceStatus['state'] | null): void { + seedCloudWorkspaceSnapshot({ + ids: new Set(['ws']), + idsLoaded: true, + status: state + ? { ws: { status: status(state), loading: false, error: null, fetchedAt: T0 } } + : {} + }) +} + +afterEach(() => { + cleanup() + seedCloudWorkspaceSnapshot({}) + useAppStore.setState({ ephemeralVmRuntimesByWorkspaceId: {} }) +}) + +describe('terminal recovery for an asleep Orca Cloud workspace (RA-12)', () => { + it('is asleep when the control plane says so, so no "Reconnecting… Down for" toast', () => { + act(() => seed('sleeping')) + const { result } = renderHook(() => useCloudRecoveryContext('ws')) + expect(result.current).toMatchObject({ asleep: true, waking: false }) + }) + + it('is asleep right after Sleep from this computer, before the status poll catches up', () => { + act(() => { + seed('ready') + useAppStore.setState({ + ephemeralVmRuntimesByWorkspaceId: { + ws: { id: 'vm', workspaceId: 'ws', status: 'suspended', canSuspend: true } + } + }) + }) + const { result } = renderHook(() => useCloudRecoveryContext('ws')) + expect(result.current?.asleep).toBe(true) + }) + + it('a running workspace whose connection dropped still reconnects', () => { + act(() => seed('ready')) + const { result } = renderHook(() => useCloudRecoveryContext('ws')) + expect(result.current?.asleep).toBe(false) + }) + + it('is not a cloud workspace: no context at all', () => { + act(() => seed('sleeping')) + const { result } = renderHook(() => useCloudRecoveryContext('local')) + expect(result.current).toBeNull() + }) +}) diff --git a/src/renderer/src/lib/orca-cloud/use-cloud-recovery-context.ts b/src/renderer/src/lib/orca-cloud/use-cloud-recovery-context.ts index 1f5a19d4f3b..2a712372574 100644 --- a/src/renderer/src/lib/orca-cloud/use-cloud-recovery-context.ts +++ b/src/renderer/src/lib/orca-cloud/use-cloud-recovery-context.ts @@ -5,6 +5,8 @@ import { useCloudWorkspace, useIsCloudWorkspace } from './orca-cloud-workspace-s export type CloudRecoveryContext = { /** A wake is in flight: the waking pill already says what's happening, so no reconnect banner. */ waking: boolean + /** Asleep or going to sleep: nothing to reconnect to, so a calm note instead of "Reconnecting" (RA-12). */ + asleep: boolean /** What the person calls it (never the sandbox's server name or id). */ workspaceName: string | null } @@ -15,11 +17,24 @@ export function useCloudRecoveryContext( ): CloudRecoveryContext | null { const isCloud = useIsCloudWorkspace(worktreeId) const phase = useCloudWorkspace((s) => (worktreeId ? s.wake[worktreeId]?.phase : undefined)) + const reported = useCloudWorkspace((s) => + worktreeId ? s.status[worktreeId]?.status?.state : undefined + ) + // The local record flips the moment this computer puts it to sleep; the status poll lags. + const vmSuspended = useAppStore((state) => + worktreeId + ? state.ephemeralVmRuntimesByWorkspaceId?.[worktreeId]?.status === 'suspended' + : false + ) const workspaceName = useAppStore((state) => worktreeId ? (findWorktreeById(state, worktreeId)?.displayName ?? null) : null ) if (!isCloud) { return null } - return { waking: phase === 'waking' || phase === 'connecting', workspaceName } + const waking = phase === 'waking' || phase === 'connecting' + const asleep = + !waking && + (reported === 'sleeping' || reported === 'stopping' || reported === 'archived' || vmSuspended) + return { waking, asleep, workspaceName } } From 546b488d3a735803f5ad19b56f37165c1b6e3c8c Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 18:09:45 -0800 Subject: [PATCH 011/149] chore(l10n): drop the retired terminal asleep keys --- src/renderer/src/i18n/en-runtime-required.json | 4 ---- src/renderer/src/i18n/locales/en.json | 2 -- 2 files changed, 6 deletions(-) diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index c05b591f630..57070f86d45 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -2353,10 +2353,6 @@ "overlay": { "pendingKeys_one": "{{count}} key waiting · it goes to the terminal when it’s up", "pendingKeys_other": "{{count}} keys waiting · they go to the terminal when it’s up" - }, - "terminal": { - "asleep": "This workspace is asleep. Open it to wake it.", - "asleepNamed": "{{name}} is asleep. Open it to wake it." } }, "pet": { diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 7648ce168f8..94e9ebe87e4 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -27029,8 +27029,6 @@ "recentCommits": "Recent commits" }, "terminal": { - "asleepNamed": "{{name}} is asleep. Open it to wake it.", - "asleep": "This workspace is asleep. Open it to wake it.", "asleepHistoryKept": "This workspace is asleep. Your terminal history is kept." } }, From 06075e682f2cefb558d92796320a30e7881f4099 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 18:10:43 -0800 Subject: [PATCH 012/149] feat(cloud): POST /v1/agent-credentials/claude/verify for the desktop's pre-launch check Runs the confirm-before-revoke auth check on demand: a pass within 10 min answers at once (verified_at, migration 0048), otherwise one check rate-limited to one a minute per person, revoking (audited) only on a definite authentication_error. Storing a new token forgets the old verification. --- .../0048_agent_credential_verified.sql | 4 + .../src/agent-credential-checks.ts | 98 ++++++++++++++----- .../sandbox-control/src/agent-credentials.ts | 4 +- cloud/apps/sandbox-control/src/index.ts | 24 ++++- .../test/agent-accounts.test.ts | 50 ++++++++++ 5 files changed, 156 insertions(+), 24 deletions(-) create mode 100644 cloud/apps/sandbox-control/migrations/0048_agent_credential_verified.sql diff --git a/cloud/apps/sandbox-control/migrations/0048_agent_credential_verified.sql b/cloud/apps/sandbox-control/migrations/0048_agent_credential_verified.sql new file mode 100644 index 00000000000..d0f0eefcc48 --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0048_agent_credential_verified.sql @@ -0,0 +1,4 @@ +-- Last time the control plane's own auth check passed for this credential (POST +-- /v1/agent-credentials/claude/verify, or the check behind a provider 401). Recent passes answer verify +-- without calling the provider again. +ALTER TABLE agent_credentials ADD COLUMN verified_at INTEGER; diff --git a/cloud/apps/sandbox-control/src/agent-credential-checks.ts b/cloud/apps/sandbox-control/src/agent-credential-checks.ts index 0dc07a408bf..2ea5948610d 100644 --- a/cloud/apps/sandbox-control/src/agent-credential-checks.ts +++ b/cloud/apps/sandbox-control/src/agent-credential-checks.ts @@ -1,46 +1,56 @@ // A provider 401 on an Orca-account request (the proxy swapped the real credential in) is a signal, not a // verdict: one transient auth error must not sign a person out of every workspace. Before revoking, the // control plane makes one cheap server-side auth check with the real credential (no tokens spent) and -// revokes only when that also says the credential is dead. Checks are rate-limited per person and agent -// (agent_credentials.checked_at), and every decision is audited (agent_credential_audit). +// revokes only when that also says the credential is dead. The desktop can ask for the same check before a +// launch (POST /v1/agent-credentials/claude/verify). Checks are rate-limited per person and agent +// (agent_credentials.checked_at), passes are remembered (verified_at), and every keep or revoke is audited +// (agent_credential_audit). import type { AccountProvider } from './account-providers' import { markAgentCredentialRevoked, readUsableAgentCredential } from './agent-credentials' import type { Keyring } from './secrets-crypto' /** At most one auth check (and so one revoke) per person and agent per minute. */ export const CREDENTIAL_CHECK_INTERVAL_MS = 60_000 +/** A pass this recent answers verify without calling the provider. */ +export const CREDENTIAL_VERIFIED_FRESH_MS = 10 * 60_000 export type CredentialVerdict = 'valid' | 'invalid' | 'unknown' -export type UnauthorizedOutcome = 'revoked' | 'kept' | 'skipped' +export type CheckOutcome = 'revoked' | 'kept' | 'skipped' + +type CheckContext = { + db: D1Database + keyring: Keyring + provider: Pick + userId: string + now: number + fetch: typeof fetch +} async function audit( db: D1Database, - entry: { userId: string; agent: string; action: 'revoked' | 'kept'; reason: string; sandboxId: string; path: string; now: number } + entry: { userId: string; agent: string; action: 'revoked' | 'kept'; reason: string; sandboxId: string | null; path: string | null; now: number } ): Promise { await db .prepare( `INSERT INTO agent_credential_audit (user_id, agent, action, reason, sandbox_id, upstream_path, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)` ) - .bind(entry.userId, entry.agent, entry.action, entry.reason, entry.sandboxId, entry.path.split('?')[0]!.slice(0, 200), entry.now) + .bind(entry.userId, entry.agent, entry.action, entry.reason, entry.sandboxId, entry.path ? entry.path.split('?')[0]!.slice(0, 200) : null, entry.now) .run() - console.log(JSON.stringify({ event: `agent_credential_${entry.action}`, agent: entry.agent, by: 'egress_401', reason: entry.reason, sandboxId: entry.sandboxId })) + console.log(JSON.stringify({ event: `agent_credential_${entry.action}`, agent: entry.agent, reason: entry.reason, sandboxId: entry.sandboxId })) } -export async function handleAccountUnauthorized(ctx: { - db: D1Database - keyring: Keyring - provider: Pick - userId: string - sandboxId: string - /** The upstream path that answered 401 (audit only; no query string). */ - path: string - now: number - fetch: typeof fetch -}): Promise { +/** + * One rate-limited auth check. Revokes only on a definite auth failure; a pass is remembered. 'skipped' + * when another check ran within the minute or the credential isn't usable. + */ +async function checkCredential( + ctx: CheckContext, + trigger: { kind: 'egress_401'; sandboxId: string; path: string } | { kind: 'verify' } +): Promise { const { db, provider, userId, now } = ctx const agent = provider.agent - // Claim the check slot: a burst of parallel 401s, or a flapping provider, makes one check a minute. + // Claim the check slot: a burst of parallel 401s or verify calls makes one check a minute. const claimed = await db .prepare( `UPDATE agent_credentials SET checked_at = ? @@ -49,7 +59,7 @@ export async function handleAccountUnauthorized(ctx: { .bind(now, userId, agent, now - CREDENTIAL_CHECK_INTERVAL_MS) .run() if (!claimed.meta.changes) { - console.log(JSON.stringify({ event: 'agent_credential_401_skipped', agent, sandboxId: ctx.sandboxId })) + console.log(JSON.stringify({ event: 'agent_credential_check_skipped', agent, trigger: trigger.kind })) return 'skipped' } const real = await readUsableAgentCredential(db, ctx.keyring, userId, agent, now) @@ -57,12 +67,56 @@ export async function handleAccountUnauthorized(ctx: { return 'skipped' } const verdict: CredentialVerdict = provider.verify ? await provider.verify(real, ctx.fetch) : 'unknown' - const base = { userId, agent, sandboxId: ctx.sandboxId, path: ctx.path, now } + const where = + trigger.kind === 'egress_401' + ? { sandboxId: trigger.sandboxId, path: trigger.path } + : { sandboxId: null, path: null } + const base = { userId, agent, now, ...where } + if (verdict === 'valid') { + await db.prepare(`UPDATE agent_credentials SET verified_at = ? WHERE user_id = ? AND agent = ?`).bind(now, userId, agent).run() + } if (verdict !== 'invalid') { - await audit(db, { ...base, action: 'kept', reason: verdict === 'valid' ? 'check_passed' : 'check_inconclusive' }) + // A pass on a pre-launch verify is routine; a 401 that didn't hold up, or any inconclusive check, is audited. + if (trigger.kind === 'egress_401' || verdict === 'unknown') { + const reason = verdict === 'valid' ? 'check_passed' : 'check_inconclusive' + await audit(db, { ...base, action: 'kept', reason: trigger.kind === 'verify' ? `verify_${reason}` : reason }) + } return 'kept' } await markAgentCredentialRevoked(db, userId, agent, now) - await audit(db, { ...base, action: 'revoked', reason: 'provider_401_confirmed_by_check' }) + await audit(db, { + ...base, + action: 'revoked', + reason: trigger.kind === 'verify' ? 'verify_confirmed_auth_failure' : 'provider_401_confirmed_by_check' + }) return 'revoked' } + +export function handleAccountUnauthorized( + ctx: CheckContext & { sandboxId: string; path: string } +): Promise { + return checkCredential(ctx, { kind: 'egress_401', sandboxId: ctx.sandboxId, path: ctx.path }) +} + +/** + * Pre-launch verify: a pass within CREDENTIAL_VERIFIED_FRESH_MS answers at once; otherwise one check (rate + * limited). Returns what happened; the caller re-reads the state. + */ +export async function verifyAccountCredential( + ctx: CheckContext +): Promise<{ outcome: CheckOutcome | 'fresh'; verifiedAt: number | null }> { + const row = await ctx.db + .prepare(`SELECT verified_at FROM agent_credentials WHERE user_id = ? AND agent = ?`) + .bind(ctx.userId, ctx.provider.agent) + .first<{ verified_at: number | null }>() + const last = row?.verified_at ?? null + if (last !== null && ctx.now - last < CREDENTIAL_VERIFIED_FRESH_MS) { + return { outcome: 'fresh', verifiedAt: last } + } + const outcome = await checkCredential(ctx, { kind: 'verify' }) + const after = await ctx.db + .prepare(`SELECT verified_at FROM agent_credentials WHERE user_id = ? AND agent = ?`) + .bind(ctx.userId, ctx.provider.agent) + .first<{ verified_at: number | null }>() + return { outcome, verifiedAt: after?.verified_at ?? null } +} diff --git a/cloud/apps/sandbox-control/src/agent-credentials.ts b/cloud/apps/sandbox-control/src/agent-credentials.ts index 7a5b143d4e5..182369da3bf 100644 --- a/cloud/apps/sandbox-control/src/agent-credentials.ts +++ b/cloud/apps/sandbox-control/src/agent-credentials.ts @@ -1,6 +1,7 @@ // Account credentials for agents (agent-sources contract D11): one per person per agent, Personal only. // GET /v1/agent-credentials -> {claude, codex: {state, label?, expiresAt?}, providerEnabled, providerState} // PUT /v1/agent-credentials/claude {token, label?, expiresAt?} (flag S1; desktop main runs `claude setup-token`) +// POST /v1/agent-credentials/claude/verify -> {claude, verifiedAt, checked} (pre-launch check, agent-credential-checks.ts) // DELETE /v1/agent-credentials/:agent // Values are never returned or logged. They leave the Worker only when the egress proxy swaps them into a // request from the person's own, unshared workspace (D10, D13). The Codex broker (flag S2) stores its tokens @@ -104,7 +105,8 @@ export async function putAgentCredential( VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?) ON CONFLICT (user_id, agent) DO UPDATE SET account_id = excluded.account_id, kek_id = excluded.kek_id, wrapped_dek = excluded.wrapped_dek, ciphertext = excluded.ciphertext, label = excluded.label, - expires_at = excluded.expires_at, state = 'active', updated_at = excluded.updated_at` + expires_at = excluded.expires_at, state = 'active', updated_at = excluded.updated_at, + checked_at = NULL, verified_at = NULL` ) .bind(input.userId, input.accountId, input.agent, sealed.kekId, sealed.wrappedDek, sealed.ciphertext, input.label ?? null, input.expiresAt ?? null, now, now) .run() diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 88fd55ca1bc..255b4d8b6ec 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -114,7 +114,7 @@ import { egressAccountRoutes, egressSecretHosts, placeholderValues, secretPlaceh import { SecretError, handleSecretsRoute, keyringFor, type SecretChange } from './secrets' import { refreshAfterSecretChange, refreshSandboxEnv } from './env-refresh' import { accountProvider, isSharedWorkspace } from './account-providers' -import { handleAccountUnauthorized } from './agent-credential-checks' +import { handleAccountUnauthorized, verifyAccountCredential } from './agent-credential-checks' import { codexBrokerTick, handleCodexBrokerRoute, type BrokerDeps } from './codex-broker' import { refreshCodexLeases } from './codex-credentials' import { @@ -529,6 +529,28 @@ async function agentCredentialsRoute(request: Request, url: URL, env: Env, deps: await refreshOwnersSandboxes(env, deps, caller.userId) return noStore(await agentCredentialsView(db, env, caller.userId, now)) } + // Pre-launch check (desktop): a recent pass answers at once; otherwise one rate-limited auth check with + // the real token, revoking only on a definite auth failure (agent-credential-checks.ts). + if (request.method === 'POST' && url.pathname === '/v1/agent-credentials/claude/verify') { + const provider = accountProvider('claude') + if (!providerEnabled(env).claude || !provider) { + return fail('not_found', 404) + } + const result = await verifyAccountCredential({ + db, + keyring: await keyring, + provider, + userId: caller.userId, + now, + fetch: deps.egressFetch ?? fetch + }) + if (result.outcome === 'revoked') { + forgetAccountCredential(caller.userId, 'claude') + await refreshOwnersSandboxes(env, deps, caller.userId) + } + const view = await agentCredentialsView(db, env, caller.userId, now) + return noStore({ claude: view.claude, verifiedAt: result.verifiedAt, checked: result.outcome !== 'fresh' && result.outcome !== 'skipped' }) + } if (url.pathname === '/v1/agent-credentials/codex/broker' || url.pathname.startsWith('/v1/agent-credentials/codex/broker/')) { return await handleCodexBrokerRoute(request, url, { enabled: providerEnabled(env).codex, deps: await codexBrokerDeps(env, deps), caller }) } diff --git a/cloud/apps/sandbox-control/test/agent-accounts.test.ts b/cloud/apps/sandbox-control/test/agent-accounts.test.ts index 7adc26fb5d7..8a287fb8e50 100644 --- a/cloud/apps/sandbox-control/test/agent-accounts.test.ts +++ b/cloud/apps/sandbox-control/test/agent-accounts.test.ts @@ -334,3 +334,53 @@ describe('a provider 401 revokes only when confirmed', () => { expect(await auditRows()).toEqual([{ action: 'revoked', reason: 'provider_401_confirmed_by_check', upstream_path: '/v1/messages' }]) }) }) + +describe('POST /v1/agent-credentials/claude/verify (pre-launch check)', () => { + it('a pass is remembered: the next calls answer without asking the provider', async () => { + const { h, as, check } = await setup() + const mia = await as('mia') + await h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: SETUP_TOKEN } }) + check.status = 200 + check.body = '{"input_tokens":3}' + const first = await h.call('POST', '/v1/agent-credentials/claude/verify', { bearer: mia }) + expect(first.body).toMatchObject({ claude: { state: 'active' }, checked: true }) + expect(first.body.verifiedAt).toEqual(expect.any(Number)) + const again = await h.call('POST', '/v1/agent-credentials/claude/verify', { bearer: mia }) + expect(again.body).toMatchObject({ claude: { state: 'active' }, checked: false, verifiedAt: first.body.verifiedAt }) + expect(check.calls).toBe(1) + }) + + it('a dead token is revoked (and audited); an inconclusive check keeps it', async () => { + const dead = await setup() + const mia = await dead.as('mia') + await dead.h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: SETUP_TOKEN } }) + const revoked = await dead.h.call('POST', '/v1/agent-credentials/claude/verify', { bearer: mia }) + expect(revoked.body).toMatchObject({ claude: { state: 'revoked' }, checked: true, verifiedAt: null }) + const rows = (await dead.h.env.SANDBOX_DB.prepare('SELECT action, reason FROM agent_credential_audit').all()).results + expect(rows).toEqual([{ action: 'revoked', reason: 'verify_confirmed_auth_failure' }]) + + const flaky = await setup() + const ada = await flaky.as('ada') + await flaky.h.call('PUT', '/v1/agent-credentials/claude', { bearer: ada, body: { token: SETUP_TOKEN } }) + flaky.check.status = 529 + flaky.check.body = '{"type":"error","error":{"type":"overloaded_error"}}' + const kept = await flaky.h.call('POST', '/v1/agent-credentials/claude/verify', { bearer: ada }) + expect(kept.body).toMatchObject({ claude: { state: 'active' }, checked: true, verifiedAt: null }) + // Rate limited: a second call within the minute doesn't ask again. + await flaky.h.call('POST', '/v1/agent-credentials/claude/verify', { bearer: ada }) + expect(flaky.check.calls).toBe(1) + }) + + it('storing a new token forgets the old verification', async () => { + const { h, as, check } = await setup() + const mia = await as('mia') + await h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: SETUP_TOKEN } }) + check.status = 200 + check.body = '{}' + await h.call('POST', '/v1/agent-credentials/claude/verify', { bearer: mia }) + await h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: SETUP_TOKEN } }) + const after = await h.call('POST', '/v1/agent-credentials/claude/verify', { bearer: mia }) + expect(after.body.checked).toBe(true) + expect(check.calls).toBe(2) + }) +}) From 12034d5c74789823da622ec8da9eea7687150aa9 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 18:21:10 -0800 Subject: [PATCH 013/149] =?UTF-8?q?fix(cloud):=20asleep=20names=20?= =?UTF-8?q?=E2=80=94=20terminal=20card=20'Terminal=20N'=20not=20its=20id,?= =?UTF-8?q?=20Files=20header=20and=20team=20list=20name=20the=20workspace,?= =?UTF-8?q?=20'Asleep=20=C2=B7'=20right=20after=20Sleep=20(RA-13)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cloud-workspaces/CloudWorkspacesHome.tsx | 9 +- .../cloud-workspace-local-titles.test.ts | 29 +++++++ .../cloud-workspace-local-titles.ts | 85 +++++++++++++++++++ .../offline/CloudWorkspaceOfflineView.tsx | 10 ++- .../use-cloud-workspace-view.test.ts | 64 ++++++++++++++ .../orca-cloud/use-cloud-workspace-view.ts | 28 ++++-- .../file-explorer/panel/FileExplorer.tsx | 6 +- src/renderer/src/i18n/locales/en.json | 3 +- 8 files changed, 215 insertions(+), 19 deletions(-) create mode 100644 src/renderer/src/components/cloud-workspaces/cloud-workspace-local-titles.test.ts create mode 100644 src/renderer/src/components/cloud-workspaces/cloud-workspace-local-titles.ts create mode 100644 src/renderer/src/components/orca-cloud/use-cloud-workspace-view.test.ts diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx index c9f462f2084..aead29afdf8 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx @@ -1,5 +1,6 @@ // Home: the org's cloud workspaces (registry on the control plane), filterable by who owns them, // which repo they are in, Mine/Team and archived, grouped by section, with live presence and cost. +import { useHomeWorkspaces } from './cloud-workspace-local-titles' import React, { useCallback, useEffect, useMemo, useState } from 'react' import { toast } from 'sonner' import { useAppStore } from '@/store' @@ -121,13 +122,7 @@ export function CloudWorkspacesHome({ }, []) // A workspace being deleted (or gone) is not something to open or manage; Home leaves it out. - const all = useMemo( - () => - state.status === 'ready' - ? state.workspaces.filter((w) => w.status !== 'destroying' && w.status !== 'destroyed') - : [], - [state] - ) + const all = useHomeWorkspaces(state.status === 'ready' ? state.workspaces : null) const { directory, canAdmin } = useMemberDirectory(orgId, all) const repos = useMemo( () => [...new Set(all.flatMap((w) => (w.repo ? [w.repo.url] : [])))].sort(), diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspace-local-titles.test.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspace-local-titles.test.ts new file mode 100644 index 00000000000..e193c3f3e3b --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspace-local-titles.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest' +import { withLocalTitles } from './cloud-workspace-local-titles' +import { cloudWorkspaceTitle } from './open-cloud-workspace' +import { workspace } from './cloud-workspaces.test-fixture' + +describe('team list names a workspace, not its repo (RA-13)', () => { + const untitled = workspace({ + id: 'sbx_1', + workspaceId: 'orca-1', + title: null, + repo: { url: 'https://github.com/octocat/Hello-World.git', branch: null } + }) + + it('an untitled workspace this computer started reads by its name', () => { + const [named] = withLocalTitles([untitled], new Map([['orca-1', 'ra12-asleep']])) + expect(cloudWorkspaceTitle(named!)).toBe('ra12-asleep') + }) + + it("a teammate's untitled workspace still falls back to the repo", () => { + const [other] = withLocalTitles([untitled], new Map()) + expect(cloudWorkspaceTitle(other!)).toBe('Hello-World') + }) + + it('a workspace with its own title keeps it', () => { + const titled = { ...untitled, title: 'Fix login' } + const [kept] = withLocalTitles([titled], new Map([['orca-1', 'ra12-asleep']])) + expect(kept?.title).toBe('Fix login') + }) +}) diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspace-local-titles.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspace-local-titles.ts new file mode 100644 index 00000000000..5359eb0943a --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspace-local-titles.ts @@ -0,0 +1,85 @@ +import { useEffect, useMemo, useRef } from 'react' +import { useAppStore } from '@/store' +import { findWorktreeById } from '@/store/github/refresh/worktree-refresh' +import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' + +/** + * Names this computer gave its own cloud workspaces, by control-plane workspace id. The local VM + * record links the two (its id is the workspace's `orca-…` id); the name is the sidebar's. + */ +export function useLocalCloudWorkspaceNames(): ReadonlyMap { + const pairs = useAppStore((state) => + Object.values(state.ephemeralVmRuntimesByWorkspaceId ?? {}) + .map((runtime) => { + const name = findWorktreeById(state, runtime.workspaceId)?.displayName + return name ? `${runtime.id}\u0000${name}` : null + }) + .filter((entry): entry is string => entry !== null) + .join('\u0001') + ) + return useMemo( + () => + new Map( + pairs + ? pairs.split('\u0001').map((entry) => { + const cut = entry.indexOf('\u0000') + return [entry.slice(0, cut), entry.slice(cut + 1)] as const + }) + : [] + ), + [pairs] + ) +} + +/** + * A workspace started without a title shows its repo in the team list ("Hello-World" for + * "ra12-asleep", RA-13). Use the name this computer gave it; the repo stays on the second line. + */ +export function withLocalTitles( + workspaces: readonly CloudWorkspace[], + names: ReadonlyMap +): CloudWorkspace[] { + return workspaces.map((w) => { + const name = w.title ? null : names.get(w.workspaceId) + return name ? { ...w, title: name } : w + }) +} + +/** Teammates see the name too: save it as the workspace's title once, for workspaces this user owns. */ +export function useBackfillLocalTitles( + workspaces: readonly CloudWorkspace[], + names: ReadonlyMap +): void { + const done = useRef(new Set()) + useEffect(() => { + const api = window.api?.cloudWorkspaces + if (!api) { + return + } + for (const w of workspaces) { + const name = names.get(w.workspaceId) + if (w.title || !name || w.access !== 'owner' || done.current.has(w.id)) { + continue + } + done.current.add(w.id) + // Best effort: the list already shows the name; a failed save only means teammates don't yet. + void api.patch(w.id, { title: name }).catch(() => {}) + } + }, [workspaces, names]) +} + +const NONE: readonly CloudWorkspace[] = [] + +/** + * What Home lists: a workspace being deleted (or gone) is not something to open or manage, so it + * is left out; untitled ones this computer started read by its name for them, not the repo. + */ +export function useHomeWorkspaces(workspaces: readonly CloudWorkspace[] | null): CloudWorkspace[] { + const listed = useMemo( + () => (workspaces ?? NONE).filter((w) => w.status !== 'destroying' && w.status !== 'destroyed'), + [workspaces] + ) + const localNames = useLocalCloudWorkspaceNames() + useBackfillLocalTitles(listed, localNames) + return useMemo(() => withLocalTitles(listed, localNames), [listed, localNames]) +} diff --git a/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.tsx b/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.tsx index 28d77c9b050..93feaed80a1 100644 --- a/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.tsx +++ b/src/renderer/src/components/orca-cloud/offline/CloudWorkspaceOfflineView.tsx @@ -125,8 +125,14 @@ export function CloudWorkspaceOfflineView(props: CloudOfflineViewProps): React.J

) : (
- {snapshot.terminals.map((terminal) => { - const title = terminal.title ?? terminal.handle + {snapshot.terminals.map((terminal, index) => { + // The tab's title, else "Terminal N": never the terminal's internal id (RA-13). + const title = + terminal.title && !terminal.title.startsWith('term_') + ? terminal.title + : t('components.orcaCloud.offline.terminalN', 'Terminal {{n}}', { + n: index + 1 + }) return (
({ + useIsSleepingWorktree: () => false +})) + +const T0 = 1_800_000_000_000 +const ready: HostedWorkspaceStatus = { + state: 'ready', + metrics: null, + uptimeMs: null, + usage: { totalMs: 0, centsPerHour: 100, costCents: 0 }, + archive: null, + checkedAt: T0 +} + +afterEach(() => { + cleanup() + seedCloudWorkspaceSnapshot({}) + useAppStore.setState({ ephemeralVmRuntimesByWorkspaceId: {} }) +}) + +describe('cloud workspace state right after Sleep (RA-13)', () => { + it('reads asleep from the local VM record while the last status read still says ready', () => { + act(() => { + seedCloudWorkspaceSnapshot({ + ids: new Set(['ws']), + idsLoaded: true, + status: { ws: { status: ready, loading: false, error: null, fetchedAt: T0 } } + }) + useAppStore.setState({ + ephemeralVmRuntimesByWorkspaceId: { + ws: { id: 'vm', workspaceId: 'ws', status: 'suspended', canSuspend: true } + } + }) + }) + const { result } = renderHook(() => useCloudWorkspaceView('ws')) + expect(result.current.state).toBe('sleeping') + }) + + it('stays running when the VM record is running too', () => { + act(() => { + seedCloudWorkspaceSnapshot({ + ids: new Set(['ws']), + idsLoaded: true, + status: { ws: { status: ready, loading: false, error: null, fetchedAt: T0 } } + }) + useAppStore.setState({ + ephemeralVmRuntimesByWorkspaceId: { + ws: { id: 'vm', workspaceId: 'ws', status: 'running', canSuspend: true } + } + }) + }) + const { result } = renderHook(() => useCloudWorkspaceView('ws')) + expect(result.current.state).toBe('running') + }) +}) diff --git a/src/renderer/src/components/orca-cloud/use-cloud-workspace-view.ts b/src/renderer/src/components/orca-cloud/use-cloud-workspace-view.ts index c9e8424a9de..a08d556f1d8 100644 --- a/src/renderer/src/components/orca-cloud/use-cloud-workspace-view.ts +++ b/src/renderer/src/components/orca-cloud/use-cloud-workspace-view.ts @@ -1,5 +1,6 @@ import { useEffect } from 'react' import { useNow } from '@/hooks/use-now' +import { useAppStore } from '@/store' import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' import { useIsSleepingWorktree } from '@/components/sidebar/workspace-actions/sleep/use-worktree-sleep-state' import { @@ -36,6 +37,11 @@ export function useCloudWorkspaceView(workspaceId: string): CloudWorkspaceView { const oomDismissed = useCloudWorkspace((s) => s.oomDismissed[workspaceId]) const pending = useCloudWorkspace((s) => s.pending[workspaceId]) const sleeping = useIsSleepingWorktree(workspaceId) + // The local VM record flips the moment this computer puts it to sleep; the last status read can + // still say "ready" for a while, which dropped "Asleep ·" from the row (RA-13). + const vmSuspended = useAppStore( + (state) => state.ephemeralVmRuntimesByWorkspaceId?.[workspaceId]?.status === 'suspended' + ) // Sleep and wake run through the desktop; re-read when the local record flips. Remounts of // virtualized sidebar rows reuse a read from the last 30 s. useEffect(() => { @@ -43,20 +49,26 @@ export function useCloudWorkspaceView(workspaceId: string): CloudWorkspaceView { void refreshCloudWorkspaceStatusIfStale(workspaceId) } }, [isCloud, sleeping, workspaceId]) + useEffect(() => { + if (isCloud && vmSuspended) { + void refreshCloudWorkspaceStatus(workspaceId) + } + }, [isCloud, vmSuspended, workspaceId]) // Only an unsettled wake needs a clock (it can go stale without an event); settled wakes are // removed from the store, so idle workspaces run no timer. const ticking = isCloud && wake !== undefined const now = useNow(5_000, ticking) + const derived = isCloud + ? deriveCloudDotState({ + status: entry?.status ?? null, + wake, + sleeping, + now: Math.max(now, wake?.at ?? 0) + }) + : 'unknown' return { isCloud, - state: isCloud - ? deriveCloudDotState({ - status: entry?.status ?? null, - wake, - sleeping, - now: Math.max(now, wake?.at ?? 0) - }) - : 'unknown', + state: derived === 'running' && vmSuspended ? 'sleeping' : derived, entry, wake, oom: visibleOom(oomEvent, oomDismissed), diff --git a/src/renderer/src/components/right-sidebar/file-explorer/panel/FileExplorer.tsx b/src/renderer/src/components/right-sidebar/file-explorer/panel/FileExplorer.tsx index f051e14848a..ef8601e0683 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/panel/FileExplorer.tsx +++ b/src/renderer/src/components/right-sidebar/file-explorer/panel/FileExplorer.tsx @@ -1,4 +1,5 @@ import React, { useCallback, useMemo } from 'react' +import { useIsCloudWorkspace } from '@/lib/orca-cloud/orca-cloud-workspace-store' import { useAsleepCloudWorkspace } from '@/components/orca-cloud/offline/use-asleep-cloud-workspace-id' import { useAppStore } from '@/store/index' import { runtimeEnvironmentIdOrLocalUnlessTwin } from '@/lib/workspace/ownership/worktree-runtime-owner' @@ -96,7 +97,10 @@ function FileExplorerFiles(): React.JSX.Element { rightSidebarOpen, worktreePath }) - const repoName = activeRepo?.displayName ?? (worktreePath ? basename(worktreePath) : '') + // An Orca Cloud workspace's files are that workspace's, so the header names it, not its repo (RA-13). + const cloudName = useIsCloudWorkspace(activeWorktreeId) ? activeWorktree?.displayName : null + const repoName = + cloudName || activeRepo?.displayName || (worktreePath ? basename(worktreePath) : '') const activeRepoSupportsGit = activeRepo ? isGitRepoKind(activeRepo) : false const expanded = useMemo(() => activeExpandedDirs ?? new Set(), [activeExpandedDirs]) diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index c3ebd799daa..f471d5c065f 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -23487,7 +23487,8 @@ "noTerminals": "No terminal output was saved.", "readOnly": "Read-only", "terminalOutput": "Saved output of {{title}}", - "noGit": "No source control state was saved." + "noGit": "No source control state was saved.", + "terminalN": "Terminal {{n}}" }, "read": { "wakeToContinue": "Wake to continue", From 7cb6272ae765f73703707fbd59b7f9d58ee8dbe8 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 18:50:19 -0800 Subject: [PATCH 014/149] revert(terminal): drop the narrow-pane title-row reservation (RA-7 won't-fix) Neil: what we have today is fine. Restores terminal.css to match stablyai/orca main; the rest of #314 stays. --- src/renderer/src/assets/terminal.css | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/src/renderer/src/assets/terminal.css b/src/renderer/src/assets/terminal.css index f0ef9037901..1127ddff056 100644 --- a/src/renderer/src/assets/terminal.css +++ b/src/renderer/src/assets/terminal.css @@ -512,19 +512,6 @@ height: calc(100% - var(--orca-pane-title-height) - var(--pane-padding-y, 4px)); } -/* Narrow panes: the always-on header actions would cover row one (the agent's own header line), - so reserve the title row like a titled pane does. Wider panes keep the chromeless overlap. */ -.pane { - container: orca-pane / inline-size; -} - -@container orca-pane (max-width: 480px) { - .xterm-container { - margin-top: var(--orca-pane-title-height); - height: calc(100% - var(--orca-pane-title-height) - var(--pane-padding-y, 4px)); - } -} - /* A pane-top banner takes real height: the terminal starts below it and refits. */ .pane-top-banner { position: absolute; From f892a6d3f63eae8da4ec4e2ec44bd4a4a51c70c1 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 15:43:45 -0800 Subject: [PATCH 015/149] =?UTF-8?q?wip(cloud):=20composer-redo=20=E2=80=94?= =?UTF-8?q?=20Project=20|=20Run=20on=20row,=20setup=20moves=20to=20a=20ful?= =?UTF-8?q?l=20page=20after=20Start?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/app-shell/AppWorkspaceShell.tsx | 2 + .../components/NewWorkspaceComposerModal.tsx | 60 ++- .../NewWorkspaceComposerFooter.tsx | 51 +-- .../NewWorkspaceComposerProjectSection.tsx | 130 ++---- .../new-workspace/OrcaCloudSelectionHint.tsx | 283 ------------ .../new-workspace/RunTargetCombobox.tsx | 36 +- .../new-workspace/RunTargetOrcaCloudRow.tsx | 27 +- .../new-workspace/RunTargetRowList.tsx | 11 +- .../CloudSetupBrowserTracker.fixture.tsx | 207 --------- .../cloud-setup/CloudSetupBrowserTracker.tsx | 120 ----- .../cloud-setup-tracker-actions.ts | 2 +- .../cloud-setup/cloud-setup-tracker.test.ts | 20 - .../cloud-setup/use-cloud-setup-tracker.ts | 125 +----- .../new-workspace/composer-modal-data.ts | 2 + .../run-on/CloudStart.fixture.tsx | 328 -------------- .../run-on/CloudStartAgentRow.fixture.tsx | 33 -- .../run-on/CloudStartBilling.fixture.tsx | 37 -- .../run-on/CloudStartModalWidth.fixture.tsx | 120 ----- .../run-on/FolderGitHubActions.tsx | 30 -- .../run-on/OrcaCloudSetupPanel.tsx | 351 --------------- .../new-workspace/run-on/RunOnHintLine.tsx | 39 -- .../run-on/RunOnSegmentedControl.tsx | 212 --------- ...t.tsx => cloud-setup-session-copy.test.ts} | 2 +- .../run-on/cloud-setup-session-copy.ts | 30 ++ .../run-on/cloud-start-actions.ts | 51 +-- .../run-on/cloud-start-model.test.ts | 167 ++++--- .../new-workspace/run-on/cloud-start-model.ts | 101 +---- .../run-on/cloud-start-preview-fixture.tsx | 194 -------- .../new-workspace/run-on/cloud-start-view.ts | 14 +- .../run-on/use-cloud-start-composer.ts | 286 ++++-------- .../run-on/use-composer-cloud-start.ts | 19 +- .../run-on/use-setup-auto-start.ts | 42 -- .../use-run-target-orca-cloud.ts | 12 +- .../orca-cloud-setup/CloudSetupPage.tsx | 421 ++++++++++++++++++ .../orca-cloud-setup/CloudSetupPageLayer.tsx | 94 ++++ .../cloud-setup-page-model.test.ts | 57 +++ .../cloud-setup-page-model.ts | 137 ++++++ .../orca-cloud-setup/use-cloud-setup-flow.ts | 200 +++++++++ .../lib/orca-cloud/cloud-setup-page-store.ts | 80 ++++ 39 files changed, 1366 insertions(+), 2767 deletions(-) delete mode 100644 src/renderer/src/components/new-workspace/OrcaCloudSelectionHint.tsx delete mode 100644 src/renderer/src/components/new-workspace/cloud-setup/CloudSetupBrowserTracker.fixture.tsx delete mode 100644 src/renderer/src/components/new-workspace/cloud-setup/CloudSetupBrowserTracker.tsx delete mode 100644 src/renderer/src/components/new-workspace/run-on/CloudStart.fixture.tsx delete mode 100644 src/renderer/src/components/new-workspace/run-on/CloudStartAgentRow.fixture.tsx delete mode 100644 src/renderer/src/components/new-workspace/run-on/CloudStartBilling.fixture.tsx delete mode 100644 src/renderer/src/components/new-workspace/run-on/CloudStartModalWidth.fixture.tsx delete mode 100644 src/renderer/src/components/new-workspace/run-on/FolderGitHubActions.tsx delete mode 100644 src/renderer/src/components/new-workspace/run-on/OrcaCloudSetupPanel.tsx delete mode 100644 src/renderer/src/components/new-workspace/run-on/RunOnHintLine.tsx delete mode 100644 src/renderer/src/components/new-workspace/run-on/RunOnSegmentedControl.tsx rename src/renderer/src/components/new-workspace/run-on/{OrcaCloudSetupPanel.test.tsx => cloud-setup-session-copy.test.ts} (94%) create mode 100644 src/renderer/src/components/new-workspace/run-on/cloud-setup-session-copy.ts delete mode 100644 src/renderer/src/components/new-workspace/run-on/cloud-start-preview-fixture.tsx delete mode 100644 src/renderer/src/components/new-workspace/run-on/use-setup-auto-start.ts create mode 100644 src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx create mode 100644 src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx create mode 100644 src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.test.ts create mode 100644 src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.ts create mode 100644 src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts create mode 100644 src/renderer/src/lib/orca-cloud/cloud-setup-page-store.ts diff --git a/src/renderer/src/app-shell/AppWorkspaceShell.tsx b/src/renderer/src/app-shell/AppWorkspaceShell.tsx index df5297cb06d..cddedd2a414 100644 --- a/src/renderer/src/app-shell/AppWorkspaceShell.tsx +++ b/src/renderer/src/app-shell/AppWorkspaceShell.tsx @@ -10,6 +10,7 @@ import { RecoverableRenderErrorBoundary } from '../components/error-boundaries/R import { FloatingTerminalToggleButton } from '../components/floating-terminal/FloatingTerminalToggleButton' import { TerminalWorkbenchContainer } from '../components/TerminalWorkbenchContainer' import { WorkspaceLowDiskBanner } from '../components/low-disk/WorkspaceLowDiskBanner' +import { CloudSetupPageLayer } from '../components/orca-cloud-setup/CloudSetupPageLayer' import type { VirtualizedScrollAnchor } from '../hooks/useVirtualizedScrollAnchor' import { TitlebarLeftControls } from './TitlebarLeftControls' import { RightSidebarToggle, TitlebarMainStrip } from './TitlebarMainStrip' @@ -246,6 +247,7 @@ export function AppWorkspaceShell(props: {
+ {floatingWorkspace.showToggleButton && !capturingPluginShot ? (
) : null} - {/* Wraps instead of overflowing: "Use this computer instead" plus a long primary label - ("Give access and start") don't fit beside "Create more" in the modal's width. */} -
+ {/* One row: "Create more" on the left, the one primary button on the right. Run on never + adds buttons here; Orca Cloud setup happens on its own page after the button. */} +
{showCreateMultiple ? ( ) : null} -
- {cloudStart?.onUseThisComputer ? ( - - ) : null} - -
- {heldReason ? ( - - {heldReason} - - ) : null} +
) diff --git a/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx b/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx index 549cdbf3909..67078a12a40 100644 --- a/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx +++ b/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx @@ -1,11 +1,10 @@ -import React, { useState } from 'react' +import React from 'react' import { FolderPlus, LoaderCircle, PlugZap } from 'lucide-react' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import ProjectCombobox from '@/components/new-workspace/ProjectCombobox' import RunTargetCombobox from '@/components/new-workspace/RunTargetCombobox' import { ORCA_CLOUD_RECIPE_ID } from '../../../../shared/hosted-sandbox/orca-cloud-recipe-id' -import { OrcaCloudAgentSetupRow } from './OrcaCloudAgentSetupRow' import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/utils' import { getSelectedNewWorkspaceProjectOptionId } from '@/lib/new-workspace-project-options' @@ -15,15 +14,7 @@ import type { NewWorkspaceComposerCardProps } from './new-workspace-composer-card-props' import { EMPTY_PROJECT_OPTIONS } from './new-workspace-composer-card-props' -import { OrcaCloudSelectionHint } from './OrcaCloudSelectionHint' -import RunOnSegmentedControl from './run-on/RunOnSegmentedControl' -import { RunOnHintLine } from './run-on/RunOnHintLine' -import { OrcaCloudSetupPanel } from './run-on/OrcaCloudSetupPanel' -import { CloudSetupBrowserTracker } from './cloud-setup/CloudSetupBrowserTracker' -import { isOrcaCloudRecipe, isOrcaCloudSelection } from './run-target-options' -import { useOrcaCloudRunTargetAccess } from './orca-cloud-billing-cache' import type { OrcaCloudRunTargetAccess } from './orca-cloud-run-target-access' -import { FolderGitHubActions } from './run-on/FolderGitHubActions' type NewWorkspaceComposerProjectSectionProps = Pick< NewWorkspaceComposerCardProps, @@ -46,8 +37,7 @@ type NewWorkspaceComposerProjectSectionProps = Pick< | 'ephemeralVmRecipeError' | 'orcaCloudAvailability' | 'cloudStart' -> & - Partial> & { +> & { disabled?: boolean projectDescriptionId: string onAddProject: () => void @@ -102,7 +92,6 @@ export function NewWorkspaceComposerProjectSection({ connectButtonLabel, selectedProjectName, orcaCloudAccess, - quickAgent = null, cloudStart = null }: NewWorkspaceComposerProjectSectionProps): React.JSX.Element { // D4 rows: while Orca Cloud is picked, and for a folder, which can only start from GitHub. @@ -110,15 +99,12 @@ export function NewWorkspaceComposerProjectSection({ selectedEphemeralVmRecipeId === ORCA_CLOUD_RECIPE_ID || cloudStart?.folderProject ? cloudStart?.cloudOnly : undefined - const [pickerSignal, setPickerSignal] = useState(0) const t = useTranslate() - const orcaCloudOffered = shouldShowRunTargetPicker && ephemeralVmRecipes.some(isOrcaCloudRecipe) - // Shared with the picker; mounting the composer prefetches it so the row rarely shows a skeleton. - const fetchedOrcaCloudAccess = useOrcaCloudRunTargetAccess(orcaCloudOffered && !orcaCloudAccess) return (
- {/* Run on as segments needs the full width, so it sits under the project (spec E1). */} -
+ {/* One row, two equal columns: Project | Run on. Picking a target never changes the rows + below it, so the dialog keeps its height (composer-redo). */} +
) : null}
- {cloudStart?.tracker && selectedEphemeralVmRecipeId === ORCA_CLOUD_RECIPE_ID ? ( - // A6: the browser trip is open; the same rows tick in place, with X1 errors. - - ) : cloudStart?.panelVisible && selectedEphemeralVmRecipeId === ORCA_CLOUD_RECIPE_ID ? ( - // The panel's own Agent row (G) comes from the same model as the standalone one below. - setPickerSignal((n) => n + 1)} - onAddProject={onAddProject} - /> - ) - } - : cloudStart.rowActions - } - /> - ) : // Agent row (cloud-start G) without the panel: links to the one-time setup; never blocks Start. - selectedEphemeralVmRecipeId === ORCA_CLOUD_RECIPE_ID ? ( - - ) : null} {!shouldShowRunTargetPicker && ephemeralVmRecipeError ? (

{ephemeralVmRecipeError}

) : null} diff --git a/src/renderer/src/components/new-workspace/OrcaCloudSelectionHint.tsx b/src/renderer/src/components/new-workspace/OrcaCloudSelectionHint.tsx deleted file mode 100644 index e8e371d777f..00000000000 --- a/src/renderer/src/components/new-workspace/OrcaCloudSelectionHint.tsx +++ /dev/null @@ -1,283 +0,0 @@ -import React from 'react' -import { cn } from '@/lib/utils' -import { useTranslate } from '@/i18n/use-translate' -import { getOrcaCloudPick, type OrcaCloudRunTargetAccess } from './orca-cloud-run-target-access' -import { invalidateOrcaCloudBilling } from './orca-cloud-billing-cache' -import { openPlansPage } from '@/components/billing/plans/plans-page-store' -import { ORCA_CLOUD_IDLE_SLEEP_MINUTES } from '../../../../shared/hosted-sandbox/hosted-sandbox-wire' -import { OrcaCloudSpecs, useOrcaCloudHoursLeft } from './RunTargetOrcaCloudRow' -import { isOrcaCloudTrialLow } from './run-on/orca-cloud-hours-copy' - -/** T1: "Trial · 0.3 sandbox hours left · Choose plan", or who can choose one for members. */ -function TrialLowLine({ - access, - hoursLeft -}: { - access: OrcaCloudRunTargetAccess - hoursLeft: string | null -}): React.JSX.Element { - const t = useTranslate() - const canChoose = access.state === 'entitled' && access.canManageBilling === true - return ( - <> -

- {hoursLeft} - {canChoose ? ( - <> - · - - - ) : null} -

-

- {canChoose - ? t( - 'auto.components.new.workspace.RunTargetCombobox.orcaCloudIdleSleep', - 'Sleeps after {{count}} minutes idle', - { - count: ORCA_CLOUD_IDLE_SLEEP_MINUTES, - defaultValue_one: 'Sleeps after {{count}} minute idle' - } - ) - : t( - 'components.newWorkspace.cloudSetup.askChoosePlan', - 'Ask an owner or admin to choose a plan.' - )} -

- - ) -} - -type BlockCopy = { - title: string - detail: string - tone: 'error' | 'neutral' - /** Owners/admins only; members read who can fix it in `detail`. */ - action?: string -} - -function useBlockCopy(access: OrcaCloudRunTargetAccess): BlockCopy | null { - const t = useTranslate() - switch (access.state) { - case 'no-plan': - if (access.trialOfferSeconds) { - // B1: the trial is included; Start claims it, so nothing blocks. - return null - } - if (access.trialUsedUp) { - // T2: neutral, nothing failed. - return { - title: t('components.newWorkspace.cloudSetup.trialUsedUpTitle', 'Your trial is used up'), - detail: access.canManageBilling - ? t( - 'components.newWorkspace.cloudSetup.trialUsedUpChoose', - 'Choose a plan to keep using Orca Cloud.' - ) - : t( - 'components.newWorkspace.cloudSetup.askChoosePlan', - 'Ask an owner or admin to choose a plan.' - ), - tone: 'neutral', - ...(access.canManageBilling - ? { action: t('components.newWorkspace.cloudSetup.choosePlan', 'Choose plan') } - : {}) - } - } - return { - title: access.lapsed - ? t( - 'auto.components.new.workspace.RunTargetCombobox.orcaCloudPlanEnded', - 'Your Team plan ended' - ) - : t( - 'auto.components.new.workspace.RunTargetCombobox.orcaCloudNeedsTeamPlan', - 'Orca Cloud needs a Team plan.' - ), - detail: access.canManageBilling - ? '' - : t( - 'auto.components.new.workspace.RunTargetCombobox.orcaCloudAskChoosePlan', - 'Ask an owner or admin to choose one.' - ), - tone: 'neutral', - ...(access.canManageBilling - ? { - action: access.lapsed - ? t('auto.components.new.workspace.RunTargetCombobox.orcaCloudRenew', 'Renew') - : t('auto.components.new.workspace.RunTargetCombobox.orcaCloudUpgrade', 'Upgrade') - } - : {}) - } - case 'out-of-hours': { - const cap = access.cause === 'cap' - // Create time: no workspace exists yet, so "Your files are safe." does not apply here. - return { - title: cap - ? t( - 'auto.components.new.workspace.RunTargetCombobox.orcaCloudCapReached', - 'Spend cap reached' - ) - : t( - 'auto.components.new.workspace.RunTargetCombobox.orcaCloudOutOfHours', - 'Out of sandbox hours' - ), - detail: access.canManageBilling - ? '' - : cap - ? t( - 'auto.components.new.workspace.RunTargetCombobox.orcaCloudAskRaiseSpendCap', - 'Ask an owner or admin to raise the spend cap.' - ) - : t( - 'auto.components.new.workspace.RunTargetCombobox.orcaCloudAskAddHoursOnly', - 'Ask an owner or admin to add hours.' - ), - tone: 'neutral', - ...(access.canManageBilling - ? { - action: - access.cause === 'cap' - ? t( - 'auto.components.new.workspace.RunTargetCombobox.orcaCloudRaiseSpendCap', - 'Raise spend cap' - ) - : t( - 'auto.components.new.workspace.RunTargetCombobox.orcaCloudTurnOnOverage', - 'Turn on overage' - ) - } - : {}) - } - } - case 'payment-issue': - return { - title: t( - 'auto.components.new.workspace.RunTargetCombobox.orcaCloudPaymentFailed', - 'Payment failed' - ), - detail: access.canManageBilling - ? t( - 'auto.components.new.workspace.RunTargetCombobox.orcaCloudPaymentEffect', - "New sandboxes can't start." - ) - : t( - 'auto.components.new.workspace.RunTargetCombobox.orcaCloudAskPayment', - 'Ask an owner or admin to update the payment method.' - ), - tone: 'error', - ...(access.canManageBilling - ? { - action: t( - 'auto.components.new.workspace.RunTargetCombobox.orcaCloudUpdatePaymentMethod', - 'Update payment method' - ) - } - : {}) - } - case 'loading': - case 'unknown': - case 'signed-out': - case 'entitled': - return null - } -} - -/** - * Context under Run on once Orca Cloud is the committed target, in exactly two reserved lines so - * neither picking nor a late billing answer moves the form: specs and sandbox hours over idle - * sleep, or what blocks it over who can fix it, with the fix as an inline link. The wrapper is an - * always-mounted polite live region, so a block that arrives after the pick is announced. - */ -export function OrcaCloudSelectionHint({ - access, - visible -}: { - access: OrcaCloudRunTargetAccess - /** Orca Cloud is the committed target; otherwise the two lines stay empty. */ - visible: boolean -}): React.JSX.Element { - const t = useTranslate() - const block = useBlockCopy(access) - const hoursLeft = useOrcaCloudHoursLeft(access) - // T1: under half an hour of trial left, announced once as it crosses (the live region below). - const low = isOrcaCloudTrialLow(access) - const pick = getOrcaCloudPick(access) - const action = - block?.action && pick.kind === 'act' ? ( - - ) : null - return ( - // @container: the specs drop out whole when the column is narrow, instead of ellipsizing. -
- {visible && !block && !low ? ( - // Outside the live region: hour ticks on refresh are not re-announced. - <> -

- - - - {hoursLeft ? ( - // pl-1: a flex item trims its leading space, so the gap before "·" comes from padding. - - {'· '} - {hoursLeft} - - ) : null} -

-

- {/* One source for n: the control plane, billing and every surface read this constant. */} - {t( - 'auto.components.new.workspace.RunTargetCombobox.orcaCloudIdleSleep', - 'Sleeps after {{count}} minutes idle', - { - count: ORCA_CLOUD_IDLE_SLEEP_MINUTES, - defaultValue_one: 'Sleeps after {{count}} minute idle' - } - )} -

- - ) : null} - {/* Always mounted, so a block that arrives after the pick (late billing, restored draft) is announced. */} -
- {visible && !block && low ? : null} - {visible && block ? ( - <> -

- {block.tone === 'error' ? ( - - ) : null} - {block.title} - {action ? · : null} - {action} -

- {block.detail ?

{block.detail}

: null} - - ) : null} -
-
- ) -} diff --git a/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx b/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx index b07abf4670e..ec6ce2b237c 100644 --- a/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx @@ -9,6 +9,7 @@ import { type ReadyProjectHostSetupOption } from '@/lib/project-host-setup-options' import type { ExecutionHostId } from '../../../../shared/execution-host' +import { ORCA_CLOUD_RECIPE_ID } from '../../../../shared/hosted-sandbox/orca-cloud-recipe-id' import { isWithinComboboxRoot, useTypeAheadCombobox } from './use-type-ahead-combobox' import { COMBOBOX_POPOVER_SURFACE } from './type-ahead-combobox-styles' import { @@ -17,6 +18,9 @@ import { getRecipeSubmenuItemKey, getRunTargetSubmenuItemKeys, getRunTargetCurrentRowKey, + getOrcaCloudDetail, + ORCA_CLOUD_LABEL, + RUN_TARGET_ORCA_CLOUD_KEY, getRunTargetOptionId, RUN_TARGET_ADD_HOST_KEY, RUN_TARGET_ADD_REMOTE_SERVER_ITEM, @@ -50,6 +54,11 @@ type RunTargetComboboxProps = { orcaCloudAccess?: OrcaCloudRunTargetAccess /** From main: drives the sign-in/upsell row when there is no Orca Cloud recipe. */ orcaCloudAvailability?: OrcaCloudAvailability + /** + * The composer's pick: Orca Cloud is selected even while the account needs setup, which then + * happens on a page after Start. Without it, a blocked account's pick runs the fix instead. + */ + onSelectOrcaCloud?: () => void } /** Add-host actions open dialogs, so the picker closes before they run. */ @@ -81,7 +90,8 @@ export default function RunTargetCombobox({ onConnectHost, onSetLocation, orcaCloudAccess: orcaCloudAccessOverride, - orcaCloudAvailability = 'unavailable' + orcaCloudAvailability = 'unavailable', + onSelectOrcaCloud }: RunTargetComboboxProps): React.JSX.Element { const t = useTranslate() // Track in-flight connects per host so one stalling connect never blocks the others. @@ -100,8 +110,13 @@ export default function RunTargetCombobox({ // An unlisted target (e.g. a per-workspace VM) shows "Choose target", never another host's name (#38669). null const selectedRecipe = recipes.find((recipe) => recipe.id === recipeValue) ?? null + // Signed out, main lists no Orca Cloud recipe, yet the composer can still pick it. + const orcaCloudPicked = + selectedRecipe === null && recipeValue === ORCA_CLOUD_RECIPE_ID && Boolean(onSelectOrcaCloud) // Opening highlights the committed row, so only one row reads as chosen. - const currentRowKey = getRunTargetCurrentRowKey(selectedRecipe, selectedHost) + const currentRowKey = orcaCloudPicked + ? RUN_TARGET_ORCA_CLOUD_KEY + : getRunTargetCurrentRowKey(selectedRecipe, selectedHost) const hasAddHost = Boolean(onAddSshHost || onAddRemoteServer) const orcaCloudOffer = getRunTargetOrcaCloudOffer({ @@ -137,7 +152,8 @@ export default function RunTargetCombobox({ const { submenu, armedItemKey, openSubmenu, closeSubmenu, armItem, moveItemArm, armItemEdge } = useRunTargetSubmenu(submenuItemKeys) const armedRow = rows.find((row) => row.key === armedKey) ?? rows[0] ?? null - const committed = query.length === 0 && (selectedRecipe !== null || selectedHost !== null) + const committed = + query.length === 0 && (orcaCloudPicked || selectedRecipe !== null || selectedHost !== null) // Closing also drops any open submenu, which the shared hook doesn't know about. const close = useCallback((): void => { @@ -173,7 +189,8 @@ export default function RunTargetCombobox({ override: orcaCloudAccessOverride, open, close, - selectRecipe + selectRecipe, + ...(onSelectOrcaCloud ? { onSelectOrcaCloud } : {}) }) const addSshHost = useMemo(() => closingFirst(close, onAddSshHost), [close, onAddSshHost]) @@ -307,7 +324,9 @@ export default function RunTargetCombobox({ const activeDescendantId = activeDescendantKey ? optionIdFor(activeDescendantKey) : undefined const addHostOptionId = optionIdFor(RUN_TARGET_ADD_HOST_KEY) - const field = getRunTargetFieldText(selectedRecipe, selectedHost, t) + const field = orcaCloudPicked + ? { label: ORCA_CLOUD_LABEL, detail: getOrcaCloudDetail(t), recipeKind: 'orca-cloud' as const } + : getRunTargetFieldText(selectedRecipe, selectedHost, t) return ( @@ -323,7 +342,7 @@ export default function RunTargetCombobox({ onToggle={() => setOpen(!open)} committed={committed} recipeKind={field.recipeKind} - hostId={selectedHost?.hostId ?? null} + hostId={orcaCloudPicked ? null : (selectedHost?.hostId ?? null)} label={field.label} detail={field.detail} controlsId={submenu ? `${listId} ${listId}-${submenu}` : listId} @@ -377,8 +396,8 @@ export default function RunTargetCombobox({ void connectHost(option)} onSetLocation={setLocation} /> diff --git a/src/renderer/src/components/new-workspace/RunTargetOrcaCloudRow.tsx b/src/renderer/src/components/new-workspace/RunTargetOrcaCloudRow.tsx index c3f574b3f7e..fbd4fd07101 100644 --- a/src/renderer/src/components/new-workspace/RunTargetOrcaCloudRow.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetOrcaCloudRow.tsx @@ -270,6 +270,22 @@ function OrcaCloudMeta({ } } +/** Hours left, the loading skeleton, and "Ask an owner or admin" still say something useful. */ +function showsMetaAfterStart(access: OrcaCloudRunTargetAccess): boolean { + switch (access.state) { + case 'loading': + case 'entitled': + return true + case 'no-plan': + case 'out-of-hours': + case 'payment-issue': + return !access.canManageBilling + case 'signed-out': + case 'unknown': + return false + } +} + /** Orca Cloud as a first-class Run-on target, with its hours or the fix for what blocks it. */ export function RunTargetOrcaCloudRow({ recipe, @@ -280,7 +296,8 @@ export function RunTargetOrcaCloudRow({ optionId, onArm, onSelect, - onBlockedAction + onBlockedAction, + setupAfterStart = false }: { recipe: EphemeralVmRecipeOption | null access: OrcaCloudRunTargetAccess @@ -292,6 +309,8 @@ export function RunTargetOrcaCloudRow({ onArm: () => void onSelect: () => void onBlockedAction: () => void + /** The composer walks setup on a page after Start: no inline Sign in / Upgrade here. */ + setupAfterStart?: boolean }): React.JSX.Element { const t = useTranslate() return ( @@ -320,7 +339,11 @@ export function RunTargetOrcaCloudRow({ onArm={onArm} onCommit={onSelect} description={orcaCloudRowHint(access, t)} - trailing={} + trailing={ + setupAfterStart && !showsMetaAfterStart(access) ? undefined : ( + + ) + } /> ) } diff --git a/src/renderer/src/components/new-workspace/RunTargetRowList.tsx b/src/renderer/src/components/new-workspace/RunTargetRowList.tsx index 89fe146ff91..7ebb22ae534 100644 --- a/src/renderer/src/components/new-workspace/RunTargetRowList.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetRowList.tsx @@ -10,6 +10,7 @@ import { RunTargetOrcaCloudRow } from './RunTargetOrcaCloudRow' import { needsSetupRowHint } from './run-target-row-hints' import { useTranslate } from '@/i18n/use-translate' import type { OrcaCloudRunTargetAccess } from './orca-cloud-run-target-access' +import { ORCA_CLOUD_RECIPE_ID } from '../../../../shared/hosted-sandbox/orca-cloud-recipe-id' import type { EphemeralVmRecipeOption, RunTargetRowModel } from './run-target-options' /** The scrolling rows of the run-target picker; "Add host" is pinned outside this list. */ @@ -34,6 +35,7 @@ export default function RunTargetRowList({ onSelectRecipe, onSelectOrcaCloud, onOrcaCloudBlockedAction, + orcaCloudSetupAfterStart = false, onConnectHost, onSetLocation }: { @@ -61,6 +63,8 @@ export default function RunTargetRowList({ onSelectOrcaCloud: (recipe: EphemeralVmRecipeOption | null) => void /** Plans or billing, for an account that cannot start a sandbox. */ onOrcaCloudBlockedAction: () => void + /** Picking Orca Cloud just picks it; setup comes after Start, so the row offers no fixes. */ + orcaCloudSetupAfterStart?: boolean onConnectHost: (option: NeedsSetupProjectHostOption) => void onSetLocation: (option: NeedsSetupProjectHostOption) => void }): React.JSX.Element { @@ -96,11 +100,16 @@ export default function RunTargetRowList({ access={orcaCloudAccess} pending={orcaCloudPending} armed={isArmed} - current={row.recipe !== null && row.recipe.id === selectedRecipeId} + current={ + row.recipe !== null + ? row.recipe.id === selectedRecipeId + : selectedRecipeId === ORCA_CLOUD_RECIPE_ID + } optionId={optionId} onArm={() => onArm(row.key, null)} onSelect={() => onSelectOrcaCloud(row.recipe)} onBlockedAction={onOrcaCloudBlockedAction} + setupAfterStart={orcaCloudSetupAfterStart} /> ) } diff --git a/src/renderer/src/components/new-workspace/cloud-setup/CloudSetupBrowserTracker.fixture.tsx b/src/renderer/src/components/new-workspace/cloud-setup/CloudSetupBrowserTracker.fixture.tsx deleted file mode 100644 index b62a4e322e6..00000000000 --- a/src/renderer/src/components/new-workspace/cloud-setup/CloudSetupBrowserTracker.fixture.tsx +++ /dev/null @@ -1,207 +0,0 @@ -import { defineFixture } from '../../../component-fixtures/component-fixture' -import { OrcaCloudSetupPanel } from '@/components/new-workspace/run-on/OrcaCloudSetupPanel' -import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model' -import { CloudSetupBrowserTracker } from './CloudSetupBrowserTracker' -import { CloudSetupErrorNotice } from './CloudSetupErrorNotice' -import { useCloudSetupSwitchTeamFor } from './CloudSetupSwitchTeam' -import type { CloudSetupError } from './cloud-setup-errors' -import type { PlannedTeam } from './use-switch-to-planned-team' - -const noop = (): void => {} -// Agent row in agent-accounts v4 wording (glossary "Agent source"). -const NOT_SET_UP = - 'Claude isn’t set up for Orca Cloud yet. Set it up once in Settings → Agent accounts.' -const FROM_ACCOUNT = 'Claude · from your Orca account' -const SET_UP_ONCE = { label: 'Set up once', onClick: noop } - -// A6: account and team done in the browser, GitHub in progress. -const waitingGithub: CloudSetupStep[] = [ - { id: 'account', state: 'done', detail: 'neil@acme.dev' }, - { id: 'team', state: 'done', detail: 'acme · 2 sandbox hours to try Orca Cloud' }, - { id: 'github', state: 'active', detail: 'Waiting for GitHub…' }, - { id: 'agent', state: 'optional', detail: NOT_SET_UP, action: SET_UP_ONCE } -] - -// Rows derived from billing before the setup session exists: the plan row is the browser's. -const derived: CloudSetupStep[] = [ - { id: 'account', state: 'done' }, - { id: 'plan', state: 'needed', need: 'plan', canFix: true }, - { id: 'agent', state: 'optional', detail: NOT_SET_UP, action: SET_UP_ONCE } -] - -// Signed in, nothing finished yet: the account step is in the browser. -const signingIn: CloudSetupStep[] = [ - { id: 'account', state: 'active' }, - { id: 'team', state: 'pending' }, - { id: 'github', state: 'pending' }, - { id: 'agent', state: 'optional', detail: NOT_SET_UP, action: SET_UP_ONCE } -] - -function Tracker({ - steps = waitingGithub, - error = null, - canManageBilling = true -}: { - steps?: CloudSetupStep[] - error?: CloudSetupError | null - canManageBilling?: boolean -}): React.JSX.Element { - return ( -
- -
- ) -} - -export const trackerWaitingGithub = defineFixture({ width: 560, render: () => }) -export const trackerSigningIn = defineFixture({ - width: 560, - render: () => -}) -export const trackerDerivedRows = defineFixture({ - width: 560, - render: () => -}) - -const stopped: CloudSetupStep[] = [ - { id: 'account', state: 'done', detail: 'neil@acme.dev' }, - { id: 'team', state: 'done', detail: 'acme' }, - { id: 'plan', state: 'needed', need: 'plan', canFix: true }, - { id: 'agent', state: 'optional', detail: NOT_SET_UP, action: SET_UP_ONCE } -] - -export const trackerTimedOut = defineFixture({ - width: 560, - render: () => -}) -export const trackerCheckoutCanceled = defineFixture({ - width: 560, - render: () => -}) -export const trackerBankStep = defineFixture({ - width: 560, - render: () => -}) -export const trackerTrialUnavailable = defineFixture({ - width: 560, - render: () => -}) -export const trackerTrialUnavailableMember = defineFixture({ - width: 560, - render: () => ( - - ) -}) -export const trackerTeamCreateFailed = defineFixture({ - width: 560, - render: () => ( - - ) -}) -export const trackerWrongAccount = defineFixture({ - width: 560, - render: () => ( - - ) -}) - -// X1: every setup error notice, as in the spec's sheet. -export const x1SetupErrors = defineFixture({ - width: 560, - render: () => ( -
- {( - [ - { kind: 'timed_out' }, - { kind: 'checkout_canceled' }, - { kind: 'bank_step' }, - { kind: 'trial_unavailable' }, - { kind: 'team_create_failed' }, - { kind: 'wrong_account', detail: 'sam@other.dev', teamName: 'acme' } - ] satisfies CloudSetupError[] - ).map((error) => ( - - ))} - -
- ) -}) - -// B1: an owner whose team never had a trial: the trial is the first plan, no trip. -export const b1OwnerTrialAvailable = defineFixture({ - width: 560, - render: () => ( -
- -
- ) -}) - -function SwitchTeamPanel({ teams }: { teams: PlannedTeam[] }): React.JSX.Element { - const b2 = useCloudSetupSwitchTeamFor(teams, noop) - return ( -
- -
- ) -} - -// B2: personal account, but a team the user is on has a plan: switch instead of buying. -export const b2SwitchTeam = defineFixture({ - width: 560, - render: () => -}) -export const b2SwitchTeamMenu = defineFixture({ - width: 560, - render: () => ( - - ) -}) diff --git a/src/renderer/src/components/new-workspace/cloud-setup/CloudSetupBrowserTracker.tsx b/src/renderer/src/components/new-workspace/cloud-setup/CloudSetupBrowserTracker.tsx deleted file mode 100644 index 8b053dca6c1..00000000000 --- a/src/renderer/src/components/new-workspace/cloud-setup/CloudSetupBrowserTracker.tsx +++ /dev/null @@ -1,120 +0,0 @@ -// A6 "Finish in your browser": while the one setup tab is open, the panel ticks each step in place -// (from the setup session, or rows derived from billing until it exists), says why it stopped (X1) -// and keeps the way back to the browser one click away. The prompt stays editable above it. -import React from 'react' -import { Copy, ExternalLink } from 'lucide-react' -import { Button } from '@/components/ui/button' -import { useTranslate } from '@/i18n/use-translate' -import { OrcaCloudSetupPanel } from '@/components/new-workspace/run-on/OrcaCloudSetupPanel' -import type { - CloudSetupStep, - CloudSetupStepId -} from '@/components/new-workspace/run-on/cloud-start-model' -import { reportCloudSetupProgress } from '@/lib/orca-cloud/cloud-setup-telemetry' -import { CloudSetupErrorNotice } from './CloudSetupErrorNotice' -import type { CloudSetupError, CloudSetupErrorAction } from './cloud-setup-errors' - -export type CloudSetupBrowserTrackerProps = { - steps: readonly CloudSetupStep[] - /** Why setup stopped (X1), from the session's `error`; null while it's going. */ - error: CloudSetupError | null - /** Members get "Ask an owner or admin…" instead of Choose plan on trial_unavailable. */ - canManageBilling?: boolean - /** Setup session id, for telemetry only (never sent). Omit for derived rows. */ - sessionId?: string | null - /** Ends the trip; finished steps stay done. */ - onCancel: () => void - /** For a default browser that's the wrong one; hidden when there's no session link to copy. */ - onCopyLink?: () => void - onReopen: () => void - onErrorAction: (action: CloudSetupErrorAction) => void - /** Per-row actions passed through to the panel (e.g. the Agent row's "Set up once"). */ - rowActions?: Partial> - /** Trial → plan conversion context for telemetry. */ - afterTrial?: boolean - className?: string -} - -/** - * Rows derived from billing (before the setup session reports its own) never say 'active'. While - * the browser is open, the first unfinished required row is the one it's working on, so it reads - * "In browser" rather than "Needed". Session rows that already mark a step active pass through. - */ -export function trackerSteps( - steps: readonly CloudSetupStep[], - stopped: boolean -): readonly CloudSetupStep[] { - if (stopped || steps.some((step) => step.state === 'active')) { - return steps - } - const index = steps.findIndex((step) => step.state === 'needed') - if (index === -1) { - return steps - } - return steps.map((step, i) => (i === index ? { ...step, state: 'active' } : step)) -} - -export function CloudSetupBrowserTracker({ - steps, - error, - canManageBilling = true, - sessionId = null, - onCancel, - onCopyLink, - onReopen, - onErrorAction, - rowActions, - afterTrial = false, - className -}: CloudSetupBrowserTrackerProps): React.JSX.Element { - const t = useTranslate() - const errorKind = error?.kind ?? null - const rows = React.useMemo(() => trackerSteps(steps, error !== null), [steps, error]) - React.useEffect(() => { - if (sessionId) { - reportCloudSetupProgress(sessionId, rows, errorKind, { afterTrial }) - } - }, [sessionId, rows, errorKind, afterTrial]) - // The error's own button already offers the browser for these; don't show it twice. - const reopenInError = error !== null && (error.kind === 'timed_out' || error.kind === 'bank_step') - return ( - - {error ? ( - - ) : null} -
- - - {onCopyLink ? ( - - ) : null} - {reopenInError ? null : ( - - )} - -
-
- ) -} diff --git a/src/renderer/src/components/new-workspace/cloud-setup/cloud-setup-tracker-actions.ts b/src/renderer/src/components/new-workspace/cloud-setup/cloud-setup-tracker-actions.ts index b8ef4759f3e..fec4b5f528e 100644 --- a/src/renderer/src/components/new-workspace/cloud-setup/cloud-setup-tracker-actions.ts +++ b/src/renderer/src/components/new-workspace/cloud-setup/cloud-setup-tracker-actions.ts @@ -21,7 +21,7 @@ function linkUnavailable(): void { toast.error( translate( 'components.newWorkspace.cloudSetup.linkUnavailable', - 'Couldn’t get a setup link. Try Set up and start again.' + 'Couldn’t get a setup link. Try Continue in browser again.' ) ) } diff --git a/src/renderer/src/components/new-workspace/cloud-setup/cloud-setup-tracker.test.ts b/src/renderer/src/components/new-workspace/cloud-setup/cloud-setup-tracker.test.ts index a169c440a3e..913f163430c 100644 --- a/src/renderer/src/components/new-workspace/cloud-setup/cloud-setup-tracker.test.ts +++ b/src/renderer/src/components/new-workspace/cloud-setup/cloud-setup-tracker.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from 'vitest' import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model' -import { trackerSteps } from './CloudSetupBrowserTracker' import { applySwitchTeamStep } from './CloudSetupSwitchTeam' const derived: CloudSetupStep[] = [ @@ -9,25 +8,6 @@ const derived: CloudSetupStep[] = [ { id: 'agent', state: 'optional' } ] -describe('trackerSteps', () => { - it('marks the first open row as the browser’s for rows derived from billing', () => { - expect(trackerSteps(derived, false).map((step) => step.state)).toEqual([ - 'done', - 'active', - 'optional' - ]) - }) - - it('passes session rows that already say active, and stopped trips, through', () => { - const session: CloudSetupStep[] = [ - { id: 'account', state: 'active' }, - { id: 'team', state: 'needed' } - ] - expect(trackerSteps(session, false)).toBe(session) - expect(trackerSteps(derived, true)).toBe(derived) - }) -}) - describe('applySwitchTeamStep', () => { const team: CloudSetupStep = { id: 'team', state: 'needed', detail: 'acme has a Team plan.' } diff --git a/src/renderer/src/components/new-workspace/cloud-setup/use-cloud-setup-tracker.ts b/src/renderer/src/components/new-workspace/cloud-setup/use-cloud-setup-tracker.ts index a4b64b924a5..7db939a3c06 100644 --- a/src/renderer/src/components/new-workspace/cloud-setup/use-cloud-setup-tracker.ts +++ b/src/renderer/src/components/new-workspace/cloud-setup/use-cloud-setup-tracker.ts @@ -1,117 +1,11 @@ -// The composer's side of the setup tracker (A6/X1) and the B2 switch row: what the tracker shows -// while the browser trip is open, and the setup rows with B2's Team row swapped in. -import { useCallback, useMemo, type ReactNode } from 'react' -import { readCloudStartDraft, saveCloudStartDraft } from '@/lib/orca-cloud/cloud-start-draft' -import type { CloudSetupSessionSnapshot } from '@/lib/orca-cloud/cloud-setup-session-seam' -import type { - CloudSetupStep, - CloudSetupStepId -} from '@/components/new-workspace/run-on/cloud-start-model' -import { setupActionFor } from '@/components/new-workspace/run-on/cloud-start-actions' -import type { OrcaCloudRunTargetAccess } from '../orca-cloud-run-target-access' -import type { OrcaCloudAvailability } from '../../../../../shared/orca-yaml-hook-types' -import type { CloudSetupBrowserTrackerProps } from './CloudSetupBrowserTracker' +// B2 for Orca Cloud setup: the setup rows with the "Switch to " Team row swapped in. +import { useMemo } from 'react' +import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model' import { applySwitchTeamStep, useCloudSetupSwitchTeam, type CloudSetupSwitchTeam } from './CloudSetupSwitchTeam' -import { parseCloudSetupError } from './cloud-setup-errors' -import { - canCopyCloudSetupLink, - copyCloudSetupLink, - reopenCloudSetup -} from './cloud-setup-tracker-actions' - -export type CloudSetupTrackerView = Omit< - CloudSetupBrowserTrackerProps, - 'steps' | 'rowActions' | 'className' -> - -/** What the tracker and B2 add to the composer's CloudStartView. */ -export type CloudSetupViewExtras = { - /** Per-row actions in the setup panel (B2's "Switch to "). */ - rowActions?: Partial> - /** While the setup trip is open in the browser: the tracker replaces the panel (A6, X1). */ - tracker?: CloudSetupTrackerView - /** Start is held (aria-disabled) with this reason, e.g. "Switch to acme first" (B2). */ - primaryHeldReason?: string -} - -/** "Cancel setup": the draft keeps its prompt but forgets the trip (finished steps stay done). */ -export function clearCloudSetupSessionFromDraft(profileId: string | null): void { - const draft = readCloudStartDraft(profileId) - if (draft) { - saveCloudStartDraft(profileId, { ...draft, setupSessionId: null }) - } -} - -/** - * The tracker's props while a trip from this composer is still waiting in the browser, or stopped - * on an error; undefined otherwise. Rows derived from billing (no session yet) work too: Reopen then - * re-runs today's setup action and there is no link to copy. - */ -export function useComposerSetupTracker({ - cloudSelected, - setupStarted, - allSet, - readyToStart, - session, - sessionId, - steps, - access, - availability, - profileId, - runSetup, - onCancel -}: { - cloudSelected: boolean - setupStarted: boolean - allSet: boolean - readyToStart: boolean - session: CloudSetupSessionSnapshot | null - sessionId: string | null - steps: readonly CloudSetupStep[] - access: OrcaCloudRunTargetAccess - availability: OrcaCloudAvailability - profileId: string | null - /** A fresh setup trip for whatever is still open. */ - runSetup: () => void - /** Ends the trip in the composer; the draft forgets the session here. */ - onCancel: () => unknown -}): CloudSetupTrackerView | undefined { - const error = useMemo(() => { - const parsed = parseCloudSetupError(session?.error) - return parsed && session?.teamName ? { ...parsed, teamName: session.teamName } : parsed - }, [session?.error, session?.teamName]) - const open = cloudSelected && setupStarted && !allSet && (!readyToStart || error !== null) - const rerun = useCallback( - () => setupActionFor(steps, access, availability)?.(), - [access, availability, steps] - ) - const canManageBilling = access.state === 'no-plan' ? access.canManageBilling : true - return useMemo(() => { - if (!open) { - return undefined - } - const reopen = (): void => void reopenCloudSetup(sessionId, rerun) - return { - error, - canManageBilling, - sessionId, - onCancel: () => { - onCancel() - clearCloudSetupSessionFromDraft(profileId) - }, - ...(sessionId && canCopyCloudSetupLink(sessionId) - ? { onCopyLink: () => void copyCloudSetupLink(sessionId) } - : {}), - onReopen: reopen, - // A canceled Checkout, a used trial or a failed team: a fresh trip covers what's still open. - onErrorAction: (action) => (action === 'reopen-browser' ? reopen() : runSetup()) - } - }, [canManageBilling, error, onCancel, open, profileId, rerun, runSetup, sessionId]) -} /** B2 applied to the setup rows: the rows to show, and the switch when it holds Start. */ export function useSwitchTeamSteps( @@ -126,16 +20,3 @@ export function useSwitchTeamSteps( ) return { steps: switched ?? baseSteps, held: switched ? switchTeam : null } } - -/** The view fields the tracker and B2 add. */ -export function setupViewExtras( - switchTeam: CloudSetupSwitchTeam | null, - tracker: CloudSetupTrackerView | undefined -): CloudSetupViewExtras { - return { - ...(switchTeam - ? { rowActions: { team: switchTeam.action }, primaryHeldReason: switchTeam.startHeldReason } - : {}), - ...(tracker ? { tracker } : {}) - } -} diff --git a/src/renderer/src/components/new-workspace/composer-modal-data.ts b/src/renderer/src/components/new-workspace/composer-modal-data.ts index 482ac94c762..0a2a0f21224 100644 --- a/src/renderer/src/components/new-workspace/composer-modal-data.ts +++ b/src/renderer/src/components/new-workspace/composer-modal-data.ts @@ -38,4 +38,6 @@ export type ComposerModalData = { telemetrySource?: WorkspaceCreateTelemetrySource contextualTourSource?: string setupGuideTourRequestId?: string + /** Orca Cloud setup finished on its page: submit without showing the dialog (falls back to it). */ + cloudAutoStart?: boolean } diff --git a/src/renderer/src/components/new-workspace/run-on/CloudStart.fixture.tsx b/src/renderer/src/components/new-workspace/run-on/CloudStart.fixture.tsx deleted file mode 100644 index 177660c20a0..00000000000 --- a/src/renderer/src/components/new-workspace/run-on/CloudStart.fixture.tsx +++ /dev/null @@ -1,328 +0,0 @@ -// "Start in Orca Cloud" composer frames from cloud-start-onboarding spec v2: E1, A1, A6, A7, T1, -// T2, E, X2, the panel's GitHub rows D1–D3 and D4's GitHub-only projects. Entry points and T4 are in CloudStartSurfaces. -import { defineFixture } from '../../../component-fixtures/component-fixture' -import type { OrcaCloudRunTargetAccess } from '../orca-cloud-run-target-access' -import type { CloudSetupStep } from './cloud-start-model' -import { ComposerPreview } from './cloud-start-preview-fixture' - -const setup = (): void => { - window.api.agentApiKeys = undefined - window.api.cloudSecrets = undefined - // No agent-accounts bridge (as in builds without it): the Agent row reads "unavailable" instead - // of awaiting the fixture harness's catch-all mock, which resolves to undefined. - window.api.orcaCloudAgents = undefined - window.api.cloudWorkspaces = { ...window.api.cloudWorkspaces, available: async () => true } -} -const entitled: OrcaCloudRunTargetAccess = { state: 'entitled', remainingSeconds: 41 * 3600 } -const trial = (hours: number, canManageBilling = true): OrcaCloudRunTargetAccess => ({ - state: 'entitled', - remainingSeconds: hours * 3600, - trial: true, - canManageBilling -}) -const githubDone: CloudSetupStep = { - id: 'github', - state: 'done', - label: 'GitHub access', - status: 'Done', - detail: 'acme/web' -} -const githubNeeded: CloudSetupStep = { - id: 'github', - state: 'needed', - need: 'github', - canFix: true, - label: 'GitHub access', - status: 'Needed', - detail: 'Orca Cloud can’t reach acme/billing yet.', - note: 'It clones your code from GitHub. Give access to this repository once.' -} - -/** E1: Run on as segments, this computer picked; the machine moves to the hint line. */ -export const e1RunOnDefault = defineFixture({ - width: 560, - setup, - render: () => -}) -/** E1 with "⋯" open: today's host picker without the Orca Cloud row. */ -export const e1MorePlaces = defineFixture({ - ...e1RunOnDefault, - interact: (frame) => { - frame.querySelector('[aria-label="More places to run"]')?.click() - } -}) -/** A1: Orca Cloud picked while signed out; trial included, one setup trip. */ -export const a1SignedOut = defineFixture({ - width: 560, - setup, - render: () => ( - - ) -}) -/** B1: signed in, the team can still get its trial. */ -export const b1TrialAvailable = defineFixture({ - width: 560, - setup, - render: () => ( - - ) -}) -/** A6: Finish in your browser; each step ticks in place. */ -export const a6FinishInBrowser = defineFixture({ - width: 560, - setup, - render: () => ( - - ) -}) -/** A7: everything done; "All set", then the composer starts by itself. */ -export const a7AllSet = defineFixture({ - width: 560, - setup, - render: () => ( - - ) -}) -/** T1: trial hours in the composer hint. */ -export const t1TrialHint = defineFixture({ - width: 560, - setup, - render: () => -}) -/** T1 under half an hour: warning, with Choose plan for owners. */ -export const t1TrialLow = defineFixture({ - width: 560, - setup, - render: () => -}) -/** T1 low, member: who can choose a plan. */ -export const t1TrialLowMember = defineFixture({ - width: 560, - setup, - render: () => -}) -/** T2: the trial is used up at New workspace; the prompt is kept. */ -export const t2TrialUsedUp = defineFixture({ - width: 560, - setup, - render: () => ( - - ) -}) -/** C1 with the trial used up: a member can't buy, so ⌘↵ runs on this computer. */ -export const t2TrialUsedUpMember = defineFixture({ - width: 560, - setup, - render: () => ( - - ) -}) -/** D1: GitHub checked up front; "Give access and start". */ -export const d1GitHubNeeded = defineFixture({ - width: 560, - setup, - render: () => ( - - ) -}) -/** D2: waiting for an owner of the GitHub org; ⌘↵ runs on this computer. */ -export const d2GitHubRequested = defineFixture({ - width: 560, - setup, - render: () => ( - - ) -}) -/** D3: the project isn't on GitHub; outranks account and plan rows. */ -export const d3NotOnGitHub = defineFixture({ - width: 560, - setup, - render: () => ( - {} } - }} - /> - ) -}) -const cloudRepos = [ - { fullName: 'acme/billing', url: 'https://github.com/acme/billing', private: true }, - { fullName: 'acme/infra', url: 'https://github.com/acme/infra', private: true }, - { fullName: 'acme/docs', url: 'https://github.com/acme/docs', private: false } -] -/** D4: Orca Cloud picked; the Project picker adds GitHub repositories with no clone here. */ -export const d4GitHubProjects = defineFixture({ - width: 560, - setup, - render: () => ( - - ), - interact: async (frame) => { - frame.querySelector('[aria-label="Browse projects"]')?.click() - await new Promise((resolve) => setTimeout(resolve, 200)) - } -}) -/** D4 picked: the repository stands in for the project; This computer says why it can't run it. */ -export const d4GitHubProjectPicked = defineFixture({ - width: 560, - setup, - render: () => ( - - ) -}) -/** D3 for a folder: Orca Cloud stays selectable; the panel offers a GitHub repository instead. */ -export const d3FolderProject = defineFixture({ - width: 560, - setup, - render: () => ( - - ) -}) -/** D3 for a folder, after "Choose a GitHub repository": the picker opens at the D4 section. */ -export const d3FolderChooseRepository = defineFixture({ - ...d3FolderProject, - interact: async (frame) => { - const link = [...frame.querySelectorAll('button')].find((b) => - b.textContent?.includes('Choose a GitHub repository') - ) - link?.click() - await new Promise((resolve) => setTimeout(resolve, 300)) - } -}) -/** E: returning, entitled; remembered Orca Cloud, no panel, "Start in Orca Cloud". */ -export const eReturning = defineFixture({ - width: 560, - setup, - render: () => ( - - ) -}) -/** X2: Orca Cloud can't be reached; the segment stays, disabled, with the reason. */ -export const x2Unreachable = defineFixture({ - width: 560, - setup, - render: () => ( - - ), - interact: async (frame) => { - frame - .querySelector('[role="radio"][aria-disabled="true"]') - ?.dispatchEvent(new PointerEvent('pointermove', { bubbles: true, pointerType: 'mouse' })) - await new Promise((resolve) => setTimeout(resolve, 500)) - } -}) diff --git a/src/renderer/src/components/new-workspace/run-on/CloudStartAgentRow.fixture.tsx b/src/renderer/src/components/new-workspace/run-on/CloudStartAgentRow.fixture.tsx deleted file mode 100644 index 35823b4b3f3..00000000000 --- a/src/renderer/src/components/new-workspace/run-on/CloudStartAgentRow.fixture.tsx +++ /dev/null @@ -1,33 +0,0 @@ -// Cloud-start G inside the "Set up Orca Cloud" panel: the Agent row from the Orca account's setup. -import { defineFixture } from '../../../component-fixtures/component-fixture' -import { translate } from '@/i18n/i18n' -import type { OrcaCloudAgentSetupRowModel } from '@/lib/orca-cloud/orca-cloud-agent-setup-row' -import { OrcaCloudSetupPanel } from './OrcaCloudSetupPanel' -import { cloudStartAgentStep } from './cloud-start-agent-step' -import type { CloudSetupStep } from './cloud-start-model' - -const BASE: CloudSetupStep[] = [ - { id: 'account', state: 'done', detail: 'neil@acme.dev' }, - { id: 'github', state: 'needed', need: 'github', canFix: true } -] - -function panel(row: OrcaCloudAgentSetupRowModel) { - return defineFixture({ - width: 560, - render: () => { - const agent = cloudStartAgentStep({ id: 'agent', state: 'optional' }, row, translate) - return ( -
- -
- ) - } - }) -} - -export const gFromAccount = panel({ kind: 'covered', agent: 'claude', via: 'account' }) -export const gTeamKey = panel({ kind: 'covered', agent: 'codex', via: 'team' }) -export const gNotSetUp = panel({ kind: 'notSetUp', agent: 'claude' }) -export const gKillSwitch = panel({ kind: 'killSwitch', agent: 'claude' }) -export const gSignedOut = panel({ kind: 'signedOut', agent: 'claude' }) -export const gLoading = panel({ kind: 'loading', agent: 'claude' }) diff --git a/src/renderer/src/components/new-workspace/run-on/CloudStartBilling.fixture.tsx b/src/renderer/src/components/new-workspace/run-on/CloudStartBilling.fixture.tsx deleted file mode 100644 index b56940016c5..00000000000 --- a/src/renderer/src/components/new-workspace/run-on/CloudStartBilling.fixture.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// Orca Cloud picked on the segmented Run on, blocked by billing: the hint under Run on names the fix -// for an owner or admin, and says who can for a member (DS-15). These replace the pre-#273 dropdown -// fixtures NewWorkspaceComposerProjectSection:orcaCloudSelected* (DS-33). -import { defineFixture } from '../../../component-fixtures/component-fixture' -import type { OrcaCloudRunTargetAccess } from '../orca-cloud-run-target-access' -import { ComposerPreview } from './cloud-start-preview-fixture' - -const setup = (): void => { - window.api.agentApiKeys = undefined - window.api.cloudSecrets = undefined - // No agent-accounts bridge: the Agent row reads "unavailable" instead of awaiting the harness's - // catch-all mock, which resolves to undefined (the page error DS-33 found). - window.api.orcaCloudAgents = undefined - window.api.cloudWorkspaces = { ...window.api.cloudWorkspaces, available: async () => true } -} - -function blocked(access: OrcaCloudRunTargetAccess) { - return defineFixture({ - width: 560, - setup, - render: () => - }) -} - -export const noPlanOwner = blocked({ state: 'no-plan', lapsed: false, canManageBilling: true }) -export const noPlanMember = blocked({ state: 'no-plan', lapsed: false, canManageBilling: false }) -export const outOfHoursMember = blocked({ - state: 'out-of-hours', - cause: 'hours', - canManageBilling: false -}) -export const spendCapMember = blocked({ - state: 'out-of-hours', - cause: 'cap', - canManageBilling: false -}) -export const paymentIssueAdmin = blocked({ state: 'payment-issue', canManageBilling: true }) diff --git a/src/renderer/src/components/new-workspace/run-on/CloudStartModalWidth.fixture.tsx b/src/renderer/src/components/new-workspace/run-on/CloudStartModalWidth.fixture.tsx deleted file mode 100644 index c0f0b899ede..00000000000 --- a/src/renderer/src/components/new-workspace/run-on/CloudStartModalWidth.fixture.tsx +++ /dev/null @@ -1,120 +0,0 @@ -// "Start in Orca Cloud" at the real modal's width (sm:max-w-lg, ~448px of content) with its -// "Create more" switch, where np4-e2e saw the primary button overflow the dialog's right edge. -// Also the setup session's plan row (no raw "subscription") and the plan + GitHub subtitle. -import { defineFixture } from '../../../component-fixtures/component-fixture' -import type { OrcaCloudRunTargetAccess } from '../orca-cloud-run-target-access' -import type { CloudSetupStep } from './cloud-start-model' -import { ComposerPreview } from './cloud-start-preview-fixture' - -const setup = (): void => { - window.api.agentApiKeys = undefined - window.api.cloudSecrets = undefined - window.api.orcaCloudAgents = undefined - window.api.cloudWorkspaces = { ...window.api.cloudWorkspaces, available: async () => true } -} -const CARD_WIDTH = 480 -const noPlan: OrcaCloudRunTargetAccess = { - state: 'no-plan', - lapsed: false, - canManageBilling: true -} -const githubNeeded: CloudSetupStep = { - id: 'github', - state: 'needed', - need: 'github', - canFix: true, - label: 'GitHub access', - status: 'Needed', - detail: 'Orca Cloud can’t reach nwparker/orca-sandbox-push-test yet.', - note: 'It clones your code from GitHub. Give access to this repository once.' -} - -/** Signed out at the modal's width: "Create more", "Use this computer instead", "Set up and start". */ -export const modalSignedOut = defineFixture({ - width: CARD_WIDTH + 40, - setup, - render: () => ( - - ) -}) - -/** Only GitHub is missing: the longer "Give access and start" at the modal's width. */ -export const modalGiveAccess = defineFixture({ - width: CARD_WIDTH + 40, - setup, - render: () => ( - - ) -}) - -/** No plan and no GitHub access: the subtitle names both parts of the one browser visit. */ -export const modalPlanAndGitHub = defineFixture({ - width: CARD_WIDTH + 40, - setup, - render: () => ( - - ) -}) - -/** A setup session after Checkout: Team plan done with no raw "subscription" under it. */ -export const sessionPlanDone = defineFixture({ - width: CARD_WIDTH + 40, - setup, - render: () => ( - - ) -}) - -/** A setup session mid-Checkout, with an owner's GitHub approval pending: codes read as words. */ -export const sessionCheckoutAndRequested = defineFixture({ - width: CARD_WIDTH + 40, - setup, - render: () => ( - - ) -}) diff --git a/src/renderer/src/components/new-workspace/run-on/FolderGitHubActions.tsx b/src/renderer/src/components/new-workspace/run-on/FolderGitHubActions.tsx deleted file mode 100644 index d87118dd03c..00000000000 --- a/src/renderer/src/components/new-workspace/run-on/FolderGitHubActions.tsx +++ /dev/null @@ -1,30 +0,0 @@ -// The setup panel's way forward for a plain folder on Orca Cloud (design-squad: D3 for folders): -// choose a GitHub repository from the Project picker (D4), or add a GitHub project. -import React from 'react' -import { Button } from '@/components/ui/button' -import { useTranslate } from '@/i18n/use-translate' - -export function FolderGitHubActions({ - canChoose, - onChooseRepository, - onAddProject -}: { - /** Signed in with GitHub access: the Project picker lists repositories to choose from. */ - canChoose: boolean - onChooseRepository: () => void - onAddProject: () => void -}): React.JSX.Element { - const t = useTranslate() - return ( - - {canChoose ? ( - - ) : null} - - - ) -} diff --git a/src/renderer/src/components/new-workspace/run-on/OrcaCloudSetupPanel.tsx b/src/renderer/src/components/new-workspace/run-on/OrcaCloudSetupPanel.tsx deleted file mode 100644 index c57a8a6e4eb..00000000000 --- a/src/renderer/src/components/new-workspace/run-on/OrcaCloudSetupPanel.tsx +++ /dev/null @@ -1,351 +0,0 @@ -// "Set up Orca Cloud": what still stands between this prompt and a running sandbox (spec A1/B1/C1). -// Shown when Orca Cloud is picked and anything required is missing; hidden once everything is done. -// The rows come from billing today and from the one-trip setup session once it exists. -import React from 'react' -import { Check, CircleDashed, CircleDot, Loader2 } from 'lucide-react' -import { Button } from '@/components/ui/button' -import { Skeleton } from '@/components/ui/skeleton' -import { cn } from '@/lib/utils' -import { useTranslate, type Translate } from '@/i18n/use-translate' -import { - cloudSetupNeedsGitHub, - cloudSetupNeedsPlan, - type CloudSetupStep, - type CloudSetupStepId -} from './cloud-start-model' - -type RowCopy = { title: string; detail: string | null; note?: string; status?: string } - -function rowCopy(step: CloudSetupStep, t: Translate): RowCopy { - switch (step.id) { - case 'account': - return { - title: t('components.newWorkspace.cloudSetup.account', 'Orca account'), - detail: - step.state === 'done' - ? null - : t( - 'components.newWorkspace.cloudSetup.accountNeededTeam', - 'Sign in or create one. We’ll make a team for you.' - ) - } - case 'team': - return { title: t('components.newWorkspace.cloudSetup.team', 'Team'), detail: null } - case 'plan': - return step.need === 'trial' ? trialCopy(step, t) : planCopy(step, t) - case 'github': - return { - title: t('components.newWorkspace.cloudSetup.github', 'GitHub access'), - detail: - step.state === 'done' - ? null - : t( - 'components.newWorkspace.cloudSetup.githubNeeded', - 'Orca Cloud clones your code from GitHub. Give access to this repository once.' - ) - } - case 'agent': - // The composer names the agent in `detail`; it never asks for a per-sandbox sign-in (G). - return { - title: t('components.newWorkspace.cloudSetup.agent', 'Agent'), - detail: null, - status: t('components.newWorkspace.cloudSetup.stateOptional', 'Optional') - } - } -} - -/** A1/B1: the one-time trial, counted from billing's offer, never a literal. */ -function trialCopy(step: CloudSetupStep, t: Translate): RowCopy { - const hours = step.trialSeconds ? Math.round((step.trialSeconds / 3600) * 10) / 10 : null - return { - title: t('components.newWorkspace.cloudSetup.trial', 'Trial'), - detail: - hours === null - ? null - : t( - 'components.newWorkspace.cloudSetup.trialOffer', - '{{hours}} sandbox hours to try Orca Cloud', - { - count: hours, - hours: String(hours), - defaultValue_one: '{{hours}} sandbox hour to try Orca Cloud' - } - ), - note: t( - 'components.newWorkspace.cloudSetup.trialNoCard', - 'No card needed. Nothing is charged until you choose a plan.' - ), - status: t('components.newWorkspace.cloudSetup.stateIncluded', 'Included') - } -} - -function planCopy(step: CloudSetupStep, t: Translate): RowCopy { - if (step.need === 'trial-used-up' && step.state === 'needed') { - // T2 / C1: neutral, nothing failed. Members read who can fix it. - return { - title: t('components.newWorkspace.cloudSetup.plan', 'Team plan'), - detail: t('components.newWorkspace.cloudSetup.trialUsedUp', 'Your trial is used up.'), - note: - step.canFix === false - ? t( - 'components.newWorkspace.cloudSetup.trialUsedUpMember', - 'Only owners and admins can choose a plan.' - ) - : t( - 'components.newWorkspace.cloudSetup.trialUsedUpOwner', - 'Choose a plan to keep using Orca Cloud. Your prompt is still here.' - ) - } - } - return { - title: t('components.newWorkspace.cloudSetup.plan', 'Team plan'), - detail: planDetail(step, t) - } -} - -function planDetail(step: CloudSetupStep, t: Translate): string | null { - if (step.state === 'pending') { - return t('components.newWorkspace.cloudSetup.planAfterSignIn', 'Checked after you sign in') - } - if (step.state !== 'needed') { - return null - } - const memberSuffix = - step.canFix === false - ? ` ${t('components.newWorkspace.cloudSetup.askOwner', 'Ask an owner or admin to fix it.')}` - : '' - switch (step.need) { - case 'renew-plan': - return ( - t('components.newWorkspace.cloudSetup.planEnded', 'Your Team plan ended.') + memberSuffix - ) - // Members read who fixes it and how, per cause (glossary), not a generic "fix it". - case 'hours': - return step.canFix === false - ? t( - 'components.newWorkspace.cloudSetup.outOfHoursMember', - 'Out of sandbox hours. Ask an owner or admin to add hours.' - ) - : t('components.newWorkspace.cloudSetup.outOfHours', 'Out of sandbox hours.') - case 'spend-cap': - return step.canFix === false - ? t( - 'components.newWorkspace.cloudSetup.spendCapMember', - 'Spend cap reached. Ask an owner or admin to raise the spend cap.' - ) - : t('components.newWorkspace.cloudSetup.spendCap', 'Spend cap reached.') - case 'payment': - return step.canFix === false - ? t( - 'components.newWorkspace.cloudSetup.paymentFailedMember', - 'Payment failed. Ask an owner or admin to update the payment method.' - ) - : t('components.newWorkspace.cloudSetup.paymentFailed', 'Payment failed.') - case 'github': - return t( - 'components.newWorkspace.cloudSetup.githubNeeded', - 'Orca Cloud clones your code from GitHub. Give access to this repository once.' - ) - case 'sign-in': - case 'plan': - case 'trial': - case 'trial-used-up': - case undefined: - return step.canFix === false - ? t( - 'components.newWorkspace.cloudSetup.planMember', - 'Orca Cloud needs a Team plan. Only owners and admins can choose one.' - ) - : t('components.newWorkspace.cloudSetup.planNeeded', 'Orca Cloud needs a Team plan.') - } -} - -/** - * A setup session's rows name how a step is covered with a code ('subscription', 'trial', - * 'checkout', 'requested'); say it in words, or nothing. Undefined: not a session code. - */ -export function sessionDetailCopy(step: CloudSetupStep, t: Translate): string | null | undefined { - if (step.id === 'plan' && step.detail === 'subscription') { - // "Team plan · Done" already says it. - return null - } - if (step.id === 'plan' && step.detail === 'trial') { - return t('components.newWorkspace.cloudSetup.planCoveredByTrial', 'Your trial covers it.') - } - if (step.id === 'plan' && step.detail === 'checkout') { - return t( - 'components.newWorkspace.cloudSetup.planCheckoutOpen', - 'Finish checkout in your browser.' - ) - } - if (step.id === 'github' && step.detail === 'requested') { - return t( - 'components.newWorkspace.cloudSetup.githubRequestedSession', - 'Waiting for an owner on GitHub to approve Orca Cloud.' - ) - } - return undefined -} - -function stateLabel(step: CloudSetupStep, t: Translate): string { - switch (step.state) { - case 'done': - return t('components.newWorkspace.cloudSetup.stateDone', 'Done') - case 'optional': - return t('components.newWorkspace.cloudSetup.stateOptional', 'Optional') - case 'pending': - return t('components.newWorkspace.cloudSetup.stateNext', 'Next') - case 'active': - return t('components.newWorkspace.cloudSetup.stateInBrowser', 'In browser') - case 'failed': - return t('components.newWorkspace.cloudSetup.stateFailed', "Didn't finish") - case 'loading': - return t('components.newWorkspace.cloudSetup.stateChecking', 'Checking') - case 'needed': - return t('components.newWorkspace.cloudSetup.stateNeeded', 'Needed') - } -} - -function StateIcon({ step }: { step: CloudSetupStep }): React.JSX.Element { - // Neutral checks: done and an included trial are facts, not alerts. - if (step.state === 'done' || step.need === 'trial') { - return - } - if (step.state === 'active') { - // The browser is working on this step; static under reduced motion, the label carries the state. - return ( - - ) - } - if (step.state === 'needed' || step.state === 'failed') { - return - } - return -} - -export function OrcaCloudSetupPanel({ - steps, - allSet = false, - title, - subtitle, - children, - rowActions, - className -}: { - steps: readonly CloudSetupStep[] - /** Setup just finished: "All set", then the composer starts the workspace by itself. */ - allSet?: boolean - /** Overrides for variants such as the "Finish in your browser" tracker. */ - title?: string - subtitle?: string - /** Rendered under the rows (tracker errors and actions). */ - children?: React.ReactNode - /** Per-row slot under a row's detail, e.g. the member "Ask for a Team plan" action on 'plan'. */ - rowActions?: Partial> - className?: string -}): React.JSX.Element { - const t = useTranslate() - const titleId = React.useId() - return ( -
-

- {allSet - ? t('components.newWorkspace.cloudSetup.allSet', 'All set') - : (title ?? t('components.newWorkspace.cloudSetup.title', 'Set up Orca Cloud'))} -

-

- {allSet - ? t('components.newWorkspace.cloudSetup.starting', 'Starting your cloud workspace…') - : (subtitle ?? - // No browser trip fixes a project without a GitHub repository (D3): say what holds. - (steps.some((step) => step.blocksStart && step.state === 'failed') - ? t( - 'components.newWorkspace.cloudSetup.subtitleNeedsRepository', - 'Orca Cloud needs a GitHub repository. Your prompt stays here.' - ) - : // A member can't fix billing, and no browser trip will. - steps.some((step) => step.state === 'needed' && step.canFix === false) - ? t( - 'components.newWorkspace.cloudSetup.subtitleOwnerFixes', - 'An owner or admin needs to fix this. Your prompt stays here.' - ) - : cloudSetupNeedsPlan(steps) && cloudSetupNeedsGitHub(steps) - ? t( - 'components.newWorkspace.cloudSetup.subtitleChoosePlanAndGitHub', - 'One visit to your browser to choose a plan and give Orca Cloud access on GitHub. Your prompt stays here and starts when you’re done.' - ) - : cloudSetupNeedsPlan(steps) - ? t( - 'components.newWorkspace.cloudSetup.subtitleChoosePlan', - 'One visit to your browser to choose a plan. Your prompt stays here and starts when you’re done.' - ) - : t( - 'components.newWorkspace.cloudSetup.subtitleNoCard', - 'One visit to your browser, no card. Your prompt stays here and starts when you’re done.' - )))} -

- {/* One polite announcement per row change ("Team plan, done"). */} -
    - {steps.map((step) => { - const copy = rowCopy(step, t) - const title = step.label ?? copy.title - const state = step.status ?? copy.status ?? stateLabel(step, t) - const note = step.note ?? copy.note - const sessionDetail = sessionDetailCopy(step, t) - const detail = sessionDetail === undefined ? (step.detail ?? copy.detail) : sessionDetail - return ( -
  • - - - - - {title} - {step.state === 'loading' ? ( - - ) : detail ? ( - {detail} - ) : null} - {note ? ( - {note} - ) : null} - {step.action ? ( - // One shared in-row action ("Set up once", "How to push"): it must read as a button. - - ) : null} - {rowActions?.[step.id] ?? null} - - - {`${title}, `} - {state} - -
  • - ) - })} -
- {children} -
- ) -} diff --git a/src/renderer/src/components/new-workspace/run-on/RunOnHintLine.tsx b/src/renderer/src/components/new-workspace/run-on/RunOnHintLine.tsx deleted file mode 100644 index 9c3b64cc2ab..00000000000 --- a/src/renderer/src/components/new-workspace/run-on/RunOnHintLine.tsx +++ /dev/null @@ -1,39 +0,0 @@ -// The hint under Run on for this computer or a "⋯" target: where it runs (spec E1). When Orca -// Cloud can't be reached, the line says so (X2) so the disabled segment never looks like a bug. -import React from 'react' -import { useTranslate } from '@/i18n/use-translate' -import type { ProjectHostSetupOption } from '@/lib/project-host-setup-options' -import type { OrcaCloudAvailability } from '../../../../../shared/orca-yaml-hook-types' -import { getRecipeDetail, type EphemeralVmRecipeOption } from '../run-target-options' - -export function RunOnHintLine({ - hostOptions, - selectedHostId, - recipes, - selectedRecipeId, - orcaCloudAvailability -}: { - hostOptions: readonly ProjectHostSetupOption[] - selectedHostId: string | null - recipes: readonly EphemeralVmRecipeOption[] - selectedRecipeId: string | null - orcaCloudAvailability: OrcaCloudAvailability -}): React.JSX.Element | null { - const t = useTranslate() - const recipe = recipes.find((candidate) => candidate.id === selectedRecipeId) ?? null - const host = hostOptions.find((option) => option.id === selectedHostId) ?? null - const where = recipe ? getRecipeDetail(recipe, t) : host ? `${host.label} · ${host.detail}` : null - return ( -
- {where ?

{where}

: null} - {orcaCloudAvailability === 'unreachable' ? ( -

- {t( - 'components.newWorkspace.runOn.cloudUnreachableReason', - "Orca Cloud: can't reach it right now. Check your connection." - )} -

- ) : null} -
- ) -} diff --git a/src/renderer/src/components/new-workspace/run-on/RunOnSegmentedControl.tsx b/src/renderer/src/components/new-workspace/run-on/RunOnSegmentedControl.tsx deleted file mode 100644 index d4bf68717da..00000000000 --- a/src/renderer/src/components/new-workspace/run-on/RunOnSegmentedControl.tsx +++ /dev/null @@ -1,212 +0,0 @@ -// Run on as one click: "This computer · Orca Cloud · ⋯" (spec D1). ⋯ opens today's host picker -// without its Orca Cloud row, and a target picked there replaces ⋯ so the choice stays visible. -import React, { useMemo, useState } from 'react' -import { Cloud, Ellipsis, Monitor } from 'lucide-react' -import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover' -import { SettingsSegmentedControl } from '@/components/settings/form-controls/SettingsSegmentedControl' -import { useTranslate } from '@/i18n/use-translate' -import type { ReadyProjectHostSetupOption } from '@/lib/project-host-setup-options' -import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host' -import { ORCA_CLOUD_RECIPE_ID } from '../../../../../shared/hosted-sandbox/orca-cloud-recipe-id' -import type { OrcaCloudAvailability } from '../../../../../shared/orca-yaml-hook-types' -import RunTargetCombobox from '../RunTargetCombobox' -import { isOrcaCloudRecipe } from '../run-target-options' -import { getOrcaCloudSegmentState, getRunOnSegment, type RunOnSegment } from './cloud-start-model' - -type RunTargetComboboxProps = React.ComponentProps - -export type RunOnSegmentedControlProps = RunTargetComboboxProps & { - orcaCloudAvailability: OrcaCloudAvailability - /** Selects Orca Cloud even when the account still needs setup; the panel below says what's missing. */ - onSelectOrcaCloud: () => void - /** Marks the control as touched so a remembered default never overrides a user pick. */ - onUserPick?: () => void - /** D4: the picked project is on GitHub only, so this computer has nothing to run. */ - cloudOnlyRepo?: boolean -} - -export default function RunOnSegmentedControl( - props: RunOnSegmentedControlProps -): React.JSX.Element { - const { - hostOptions, - hostValue, - hostExecutionHostId, - onHostChange, - recipes, - recipeValue, - onRecipeChange, - orcaCloudAvailability, - onSelectOrcaCloud, - onUserPick, - cloudOnlyRepo = false - } = props - const t = useTranslate() - const [moreOpen, setMoreOpen] = useState(false) - - const localOption = useMemo( - () => - hostOptions.find( - (option): option is ReadyProjectHostSetupOption => - option.kind === 'ready' && option.hostId === LOCAL_EXECUTION_HOST_ID - ) ?? null, - [hostOptions] - ) - const selectedRecipe = recipes.find((recipe) => recipe.id === recipeValue) ?? null - const orcaCloudSelected = recipeValue === ORCA_CLOUD_RECIPE_ID - const selectedHost = - hostOptions.find( - (option) => - option.kind === 'ready' && - option.id === hostValue && - (!hostExecutionHostId || option.hostId === hostExecutionHostId) - ) ?? null - const segment = getRunOnSegment({ - orcaCloudSelected, - otherRecipeSelected: selectedRecipe !== null && !orcaCloudSelected, - selectedHostIsLocal: selectedHost ? selectedHost.hostId === LOCAL_EXECUTION_HOST_ID : null - }) - const cloudState = getOrcaCloudSegmentState(orcaCloudAvailability) - const localReason = cloudOnlyRepo - ? t( - 'components.newWorkspace.cloudOnly.notOnThisComputer', - 'Not on this computer · Orca Cloud only' - ) - : t('components.newWorkspace.runOn.locationNotSet', 'Project location not set') - - const pickLocal = (): void => { - if (!localOption || cloudOnlyRepo) { - return - } - onUserPick?.() - onRecipeChange?.(null) - onHostChange?.(localOption.id) - } - const pickCloud = (): void => { - if (cloudState !== 'enabled') { - return - } - onUserPick?.() - onSelectOrcaCloud() - } - - const otherLabel = - segment === 'other' - ? ((selectedRecipe && !isOrcaCloudRecipe(selectedRecipe) - ? selectedRecipe.name - : selectedHost?.label) ?? null) - : null - - const options = [ - { - value: 'local' as const, - label: ( - - - {t('components.newWorkspace.runOn.thisComputer', 'This computer')} - - ), - disabled: !localOption || cloudOnlyRepo, - // A disabled option says why in its accessible name too (spec E1). - ariaLabel: - localOption && !cloudOnlyRepo - ? undefined - : t('components.newWorkspace.runOn.thisComputerUnusable', 'This computer, {{reason}}', { - reason: localReason - }), - tooltip: localOption && !cloudOnlyRepo ? localOption.label : localReason - }, - ...(cloudState === 'hidden' - ? [] - : [ - { - value: 'orca-cloud' as const, - label: ( - - - {t('components.newWorkspace.runOn.orcaCloud', 'Orca Cloud')} - - ), - disabled: cloudState === 'unreachable', - ariaLabel: - cloudState === 'unreachable' - ? t( - 'components.newWorkspace.runOn.cloudUnreachableName', - "Orca Cloud, can't reach it right now" - ) - : undefined, - tooltip: - cloudState === 'unreachable' - ? t( - 'components.newWorkspace.runOn.cloudUnreachableReason', - "Orca Cloud: can't reach it right now. Check your connection." - ) - : t('components.newWorkspace.runOn.cloudHosted', 'Hosted sandbox') - } - ]), - { - value: 'other' as const, - ariaLabel: otherLabel - ? t('components.newWorkspace.runOn.moreWithTarget', 'More places to run: {{name}}', { - name: otherLabel - }) - : t('components.newWorkspace.runOn.more', 'More places to run'), - label: otherLabel ? ( - {otherLabel} - ) : ( - - ), - tooltip: t('components.newWorkspace.runOn.more', 'More places to run') - } - ] - - // The host picker keeps everything except Orca Cloud, which now has its own segment. - const otherRecipes = useMemo( - () => recipes.filter((recipe) => !isOrcaCloudRecipe(recipe)), - [recipes] - ) - - return ( - - -
- - value={segment ?? 'local'} - activation="manual" - size="sm" - ariaLabel={t('auto.components.NewWorkspaceComposerCard.runOn', 'Run on')} - options={options} - onChange={(value) => { - if (value === 'local') { - pickLocal() - } else if (value === 'orca-cloud') { - pickCloud() - } else { - setMoreOpen(true) - } - }} - /> -
-
- - { - onUserPick?.() - onRecipeChange?.(null) - onHostChange?.(setupId) - setMoreOpen(false) - }} - onRecipeChange={(recipeId) => { - onUserPick?.() - onRecipeChange?.(recipeId) - setMoreOpen(false) - }} - /> - -
- ) -} diff --git a/src/renderer/src/components/new-workspace/run-on/OrcaCloudSetupPanel.test.tsx b/src/renderer/src/components/new-workspace/run-on/cloud-setup-session-copy.test.ts similarity index 94% rename from src/renderer/src/components/new-workspace/run-on/OrcaCloudSetupPanel.test.tsx rename to src/renderer/src/components/new-workspace/run-on/cloud-setup-session-copy.test.ts index c36929e963a..7b424cd31b5 100644 --- a/src/renderer/src/components/new-workspace/run-on/OrcaCloudSetupPanel.test.tsx +++ b/src/renderer/src/components/new-workspace/run-on/cloud-setup-session-copy.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import { translate } from '@/i18n/i18n' -import { sessionDetailCopy } from './OrcaCloudSetupPanel' +import { sessionDetailCopy } from './cloud-setup-session-copy' describe('sessionDetailCopy', () => { // np4-e2e: the plan row read the session's raw "subscription". diff --git a/src/renderer/src/components/new-workspace/run-on/cloud-setup-session-copy.ts b/src/renderer/src/components/new-workspace/run-on/cloud-setup-session-copy.ts new file mode 100644 index 00000000000..2ad45b29562 --- /dev/null +++ b/src/renderer/src/components/new-workspace/run-on/cloud-setup-session-copy.ts @@ -0,0 +1,30 @@ +// Setup-session codes in words, for the Orca Cloud setup page. +import type { Translate } from '@/i18n/use-translate' +import type { CloudSetupStep } from './cloud-start-model' + +/** + * A setup session's rows name how a step is covered with a code ('subscription', 'trial', + * 'checkout', 'requested'); say it in words, or nothing. Undefined: not a session code. + */ +export function sessionDetailCopy(step: CloudSetupStep, t: Translate): string | null | undefined { + if (step.id === 'plan' && step.detail === 'subscription') { + // "Team plan · Done" already says it. + return null + } + if (step.id === 'plan' && step.detail === 'trial') { + return t('components.newWorkspace.cloudSetup.planCoveredByTrial', 'Your trial covers it.') + } + if (step.id === 'plan' && step.detail === 'checkout') { + return t( + 'components.newWorkspace.cloudSetup.planCheckoutOpen', + 'Finish checkout in your browser.' + ) + } + if (step.id === 'github' && step.detail === 'requested') { + return t( + 'components.newWorkspace.cloudSetup.githubRequestedSession', + 'Waiting for an owner on GitHub to approve Orca Cloud.' + ) + } + return undefined +} diff --git a/src/renderer/src/components/new-workspace/run-on/cloud-start-actions.ts b/src/renderer/src/components/new-workspace/run-on/cloud-start-actions.ts index c2781995838..054aaaa6ced 100644 --- a/src/renderer/src/components/new-workspace/run-on/cloud-start-actions.ts +++ b/src/renderer/src/components/new-workspace/run-on/cloud-start-actions.ts @@ -1,39 +1,8 @@ -// What the "Start in Orca Cloud" primary button says, and the fix one click runs before a session -// exists (sign in first, else the plan/billing action). -import { toast } from 'sonner' -import { translate } from '@/i18n/i18n' +// The fix one click runs before a setup session exists (sign in first, else the plan/billing +// action); the setup page's fallback when the session can't open. import type { OrcaCloudAvailability } from '../../../../../shared/orca-yaml-hook-types' import { getOrcaCloudPick, type OrcaCloudRunTargetAccess } from '../orca-cloud-run-target-access' -import type { CloudPrimaryAction, CloudSetupStep } from './cloud-start-model' - -export function getCloudPrimaryLabel(action: CloudPrimaryAction): string { - switch (action) { - case 'start': - case 'startTrial': - return translate('components.newWorkspace.cloudStart.start', 'Start in Orca Cloud') - case 'setUpAndStart': - return translate('components.newWorkspace.cloudStart.setUpAndStart', 'Set up and start') - case 'choosePlanAndStart': - return translate( - 'components.newWorkspace.cloudStart.choosePlanAndStart', - 'Choose plan and start' - ) - case 'renewAndStart': - return translate('components.newWorkspace.cloudStart.renewAndStart', 'Renew and start') - case 'giveAccessAndStart': - return translate( - 'components.newWorkspace.cloudStart.giveAccessAndStart', - 'Give access and start' - ) - case 'useThisComputer': - return translate( - 'components.newWorkspace.cloudStart.useThisComputer', - 'Use this computer instead' - ) - case 'checking': - return translate('components.newWorkspace.cloudStart.checking', 'Checking Orca Cloud…') - } -} +import type { CloudSetupStep } from './cloud-start-model' /** The fix one click on the primary button runs: sign in first, else the plan/billing action. */ export function setupActionFor( @@ -52,17 +21,3 @@ export function setupActionFor( const pick = getOrcaCloudPick(effective) return pick.kind === 'act' ? pick.run : null } - -/** D2: an owner approved on GitHub while this composer waits; offer the start (never auto). */ -export function showGitHubGrantedToast(repoName: string, onStart: () => void): void { - toast.message( - translate( - 'components.newWorkspace.cloudStart.githubGranted', - 'GitHub access granted for {{repo}}', - { - repo: repoName - } - ), - { action: { label: getCloudPrimaryLabel('start'), onClick: onStart } } - ) -} diff --git a/src/renderer/src/components/new-workspace/run-on/cloud-start-model.test.ts b/src/renderer/src/components/new-workspace/run-on/cloud-start-model.test.ts index d5d4fe9bada..a5b5af7fc16 100644 --- a/src/renderer/src/components/new-workspace/run-on/cloud-start-model.test.ts +++ b/src/renderer/src/components/new-workspace/run-on/cloud-start-model.test.ts @@ -1,54 +1,18 @@ import { describe, expect, it } from 'vitest' import { - cloudSetupNeedsGitHub, deriveCloudSetupSteps, - getCloudPrimaryAction, getOrcaCloudSegmentState, - getRunOnSegment, - isCloudSetupPanelVisible, resolveDefaultRunOn, + type CloudSetupStep, withReachableGitHub } from './cloud-start-model' +import { + cloudSetupPageModel, + cloudSetupRequired, + sessionNeedsFrom +} from '../../orca-cloud-setup/cloud-setup-page-model' -describe('Run on segment', () => { - it('maps the committed target to a segment', () => { - expect( - getRunOnSegment({ - orcaCloudSelected: true, - otherRecipeSelected: false, - selectedHostIsLocal: true - }) - ).toBe('orca-cloud') - expect( - getRunOnSegment({ - orcaCloudSelected: false, - otherRecipeSelected: true, - selectedHostIsLocal: true - }) - ).toBe('other') - expect( - getRunOnSegment({ - orcaCloudSelected: false, - otherRecipeSelected: false, - selectedHostIsLocal: false - }) - ).toBe('other') - expect( - getRunOnSegment({ - orcaCloudSelected: false, - otherRecipeSelected: false, - selectedHostIsLocal: true - }) - ).toBe('local') - expect( - getRunOnSegment({ - orcaCloudSelected: false, - otherRecipeSelected: false, - selectedHostIsLocal: null - }) - ).toBeNull() - }) - +describe('Orca Cloud availability', () => { it('keeps Orca Cloud visible but disabled when it cannot be reached (X2)', () => { expect(getOrcaCloudSegmentState('unreachable')).toBe('unreachable') expect(getOrcaCloudSegmentState('unavailable')).toBe('hidden') @@ -58,17 +22,29 @@ describe('Run on segment', () => { }) }) -describe('setup rows and the primary label', () => { +describe('setup rows and the setup page', () => { + const page = (steps: Parameters[0]) => + cloudSetupPageModel(steps, { agentSkipped: true }).action + it('starts directly when the account is entitled', () => { const steps = deriveCloudSetupSteps({ availability: 'offered', access: { state: 'entitled', remainingSeconds: 3600 } }) - expect(isCloudSetupPanelVisible(steps)).toBe(false) - expect(getCloudPrimaryAction(steps)).toBe('start') + expect(cloudSetupRequired(steps, { agentSkipped: true })).toBe(false) + expect(page(steps)).toBe('done') }) - it('signed out: one setup trip ("Set up and start"), plan checked after sign-in', () => { + it('an agent with no account opens the page until it is skipped once', () => { + const steps = deriveCloudSetupSteps({ + availability: 'offered', + access: { state: 'entitled', remainingSeconds: 3600 } + }) + expect(cloudSetupRequired(steps)).toBe(true) + expect(cloudSetupPageModel(steps).action).toBe('agent') + }) + + it('signed out: sign-in first, plan checked after sign-in', () => { const steps = deriveCloudSetupSteps({ availability: 'needs-sign-in', access: { state: 'loading' } @@ -78,49 +54,57 @@ describe('setup rows and the primary label', () => { ['plan', 'pending'], ['agent', 'optional'] ]) - expect(isCloudSetupPanelVisible(steps)).toBe(true) - expect(getCloudPrimaryAction(steps)).toBe('setUpAndStart') + expect(page(steps)).toBe('sign-in') }) - it('owner without a plan: "Choose plan and start"; lapsed: "Renew and start"', () => { + it('owner without a plan chooses one in the browser; lapsed renews there', () => { const noPlan = deriveCloudSetupSteps({ availability: 'needs-capability', access: { state: 'no-plan', lapsed: false, canManageBilling: true } }) - expect(getCloudPrimaryAction(noPlan)).toBe('choosePlanAndStart') + expect(page(noPlan)).toBe('choose-plan') const lapsed = deriveCloudSetupSteps({ - availability: 'needs-capability', + availability: 'offered', access: { state: 'no-plan', lapsed: true, canManageBilling: true } }) - expect(getCloudPrimaryAction(lapsed)).toBe('renewAndStart') + expect(page(lapsed)).toBe('choose-plan') + expect(lapsed.find((s) => s.id === 'plan')?.need).toBe('renew-plan') }) - it('a member who cannot fix it gets "Use this computer instead" and no agent row', () => { + it('a member who cannot fix billing is told to ask an owner, with no agent row', () => { const steps = deriveCloudSetupSteps({ availability: 'needs-capability', access: { state: 'no-plan', lapsed: false, canManageBilling: false } }) expect(steps.some((s) => s.id === 'agent')).toBe(false) - expect(getCloudPrimaryAction(steps)).toBe('useThisComputer') + expect(page(steps)).toBe('ask-owner') const outOfHours = deriveCloudSetupSteps({ availability: 'offered', access: { state: 'out-of-hours', cause: 'hours', canManageBilling: false } }) - expect(getCloudPrimaryAction(outOfHours)).toBe('useThisComputer') + expect(page(outOfHours)).toBe('ask-owner') }) - it('a missing GitHub grant alone reads "Give access and start"', () => { + it('an owner out of hours fixes it in billing', () => { + const steps = deriveCloudSetupSteps({ + availability: 'offered', + access: { state: 'out-of-hours', cause: 'hours', canManageBilling: true } + }) + expect(page(steps)).toBe('fix-billing') + }) + + it('a missing GitHub grant alone is the GitHub step', () => { expect( - getCloudPrimaryAction([ + page([ { id: 'account', state: 'done' }, { id: 'plan', state: 'done' }, { id: 'github', state: 'needed', need: 'github', canFix: true }, { id: 'agent', state: 'optional' } ]) - ).toBe('giveAccessAndStart') + ).toBe('github-install') }) - it('a team that can still get its trial just starts (B1); setup grants it with no card', () => { + it('a team that can still get its trial claims it in the app (B1)', () => { const steps = deriveCloudSetupSteps({ availability: 'offered', access: { state: 'no-plan', lapsed: false, canManageBilling: false, trialOfferSeconds: 7200 } @@ -129,23 +113,21 @@ describe('setup rows and the primary label', () => { expect(plan).toMatchObject({ need: 'trial', trialSeconds: 7200, canFix: true }) // Members aren't blocked from the trial: the agent row stays. expect(steps.some((s) => s.id === 'agent')).toBe(true) - expect(getCloudPrimaryAction(steps)).toBe('startTrial') - // An included trial isn't a task: no panel, the hint line carries it. - expect(isCloudSetupPanelVisible(steps)).toBe(false) + expect(page(steps)).toBe('start-trial') }) - it('trial used up: owner "Choose plan and start"; member runs on this computer (T2, C1)', () => { + it('trial used up: owner chooses a plan; member asks an owner (T2, C1)', () => { const owner = deriveCloudSetupSteps({ availability: 'offered', access: { state: 'no-plan', lapsed: false, canManageBilling: true, trialUsedUp: true } }) expect(owner.find((s) => s.id === 'plan')?.need).toBe('trial-used-up') - expect(getCloudPrimaryAction(owner)).toBe('choosePlanAndStart') + expect(page(owner)).toBe('choose-plan') const member = deriveCloudSetupSteps({ availability: 'offered', access: { state: 'no-plan', lapsed: false, canManageBilling: false, trialUsedUp: true } }) - expect(getCloudPrimaryAction(member)).toBe('useThisComputer') + expect(page(member)).toBe('ask-owner') }) it('signed out: the trial row is included and GitHub is checked up front (A1)', () => { @@ -156,17 +138,18 @@ describe('setup rows and the primary label', () => { }) expect(steps.map((s) => s.id)).toEqual(['account', 'plan', 'github', 'agent']) expect(steps.find((s) => s.id === 'plan')?.need).toBe('trial') - expect(getCloudPrimaryAction(steps)).toBe('setUpAndStart') + expect(sessionNeedsFrom(steps)).toEqual(['account', 'plan', 'github']) + expect(page(steps)).toBe('sign-in') }) - it('GitHub waiting on an owner blocks the start, so ⌘↵ runs locally (D2)', () => { + it('GitHub waiting on an owner: the page waits and starts on its own (D2)', () => { const steps = deriveCloudSetupSteps({ availability: 'offered', access: { state: 'entitled', remainingSeconds: 3600 }, github: { id: 'github', state: 'pending', need: 'github', blocksStart: true } }) - expect(isCloudSetupPanelVisible(steps)).toBe(true) - expect(getCloudPrimaryAction(steps)).toBe('useThisComputer') + expect(cloudSetupRequired(steps, { agentSkipped: true })).toBe(true) + expect(page(steps)).toBe('github-waiting') }) it('no GitHub remote outranks account and plan rows (D3)', () => { @@ -176,21 +159,37 @@ describe('setup rows and the primary label', () => { github: { id: 'github', state: 'failed', need: 'github', blocksStart: true } }) expect(steps.map((s) => s.id)).toEqual(['github']) - expect(getCloudPrimaryAction(steps)).toBe('useThisComputer') + expect(page(steps)).toBe('needs-repository') }) - it('a GitHub check still running holds the start (D1 cache miss)', () => { - const steps = deriveCloudSetupSteps({ + it('checks while GitHub or billing are still being read', () => { + const github = deriveCloudSetupSteps({ availability: 'offered', access: { state: 'entitled', remainingSeconds: 3600 }, github: { id: 'github', state: 'loading' } }) - expect(getCloudPrimaryAction(steps)).toBe('checking') + expect(page(github)).toBe('checking') + const billing = deriveCloudSetupSteps({ availability: 'offered', access: { state: 'loading' } }) + expect(page(billing)).toBe('checking') }) - it('waits while billing is still being read', () => { - const steps = deriveCloudSetupSteps({ availability: 'offered', access: { state: 'loading' } }) - expect(getCloudPrimaryAction(steps)).toBe('checking') + it('B2: a team switch is its own step and always opens the page', () => { + const steps: CloudSetupStep[] = [ + { id: 'account', state: 'done' }, + { id: 'team', state: 'needed' } + ] + expect(cloudSetupRequired(steps, { teamSwitch: true })).toBe(true) + expect(cloudSetupPageModel(steps, { teamSwitch: true }).action).toBe('switch-team') + }) + + it('a still-loading agent row never holds a ready start', () => { + const steps: CloudSetupStep[] = [ + { id: 'account', state: 'done' }, + { id: 'plan', state: 'done' }, + { id: 'agent', state: 'loading' } + ] + expect(cloudSetupRequired(steps)).toBe(false) + expect(cloudSetupPageModel(steps).action).toBe('done') }) }) @@ -266,7 +265,7 @@ describe('withReachableGitHub', () => { { id: 'plan', state: 'done', detail: 'subscription' }, { id: 'github', state: 'done' } ]) - expect(getCloudPrimaryAction([...withReachableGitHub([...session], true)])).toBe('start') + expect(cloudSetupPageModel([...withReachableGitHub([...session], true)]).action).toBe('done') }) it('leaves the rows alone while the repository is still unreachable', () => { @@ -274,15 +273,3 @@ describe('withReachableGitHub', () => { expect(withReachableGitHub(steps, false)).toBe(steps) }) }) - -describe('cloudSetupNeedsGitHub', () => { - it('counts GitHub access the browser visit gives, not an approval, a missing remote or a check', () => { - expect(cloudSetupNeedsGitHub([{ id: 'github', state: 'needed', need: 'github' }])).toBe(true) - expect(cloudSetupNeedsGitHub([{ id: 'github', state: 'active' }])).toBe(true) - expect(cloudSetupNeedsGitHub([{ id: 'github', state: 'done' }])).toBe(false) - expect(cloudSetupNeedsGitHub([{ id: 'github', state: 'loading' }])).toBe(false) - expect( - cloudSetupNeedsGitHub([{ id: 'github', state: 'pending', need: 'github', blocksStart: true }]) - ).toBe(false) - }) -}) diff --git a/src/renderer/src/components/new-workspace/run-on/cloud-start-model.ts b/src/renderer/src/components/new-workspace/run-on/cloud-start-model.ts index 4ea27621248..22137588ce5 100644 --- a/src/renderer/src/components/new-workspace/run-on/cloud-start-model.ts +++ b/src/renderer/src/components/new-workspace/run-on/cloud-start-model.ts @@ -1,30 +1,8 @@ -// "Start in Orca Cloud": what the Run on control shows, which setup rows are missing, and what the -// composer's primary button says and does. Pure, so every state the spec draws is unit-tested here. +// Orca Cloud from the composer: whether its Run on option is offered, which setup rows are missing, +// and the remembered default. Pure, so every state the spec draws is unit-tested here. import type { OrcaCloudAvailability } from '../../../../../shared/orca-yaml-hook-types' import type { OrcaCloudRunTargetAccess } from '../orca-cloud-run-target-access' -/** The three segments of Run on: this computer, Orca Cloud, and everything else behind "⋯". */ -export type RunOnSegment = 'local' | 'orca-cloud' | 'other' - -export function getRunOnSegment({ - orcaCloudSelected, - otherRecipeSelected, - selectedHostIsLocal -}: { - orcaCloudSelected: boolean - otherRecipeSelected: boolean - /** Null when no host is committed (the picker's "Choose where to run" state). */ - selectedHostIsLocal: boolean | null -}): RunOnSegment | null { - if (orcaCloudSelected) { - return 'orca-cloud' - } - if (otherRecipeSelected || selectedHostIsLocal === false) { - return 'other' - } - return selectedHostIsLocal === null ? null : 'local' -} - /** * How the Orca Cloud segment behaves. `hidden`: this build doesn't ship Orca Cloud. * `unreachable`: it does, but the account check failed (offline); the segment stays visible and @@ -47,7 +25,7 @@ export function getOrcaCloudSegmentState( } } -/** One row of the "Set up Orca Cloud" panel. Shape shared with the setup session (team-billing-ux). */ +/** One step of the Orca Cloud setup page. Shape shared with the setup session (team-billing-ux). */ export type CloudSetupStepId = 'account' | 'team' | 'plan' | 'github' | 'agent' export type CloudSetupStepState = | 'done' @@ -173,79 +151,6 @@ function derivePlanStep( } } -/** Required rows still open; `optional` (agent) never counts. */ -export function getOpenSetupSteps(steps: readonly CloudSetupStep[]): CloudSetupStep[] { - return steps.filter((step) => step.state !== 'done' && step.state !== 'optional') -} - -/** The panel shows while anything required is open (or still loading). */ -export function isCloudSetupPanelVisible(steps: readonly CloudSetupStep[]): boolean { - // An included trial isn't a task: with nothing else open, the hint line carries it (B1). - return getOpenSetupSteps(steps).some((step) => step.need !== 'trial') -} - -/** The browser trip is for choosing a plan (T2, lapsed, no plan), not a free trial. */ -export function cloudSetupNeedsPlan(steps: readonly CloudSetupStep[]): boolean { - return getOpenSetupSteps(steps).some( - (step) => step.need === 'plan' || step.need === 'renew-plan' || step.need === 'trial-used-up' - ) -} - -/** - * The same browser trip also gives Orca Cloud access to the repository on GitHub. An owner's - * approval (D2) or a project not on GitHub (D3) isn't part of the trip; still checking isn't either. - */ -export function cloudSetupNeedsGitHub(steps: readonly CloudSetupStep[]): boolean { - return getOpenSetupSteps(steps).some( - (step) => step.id === 'github' && !step.blocksStart && step.state !== 'loading' - ) -} - -export type CloudPrimaryAction = - | 'start' - | 'setUpAndStart' - | 'choosePlanAndStart' - | 'renewAndStart' - | 'giveAccessAndStart' - /** Only the trial is missing: setup grants it, so the button just says Start (B1). */ - | 'startTrial' - | 'useThisComputer' - | 'checking' - -/** - * The composer's primary action while Orca Cloud is selected. The label names where the work runs - * (spec D10); a member who can't fix a block gets "Use this computer instead" so ⌘↵ always works. - */ -export function getCloudPrimaryAction(steps: readonly CloudSetupStep[]): CloudPrimaryAction { - const open = getOpenSetupSteps(steps) - if (open.length === 0) { - return 'start' - } - if (open.some((step) => (step.state === 'needed' && step.canFix === false) || step.blocksStart)) { - return 'useThisComputer' - } - if (open.every((step) => step.state === 'loading')) { - return 'checking' - } - const needed = open.filter((step) => step.state !== 'pending' && step.state !== 'loading') - if (needed.length === 1) { - const need = needed[0]?.need - if (need === 'plan' || need === 'trial-used-up') { - return 'choosePlanAndStart' - } - if (need === 'trial') { - return 'startTrial' - } - if (need === 'renew-plan') { - return 'renewAndStart' - } - if (need === 'github') { - return 'giveAccessAndStart' - } - } - return 'setUpAndStart' -} - export type RunOnPreference = 'last' | 'local' | 'orca-cloud' /** diff --git a/src/renderer/src/components/new-workspace/run-on/cloud-start-preview-fixture.tsx b/src/renderer/src/components/new-workspace/run-on/cloud-start-preview-fixture.tsx deleted file mode 100644 index 15445595c82..00000000000 --- a/src/renderer/src/components/new-workspace/run-on/cloud-start-preview-fixture.tsx +++ /dev/null @@ -1,194 +0,0 @@ -// Shared preview for the cloud-start fixtures: the composer's project section and footer wired to -// the pure setup model, so every spec frame renders without a store or network. -import React, { useState } from 'react' -import type { ProjectHostSetupOption } from '@/lib/project-host-setup-options' -import type { NewWorkspaceProjectOption } from '@/lib/new-workspace-project-options' -import type { OrcaCloudAvailability } from '../../../../../shared/orca-yaml-hook-types' -import { NewWorkspaceComposerProjectSection } from '../NewWorkspaceComposerProjectSection' -import { NewWorkspaceComposerFooter } from '../NewWorkspaceComposerFooter' -import type { EphemeralVmRecipeOption } from '../run-target-options' -import type { OrcaCloudRunTargetAccess } from '../orca-cloud-run-target-access' -import { - deriveCloudSetupSteps, - getCloudPrimaryAction, - isCloudSetupPanelVisible, - type CloudSetupStep -} from './cloud-start-model' -import type { CloudStartView } from './use-cloud-start-composer' -import { getCloudPrimaryLabel } from './cloud-start-actions' -import { decorateCloudSetupSteps } from './use-cloud-start-steps' -import type { OrcaCloudGitHubRepository } from '@/lib/orca-cloud/use-orca-cloud-github-repositories' - -const projects: NewWorkspaceProjectOption[] = [ - { - kind: 'project', - id: 'web', - projectId: 'web', - displayName: 'acme/web', - badgeColor: 'var(--muted-foreground)', - detail: 'acme/web' - } -] -/** A plain folder (no git): the D3-for-folders frames. */ -const folderProjects: NewWorkspaceProjectOption[] = [ - { - kind: 'project', - id: 'web', - projectId: 'web', - displayName: 'meeting-notes', - badgeColor: 'var(--muted-foreground)', - detail: '~/Documents/meeting-notes' - } -] -const hosts: ProjectHostSetupOption[] = [ - { - kind: 'ready', - id: 'local', - projectId: 'web', - repoId: 'web', - hostId: 'local', - label: 'MacBook Pro', - detail: '~/code/acme-web', - path: '/Users/neil/code/acme-web' - }, - { - kind: 'ready', - id: 'devbox', - projectId: 'web', - repoId: 'web-devbox', - hostId: 'ssh:devbox', - label: 'devbox', - detail: 'SSH', - path: '/home/neil/acme-web' - } -] -const orcaCloudRecipe: EphemeralVmRecipeOption = { - id: 'cloud', - name: 'Orca Cloud', - description: 'Hosted by Orca. Sleeps when idle and keeps your files.', - provider: 'orca-cloud', - create: 'orca-cloud create' -} - -export function ComposerPreview({ - availability, - access, - cloudSelected, - steps: pinnedSteps, - github = null, - allSet = false, - prompt = 'Fix the flaky login test in e2e/auth.spec.ts and open a PR.', - cloudRepos, - pickedCloudRepo = null, - folderProject = false, - showCreateMultiple = false, - width -}: { - availability: OrcaCloudAvailability - access: OrcaCloudRunTargetAccess - cloudSelected: boolean - steps?: CloudSetupStep[] - /** The GitHub row (D1–D3), as the repository check would report it. */ - github?: CloudSetupStep | null - allSet?: boolean - prompt?: string - /** D4: GitHub repositories with no clone here. */ - cloudRepos?: OrcaCloudGitHubRepository[] - pickedCloudRepo?: string | null - /** The project is a plain folder (D3 for folders). */ - folderProject?: boolean - /** The modal's "Create more" switch, which shares the footer row with the actions. */ - showCreateMultiple?: boolean - /** Pins the card's width, e.g. the modal's content width. */ - width?: number -}): React.JSX.Element { - const [picked, setPicked] = useState(pickedCloudRepo) - const [host, setHost] = useState('local') - const [recipe, setRecipe] = useState(cloudSelected ? 'cloud' : null) - const signedOut = availability === 'needs-sign-in' || access.state === 'signed-out' - // G: Claude not set up yet, so the Agent row offers the one-time setup (or waits for sign-in). - const steps = decorateCloudSetupSteps( - pinnedSteps ?? deriveCloudSetupSteps({ availability, access, github }), - signedOut ? { kind: 'signedOut', agent: 'claude' } : { kind: 'notSetUp', agent: 'claude' } - ) - const selected = recipe === 'cloud' - const panelVisible = selected && (isCloudSetupPanelVisible(steps) || allSet) - const action = getCloudPrimaryAction(steps) - const cloudStart: CloudStartView = { - steps, - panelVisible, - allSet, - onSelectOrcaCloud: () => setRecipe('cloud'), - onUserPick: () => {}, - folderProject, - ...(cloudRepos - ? { - cloudOnly: { - repos: cloudRepos, - showMore: () => {}, - picked: cloudRepos.find((repo) => repo.fullName === picked) ?? null, - githubStep: null, - folderProject, - pick: setPicked, - clear: () => setPicked(null), - moreAccess: () => {}, - start: async () => true - } - } - : {}), - ...(panelVisible && !allSet && action !== 'useThisComputer' - ? { onUseThisComputer: () => setRecipe(null) } - : {}) - } - return ( -
-

Create workspace

-

{prompt}

- {}} - projectDescriptionId="fixture-project-description" - onAddProject={() => {}} - focusNameInput={() => {}} - shouldShowRunTargetPicker - projectHostSetupOptions={hosts} - selectedProjectHostSetupId={host} - handleProjectHostSetupChange={(id) => setHost(id)} - ephemeralVmRecipes={availability === 'offered' ? [orcaCloudRecipe] : []} - selectedEphemeralVmRecipeId={recipe} - onEphemeralVmRecipeChange={setRecipe} - orcaCloudAvailability={availability} - orcaCloudAccess={access} - cloudStart={cloudStart} - handleAddSshHost={() => {}} - handleAddRemoteServer={() => {}} - handleConnectRunTargetHost={async () => {}} - handleSetLocation={() => {}} - onConnectSelectedRepo={async () => {}} - sshStatusLabel="Connected" - connectButtonLabel="Connect" - selectedProjectName={folderProject ? 'meeting-notes' : 'acme/web'} - /> - {}} - createDisabled={allSet || action === 'checking'} - creating={allSet} - primaryActionLabel={ - selected ? getCloudPrimaryLabel(allSet ? 'start' : action) : 'Create worktree' - } - submitShortcutModifierLabel="⌘" - cloudStart={cloudStart} - showCreateMultiple={showCreateMultiple} - /> -
- ) -} diff --git a/src/renderer/src/components/new-workspace/run-on/cloud-start-view.ts b/src/renderer/src/components/new-workspace/run-on/cloud-start-view.ts index d2f656c4f3a..36193ccbb95 100644 --- a/src/renderer/src/components/new-workspace/run-on/cloud-start-view.ts +++ b/src/renderer/src/components/new-workspace/run-on/cloud-start-view.ts @@ -1,17 +1,11 @@ -// What the composer card renders for "Start in Orca Cloud", shared by the hook and the card. -import type { CloudSetupStep } from './cloud-start-model' +// What the composer card needs for Orca Cloud, shared by the hook and the card. Picking Orca Cloud +// changes nothing else in the dialog (composer-redo): setup lives on its own page after Start. import type { CloudOnlyRepo } from './use-cloud-only-repo' -import type { CloudSetupViewExtras } from '../cloud-setup/use-cloud-setup-tracker' -/** What the card renders: Run on's Orca Cloud segment, the setup panel and the fallback button. */ -export type CloudStartView = CloudSetupViewExtras & { - steps: CloudSetupStep[] - panelVisible: boolean - allSet: boolean +export type CloudStartView = { + /** Picks Orca Cloud even while the account still needs setup; Start walks it on a page. */ onSelectOrcaCloud: () => void onUserPick: () => void - /** Present while setup blocks a start: creates the same prompt on this computer. */ - onUseThisComputer?: () => void /** D4: GitHub repositories with no clone here, and the one picked. */ cloudOnly?: CloudOnlyRepo /** The project is a plain folder: Orca Cloud needs a GitHub repository instead (D3/D4). */ diff --git a/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts b/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts index 8f5ae3564e7..d21e4d424ea 100644 --- a/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts +++ b/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts @@ -1,42 +1,27 @@ -// Composer glue for "Start in Orca Cloud": the setup rows, the primary button's label and action, -// setup instead of a build that billing or GitHub would refuse, the start on its own once setup -// finishes (O4), the draft on disk (N7), and where each project last started (O5). -import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +// Composer glue for Orca Cloud (composer-redo). Picking Orca Cloud changes nothing else in the +// dialog: Start either creates the workspace (everything is set up) or saves the draft, closes the +// dialog and opens the full-page setup, which starts the prompt by itself when done. Also: where +// each project last started (O5), the remembered default (D7) and GitHub-only repositories (D4). +import { useCallback, useEffect, useMemo, useRef } from 'react' import { toast } from 'sonner' import { useAppStore } from '@/store/index' -import { claimOrcaCloudTrial } from '@/components/billing/claim-trial' import { translate } from '@/i18n/i18n' -import type { - ProjectHostSetupOption, - ReadyProjectHostSetupOption -} from '@/lib/project-host-setup-options' +import { clearCloudStartDraft, saveCloudStartDraft } from '@/lib/orca-cloud/cloud-start-draft' import { - clearCloudStartDraft, - readCloudStartDraft, - saveCloudStartDraft -} from '@/lib/orca-cloud/cloud-start-draft' -import { getCloudSetupStarter } from '@/lib/orca-cloud/cloud-setup-session-seam' + isCloudSetupAgentSkipped, + openCloudSetupPage +} from '@/lib/orca-cloud/cloud-setup-page-store' import { recordSuccessfulRunOn } from '@/lib/orca-cloud/run-on-memory' -import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host' import { ORCA_CLOUD_RECIPE_ID } from '../../../../../shared/hosted-sandbox/orca-cloud-recipe-id' import type { OrcaCloudAvailability } from '../../../../../shared/orca-yaml-hook-types' import { useOrcaCloudRunTargetAccess } from '../orca-cloud-billing-cache' import type { OrcaCloudRunTargetAccess } from '../orca-cloud-run-target-access' -import { getCloudPrimaryLabel, setupActionFor, showGitHubGrantedToast } from './cloud-start-actions' -import { - getCloudPrimaryAction, - getOpenSetupSteps, - getOrcaCloudSegmentState, - isCloudSetupPanelVisible -} from './cloud-start-model' +import type { ComposerModalData } from '../composer-modal-data' +import { getOrcaCloudSegmentState } from './cloud-start-model' import { getOrcaCloudStartToast } from './orca-cloud-hours-copy' import { useCloudStartSteps } from './use-cloud-start-steps' -import { useSetupAutoStart } from './use-setup-auto-start' -import { - setupViewExtras, - useComposerSetupTracker, - useSwitchTeamSteps -} from '../cloud-setup/use-cloud-setup-tracker' +import { useSwitchTeamSteps } from '../cloud-setup/use-cloud-setup-tracker' +import { cloudSetupRequired } from '../../orca-cloud-setup/cloud-setup-page-model' import { useRunOnDefault } from './use-run-on-default' import { useCloudOnlyCreate, useCloudOnlyRepo } from './use-cloud-only-repo' import type { CloudStartView } from './cloud-start-view' @@ -48,12 +33,13 @@ export function useCloudStartComposer({ availability, selectedRecipeId, setRecipeId, - hostOptions, - onHostChange, repoId, prompt, agent, initialTargetFixed, + autoStart = false, + createReady = true, + composerSnapshot, onCreate: createWorkspace, onClose, accessOverride @@ -62,26 +48,26 @@ export function useCloudStartComposer({ availability: OrcaCloudAvailability selectedRecipeId: string | null setRecipeId: ((recipeId: string | null) => void) | undefined - hostOptions: readonly ProjectHostSetupOption[] - onHostChange: ((setupId: string) => void) | undefined repoId: string prompt: string agent: string | null /** The composer was opened on an explicit target (Landing card, a recovery). */ initialTargetFixed: boolean + /** Reopened by the setup page once everything is done: submit as soon as the form is ready. */ + autoStart?: boolean + /** The composer's own create would run now (project picked, agent resolved). */ + createReady?: boolean + /** The composer as it is now, for the setup page's Back and its auto-start. */ + composerSnapshot: () => ComposerModalData onCreate: () => void - /** Closes the composer once a cloud-only repository has started (D4). */ + /** Closes the composer (setup moves to its page; a cloud-only repository started, D4). */ onClose?: () => void /** Fixtures pin the account's access. */ accessOverride?: OrcaCloudRunTargetAccess }): { view: CloudStartView | null - primaryActionLabel: string | null /** Replaces the plain create while Orca Cloud is selected. */ onPrimary: (() => void) | null - primaryDisabled: boolean - /** False while the primary runs setup or the local fallback instead of a plain create. */ - primaryIsCreate: boolean /** Call from the composer's onCreated: only a successful start is remembered. */ recordCreated: () => void } { @@ -105,57 +91,20 @@ export function useCloudStartComposer({ hoursToast: getOrcaCloudStartToast(access, translate, navigator.language), onClose }) - const [startedSessionId, setSetupSessionId] = useState(null) - // A composer reopened after setup (e.g. the Checkout return) resumes its saved draft: derived, - // not copied into state, so it is right on the first render. - const restoredDraft = useMemo( - () => (active && cloudSelected ? readCloudStartDraft(profileId) : null), - [active, cloudSelected, profileId] - ) - const [restoreDone, setRestoreDone] = useState(false) - const restored = restoredDraft !== null && restoredDraft.repoId === repoId && !restoreDone - const setupSessionId = startedSessionId ?? (restored ? restoredDraft.setupSessionId : null) - const [startedHere, setSetupStarted] = useState(false) - const setupStarted = startedHere || restored - const setupStartedRef = useRef(setupStarted) - const onCreateRef = useRef(onCreate) - useEffect(() => { - setupStartedRef.current = setupStarted - onCreateRef.current = onCreate - }, [onCreate, setupStarted]) - const { - steps: rowSteps, - session, - openInstall - } = useCloudStartSteps({ + const { steps: rowSteps } = useCloudStartSteps({ availability, access, repoId, agent, cloudSelected, - setupSessionId, - githubOverride: cloudOnly.githubStep, - onGranted: (repoName) => { - // D2: an owner approved on GitHub. Setup already running starts by itself; otherwise ask. - if (setupStartedRef.current) { - return - } - showGitHubGrantedToast(repoName, () => onCreateRef.current()) - } + setupSessionId: null, + githubOverride: cloudOnly.githubStep + }) + const { steps, held: switchTeam } = useSwitchTeamSteps(rowSteps, cloudSelected) + const setupNeeded = cloudSetupRequired(steps, { + teamSwitch: switchTeam !== null, + agentSkipped: isCloudSetupAgentSkipped(agent) }) - // B2: on the personal account while a team the user is on has a plan, switch instead of buying. - const { steps, held: switchTeam } = useSwitchTeamSteps(rowSteps, cloudSelected && !session) - const action = getCloudPrimaryAction(steps) - const panelVisible = cloudSelected && isCloudSetupPanelVisible(steps) - - const localOption = useMemo( - () => - hostOptions.find( - (option): option is ReadyProjectHostSetupOption => - option.kind === 'ready' && option.hostId === LOCAL_EXECUTION_HOST_ID - ) ?? null, - [hostOptions] - ) const { markTouched } = useRunOnDefault({ active, @@ -172,95 +121,41 @@ export function useCloudStartComposer({ setRecipeId?.(ORCA_CLOUD_RECIPE_ID) }, [markTouched, setRecipeId]) - // "Use this computer instead": switch, then submit once the switch has rendered. - const localSubmitPendingRef = useRef(false) - const useThisComputer = useCallback(() => { - if (!localOption) { - return - } - markTouched() - localSubmitPendingRef.current = true - setRecipeId?.(null) - onHostChange?.(localOption.id) - }, [localOption, markTouched, onHostChange, setRecipeId]) - useEffect(() => { - if (localSubmitPendingRef.current && !cloudSelected) { - localSubmitPendingRef.current = false - createWorkspace() - } - }, [cloudSelected, createWorkspace]) - - // O4: setup started here (or its restored draft) starts by itself once every row is done. - const startAfterSetup = useCallback(() => { - setSetupStarted(false) - setRestoreDone(true) - onCreate() - }, [onCreate]) - const allSet = useSetupAutoStart({ - armed: setupStarted && cloudSelected, - done: action === 'start' || session?.finished === true, - setupSessionId, - onStart: startAfterSetup - }) - - // The draft survives the browser trip and a quit; it is cleared once a workspace starts. - const runSetup = useCallback(() => { - const draft = { + // Start with setup still open: the dialog closes and the page takes over, prompt kept (N6). + const openSetup = useCallback(() => { + saveCloudStartDraft(profileId, { prompt, repoId, agent, - target: 'orca-cloud' as const, - setupSessionId, + target: 'orca-cloud', + setupSessionId: null, createdAt: Date.now() - } - saveCloudStartDraft(profileId, draft) - setSetupStarted(true) - const open = getOpenSetupSteps(steps) - // D1: GitHub is the only thing missing, so its install page is the whole trip. - if (open.length > 0 && open.every((step) => step.id === 'github' || step.id === 'agent')) { - void openInstall() - return - } - const startSession = getCloudSetupStarter() - const fallback = setupActionFor(steps, access, availability) - if (!startSession) { - fallback?.() - return - } - // One browser trip for every missing step; the session id rides on the draft across a quit. - void startSession({ repoId, needs: open.map((step) => step.id) }) - .then((opened) => { - if (!opened) { - fallback?.() - return - } - setSetupSessionId(opened.sessionId) - saveCloudStartDraft(profileId, { ...draft, setupSessionId: opened.sessionId }) - }) - .catch(() => fallback?.()) - }, [access, agent, availability, openInstall, profileId, prompt, repoId, setupSessionId, steps]) - - // B1: only the trial is missing. Claiming it is the whole setup; the billing cache then reads - // entitled and the auto-start above submits. A personal account needs a team first: setup trip. - const startTrial = useCallback(() => { - setSetupStarted(true) - void claimOrcaCloudTrial().then((result) => { - if (result.status !== 'ok') { - runSetup() - } }) - }, [runSetup]) + openCloudSetupPage({ + prompt, + repoId, + agent, + availability, + cloudOnlyRepo: cloudOnly.picked?.fullName ?? null, + composer: composerSnapshot() + }) + onClose?.() + }, [agent, availability, cloudOnly.picked, composerSnapshot, onClose, profileId, prompt, repoId]) - const trip = { cloudSelected, setupStarted, allSet, session, steps, access, availability } - const tracker = useComposerSetupTracker({ - ...trip, - profileId, - readyToStart: action === 'start', - sessionId: setupSessionId, - runSetup, - // Ends the trip here; the tracker hook also clears the draft's session id. - onCancel: () => [setSetupStarted(false), setRestoreDone(true), setSetupSessionId(null)] - }) + // Reopened by the setup page: submit once the account and form are ready. Anything still open + // (a race, a revoked grant) leaves the composer for the user, never a second trip on its own. + const autoStartedRef = useRef(false) + const stepsSettled = !steps.some((step) => step.state === 'loading' && step.id !== 'agent') + useEffect(() => { + if (!autoStart || autoStartedRef.current || !cloudSelected || !createReady || !stepsSettled) { + return + } + if (setupNeeded) { + return + } + autoStartedRef.current = true + onCreate() + }, [autoStart, cloudSelected, createReady, onCreate, setupNeeded, stepsSettled]) const recordCreated = useCallback(() => { if (!repoId) { @@ -278,51 +173,20 @@ export function useCloudStartComposer({ } }, [access, cloudSelected, profileId, repoId]) - // Orca Cloud isn't the target (or this build has none): the composer's own create runs. - const plainCreate = { - primaryActionLabel: null, - onPrimary: null, - primaryDisabled: false, - primaryIsCreate: true, - recordCreated - } - if (segment === 'hidden') { - return { view: null, ...plainCreate } - } - const view: CloudStartView = { - steps, - panelVisible: panelVisible || allSet, - allSet, - onSelectOrcaCloud, - onUserPick: markTouched, - cloudOnly, - folderProject: cloudOnly.folderProject, - ...setupViewExtras(switchTeam, tracker), - ...(panelVisible && localOption && action !== 'useThisComputer' && !cloudOnly.picked - ? { onUseThisComputer: useThisComputer } - : {}) - } - if (!cloudSelected) { - return { view, ...plainCreate } - } - const onPrimary = switchTeam - ? () => undefined - : action === 'start' - ? onCreate - : action === 'useThisComputer' - ? useThisComputer - : action === 'checking' - ? () => undefined - : action === 'startTrial' - ? startTrial - : runSetup - return { - view, - primaryActionLabel: getCloudPrimaryLabel(allSet || switchTeam ? 'start' : action), - onPrimary, - primaryDisabled: - action === 'checking' || allSet || (action === 'useThisComputer' && !localOption), - primaryIsCreate: action === 'start', - recordCreated + const view = useMemo( + () => + segment === 'hidden' + ? null + : { + onSelectOrcaCloud, + onUserPick: markTouched, + cloudOnly, + folderProject: cloudOnly.folderProject + }, + [cloudOnly, markTouched, onSelectOrcaCloud, segment] + ) + if (!view || !cloudSelected) { + return { view, onPrimary: null, recordCreated } } + return { view, onPrimary: setupNeeded ? openSetup : onCreate, recordCreated } } diff --git a/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts b/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts index b4d3b564034..7398b7f8375 100644 --- a/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts +++ b/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts @@ -1,5 +1,5 @@ -// The composer modal's side of "Start in Orca Cloud": feeds the composer state into -// useCloudStartComposer and returns what the primary button and ⌘↵ do. +// The composer modal's side of Orca Cloud: feeds the composer state into useCloudStartComposer and +// returns what the primary button and ⌘↵ do. import { useCallback, useEffect, type MutableRefObject } from 'react' import type { ComposerModalData } from '../composer-modal-data' import type { NewWorkspaceComposerCardProps } from '../new-workspace-composer-card-props' @@ -10,8 +10,6 @@ type ComposerCardState = Pick< | 'orcaCloudAvailability' | 'selectedEphemeralVmRecipeId' | 'onEphemeralVmRecipeChange' - | 'projectHostSetupOptions' - | 'onProjectHostSetupChange' | 'repoId' | 'name' > @@ -23,6 +21,7 @@ export function useComposerCloudStart({ quickAgent, handleCreate, createDisabled, + composerSnapshot, recordCreatedRef, onClose }: { @@ -32,6 +31,7 @@ export function useComposerCloudStart({ quickAgent: string | null handleCreate: () => Promise createDisabled: boolean + composerSnapshot: () => ComposerModalData /** The composer's onCreated calls this: only a start that happened is remembered. */ recordCreatedRef: MutableRefObject<(() => void) | null> onClose?: () => void @@ -44,26 +44,25 @@ export function useComposerCloudStart({ availability: cardProps.orcaCloudAvailability ?? 'unavailable', selectedRecipeId: cardProps.selectedEphemeralVmRecipeId ?? null, setRecipeId: cardProps.onEphemeralVmRecipeChange, - hostOptions: cardProps.projectHostSetupOptions ?? [], - onHostChange: cardProps.onProjectHostSetupChange, repoId: cardProps.repoId, prompt: cardProps.name, agent: quickAgent, initialTargetFixed: Boolean( modalData.initialEphemeralVmRecipeId || modalData.initialWorkspaceTarget || modalData.recovery ), + autoStart: modalData.cloudAutoStart === true, + createReady: !createDisabled, + composerSnapshot, onCreate: runCreate, onClose }) useEffect(() => { recordCreatedRef.current = cloudStart.recordCreated }, [cloudStart.recordCreated, recordCreatedRef]) - const primaryCreateDisabled = cloudStart.primaryIsCreate - ? createDisabled || cloudStart.primaryDisabled - : cloudStart.primaryDisabled return { cloudStart, - primaryCreateDisabled, + // Local and Orca Cloud share one button: same label, same rules for when it's enabled. + primaryCreateDisabled: createDisabled, onPrimary: cloudStart.onPrimary ?? runCreate } } diff --git a/src/renderer/src/components/new-workspace/run-on/use-setup-auto-start.ts b/src/renderer/src/components/new-workspace/run-on/use-setup-auto-start.ts deleted file mode 100644 index bd3793ddef4..00000000000 --- a/src/renderer/src/components/new-workspace/run-on/use-setup-auto-start.ts +++ /dev/null @@ -1,42 +0,0 @@ -// O4: setup started from this composer (or its restored draft) starts the workspace by itself. -// When every required row is done, hold "All set", then submit as if ⌘↵ had been pressed. -import { useEffect, useState } from 'react' -import { CLOUD_SETUP_ALL_SET_HOLD_MS } from '@/lib/orca-cloud/cloud-setup-session-seam' -import { recordCloudSetupFirstSandbox } from '@/lib/orca-cloud/cloud-setup-telemetry' -import { prefersReducedMotion } from './cloud-start-view' - -/** Returns whether "All set" is showing. `onStart` ends the trip state, then creates. */ -export function useSetupAutoStart({ - armed, - done, - setupSessionId, - onStart -}: { - /** Setup was started here and Orca Cloud is still the target. */ - armed: boolean - /** Every required row is done, or the session says it finished. */ - done: boolean - setupSessionId: string | null - onStart: () => void -}): boolean { - const [allSet, setAllSet] = useState(false) - useEffect(() => { - if (!armed || !done) { - return - } - setAllSet(true) - const timer = window.setTimeout( - () => { - setAllSet(false) - // N10: time to first sandbox, from when the tracker first saw this trip. - if (setupSessionId) { - recordCloudSetupFirstSandbox({ sessionId: setupSessionId, hoursSource: 'unknown' }) - } - onStart() - }, - prefersReducedMotion() ? 0 : CLOUD_SETUP_ALL_SET_HOLD_MS - ) - return () => window.clearTimeout(timer) - }, [armed, done, onStart, setupSessionId]) - return allSet -} diff --git a/src/renderer/src/components/new-workspace/use-run-target-orca-cloud.ts b/src/renderer/src/components/new-workspace/use-run-target-orca-cloud.ts index 0de3f1d8ec9..291b1352c47 100644 --- a/src/renderer/src/components/new-workspace/use-run-target-orca-cloud.ts +++ b/src/renderer/src/components/new-workspace/use-run-target-orca-cloud.ts @@ -51,7 +51,8 @@ export function useRunTargetOrcaCloud({ override, open, close, - selectRecipe + selectRecipe, + onSelectOrcaCloud }: { recipes: readonly EphemeralVmRecipeOption[] offer: OrcaCloudRunTargetAccess | null @@ -60,6 +61,8 @@ export function useRunTargetOrcaCloud({ open: boolean close: () => void selectRecipe: (recipeId: string) => void + /** Picks Orca Cloud whatever setup it still needs (the composer walks it after Start). */ + onSelectOrcaCloud?: () => void }): { access: OrcaCloudRunTargetAccess /** A pick is waiting on billing; the row shows busy. */ @@ -97,6 +100,11 @@ export function useRunTargetOrcaCloud({ const pickFor = useCallback( (resolved: OrcaCloudRunTargetAccess, recipe: EphemeralVmRecipeOption | null): void => { const pick = getOrcaCloudPick(resolved) + if (onSelectOrcaCloud && pick.kind !== 'blocked') { + close() + onSelectOrcaCloud() + return + } if (pick.kind === 'act') { close() // The fix finishes elsewhere (plans, portal, settings): reread billing on return. @@ -106,7 +114,7 @@ export function useRunTargetOrcaCloud({ selectRecipe(recipe.id) } }, - [close, selectRecipe] + [close, onSelectOrcaCloud, selectRecipe] ) const runBlockedAction = useCallback((): void => pickFor(access, null), [access, pickFor]) const select = useCallback( diff --git a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx new file mode 100644 index 00000000000..2c92bc3ba0b --- /dev/null +++ b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx @@ -0,0 +1,421 @@ +// "Set up Orca Cloud" as a page (composer-redo). Start in the composer closes the dialog and opens +// this when the account isn't ready. One step at a time: the current step is the page; finished +// steps are ticks in the stepper. Browser hops only for sign-in, Stripe and GitHub. When every +// step is done, the saved prompt starts by itself. +import React from 'react' +import { ArrowLeft, Check, Cloud, Copy, ExternalLink, LoaderCircle } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Skeleton } from '@/components/ui/skeleton' +import { cn } from '@/lib/utils' +import { useTranslate, type Translate } from '@/i18n/use-translate' +import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model' +import { CloudSetupErrorNotice } from '@/components/new-workspace/cloud-setup/CloudSetupErrorNotice' +import { sessionDetailCopy } from '@/components/new-workspace/run-on/cloud-setup-session-copy' +import type { CloudSetupFlow } from './use-cloud-setup-flow' + +export type CloudSetupPageProps = { + flow: CloudSetupFlow + projectName: string | null + prompt: string + agentLabel: string | null + /** Back to the composer with the prompt, project and agent as they were. */ + onBack: () => void + /** "All set": shown for a moment before the workspace starts. */ + starting: boolean +} + +function stepLabel(step: CloudSetupStep, t: Translate): string { + switch (step.id) { + case 'account': + return t('cloudSetupPage.step.account', 'Account') + case 'team': + return t('cloudSetupPage.step.team', 'Team') + case 'plan': + return step.need === 'trial' + ? t('cloudSetupPage.step.trial', 'Trial') + : t('cloudSetupPage.step.plan', 'Plan') + case 'github': + return t('cloudSetupPage.step.github', 'GitHub') + case 'agent': + return t('cloudSetupPage.step.agent', 'Agent') + } +} + +type StepState = 'done' | 'current' | 'todo' + +function SetupStepper({ + steps, + current, + allDone +}: { + steps: readonly CloudSetupStep[] + current: CloudSetupStep | null + allDone: boolean +}): React.JSX.Element { + const t = useTranslate() + const currentIndex = current ? steps.findIndex((step) => step.id === current.id) : steps.length + return ( +
    + {steps.map((step, index) => { + const state: StepState = + allDone || index < currentIndex ? 'done' : index === currentIndex ? 'current' : 'todo' + const label = stepLabel(step, t) + return ( +
  1. + {index > 0 ? : null} + + {state === 'done' ? : null} + {state === 'current' ? : null} + + + {label} + + {state === 'done' + ? `, ${t('cloudSetupPage.stepDone', 'done')}` + : state === 'current' + ? `, ${t('cloudSetupPage.stepCurrent', 'current step')}` + : ''} + + +
  2. + ) + })} +
+ ) +} + +type StepCopy = { title: string; lead: string | null; note?: string | null } + +function trialHours(step: CloudSetupStep): string | null { + return step.trialSeconds ? String(Math.round((step.trialSeconds / 3600) * 10) / 10) : null +} + +function currentStepCopy(flow: CloudSetupFlow, t: Translate, agentLabel: string | null): StepCopy { + const step = flow.current + const detail = step + ? (sessionDetailCopy(step, t) === undefined ? step.detail : sessionDetailCopy(step, t)) ?? null + : null + switch (flow.action) { + case 'sign-in': + return { + title: t('cloudSetupPage.signIn.title', 'Sign in to Orca'), + lead: t( + 'cloudSetupPage.signIn.lead', + 'Orca Cloud runs your agents in a cloud workspace, so they keep going with your laptop closed. Sign in or create an account in your browser. We’ll make a team for you.' + ), + note: t( + 'cloudSetupPage.signIn.note', + 'New teams get a trial with no card needed. This page picks up each step on its own.' + ) + } + case 'start-trial': { + const hours = step ? trialHours(step) : null + return { + title: t('cloudSetupPage.trial.title', 'Start your free trial'), + lead: + hours === null + ? t('cloudSetupPage.trial.leadNoHours', 'Try Orca Cloud on your team. No card needed.') + : t('cloudSetupPage.trial.lead', '{{hours}} sandbox hours to try Orca Cloud. No card needed.', { + hours + }), + note: t('cloudSetupPage.trial.note', 'Nothing is charged until you choose a plan.') + } + } + case 'choose-plan': + return step?.need === 'trial-used-up' + ? { + title: t('cloudSetupPage.plan.trialUsedUpTitle', 'Your trial is used up'), + lead: t( + 'cloudSetupPage.plan.trialUsedUpLead', + 'Choose a Team plan to keep using Orca Cloud. Checkout opens in your browser.' + ) + } + : step?.need === 'renew-plan' + ? { + title: t('cloudSetupPage.plan.renewTitle', 'Renew your Team plan'), + lead: t( + 'cloudSetupPage.plan.renewLead', + 'Your Team plan ended. Renew it in your browser to start this workspace.' + ) + } + : { + title: t('cloudSetupPage.plan.title', 'Choose a Team plan'), + lead: t( + 'cloudSetupPage.plan.lead', + 'Orca Cloud needs a Team plan. Checkout opens in your browser.' + ) + } + case 'fix-billing': + return { + title: + step?.need === 'payment' + ? t('cloudSetupPage.billing.paymentTitle', 'Update your payment method') + : step?.need === 'spend-cap' + ? t('cloudSetupPage.billing.capTitle', 'Spend cap reached') + : t('cloudSetupPage.billing.hoursTitle', 'Out of sandbox hours'), + lead: + step?.need === 'payment' + ? t('cloudSetupPage.billing.paymentLead', 'The last payment failed. Update the card to keep going.') + : step?.need === 'spend-cap' + ? t('cloudSetupPage.billing.capLead', 'Raise the spend cap to start this workspace.') + : t('cloudSetupPage.billing.hoursLead', 'Turn on overage to start this workspace.') + } + case 'switch-team': + return { title: t('cloudSetupPage.team.title', 'Switch to your team'), lead: detail } + case 'github-install': + return { + title: t('cloudSetupPage.github.title', 'Give Orca Cloud access on GitHub'), + lead: t( + 'cloudSetupPage.github.lead', + 'Orca Cloud clones your code from GitHub. Install the Orca Cloud app on this repository once.' + ), + note: step?.note ?? null + } + case 'github-waiting': + return { + title: t('cloudSetupPage.github.waitingTitle', 'Waiting for approval on GitHub'), + lead: detail, + note: step?.note ?? null + } + case 'needs-repository': + return { + title: t('cloudSetupPage.repository.title', 'Orca Cloud needs a GitHub repository'), + lead: detail, + note: step?.note ?? null + } + case 'ask-owner': + return { + title: t('cloudSetupPage.owner.title', 'An owner or admin needs to fix this'), + lead: detail ?? t('cloudSetupPage.owner.lead', 'Orca Cloud needs a Team plan. Only owners and admins can choose one.') + } + case 'agent': + return { + title: agentLabel + ? t('cloudSetupPage.agent.title', 'Sign in to {{agent}} once', { agent: agentLabel }) + : t('cloudSetupPage.agent.titleGeneric', 'Sign in to your agent once'), + lead: t( + 'cloudSetupPage.agent.lead', + 'Save your agent sign-in to your Orca account and every cloud workspace uses it. You can also skip this and sign in inside the workspace.' + ) + } + case 'checking': + return { title: t('cloudSetupPage.checking.title', 'Checking your Orca Cloud account…'), lead: null } + case 'done': + return { + title: t('cloudSetupPage.done.title', 'All set'), + lead: t('cloudSetupPage.done.lead', 'Starting your cloud workspace…') + } + } +} + +function BrowserWaiting({ flow }: { flow: CloudSetupFlow }): React.JSX.Element { + const t = useTranslate() + return ( +
+ + + {t('cloudSetupPage.waitingBrowser', 'Waiting for your browser…')} + + + {flow.copyLink ? ( + + ) : null} + + +
+ ) +} + +function StepActions({ flow }: { flow: CloudSetupFlow }): React.JSX.Element | null { + const t = useTranslate() + const browser = (label: string, onClick: () => void): React.JSX.Element => ( + + ) + const inBrowserAction = + flow.action === 'sign-in' || + flow.action === 'choose-plan' || + flow.action === 'fix-billing' || + flow.action === 'github-install' + if (flow.inBrowser && inBrowserAction && !flow.error) { + return + } + const continueLabel = t('cloudSetupPage.continueInBrowser', 'Continue in browser') + switch (flow.action) { + case 'sign-in': + case 'choose-plan': + return browser(continueLabel, flow.continueInBrowser) + case 'fix-billing': + return browser(continueLabel, flow.fixBilling) + case 'github-install': + return browser(continueLabel, flow.installGitHub) + case 'start-trial': + return ( + + ) + case 'switch-team': + return
{flow.teamAction}
+ case 'agent': + return ( +
+ {flow.current?.action ? ( + + ) : null} + +
+ ) + case 'needs-repository': + return flow.current?.action ? ( + + ) : null + case 'ask-owner': + return ( + + ) + case 'github-waiting': + return ( + + + {t('cloudSetupPage.github.waiting', 'This page starts the workspace once they approve.')} + + ) + case 'checking': + return + case 'done': + return ( + + + {t('cloudSetupPage.starting', 'Starting…')} + + ) + } +} + +export function CloudSetupPage({ + flow, + projectName, + prompt, + agentLabel, + onBack, + starting +}: CloudSetupPageProps): React.JSX.Element { + const t = useTranslate() + const titleId = React.useId() + const headingRef = React.useRef(null) + const copy = currentStepCopy(starting ? { ...flow, action: 'done' } : flow, t, agentLabel) + // Each new step moves focus to its heading so screen readers hear the change once. + const stepKey = starting ? 'done' : `${flow.current?.id ?? 'done'}:${flow.action}` + React.useEffect(() => { + headingRef.current?.focus({ preventScroll: true }) + }, [stepKey]) + return ( +
+
+
+ + + + {t('cloudSetupPage.eyebrow', 'Orca Cloud setup')} + +
+ +
+ +
+ +
+

+ {copy.title} +

+ {flow.action === 'checking' && !starting ? ( + + ) : copy.lead ? ( +

{copy.lead}

+ ) : null} + {copy.note ?

{copy.note}

: null} +
+ + {flow.error && !starting ? ( + + action === 'reopen-browser' ? flow.reopenBrowser() : flow.continueInBrowser() + } + className="mt-6" + /> + ) : null} + +
+ +
+ +
+
+
+ {t('cloudSetupPage.startsAfter', 'Starts when setup is done')} +
+
+ {prompt.trim() || + t('cloudSetupPage.untitled', 'New cloud workspace')} +
+
+ {[projectName, agentLabel, t('cloudSetupPage.orcaCloud', 'Orca Cloud')] + .filter(Boolean) + .join(' · ')} +
+
+
+
+
+ ) +} diff --git a/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx b/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx new file mode 100644 index 00000000000..29603aa6f9a --- /dev/null +++ b/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx @@ -0,0 +1,94 @@ +// Mounts the Orca Cloud setup page over the workspace area while a Start is waiting on setup. Other +// pages (Settings for billing or agent accounts) show over it; coming back shows it again. Opening +// another workspace from the sidebar puts setup away (Back in the composer still has the prompt). +import React, { useCallback, useEffect, useRef, useState } from 'react' +import { useAppStore } from '@/store' +import { useTranslate } from '@/i18n/use-translate' +import { + closeCloudSetupPage, + useCloudSetupPageRequest, + type CloudSetupPageRequest +} from '@/lib/orca-cloud/cloud-setup-page-store' +import { CLOUD_SETUP_ALL_SET_HOLD_MS } from '@/lib/orca-cloud/cloud-setup-session-seam' +import { isOrcaCloudAccountAgent } from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' +import { ORCA_CLOUD_RECIPE_ID } from '../../../../shared/hosted-sandbox/orca-cloud-recipe-id' +import { agentName } from '@/components/settings/agent-accounts/orca-cloud-accounts-copy' +import { prefersReducedMotion } from '@/components/new-workspace/run-on/cloud-start-view' +import { CloudSetupPage } from './CloudSetupPage' +import { useCloudSetupFlow } from './use-cloud-setup-flow' + +function reopenComposer(request: CloudSetupPageRequest, autoStart: boolean): void { + closeCloudSetupPage() + useAppStore.getState().openModal('new-workspace-composer', { + ...request.composer, + initialEphemeralVmRecipeId: ORCA_CLOUD_RECIPE_ID, + // A GitHub-only repository can't be preselected; the composer opens for one more Start. + ...(autoStart && !request.cloudOnlyRepo ? { cloudAutoStart: true } : {}) + }) +} + +function ActiveCloudSetupPage({ request }: { request: CloudSetupPageRequest }): React.JSX.Element { + const t = useTranslate() + const flow = useCloudSetupFlow(request) + const projectName = useAppStore( + (s) => s.repos.find((repo) => repo.id === request.repoId)?.displayName ?? null + ) + const agentLabel = isOrcaCloudAccountAgent(request.agent) ? agentName(request.agent, t) : null + const [starting, setStarting] = useState(false) + const startedRef = useRef(false) + useEffect(() => { + if (flow.action !== 'done' || startedRef.current) { + return + } + startedRef.current = true + setStarting(true) + const timer = window.setTimeout( + () => reopenComposer(request, true), + prefersReducedMotion() ? 0 : CLOUD_SETUP_ALL_SET_HOLD_MS + ) + return () => window.clearTimeout(timer) + }, [flow.action, request]) + const onBack = useCallback(() => reopenComposer(request, false), [request]) + return ( + + ) +} + +export function CloudSetupPageLayer(): React.JSX.Element | null { + const request = useCloudSetupPageRequest() + const onWorkspaceView = useAppStore((s) => s.activeView === 'terminal') + const activeWorktreeId = useAppStore((s) => s.activeWorktreeId ?? null) + const openedOnRef = useRef(undefined) + useEffect(() => { + if (!request) { + openedOnRef.current = undefined + return + } + if (openedOnRef.current === undefined) { + openedOnRef.current = activeWorktreeId + return + } + if (openedOnRef.current !== activeWorktreeId) { + closeCloudSetupPage() + } + }, [activeWorktreeId, request]) + if (!request) { + return null + } + // Stays mounted under other pages so an open browser trip keeps its session and waiting state. + return ( +
+ +
+ ) +} diff --git a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.test.ts b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.test.ts new file mode 100644 index 00000000000..f6864620616 --- /dev/null +++ b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from 'vitest' +import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model' +import { actionForStep, cloudSetupPageModel, sessionNeedsFrom } from './cloud-setup-page-model' +import { effectiveAvailability } from './use-cloud-setup-flow' + +describe('cloudSetupPageModel', () => { + it('walks one step at a time: the first unfinished step is current', () => { + const steps: CloudSetupStep[] = [ + { id: 'account', state: 'done' }, + { id: 'plan', state: 'needed', need: 'trial', canFix: true, trialSeconds: 7200 }, + { id: 'github', state: 'needed', need: 'github', canFix: true }, + { id: 'agent', state: 'optional' } + ] + const model = cloudSetupPageModel(steps) + expect(model.current?.id).toBe('plan') + expect(model.action).toBe('start-trial') + expect(sessionNeedsFrom(steps)).toEqual(['plan', 'github']) + }) + + it('a skipped agent finishes setup', () => { + const steps: CloudSetupStep[] = [ + { id: 'account', state: 'done' }, + { id: 'plan', state: 'done' }, + { id: 'agent', state: 'optional' } + ] + expect(cloudSetupPageModel(steps).action).toBe('agent') + expect(cloudSetupPageModel(steps, { agentSkipped: true })).toMatchObject({ + current: null, + action: 'done' + }) + }) + + it('maps each blocker to its one action', () => { + expect(actionForStep({ id: 'plan', state: 'pending', need: 'trial' })).toBe('sign-in') + expect(actionForStep({ id: 'plan', state: 'needed', need: 'payment', canFix: true })).toBe( + 'fix-billing' + ) + expect(actionForStep({ id: 'plan', state: 'needed', need: 'plan', canFix: false })).toBe( + 'ask-owner' + ) + expect(actionForStep({ id: 'team', state: 'needed' }, { teamSwitch: true })).toBe( + 'switch-team' + ) + expect(actionForStep({ id: 'github', state: 'loading' })).toBe('checking') + }) +}) + +describe('effectiveAvailability', () => { + it('a sign-in that lands upgrades the snapshot from Start', () => { + expect(effectiveAvailability('needs-sign-in', { state: 'signed-out' })).toBe('needs-sign-in') + expect(effectiveAvailability('needs-sign-in', { state: 'loading' })).toBe('needs-sign-in') + expect( + effectiveAvailability('needs-sign-in', { state: 'entitled', remainingSeconds: 60 }) + ).toBe('offered') + expect(effectiveAvailability('offered', { state: 'signed-out' })).toBe('offered') + }) +}) diff --git a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.ts b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.ts new file mode 100644 index 00000000000..c867e00cd81 --- /dev/null +++ b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.ts @@ -0,0 +1,137 @@ +// The full-page Orca Cloud setup (composer-redo): which step is current, what its one action is, +// and when the saved prompt can start. Pure, so every state is unit-tested here. +import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model' + +/** What the current step's primary button does. */ +export type CloudSetupPageAction = + /** Sign in (and whatever the browser trip covers next): one browser hop. */ + | 'sign-in' + /** The team's trial, claimed in the app: no browser, no card. */ + | 'start-trial' + /** Stripe Checkout for a plan: one browser hop. */ + | 'choose-plan' + /** Hours, spend cap or payment, fixed in billing settings or the portal. */ + | 'fix-billing' + /** Personal account while a team has the plan: switch in place (B2). */ + | 'switch-team' + /** Install the GitHub App on this repository: one browser hop. */ + | 'github-install' + /** An owner must approve on GitHub; the page waits and starts on its own. */ + | 'github-waiting' + /** The project isn't on GitHub; nothing here fixes it. */ + | 'needs-repository' + /** A member can't fix billing; an owner or admin has to. */ + | 'ask-owner' + /** Optional agent account: set it up once, or skip. */ + | 'agent' + /** Still reading account, plan or repository state. */ + | 'checking' + /** Every step is done: the prompt starts. */ + | 'done' + +export type CloudSetupPageModel = { + steps: readonly CloudSetupStep[] + current: CloudSetupStep | null + action: CloudSetupPageAction +} + +function isFinished(step: CloudSetupStep, agentSkipped: boolean): boolean { + if (step.state === 'done') { + return true + } + if (step.id === 'agent') { + // Never wait on a slow agent-accounts read: it doesn't block a start. + return agentSkipped || step.state === 'loading' + } + return false +} + +export function actionForStep( + step: CloudSetupStep, + { teamSwitch = false }: { teamSwitch?: boolean } = {} +): CloudSetupPageAction { + if (step.state === 'loading') { + return 'checking' + } + switch (step.id) { + case 'account': + return 'sign-in' + case 'team': + return teamSwitch ? 'switch-team' : 'sign-in' + case 'plan': + if (step.state === 'pending') { + return 'sign-in' + } + if (step.canFix === false) { + return 'ask-owner' + } + switch (step.need) { + case 'trial': + return 'start-trial' + case 'hours': + case 'spend-cap': + case 'payment': + return 'fix-billing' + case 'plan': + case 'renew-plan': + case 'trial-used-up': + case 'sign-in': + case 'github': + case undefined: + return 'choose-plan' + } + return 'choose-plan' + case 'github': + if (step.state === 'failed' && step.blocksStart) { + return 'needs-repository' + } + if (step.state === 'pending' && step.blocksStart) { + return 'github-waiting' + } + return 'github-install' + case 'agent': + return 'agent' + } +} + +/** + * The page's state from the setup rows. Steps come in walk order (account, team, plan, GitHub, + * agent); the first unfinished one is current. A signed-out plan row is "pending" until sign-in, so + * account stays current until then. + */ +export function cloudSetupPageModel( + steps: readonly CloudSetupStep[], + { agentSkipped = false, teamSwitch = false }: { agentSkipped?: boolean; teamSwitch?: boolean } = {} +): CloudSetupPageModel { + const current = steps.find((step) => !isFinished(step, agentSkipped)) ?? null + if (!current) { + return { steps, current: null, action: 'done' } + } + return { steps, current, action: actionForStep(current, { teamSwitch }) } +} + +/** Needs that a browser trip (setup session) can cover, from the current step on. */ +export function sessionNeedsFrom(steps: readonly CloudSetupStep[]): CloudSetupStep['id'][] { + return steps + .filter((step) => step.state !== 'done' && step.state !== 'optional' && step.id !== 'agent') + .map((step) => step.id) +} + +/** + * Pressing Start goes straight to create only when nothing is open. An agent without an account + * counts until the user skips it once; a still-loading agent row never holds a start. + */ +export function cloudSetupRequired( + steps: readonly CloudSetupStep[], + { teamSwitch = false, agentSkipped = false }: { teamSwitch?: boolean; agentSkipped?: boolean } = {} +): boolean { + if (teamSwitch) { + return true + } + return steps.some((step) => { + if (step.id === 'agent') { + return step.state === 'optional' && !agentSkipped + } + return step.state !== 'done' + }) +} diff --git a/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts b/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts new file mode 100644 index 00000000000..1dcc361fdd5 --- /dev/null +++ b/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts @@ -0,0 +1,200 @@ +// The setup page's state and actions (composer-redo). It reuses the composer's setup plumbing: the +// rows from billing, the GitHub repository check and the agent accounts (useCloudStartSteps), the +// one-trip setup session (#255) with its deep-link return (#257), B2's team switch, and the +// tracker's error parsing (#260). Only the UI moved: from a card in the dialog to this page. +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { claimOrcaCloudTrial } from '@/components/billing/claim-trial' +import { + invalidateOrcaCloudBilling, + prefetchOrcaCloudBilling, + useOrcaCloudRunTargetAccess +} from '@/components/new-workspace/orca-cloud-billing-cache' +import { setupActionFor } from '@/components/new-workspace/run-on/cloud-start-actions' +import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model' +import { useCloudStartSteps } from '@/components/new-workspace/run-on/use-cloud-start-steps' +import { useSwitchTeamSteps } from '@/components/new-workspace/cloud-setup/use-cloud-setup-tracker' +import { parseCloudSetupError } from '@/components/new-workspace/cloud-setup/cloud-setup-errors' +import { + canCopyCloudSetupLink, + copyCloudSetupLink, + reopenCloudSetup +} from '@/components/new-workspace/cloud-setup/cloud-setup-tracker-actions' +import { getCloudSetupStarter } from '@/lib/orca-cloud/cloud-setup-session-seam' +import { + isCloudSetupAgentSkipped, + rememberCloudSetupAgentSkipped, + type CloudSetupPageRequest +} from '@/lib/orca-cloud/cloud-setup-page-store' +import { reportCloudSetupProgress } from '@/lib/orca-cloud/cloud-setup-telemetry' +import type { OrcaCloudAvailability } from '../../../../shared/orca-yaml-hook-types' +import type { OrcaCloudRunTargetAccess } from '@/components/new-workspace/orca-cloud-run-target-access' +import { cloudSetupPageModel, sessionNeedsFrom, type CloudSetupPageModel } from './cloud-setup-page-model' + +/** Billing rows re-read this often while the page waits on a browser step (focus also re-reads). */ +const BILLING_POLL_MS = 4_000 + +/** Main's availability is a snapshot from Start; once billing answers for a signed-in account, it wins. */ +export function effectiveAvailability( + requested: OrcaCloudAvailability, + access: OrcaCloudRunTargetAccess +): OrcaCloudAvailability { + if (requested === 'needs-sign-in' && access.state !== 'signed-out' && access.state !== 'loading') { + return 'offered' + } + return requested +} + +export type CloudSetupFlow = CloudSetupPageModel & { + /** True from the click until the browser opens or the trial answers. */ + busy: boolean + /** The browser trip is open: the current step reads "Waiting for your browser". */ + inBrowser: boolean + error: ReturnType + canManageBilling: boolean + teamAction: React.ReactNode | null + continueInBrowser: () => void + startTrial: () => void + fixBilling: () => void + installGitHub: () => void + skipAgent: () => void + checkAgain: () => void + copyLink: (() => void) | null + reopenBrowser: () => void +} + +export function useCloudSetupFlow( + request: CloudSetupPageRequest, + /** Fixtures pin the account; the app reads billing. */ + accessOverride?: OrcaCloudRunTargetAccess +): CloudSetupFlow { + const fetched = useOrcaCloudRunTargetAccess(!accessOverride) + const access = accessOverride ?? fetched + const availability = effectiveAvailability(request.availability, access) + const [sessionId, setSessionId] = useState(null) + const [inBrowser, setInBrowser] = useState(false) + const [busy, setBusy] = useState(false) + const [agentSkipped, setAgentSkipped] = useState(() => isCloudSetupAgentSkipped(request.agent)) + const githubOverride = useMemo( + () => (request.cloudOnlyRepo ? { id: 'github', state: 'done' } : null), + [request.cloudOnlyRepo] + ) + const { steps: rowSteps, session, openInstall } = useCloudStartSteps({ + availability, + access, + repoId: request.repoId, + agent: request.agent, + cloudSelected: true, + setupSessionId: sessionId, + githubOverride + }) + const { steps, held: switchTeam } = useSwitchTeamSteps(rowSteps, !session) + const model = cloudSetupPageModel(steps, { agentSkipped, teamSwitch: switchTeam !== null }) + const error = useMemo(() => { + const parsed = parseCloudSetupError(session?.error) + return parsed && session?.teamName ? { ...parsed, teamName: session.teamName } : parsed + }, [session?.error, session?.teamName]) + + // Rows derived from billing tick on their own: re-read while a step is waiting elsewhere. + const waiting = model.action !== 'done' && model.action !== 'agent' + useEffect(() => { + if (!waiting || accessOverride) { + return + } + const timer = window.setInterval(() => void prefetchOrcaCloudBilling(true), BILLING_POLL_MS) + return () => window.clearInterval(timer) + }, [accessOverride, waiting]) + + useEffect(() => { + if (sessionId) { + reportCloudSetupProgress(sessionId, steps, error?.kind ?? null, { afterTrial: false }) + } + }, [error?.kind, sessionId, steps]) + + const stepsRef = useRef(steps) + useEffect(() => { + stepsRef.current = steps + }, [steps]) + + const fallback = useCallback( + () => setupActionFor(stepsRef.current, access, availability)?.(), + [access, availability] + ) + + // One browser trip for everything still open from here (sign-in, team, trial or Checkout, GitHub). + const continueInBrowser = useCallback(() => { + const needs = sessionNeedsFrom(stepsRef.current) + if (needs.length > 0 && needs.every((need) => need === 'github')) { + setInBrowser(true) + void openInstall() + return + } + const start = getCloudSetupStarter() + if (!start) { + setInBrowser(true) + fallback() + return + } + setBusy(true) + void start({ repoId: request.repoId, needs }) + .then((opened) => { + setInBrowser(true) + if (opened) { + setSessionId(opened.sessionId) + } else { + fallback() + } + }) + .catch(() => fallback()) + .finally(() => setBusy(false)) + }, [fallback, openInstall, request.repoId]) + + const startTrial = useCallback(() => { + setBusy(true) + void claimOrcaCloudTrial() + .then((result) => { + if (result.status !== 'ok') { + // A personal account needs a team first, or the trial is gone: the browser covers it. + continueInBrowser() + } + }) + .finally(() => setBusy(false)) + }, [continueInBrowser]) + + const fixBilling = useCallback(() => { + setInBrowser(true) + invalidateOrcaCloudBilling({ refetchNow: false }) + fallback() + }, [fallback]) + + const installGitHub = useCallback(() => { + setInBrowser(true) + void openInstall() + }, [openInstall]) + + const skipAgent = useCallback(() => { + rememberCloudSetupAgentSkipped(request.agent) + setAgentSkipped(true) + }, [request.agent]) + + const checkAgain = useCallback(() => void prefetchOrcaCloudBilling(true), []) + + return { + ...model, + busy, + inBrowser, + error, + canManageBilling: access.state === 'no-plan' ? access.canManageBilling : true, + teamAction: switchTeam?.action ?? null, + continueInBrowser, + startTrial, + fixBilling, + installGitHub, + skipAgent, + checkAgain, + copyLink: + sessionId && canCopyCloudSetupLink(sessionId) + ? () => void copyCloudSetupLink(sessionId) + : null, + reopenBrowser: () => void reopenCloudSetup(sessionId, continueInBrowser) + } +} diff --git a/src/renderer/src/lib/orca-cloud/cloud-setup-page-store.ts b/src/renderer/src/lib/orca-cloud/cloud-setup-page-store.ts new file mode 100644 index 00000000000..8965f4d32b4 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-setup-page-store.ts @@ -0,0 +1,80 @@ +// The full-page "Set up Orca Cloud" view (composer-redo): Start in the composer closes the dialog +// and opens this page when the account isn't ready yet. The page walks the missing steps, then +// starts the saved prompt. One request at a time; a new Start replaces an older one. +import { useSyncExternalStore } from 'react' +import type { OrcaCloudAvailability } from '../../../../shared/orca-yaml-hook-types' +import type { ComposerModalData } from '@/components/new-workspace/composer-modal-data' + +export type CloudSetupPageRequest = { + prompt: string + repoId: string + agent: string | null + /** What main reported when Start was pressed; the page upgrades it once sign-in lands. */ + availability: OrcaCloudAvailability + /** D4: a GitHub repository with no clone here; the start goes through the composer visibly. */ + cloudOnlyRepo: string | null + /** The composer as it was: Back and the auto-start reopen it with everything kept. */ + composer: ComposerModalData + openedAt: number +} + +let current: CloudSetupPageRequest | null = null +const listeners = new Set<() => void>() + +function emit(): void { + for (const listener of listeners) { + listener() + } +} + +export function openCloudSetupPage(request: Omit): void { + current = { ...request, openedAt: Date.now() } + emit() +} + +export function closeCloudSetupPage(): void { + if (current === null) { + return + } + current = null + emit() +} + +export function getCloudSetupPageRequest(): CloudSetupPageRequest | null { + return current +} + +export function useCloudSetupPageRequest(): CloudSetupPageRequest | null { + return useSyncExternalStore( + (listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, + () => current + ) +} + +const AGENT_SKIP_KEY = 'orca.cloudSetup.agentSkipped.v1' + +/** "Skip for now" on the agent step is remembered, so a ready account isn't asked on every Start. */ +export function isCloudSetupAgentSkipped(agent: string | null): boolean { + if (!agent || typeof localStorage === 'undefined') { + return false + } + try { + return localStorage.getItem(`${AGENT_SKIP_KEY}:${agent}`) === '1' + } catch { + return false + } +} + +export function rememberCloudSetupAgentSkipped(agent: string | null): void { + if (!agent || typeof localStorage === 'undefined') { + return + } + try { + localStorage.setItem(`${AGENT_SKIP_KEY}:${agent}`, '1') + } catch { + // Private mode: the step asks again next time. + } +} From 81e8a445305db630502e756ae6ecf3fe5657abb3 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 15:58:58 -0800 Subject: [PATCH 016/149] fix(cloud): setup page re-reads availability; agent step always offers Set up once --- .../orca-cloud-setup/CloudSetupPage.tsx | 9 ++-- .../cloud-setup-page-model.test.ts | 12 ----- .../orca-cloud-setup/use-cloud-setup-flow.ts | 51 +++++++++++++++---- 3 files changed, 46 insertions(+), 26 deletions(-) diff --git a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx index 2c92bc3ba0b..136b2899d67 100644 --- a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx +++ b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx @@ -12,6 +12,7 @@ import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-sta import { CloudSetupErrorNotice } from '@/components/new-workspace/cloud-setup/CloudSetupErrorNotice' import { sessionDetailCopy } from '@/components/new-workspace/run-on/cloud-setup-session-copy' import type { CloudSetupFlow } from './use-cloud-setup-flow' +import { openOrcaCloudAgentAccounts } from '@/components/new-workspace/OrcaCloudAgentSetupRow' export type CloudSetupPageProps = { flow: CloudSetupFlow @@ -286,11 +287,9 @@ function StepActions({ flow }: { flow: CloudSetupFlow }): React.JSX.Element | nu case 'agent': return (
- {flow.current?.action ? ( - - ) : null} + diff --git a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.test.ts b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.test.ts index f6864620616..29903001e3d 100644 --- a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.test.ts +++ b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it } from 'vitest' import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model' import { actionForStep, cloudSetupPageModel, sessionNeedsFrom } from './cloud-setup-page-model' -import { effectiveAvailability } from './use-cloud-setup-flow' describe('cloudSetupPageModel', () => { it('walks one step at a time: the first unfinished step is current', () => { @@ -44,14 +43,3 @@ describe('cloudSetupPageModel', () => { expect(actionForStep({ id: 'github', state: 'loading' })).toBe('checking') }) }) - -describe('effectiveAvailability', () => { - it('a sign-in that lands upgrades the snapshot from Start', () => { - expect(effectiveAvailability('needs-sign-in', { state: 'signed-out' })).toBe('needs-sign-in') - expect(effectiveAvailability('needs-sign-in', { state: 'loading' })).toBe('needs-sign-in') - expect( - effectiveAvailability('needs-sign-in', { state: 'entitled', remainingSeconds: 60 }) - ).toBe('offered') - expect(effectiveAvailability('offered', { state: 'signed-out' })).toBe('offered') - }) -}) diff --git a/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts b/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts index 1dcc361fdd5..bac1d3e1a45 100644 --- a/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts +++ b/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts @@ -33,15 +33,42 @@ import { cloudSetupPageModel, sessionNeedsFrom, type CloudSetupPageModel } from /** Billing rows re-read this often while the page waits on a browser step (focus also re-reads). */ const BILLING_POLL_MS = 4_000 -/** Main's availability is a snapshot from Start; once billing answers for a signed-in account, it wins. */ -export function effectiveAvailability( - requested: OrcaCloudAvailability, - access: OrcaCloudRunTargetAccess +/** + * Main's Orca Cloud availability for the project (needs-sign-in, needs-capability, offered), read + * the way the composer reads it and re-read while the page waits, so a sign-in in the browser (or + * the dev sign-in) moves the page on. Starts from the composer's answer at Start. + */ +function useLiveAvailability( + repoId: string, + initial: OrcaCloudAvailability, + enabled: boolean ): OrcaCloudAvailability { - if (requested === 'needs-sign-in' && access.state !== 'signed-out' && access.state !== 'loading') { - return 'offered' - } - return requested + const [availability, setAvailability] = useState(initial) + useEffect(() => { + if (!enabled) { + return + } + let cancelled = false + const read = (): void => { + void Promise.resolve() + .then(() => window.api.ephemeralVm.listRecipes({ repoId })) + .then((result) => { + if (!cancelled && result.orcaCloud) { + setAvailability(result.orcaCloud) + } + }) + .catch(() => undefined) + } + read() + const timer = window.setInterval(read, BILLING_POLL_MS) + window.addEventListener('focus', read) + return () => { + cancelled = true + window.clearInterval(timer) + window.removeEventListener('focus', read) + } + }, [enabled, repoId]) + return availability } export type CloudSetupFlow = CloudSetupPageModel & { @@ -69,7 +96,8 @@ export function useCloudSetupFlow( ): CloudSetupFlow { const fetched = useOrcaCloudRunTargetAccess(!accessOverride) const access = accessOverride ?? fetched - const availability = effectiveAvailability(request.availability, access) + const [settled, setSettled] = useState(false) + const availability = useLiveAvailability(request.repoId, request.availability, !settled && !accessOverride) const [sessionId, setSessionId] = useState(null) const [inBrowser, setInBrowser] = useState(false) const [busy, setBusy] = useState(false) @@ -89,6 +117,11 @@ export function useCloudSetupFlow( }) const { steps, held: switchTeam } = useSwitchTeamSteps(rowSteps, !session) const model = cloudSetupPageModel(steps, { agentSkipped, teamSwitch: switchTeam !== null }) + useEffect(() => { + if (model.action === 'done') { + setSettled(true) + } + }, [model.action]) const error = useMemo(() => { const parsed = parseCloudSetupError(session?.error) return parsed && session?.teamName ? { ...parsed, teamName: session.teamName } : parsed From 3431639cc2a5ce3e3f3bdaf4275c53e93108e172 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 16:00:10 -0800 Subject: [PATCH 017/149] fix(cloud): an agent with no Orca Cloud account never launches into /login; start a terminal and offer Set up once --- .../components/NewWorkspaceComposerModal.tsx | 11 +-- .../run-on/use-cloud-start-composer.ts | 68 ++++++++++++++++--- .../run-on/use-composer-cloud-start.ts | 7 +- 3 files changed, 72 insertions(+), 14 deletions(-) diff --git a/src/renderer/src/components/NewWorkspaceComposerModal.tsx b/src/renderer/src/components/NewWorkspaceComposerModal.tsx index c3dade45313..460cd81b925 100644 --- a/src/renderer/src/components/NewWorkspaceComposerModal.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerModal.tsx @@ -234,14 +234,17 @@ function QuickTabBody({ [observation.contextKey, orcaCloud] ) - const handleCreate = useCallback(async (): Promise => { + // `withoutAgent`: Orca Cloud with an agent that has no account there starts a plain terminal + // instead of dropping the user into the agent's /login. + const handleCreate = useCallback(async (options?: { withoutAgent?: boolean }): Promise => { if (createDisabled) { return } - await submitQuick(quickAgent, { + const agent = options?.withoutAgent ? null : quickAgent + await submitQuick(agent, { // Blank Terminal is the setup-only create: no agent, and no extra shell beside setup. - setupOnly: quickAgent === null, - launchChoice: launchSelection.choice, + setupOnly: agent === null, + ...(agent === null ? {} : { launchChoice: launchSelection.choice }), onLegacyPreparationFailure: (error) => { if (isSubmissionCancelled()) { return diff --git a/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts b/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts index d21e4d424ea..b090d33479f 100644 --- a/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts +++ b/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts @@ -25,9 +25,39 @@ import { cloudSetupRequired } from '../../orca-cloud-setup/cloud-setup-page-mode import { useRunOnDefault } from './use-run-on-default' import { useCloudOnlyCreate, useCloudOnlyRepo } from './use-cloud-only-repo' import type { CloudStartView } from './cloud-start-view' +import { openOrcaCloudAgentAccounts } from '../OrcaCloudAgentSetupRow' +import { agentName } from '../../settings/agent-accounts/orca-cloud-accounts-copy' +import { isOrcaCloudAccountAgent } from '../../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' export type { CloudStartView } from './cloud-start-view' +/** The workspace started without its agent: one clear way to set the agent up for next time. */ +function showAgentNotStartedToast(agent: string | null): void { + const name = isOrcaCloudAccountAgent(agent) ? agentName(agent, translate) : null + toast.message( + name + ? translate( + 'components.newWorkspace.cloudStart.agentNotStarted', + '{{agent}} isn’t set up for Orca Cloud, so it didn’t start. The workspace has a terminal.', + { agent: name } + ) + : translate( + 'components.newWorkspace.cloudStart.agentNotStartedGeneric', + 'Your agent isn’t set up for Orca Cloud, so it didn’t start. The workspace has a terminal.' + ), + { + action: { + label: name + ? translate('components.newWorkspace.cloudStart.setUpAgentOnce', 'Set up {{agent}} once', { + agent: name + }) + : translate('components.newWorkspace.cloudStart.setUpAgentOnceGeneric', 'Set up once'), + onClick: openOrcaCloudAgentAccounts + } + } + ) +} + export function useCloudStartComposer({ active, availability, @@ -41,6 +71,7 @@ export function useCloudStartComposer({ createReady = true, composerSnapshot, onCreate: createWorkspace, + onCreateWithoutAgent, onClose, accessOverride }: { @@ -60,6 +91,8 @@ export function useCloudStartComposer({ /** The composer as it is now, for the setup page's Back and its auto-start. */ composerSnapshot: () => ComposerModalData onCreate: () => void + /** The same create with no agent launched (the agent has no Orca Cloud account yet). */ + onCreateWithoutAgent?: () => void /** Closes the composer (setup moves to its page; a cloud-only repository started, D4). */ onClose?: () => void /** Fixtures pin the account's access. */ @@ -82,15 +115,6 @@ export function useCloudStartComposer({ cloudOffered: segment === 'enabled', signedIn: availability !== 'needs-sign-in' && access.state !== 'signed-out' }) - const onCreate = useCloudOnlyCreate({ - cloudOnly, - createWorkspace, - prompt, - agent, - profileId, - hoursToast: getOrcaCloudStartToast(access, translate, navigator.language), - onClose - }) const { steps: rowSteps } = useCloudStartSteps({ availability, access, @@ -105,6 +129,32 @@ export function useCloudStartComposer({ teamSwitch: switchTeam !== null, agentSkipped: isCloudSetupAgentSkipped(agent) }) + // The agent has no Orca Cloud account (the user skipped setting it up): never launch it into its + // /login. Start a plain terminal and say how to set the agent up once. + const agentUnset = + cloudSelected && steps.some((step) => step.id === 'agent' && step.state === 'optional') + const onCreateRaw = useCloudOnlyCreate({ + cloudOnly, + createWorkspace, + prompt, + agent: agentUnset ? null : agent, + profileId, + hoursToast: getOrcaCloudStartToast(access, translate, navigator.language), + onClose + }) + const onCreate = useCallback(() => { + if (!agentUnset) { + onCreateRaw() + return + } + // A GitHub-only start already leaves the agent out (above); a local project's create skips it. + if (cloudOnly.picked || !onCreateWithoutAgent) { + onCreateRaw() + } else { + onCreateWithoutAgent() + } + showAgentNotStartedToast(agent) + }, [agent, agentUnset, cloudOnly.picked, onCreateRaw, onCreateWithoutAgent]) const { markTouched } = useRunOnDefault({ active, diff --git a/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts b/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts index 7398b7f8375..4c14cbeb795 100644 --- a/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts +++ b/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts @@ -29,7 +29,7 @@ export function useComposerCloudStart({ modalData: ComposerModalData cardProps: ComposerCardState quickAgent: string | null - handleCreate: () => Promise + handleCreate: (options?: { withoutAgent?: boolean }) => Promise createDisabled: boolean composerSnapshot: () => ComposerModalData /** The composer's onCreated calls this: only a start that happened is remembered. */ @@ -39,6 +39,10 @@ export function useComposerCloudStart({ // The latest handleCreate, never a ref copied after render: a submit right after an edit must // see that edit. const runCreate = useCallback(() => void handleCreate(), [handleCreate]) + const runCreateWithoutAgent = useCallback( + () => void handleCreate({ withoutAgent: true }), + [handleCreate] + ) const cloudStart = useCloudStartComposer({ active, availability: cardProps.orcaCloudAvailability ?? 'unavailable', @@ -54,6 +58,7 @@ export function useComposerCloudStart({ createReady: !createDisabled, composerSnapshot, onCreate: runCreate, + onCreateWithoutAgent: runCreateWithoutAgent, onClose }) useEffect(() => { From 0c8d1422995441c08faca992daef507b9973fb10 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 16:03:01 -0800 Subject: [PATCH 018/149] chore(cloud): composer-redo lint (file size, footer type, no stale state) --- .../components/NewWorkspaceComposerModal.tsx | 173 +++++++----------- .../NewWorkspaceComposerFooter.tsx | 11 +- .../NewWorkspaceComposerProjectSection.tsx | 36 ++-- .../new-workspace/RunTargetCombobox.tsx | 24 +-- .../new-workspace/RunTargetRowList.tsx | 7 +- .../composer-cloud-auto-start.tsx | 61 ++++++ .../run-on/use-cloud-start-composer.ts | 10 +- .../run-on/use-composer-cloud-start.ts | 17 +- .../orca-cloud-setup/CloudSetupPage.tsx | 48 +++-- .../cloud-setup-page-model.test.ts | 4 +- .../cloud-setup-page-model.ts | 10 +- .../orca-cloud-setup/use-cloud-setup-flow.ts | 20 +- 12 files changed, 240 insertions(+), 181 deletions(-) create mode 100644 src/renderer/src/components/new-workspace/composer-cloud-auto-start.tsx diff --git a/src/renderer/src/components/NewWorkspaceComposerModal.tsx b/src/renderer/src/components/NewWorkspaceComposerModal.tsx index 460cd81b925..7870613b944 100644 --- a/src/renderer/src/components/NewWorkspaceComposerModal.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerModal.tsx @@ -39,9 +39,7 @@ import { getFolderWorkspacePrimaryActionLabel } from '@/components/sidebar/works import { useAgentMenuObservation } from '@/components/tab-bar/use-new-tab-agent-menu-rows' import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router' import { useComposerCloudStart } from './new-workspace/run-on/use-composer-cloud-start' - -/** How long a hidden Orca Cloud auto-start may take before the dialog shows instead. */ -const CLOUD_AUTO_START_REVEAL_MS = 8_000 +import { HiddenComposer, useCloudAutoStartReveal } from './new-workspace/composer-cloud-auto-start' // Keep Add Project’s clone/SSH machinery outside the composer entry render, matching App loading. const HostedAddRepoDialog = lazyWithRetry( @@ -83,34 +81,18 @@ function ComposerModalBody({ onClose() }, [onClose]) const isSubmissionCancelled = useCallback(() => submitCancelledRef.current, []) - // Orca Cloud setup finished on its page: submit with the dialog unseen. If the start can't run - // by itself (a form error, a revoked grant), the dialog appears with everything kept. - const [autoStartRevealed, setAutoStartRevealed] = useState(false) - useEffect(() => { - if (!modalData.cloudAutoStart) { - return - } - const timer = window.setTimeout(() => setAutoStartRevealed(true), CLOUD_AUTO_START_REVEAL_MS) - return () => window.clearTimeout(timer) - }, [modalData.cloudAutoStart]) - if (modalData.cloudAutoStart && !autoStartRevealed) { - return ( - // A closed Root still provides the title's context; nothing is portaled or shown. - -
- -
-
- ) + const visibleModalData = useCloudAutoStartReveal(modalData) + const body = (data: ComposerModalData): React.JSX.Element => ( + + ) + if (!visibleModalData) { + return {body(modalData)} } - const visibleModalData = modalData.cloudAutoStart - ? { ...modalData, cloudAutoStart: false } - : modalData return ( !open && handleDismiss()}> @@ -129,12 +111,7 @@ function ComposerModalBody({ getWorkspaceComposerInitialFocusTarget(content)?.focus({ preventScroll: true }) }} > - + {body(visibleModalData)} ) @@ -236,75 +213,67 @@ function QuickTabBody({ // `withoutAgent`: Orca Cloud with an agent that has no account there starts a plain terminal // instead of dropping the user into the agent's /login. - const handleCreate = useCallback(async (options?: { withoutAgent?: boolean }): Promise => { - if (createDisabled) { - return - } - const agent = options?.withoutAgent ? null : quickAgent - await submitQuick(agent, { - // Blank Terminal is the setup-only create: no agent, and no extra shell beside setup. - setupOnly: agent === null, - ...(agent === null ? {} : { launchChoice: launchSelection.choice }), - onLegacyPreparationFailure: (error) => { - if (isSubmissionCancelled()) { - return - } - const snapshot = { - ...modalData, - prefilledName: cardProps.name, - initialRepoId: cardProps.repoId, - initialBaseBranch: cardProps.baseBranch, - initialWorkspaceTarget: - cardProps.selectedProjectId && cardProps.selectedRepoExecutionHostId - ? { - projectId: cardProps.selectedProjectId, - hostId: cardProps.selectedRepoExecutionHostId, - projectHostSetupId: cardProps.selectedProjectHostSetupId ?? null + const handleCreate = useCallback( + async (options?: { withoutAgent?: boolean }): Promise => { + if (createDisabled) { + return + } + const agent = options?.withoutAgent ? null : quickAgent + await submitQuick(agent, { + // Blank Terminal is the setup-only create: no agent, and no extra shell beside setup. + setupOnly: agent === null, + ...(agent === null ? {} : { launchChoice: launchSelection.choice }), + onLegacyPreparationFailure: (error) => { + if (isSubmissionCancelled()) { + return + } + const snapshot = { + ...modalData, + prefilledName: cardProps.name, + initialRepoId: cardProps.repoId, + initialBaseBranch: cardProps.baseBranch, + initialWorkspaceTarget: + cardProps.selectedProjectId && cardProps.selectedRepoExecutionHostId + ? { + projectId: cardProps.selectedProjectId, + hostId: cardProps.selectedRepoExecutionHostId, + projectHostSetupId: cardProps.selectedProjectHostSetupId ?? null + } + : modalData.initialWorkspaceTarget, + linkedWorkItem: cardProps.linkedWorkItem, + recovery: { ...quickAgentPick, agent: quickAgent, note: cardProps.note } + } + toast.error(getWorkspaceCreateErrorToastMessage(formatWorkspaceCreateError(error)), { + action: { + label: translate('auto.lib.composerCreateHandoff.reopen', 'Reopen'), + onClick: () => { + if (!isSubmissionCancelled() && useAppStore.getState().activeModal === 'none') { + useAppStore.getState().openModal('new-workspace-composer', snapshot) } - : modalData.initialWorkspaceTarget, - linkedWorkItem: cardProps.linkedWorkItem, - recovery: { ...quickAgentPick, agent: quickAgent, note: cardProps.note } - } - toast.error(getWorkspaceCreateErrorToastMessage(formatWorkspaceCreateError(error)), { - action: { - label: translate('auto.lib.composerCreateHandoff.reopen', 'Reopen'), - onClick: () => { - if (!isSubmissionCancelled() && useAppStore.getState().activeModal === 'none') { - useAppStore.getState().openModal('new-workspace-composer', snapshot) } } - } - }) - }, - ...quickWorkspacePickerInputs( - pickerDraft, - quickAgentPick.entry, - launchSelection.choice?.executionHostId - ) - }) - }, [ - createDisabled, - quickAgent, - launchSelection.choice, - submitQuick, - pickerDraft, - quickAgentPick, - isSubmissionCancelled, - modalData, - cardProps - ]) - // The composer as it is now, for Orca Cloud's setup page (Back, and the start when it's done). - const composerSnapshot = useCallback( - (): ComposerModalData => ({ - ...modalData, - prefilledName: cardProps.name, - initialRepoId: cardProps.repoId, - initialBaseBranch: cardProps.baseBranch, - linkedWorkItem: cardProps.linkedWorkItem, - recovery: { ...quickAgentPick, agent: quickAgent, note: cardProps.note } - }), - [cardProps, modalData, quickAgent, quickAgentPick] + }) + }, + ...quickWorkspacePickerInputs( + pickerDraft, + quickAgentPick.entry, + launchSelection.choice?.executionHostId + ) + }) + }, + [ + createDisabled, + quickAgent, + launchSelection.choice, + submitQuick, + pickerDraft, + quickAgentPick, + isSubmissionCancelled, + modalData, + cardProps + ] ) + // The composer as it is now, for Orca Cloud's setup page (Back, and the start when it's done). const { cloudStart, primaryCreateDisabled, onPrimary } = useComposerCloudStart({ active, modalData, @@ -312,7 +281,7 @@ function QuickTabBody({ quickAgent, handleCreate, createDisabled, - composerSnapshot, + quickAgentPick, recordCreatedRef, onClose }) diff --git a/src/renderer/src/components/new-workspace/NewWorkspaceComposerFooter.tsx b/src/renderer/src/components/new-workspace/NewWorkspaceComposerFooter.tsx index 07f1534aa61..c041625c6e2 100644 --- a/src/renderer/src/components/new-workspace/NewWorkspaceComposerFooter.tsx +++ b/src/renderer/src/components/new-workspace/NewWorkspaceComposerFooter.tsx @@ -72,11 +72,14 @@ export function NewWorkspaceComposerFooter({ onClick={() => void onCreate()} disabled={createDisabled} size="sm" - className="ml-auto shrink-0 text-xs" + className="ml-auto shrink-0" > - {creating ? : null} - {primaryActionLabel} - + {/* The footer's compact type, as before; the Button keeps its own variant styling. */} + + {creating ? : null} + {primaryActionLabel} + +
diff --git a/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx b/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx index 67078a12a40..d7f1e67462b 100644 --- a/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx +++ b/src/renderer/src/components/new-workspace/NewWorkspaceComposerProjectSection.tsx @@ -38,24 +38,24 @@ type NewWorkspaceComposerProjectSectionProps = Pick< | 'orcaCloudAvailability' | 'cloudStart' > & { - disabled?: boolean - projectDescriptionId: string - onAddProject: () => void - focusNameInput: () => void - shouldShowRunTargetPicker: boolean - projectHostSetupOptions: NewWorkspaceComposerCardProps['projectHostSetupOptions'] - ephemeralVmRecipes: EphemeralVmRecipeOption[] - handleProjectHostSetupChange: (setupId: string) => void - handleAddSshHost: () => void - handleAddRemoteServer: () => void - handleConnectRunTargetHost: (option: NeedsProjectHostOption) => Promise - handleSetLocation: (option: NeedsProjectHostOption) => void - sshStatusLabel: string - connectButtonLabel: string - selectedProjectName: string - /** Fixtures pin Orca Cloud entitlement; the app reads it from billing. */ - orcaCloudAccess?: OrcaCloudRunTargetAccess - } + disabled?: boolean + projectDescriptionId: string + onAddProject: () => void + focusNameInput: () => void + shouldShowRunTargetPicker: boolean + projectHostSetupOptions: NewWorkspaceComposerCardProps['projectHostSetupOptions'] + ephemeralVmRecipes: EphemeralVmRecipeOption[] + handleProjectHostSetupChange: (setupId: string) => void + handleAddSshHost: () => void + handleAddRemoteServer: () => void + handleConnectRunTargetHost: (option: NeedsProjectHostOption) => Promise + handleSetLocation: (option: NeedsProjectHostOption) => void + sshStatusLabel: string + connectButtonLabel: string + selectedProjectName: string + /** Fixtures pin Orca Cloud entitlement; the app reads it from billing. */ + orcaCloudAccess?: OrcaCloudRunTargetAccess +} export function NewWorkspaceComposerProjectSection({ disabled = false, diff --git a/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx b/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx index ec6ce2b237c..c8e7a185a1d 100644 --- a/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx @@ -9,7 +9,6 @@ import { type ReadyProjectHostSetupOption } from '@/lib/project-host-setup-options' import type { ExecutionHostId } from '../../../../shared/execution-host' -import { ORCA_CLOUD_RECIPE_ID } from '../../../../shared/hosted-sandbox/orca-cloud-recipe-id' import { isWithinComboboxRoot, useTypeAheadCombobox } from './use-type-ahead-combobox' import { COMBOBOX_POPOVER_SURFACE } from './type-ahead-combobox-styles' import { @@ -18,9 +17,6 @@ import { getRecipeSubmenuItemKey, getRunTargetSubmenuItemKeys, getRunTargetCurrentRowKey, - getOrcaCloudDetail, - ORCA_CLOUD_LABEL, - RUN_TARGET_ORCA_CLOUD_KEY, getRunTargetOptionId, RUN_TARGET_ADD_HOST_KEY, RUN_TARGET_ADD_REMOTE_SERVER_ITEM, @@ -110,13 +106,8 @@ export default function RunTargetCombobox({ // An unlisted target (e.g. a per-workspace VM) shows "Choose target", never another host's name (#38669). null const selectedRecipe = recipes.find((recipe) => recipe.id === recipeValue) ?? null - // Signed out, main lists no Orca Cloud recipe, yet the composer can still pick it. - const orcaCloudPicked = - selectedRecipe === null && recipeValue === ORCA_CLOUD_RECIPE_ID && Boolean(onSelectOrcaCloud) // Opening highlights the committed row, so only one row reads as chosen. - const currentRowKey = orcaCloudPicked - ? RUN_TARGET_ORCA_CLOUD_KEY - : getRunTargetCurrentRowKey(selectedRecipe, selectedHost) + const currentRowKey = getRunTargetCurrentRowKey(selectedRecipe, selectedHost) const hasAddHost = Boolean(onAddSshHost || onAddRemoteServer) const orcaCloudOffer = getRunTargetOrcaCloudOffer({ @@ -152,8 +143,7 @@ export default function RunTargetCombobox({ const { submenu, armedItemKey, openSubmenu, closeSubmenu, armItem, moveItemArm, armItemEdge } = useRunTargetSubmenu(submenuItemKeys) const armedRow = rows.find((row) => row.key === armedKey) ?? rows[0] ?? null - const committed = - query.length === 0 && (orcaCloudPicked || selectedRecipe !== null || selectedHost !== null) + const committed = query.length === 0 && (selectedRecipe !== null || selectedHost !== null) // Closing also drops any open submenu, which the shared hook doesn't know about. const close = useCallback((): void => { @@ -324,9 +314,7 @@ export default function RunTargetCombobox({ const activeDescendantId = activeDescendantKey ? optionIdFor(activeDescendantKey) : undefined const addHostOptionId = optionIdFor(RUN_TARGET_ADD_HOST_KEY) - const field = orcaCloudPicked - ? { label: ORCA_CLOUD_LABEL, detail: getOrcaCloudDetail(t), recipeKind: 'orca-cloud' as const } - : getRunTargetFieldText(selectedRecipe, selectedHost, t) + const field = getRunTargetFieldText(selectedRecipe, selectedHost, t) return ( @@ -342,7 +330,7 @@ export default function RunTargetCombobox({ onToggle={() => setOpen(!open)} committed={committed} recipeKind={field.recipeKind} - hostId={orcaCloudPicked ? null : (selectedHost?.hostId ?? null)} + hostId={selectedHost?.hostId ?? null} label={field.label} detail={field.detail} controlsId={submenu ? `${listId} ${listId}-${submenu}` : listId} @@ -396,8 +384,8 @@ export default function RunTargetCombobox({ onArm(row.key, null)} onSelect={() => onSelectOrcaCloud(row.recipe)} diff --git a/src/renderer/src/components/new-workspace/composer-cloud-auto-start.tsx b/src/renderer/src/components/new-workspace/composer-cloud-auto-start.tsx new file mode 100644 index 00000000000..c327e43e5c7 --- /dev/null +++ b/src/renderer/src/components/new-workspace/composer-cloud-auto-start.tsx @@ -0,0 +1,61 @@ +// The composer's side of the Orca Cloud setup page (composer-redo): the snapshot the page keeps for +// Back and for its auto-start, and the hidden composer that submits once setup is done. +import React, { useEffect, useState } from 'react' +import { Dialog } from '@/components/ui/dialog' +import type { ComposerModalData } from './composer-modal-data' + +/** How long a hidden Orca Cloud auto-start may take before the dialog shows instead. */ +const CLOUD_AUTO_START_REVEAL_MS = 8_000 + +/** The composer as it is now: prompt, project, base branch, linked item and agent pick. */ +export function buildComposerSnapshot( + modalData: ComposerModalData, + card: { + name: string + repoId: string + baseBranch?: string + linkedWorkItem?: ComposerModalData['linkedWorkItem'] + note: string + }, + agentPick: Omit, 'note'> +): ComposerModalData { + return { + ...modalData, + prefilledName: card.name, + initialRepoId: card.repoId, + ...(card.baseBranch ? { initialBaseBranch: card.baseBranch } : {}), + linkedWorkItem: card.linkedWorkItem ?? null, + recovery: { ...agentPick, note: card.note } + } +} + +/** + * Setup finished on its page: the composer submits with the dialog unseen. If the start can't run + * by itself in time (a form error, a revoked grant), the dialog appears with everything kept. + * Returns the modal data to render once visible (no second auto-start), or null while hidden. + */ +export function useCloudAutoStartReveal(modalData: ComposerModalData): ComposerModalData | null { + const [revealed, setRevealed] = useState(false) + useEffect(() => { + if (!modalData.cloudAutoStart) { + return + } + const timer = window.setTimeout(() => setRevealed(true), CLOUD_AUTO_START_REVEAL_MS) + return () => window.clearTimeout(timer) + }, [modalData.cloudAutoStart]) + if (!modalData.cloudAutoStart) { + return modalData + } + return revealed ? { ...modalData, cloudAutoStart: false } : null +} + +/** A closed Root still gives the title its context; nothing is portaled or shown. */ +export function HiddenComposer({ children }: { children: React.ReactNode }): React.JSX.Element { + return ( + +
+ {children} +
+
+ ) +} diff --git a/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts b/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts index b090d33479f..28cc960bfd6 100644 --- a/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts +++ b/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts @@ -48,9 +48,13 @@ function showAgentNotStartedToast(agent: string | null): void { { action: { label: name - ? translate('components.newWorkspace.cloudStart.setUpAgentOnce', 'Set up {{agent}} once', { - agent: name - }) + ? translate( + 'components.newWorkspace.cloudStart.setUpAgentOnce', + 'Set up {{agent}} once', + { + agent: name + } + ) : translate('components.newWorkspace.cloudStart.setUpAgentOnceGeneric', 'Set up once'), onClick: openOrcaCloudAgentAccounts } diff --git a/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts b/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts index 4c14cbeb795..d275d5e4351 100644 --- a/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts +++ b/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts @@ -4,6 +4,8 @@ import { useCallback, useEffect, type MutableRefObject } from 'react' import type { ComposerModalData } from '../composer-modal-data' import type { NewWorkspaceComposerCardProps } from '../new-workspace-composer-card-props' import { useCloudStartComposer } from './use-cloud-start-composer' +import { buildComposerSnapshot } from '../composer-cloud-auto-start' +import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent' type ComposerCardState = Pick< NewWorkspaceComposerCardProps, @@ -12,7 +14,9 @@ type ComposerCardState = Pick< | 'onEphemeralVmRecipeChange' | 'repoId' | 'name' -> + | 'baseBranch' + | 'note' +> & { linkedWorkItem?: ComposerModalData['linkedWorkItem'] } export function useComposerCloudStart({ active, @@ -21,17 +25,18 @@ export function useComposerCloudStart({ quickAgent, handleCreate, createDisabled, - composerSnapshot, + quickAgentPick, recordCreatedRef, onClose }: { active: boolean modalData: ComposerModalData cardProps: ComposerCardState - quickAgent: string | null + quickAgent: TuiAgent | null handleCreate: (options?: { withoutAgent?: boolean }) => Promise createDisabled: boolean - composerSnapshot: () => ComposerModalData + /** The agent pick (surface, draft) as the composer keeps it, for the setup page's snapshot. */ + quickAgentPick: Omit, 'note'> /** The composer's onCreated calls this: only a start that happened is remembered. */ recordCreatedRef: MutableRefObject<(() => void) | null> onClose?: () => void @@ -43,6 +48,10 @@ export function useComposerCloudStart({ () => void handleCreate({ withoutAgent: true }), [handleCreate] ) + const composerSnapshot = useCallback( + () => buildComposerSnapshot(modalData, cardProps, { ...quickAgentPick, agent: quickAgent }), + [cardProps, modalData, quickAgent, quickAgentPick] + ) const cloudStart = useCloudStartComposer({ active, availability: cardProps.orcaCloudAvailability ?? 'unavailable', diff --git a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx index 136b2899d67..21badae9365 100644 --- a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx +++ b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx @@ -77,7 +77,9 @@ function SetupStepper({ )} > {state === 'done' ? : null} - {state === 'current' ? : null} + {state === 'current' ? ( + + ) : null} -
- +
@@ -404,8 +429,7 @@ export function CloudSetupPage({ {t('cloudSetupPage.startsAfter', 'Starts when setup is done')}
- {prompt.trim() || - t('cloudSetupPage.untitled', 'New cloud workspace')} + {prompt.trim() || t('cloudSetupPage.untitled', 'New cloud workspace')}
{[projectName, agentLabel, t('cloudSetupPage.orcaCloud', 'Orca Cloud')] diff --git a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.test.ts b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.test.ts index 29903001e3d..39992136e7a 100644 --- a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.test.ts +++ b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.test.ts @@ -37,9 +37,7 @@ describe('cloudSetupPageModel', () => { expect(actionForStep({ id: 'plan', state: 'needed', need: 'plan', canFix: false })).toBe( 'ask-owner' ) - expect(actionForStep({ id: 'team', state: 'needed' }, { teamSwitch: true })).toBe( - 'switch-team' - ) + expect(actionForStep({ id: 'team', state: 'needed' }, { teamSwitch: true })).toBe('switch-team') expect(actionForStep({ id: 'github', state: 'loading' })).toBe('checking') }) }) diff --git a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.ts b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.ts index c867e00cd81..528ebbecce4 100644 --- a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.ts +++ b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.ts @@ -101,7 +101,10 @@ export function actionForStep( */ export function cloudSetupPageModel( steps: readonly CloudSetupStep[], - { agentSkipped = false, teamSwitch = false }: { agentSkipped?: boolean; teamSwitch?: boolean } = {} + { + agentSkipped = false, + teamSwitch = false + }: { agentSkipped?: boolean; teamSwitch?: boolean } = {} ): CloudSetupPageModel { const current = steps.find((step) => !isFinished(step, agentSkipped)) ?? null if (!current) { @@ -123,7 +126,10 @@ export function sessionNeedsFrom(steps: readonly CloudSetupStep[]): CloudSetupSt */ export function cloudSetupRequired( steps: readonly CloudSetupStep[], - { teamSwitch = false, agentSkipped = false }: { teamSwitch?: boolean; agentSkipped?: boolean } = {} + { + teamSwitch = false, + agentSkipped = false + }: { teamSwitch?: boolean; agentSkipped?: boolean } = {} ): boolean { if (teamSwitch) { return true diff --git a/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts b/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts index bac1d3e1a45..c2496997546 100644 --- a/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts +++ b/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts @@ -28,7 +28,11 @@ import { import { reportCloudSetupProgress } from '@/lib/orca-cloud/cloud-setup-telemetry' import type { OrcaCloudAvailability } from '../../../../shared/orca-yaml-hook-types' import type { OrcaCloudRunTargetAccess } from '@/components/new-workspace/orca-cloud-run-target-access' -import { cloudSetupPageModel, sessionNeedsFrom, type CloudSetupPageModel } from './cloud-setup-page-model' +import { + cloudSetupPageModel, + sessionNeedsFrom, + type CloudSetupPageModel +} from './cloud-setup-page-model' /** Billing rows re-read this often while the page waits on a browser step (focus also re-reads). */ const BILLING_POLL_MS = 4_000 @@ -96,8 +100,7 @@ export function useCloudSetupFlow( ): CloudSetupFlow { const fetched = useOrcaCloudRunTargetAccess(!accessOverride) const access = accessOverride ?? fetched - const [settled, setSettled] = useState(false) - const availability = useLiveAvailability(request.repoId, request.availability, !settled && !accessOverride) + const availability = useLiveAvailability(request.repoId, request.availability, !accessOverride) const [sessionId, setSessionId] = useState(null) const [inBrowser, setInBrowser] = useState(false) const [busy, setBusy] = useState(false) @@ -106,7 +109,11 @@ export function useCloudSetupFlow( () => (request.cloudOnlyRepo ? { id: 'github', state: 'done' } : null), [request.cloudOnlyRepo] ) - const { steps: rowSteps, session, openInstall } = useCloudStartSteps({ + const { + steps: rowSteps, + session, + openInstall + } = useCloudStartSteps({ availability, access, repoId: request.repoId, @@ -117,11 +124,6 @@ export function useCloudSetupFlow( }) const { steps, held: switchTeam } = useSwitchTeamSteps(rowSteps, !session) const model = cloudSetupPageModel(steps, { agentSkipped, teamSwitch: switchTeam !== null }) - useEffect(() => { - if (model.action === 'done') { - setSettled(true) - } - }, [model.action]) const error = useMemo(() => { const parsed = parseCloudSetupError(session?.error) return parsed && session?.teamName ? { ...parsed, teamName: session.teamName } : parsed From 2c44c982f67f31d01bcccfbea3381a01c5726990 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 16:05:34 -0800 Subject: [PATCH 019/149] chore(cloud): split setup page copy; composer stays under max-lines --- .../components/NewWorkspaceComposerModal.tsx | 119 +++++++------ .../new-workspace/RunTargetCombobox.tsx | 14 +- .../run-on/use-composer-cloud-start.ts | 13 +- .../new-workspace/run-target-options.ts | 13 ++ .../orca-cloud-setup/CloudSetupPage.tsx | 161 +---------------- .../orca-cloud-setup/cloud-setup-page-copy.ts | 167 ++++++++++++++++++ 6 files changed, 250 insertions(+), 237 deletions(-) create mode 100644 src/renderer/src/components/orca-cloud-setup/cloud-setup-page-copy.ts diff --git a/src/renderer/src/components/NewWorkspaceComposerModal.tsx b/src/renderer/src/components/NewWorkspaceComposerModal.tsx index 7870613b944..2fa9c7c6e42 100644 --- a/src/renderer/src/components/NewWorkspaceComposerModal.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerModal.tsx @@ -211,69 +211,67 @@ function QuickTabBody({ [observation.contextKey, orcaCloud] ) - // `withoutAgent`: Orca Cloud with an agent that has no account there starts a plain terminal - // instead of dropping the user into the agent's /login. - const handleCreate = useCallback( - async (options?: { withoutAgent?: boolean }): Promise => { - if (createDisabled) { - return - } - const agent = options?.withoutAgent ? null : quickAgent - await submitQuick(agent, { - // Blank Terminal is the setup-only create: no agent, and no extra shell beside setup. - setupOnly: agent === null, - ...(agent === null ? {} : { launchChoice: launchSelection.choice }), - onLegacyPreparationFailure: (error) => { - if (isSubmissionCancelled()) { - return - } - const snapshot = { - ...modalData, - prefilledName: cardProps.name, - initialRepoId: cardProps.repoId, - initialBaseBranch: cardProps.baseBranch, - initialWorkspaceTarget: - cardProps.selectedProjectId && cardProps.selectedRepoExecutionHostId - ? { - projectId: cardProps.selectedProjectId, - hostId: cardProps.selectedRepoExecutionHostId, - projectHostSetupId: cardProps.selectedProjectHostSetupId ?? null - } - : modalData.initialWorkspaceTarget, - linkedWorkItem: cardProps.linkedWorkItem, - recovery: { ...quickAgentPick, agent: quickAgent, note: cardProps.note } - } - toast.error(getWorkspaceCreateErrorToastMessage(formatWorkspaceCreateError(error)), { - action: { - label: translate('auto.lib.composerCreateHandoff.reopen', 'Reopen'), - onClick: () => { - if (!isSubmissionCancelled() && useAppStore.getState().activeModal === 'none') { - useAppStore.getState().openModal('new-workspace-composer', snapshot) + // Orca Cloud with an agent that has no account there starts a plain terminal, never the agent's + // /login: the cloud hook sets this for one create. + const noAgentRef = useRef(false) + const handleCreate = useCallback(async (): Promise => { + const agent = noAgentRef.current ? null : quickAgent + noAgentRef.current = false + if (createDisabled) { + return + } + await submitQuick(agent, { + // Blank Terminal is the setup-only create: no agent, and no extra shell beside setup. + setupOnly: agent === null, + ...(agent === null ? {} : { launchChoice: launchSelection.choice }), + onLegacyPreparationFailure: (error) => { + if (isSubmissionCancelled()) { + return + } + const snapshot = { + ...modalData, + prefilledName: cardProps.name, + initialRepoId: cardProps.repoId, + initialBaseBranch: cardProps.baseBranch, + initialWorkspaceTarget: + cardProps.selectedProjectId && cardProps.selectedRepoExecutionHostId + ? { + projectId: cardProps.selectedProjectId, + hostId: cardProps.selectedRepoExecutionHostId, + projectHostSetupId: cardProps.selectedProjectHostSetupId ?? null } + : modalData.initialWorkspaceTarget, + linkedWorkItem: cardProps.linkedWorkItem, + recovery: { ...quickAgentPick, agent: quickAgent, note: cardProps.note } + } + toast.error(getWorkspaceCreateErrorToastMessage(formatWorkspaceCreateError(error)), { + action: { + label: translate('auto.lib.composerCreateHandoff.reopen', 'Reopen'), + onClick: () => { + if (!isSubmissionCancelled() && useAppStore.getState().activeModal === 'none') { + useAppStore.getState().openModal('new-workspace-composer', snapshot) } } - }) - }, - ...quickWorkspacePickerInputs( - pickerDraft, - quickAgentPick.entry, - launchSelection.choice?.executionHostId - ) - }) - }, - [ - createDisabled, - quickAgent, - launchSelection.choice, - submitQuick, - pickerDraft, - quickAgentPick, - isSubmissionCancelled, - modalData, - cardProps - ] - ) - // The composer as it is now, for Orca Cloud's setup page (Back, and the start when it's done). + } + }) + }, + ...quickWorkspacePickerInputs( + pickerDraft, + quickAgentPick.entry, + launchSelection.choice?.executionHostId + ) + }) + }, [ + createDisabled, + quickAgent, + launchSelection.choice, + submitQuick, + pickerDraft, + quickAgentPick, + isSubmissionCancelled, + modalData, + cardProps + ]) const { cloudStart, primaryCreateDisabled, onPrimary } = useComposerCloudStart({ active, modalData, @@ -282,6 +280,7 @@ function QuickTabBody({ handleCreate, createDisabled, quickAgentPick, + noAgentRef, recordCreatedRef, onClose }) diff --git a/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx b/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx index c8e7a185a1d..76a9255d73e 100644 --- a/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx @@ -16,6 +16,7 @@ import { getRunTargetFieldText, getRecipeSubmenuItemKey, getRunTargetSubmenuItemKeys, + closingFirst, getRunTargetCurrentRowKey, getRunTargetOptionId, RUN_TARGET_ADD_HOST_KEY, @@ -57,19 +58,6 @@ type RunTargetComboboxProps = { onSelectOrcaCloud?: () => void } -/** Add-host actions open dialogs, so the picker closes before they run. */ -function closingFirst( - close: () => void, - action: (() => void) | undefined -): (() => void) | undefined { - return action - ? () => { - close() - action() - } - : undefined -} - const ROOT_ATTRIBUTE = 'data-run-target-combobox-root' /** Match project-picker navigation; Connect must not select its host, and recipe/Add host rows open nested lists. */ diff --git a/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts b/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts index d275d5e4351..fd9ec93edc9 100644 --- a/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts +++ b/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts @@ -26,6 +26,7 @@ export function useComposerCloudStart({ handleCreate, createDisabled, quickAgentPick, + noAgentRef, recordCreatedRef, onClose }: { @@ -33,7 +34,9 @@ export function useComposerCloudStart({ modalData: ComposerModalData cardProps: ComposerCardState quickAgent: TuiAgent | null - handleCreate: (options?: { withoutAgent?: boolean }) => Promise + handleCreate: () => Promise + /** Set right before a create to start it with no agent. */ + noAgentRef: MutableRefObject createDisabled: boolean /** The agent pick (surface, draft) as the composer keeps it, for the setup page's snapshot. */ quickAgentPick: Omit, 'note'> @@ -44,10 +47,10 @@ export function useComposerCloudStart({ // The latest handleCreate, never a ref copied after render: a submit right after an edit must // see that edit. const runCreate = useCallback(() => void handleCreate(), [handleCreate]) - const runCreateWithoutAgent = useCallback( - () => void handleCreate({ withoutAgent: true }), - [handleCreate] - ) + const runCreateWithoutAgent = useCallback(() => { + noAgentRef.current = true + void handleCreate() + }, [handleCreate, noAgentRef]) const composerSnapshot = useCallback( () => buildComposerSnapshot(modalData, cardProps, { ...quickAgentPick, agent: quickAgent }), [cardProps, modalData, quickAgent, quickAgentPick] diff --git a/src/renderer/src/components/new-workspace/run-target-options.ts b/src/renderer/src/components/new-workspace/run-target-options.ts index 9ed7fe869a5..c484b9d4b5c 100644 --- a/src/renderer/src/components/new-workspace/run-target-options.ts +++ b/src/renderer/src/components/new-workspace/run-target-options.ts @@ -308,3 +308,16 @@ export function buildRunTargetRows( ] return { rows, matchedRecipes, hiddenHostCount: hostRows.hiddenHostCount } } + +/** Add-host actions open dialogs, so the picker closes before they run. */ +export function closingFirst( + close: () => void, + action: (() => void) | undefined +): (() => void) | undefined { + return action + ? () => { + close() + action() + } + : undefined +} diff --git a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx index 21badae9365..e08c5f8bb49 100644 --- a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx +++ b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx @@ -7,10 +7,10 @@ import { ArrowLeft, Check, Cloud, Copy, ExternalLink, LoaderCircle } from 'lucid import { Button } from '@/components/ui/button' import { Skeleton } from '@/components/ui/skeleton' import { cn } from '@/lib/utils' -import { useTranslate, type Translate } from '@/i18n/use-translate' +import { useTranslate } from '@/i18n/use-translate' import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model' import { CloudSetupErrorNotice } from '@/components/new-workspace/cloud-setup/CloudSetupErrorNotice' -import { sessionDetailCopy } from '@/components/new-workspace/run-on/cloud-setup-session-copy' +import { currentStepCopy, stepLabel } from './cloud-setup-page-copy' import type { CloudSetupFlow } from './use-cloud-setup-flow' import { openOrcaCloudAgentAccounts } from '@/components/new-workspace/OrcaCloudAgentSetupRow' @@ -25,23 +25,6 @@ export type CloudSetupPageProps = { starting: boolean } -function stepLabel(step: CloudSetupStep, t: Translate): string { - switch (step.id) { - case 'account': - return t('cloudSetupPage.step.account', 'Account') - case 'team': - return t('cloudSetupPage.step.team', 'Team') - case 'plan': - return step.need === 'trial' - ? t('cloudSetupPage.step.trial', 'Trial') - : t('cloudSetupPage.step.plan', 'Plan') - case 'github': - return t('cloudSetupPage.step.github', 'GitHub') - case 'agent': - return t('cloudSetupPage.step.agent', 'Agent') - } -} - type StepState = 'done' | 'current' | 'todo' function SetupStepper({ @@ -103,146 +86,6 @@ function SetupStepper({ ) } -type StepCopy = { title: string; lead: string | null; note?: string | null } - -function trialHours(step: CloudSetupStep): string | null { - return step.trialSeconds ? String(Math.round((step.trialSeconds / 3600) * 10) / 10) : null -} - -function currentStepCopy(flow: CloudSetupFlow, t: Translate, agentLabel: string | null): StepCopy { - const step = flow.current - const detail = step - ? ((sessionDetailCopy(step, t) === undefined ? step.detail : sessionDetailCopy(step, t)) ?? - null) - : null - switch (flow.action) { - case 'sign-in': - return { - title: t('cloudSetupPage.signIn.title', 'Sign in to Orca'), - lead: t( - 'cloudSetupPage.signIn.lead', - 'Orca Cloud runs your agents in a cloud workspace, so they keep going with your laptop closed. Sign in or create an account in your browser. We’ll make a team for you.' - ), - note: t( - 'cloudSetupPage.signIn.note', - 'New teams get a trial with no card needed. This page picks up each step on its own.' - ) - } - case 'start-trial': { - const hours = step ? trialHours(step) : null - return { - title: t('cloudSetupPage.trial.title', 'Start your free trial'), - lead: - hours === null - ? t('cloudSetupPage.trial.leadNoHours', 'Try Orca Cloud on your team. No card needed.') - : t( - 'cloudSetupPage.trial.lead', - '{{hours}} sandbox hours to try Orca Cloud. No card needed.', - { - hours - } - ), - note: t('cloudSetupPage.trial.note', 'Nothing is charged until you choose a plan.') - } - } - case 'choose-plan': - return step?.need === 'trial-used-up' - ? { - title: t('cloudSetupPage.plan.trialUsedUpTitle', 'Your trial is used up'), - lead: t( - 'cloudSetupPage.plan.trialUsedUpLead', - 'Choose a Team plan to keep using Orca Cloud. Checkout opens in your browser.' - ) - } - : step?.need === 'renew-plan' - ? { - title: t('cloudSetupPage.plan.renewTitle', 'Renew your Team plan'), - lead: t( - 'cloudSetupPage.plan.renewLead', - 'Your Team plan ended. Renew it in your browser to start this workspace.' - ) - } - : { - title: t('cloudSetupPage.plan.title', 'Choose a Team plan'), - lead: t( - 'cloudSetupPage.plan.lead', - 'Orca Cloud needs a Team plan. Checkout opens in your browser.' - ) - } - case 'fix-billing': - return { - title: - step?.need === 'payment' - ? t('cloudSetupPage.billing.paymentTitle', 'Update your payment method') - : step?.need === 'spend-cap' - ? t('cloudSetupPage.billing.capTitle', 'Spend cap reached') - : t('cloudSetupPage.billing.hoursTitle', 'Out of sandbox hours'), - lead: - step?.need === 'payment' - ? t( - 'cloudSetupPage.billing.paymentLead', - 'The last payment failed. Update the card to keep going.' - ) - : step?.need === 'spend-cap' - ? t('cloudSetupPage.billing.capLead', 'Raise the spend cap to start this workspace.') - : t('cloudSetupPage.billing.hoursLead', 'Turn on overage to start this workspace.') - } - case 'switch-team': - return { title: t('cloudSetupPage.team.title', 'Switch to your team'), lead: detail } - case 'github-install': - return { - title: t('cloudSetupPage.github.title', 'Give Orca Cloud access on GitHub'), - lead: t( - 'cloudSetupPage.github.lead', - 'Orca Cloud clones your code from GitHub. Install the Orca Cloud app on this repository once.' - ), - note: step?.note ?? null - } - case 'github-waiting': - return { - title: t('cloudSetupPage.github.waitingTitle', 'Waiting for approval on GitHub'), - lead: detail, - note: step?.note ?? null - } - case 'needs-repository': - return { - title: t('cloudSetupPage.repository.title', 'Orca Cloud needs a GitHub repository'), - lead: detail, - note: step?.note ?? null - } - case 'ask-owner': - return { - title: t('cloudSetupPage.owner.title', 'An owner or admin needs to fix this'), - lead: - detail ?? - t( - 'cloudSetupPage.owner.lead', - 'Orca Cloud needs a Team plan. Only owners and admins can choose one.' - ) - } - case 'agent': - return { - title: agentLabel - ? t('cloudSetupPage.agent.title', 'Sign in to {{agent}} once', { agent: agentLabel }) - : t('cloudSetupPage.agent.titleGeneric', 'Sign in to your agent once'), - lead: t( - 'cloudSetupPage.agent.lead', - 'Save your agent sign-in to your Orca account and every cloud workspace uses it. You can also skip this and sign in inside the workspace.' - ) - } - case 'checking': - return { - title: t('cloudSetupPage.checking.title', 'Checking your Orca Cloud account…'), - lead: null - } - case 'done': - return { - title: t('cloudSetupPage.done.title', 'All set'), - lead: t('cloudSetupPage.done.lead', 'Starting your cloud workspace…') - } - } -} - function BrowserWaiting({ flow }: { flow: CloudSetupFlow }): React.JSX.Element { const t = useTranslate() return ( diff --git a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-copy.ts b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-copy.ts new file mode 100644 index 00000000000..c55189512f1 --- /dev/null +++ b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-copy.ts @@ -0,0 +1,167 @@ +// Words for the Orca Cloud setup page: each step's stepper label, and the current step's title, +// lead and note. Copy follows the product glossary (Orca Cloud, sandbox hours, Team plan). +import type { Translate } from '@/i18n/use-translate' +import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model' +import { sessionDetailCopy } from '@/components/new-workspace/run-on/cloud-setup-session-copy' +import type { CloudSetupPageModel } from './cloud-setup-page-model' + +export function stepLabel(step: CloudSetupStep, t: Translate): string { + switch (step.id) { + case 'account': + return t('cloudSetupPage.step.account', 'Account') + case 'team': + return t('cloudSetupPage.step.team', 'Team') + case 'plan': + return step.need === 'trial' + ? t('cloudSetupPage.step.trial', 'Trial') + : t('cloudSetupPage.step.plan', 'Plan') + case 'github': + return t('cloudSetupPage.step.github', 'GitHub') + case 'agent': + return t('cloudSetupPage.step.agent', 'Agent') + } +} + +type StepCopy = { title: string; lead: string | null; note?: string | null } + +function trialHours(step: CloudSetupStep): string | null { + return step.trialSeconds ? String(Math.round((step.trialSeconds / 3600) * 10) / 10) : null +} + +export function currentStepCopy( + flow: Pick, + t: Translate, + agentLabel: string | null +): StepCopy { + const step = flow.current + const detail = step + ? ((sessionDetailCopy(step, t) === undefined ? step.detail : sessionDetailCopy(step, t)) ?? + null) + : null + switch (flow.action) { + case 'sign-in': + return { + title: t('cloudSetupPage.signIn.title', 'Sign in to Orca'), + lead: t( + 'cloudSetupPage.signIn.lead', + 'Orca Cloud runs your agents in a cloud workspace, so they keep going with your laptop closed. Sign in or create an account in your browser. We’ll make a team for you.' + ), + note: t( + 'cloudSetupPage.signIn.note', + 'New teams get a trial with no card needed. This page picks up each step on its own.' + ) + } + case 'start-trial': { + const hours = step ? trialHours(step) : null + return { + title: t('cloudSetupPage.trial.title', 'Start your free trial'), + lead: + hours === null + ? t('cloudSetupPage.trial.leadNoHours', 'Try Orca Cloud on your team. No card needed.') + : t( + 'cloudSetupPage.trial.lead', + '{{hours}} sandbox hours to try Orca Cloud. No card needed.', + { + hours + } + ), + note: t('cloudSetupPage.trial.note', 'Nothing is charged until you choose a plan.') + } + } + case 'choose-plan': + return step?.need === 'trial-used-up' + ? { + title: t('cloudSetupPage.plan.trialUsedUpTitle', 'Your trial is used up'), + lead: t( + 'cloudSetupPage.plan.trialUsedUpLead', + 'Choose a Team plan to keep using Orca Cloud. Checkout opens in your browser.' + ) + } + : step?.need === 'renew-plan' + ? { + title: t('cloudSetupPage.plan.renewTitle', 'Renew your Team plan'), + lead: t( + 'cloudSetupPage.plan.renewLead', + 'Your Team plan ended. Renew it in your browser to start this workspace.' + ) + } + : { + title: t('cloudSetupPage.plan.title', 'Choose a Team plan'), + lead: t( + 'cloudSetupPage.plan.lead', + 'Orca Cloud needs a Team plan. Checkout opens in your browser.' + ) + } + case 'fix-billing': + return { + title: + step?.need === 'payment' + ? t('cloudSetupPage.billing.paymentTitle', 'Update your payment method') + : step?.need === 'spend-cap' + ? t('cloudSetupPage.billing.capTitle', 'Spend cap reached') + : t('cloudSetupPage.billing.hoursTitle', 'Out of sandbox hours'), + lead: + step?.need === 'payment' + ? t( + 'cloudSetupPage.billing.paymentLead', + 'The last payment failed. Update the card to keep going.' + ) + : step?.need === 'spend-cap' + ? t('cloudSetupPage.billing.capLead', 'Raise the spend cap to start this workspace.') + : t('cloudSetupPage.billing.hoursLead', 'Turn on overage to start this workspace.') + } + case 'switch-team': + return { title: t('cloudSetupPage.team.title', 'Switch to your team'), lead: detail } + case 'github-install': + return { + title: t('cloudSetupPage.github.title', 'Give Orca Cloud access on GitHub'), + lead: t( + 'cloudSetupPage.github.lead', + 'Orca Cloud clones your code from GitHub. Install the Orca Cloud app on this repository once.' + ), + note: step?.note ?? null + } + case 'github-waiting': + return { + title: t('cloudSetupPage.github.waitingTitle', 'Waiting for approval on GitHub'), + lead: detail, + note: step?.note ?? null + } + case 'needs-repository': + return { + title: t('cloudSetupPage.repository.title', 'Orca Cloud needs a GitHub repository'), + lead: detail, + note: step?.note ?? null + } + case 'ask-owner': + return { + title: t('cloudSetupPage.owner.title', 'An owner or admin needs to fix this'), + lead: + detail ?? + t( + 'cloudSetupPage.owner.lead', + 'Orca Cloud needs a Team plan. Only owners and admins can choose one.' + ) + } + case 'agent': + return { + title: agentLabel + ? t('cloudSetupPage.agent.title', 'Sign in to {{agent}} once', { agent: agentLabel }) + : t('cloudSetupPage.agent.titleGeneric', 'Sign in to your agent once'), + lead: t( + 'cloudSetupPage.agent.lead', + 'Save your agent sign-in to your Orca account and every cloud workspace uses it. You can also skip this and sign in inside the workspace.' + ) + } + case 'checking': + return { + title: t('cloudSetupPage.checking.title', 'Checking your Orca Cloud account…'), + lead: null + } + case 'done': + return { + title: t('cloudSetupPage.done.title', 'All set'), + lead: t('cloudSetupPage.done.lead', 'Starting your cloud workspace…') + } + } +} From 7901ef3123e69af99cf38eaf33a6d2882ac589a6 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 16:27:04 -0800 Subject: [PATCH 020/149] chore(cloud): localization catalog and visibility-aware polling for the setup page --- .../components/NewWorkspaceComposerModal.tsx | 11 +- .../cloud-setup-tracker-actions.ts | 2 +- .../orca-cloud-setup/use-cloud-setup-flow.ts | 12 +- .../src/i18n/en-runtime-required.json | 2 - src/renderer/src/i18n/locales/en.json | 166 ++++++++++-------- 5 files changed, 105 insertions(+), 88 deletions(-) diff --git a/src/renderer/src/components/NewWorkspaceComposerModal.tsx b/src/renderer/src/components/NewWorkspaceComposerModal.tsx index 2fa9c7c6e42..2a03e374a04 100644 --- a/src/renderer/src/components/NewWorkspaceComposerModal.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerModal.tsx @@ -82,16 +82,16 @@ function ComposerModalBody({ }, [onClose]) const isSubmissionCancelled = useCallback(() => submitCancelledRef.current, []) const visibleModalData = useCloudAutoStartReveal(modalData) - const body = (data: ComposerModalData): React.JSX.Element => ( + const body = ( ) if (!visibleModalData) { - return {body(modalData)} + return {body} } return ( @@ -111,7 +111,7 @@ function ComposerModalBody({ getWorkspaceComposerInitialFocusTarget(content)?.focus({ preventScroll: true }) }} > - {body(visibleModalData)} + {body} ) @@ -212,11 +212,10 @@ function QuickTabBody({ ) // Orca Cloud with an agent that has no account there starts a plain terminal, never the agent's - // /login: the cloud hook sets this for one create. + // /login: the cloud hook sets this around one create (read before the first await). const noAgentRef = useRef(false) const handleCreate = useCallback(async (): Promise => { const agent = noAgentRef.current ? null : quickAgent - noAgentRef.current = false if (createDisabled) { return } diff --git a/src/renderer/src/components/new-workspace/cloud-setup/cloud-setup-tracker-actions.ts b/src/renderer/src/components/new-workspace/cloud-setup/cloud-setup-tracker-actions.ts index fec4b5f528e..07bbbdeb2a9 100644 --- a/src/renderer/src/components/new-workspace/cloud-setup/cloud-setup-tracker-actions.ts +++ b/src/renderer/src/components/new-workspace/cloud-setup/cloud-setup-tracker-actions.ts @@ -20,7 +20,7 @@ async function freshLink(sessionId: string): Promise { function linkUnavailable(): void { toast.error( translate( - 'components.newWorkspace.cloudSetup.linkUnavailable', + 'components.newWorkspace.cloudSetup.linkUnavailableRetry', 'Couldn’t get a setup link. Try Continue in browser again.' ) ) diff --git a/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts b/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts index c2496997546..22184d6fa52 100644 --- a/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts +++ b/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts @@ -26,6 +26,7 @@ import { type CloudSetupPageRequest } from '@/lib/orca-cloud/cloud-setup-page-store' import { reportCloudSetupProgress } from '@/lib/orca-cloud/cloud-setup-telemetry' +import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' import type { OrcaCloudAvailability } from '../../../../shared/orca-yaml-hook-types' import type { OrcaCloudRunTargetAccess } from '@/components/new-workspace/orca-cloud-run-target-access' import { @@ -64,11 +65,12 @@ function useLiveAvailability( .catch(() => undefined) } read() - const timer = window.setInterval(read, BILLING_POLL_MS) + // Paused while the window is hidden; returning from the browser re-reads at once. + const stop = installWindowVisibilityInterval({ run: read, intervalMs: BILLING_POLL_MS }) window.addEventListener('focus', read) return () => { cancelled = true - window.clearInterval(timer) + stop() window.removeEventListener('focus', read) } }, [enabled, repoId]) @@ -135,8 +137,10 @@ export function useCloudSetupFlow( if (!waiting || accessOverride) { return } - const timer = window.setInterval(() => void prefetchOrcaCloudBilling(true), BILLING_POLL_MS) - return () => window.clearInterval(timer) + return installWindowVisibilityInterval({ + run: () => void prefetchOrcaCloudBilling(true), + intervalMs: BILLING_POLL_MS + }) }, [accessOverride, waiting]) useEffect(() => { diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 57070f86d45..a4d9fda75d5 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -415,8 +415,6 @@ "new": { "workspace": { "RunTargetCombobox": { - "orcaCloudIdleSleep_one": "Sleeps after {{count}} minute idle", - "orcaCloudIdleSleep_other": "Sleeps after {{count}} minutes idle", "orcaCloudSandboxHoursLeft_one": "{{hours}} sandbox hour left", "orcaCloudSandboxHoursLeft_other": "{{hours}} sandbox hours left" } diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index cd109e0d6fe..6f4de180e00 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -16715,20 +16715,12 @@ "currentSuffix": "(current)", "orcaCloudSignInDetail": "Sign in to start a sandbox", "orcaCloudChecking": "Checking your plan…", - "orcaCloudNeedsTeamPlan": "Orca Cloud needs a Team plan.", "orcaCloudOutOfHours": "Out of sandbox hours", "orcaCloudRaiseSpendCap": "Raise spend cap", - "orcaCloudPaymentEffect": "New sandboxes can't start.", "orcaCloudUpdatePaymentMethod": "Update payment method", "orcaCloudSandboxHoursLeft_one": "{{hours}} sandbox hour left", "orcaCloudSandboxHoursLeft_other": "{{hours}} sandbox hours left", "orcaCloudAskOwnerOrAdmin": "Ask an owner or admin", - "orcaCloudAskPayment": "Ask an owner or admin to update the payment method.", - "orcaCloudIdleSleep_one": "Sleeps after {{count}} minute idle", - "orcaCloudIdleSleep_other": "Sleeps after {{count}} minutes idle", - "orcaCloudAskAddHoursOnly": "Ask an owner or admin to add hours.", - "orcaCloudAskChoosePlan": "Ask an owner or admin to choose one.", - "orcaCloudAskRaiseSpendCap": "Ask an owner or admin to raise the spend cap.", "hintConnect": "{{host}}, not connected. Press Enter to connect.", "hintSetLocation": "{{host}}, project location not set. Press Enter to set it.", "hintSignIn": "Orca Cloud, signed out. Press Enter to sign in.", @@ -23099,68 +23091,15 @@ "bothSources": "orca.yaml + local", "localSource": "local settings" }, - "cloudStart": { - "useThisComputer": "Use this computer instead", - "start": "Start in Orca Cloud", - "setUpAndStart": "Set up and start", - "choosePlanAndStart": "Choose plan and start", - "renewAndStart": "Renew and start", - "giveAccessAndStart": "Give access and start", - "checking": "Checking Orca Cloud…", - "githubGranted": "GitHub access granted for {{repo}}" - }, "cloudSetup": { - "account": "Orca account", - "team": "Team", - "plan": "Team plan", - "github": "GitHub access", - "githubNeeded": "Orca Cloud clones your code from GitHub. Give access to this repository once.", - "agent": "Agent", - "planAfterSignIn": "Checked after you sign in", - "askOwner": "Ask an owner or admin to fix it.", - "planEnded": "Your Team plan ended.", - "outOfHours": "Out of sandbox hours.", - "spendCap": "Spend cap reached.", - "paymentFailed": "Payment failed.", - "planMember": "Orca Cloud needs a Team plan. Only owners and admins can choose one.", - "planNeeded": "Orca Cloud needs a Team plan.", - "stateDone": "Done", - "stateOptional": "Optional", - "stateNext": "Next", - "stateInBrowser": "In browser", - "stateFailed": "Didn't finish", - "stateChecking": "Checking", - "stateNeeded": "Needed", - "allSet": "All set", - "title": "Set up Orca Cloud", - "starting": "Starting your cloud workspace…", - "accountNeededTeam": "Sign in or create one. We’ll make a team for you.", - "trial": "Trial", - "trialNoCard": "No card needed. Nothing is charged until you choose a plan.", - "stateIncluded": "Included", - "trialUsedUp": "Your trial is used up.", - "trialUsedUpMember": "Only owners and admins can choose a plan.", - "trialUsedUpOwner": "Choose a plan to keep using Orca Cloud. Your prompt is still here.", - "subtitleNoCard": "One visit to your browser, no card. Your prompt stays here and starts when you’re done.", "trialUsedUpTitle": "Your trial is used up", "choosePlan": "Choose plan", "askChoosePlan": "Ask an owner or admin to choose a plan.", - "trialUsedUpChoose": "Choose a plan to keep using Orca Cloud.", "trialOffer_one": "{{hours}} sandbox hour to try Orca Cloud", "trialOffer_other": "{{hours}} sandbox hours to try Orca Cloud", - "subtitleChoosePlan": "One visit to your browser to choose a plan. Your prompt stays here and starts when you’re done.", - "subtitleNeedsRepository": "Orca Cloud needs a GitHub repository. Your prompt stays here.", - "outOfHoursMember": "Out of sandbox hours. Ask an owner or admin to add hours.", - "spendCapMember": "Spend cap reached. Ask an owner or admin to raise the spend cap.", - "paymentFailedMember": "Payment failed. Ask an owner or admin to update the payment method.", - "subtitleOwnerFixes": "An owner or admin needs to fix this. Your prompt stays here.", - "cancelSetup": "Cancel setup", - "copySetupLink": "Copy setup link", "reopenBrowser": "Reopen browser", "tryAgain": "Try again", "switchAccount": "Switch account", - "trackerTitle": "Finish in your browser", - "trackerSubtitle": "Orca picks up each step the moment it’s done, then starts this workspace.", "teamRequired": "Cloud workspaces belong to a team.", "teamHasPlan": "{{team}} has a Team plan. Switch to start this workspace there.", "teamsHavePlans": "{{teams}} have a Team plan. Switch to one to start this workspace there.", @@ -23168,7 +23107,6 @@ "switchTeam": "Switch team", "switchFirst": "Switch to {{team}} first", "switchTeamFirst": "Switch to a team first", - "linkUnavailable": "Couldn’t get a setup link. Try Set up and start again.", "linkCopied": "Setup link copied. Open it in the browser you use for Orca.", "error": { "timedOut": "Setup didn’t finish in your browser. Your prompt is still here.", @@ -23183,18 +23121,11 @@ "planCoveredByTrial": "Your trial covers it.", "planCheckoutOpen": "Finish checkout in your browser.", "githubRequestedSession": "Waiting for an owner on GitHub to approve Orca Cloud.", - "subtitleChoosePlanAndGitHub": "One visit to your browser to choose a plan and give Orca Cloud access on GitHub. Your prompt stays here and starts when you’re done." + "linkUnavailableRetry": "Couldn’t get a setup link. Try Continue in browser again." }, "runOn": { "thisComputer": "This computer", - "orcaCloud": "Orca Cloud", - "moreWithTarget": "More places to run: {{name}}", - "more": "More places to run", - "cloudUnreachableReason": "Orca Cloud: can't reach it right now. Check your connection.", - "thisComputerUnusable": "This computer, {{reason}}", - "locationNotSet": "Project location not set", - "cloudUnreachableName": "Orca Cloud, can't reach it right now", - "cloudHosted": "Hosted sandbox" + "orcaCloud": "Orca Cloud" }, "cloudHours": { "trialChip_one": "Trial · {{hours}} sandbox hour left", @@ -23218,18 +23149,21 @@ "heading": "On GitHub · Orca Cloud only", "detail": "Orca Cloud clones it. No copy on this computer needed.", "moreAccess": "Give Orca Cloud access to more repositories…", - "notOnThisComputer": "Not on this computer · Orca Cloud only", "startFailed": "Couldn’t start the cloud workspace. Nothing was created, and you weren’t charged.", "starting": "Starting {{repo}} in Orca Cloud…", "openLater": "Your cloud workspace started, but this computer couldn’t open it yet. Open it from Cloud workspaces.", "private": "{{owner}} · Private", "public": "{{owner}} · Public", "showMore": "Show more repositories…", - "chooseRepository": "Choose a GitHub repository", - "addGitHubProject": "Add a GitHub project…", "folderDetail": "Orca Cloud starts from a GitHub repository. This project is a folder on this computer." }, - "orcaCloudAgentFallback": "{{agent}} isn’t available on Orca Cloud yet, so {{fallback}} is selected." + "orcaCloudAgentFallback": "{{agent}} isn’t available on Orca Cloud yet, so {{fallback}} is selected.", + "cloudStart": { + "agentNotStarted": "{{agent}} isn’t set up for Orca Cloud, so it didn’t start. The workspace has a terminal.", + "agentNotStartedGeneric": "Your agent isn’t set up for Orca Cloud, so it didn’t start. The workspace has a terminal.", + "setUpAgentOnce": "Set up {{agent}} once", + "setUpAgentOnceGeneric": "Set up once" + } }, "JiraIssueWorkspace": { "pendingChange": "Another issue change is in progress." @@ -28064,5 +27998,87 @@ "signInHere": "{{agent}} isn’t signed in for this workspace.", "pausedFix": "Orca account sign-in is paused. Sign in for this workspace; the sign-in stays with this workspace.", "notOfferedFix": "Signs in for each cloud workspace for now. Sign in for this workspace; the sign-in stays with this workspace." + }, + "cloudSetupPage": { + "agent": { + "lead": "Save your agent sign-in to your Orca account and every cloud workspace uses it. You can also skip this and sign in inside the workspace.", + "setUp": "Set up once", + "skip": "Skip for now", + "title": "Sign in to {{agent}} once", + "titleGeneric": "Sign in to your agent once" + }, + "back": "Back", + "billing": { + "capLead": "Raise the spend cap to start this workspace.", + "capTitle": "Spend cap reached", + "hoursLead": "Turn on overage to start this workspace.", + "hoursTitle": "Out of sandbox hours", + "paymentLead": "The last payment failed. Update the card to keep going.", + "paymentTitle": "Update your payment method" + }, + "checkAgain": "Check again", + "checking": { + "title": "Checking your Orca Cloud account…" + }, + "continueInBrowser": "Continue in browser", + "copyLink": "Copy link", + "done": { + "lead": "Starting your cloud workspace…", + "title": "All set" + }, + "eyebrow": "Orca Cloud setup", + "github": { + "lead": "Orca Cloud clones your code from GitHub. Install the Orca Cloud app on this repository once.", + "title": "Give Orca Cloud access on GitHub", + "waiting": "This page starts the workspace once they approve.", + "waitingTitle": "Waiting for approval on GitHub" + }, + "orcaCloud": "Orca Cloud", + "owner": { + "lead": "Orca Cloud needs a Team plan. Only owners and admins can choose one.", + "title": "An owner or admin needs to fix this" + }, + "plan": { + "lead": "Orca Cloud needs a Team plan. Checkout opens in your browser.", + "renewLead": "Your Team plan ended. Renew it in your browser to start this workspace.", + "renewTitle": "Renew your Team plan", + "title": "Choose a Team plan", + "trialUsedUpLead": "Choose a Team plan to keep using Orca Cloud. Checkout opens in your browser.", + "trialUsedUpTitle": "Your trial is used up" + }, + "reopenBrowser": "Reopen browser", + "repository": { + "title": "Orca Cloud needs a GitHub repository" + }, + "signIn": { + "lead": "Orca Cloud runs your agents in a cloud workspace, so they keep going with your laptop closed. Sign in or create an account in your browser. We’ll make a team for you.", + "note": "New teams get a trial with no card needed. This page picks up each step on its own.", + "title": "Sign in to Orca" + }, + "starting": "Starting…", + "startsAfter": "Starts when setup is done", + "step": { + "account": "Account", + "agent": "Agent", + "github": "GitHub", + "plan": "Plan", + "team": "Team", + "trial": "Trial" + }, + "stepCurrent": "current step", + "stepDone": "done", + "stepsLabel": "Setup steps", + "team": { + "title": "Switch to your team" + }, + "trial": { + "lead": "{{hours}} sandbox hours to try Orca Cloud. No card needed.", + "leadNoHours": "Try Orca Cloud on your team. No card needed.", + "note": "Nothing is charged until you choose a plan.", + "start": "Start free trial", + "title": "Start your free trial" + }, + "untitled": "New cloud workspace", + "waitingBrowser": "Waiting for your browser…" } } From 3438a5d6effc7222a21a81b60d9b1558f5cb9bdf Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 16:33:39 -0800 Subject: [PATCH 021/149] fix(cloud): setup page waits for every row to settle before it starts --- .../run-on/cloud-start-model.test.ts | 1 - .../orca-cloud-setup/CloudSetupPage.tsx | 20 ++++++++++--------- .../orca-cloud-setup/CloudSetupPageLayer.tsx | 20 ++++++++++++++----- .../cloud-setup-page-model.test.ts | 11 ++++++++++ .../cloud-setup-page-model.ts | 4 ++-- 5 files changed, 39 insertions(+), 17 deletions(-) diff --git a/src/renderer/src/components/new-workspace/run-on/cloud-start-model.test.ts b/src/renderer/src/components/new-workspace/run-on/cloud-start-model.test.ts index a5b5af7fc16..7cb5e31ca4b 100644 --- a/src/renderer/src/components/new-workspace/run-on/cloud-start-model.test.ts +++ b/src/renderer/src/components/new-workspace/run-on/cloud-start-model.test.ts @@ -189,7 +189,6 @@ describe('setup rows and the setup page', () => { { id: 'agent', state: 'loading' } ] expect(cloudSetupRequired(steps)).toBe(false) - expect(cloudSetupPageModel(steps).action).toBe('done') }) }) diff --git a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx index e08c5f8bb49..4c69699f7d6 100644 --- a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx +++ b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx @@ -202,9 +202,15 @@ export function CloudSetupPage({ const t = useTranslate() const titleId = React.useId() const headingRef = React.useRef(null) - const copy = currentStepCopy(starting ? { ...flow, action: 'done' } : flow, t, agentLabel) + // Every row reads done but hasn't held yet: still "Checking" until the layer says it's starting. + const shown: CloudSetupFlow = starting + ? { ...flow, action: 'done' } + : flow.action === 'done' + ? { ...flow, action: 'checking' } + : flow + const copy = currentStepCopy(shown, t, agentLabel) // Each new step moves focus to its heading so screen readers hear the change once. - const stepKey = starting ? 'done' : `${flow.current?.id ?? 'done'}:${flow.action}` + const stepKey = `${shown.current?.id ?? 'done'}:${shown.action}` React.useEffect(() => { headingRef.current?.focus({ preventScroll: true }) }, [stepKey]) @@ -227,11 +233,7 @@ export function CloudSetupPage({
- +
@@ -243,7 +245,7 @@ export function CloudSetupPage({ > {copy.title} - {flow.action === 'checking' && !starting ? ( + {shown.action === 'checking' ? ( ) : copy.lead ? (

{copy.lead}

@@ -263,7 +265,7 @@ export function CloudSetupPage({ ) : null}
- +
diff --git a/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx b/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx index 29603aa6f9a..7ce5e9950ff 100644 --- a/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx +++ b/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx @@ -17,6 +17,9 @@ import { prefersReducedMotion } from '@/components/new-workspace/run-on/cloud-st import { CloudSetupPage } from './CloudSetupPage' import { useCloudSetupFlow } from './use-cloud-setup-flow' +/** How long every row must read done before the page starts the workspace. */ +const SETTLE_MS = 1_500 + function reopenComposer(request: CloudSetupPageRequest, autoStart: boolean): void { closeCloudSetupPage() useAppStore.getState().openModal('new-workspace-composer', { @@ -35,19 +38,26 @@ function ActiveCloudSetupPage({ request }: { request: CloudSetupPageRequest }): ) const agentLabel = isOrcaCloudAccountAgent(request.agent) ? agentName(request.agent, t) : null const [starting, setStarting] = useState(false) - const startedRef = useRef(false) + // Rows can all read done for a moment right after a sign-in, before billing, GitHub and agent + // accounts answer for the new account. Done must hold for SETTLE_MS before "All set". + const done = flow.action === 'done' useEffect(() => { - if (flow.action !== 'done' || startedRef.current) { + if (!done) { + return + } + const timer = window.setTimeout(() => setStarting(true), SETTLE_MS) + return () => window.clearTimeout(timer) + }, [done]) + useEffect(() => { + if (!starting) { return } - startedRef.current = true - setStarting(true) const timer = window.setTimeout( () => reopenComposer(request, true), prefersReducedMotion() ? 0 : CLOUD_SETUP_ALL_SET_HOLD_MS ) return () => window.clearTimeout(timer) - }, [flow.action, request]) + }, [request, starting]) const onBack = useCallback(() => reopenComposer(request, false), [request]) return ( { expect(actionForStep({ id: 'github', state: 'loading' })).toBe('checking') }) }) + +describe('page settles before it starts', () => { + it('a still-loading agent row reads Checking, not All set', () => { + const steps: CloudSetupStep[] = [ + { id: 'account', state: 'done' }, + { id: 'plan', state: 'done' }, + { id: 'agent', state: 'loading' } + ] + expect(cloudSetupPageModel(steps).action).toBe('checking') + }) +}) diff --git a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.ts b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.ts index 528ebbecce4..ca7c8884e5f 100644 --- a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.ts +++ b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.ts @@ -40,8 +40,8 @@ function isFinished(step: CloudSetupStep, agentSkipped: boolean): boolean { return true } if (step.id === 'agent') { - // Never wait on a slow agent-accounts read: it doesn't block a start. - return agentSkipped || step.state === 'loading' + // Still loading reads "Checking": the page only says All set once every row has answered. + return agentSkipped && step.state !== 'loading' } return false } From 8bc169abf3883abe001d38239b2481bce8a114d9 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 16:38:35 -0800 Subject: [PATCH 022/149] fix(cloud): a single browser hop only waits on its own step --- .../orca-cloud-setup/use-cloud-setup-flow.ts | 27 ++++++++++++------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts b/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts index 22184d6fa52..165dbd03b21 100644 --- a/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts +++ b/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts @@ -104,7 +104,9 @@ export function useCloudSetupFlow( const access = accessOverride ?? fetched const availability = useLiveAvailability(request.repoId, request.availability, !accessOverride) const [sessionId, setSessionId] = useState(null) - const [inBrowser, setInBrowser] = useState(false) + // The step that was current when the browser opened. A setup session covers every step it was + // opened for, so it waits on all of them; a single hop (GitHub install, billing) only on its own. + const [browserStep, setBrowserStep] = useState(null) const [busy, setBusy] = useState(false) const [agentSkipped, setAgentSkipped] = useState(() => isCloudSetupAgentSkipped(request.agent)) const githubOverride = useMemo( @@ -154,6 +156,11 @@ export function useCloudSetupFlow( stepsRef.current = steps }, [steps]) + const markInBrowser = useCallback( + () => setBrowserStep(cloudSetupPageModel(stepsRef.current).current?.id ?? null), + [] + ) + const fallback = useCallback( () => setupActionFor(stepsRef.current, access, availability)?.(), [access, availability] @@ -163,20 +170,20 @@ export function useCloudSetupFlow( const continueInBrowser = useCallback(() => { const needs = sessionNeedsFrom(stepsRef.current) if (needs.length > 0 && needs.every((need) => need === 'github')) { - setInBrowser(true) + markInBrowser() void openInstall() return } const start = getCloudSetupStarter() if (!start) { - setInBrowser(true) + markInBrowser() fallback() return } setBusy(true) void start({ repoId: request.repoId, needs }) .then((opened) => { - setInBrowser(true) + markInBrowser() if (opened) { setSessionId(opened.sessionId) } else { @@ -185,7 +192,7 @@ export function useCloudSetupFlow( }) .catch(() => fallback()) .finally(() => setBusy(false)) - }, [fallback, openInstall, request.repoId]) + }, [fallback, markInBrowser, openInstall, request.repoId]) const startTrial = useCallback(() => { setBusy(true) @@ -200,15 +207,15 @@ export function useCloudSetupFlow( }, [continueInBrowser]) const fixBilling = useCallback(() => { - setInBrowser(true) + markInBrowser() invalidateOrcaCloudBilling({ refetchNow: false }) fallback() - }, [fallback]) + }, [fallback, markInBrowser]) const installGitHub = useCallback(() => { - setInBrowser(true) + markInBrowser() void openInstall() - }, [openInstall]) + }, [markInBrowser, openInstall]) const skipAgent = useCallback(() => { rememberCloudSetupAgentSkipped(request.agent) @@ -220,7 +227,7 @@ export function useCloudSetupFlow( return { ...model, busy, - inBrowser, + inBrowser: browserStep !== null && (sessionId !== null || model.current?.id === browserStep), error, canManageBilling: access.state === 'no-plan' ? access.canManageBilling : true, teamAction: switchTeam?.action ?? null, From dbf554e89b3e50b5eaab31b3e608863d4b86f675 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 16:45:14 -0800 Subject: [PATCH 023/149] chore(cloud): dev hook to walk the setup page; GitHub step names the repository --- .../orca-cloud-setup/CloudSetupPageLayer.tsx | 2 +- .../orca-cloud-setup/cloud-setup-page-copy.ts | 7 ++++--- .../src/lib/orca-cloud/cloud-setup-page-store.ts | 16 ++++++++++++++++ 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx b/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx index 7ce5e9950ff..4150d6f71f9 100644 --- a/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx +++ b/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx @@ -32,7 +32,7 @@ function reopenComposer(request: CloudSetupPageRequest, autoStart: boolean): voi function ActiveCloudSetupPage({ request }: { request: CloudSetupPageRequest }): React.JSX.Element { const t = useTranslate() - const flow = useCloudSetupFlow(request) + const flow = useCloudSetupFlow(request, request.debugAccess) const projectName = useAppStore( (s) => s.repos.find((repo) => repo.id === request.repoId)?.displayName ?? null ) diff --git a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-copy.ts b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-copy.ts index c55189512f1..25a6f620505 100644 --- a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-copy.ts +++ b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-copy.ts @@ -115,11 +115,12 @@ export function currentStepCopy( case 'github-install': return { title: t('cloudSetupPage.github.title', 'Give Orca Cloud access on GitHub'), - lead: t( + // The row names the repository ("Orca Cloud can't reach acme/web yet"). + lead: detail, + note: t( 'cloudSetupPage.github.lead', 'Orca Cloud clones your code from GitHub. Install the Orca Cloud app on this repository once.' - ), - note: step?.note ?? null + ) } case 'github-waiting': return { diff --git a/src/renderer/src/lib/orca-cloud/cloud-setup-page-store.ts b/src/renderer/src/lib/orca-cloud/cloud-setup-page-store.ts index 8965f4d32b4..d5f4ad6dbb3 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-setup-page-store.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-setup-page-store.ts @@ -4,6 +4,8 @@ import { useSyncExternalStore } from 'react' import type { OrcaCloudAvailability } from '../../../../shared/orca-yaml-hook-types' import type { ComposerModalData } from '@/components/new-workspace/composer-modal-data' +import type { OrcaCloudRunTargetAccess } from '@/components/new-workspace/orca-cloud-run-target-access' +import { e2eConfig } from '@/lib/e2e-config' export type CloudSetupPageRequest = { prompt: string @@ -15,6 +17,11 @@ export type CloudSetupPageRequest = { cloudOnlyRepo: string | null /** The composer as it was: Back and the auto-start reopen it with everything kept. */ composer: ComposerModalData + /** + * Dev and e2e only: pins the account's billing answer so every step can be walked against the + * real page (dev sign-in has no billing). Never set by the app. + */ + debugAccess?: OrcaCloudRunTargetAccess openedAt: number } @@ -78,3 +85,12 @@ export function rememberCloudSetupAgentSkipped(agent: string | null): void { // Private mode: the step asks again next time. } } + +// Dev and e2e: drive the page from the console or CDP (as `__store` is), e.g. to walk the trial step. +if ((import.meta.env.DEV || e2eConfig.exposeStore) && typeof window !== 'undefined') { + ;(window as unknown as Record).__cloudSetupPage = { + open: openCloudSetupPage, + close: closeCloudSetupPage, + get: getCloudSetupPageRequest + } +} From b5c4d07bce163f232628cd9460186e772dcec365 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 16:50:43 -0800 Subject: [PATCH 024/149] fix(cloud): setup page copy (hour plural, billing settings label) and prompt card placement --- .../components/orca-cloud-setup/CloudSetupPage.tsx | 11 +++++++++-- .../orca-cloud-setup/cloud-setup-page-copy.ts | 4 +++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx index 4c69699f7d6..d9dabad6168 100644 --- a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx +++ b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx @@ -133,7 +133,14 @@ function StepActions({ flow }: { flow: CloudSetupFlow }): React.JSX.Element | nu case 'choose-plan': return browser(continueLabel, flow.continueInBrowser) case 'fix-billing': - return browser(continueLabel, flow.fixBilling) + // A failed payment is fixed in the billing portal (browser); hours and the cap in Settings. + return flow.current?.need === 'payment' ? ( + browser(continueLabel, flow.fixBilling) + ) : ( + + ) case 'github-install': return browser(continueLabel, flow.installGitHub) case 'start-trial': @@ -268,7 +275,7 @@ export function CloudSetupPage({
-
+
{t('cloudSetupPage.startsAfter', 'Starts when setup is done')} diff --git a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-copy.ts b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-copy.ts index 25a6f620505..edd0e67a473 100644 --- a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-copy.ts +++ b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-copy.ts @@ -62,7 +62,9 @@ export function currentStepCopy( 'cloudSetupPage.trial.lead', '{{hours}} sandbox hours to try Orca Cloud. No card needed.', { - hours + hours, + count: Number(hours), + defaultValue_one: '{{hours}} sandbox hour to try Orca Cloud. No card needed.' } ), note: t('cloudSetupPage.trial.note', 'Nothing is charged until you choose a plan.') From 466dddc3e04e54c358b33c22f23b240b7bbddf45 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 17:24:13 -0800 Subject: [PATCH 025/149] =?UTF-8?q?fix(cloud):=20design-squad=20=E2=80=94?= =?UTF-8?q?=20one=20'Create=20workspace'=20label,=20Run=20on=20menu=20insi?= =?UTF-8?q?de=20the=20dialog,=20no=20right=20sidebar=20during=20setup?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...ewWorkspaceComposerModal.retention.test.tsx | 2 +- .../components/NewWorkspaceComposerModal.tsx | 6 ++---- .../new-workspace/RunTargetCombobox.tsx | 4 +++- .../orca-cloud-setup/CloudSetupPageLayer.tsx | 18 ++++++++++++++++++ src/renderer/src/i18n/en-runtime-required.json | 7 +++++++ src/renderer/src/i18n/locales/en.json | 7 +++++-- .../lib/orca-cloud/cloud-setup-page-store.ts | 12 +++++++----- 7 files changed, 43 insertions(+), 13 deletions(-) diff --git a/src/renderer/src/components/NewWorkspaceComposerModal.retention.test.tsx b/src/renderer/src/components/NewWorkspaceComposerModal.retention.test.tsx index d01c63cd408..3be69bf3b51 100644 --- a/src/renderer/src/components/NewWorkspaceComposerModal.retention.test.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerModal.retention.test.tsx @@ -397,7 +397,7 @@ it('offers Reopen with the submitted target and picker and does not replace a ne fireEvent.change(textarea(), { target: { value: '--verbose' } }) fireEvent.click(screen.getByRole('radio', { name: 'Low' })) await useDraft() - const create = await screen.findByRole('button', { name: 'Create worktree' }) + const create = await screen.findByRole('button', { name: 'Create workspace' }) await waitFor(() => expect(create.hasAttribute('disabled')).toBe(false)) fireEvent.click(create) await waitFor(() => expect(evidence.submit).toHaveBeenCalledOnce()) diff --git a/src/renderer/src/components/NewWorkspaceComposerModal.tsx b/src/renderer/src/components/NewWorkspaceComposerModal.tsx index 2a03e374a04..5e5f9c61cba 100644 --- a/src/renderer/src/components/NewWorkspaceComposerModal.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerModal.tsx @@ -318,12 +318,10 @@ function QuickTabBody({ const isFolderWorkspaceTarget = cardProps.projectOptions.find((option) => option.id === cardProps.selectedProjectId)?.kind === 'project-group' - // Run on never changes the button: Orca Cloud reads exactly like this computer. + // Run on never changes the button, and it matches the title for every target (design-squad). const primaryActionLabel = isFolderWorkspaceTarget ? getFolderWorkspacePrimaryActionLabel(t) - : cardProps.selectedRepoIsGit - ? t('auto.components.NewWorkspaceComposerModal.createWorktree', 'Create worktree') - : t('auto.components.NewWorkspaceComposerModal.createWorkspace', 'Create workspace') + : t('auto.components.NewWorkspaceComposerModal.createWorkspace', 'Create workspace') // Let Radix own Escape for the topmost layer. This dialog auto-focuses input, so page-style blur-first handling swallowed its first Escape. const nestedDialogOpen = agentSettingsOpen || addProjectOpen || setLocationOpen diff --git a/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx b/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx index 76a9255d73e..a80779b6e57 100644 --- a/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetCombobox.tsx @@ -327,7 +327,9 @@ export default function RunTargetCombobox({ onKeyDown={handleKeyDown} /> { + if (!showing) { + return + } + const store = useAppStore.getState() + const wasOpen = store.rightSidebarOpen + if (wasOpen) { + store.setRightSidebarOpen(false) + } + return () => { + if (wasOpen && !useAppStore.getState().rightSidebarOpen) { + useAppStore.getState().setRightSidebarOpen(true) + } + } + }, [showing]) if (!request) { return null } diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index a4d9fda75d5..5a71a0907a4 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -1560,6 +1560,13 @@ "save_one": "Save secret", "save_other": "Save {{count}} secrets" }, + "cloudSetupPage": { + "trial": { + "lead": "{{hours}} sandbox hours to try Orca Cloud. No card needed.", + "lead_one": "{{hours}} sandbox hour to try Orca Cloud. No card needed.", + "lead_other": "{{hours}} sandbox hours to try Orca Cloud. No card needed." + } + }, "codeHost": { "bitbucketConnect": { "accessTokenRequired": "Enter an access token.", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 6f4de180e00..d8f3805ea4b 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -28014,7 +28014,8 @@ "hoursLead": "Turn on overage to start this workspace.", "hoursTitle": "Out of sandbox hours", "paymentLead": "The last payment failed. Update the card to keep going.", - "paymentTitle": "Update your payment method" + "paymentTitle": "Update your payment method", + "openSettings": "Open billing settings" }, "checkAgain": "Check again", "checking": { @@ -28076,7 +28077,9 @@ "leadNoHours": "Try Orca Cloud on your team. No card needed.", "note": "Nothing is charged until you choose a plan.", "start": "Start free trial", - "title": "Start your free trial" + "title": "Start your free trial", + "lead_one": "{{hours}} sandbox hour to try Orca Cloud. No card needed.", + "lead_other": "{{hours}} sandbox hours to try Orca Cloud. No card needed." }, "untitled": "New cloud workspace", "waitingBrowser": "Waiting for your browser…" diff --git a/src/renderer/src/lib/orca-cloud/cloud-setup-page-store.ts b/src/renderer/src/lib/orca-cloud/cloud-setup-page-store.ts index d5f4ad6dbb3..1a927a81feb 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-setup-page-store.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-setup-page-store.ts @@ -88,9 +88,11 @@ export function rememberCloudSetupAgentSkipped(agent: string | null): void { // Dev and e2e: drive the page from the console or CDP (as `__store` is), e.g. to walk the trial step. if ((import.meta.env.DEV || e2eConfig.exposeStore) && typeof window !== 'undefined') { - ;(window as unknown as Record).__cloudSetupPage = { - open: openCloudSetupPage, - close: closeCloudSetupPage, - get: getCloudSetupPageRequest - } + Object.assign(window, { + __cloudSetupPage: { + open: openCloudSetupPage, + close: closeCloudSetupPage, + get: getCloudSetupPageRequest + } + }) } From 64874e40271465d3493f82b212b75cd82c221e0c Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 18:57:06 -0800 Subject: [PATCH 026/149] =?UTF-8?q?fix(cloud):=20Orca=20Cloud=20adds=20not?= =?UTF-8?q?hing=20to=20the=20dialog=20=E2=80=94=20no=20hours=20in=20the=20?= =?UTF-8?q?Run=20on=20menu,=20no=20agent=20fallback=20notice=20(Neil)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../new-workspace/RunTargetOrcaCloudRow.tsx | 10 +++++--- .../new-workspace/use-composer-quick-agent.ts | 25 +++---------------- src/renderer/src/i18n/locales/en.json | 1 - 3 files changed, 9 insertions(+), 27 deletions(-) diff --git a/src/renderer/src/components/new-workspace/RunTargetOrcaCloudRow.tsx b/src/renderer/src/components/new-workspace/RunTargetOrcaCloudRow.tsx index fbd4fd07101..b23cd91a6c9 100644 --- a/src/renderer/src/components/new-workspace/RunTargetOrcaCloudRow.tsx +++ b/src/renderer/src/components/new-workspace/RunTargetOrcaCloudRow.tsx @@ -270,16 +270,18 @@ function OrcaCloudMeta({ } } -/** Hours left, the loading skeleton, and "Ask an owner or admin" still say something useful. */ +/** + * In the composer, hours and plan details wait until after create (Neil): the row only keeps what + * explains why it can't be picked, "Ask an owner or admin". + */ function showsMetaAfterStart(access: OrcaCloudRunTargetAccess): boolean { switch (access.state) { - case 'loading': - case 'entitled': - return true case 'no-plan': case 'out-of-hours': case 'payment-issue': return !access.canManageBilling + case 'loading': + case 'entitled': case 'signed-out': case 'unknown': return false diff --git a/src/renderer/src/components/new-workspace/use-composer-quick-agent.ts b/src/renderer/src/components/new-workspace/use-composer-quick-agent.ts index 2178b08b831..e8d235303eb 100644 --- a/src/renderer/src/components/new-workspace/use-composer-quick-agent.ts +++ b/src/renderer/src/components/new-workspace/use-composer-quick-agent.ts @@ -1,7 +1,5 @@ import { useMemo } from 'react' import { useAppStore } from '@/store/index' -import { useTranslate } from '@/i18n/use-translate' -import { formatAgentTypeLabel } from '../../../../shared/agent-status/presentation/agent-type-label' import { agentChoicePending } from '@/lib/host-chat-program' import { useAgentsOfferedForLaunch } from '@/lib/host-chat-program-acquisition' import { @@ -11,7 +9,6 @@ import { } from '@/lib/quick-workspace-agent-selection' import { ORCA_CLOUD_AGENT_IDS, - orcaCloudAgentFallback, orcaCloudAgentMenuModel, pickOrcaCloudAgent } from '@/lib/orca-cloud/orca-cloud-agent-picker' @@ -38,7 +35,6 @@ export function useComposerQuickAgent( quickAgentOverride: TuiAgent | null | undefined, setQuickAgentOverride: (agent: TuiAgent | null | undefined) => void ) { - const t = useTranslate() // The picker rows' workspace when known, so the offered list and the rows read one host. const launchWorkspace = cardProps.agentRows?.target.workspace ?? composerLaunchWorkspace(cardProps) @@ -83,23 +79,8 @@ export function useComposerQuickAgent( const chipAgentIds = offeredAgentIds && new Set([...offeredAgentIds, ...(quickAgent && choicePending(quickAgent) ? [quickAgent] : [])]) - // Said, not silent: the agent the user wanted isn't on the image, so another one is selected. - const orcaCloudFallback = orcaCloud - ? orcaCloudAgentFallback({ - override: quickAgentOverride, - defaultAgent: settings?.defaultTuiAgent, - selected: quickAgent - }) - : null - const agentNotice = orcaCloudFallback - ? t( - 'components.newWorkspace.orcaCloudAgentFallback', - '{{agent}} isn’t available on Orca Cloud yet, so {{fallback}} is selected.', - { - agent: formatAgentTypeLabel(orcaCloudFallback.wanted), - fallback: formatAgentTypeLabel(orcaCloudFallback.selected) - } - ) - : undefined + // Orca Cloud adds nothing to the dialog (Neil): an agent it can't run falls back silently; the + // picker shows what will start. + const agentNotice: string | undefined = undefined return { orcaCloud, orcaCloudModel, quickAgent, chipAgentIds, agentNotice } } diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index d8f3805ea4b..13ddd1561e6 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -23157,7 +23157,6 @@ "showMore": "Show more repositories…", "folderDetail": "Orca Cloud starts from a GitHub repository. This project is a folder on this computer." }, - "orcaCloudAgentFallback": "{{agent}} isn’t available on Orca Cloud yet, so {{fallback}} is selected.", "cloudStart": { "agentNotStarted": "{{agent}} isn’t set up for Orca Cloud, so it didn’t start. The workspace has a terminal.", "agentNotStartedGeneric": "Your agent isn’t set up for Orca Cloud, so it didn’t start. The workspace has a terminal.", From 0792a56a0a348c4731b92028c1bfe57c797bae12 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 19:08:32 -0800 Subject: [PATCH 027/149] wip(cloud): env-check gate opens on warnings, sleeps blocked sandboxes --- .../environment-doctor-setup.ts | 4 +- src/main/ipc/ephemeral-vm-runtime-handlers.ts | 28 ++ src/preload/api/ephemeral-vm-api.ts | 10 + src/preload/api/ephemeral-vm-bridge.ts | 2 + .../orca-cloud/CloudSetupNotices.tsx | 260 ++++++++++++ .../orca-cloud/OrcaCloudWorkspaceSurface.tsx | 5 + .../BlockedSandboxHoursNote.tsx | 59 +++ .../worktree-creation/VmBuildCheckRow.tsx | 11 +- .../VmBuildFailureActions.tsx | 28 +- .../worktree-creation/VmBuildFailureCard.tsx | 26 +- .../VmBuildSheet.fixture.tsx | 63 ++- .../worktree-creation/VmBuildSheet.tsx | 35 +- .../cloud-agent-check-copy.test.ts | 85 ---- .../cloud-agent-check-copy.ts | 93 ----- .../VmBuildCloudAgentsMenu.tsx | 145 ------- .../VmBuildCloudAgentsRow.tsx | 202 ---------- .../VmBuildCloudAgentsRowView.tsx | 375 ------------------ .../environment-check-copy.ts | 46 +++ .../vm-build-failure-copy.ts | 69 ++-- .../worktree-creation/vm-build-failure.ts | 15 +- .../vm-build-sheet-agents-fixtures.tsx | 238 ----------- .../vm-build-sheet-fixture-support.tsx | 28 +- ...ephemeral-vm-environment-check-decision.ts | 8 +- .../ephemeral-vm-environment-check-triage.ts | 84 ++++ .../src/lib/ephemeral-vm-environment-check.ts | 165 ++++++-- .../src/lib/ephemeral-vm-worktree-creation.ts | 39 +- .../orca-cloud/cloud-setup-notice-actions.ts | 115 ++++++ .../orca-cloud/cloud-setup-notices-store.ts | 90 +++++ .../creation/pending-worktree-creation.ts | 4 + 29 files changed, 1000 insertions(+), 1332 deletions(-) create mode 100644 src/renderer/src/components/orca-cloud/CloudSetupNotices.tsx create mode 100644 src/renderer/src/components/worktree-creation/BlockedSandboxHoursNote.tsx delete mode 100644 src/renderer/src/components/worktree-creation/cloud-agent-check-copy.test.ts delete mode 100644 src/renderer/src/components/worktree-creation/cloud-agent-check-copy.ts delete mode 100644 src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsMenu.tsx delete mode 100644 src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRow.tsx delete mode 100644 src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRowView.tsx delete mode 100644 src/renderer/src/components/worktree-creation/vm-build-sheet-agents-fixtures.tsx create mode 100644 src/renderer/src/lib/ephemeral-vm-environment-check-triage.ts create mode 100644 src/renderer/src/lib/orca-cloud/cloud-setup-notice-actions.ts create mode 100644 src/renderer/src/lib/orca-cloud/cloud-setup-notices-store.ts diff --git a/src/main/environment-doctor/environment-doctor-setup.ts b/src/main/environment-doctor/environment-doctor-setup.ts index edd30791626..dd431e17663 100644 --- a/src/main/environment-doctor/environment-doctor-setup.ts +++ b/src/main/environment-doctor/environment-doctor-setup.ts @@ -87,7 +87,9 @@ export async function checkSetup( 'Setup script is configured and has run here. Use --run-setup to check its exit code.' ) : check('setup', 'setup.run', 'warn', 'Setup script is configured but has not run here.', { - remediation: 'Re-run the doctor with --run-setup to run it and check the result.' + remediation: 'Re-run the doctor with --run-setup to run it and check the result.', + // Desktop clients show their own words (no CLI flags) for this code. + code: 'setupNotRun' }) ] } diff --git a/src/main/ipc/ephemeral-vm-runtime-handlers.ts b/src/main/ipc/ephemeral-vm-runtime-handlers.ts index 2d1209de786..a6601134042 100644 --- a/src/main/ipc/ephemeral-vm-runtime-handlers.ts +++ b/src/main/ipc/ephemeral-vm-runtime-handlers.ts @@ -11,6 +11,7 @@ import { import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes' import { cleanupOwnedEphemeralVmRuntime } from '../ephemeral-vm/owned-runtime-cleanup' import { stopEphemeralVmRuntimeCleanup } from '../ephemeral-vm/runtime-cleanup-control' +import { suspendEphemeralVmRuntime } from '../ephemeral-vm/runtime-service' import { buildEphemeralVmRecipeCleanupCommand, buildEphemeralVmRecipeCleanupPayload @@ -118,6 +119,7 @@ export function registerEphemeralVmRuntimeHandlers(store: Store): void { ipcMain.removeHandler('ephemeralVm:attachWorkspace') ipcMain.removeHandler('ephemeralVm:listRuntimes') ipcMain.removeHandler('ephemeralVm:cleanup') + ipcMain.removeHandler('ephemeralVm:suspendRuntime') ipcMain.removeHandler('ephemeralVm:preflightCloudDelete') ipcMain.removeHandler('ephemeralVm:stopCleanup') ipcMain.removeHandler('ephemeralVm:forgetRuntime') @@ -159,6 +161,32 @@ export function registerEphemeralVmRuntimeHandlers(store: Store): void { } ) + // A create blocked on a failed environment check holds a sandbox no workspace owns yet, so the + // window's idle sleep never sees it. The build sheet sleeps it after a few unused minutes. + ipcMain.handle( + 'ephemeralVm:suspendRuntime', + async (_event, args: { runtimeId: string }): Promise<{ ok: boolean; error?: string }> => { + const userDataPath = app.getPath('userData') + const runtimeId = String(args?.runtimeId ?? '') + const runtime = listEphemeralVmRuntimes(userDataPath).find((entry) => entry.id === runtimeId) + if (!runtime || runtime.workspaceId || runtime.recipe?.provider !== 'orca-cloud') { + return { ok: false, error: 'Not a sandbox waiting on its create.' } + } + try { + const context = getRuntimeRecipeContext(store, userDataPath, runtimeId) + const result = await suspendEphemeralVmRuntime({ + userDataPath, + repoPath: context.repoPath, + recipe: context.recipe, + runtimeId + }) + return result.ok ? { ok: true } : { ok: false, error: result.error } + } catch (error) { + return { ok: false, error: error instanceof Error ? error.message : String(error) } + } + } + ) + ipcMain.handle( 'ephemeralVm:stopCleanup', async (_event, args: { runtimeId: string }): Promise => { diff --git a/src/preload/api/ephemeral-vm-api.ts b/src/preload/api/ephemeral-vm-api.ts index e842143d555..8aeb073182f 100644 --- a/src/preload/api/ephemeral-vm-api.ts +++ b/src/preload/api/ephemeral-vm-api.ts @@ -112,6 +112,16 @@ export type EphemeralVmApi = { suspendWorkspace: (args: { workspaceId: string }) => Promise /** Fires after any runtime record write; re-list to read the new lifecycle status. */ onRuntimesChanged: (callback: () => void) => () => void + /** + * Orca Cloud: puts a sandbox that never became a workspace to sleep (a create blocked on a + * failed environment check). Optional: the web client has no VM lifecycle. + */ + suspendRuntime?: (args: { runtimeId: string }) => Promise<{ ok: boolean; error?: string }> + /** + * Orca Cloud: puts a sandbox that never became a workspace to sleep (a create blocked on a + * failed environment check). Optional: the web client has no VM lifecycle. + */ + suspendRuntime?: (args: { runtimeId: string }) => Promise<{ ok: boolean; error?: string }> cleanup: (args: { runtimeId: string }) => Promise /** Orca Cloud: before Delete drops the row, prove the signed-in identity can reach the sandbox. */ preflightCloudDelete?: (args: { diff --git a/src/preload/api/ephemeral-vm-bridge.ts b/src/preload/api/ephemeral-vm-bridge.ts index 2daca4b1614..3220045fa09 100644 --- a/src/preload/api/ephemeral-vm-bridge.ts +++ b/src/preload/api/ephemeral-vm-bridge.ts @@ -56,6 +56,8 @@ export const ephemeralVmApi = { ipcRenderer.on(EPHEMERAL_VM_RUNTIMES_CHANGED_CHANNEL, listener) return () => ipcRenderer.removeListener(EPHEMERAL_VM_RUNTIMES_CHANGED_CHANNEL, listener) }, + suspendRuntime: (args) => ipcRenderer.invoke('ephemeralVm:suspendRuntime', args), + suspendRuntime: (args) => ipcRenderer.invoke('ephemeralVm:suspendRuntime', args), cleanup: (args) => ipcRenderer.invoke('ephemeralVm:cleanup', args), preflightCloudDelete: (args) => ipcRenderer.invoke('ephemeralVm:preflightCloudDelete', args), stopCleanup: (args) => ipcRenderer.invoke('ephemeralVm:stopCleanup', args), diff --git a/src/renderer/src/components/orca-cloud/CloudSetupNotices.tsx b/src/renderer/src/components/orca-cloud/CloudSetupNotices.tsx new file mode 100644 index 00000000000..82b9d46f846 --- /dev/null +++ b/src/renderer/src/components/orca-cloud/CloudSetupNotices.tsx @@ -0,0 +1,260 @@ +import React, { useEffect, useId, useRef, useState } from 'react' +import { GitPullRequestArrow, Loader2, Play, TriangleAlert, X } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { useAppStore } from '@/store' +import { useTranslate, type Translate } from '@/i18n/use-translate' +import { environmentCheckCopy } from '@/components/worktree-creation/environment-check-copy' +import type { CloudSetupNotice } from '@/lib/ephemeral-vm-environment-check-triage' +import { + dismissCloudSetupNotice, + useCloudSetupNoticesSnapshot, + visibleCloudSetupNotices, + type CloudSetupNoticesRecord +} from '@/lib/orca-cloud/cloud-setup-notices-store' +import { + openOrcaGitHubAppInstall, + recheckCloudPushAccess, + repoOwner, + repoSlug, + runCloudSetupScript +} from '@/lib/orca-cloud/cloud-setup-notice-actions' + +// After Install: GitHub's webhook usually lands within seconds, then the owner may take a while. +const FAST_POLL_MS = 2_000 +const FAST_POLL_WINDOW_MS = 3 * 60_000 +const SLOW_POLL_MS = 10_000 +const GIVE_UP_MS = 30 * 60_000 + +export type CloudSetupNoticeLine = { + text: string + action: { label: string; icon: React.ReactNode; run: () => void; pending?: boolean } | null +} + +export function cloudSetupNoticeLine( + notice: CloudSetupNotice, + record: Pick, + t: Translate, + handlers: { install: () => void; runSetup: () => void; installing: boolean } +): CloudSetupNoticeLine { + switch (notice.kind) { + case 'push': + if (record.repoUrl) { + const owner = repoOwner(record.repoUrl) + return { + text: t( + 'orcaCloud.setupNotices.pushNeedsApp', + 'Orca Cloud can read {{repo}} but can’t push yet. Install the Orca GitHub App on {{owner}} to push.', + { repo: repoSlug(record.repoUrl), owner } + ), + action: { + label: handlers.installing + ? t('orcaCloud.setupNotices.waitingForGitHub', 'Waiting for GitHub…') + : t('orcaCloud.setupNotices.installOn', 'Install on {{owner}}', { owner }), + icon: handlers.installing ? ( + + ) : ( + + ), + run: handlers.install, + pending: handlers.installing + } + } + } + return { + text: t('orcaCloud.setupNotices.pushRefused', 'Orca Cloud can’t push from this workspace.'), + action: null + } + case 'setup': + return { + text: t('orcaCloud.setupNotices.setupNotRun', 'Setup script hasn’t run yet'), + action: { + label: t('orcaCloud.setupNotices.runSetup', 'Run setup script'), + icon: , + run: handlers.runSetup + } + } + case 'check': + return { text: environmentCheckCopy(notice.check, t, true).message, action: null } + } +} + +/** Polls repo access after Install until the push works, GitHub refuses it, or it gives up. */ +function usePushRecheck(environmentId: string | undefined, hasPush: boolean): { + installing: boolean + startInstall: (repoUrl: string) => void +} { + const [installStartedAt, setInstallStartedAt] = useState(null) + const [tick, setTick] = useState(0) + const busy = useRef(false) + + useEffect(() => { + if (!environmentId || !hasPush || installStartedAt === null) { + return + } + const elapsed = Date.now() - installStartedAt + if (elapsed > GIVE_UP_MS) { + setInstallStartedAt(null) + return + } + const timer = setTimeout( + () => { + if (busy.current) { + setTick((n) => n + 1) + return + } + busy.current = true + void recheckCloudPushAccess(environmentId) + .then((result) => { + if (result !== 'waiting') { + setInstallStartedAt(null) + } + }) + .finally(() => { + busy.current = false + setTick((n) => n + 1) + }) + }, + elapsed < FAST_POLL_WINDOW_MS ? FAST_POLL_MS : SLOW_POLL_MS + ) + return () => clearTimeout(timer) + }, [environmentId, hasPush, installStartedAt, tick]) + + // Installed somewhere else (the browser, another device): check again when Orca is focused. + useEffect(() => { + if (!environmentId || !hasPush) { + return + } + const onFocus = (): void => { + if (!busy.current) { + busy.current = true + void recheckCloudPushAccess(environmentId).finally(() => { + busy.current = false + }) + } + } + window.addEventListener('focus', onFocus) + return () => window.removeEventListener('focus', onFocus) + }, [environmentId, hasPush]) + + return { + installing: installStartedAt !== null, + startInstall: (repoUrl) => { + void openOrcaGitHubAppInstall(repoUrl).then((opened) => { + if (opened) { + setInstallStartedAt(Date.now()) + } + }) + } + } +} + +/** + * What the environment check found that didn't need to stop the create: one line per problem, one + * action each, each dismissible. Sits with the workspace's other notices, top right. + */ +export function CloudSetupNotices({ + workspaceId +}: { + workspaceId: string +}): React.JSX.Element | null { + const environmentId = useAppStore( + (state) => state.ephemeralVmRuntimesByWorkspaceId?.[workspaceId]?.runtimeEnvironmentId + ) + const snapshot = useCloudSetupNoticesSnapshot() + const record = environmentId ? snapshot.records[environmentId] : undefined + const notices = visibleCloudSetupNotices(snapshot, environmentId) + const push = usePushRecheck( + environmentId, + notices.some((notice) => notice.kind === 'push') + ) + if (!record || notices.length === 0) { + return null + } + return ( + record.repoUrl && push.startInstall(record.repoUrl)} + onRunSetup={(noticeId) => void runCloudSetupScript(workspaceId, record, noticeId)} + onDismiss={(noticeId) => dismissCloudSetupNotice(record.environmentId, noticeId)} + /> + ) +} + +export function CloudSetupNoticesView({ + record, + notices, + installing, + onInstall, + onRunSetup, + onDismiss +}: { + record: Pick + notices: readonly CloudSetupNotice[] + installing: boolean + onInstall: () => void + onRunSetup: (noticeId: string) => void + onDismiss: (noticeId: string) => void +}): React.JSX.Element { + const t = useTranslate() + const labelId = useId() + return ( +
+

+ {t('orcaCloud.setupNotices.label', 'Workspace setup')} +

+
    + {notices.map((notice) => { + const line = cloudSetupNoticeLine(notice, record, t, { + install: onInstall, + runSetup: () => onRunSetup(notice.id), + installing + }) + return ( +
  • + +

    {line.text}

    + {line.action ? ( + + ) : null} + +
  • + ) + })} +
+
+ ) +} diff --git a/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx b/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx index a94ff5f056f..7b3116d044c 100644 --- a/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx +++ b/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx @@ -21,6 +21,7 @@ import type { CloudWakeProgressEvent } from '../../../../shared/hosted-sandbox/c import { CloudArchivedWorkspaceView, type ArchiveLoad } from './CloudArchivedWorkspaceView' import { CloudWakingOverlay } from './CloudWakingOverlay' import { CloudWorkspaceNotice } from './CloudWorkspaceNotice' +import { CloudSetupNotices } from './CloudSetupNotices' import { useConfirmedRestart } from './use-cloud-panel-actions' import { useCloudVersionSkewNotice } from './use-cloud-version-skew-notice' import { CloudWorkspaceOfflineView } from './offline/CloudWorkspaceOfflineView' @@ -336,6 +337,10 @@ function CloudSurface({ workspaceId }: { workspaceId: string }): React.JSX.Eleme if (layer === null && versionSkewNotice) { notices.push(versionSkewNotice) } + if (layer === null && view.state !== 'sleeping' && view.state !== 'archived') { + // What the environment check found that didn't need to stop the create (env-check-ux). + notices.push() + } if (layer === null && view.oom) { notices.push( + + {text} +

+ ) +} diff --git a/src/renderer/src/components/worktree-creation/VmBuildCheckRow.tsx b/src/renderer/src/components/worktree-creation/VmBuildCheckRow.tsx index df072758288..c48d12fd7ed 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildCheckRow.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildCheckRow.tsx @@ -3,28 +3,19 @@ import { Badge } from '@/components/ui/badge' import type { Translate } from '@/i18n/use-translate' import type { EnvironmentDoctorCheck } from '../../../../shared/environment-doctor-types' import { environmentCheckBadge, environmentCheckCopy } from './environment-check-copy' -import { cloudAgentCheckCopy } from './cloud-agent-check-copy' -import type { OrcaCloudAgentAccountsState } from '@/lib/orca-cloud/orca-cloud-agent-accounts-store' export function CheckRow({ check, index, cloud, - accounts, t }: { check: EnvironmentDoctorCheck index: number cloud: boolean - /** Orca Cloud: agent sign-in comes from the Orca account, not the sandbox's own probe. */ - accounts: Pick t: Translate }): React.JSX.Element | null { - const cloudAgent = cloud ? cloudAgentCheckCopy(check, accounts, t) : null - if (cloudAgent?.kind === 'hide') { - return null - } - const copy = cloudAgent ?? environmentCheckCopy(check, t, cloud) + const copy = environmentCheckCopy(check, t, cloud) const { message } = copy // Uncoded fixes end in raw CLI output; on Orca Cloud keep only the advice line above it. const remediation = diff --git a/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx b/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx index 33be7e9bbf8..e3c5481111a 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx @@ -28,6 +28,8 @@ export type VmBuildFailureActions = { onRetry: () => void onEditRecipe: () => void onOpenAnyway: () => void + /** Orca Cloud, unusable sandbox: delete it and start the create on a new one. */ + onStartAgain: () => void onDismiss: () => void onSeePlans: () => void onOpenBilling: () => void @@ -173,18 +175,20 @@ function failureActions( icon: , onClick: actions.onOpenAnyway } - // Hosted sandboxes have no recipe for an agent or the user to edit. Checks rarely pass on a - // rerun without a change, so opening the sandbox to fix them in place leads. Two plain text - // buttons read as a choice between equals rather than a toolbar. - return cloud - ? { - primary: [ - { ...openAnyway, icon: undefined }, - { ...retryChecks, icon: undefined } - ], - more: [] - } - : { primary: [fix, retryChecks], more: [openAnyway, editRecipe] } + if (!cloud) { + return { primary: [fix, retryChecks], more: [openAnyway, editRecipe] } + } + // Orca Cloud stops here only when the sandbox can't hold the workspace (no checkout, no git, + // orcad unreachable), so opening it anyway would land in a broken workspace. A fresh sandbox + // is the fix; checking again only helps while this one is still awake. + const startAgain: Action = { + key: 'start-again', + label: t('auto.components.worktree.creation.VmBuildFailureCard.startAgain', 'Start again'), + onClick: actions.onStartAgain + } + return failure.sandbox + ? { primary: [startAgain], more: [] } + : { primary: [startAgain, { ...retryChecks, icon: undefined }], more: [] } } case 'provision': return cloud diff --git a/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx b/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx index 8fea19a218c..a78278f84b0 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx @@ -7,8 +7,8 @@ import { getLastBillingStatus } from '@/components/billing/billing-summary-store import { sandboxLimitFromBilling, vmBuildFailureCopy } from './vm-build-failure-copy' import { FailureActionRow, type VmBuildFailureActions } from './VmBuildFailureActions' import { CheckRow } from './VmBuildCheckRow' -import { useOrcaCloudAgentAccounts } from '@/lib/orca-cloud/orca-cloud-agent-accounts-store' import { VmBuildErrorDetails } from './VmBuildErrorDetails' +import { BlockedSandboxHoursNote } from './BlockedSandboxHoursNote' export type { VmBuildFailureActions } @@ -41,8 +41,6 @@ export function VmBuildFailureCard({ actions: VmBuildFailureActions }): React.JSX.Element { const t = useTranslate() - // Read only on Orca Cloud with checks to show; recipe VMs keep the host's own sign-in copy. - const accounts = useOrcaCloudAgentAccounts(cloud && failure?.kind === 'checks') // Why: a closing card still needs its content, or it would empty out before it finishes collapsing. const [shown, setShown] = React.useState(failure) // Each opening is a new run, so the rows remount and their stagger replays on a repeated failure. @@ -119,7 +117,6 @@ export function VmBuildFailureCard({ check={check} index={index} cloud={cloud} - accounts={accounts} t={t} /> ))} @@ -137,17 +134,16 @@ export function VmBuildFailureCard({ t={t} /> {visible.kind === 'checks' ? ( -

- {cloud - ? t( - 'auto.components.worktree.creation.VmBuildFailureCard.stillRunningCloud', - 'The sandbox is running and using sandbox hours until you choose.' - ) - : t( - 'auto.components.worktree.creation.VmBuildFailureCard.stillRunningLocal', - 'The VM is running and using hours until you choose.' - )} -

+ cloud ? ( + + ) : ( +

+ {t( + 'auto.components.worktree.creation.VmBuildFailureCard.stillRunningLocal', + 'The VM is running and using hours until you choose.' + )} +

+ ) ) : null}
diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheet.fixture.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheet.fixture.tsx index 8026c0a8305..06a3c9523fe 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheet.fixture.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheet.fixture.tsx @@ -10,7 +10,6 @@ import { FAILED_LOG, LOG, frame, - seedCloudAgentAccounts, LOG_LINES, NOW, seedFixtureRepo, @@ -248,52 +247,43 @@ export const checksSkipped = frame( }) ) -const cloudChecks = frame( - entry( - { environmentCheck: { status: 'failed', checks: FAILED_CHECKS, ...CHECKS_FAILED_AT } }, - CLOUD_RECIPE - ) -) -// Claude isn't set up through the Orca account: the sign-in warning says where to set it up. -export const cloudChecksFailed = defineFixture({ - ...cloudChecks, - setup: () => { - cloudChecks.setup?.() - seedCloudAgentAccounts('none') +// Orca Cloud stops only on a fatal check; orcad never answered here, so the doctor couldn't run. +const CLOUD_FATAL_CHECKS: NonNullable['checks'] = [ + { + id: 'environment.doctor', + category: 'workspace', + status: 'fail', + message: 'The environment checks could not finish: Runtime environment is unreachable.' } -}) -// Claude is covered by the Orca account: the sandbox's own sign-in probe isn't shown at all. -export const cloudChecksAgentCovered = defineFixture({ - ...cloudChecks, - setup: () => { - cloudChecks.setup?.() - seedCloudAgentAccounts('active') - } -}) +] +// Rendered relative to the real clock: the note counts down from it. +const sleepsIn = (ms: number): number => Date.now() + ms -// One failure plus a warning: the title counts failures only, in the singular. -const cloudChecksOne = frame( - entry( +function cloudFatal( + extra: Partial> +): PendingWorktreeCreation { + return entry( { environmentCheck: { status: 'failed', - checks: FAILED_CHECKS?.filter((check) => check.id !== 'git.push'), - ...CHECKS_FAILED_AT + checks: CLOUD_FATAL_CHECKS, + ...CHECKS_FAILED_AT, + sleepsAt: sleepsIn(5 * 60_000), + ...extra } }, CLOUD_RECIPE ) -) +} -export const cloudChecksFailedOne = defineFixture({ - ...cloudChecksOne, - setup: () => { - cloudChecksOne.setup?.() - seedCloudAgentAccounts('none') - } -}) +// Unusable sandbox, still awake: Start again leads, and the note says when it sleeps. +export const cloudChecksFailed = frame(cloudFatal({})) +// Five unused minutes later: asleep, so checking again can't help; only Start again or Delete. +export const cloudChecksAsleep = frame(cloudFatal({ sandbox: 'asleep' })) +// It couldn't sleep, so it was deleted: nothing is kept, Start again retries on a new one. +export const cloudChecksDeleted = frame(cloudFatal({ sandbox: 'deleted' })) -// A narrow sheet: the pills keep one column and Delete sandbox wraps under the recovery actions. +// A narrow sheet: Delete sandbox wraps under the recovery actions. export const cloudChecksFailedNarrow = defineFixture({ ...cloudChecksFailed, width: 420 @@ -405,4 +395,3 @@ export const secretsRefused = secretsFrame( export const secretsSkipped = secretsFrame(secretsRow(secretsData('admin'), { phase: 'skipped' })) // The Agents row (spec §5b), as VmBuildSheet:agents*. -export * from './vm-build-sheet-agents-fixtures' diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx index 4cea68efd6d..8cc9d37c046 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx @@ -7,7 +7,10 @@ import { useOrcaBillingStatus } from '@/components/billing/use-orca-billing-stat import { cn } from '@/lib/utils' import { useAppStore } from '@/store' import { useTranslate, type Translate } from '@/i18n/use-translate' -import { resolveVmEnvironmentCheckDecision } from '@/lib/ephemeral-vm-environment-check-decision' +import { + isAwaitingVmEnvironmentCheckDecision, + resolveVmEnvironmentCheckDecision +} from '@/lib/ephemeral-vm-environment-check-decision' import { openPlansPage } from '@/components/billing/plans/plans-page-store' import { ORCA_BILLING_OVERAGE_SECTION_ID } from '@/components/new-workspace/orca-cloud-run-target-access' import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation' @@ -19,7 +22,6 @@ import { VmBuildStepRow } from './VmBuildStepRow' import { firstBuildLogErrorLine, VmBuildLog } from './VmBuildLog' import { VmBuildFailureCard } from './VmBuildFailureCard' import { VmBuildAgentSignInRow } from './VmBuildAgentSignInRow' -import { VmBuildCloudAgentsRow } from './cloud-agents-row/VmBuildCloudAgentsRow' import { VmBuildSecretsRow } from '../cloud-secrets-ask/VmBuildSecretsRow' import { OrcaCloudQueuedPrompt } from '@/components/orca-cloud/OrcaCloudQueuedPrompt' import { @@ -99,7 +101,6 @@ export function VmBuildSheet({ onReturnToComposer, onEditRecipe, agentSignInRow, - cloudAgentsRow, secretsRow, stepTimings }: { @@ -117,8 +118,6 @@ export function VmBuildSheet({ onEditRecipe: () => void /** Fixtures only: a fixed sign-in row in place of the live one. */ agentSignInRow?: React.ReactNode - /** Fixtures only: a fixed cloud Agents row (null for none) in place of the live one. */ - cloudAgentsRow?: React.ReactNode /** Fixtures only: a fixed Secrets row (null for none) in place of the live one. */ secretsRow?: React.ReactNode /** Fixtures only: measured step timings in place of the control plane's. */ @@ -204,7 +203,9 @@ export function VmBuildSheet({ // Failed checks leave a running sandbox that needs a decision, not a broken start. className={cn( 'size-4 motion-safe:animate-in motion-safe:fade-in-0 motion-safe:zoom-in-90 motion-safe:duration-200', - failure?.kind === 'checks' ? 'text-status-warning-text' : 'text-destructive' + failure?.kind === 'checks' && !cloud + ? 'text-status-warning-text' + : 'text-destructive' )} /> )} @@ -255,15 +256,8 @@ export function VmBuildSheet({ t={t} /> ))} - {/* Orca Cloud: one fixed-height row from the Orca account, never a per-sandbox sign-in - (spec §5b). Other VMs keep the host's own sign-in row. */} - {cloud ? ( - cloudAgentsRow !== undefined ? ( - cloudAgentsRow - ) : ( - - ) - ) : null} + {/* Orca Cloud: agent setup happens after create (the setup page and the workspace's + sign-in strip), so the build card has no agent row. Other VMs keep the host's own. */} {agentSignInRow ?? (!cloud && entry.vmEnvironmentId ? ( resolveVmEnvironmentCheckDecision(creationId, 'open-anyway'), + // A paused create deletes this sandbox and starts over; one already gone just retries. + onStartAgain: () => + isAwaitingVmEnvironmentCheckDecision(creationId) + ? resolveVmEnvironmentCheckDecision(creationId, 'restart') + : onRetry(), // Nothing was created, so leaving a billing refusal hands the typed prompt back. onDismiss: isBillingFailure(failure) && typedComposerPrompt(entry).trim() diff --git a/src/renderer/src/components/worktree-creation/cloud-agent-check-copy.test.ts b/src/renderer/src/components/worktree-creation/cloud-agent-check-copy.test.ts deleted file mode 100644 index 15581ba4950..00000000000 --- a/src/renderer/src/components/worktree-creation/cloud-agent-check-copy.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { translate } from '@/i18n/i18n' -import type { EnvironmentDoctorCheck } from '../../../../shared/environment-doctor-types' -import type { OrcaCloudAgentsStatus } from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' -import { cloudAgentCheckCopy } from './cloud-agent-check-copy' - -const signedOut = (agent: string, name: string): EnvironmentDoctorCheck => ({ - category: 'agents', - id: `agent.${agent}`, - status: 'warn', - message: `${name} is installed but not signed in.`, - code: 'agentSignedOut', - params: { agent: name } -}) -const CLAUDE = signedOut('claude', 'Claude') - -function ready(overrides: { - state?: 'none' | 'active' | 'expired' - provider?: 'on' | 'off' | 'disabled' - covered?: boolean -}): Parameters[1] { - const provider = overrides.provider ?? 'on' - const status: OrcaCloudAgentsStatus = { - credentials: { - claude: { state: overrides.state ?? 'none' }, - codex: { state: 'none' }, - providerEnabled: { claude: provider === 'on', codex: true }, - providerState: { claude: provider, codex: 'on' } - }, - sources: { defaults: {}, coveredByKey: { claude: overrides.covered ?? false, codex: false } } - } - return { - load: { kind: 'ready', status }, - keyKinds: { claude: overrides.covered ? 'team' : null, codex: null } - } -} - -const copy = (check: EnvironmentDoctorCheck, accounts: Parameters[1]) => - cloudAgentCheckCopy(check, accounts, translate) - -describe('cloudAgentCheckCopy', () => { - it('hides the row when the Orca account or a key covers the agent', () => { - expect(copy(CLAUDE, ready({ state: 'active' }))).toEqual({ kind: 'hide' }) - expect(copy(CLAUDE, ready({ covered: true }))).toEqual({ kind: 'hide' }) - }) - - it('says not set up, and where to set it up, when nothing covers the agent', () => { - expect(copy(CLAUDE, ready({}))).toEqual({ - kind: 'copy', - message: 'Claude isn’t set up for Orca Cloud yet.', - remediation: 'Set it up once in Settings → Agent accounts. Every cloud workspace uses it.' - }) - expect(copy(CLAUDE, ready({ state: 'expired' }))).toMatchObject({ - message: 'Your Claude sign-in for Orca Cloud expired.' - }) - }) - - it('never says “isn’t set up” when there is nothing to set up', () => { - const paused = copy(CLAUDE, ready({ provider: 'disabled' })) - const notOffered = copy(CLAUDE, ready({ provider: 'off' })) - for (const result of [paused, notOffered]) { - expect(result?.kind).toBe('copy') - expect(result && 'message' in result ? result.message : '').not.toMatch(/set up/) - } - expect(paused).toMatchObject({ remediation: expect.stringContaining('paused') }) - expect(notOffered).toMatchObject({ - remediation: expect.stringContaining('Signs in for each cloud workspace for now') - }) - }) - - it('says nothing until the account is read', () => { - expect( - copy(CLAUDE, { load: { kind: 'loading' }, keyKinds: { claude: null, codex: null } }) - ).toEqual({ kind: 'hide' }) - }) - - it('points API-key agents at Cloud secrets, and leaves other checks to the shared copy', () => { - expect(copy(signedOut('gemini', 'Gemini CLI'), ready({}))).toMatchObject({ - message: 'Gemini CLI isn’t signed in.', - remediation: expect.stringContaining('Cloud secrets') - }) - expect(copy({ ...CLAUDE, code: 'diskLow', params: { free: '2' } }, ready({}))).toBeNull() - expect(copy({ ...CLAUDE, code: undefined }, ready({}))).toBeNull() - }) -}) diff --git a/src/renderer/src/components/worktree-creation/cloud-agent-check-copy.ts b/src/renderer/src/components/worktree-creation/cloud-agent-check-copy.ts deleted file mode 100644 index 446946147bf..00000000000 --- a/src/renderer/src/components/worktree-creation/cloud-agent-check-copy.ts +++ /dev/null @@ -1,93 +0,0 @@ -// The environment check's agent sign-in row on Orca Cloud. A sandbox holds only placeholders, so its -// own `auth status` probe can't see an Orca-account sign-in: what the person sees comes from the -// account instead (agent-accounts spec, design-squad sweep). Non-cloud recipe VMs keep the host copy. -import type { Translate } from '@/i18n/use-translate' -import type { EnvironmentDoctorCheck } from '../../../../shared/environment-doctor-types' -import { isOrcaCloudAccountAgent } from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' -import { orcaCloudAgentCoverage } from '@/lib/orca-cloud/orca-cloud-agent-accounts-model' -import type { OrcaCloudAgentAccountsState } from '@/lib/orca-cloud/orca-cloud-agent-accounts-store' - -export type CloudAgentCheckCopy = - /** Covered (or not known yet): nothing for the person to do, so no row. */ - { kind: 'hide' } | { kind: 'copy'; message: string; remediation: string } - -const SIGN_IN_CODES = new Set(['agentSignedOut', 'agentSignInTimedOut']) - -/** Null when this isn't a cloud agent sign-in check; the shared copy applies then. */ -export function cloudAgentCheckCopy( - check: EnvironmentDoctorCheck, - accounts: Pick, - t: Translate -): CloudAgentCheckCopy | null { - if (!check.code || !SIGN_IN_CODES.has(check.code)) { - return null - } - const agent = check.params?.agent ?? '' - const id = check.id.startsWith('agent.') ? check.id.slice('agent.'.length) : '' - if (!isOrcaCloudAccountAgent(id)) { - // API-key agents (Gemini, Cursor, Copilot, OpenCode): their keys come from Cloud secrets. - return { - kind: 'copy', - message: t('cloudAgentCheck.keyAgentSignedOut', '{{agent}} isn’t signed in.', { agent }), - remediation: t( - 'cloudAgentCheck.keyAgentFix', - 'Add its API key in Settings → Cloud secrets, or sign in when it starts in this workspace.' - ) - } - } - // Until the account is read, say nothing rather than guess (the Agents row shows the state). - if (accounts.load.kind !== 'ready') { - return { kind: 'hide' } - } - const coverage = orcaCloudAgentCoverage(id, accounts.load.status, accounts.keyKinds[id]) - switch (coverage.kind) { - case 'account': - case 'key': - return { kind: 'hide' } - case 'notSetUp': - return { - kind: 'copy', - message: t('cloudAgentCheck.notSetUp', '{{agent}} isn’t set up for Orca Cloud yet.', { - agent - }), - remediation: t( - 'cloudAgentCheck.notSetUpFix', - 'Set it up once in Settings → Agent accounts. Every cloud workspace uses it.' - ) - } - case 'expired': - return { - kind: 'copy', - message: t('cloudAgentCheck.expired', 'Your {{agent}} sign-in for Orca Cloud expired.', { - agent - }), - remediation: t( - 'cloudAgentCheck.expiredFix', - 'Renew it once in Settings → Agent accounts. Every cloud workspace uses it.' - ) - } - // Nothing to set up: the per-workspace wording of the build sheet's Agents row. - case 'killSwitch': - return { - kind: 'copy', - message: t('cloudAgentCheck.signInHere', '{{agent}} isn’t signed in for this workspace.', { - agent - }), - remediation: t( - 'cloudAgentCheck.pausedFix', - 'Orca account sign-in is paused. Sign in for this workspace; the sign-in stays with this workspace.' - ) - } - case 'unavailable': - return { - kind: 'copy', - message: t('cloudAgentCheck.signInHere', '{{agent}} isn’t signed in for this workspace.', { - agent - }), - remediation: t( - 'cloudAgentCheck.notOfferedFix', - 'Signs in for each cloud workspace for now. Sign in for this workspace; the sign-in stays with this workspace.' - ) - } - } -} diff --git a/src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsMenu.tsx b/src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsMenu.tsx deleted file mode 100644 index d5068943b94..00000000000 --- a/src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsMenu.tsx +++ /dev/null @@ -1,145 +0,0 @@ -// S1-b: the Agents row's ⋯ menu. Source per agent "in this workspace" (the per-workspace override), -// then the way into Settings → Agent accounts. Before S0 it offers the key path instead. -import React from 'react' -import { MoreHorizontal } from 'lucide-react' -import { useTranslate } from '@/i18n/use-translate' -import { Button } from '@/components/ui/button' -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuLabel, - DropdownMenuRadioGroup, - DropdownMenuRadioItem, - DropdownMenuSeparator, - DropdownMenuTrigger -} from '@/components/ui/dropdown-menu' -import { - ORCA_CLOUD_ACCOUNT_AGENTS, - isUsableAgentCredential, - type AgentKeyKind, - type AgentSource, - type AgentSourcesView, - type OrcaCloudAccountAgent, - type OrcaCloudAgentsStatus -} from '../../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' -import { agentName, keyOptionLabel } from '../../settings/agent-accounts/orca-cloud-accounts-copy' - -/** This workspace's Sources: none until the sandbox exists (there is no workspace to name yet). */ -export type WorkspaceSourcesLoad = - | { kind: 'loading' } - | { kind: 'none' } - | { kind: 'failed' } - | { kind: 'ready'; view: AgentSourcesView } - -export type VmBuildCloudAgentsMenuProps = { - /** R2 (nothing set up): the key path and Manage only. */ - offer: boolean - status: OrcaCloudAgentsStatus | null - keyKinds: Record - sources: WorkspaceSourcesLoad - onOpen: () => void - onChoose: (agent: OrcaCloudAccountAgent, source: Exclude) => void - onManage: () => void - onUseKey: () => void -} - -function chosen(view: AgentSourcesView, agent: OrcaCloudAccountAgent): AgentSource { - return view.effective?.[agent]?.source ?? view.defaults[agent] ?? null -} - -export function VmBuildCloudAgentsMenu({ - offer, - status, - keyKinds, - sources, - onOpen, - onChoose, - onManage, - onUseKey -}: VmBuildCloudAgentsMenuProps): React.JSX.Element { - const t = useTranslate() - const view = sources.kind === 'ready' ? sources.view : null - const shared = view?.sharedWorkspace === true - const note = - sources.kind === 'none' - ? t('vmBuildAgents.menu.notYet', 'You can choose once the sandbox is created.') - : sources.kind === 'failed' - ? t('vmBuildAgents.menu.failed', 'Couldn’t read this workspace’s choice.') - : shared - ? t('vmBuildAgents.menu.shared', 'Personal accounts aren’t used in shared workspaces.') - : null - const agents = offer - ? [] - : ORCA_CLOUD_ACCOUNT_AGENTS.filter( - (agent) => - status !== null && - (status.sources.coveredByKey[agent] || - isUsableAgentCredential(status.credentials[agent].state)) - ) - return ( - (open ? onOpen() : undefined)}> - - - - - {agents.map((agent) => { - const usable = - status !== null && - status.credentials.providerEnabled[agent] && - isUsableAgentCredential(status.credentials[agent].state) - const keyKind = status?.sources.coveredByKey[agent] ? (keyKinds[agent] ?? 'team') : null - const disabled = view === null || shared - return ( - - - {t('vmBuildAgents.menu.inThisWorkspace', '{{agent}} in this workspace', { - agent: agentName(agent, t) - })} - - { - if (value === 'sign-in' || value === 'key') { - onChoose(agent, value) - } - }} - > - - {t('vmBuildAgents.menu.yourAccount', 'Your account')} - - {keyKind ? ( - - {keyOptionLabel(keyKind, t)} - - ) : null} - - - - ) - })} - {agents.length > 0 && note ? ( - <> -

{note}

- - - ) : null} - {offer ? ( - - {t('vmBuildAgents.menu.useKey', 'Use an API key instead')} - - ) : null} - - {t('vmBuildAgents.menu.manage', 'Manage agent accounts…')} - -
-
- ) -} diff --git a/src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRow.tsx b/src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRow.tsx deleted file mode 100644 index b61d73246f0..00000000000 --- a/src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRow.tsx +++ /dev/null @@ -1,202 +0,0 @@ -// Live Agents row for an Orca Cloud build. Reads the Orca account once (shared store with S0 and the -// composer), never the sandbox; runs S0's setup inline when nothing is set up (R2), and writes the -// per-workspace Source from the ⋯ menu (S1-b). -import React, { useCallback, useEffect, useRef, useState } from 'react' -import { toast } from 'sonner' -import { useAppStore } from '@/store' -import { useTranslate } from '@/i18n/use-translate' -import { - reloadOrcaCloudAgentAccounts, - runOrcaCloudAgentSetups, - stopOrcaCloudAgentSetups, - useOrcaCloudAgentAccounts -} from '@/lib/orca-cloud/orca-cloud-agent-accounts-store' -import { - buildAgentsRow, - buildAgentsRowDensity, - buildAgentsToSetUp, - type BuildAgentsRowDensity -} from '@/lib/orca-cloud/orca-cloud-build-agents-row' -import { - startVmBuildAgentSignIn, - useVmBuildAgentSignIn -} from '@/lib/agent-sign-in/vm-build-agent-sign-in' -import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation' -import type { - AgentSource, - OrcaCloudAccountAgent -} from '../../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' -import { useCloudAgentSetup } from '../../cloud-agent-setup/use-cloud-agent-setup' -import { cloudSecretRepoKey } from '../../settings/cloud-secrets/cloud-secret-repos' -import { VmBuildAgentSignInRow } from '../VmBuildAgentSignInRow' -import { VmBuildCloudAgentsMenu, type WorkspaceSourcesLoad } from './VmBuildCloudAgentsMenu' -import { VmBuildCloudAgentsRowView, type DesktopKeySave } from './VmBuildCloudAgentsRowView' - -function openSettings(pane: 'accounts' | 'cloud-secrets', sectionId?: string): void { - const store = useAppStore.getState() - store.openSettingsTarget({ pane, repoId: null, ...(sectionId ? { sectionId } : {}) }) - store.openSettingsPage() -} - -export function VmBuildCloudAgentsRow({ - creationId, - entry -}: { - creationId: string - entry: PendingWorktreeCreation -}): React.JSX.Element | null { - const t = useTranslate() - const accounts = useOrcaCloudAgentAccounts() - const environmentId = entry.vmEnvironmentId ?? null - const runtimeEnvironmentId = - environmentId ?? entry.request.ephemeralVmRuntimeEnvironmentId ?? null - const repoKey = useAppStore((s) => { - const repo = s.repos.find((candidate) => candidate.id === entry.request.repoId) - return repo ? cloudSecretRepoKey(repo) : null - }) - const { model: keysModel, saveDesktopKey } = useCloudAgentSetup({ - repo: repoKey, - runtimeEnvironmentId: environmentId - }) - const desktopKeys = keysModel.status === 'ready' ? keysModel.desktopKeys : [] - const model = buildAgentsRow({ accounts, desktopKeys }) - // Decided on the first render and never re-derived (redesign §5, AC-3). - const [density] = useState(() => buildAgentsRowDensity(model)) - - const [desktopKeySave, setDesktopKeySave] = useState({ kind: 'idle' }) - const saveKey = useCallback(() => { - if (model.kind !== 'desktopKey') { - return - } - setDesktopKeySave({ kind: 'saving' }) - void saveDesktopKey(model.key).then((error) => { - setDesktopKeySave(error ? { kind: 'failed', error } : { kind: 'idle' }) - if (!error) { - // The saved key now covers the agent: the row becomes the ready line. - void reloadOrcaCloudAgentAccounts() - } - }) - }, [model, saveDesktopKey]) - - // §5c: a per-workspace sign-in. Pressed before the sandbox answers, it waits for it (R3); each - // press is its own request, so a cancelled one never starts later. - const [signInHere, setSignInHere] = useState<{ - agent: OrcaCloudAccountAgent - request: number - } | null>(null) - const startedRequest = useRef(0) - const nextRequest = useRef(0) - const hostLabel = useAppStore( - (s) => s.runtimeEnvironments.find((environment) => environment.id === environmentId)?.name - ) - useEffect(() => { - if (!signInHere || !environmentId || startedRequest.current === signInHere.request) { - return - } - startedRequest.current = signInHere.request - void startVmBuildAgentSignIn(creationId, environmentId, hostLabel ?? environmentId, [ - signInHere.agent - ]) - }, [signInHere, environmentId, creationId, hostLabel]) - const queued = signInHere !== null && !environmentId - const signInRun = useVmBuildAgentSignIn(creationId, environmentId ?? '') - - const [sources, setSources] = useState({ kind: 'loading' }) - const readSources = useCallback(() => { - const api = window.api.orcaCloudAgents - if (!api || !runtimeEnvironmentId) { - setSources({ kind: 'none' }) - return - } - void api - .workspaceSources({ runtimeEnvironmentId }) - .then((result) => - setSources( - result.ok - ? { kind: 'ready', view: result.value } - : { kind: result.error === 'not_found' ? 'none' : 'failed' } - ) - ) - .catch(() => setSources({ kind: 'failed' })) - }, [runtimeEnvironmentId]) - const choose = useCallback( - (agent: OrcaCloudAccountAgent, source: Exclude) => { - const api = window.api.orcaCloudAgents - if (!api || !runtimeEnvironmentId) { - return - } - void api - .setWorkspaceSource({ agent, source, runtimeEnvironmentId }) - .then((result) => { - if (result.ok) { - // This workspace only; the account-wide defaults the store holds are unchanged. - setSources({ kind: 'ready', view: result.value }) - } else { - toast.error( - t('vmBuildAgents.menu.saveFailed', 'Couldn’t change it. Nothing was changed.') - ) - } - }) - .catch(() => undefined) - }, - [runtimeEnvironmentId, t] - ) - - if (model.kind === 'hidden' || entry.status === 'error') { - return null - } - const api = window.api.orcaCloudAgents - const status = accounts.load.kind === 'ready' ? accounts.load.status : null - const menu = - model.kind === 'loading' || model.kind === 'setup' ? undefined : ( - openSettings('accounts', 'orca-cloud')} - onUseKey={() => openSettings('cloud-secrets')} - /> - ) - return ( - <> - runOrcaCloudAgentSetups(buildAgentsToSetUp(model)), - cancel: (agent) => stopOrcaCloudAgentSetups(agent), - reopen: (agent) => void api?.reopen({ agent }), - copyCodeAndOpen: (agent, code) => { - void window.api.ui - .writeClipboardText(code) - .then(() => toast.success(t('vmBuildAgents.codeCopied', 'Code copied'))) - .catch(() => undefined) - void api?.reopen({ agent }) - }, - dismissFailure: (agent) => { - stopOrcaCloudAgentSetups() - void api?.acknowledge({ agent }) - }, - retryLoad: () => void reloadOrcaCloudAgentAccounts(), - manage: () => openSettings('accounts', 'orca-cloud'), - saveDesktopKey: saveKey, - signInHere: (agent) => { - nextRequest.current += 1 - setSignInHere({ agent, request: nextRequest.current }) - }, - cancelSignInHere: () => setSignInHere(null) - }} - /> - {/* §5c only: the per-workspace sign-in's browser and code steps, once it has started. */} - {model.kind === 'killSwitch' && environmentId && signInRun ? ( - - ) : null} - - ) -} diff --git a/src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRowView.tsx b/src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRowView.tsx deleted file mode 100644 index 82f2d478780..00000000000 --- a/src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRowView.tsx +++ /dev/null @@ -1,375 +0,0 @@ -// The cloud build sheet's Agents row (spec §5b S1; redesign §5). Its height is decided once, at -// mount: 32 px when every agent was ready then, 48 px otherwise. Every later state renders inside -// that height, so the checklist never moves (AC-3: measured layout shift 0). -import React from 'react' -import { CircleCheck, CircleDashed, Info, KeyRound, Loader2, TriangleAlert, X } from 'lucide-react' -import { useTranslate, type Translate } from '@/i18n/use-translate' -import { Button } from '@/components/ui/button' -import { Skeleton } from '@/components/ui/skeleton' -import { cn } from '@/lib/utils' -import type { - BuildAgentsRowDensity, - BuildAgentsRowModel -} from '@/lib/orca-cloud/orca-cloud-build-agents-row' -import type { OrcaCloudAccountAgent } from '../../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' -import type { CloudSecretsErrorCode } from '../../../../../shared/cloud-secrets/cloud-secrets-wire' -import { buildAgentsRowText, deviceHost, readyLine } from './build-agents-row-copy' - -export type DesktopKeySave = - | { kind: 'idle' } - | { kind: 'saving' } - | { kind: 'failed'; error: CloudSecretsErrorCode } - -export type VmBuildCloudAgentsRowActions = { - setUp: () => void - cancel: (agent: OrcaCloudAccountAgent) => void - reopen: (agent: OrcaCloudAccountAgent) => void - copyCodeAndOpen: (agent: OrcaCloudAccountAgent, code: string) => void - dismissFailure: (agent: OrcaCloudAccountAgent) => void - retryLoad: () => void - manage: () => void - saveDesktopKey: () => void - /** §5c only: sign this one workspace in (queued until the sandbox answers). */ - signInHere: (agent: OrcaCloudAccountAgent) => void - cancelSignInHere: () => void -} - -const ICON = 'size-4 shrink-0' -const IDLE_SAVE: DesktopKeySave = { kind: 'idle' } - -function StatusIcon({ model }: { model: BuildAgentsRowModel }): React.JSX.Element { - switch (model.kind) { - case 'ready': - return - case 'setup': - case 'loading': - return - case 'failed': - case 'expired': - case 'error': - return - case 'killSwitch': - return - case 'desktopKey': - return - case 'offer': - case 'hidden': - return - } -} - -function Trailing({ - model, - actions, - desktopKeySave, - queued, - t -}: { - model: BuildAgentsRowModel - actions: VmBuildCloudAgentsRowActions - desktopKeySave: DesktopKeySave - queued: boolean - t: Translate -}): React.ReactNode { - const cancel = (agent: OrcaCloudAccountAgent): React.JSX.Element => ( - - ) - switch (model.kind) { - case 'ready': - return model.expiring ? ( - - ) : null - case 'offer': - return ( - - ) - case 'setup': - switch (model.setup.phase) { - case 'browser': - return ( - <> - {model.setup.canReopen ? ( - - ) : null} - {cancel(model.agent)} - - ) - case 'device': { - const code = model.setup.userCode - return ( - <> - - {cancel(model.agent)} - - ) - } - case 'paste': - return ( - <> - - {cancel(model.agent)} - - ) - case 'preparing': - return cancel(model.agent) - case 'saving': - return null - } - return null - case 'failed': - return ( - <> - - - - ) - case 'expired': - return ( - - ) - case 'killSwitch': - return queued ? ( - - ) : ( - - ) - case 'desktopKey': - return desktopKeySave.kind === 'failed' ? ( - - ) : ( - - ) - case 'error': - return ( - - ) - case 'loading': - case 'hidden': - return null - } -} - -function Lines({ - model, - density, - desktopKeySave, - queued, - t -}: { - model: Exclude - density: BuildAgentsRowDensity - desktopKeySave: DesktopKeySave - queued: boolean - t: Translate -}): React.JSX.Element { - const line = density === 'line' - if (model.kind === 'loading') { - return ( - <> - {t('vmBuildAgents.checking', 'Checking agent sign-in')} - - {line ? null : } - - ) - } - if (model.kind === 'ready') { - const text = readyLine(model, t) - return ( - <> - - {text} - - {line ? null : ( - - {t('vmBuildAgents.readyDetail', 'Every cloud workspace uses it. Nothing to do here.')} - - )} - - ) - } - const text = buildAgentsRowText(model, t) - const detail = - model.kind === 'desktopKey' && desktopKeySave.kind === 'failed' - ? t('vmBuildAgents.keyFailed', 'Couldn’t save {{name}}. Nothing was changed.', { - name: model.key.envName - }) - : model.kind === 'killSwitch' && queued - ? t('vmBuildAgents.queued', 'Opens when the sandbox is ready. Keep Orca open until then.') - : text.detail - const device = model.kind === 'setup' && model.setup.phase === 'device' ? model.setup : null - return ( - <> - - {device ? ( - <> - {t('vmBuildAgents.deviceEnter', 'Enter')}{' '} - - {device.userCode} - {' '} - {t('vmBuildAgents.deviceOn', 'on {{host}}', { - host: deviceHost(device.verificationUrl) - })} - - ) : ( - text.title - )} - {text.tag ? · {text.tag} : null} - - {line ? ( - {detail} - ) : ( - - {detail} - - )} - - ) -} - -export function VmBuildCloudAgentsRowView({ - model, - density, - actions, - menu, - desktopKeySave = IDLE_SAVE, - queued = false -}: { - model: BuildAgentsRowModel - density: BuildAgentsRowDensity - actions: VmBuildCloudAgentsRowActions - /** The ⋯ menu (S1-b); absent while loading or when it has nothing to offer. */ - menu?: React.ReactNode - desktopKeySave?: DesktopKeySave - queued?: boolean -}): React.JSX.Element | null { - const t = useTranslate() - if (model.kind === 'hidden') { - return null - } - // Each state mounts fresh nodes: a reused button or line that changed width would count as a - // layout shift even though the row itself never moves. - const stateKey = [ - model.kind, - model.kind === 'setup' ? model.setup.phase : '', - desktopKeySave.kind, - queued ? 'queued' : '' - ].join(':') - return ( - // A hairline: the agent row is not a build step. -
  • -
    - -
    - -
    - {/* Fixed slots: the actions (184 px, redesign §5), then the ⋯ menu, which never moves. */} -
    - - {model.kind === 'ready' ? ( - - ) : null} -
    -
    {menu}
    -
    -
  • - ) -} diff --git a/src/renderer/src/components/worktree-creation/environment-check-copy.ts b/src/renderer/src/components/worktree-creation/environment-check-copy.ts index 0d0d6e43b7b..09858149bcb 100644 --- a/src/renderer/src/components/worktree-creation/environment-check-copy.ts +++ b/src/renderer/src/components/worktree-creation/environment-check-copy.ts @@ -8,6 +8,13 @@ export function environmentCheckCopy( cloud = false ): { message: string; remediation: string | null } { const p = check.params ?? {} + if (cloud) { + const fatal = cloudFatalCheckMessage(check, t) + if (fatal) { + // The card's body carries the one way forward (Start again), so no per-row fix. + return { message: fatal, remediation: null } + } + } switch (check.code) { case 'gitMissing': return { @@ -78,6 +85,14 @@ export function environmentCheckCopy( } } break + case 'setupNotRun': + return { + message: t( + 'auto.components.worktree.creation.environmentCheckCopy.setupNotRun', + 'Setup script hasn’t run yet.' + ), + remediation: null + } case 'diskVeryLow': case 'diskLow': if (p.free) { @@ -107,6 +122,37 @@ export function environmentCheckCopy( return { message: check.message, remediation: check.remediation ?? null } } +/** Orca Cloud's create-stopping checks in plain words; null for every other check. */ +function cloudFatalCheckMessage(check: EnvironmentDoctorCheck, t: Translate): string | null { + if (check.status !== 'fail') { + return null + } + switch (check.id) { + case 'environment.doctor': + return t( + 'auto.components.worktree.creation.environmentCheckCopy.cloudUnreachable', + 'Orca couldn’t reach the sandbox.' + ) + case 'workspace.path': + return t( + 'auto.components.worktree.creation.environmentCheckCopy.cloudRepoMissing', + 'The repository isn’t in the sandbox.' + ) + case 'git.repo': + return t( + 'auto.components.worktree.creation.environmentCheckCopy.cloudRepoUnreadable', + 'Git can’t read the repository in the sandbox.' + ) + case 'tool.git': + return t( + 'auto.components.worktree.creation.environmentCheckCopy.cloudGitMissing', + 'git isn’t installed in the sandbox.' + ) + default: + return null + } +} + export function environmentCheckBadge( status: EnvironmentDoctorCheck['status'], t: Translate diff --git a/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts b/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts index 023ff4fa8af..5c2337e4097 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts @@ -56,48 +56,43 @@ export function vmBuildFailureCopy( ): { title: string; body: string | null } { switch (failure.kind) { case 'checks': { + if (cloud) { + // Orca Cloud stops only when the sandbox can't hold the workspace at all; warnings open it. + return { + title: t( + 'auto.components.worktree.creation.VmBuildFailureCard.cloudUnusableTitle', + 'This sandbox can’t open your workspace' + ), + body: + failure.sandbox === 'deleted' + ? t( + 'auto.components.worktree.creation.VmBuildFailureCard.cloudUnusableDeletedBody', + 'The sandbox was deleted. Start again to try a new one.' + ) + : t( + 'auto.components.worktree.creation.VmBuildFailureCard.cloudUnusableBody', + 'Start again on a new sandbox, or delete this one.' + ) + } + } // Warnings ride along in the list but don't count as failures in the title. const count = failure.problems.filter((check) => check.status === 'fail').length return { title: count === 0 - ? cloud - ? t( - 'auto.components.worktree.creation.VmBuildFailureCard.checksAttentionTitleCloud', - 'The sandbox is up, but some environment checks need attention' - ) - : t( - 'auto.components.worktree.creation.VmBuildFailureCard.checksAttentionTitleVm', - 'The VM is up, but some environment checks need attention' - ) - : cloud - ? t( - 'auto.components.worktree.creation.VmBuildFailureCard.checksCountTitleCloud', - 'The sandbox is up, but {{count}} environment checks failed', - { - count, - defaultValue_one: 'The sandbox is up, but {{count}} environment check failed' - } - ) - : t( - 'auto.components.worktree.creation.VmBuildFailureCard.checksCountTitleVm', - 'The VM is up, but {{count}} environment checks failed', - { - count, - defaultValue_one: 'The VM is up, but {{count}} environment check failed' - } - ), - body: cloud - ? t( - 'auto.components.worktree.creation.VmBuildFailureCard.checksBodyCloud2', - 'Open it anyway and fix them inside the workspace, or run the checks again after changing your project.', - { - count: failure.problems.length, - defaultValue_one: - 'Open it anyway and fix it inside the workspace, or run the checks again after changing your project.' - } - ) - : null + ? t( + 'auto.components.worktree.creation.VmBuildFailureCard.checksAttentionTitleVm', + 'The VM is up, but some environment checks need attention' + ) + : t( + 'auto.components.worktree.creation.VmBuildFailureCard.checksCountTitleVm', + 'The VM is up, but {{count}} environment checks failed', + { + count, + defaultValue_one: 'The VM is up, but {{count}} environment check failed' + } + ), + body: null } } case 'plan': diff --git a/src/renderer/src/components/worktree-creation/vm-build-failure.ts b/src/renderer/src/components/worktree-creation/vm-build-failure.ts index 11111abe37b..3e1102ec397 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-failure.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-failure.ts @@ -22,7 +22,13 @@ export type VmBuildAccountFailureKind = | 'snapshotMissing' export type VmBuildFailure = - | { kind: 'checks'; problems: readonly EnvironmentDoctorCheck[] } + | { + kind: 'checks' + problems: readonly EnvironmentDoctorCheck[] + /** Orca Cloud: when the unused sandbox sleeps, and what became of it after. */ + sleepsAt?: number + sandbox?: 'sleeping' | 'asleep' | 'deleted' + } | { kind: VmBuildAccountFailureKind } /** The VM did not come up; the raw error is shown only for user-authored recipes. */ | { kind: 'provision'; error: string } @@ -67,7 +73,12 @@ export function classifyVmBuildFailure(args: { const { entry, error, cloud } = args const check = entry.environmentCheck if (check?.status === 'failed') { - return { kind: 'checks', problems: (check.checks ?? []).filter((c) => c.status !== 'pass') } + return { + kind: 'checks', + problems: (check.checks ?? []).filter((c) => c.status !== 'pass'), + ...(check.sleepsAt !== undefined ? { sleepsAt: check.sleepsAt } : {}), + ...(check.sandbox ? { sandbox: check.sandbox } : {}) + } } if (error === null) { return null diff --git a/src/renderer/src/components/worktree-creation/vm-build-sheet-agents-fixtures.tsx b/src/renderer/src/components/worktree-creation/vm-build-sheet-agents-fixtures.tsx deleted file mode 100644 index 9bf1be6578c..00000000000 --- a/src/renderer/src/components/worktree-creation/vm-build-sheet-agents-fixtures.tsx +++ /dev/null @@ -1,238 +0,0 @@ -// The cloud build sheet's Agents row (spec §5b; redesign §5), every state, inside the real sheet. -// Re-exported by VmBuildSheet.fixture.tsx as VmBuildSheet:agents*. -import React, { useEffect, useState } from 'react' -import { defineFixture } from '../../component-fixtures/component-fixture' -import { - buildAgentsRowDensity, - type BuildAgentsRowDensity, - type BuildAgentsRowModel -} from '@/lib/orca-cloud/orca-cloud-build-agents-row' -import type { OrcaCloudAgentsStatus } from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' -import { - CLOUD_LOG, - CLOUD_RECIPE, - entry, - NOW, - seedFixtureRepo, - sheet -} from './vm-build-sheet-fixture-support' -import { - VmBuildCloudAgentsRowView, - type DesktopKeySave, - type VmBuildCloudAgentsRowActions -} from './cloud-agents-row/VmBuildCloudAgentsRowView' -import { VmBuildCloudAgentsMenu } from './cloud-agents-row/VmBuildCloudAgentsMenu' - -const noop = (): void => {} -const ACTIONS: VmBuildCloudAgentsRowActions = { - setUp: noop, - cancel: noop, - reopen: noop, - copyCodeAndOpen: noop, - dismissFailure: noop, - retryLoad: noop, - manage: noop, - saveDesktopKey: noop, - signInHere: noop, - cancelSignInHere: noop -} - -const CLOUD = entry({ provisioningLog: CLOUD_LOG }, CLOUD_RECIPE) - -const STATUS: OrcaCloudAgentsStatus = { - credentials: { - claude: { state: 'active', label: 'nw@stably.ai' }, - codex: { state: 'active', label: 'nw@stably.ai' }, - providerEnabled: { claude: true, codex: true } - }, - sources: { - defaults: { claude: 'sign-in', codex: 'key' }, - effective: { claude: { source: 'sign-in' }, codex: { source: 'key' } }, - coveredByKey: { claude: false, codex: true } - } -} - -function menu(offer: boolean): React.ReactNode { - return ( - - ) -} - -function agents( - model: BuildAgentsRowModel, - options: { - density?: BuildAgentsRowDensity - desktopKeySave?: DesktopKeySave - queued?: boolean - interact?: (frame: HTMLElement) => Promise - } = {} -) { - const hasMenu = model.kind !== 'loading' && model.kind !== 'setup' - return defineFixture({ - width: 760, - setup: () => seedFixtureRepo(), - interact: options.interact, - render: () => - sheet(CLOUD, null, NOW, undefined, { - cloudAgentsRow: ( - - ) - }) - }) -} - -const ACCOUNT_BOTH: BuildAgentsRowModel = { - kind: 'ready', - covered: [ - { agent: 'claude', via: 'account' }, - { agent: 'codex', via: 'account' } - ], - label: 'nw@stably.ai', - expiring: null -} - -export const agentsAccount = agents(ACCOUNT_BOTH) -export const agentsAccountAndTeamKey = agents({ - kind: 'ready', - covered: [ - { agent: 'claude', via: 'account' }, - { agent: 'codex', via: 'team' } - ], - label: null, - expiring: null -}) -export const agentsTeamKeyOnly = agents({ - kind: 'ready', - covered: [{ agent: 'codex', via: 'team' }], - label: null, - expiring: null -}) -export const agentsNotSetUp = agents({ kind: 'offer', agents: ['claude', 'codex'] }) -export const agentsDesktopKeyOnly = agents({ - kind: 'desktopKey', - key: { id: 'k1', agent: 'claude', envName: 'ANTHROPIC_API_KEY', hint: 'x4Qa' } -}) -export const agentsDesktopKeyFailed = agents( - { - kind: 'desktopKey', - key: { id: 'k1', agent: 'claude', envName: 'ANTHROPIC_API_KEY', hint: 'x4Qa' } - }, - { desktopKeySave: { kind: 'failed', error: 'unavailable' } } -) -export const agentsKillSwitch = agents({ kind: 'killSwitch', agent: 'claude', reason: 'paused' }) -/** Flag off on this server: same sign-in-here action, never worded as paused. */ -export const agentsNotOffered = agents({ - kind: 'killSwitch', - agent: 'claude', - reason: 'notOffered' -}) -export const agentsKillSwitchQueued = agents( - { kind: 'killSwitch', agent: 'claude', reason: 'paused' }, - { queued: true } -) -export const agentsLoading = agents({ kind: 'loading' }) -export const agentsSettingUpClaude = agents({ - kind: 'setup', - agent: 'claude', - setup: { phase: 'browser', startedAt: NOW - 8_000, canReopen: true }, - step: 1, - of: 2 -}) -export const agentsSettingUpCodexDevice = agents({ - kind: 'setup', - agent: 'codex', - setup: { - phase: 'device', - startedAt: NOW - 12_000, - userCode: 'K7QF-2M9D', - verificationUrl: 'https://auth.openai.com/codex/device', - expiresAt: NOW + 600_000 - }, - step: 2, - of: 2 -}) -export const agentsSetupFailed = agents({ kind: 'failed', agent: 'claude', error: 'denied' }) -export const agentsExpired = agents({ kind: 'expired', agent: 'claude' }) -/** R1c: mounted ready, then within its renewal window: stays a line with a quiet Renew. */ -export const agentsExpiringLine = agents({ ...ACCOUNT_BOTH, expiring: 'claude' }) -/** R1b: mounted as a line, then expired: stays a line. */ -export const agentsExpiredLine = agents({ kind: 'expired', agent: 'claude' }, { density: 'line' }) -export const agentsError = agents({ kind: 'error' }) -/** S1-b: the ⋯ menu open, Source per agent in this workspace. */ -export const agentsMenu = agents( - { - kind: 'ready', - covered: [ - { agent: 'claude', via: 'account' }, - { agent: 'codex', via: 'team' } - ], - label: null, - expiring: null - }, - { - interact: async (frame) => { - const trigger = frame.querySelector('[aria-label="Agent sign-in options"]') - trigger?.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 })) - await new Promise((resolve) => setTimeout(resolve, 100)) - } - } -) - -/** - * For the layout-shift test: the row mounts in `start` and moves through states on a window event - * (`orca-fixture-agents`, detail = a model), the way the store and main move it in the app. - */ -// The test sends well-formed models; this only keeps the event's `any` out of the row. -function isRowModel(value: unknown): value is BuildAgentsRowModel { - return typeof value === 'object' && value !== null && 'kind' in value -} - -function SteppedRow({ start }: { start: BuildAgentsRowModel }): React.JSX.Element { - const [model, setModel] = useState(start) - const [density] = useState(() => buildAgentsRowDensity(start)) - useEffect(() => { - const onStep = (event: Event): void => { - if (event instanceof CustomEvent && isRowModel(event.detail)) { - setModel(event.detail) - } - } - window.addEventListener('orca-fixture-agents', onStep) - return () => window.removeEventListener('orca-fixture-agents', onStep) - }, []) - return ( - - ) -} - -function stepped(start: BuildAgentsRowModel) { - return defineFixture({ - width: 760, - setup: () => seedFixtureRepo(), - render: () => - sheet(CLOUD, null, NOW, undefined, { cloudAgentsRow: }) - }) -} - -export const agentsSteppedFromLoading = stepped({ kind: 'loading' }) -export const agentsSteppedFromReady = stepped(ACCOUNT_BOTH) diff --git a/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx b/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx index f78cfb9365d..51dba4f9da5 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx +++ b/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx @@ -7,8 +7,6 @@ import { formatElapsedTime } from './worktree-creation-clock' import type { VmBuildStepTimings } from './vm-build-timing' import { useAppStore } from '@/store' import type { Repo } from '../../../../shared/repo-types' -import { IDLE_ORCA_CLOUD_AGENT_SETUPS } from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' -import { setOrcaCloudAgentAccountsStateForTest } from '@/lib/orca-cloud/orca-cloud-agent-accounts-store' export const LOG_LINES = [ 'Creating sandbox from snapshot snap_7f2c…', @@ -58,7 +56,7 @@ export function sheet( error: string | null, now: number, agentSignInRow?: React.ReactNode, - options: { cloudAgentsRow?: React.ReactNode; secretsRow?: React.ReactNode } = {} + options: { secretsRow?: React.ReactNode } = {} ) { return (
    @@ -75,7 +73,6 @@ export function sheet( onEditRecipe={() => {}} agentSignInRow={agentSignInRow} stepTimings={FIXTURE_STEP_TIMINGS} - cloudAgentsRow={options.cloudAgentsRow ?? null} secretsRow={options.secretsRow ?? null} />
    @@ -119,26 +116,3 @@ export const CLOUD_FAILED_LOG = [ ].join('\n') export const FAILED_LOG = `${LOG}\nError: snapshot snap_7f2c not found` -/** - * The Orca account as the cloud build sheet reads it, fixed for a fixture so nothing calls the bridge - * (the harness's catch-all mock resolves to undefined): Claude set up through the account, or not. - */ -export function seedCloudAgentAccounts(claude: 'active' | 'none'): void { - setOrcaCloudAgentAccountsStateForTest({ - load: { - kind: 'ready', - status: { - credentials: { - claude: { state: claude }, - codex: { state: 'none' }, - providerEnabled: { claude: true, codex: true }, - providerState: { claude: 'on', codex: 'on' } - }, - sources: { defaults: {}, coveredByKey: { claude: false, codex: false } } - } - }, - setups: IDLE_ORCA_CLOUD_AGENT_SETUPS, - keyKinds: { claude: null, codex: null }, - queue: { agents: [], index: 0 } - }) -} diff --git a/src/renderer/src/lib/ephemeral-vm-environment-check-decision.ts b/src/renderer/src/lib/ephemeral-vm-environment-check-decision.ts index f06ef5cc4cf..ad0c8a95283 100644 --- a/src/renderer/src/lib/ephemeral-vm-environment-check-decision.ts +++ b/src/renderer/src/lib/ephemeral-vm-environment-check-decision.ts @@ -1,4 +1,5 @@ -export type VmEnvironmentCheckDecision = 'open-anyway' | 'retry' | 'cancel' +/** `restart`: delete this sandbox and start the create over on a fresh one. */ +export type VmEnvironmentCheckDecision = 'open-anyway' | 'retry' | 'restart' | 'cancel' // Dependency-free so the pending-creation store can stop a VM build's checks when the user dismisses it. const waiting = new Map void>() @@ -23,6 +24,11 @@ export function awaitVmEnvironmentCheckDecision( }) } +/** True while a paused create is waiting on the user (false once it gave up on its own). */ +export function isAwaitingVmEnvironmentCheckDecision(creationId: string): boolean { + return waiting.has(creationId) +} + export function resolveVmEnvironmentCheckDecision( creationId: string, decision: VmEnvironmentCheckDecision diff --git a/src/renderer/src/lib/ephemeral-vm-environment-check-triage.ts b/src/renderer/src/lib/ephemeral-vm-environment-check-triage.ts new file mode 100644 index 00000000000..c2e64885036 --- /dev/null +++ b/src/renderer/src/lib/ephemeral-vm-environment-check-triage.ts @@ -0,0 +1,84 @@ +// Which environment-check results stop an Orca Cloud create, and which only become a notice in the +// opened workspace. Peers (Conductor, Capy, Codex, Cursor) open the workspace and surface problems +// there; only a sandbox nobody can work in should hold the create on the build sheet. +import type { EnvironmentDoctorCheck } from '../../../shared/environment-doctor-types' + +/** Failed checks that make the sandbox unusable: no checkout, no git, or orcad never answered. */ +const FATAL_CHECK_IDS: ReadonlySet = new Set([ + // The doctor call itself could not finish: orcad is unreachable. + 'environment.doctor', + // The repository isn't where the workspace would open. + 'workspace.path', + // Git can't read the checkout. + 'git.repo', + 'tool.git' +]) + +export type CloudSetupNoticeKind = 'push' | 'setup' | 'check' + +/** One problem the opened workspace shows as a single dismissible line. */ +export type CloudSetupNotice = { + /** Stable per problem, so a dismissal or a re-check replaces the same line. */ + id: string + kind: CloudSetupNoticeKind + check: EnvironmentDoctorCheck +} + +export type CloudEnvironmentCheckTriage = { + /** Fatal failures: the create waits on the user (and the sandbox sleeps if they don't come back). */ + fatal: EnvironmentDoctorCheck[] + /** Everything else worth one line in the opened workspace. */ + notices: CloudSetupNotice[] +} + +export function isFatalEnvironmentCheck(check: EnvironmentDoctorCheck): boolean { + return check.status === 'fail' && FATAL_CHECK_IDS.has(check.id) +} + +/** + * Splits an Orca Cloud doctor result. Agent sign-in is never a check here: the account's agent row + * and the in-workspace sign-in strip own it. A setup script the create is about to run is not news. + */ +export function triageCloudEnvironmentChecks( + checks: readonly EnvironmentDoctorCheck[], + options: { setupRunsOnCreate: boolean } +): CloudEnvironmentCheckTriage { + const fatal: EnvironmentDoctorCheck[] = [] + const notices: CloudSetupNotice[] = [] + for (const check of checks) { + if (check.status === 'pass') { + continue + } + if (isFatalEnvironmentCheck(check)) { + fatal.push(check) + continue + } + const kind = noticeKind(check, options) + if (kind) { + notices.push({ id: check.id, kind, check }) + } + } + return { fatal, notices } +} + +function noticeKind( + check: EnvironmentDoctorCheck, + options: { setupRunsOnCreate: boolean } +): CloudSetupNoticeKind | null { + if (check.category === 'agents') { + return null + } + switch (check.id) { + case 'git.push': + // "No commits yet" is a warn with nothing to do; only a refused push needs access. + return check.status === 'fail' ? 'push' : null + case 'setup.run': + return options.setupRunsOnCreate ? null : 'setup' + // Advice for the repository, not a problem with this workspace. + case 'setup.script': + case 'git.remote': + return null + default: + return 'check' + } +} diff --git a/src/renderer/src/lib/ephemeral-vm-environment-check.ts b/src/renderer/src/lib/ephemeral-vm-environment-check.ts index 6e1738935c1..06bd91ec048 100644 --- a/src/renderer/src/lib/ephemeral-vm-environment-check.ts +++ b/src/renderer/src/lib/ephemeral-vm-environment-check.ts @@ -7,6 +7,7 @@ import type { EnvironmentDoctorCheck, EnvironmentDoctorResult } from '../../../shared/environment-doctor-types' +import type { ExecutionHostId } from '../../../shared/execution-host' import { ENVIRONMENT_DOCTOR_METHOD, ENVIRONMENT_DOCTOR_RUNTIME_CAPABILITY @@ -14,13 +15,31 @@ import { import { awaitVmEnvironmentCheckDecision, beginVmEnvironmentCheckRun, - endVmEnvironmentCheckRun + endVmEnvironmentCheckRun, + resolveVmEnvironmentCheckDecision, + type VmEnvironmentCheckDecision } from './ephemeral-vm-environment-check-decision' +import { triageCloudEnvironmentChecks } from './ephemeral-vm-environment-check-triage' +import { setCloudSetupNotices } from './orca-cloud/cloud-setup-notices-store' // Two 20s network probes, local probes and a login-shell PATH refresh, with headroom for a slow VM. const ENVIRONMENT_CHECK_TIMEOUT_MS = 150_000 // A paused build holds a running VM; give up after an hour so a forgotten one stops billing. const PAUSE_TIMEOUT_MS = 60 * 60_000 +/** Orca Cloud: a create stopped on a fatal check puts its sandbox to sleep after this long unused. */ +export const BLOCKED_SANDBOX_SLEEP_MS = 5 * 60_000 + +/** What the Orca Cloud gate needs beyond the VM: who to show notices to, and what runs on create. */ +export type CloudEnvironmentCheckContext = { + runtimeId: string | undefined + /** The create runs the setup script itself, so "hasn't run yet" is not news. */ + setupRunsOnCreate: boolean + repoId: string | null + hostId: ExecutionHostId | null + repoUrl: string | null +} + +export type VmEnvironmentCheckGateResult = 'proceed' | 'stop' | 'restart' async function supportsEnvironmentChecks(environmentId: string): Promise { try { @@ -35,18 +54,18 @@ async function supportsEnvironmentChecks(environmentId: string): Promise { - const signal = beginVmEnvironmentCheckRun(creationId) + const signal = creationId ? beginVmEnvironmentCheckRun(creationId) : undefined try { return await callRuntimeRpc( { kind: 'environment', environmentId }, ENVIRONMENT_DOCTOR_METHOD, { path }, - { timeoutMs: ENVIRONMENT_CHECK_TIMEOUT_MS, signal } + { timeoutMs: ENVIRONMENT_CHECK_TIMEOUT_MS, ...(signal ? { signal } : {}) } ) } catch (error) { const unreachable: EnvironmentDoctorCheck = { @@ -61,15 +80,12 @@ async function runVmEnvironmentCheck( } return { worktreePath: path, ok: false, checks: [unreachable] } } finally { - endVmEnvironmentCheckRun(creationId, signal) + if (creationId && signal) { + endVmEnvironmentCheckRun(creationId, signal) + } } } -/** - * Check the freshly provisioned VM before creating the workspace. A failure pauses the create on the - * build sheet; it resolves true to continue (passed, unsupported, or "Open anyway") and false to cancel. - * Nothing here tears the VM down: only cancelling does, so a degraded open keeps the VM that provisioned. - */ /** The user decided: fold the wait into pausedMs so the clock resumes where it stopped. */ export function resumeBuildClock(creationId: string, now = Date.now()): void { const state = useAppStore.getState() @@ -84,31 +100,94 @@ export function resumeBuildClock(creationId: string, now = Date.now()): void { }) } +/** + * After BLOCKED_SANDBOX_SLEEP_MS unused, a blocked create's sandbox sleeps. No workspace owns it yet, + * so the window's idle sleep never would. If it can't sleep, it is deleted: it must not keep billing. + */ +function scheduleBlockedSandboxSleep( + creationId: string, + runtimeId: string | undefined, + failedAt: number +): () => void { + const timer = setTimeout(() => { + const state = useAppStore.getState() + const entry = state.pendingWorktreeCreations[creationId] + const check = entry?.environmentCheck + if (check?.status !== 'failed' || check.finishedAt !== failedAt || check.sandbox) { + return + } + const mark = (sandbox: 'sleeping' | 'asleep' | 'deleted'): void => { + const current = useAppStore.getState().pendingWorktreeCreations[creationId]?.environmentCheck + if (current?.status === 'failed' && current.finishedAt === failedAt) { + useAppStore.getState().updatePendingWorktreeCreation(creationId, { + environmentCheck: { ...current, sandbox } + }) + } + } + const suspend = runtimeId ? window.api?.ephemeralVm?.suspendRuntime : undefined + if (!suspend || !runtimeId) { + mark('deleted') + resolveVmEnvironmentCheckDecision(creationId, 'cancel') + return + } + mark('sleeping') + void suspend({ runtimeId }) + .catch((error: unknown) => ({ + ok: false, + error: error instanceof Error ? error.message : String(error) + })) + .then((result) => { + if (result.ok) { + mark('asleep') + return + } + console.warn('[orca-cloud] Could not put a blocked sandbox to sleep:', result.error) + mark('deleted') + resolveVmEnvironmentCheckDecision(creationId, 'cancel') + }) + }, BLOCKED_SANDBOX_SLEEP_MS) + return () => clearTimeout(timer) +} + +/** + * Check the freshly provisioned VM before creating the workspace. Orca Cloud stops only on a fatal + * check (no checkout, no git, orcad unreachable); everything else opens the workspace and shows + * there as a notice. Recipe VMs pause on any failed check. Resolves `proceed` to continue (passed, + * unsupported, or "Open anyway"), `stop` to cancel, `restart` to cancel and start on a new sandbox. + * Nothing here tears the VM down: only the caller does, so a degraded open keeps the VM. + */ export async function gateVmCreateOnEnvironmentCheck( creationId: string, environmentId: string, - path: string -): Promise { + path: string, + cloud?: CloudEnvironmentCheckContext +): Promise { const update = useAppStore.getState().updatePendingWorktreeCreation const isPending = (): boolean => Boolean(useAppStore.getState().pendingWorktreeCreations[creationId]) if (!(await supportsEnvironmentChecks(environmentId))) { const at = Date.now() update(creationId, { environmentCheck: { status: 'skipped', startedAt: at, finishedAt: at } }) - return isPending() + return isPending() ? 'proceed' : 'stop' } for (;;) { // A dismiss during the probe or the previous pause registered nothing to abort. if (!isPending()) { - return false + return 'stop' } const startedAt = Date.now() update(creationId, { environmentCheck: { status: 'running', startedAt } }) const result = await runVmEnvironmentCheck(creationId, environmentId, path) if (!isPending()) { - return false + return 'stop' } - if (result.ok) { + const triage = cloud + ? triageCloudEnvironmentChecks(result.checks, { + setupRunsOnCreate: cloud.setupRunsOnCreate + }) + : null + const blocking = triage ? triage.fatal.length > 0 : !result.ok + if (!blocking) { update(creationId, { environmentCheck: { status: 'passed', @@ -117,32 +196,64 @@ export async function gateVmCreateOnEnvironmentCheck( finishedAt: Date.now() } }) - return true + if (cloud && triage) { + setCloudSetupNotices({ + environmentId, + path: result.worktreePath || path, + repoId: cloud.repoId, + hostId: cloud.hostId, + repoUrl: cloud.repoUrl, + notices: triage.notices + }) + } + return 'proceed' } const failedAt = Date.now() update(creationId, { environmentCheck: { status: 'failed', - checks: result.checks, + // Orca Cloud lists only what stopped it; the rest would show in the workspace. + checks: triage ? triage.fatal : result.checks, startedAt, - finishedAt: failedAt + finishedAt: failedAt, + ...(cloud ? { sleepsAt: failedAt + BLOCKED_SANDBOX_SLEEP_MS } : {}) }, waitingSince: failedAt }) if (useAppStore.getState().activePendingCreationId !== creationId) { // The paused build keeps its VM running, so a background create must say it needs the user. toast.error( - translate( - 'auto.lib.ephemeralVmEnvironmentCheck.backgroundFailed', - 'Environment checks failed for a new VM workspace. Open it in the sidebar to continue.' - ) + cloud + ? translate( + 'auto.lib.ephemeralVmEnvironmentCheck.backgroundFailedCloud', + 'A new cloud workspace couldn’t start. Open it in the sidebar to continue.' + ) + : translate( + 'auto.lib.ephemeralVmEnvironmentCheck.backgroundFailed', + 'Environment checks failed for a new VM workspace. Open it in the sidebar to continue.' + ) ) } - const decision = await awaitVmEnvironmentCheckDecision(creationId, PAUSE_TIMEOUT_MS) + const cancelSleep = cloud + ? scheduleBlockedSandboxSleep(creationId, cloud.runtimeId, failedAt) + : () => {} + let decision: VmEnvironmentCheckDecision + try { + // Orca Cloud has its own (shorter) sleep; recipe VMs give up after an hour. + decision = await awaitVmEnvironmentCheckDecision( + creationId, + cloud ? undefined : PAUSE_TIMEOUT_MS + ) + } finally { + cancelSleep() + } if (decision === 'cancel' || !isPending()) { - return false + return 'stop' } resumeBuildClock(creationId) + if (decision === 'restart') { + return 'restart' + } if (decision === 'open-anyway') { toast.warning( translate( @@ -150,7 +261,7 @@ export async function gateVmCreateOnEnvironmentCheck( 'Creating the workspace on a VM whose environment checks failed.' ) ) - return true + return 'proceed' } } } diff --git a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts b/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts index a4b0b3399c1..3a5586a6edc 100644 --- a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts +++ b/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts @@ -7,6 +7,7 @@ import type { Repo } from '../../../shared/repo-types' import { translate } from '@/i18n/i18n' import { cleanupFailedEphemeralVmWorkspace } from '@/lib/ephemeral-vm-failed-create-cleanup' import { gateVmCreateOnEnvironmentCheck } from '@/lib/ephemeral-vm-environment-check' +import { orcaCloudGitHubRepoUrl } from '@/lib/orca-cloud/use-orca-cloud-repo-access' import { showVmBuildFailureToast } from '@/components/worktree-creation/vm-build-failure-toast' import { ephemeralVmErrorText } from '@/lib/ephemeral-vm-error-copy' import { selectWorktreeCreationSurfaceShown } from '@/lib/workspace/creation/worktree-creation-surface' @@ -147,16 +148,36 @@ async function prepareEphemeralVmRecipeRequest( path: preparedTarget.setup.repo.path } } - const proceed = - Boolean(useAppStore.getState().pendingWorktreeCreations[creationId]) && - (!preparedTarget.environmentId || - (await gateVmCreateOnEnvironmentCheck( - creationId, - preparedTarget.environmentId, - preparedTarget.setup.repo.path - ))) - if (!proceed) { + const gate = !useAppStore.getState().pendingWorktreeCreations[creationId] + ? 'stop' + : !preparedTarget.environmentId + ? 'proceed' + : await gateVmCreateOnEnvironmentCheck( + creationId, + preparedTarget.environmentId, + preparedTarget.setup.repo.path, + recipe.provider === 'orca-cloud' + ? { + runtimeId: preparedTarget.runtimeId, + // `inherit` follows the project's setup policy, which runs it on create. + setupRunsOnCreate: request.setupDecision !== 'skip', + repoId: preparedTarget.setup.repo.id, + hostId: preparedTarget.setup.setup.hostId, + repoUrl: orcaCloudGitHubRepoUrl( + useAppStore.getState().repos.find((repo) => repo.id === recipe.sourceRepoId) + ) + } + : undefined + ) + if (gate !== 'proceed') { await cleanupEphemeralVmRuntimeForFailedCreate(preparedRequest, creationId) + if (gate === 'restart' && useAppStore.getState().pendingWorktreeCreations[creationId]) { + // Lazy: the creation flow imports this module. + const { retryBackgroundWorktreeCreation } = await import( + '@/lib/workspace/creation/worktree-creation-flow' + ) + retryBackgroundWorktreeCreation(creationId) + } return null } useAppStore.getState().updatePendingWorktreeCreation(creationId, { diff --git a/src/renderer/src/lib/orca-cloud/cloud-setup-notice-actions.ts b/src/renderer/src/lib/orca-cloud/cloud-setup-notice-actions.ts new file mode 100644 index 00000000000..049c68e0b35 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-setup-notice-actions.ts @@ -0,0 +1,115 @@ +// What the in-workspace setup notices do: install the GitHub App so a read-only repository can +// push (then re-check on their own once GitHub's install webhook binds it), and run a setup script +// the create skipped. +import { toast } from 'sonner' +import { useAppStore } from '@/store' +import { translate } from '@/i18n/i18n' +import { checkRuntimeHooks } from '@/runtime/repo-hooks/runtime-hooks-client' +import { runVmEnvironmentCheck } from '@/lib/ephemeral-vm-environment-check' +import { cloudWorkspaceApi } from './orca-cloud-workspace-store' +import { fetchOrcaCloudRepoAccess, invalidateOrcaCloudRepoAccess } from './use-orca-cloud-repo-access' +import { + dismissCloudSetupNotice, + getCloudSetupNoticesRecord, + setCloudSetupNotices, + type CloudSetupNoticesRecord +} from './cloud-setup-notices-store' + +/** owner/repo from https://github.com//. */ +export function repoSlug(repoUrl: string): string { + return repoUrl.replace(/^https:\/\/github\.com\//, '') +} + +export function repoOwner(repoUrl: string): string { + return repoSlug(repoUrl).split('/')[0] ?? '' +} + +/** GitHub's install page, preselecting this repository (#246). False when it couldn't open. */ +export async function openOrcaGitHubAppInstall(repoUrl: string): Promise { + const result = await cloudWorkspaceApi() + ?.connectGitHub({ repoUrl }) + .catch(() => null) + if (!result?.ok) { + toast.error( + translate( + 'orcaCloud.setupNotices.installFailed', + 'Couldn’t open GitHub. Check your connection and try again.' + ) + ) + return false + } + return true +} + +/** + * Once the App's installation covers the repository (the install webhook bound it), runs the + * sandbox's push check again and drops the notice when the push is now authorized. Returns + * 'granted' when the push works, 'waiting' while GitHub hasn't confirmed yet, 'refused' when the + * installation landed but the sandbox still can't push. + */ +export async function recheckCloudPushAccess( + environmentId: string +): Promise<'granted' | 'waiting' | 'refused'> { + const record = getCloudSetupNoticesRecord(environmentId) + if (!record?.repoUrl || !record.notices.some((notice) => notice.kind === 'push')) { + return 'granted' + } + invalidateOrcaCloudRepoAccess(record.repoUrl) + const access = await fetchOrcaCloudRepoAccess(record.repoUrl, { force: true }) + if (access?.access !== 'granted') { + return 'waiting' + } + const result = await runVmEnvironmentCheck(null, environmentId, record.path) + const push = result.checks.find((check) => check.id === 'git.push') + const current = getCloudSetupNoticesRecord(environmentId) + if (!push || push.status === 'fail') { + return 'refused' + } + if (current) { + setCloudSetupNotices({ + ...current, + notices: current.notices.filter((notice) => notice.kind !== 'push') + }) + } + toast.success( + translate('orcaCloud.setupNotices.pushReady', 'Orca Cloud can push to {{repo}} now.', { + repo: repoSlug(record.repoUrl) + }) + ) + return 'granted' +} + +/** + * Runs the project's setup script in a new "Setup" terminal of the workspace, as a create with + * setup on would have. The script is read from the sandbox's own orca.yaml, never from here. + */ +export async function runCloudSetupScript( + workspaceId: string, + record: Pick, + noticeId: string +): Promise { + let script: string | undefined + try { + if (record.hostId && record.repoId) { + const hooks = await checkRuntimeHooks(record.hostId, record.repoId) + script = hooks.hooks?.scripts?.setup?.trim() || undefined + } + } catch (error) { + console.warn('[orca-cloud] Could not read the setup script:', error) + } + if (!script) { + toast.error( + translate( + 'orcaCloud.setupNotices.setupMissing', + 'Couldn’t read the setup script from orca.yaml in this workspace.' + ) + ) + return + } + const store = useAppStore.getState() + const tab = store.createTab(workspaceId, undefined, undefined, { + pendingStartup: { command: script } + }) + store.setTabCustomTitle(tab.id, translate('worktree.setupTerminalTitle', 'Setup')) + dismissCloudSetupNotice(record.environmentId, noticeId) +} diff --git a/src/renderer/src/lib/orca-cloud/cloud-setup-notices-store.ts b/src/renderer/src/lib/orca-cloud/cloud-setup-notices-store.ts new file mode 100644 index 00000000000..5d1710fce3c --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-setup-notices-store.ts @@ -0,0 +1,90 @@ +// Non-fatal environment-check results for an opened Orca Cloud workspace, keyed by the sandbox's +// runtime environment. The build sheet no longer stops on them (env-check-ux); the workspace shows +// each as one dismissible line with one action. Session-only: a restart re-checks nothing, and +// what was worth saying once is not re-raised. +import { useSyncExternalStore } from 'react' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { CloudSetupNotice } from '../ephemeral-vm-environment-check-triage' + +export type CloudSetupNoticesRecord = { + environmentId: string + /** The checkout the doctor ran on, for re-checks. */ + path: string + repoId: string | null + hostId: ExecutionHostId | null + /** https://github.com//, or null when the project isn't on GitHub. */ + repoUrl: string | null + notices: readonly CloudSetupNotice[] +} + +type Snapshot = { + records: Readonly> + dismissed: ReadonlySet +} + +let snapshot: Snapshot = { records: {}, dismissed: new Set() } +const listeners = new Set<() => void>() + +function emit(next: Snapshot): void { + snapshot = next + for (const listener of listeners) { + listener() + } +} + +function subscribe(listener: () => void): () => void { + listeners.add(listener) + return () => listeners.delete(listener) +} + +function dismissalKey(environmentId: string, noticeId: string): string { + return `${environmentId}\0${noticeId}` +} + +/** Replaces what an environment shows; an empty list clears it. */ +export function setCloudSetupNotices(record: CloudSetupNoticesRecord): void { + const records = { ...snapshot.records } + if (record.notices.length === 0) { + delete records[record.environmentId] + } else { + records[record.environmentId] = record + } + emit({ ...snapshot, records }) +} + +export function dismissCloudSetupNotice(environmentId: string, noticeId: string): void { + const dismissed = new Set(snapshot.dismissed) + dismissed.add(dismissalKey(environmentId, noticeId)) + emit({ ...snapshot, dismissed }) +} + +export function getCloudSetupNoticesRecord( + environmentId: string +): CloudSetupNoticesRecord | undefined { + return snapshot.records[environmentId] +} + +/** Visible notices first by importance: push access, then setup, then the rest. */ +export function visibleCloudSetupNotices( + state: Snapshot, + environmentId: string | undefined +): readonly CloudSetupNotice[] { + const record = environmentId ? state.records[environmentId] : undefined + if (!record) { + return [] + } + const order = { push: 0, setup: 1, check: 2 } as const + return record.notices + .filter((notice) => !state.dismissed.has(dismissalKey(record.environmentId, notice.id))) + .slice() + .sort((a, b) => order[a.kind] - order[b.kind]) +} + +export function useCloudSetupNoticesSnapshot(): Snapshot { + return useSyncExternalStore(subscribe, () => snapshot) +} + +/** Test seam. */ +export function resetCloudSetupNotices(): void { + emit({ records: {}, dismissed: new Set() }) +} diff --git a/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts b/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts index 69555fda09f..f5aa479f88a 100644 --- a/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts +++ b/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts @@ -153,6 +153,10 @@ export type PendingVmEnvironmentCheck = { checks?: readonly EnvironmentDoctorCheck[] startedAt?: number finishedAt?: number + /** Orca Cloud, failed: when the unused sandbox is put to sleep so it stops spending hours. */ + sleepsAt?: number + /** Orca Cloud, failed: the sandbox after that timer (absent while it still runs). */ + sandbox?: 'sleeping' | 'asleep' | 'deleted' } /** Session-only creation status drives sidebar/panel and vanishes on reload; completed worktrees reconcile normally. request owns display fields and retry intent so they cannot drift. */ From a86a8d6850af4d8699ba42df0399cc0ada91bdd9 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 19:07:15 -0800 Subject: [PATCH 028/149] =?UTF-8?q?feat(cloud-create):=20automatic=20envir?= =?UTF-8?q?onments=20=E2=80=94=20repos=20come=20prebuilt=20after=20the=20f?= =?UTF-8?q?irst=20create?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The first create of a repo that no environment of the account lists makes a default environment for it (just the repo, cloned blobless, no install script) and builds it in the background with the existing environment build pipeline (EnvironmentBuildRunner). Later creates boot from its active build and fetch only what changed, in the background, shown as 'Update repository' with git's real progress. - environments.kind 'org' | 'auto' + last_used_at (migration 0049, applied to dev); an admin's edit adopts an auto environment; an admin environment listing the repo always wins - auto environments unused for 14 days are deleted with their snapshots (cron); per account only - golden refresh, staleness, pruning and the warm pool apply as for any environment - the caller's machine size stands for auto environments; an explicit other region skips them - AUTO_ENVIRONMENTS=off disables it - desktop: feature repo-update, 'Update repository' / 'Fetching changes…' / sidebar 'Updating the repository…' Measured on dev (stablyai/orca, staging OWNER): before 6 s to ready + 58 s clone; the background build took 79 s; after, ready in 6.6-8.7 s with the repo current 0.7 s later (7.4-9.4 s total). --- .../image/env/environment-build.sh | 5 +- .../image/env/workspace-prelude.sh | 75 +++++--- .../image/vm-scripts.generated.ts | 4 +- .../migrations/0049_auto_environments.sql | 8 + .../sandbox-control/src/auto-environments.ts | 168 ++++++++++++++++++ .../apps/sandbox-control/src/clone-status.ts | 3 +- cloud/apps/sandbox-control/src/env.ts | 2 + .../sandbox-control/src/environment-builds.ts | 5 +- .../sandbox-control/src/environment-routes.ts | 11 +- .../apps/sandbox-control/src/environments.ts | 31 +++- cloud/apps/sandbox-control/src/index.ts | 22 ++- cloud/apps/sandbox-control/src/lifecycle.ts | 47 ++++- cloud/apps/sandbox-control/src/wire.ts | 12 +- .../test/auto-environments.test.ts | 126 +++++++++++++ cloud/apps/sandbox-control/test/harness.ts | 2 + .../environment-provider-driver.ts | 2 + .../hosted-sandbox-control-plane-client.ts | 3 +- .../hosted-sandbox-driver.test.ts | 18 ++ .../hosted-sandbox/hosted-sandbox-driver.ts | 13 +- .../hosted-sandbox/hosted-sandbox-recipe.ts | 2 +- .../worktree-creation/VmBuildSheet.tsx | 2 +- .../worktree-creation/orca-cloud-build-log.ts | 5 + .../worktree-creation/vm-build-sheet-copy.ts | 10 +- .../worktree-creation/vm-build-steps.test.ts | 22 +++ .../worktree-creation/vm-build-steps.ts | 13 +- src/renderer/src/i18n/locales/en.json | 10 +- .../orca-cloud/orca-cloud-clone-progress.ts | 15 +- .../creation/pending-worktree-creation.ts | 4 +- .../hosted-sandbox/hosted-sandbox-wire.ts | 6 +- 29 files changed, 570 insertions(+), 76 deletions(-) create mode 100644 cloud/apps/sandbox-control/migrations/0049_auto_environments.sql create mode 100644 cloud/apps/sandbox-control/src/auto-environments.ts create mode 100644 cloud/apps/sandbox-control/test/auto-environments.test.ts diff --git a/cloud/apps/sandbox-control/image/env/environment-build.sh b/cloud/apps/sandbox-control/image/env/environment-build.sh index 24f4f10c053..595ab970c83 100644 --- a/cloud/apps/sandbox-control/image/env/environment-build.sh +++ b/cloud/apps/sandbox-control/image/env/environment-build.sh @@ -5,7 +5,7 @@ # Everything printed here streams live to the desktop build log. # # Env from the control plane (validated there): ORCA_BUILD_REPOS (`||| -# ` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER, plus +# ` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER and ORCA_CLONE_FILTER, plus # the org secrets the environment names. `::orca-step:: ` lines mark progress. # Exit codes: 10 clone, 20 install script, 30 recording the result. set -uo pipefail @@ -39,7 +39,8 @@ while IFS='|' read -r url branch dir header; do echo "Cloning $url${branch:+ ($branch)}" rm -rf -- "$dest" # The clone's own error shows only when it really failed (an empty repo is recovered below). - if ! git "${git_auth[@]}" clone --quiet ${branch:+--branch "$branch"} -- "$url" "$dest" 2>"$OUT/clone.err"; then + # ORCA_CLONE_FILTER (automatic environments: blob:none) keeps history and trees, not every old blob. + if ! git "${git_auth[@]}" clone --quiet ${ORCA_CLONE_FILTER:+--filter="$ORCA_CLONE_FILTER"} ${branch:+--branch "$branch"} -- "$url" "$dest" 2>"$OUT/clone.err"; then refs=0 git "${git_auth[@]}" ls-remote --exit-code -- "$url" >/dev/null 2>&1 || refs=$? if [ -n "$branch" ] && [ "$refs" -eq 2 ]; then diff --git a/cloud/apps/sandbox-control/image/env/workspace-prelude.sh b/cloud/apps/sandbox-control/image/env/workspace-prelude.sh index 4653e949148..3f8787c7247 100644 --- a/cloud/apps/sandbox-control/image/env/workspace-prelude.sh +++ b/cloud/apps/sandbox-control/image/env/workspace-prelude.sh @@ -68,9 +68,62 @@ clone_failure_reason() { fi } + +# Brings a prebuilt checkout (environment build) up to date: fetches only what changed on the target +# branch (ORCA_REPO_REF, else the build's branch) and checks it out. A branch the remote doesn't have +# yet (a new workspace branch) starts from the build's branch, freshly fetched. Progress goes to stderr. +update_repo() { + local base target status + base="$(git -C "$P" symbolic-ref --quiet --short HEAD 2>/dev/null || true)" + target="${ref:-$base}" + [ -n "$target" ] || return 0 + timeout "$CLONE_TIMEOUT_S" git ${auth[@]+"${auth[@]}"} -C "$P" fetch --progress origin "+refs/heads/$target:refs/remotes/origin/$target" + status=$? + if [ "$status" -eq 0 ]; then + # -f: the install may have rewritten tracked files (a lockfile); the branch's version wins. + git -C "$P" checkout --quiet -f -B "$target" "origin/$target" -- + return $? + fi + [ "$status" -eq 124 ] && return 124 + { [ -n "$base" ] && [ "$base" != "$target" ]; } || return "$status" + timeout "$CLONE_TIMEOUT_S" git ${auth[@]+"${auth[@]}"} -C "$P" fetch --progress origin "+refs/heads/$base:refs/remotes/origin/$base" || return $? + git -C "$P" checkout --quiet -f -B "$target" "origin/$base" -- +} + +# Runs clone_repo or update_repo detached (own session, no inherited stdio), so the start command +# returns while it runs; $CLONE_DIR/state reads running, then done or "failed ". +run_detached() { + echo running >"$CLONE_DIR/state" + : >"$CLONE_DIR/progress.log" + export -f clone_repo update_repo first_commit clone_failure_reason + export P CLONE_DIR CLONE_TIMEOUT_S ORCA_REPO_URL ref + export ORCA_PRELUDE_AUTH="${ORCA_GIT_EXTRAHEADER:-}" ORCA_PRELUDE_STEP="$1" + setsid bash -c ' + auth=() + [ -n "$ORCA_PRELUDE_AUTH" ] && auth=(-c "http.https://github.com/.extraheader=$ORCA_PRELUDE_AUTH") + unset ORCA_PRELUDE_AUTH + "$ORCA_PRELUDE_STEP" >>"$CLONE_DIR/progress.log" 2>&1 + status=$? + if [ "$status" -eq 0 ]; then + echo done >"$CLONE_DIR/state.next" + elif [ "$ORCA_PRELUDE_STEP" = update_repo ]; then + # Not fatal: the build'"'"'s checkout is there, just older. The status says so; the create goes on. + echo "done stale" >"$CLONE_DIR/state.next" + else + echo "failed $(clone_failure_reason "$status" "$CLONE_DIR/progress.log")" >"$CLONE_DIR/state.next" + fi + mv -f "$CLONE_DIR/state.next" "$CLONE_DIR/state" + ' /dev/null 2>&1 & +} + if [ ! -e "$P" ] && [ -n "${ORCA_ENV_REPO_DIR:-}" ] && [ -d "$ROOT/$ORCA_ENV_REPO_DIR/.git" ]; then ln -s "$ROOT/$ORCA_ENV_REPO_DIR" "$P" - if [ -n "$ref" ] && [ "$(git -C "$P" symbolic-ref --quiet --short HEAD 2>/dev/null)" != "$ref" ]; then + if [ "${ORCA_CLONE_BACKGROUND:-}" = 1 ]; then + # The desktop shows this as "Update repository" (GET /v1/sandboxes/:id/clone): fetch what changed + # since the build, in the background. A failure leaves the build's commit, which still opens. + mkdir -p "$CLONE_DIR" + run_detached update_repo + elif [ -n "$ref" ] && [ "$(git -C "$P" symbolic-ref --quiet --short HEAD 2>/dev/null)" != "$ref" ]; then if timeout 60 git "${auth[@]}" -C "$P" fetch --quiet origin "+refs/heads/$ref:refs/remotes/origin/$ref"; then # -f: the install may have rewritten tracked files (a lockfile); the branch's version wins. git -C "$P" checkout --quiet -f -B "$ref" "origin/$ref" -- || @@ -83,25 +136,7 @@ if [ ! -e "$P" ] && [ -n "${ORCA_ENV_REPO_DIR:-}" ] && [ -d "$ROOT/$ORCA_ENV_REP elif [ ! -e "$P" ] && [ -n "${ORCA_REPO_URL:-}" ]; then mkdir -p "$P" "$CLONE_DIR" if [ "${ORCA_CLONE_BACKGROUND:-}" = 1 ]; then - echo running >"$CLONE_DIR/state" - : >"$CLONE_DIR/progress.log" - # Detached (own session, no inherited stdio): the start command returns while this runs. - export -f clone_repo first_commit clone_failure_reason - export P CLONE_DIR CLONE_TIMEOUT_S ORCA_REPO_URL ref - export ORCA_PRELUDE_AUTH="${ORCA_GIT_EXTRAHEADER:-}" - setsid bash -c ' - auth=() - [ -n "$ORCA_PRELUDE_AUTH" ] && auth=(-c "http.https://github.com/.extraheader=$ORCA_PRELUDE_AUTH") - unset ORCA_PRELUDE_AUTH - clone_repo >>"$CLONE_DIR/progress.log" 2>&1 - status=$? - if [ "$status" -eq 0 ]; then - echo done >"$CLONE_DIR/state.next" - else - echo "failed $(clone_failure_reason "$status" "$CLONE_DIR/progress.log")" >"$CLONE_DIR/state.next" - fi - mv -f "$CLONE_DIR/state.next" "$CLONE_DIR/state" - ' /dev/null 2>&1 & + run_detached clone_repo else clone_repo 2>"$CLONE_DIR/progress.log" || exit 1 fi diff --git a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts index 58c4fb576bd..5aa062f32a8 100644 --- a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts +++ b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts @@ -5,6 +5,6 @@ export const MANIFEST: GoldenImageManifest = {"imageVersion":"2026-11-09.1","ima export const PROVISION_SCRIPT: string = "#!/usr/bin/env bash\n# Runs once inside the build sandbox (as the sandbox user, with sudo). Installs the pinned orcad\n# bundle, agent CLIs and Orca's VM entry points into /opt/orca, then smoke-tests orcad.\n# Inputs (env, from image/golden-image.manifest.json via build-golden-image.ts):\n# ORCAD_BUNDLE_URL ORCAD_BUNDLE_SHA256 [GH_VERSION GH_SHA256] [CHROME_VERSION CHROME_SHA256]\n# AGENT_NPM_PACKAGES (space-separated\n# name@version), [CURSOR_AGENT_VERSION CURSOR_AGENT_SHA256], [NOVNC_VERSION NOVNC_SHA256 WEBSOCKIFY_VERSION WEBSOCKIFY_SHA256] and ORCA_VM_SCRIPT_ (base64) for each /opt/orca/bin entry point.\nset -euo pipefail\nORCA_HOME=/opt/orca\nlog() { printf '[golden] %s\\n' \"$*\" >&2; }\n\nsudo mkdir -p \"$ORCA_HOME/bin\" \"$ORCA_HOME/runtime\" \"$ORCA_HOME/tools\"\nsudo chown -R \"$(id -u):$(id -g)\" \"$ORCA_HOME\"\n\nlog 'system packages'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n # Sandbox egress is TLS-only: plain-http apt mirrors time out at runtime (W2, wake on SSH).\n sudo sed -i 's#http://#https://#g' /etc/apt/sources.list.d/*.sources /etc/apt/sources.list 2>/dev/null || true\n sudo DEBIAN_FRONTEND=noninteractive apt-get update -qq\n # Developer basics agents expect (Conductor parity): rg, tmux, vim, git-lfs alongside the build tools.\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n ca-certificates curl git git-lfs jq ripgrep tmux vim-nox less openssh-client openssh-server build-essential python3 \\\n unzip zip util-linux procps >/dev/null\n git lfs install --system --skip-repo >/dev/null\n # sshd is started on demand by the wake-on-SSH bridge (key-only, loopback); never at boot.\n sudo systemctl disable ssh.service ssh.socket >/dev/null 2>&1 || true\n # A locked password field (\"!\") makes sshd refuse even key logins; '*' = no password, not locked.\n sudo usermod -p '*' \"$(id -un)\"\nelif command -v dnf >/dev/null; then\n sudo dnf install -y -q ca-certificates curl-minimal git git-lfs jq tmux vim-enhanced gcc gcc-c++ make python3 \\\n unzip util-linux procps-ng >/dev/null\nelse\n log 'no supported package manager'; exit 1\nfi\n\n# Managed images have no /vercel/sandbox; the project lives at /vercel/sandbox/project on every image.\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" /vercel/sandbox\n\nfetch_verified() { # url sha256 dest\n curl -fsSL --retry 3 -o \"$3\" \"$1\"\n echo \"$2 $3\" | sha256sum -c --quiet -\n}\n\nlog 'orcad bundle'\nbundle=\"$(mktemp -d)/orcad.tgz\"\nfetch_verified \"$ORCAD_BUNDLE_URL\" \"$ORCAD_BUNDLE_SHA256\" \"$bundle\"\ntar -xzf \"$bundle\" -C \"$ORCA_HOME/runtime\"\nrm -rf \"$(dirname \"$bundle\")\"\n# Release tarballs (orca-server-linux-*) may nest the server; normalize to runtime/orcad + runtime/runtimes.\nif [ ! -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\" ]; then\n server=\"$(find \"$ORCA_HOME/runtime\" -name orcad-server.js -type f | head -n 1)\"\n [ -n \"$server\" ] || { log 'bundle has no orcad-server.js'; exit 1; }\n root=\"$(dirname \"$(dirname \"$server\")\")\"\n ln -sfn \"$(dirname \"$server\")\" \"$ORCA_HOME/runtime/orcad\"\n [ -d \"$ORCA_HOME/runtime/runtimes\" ] || ln -sfn \"$root/runtimes\" \"$ORCA_HOME/runtime/runtimes\"\nfi\ntest -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ntest -x \"$node\"\n\nif [ -n \"${GH_VERSION:-}\" ]; then\n log \"gh $GH_VERSION\"\n fetch_verified \"https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_amd64.tar.gz\" \\\n \"$GH_SHA256\" /tmp/gh.tgz\n tar -xzf /tmp/gh.tgz -C /tmp\n mkdir -p \"$ORCA_HOME/tools/bin\"\n install -m 0755 \"/tmp/gh_${GH_VERSION}_linux_amd64/bin/gh\" \"$ORCA_HOME/tools/bin/gh\"\n rm -rf /tmp/gh.tgz \"/tmp/gh_${GH_VERSION}_linux_amd64\"\nfi\n\nif [ -n \"${CHROME_VERSION:-}\" ] && command -v apt-get >/dev/null; then\n log \"google-chrome $CHROME_VERSION (headless browser for agents and Orca browser automation)\"\n deb=\"$(mktemp -d)/chrome.deb\"\n fetch_verified \"https://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-stable/google-chrome-stable_${CHROME_VERSION}_amd64.deb\" \\\n \"$CHROME_SHA256\" \"$deb\"\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \"$deb\" >/dev/null\n rm -rf \"$(dirname \"$deb\")\"\n # The .deb adds Google's apt source; the image stays pinned, so drop it.\n sudo rm -f /etc/apt/sources.list.d/google-chrome.list /etc/cron.daily/google-chrome\n google-chrome --headless=new --no-sandbox --disable-gpu --dump-dom 'data:text/html,

    ok

    ' 2>/dev/null | grep -q '

    ok

    '\nfi\n\nlog 'agent CLIs'\n# The image's system npm installs them; agents later run on whatever node orcad puts on PATH.\n# shellcheck disable=SC2086 # word splitting is the package list\nnpm install --global --no-fund --no-audit --prefix \"$ORCA_HOME/tools\" $AGENT_NPM_PACKAGES\n# opencode-ai installs every linux-x64 build variant (~205 MB each) and hardlinks the one its\n# postinstall picked into bin/opencode.exe, a standalone binary: drop the variants it did not pick.\nopencode_pkg=\"$ORCA_HOME/tools/lib/node_modules/opencode-ai\"\nif [ -x \"$opencode_pkg/bin/opencode.exe\" ]; then\n picked=\"$(stat -c %i \"$opencode_pkg/bin/opencode.exe\")\"\n for variant in \"$opencode_pkg\"/node_modules/opencode-*; do\n [ -d \"$variant\" ] || continue\n [ \"$(stat -c %i \"$variant/bin/opencode\" 2>/dev/null)\" = \"$picked\" ] || rm -rf \"$variant\"\n done\n \"$opencode_pkg/bin/opencode.exe\" --version >/dev/null\nfi\n\n# Copilot CLI prefers GH_TOKEN/GITHUB_TOKEN over the user's own /login. In Orca Cloud those hold the\n# workspace's GitHub App placeholder, which Copilot can't use (\"Resource not accessible by\n# integration\"), so a signed-in user could never get past it. The wrapper drops them for Copilot\n# only (COPILOT_GITHUB_TOKEN, a /login and BYOK still work), unless BYOK is set up, which needs no\n# GitHub sign-in and keeps them so `gh` in Copilot's shell still works.\ncopilot_loader=\"$ORCA_HOME/tools/lib/node_modules/@github/copilot/npm-loader.js\"\nif [ -f \"$copilot_loader\" ]; then\n rm -f \"$ORCA_HOME/tools/bin/copilot\"\n cat >\"$ORCA_HOME/tools/bin/copilot\" </dev/null; fi\ndone\n\nif [ -n \"${CURSOR_AGENT_VERSION:-}\" ]; then\n # Cursor's agent CLI is a pinned tarball (its own node + bundle), not an npm package. The image\n # copy lives under /opt/orca (root-owned) and its release channel is set to \"static\" at boot\n # (orca-sandbox-env), so it never replaces itself mid-session.\n log \"cursor-agent $CURSOR_AGENT_VERSION\"\n tgz=\"$(mktemp -d)/cursor-agent.tgz\"\n fetch_verified \"https://downloads.cursor.com/lab/${CURSOR_AGENT_VERSION}/linux/x64/agent-cli-package.tar.gz\" \\\n \"$CURSOR_AGENT_SHA256\" \"$tgz\"\n rm -rf \"$ORCA_HOME/tools/cursor-agent\"\n mkdir -p \"$ORCA_HOME/tools/cursor-agent\" \"$ORCA_HOME/tools/bin\"\n tar --strip-components=1 -xzf \"$tgz\" -C \"$ORCA_HOME/tools/cursor-agent\"\n rm -rf \"$(dirname \"$tgz\")\"\n ln -sfn ../cursor-agent/cursor-agent \"$ORCA_HOME/tools/bin/cursor-agent\"\n \"$ORCA_HOME/tools/bin/cursor-agent\" --version >/dev/null\nfi\n\nlog 'openssh server (binaries only)'\n# For `orca ssh`: an unprivileged sshd on loopback (see vm/orca-sshd). Only the server binaries,\n# kept out of /usr: the packages would pull in systemd units, SELinux policy (~38 MB on AL2023) and\n# system host keys a user-run sshd never uses. Its libraries are already in the base image, except\n# tcp-wrappers on Ubuntu.\nmkdir -p \"$ORCA_HOME/openssh\"\npkgs=\"$(mktemp -d)\"\nif command -v dnf >/dev/null; then\n sudo dnf install -y -q --setopt=install_weak_deps=False cpio >/dev/null\n sudo dnf install -y -q --downloadonly --downloaddir=\"$pkgs\" openssh-server >/dev/null\n (cd \"$pkgs\" && rpm2cpio openssh-server-[0-9]*.rpm | cpio -idm --quiet)\n sudo dnf clean all -q >/dev/null 2>&1 || true\n libexec=\"$pkgs/usr/libexec/openssh\"\nelse\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends libwrap0 >/dev/null\n (cd \"$pkgs\" && apt-get download -qq openssh-server openssh-sftp-server >/dev/null)\n for deb in \"$pkgs\"/*.deb; do dpkg-deb -x \"$deb\" \"$pkgs\"; done\n libexec=\"$pkgs/usr/lib/openssh\"\nfi\ninstall -m 0755 \"$pkgs/usr/sbin/sshd\" \"$libexec/sshd-session\" \"$libexec/sftp-server\" \"$ORCA_HOME/openssh/\"\n# OpenSSH 10 splits authentication into its own binary.\nif [ -x \"$libexec/sshd-auth\" ]; then install -m 0755 \"$libexec/sshd-auth\" \"$ORCA_HOME/openssh/\"; fi\nsudo rm -rf \"$pkgs\"\n\"$ORCA_HOME/openssh/sshd\" -V 2>&1 | head -n 1 >&2 || true\n# sshd refuses a locked account ('!') even for key logins; '*' unlocks it with no usable password.\nsudo usermod -p '*' \"$(id -un)\"\n\ninstall_desktop() {\n # Remote desktop (~80 MB): Xvnc + openbox + xterm from the distro, noVNC + websockify pinned\n # tarballs. Only orca-desktop-start runs it, on demand; nothing starts at boot. Every step says\n # `|| return 1`: errexit does not apply inside an `if` condition.\n command -v apt-get >/dev/null || { log 'remote desktop: apt only'; return 1; }\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n tigervnc-standalone-server tigervnc-tools openbox xterm x11-xserver-utils >/dev/null || return 1\n local tmp dir=\"$ORCA_HOME/desktop\"\n tmp=\"$(mktemp -d)\" || return 1\n fetch_verified \"https://github.com/novnc/noVNC/archive/refs/tags/v${NOVNC_VERSION}.tar.gz\" \\\n \"$NOVNC_SHA256\" \"$tmp/novnc.tgz\" || return 1\n fetch_verified \"https://github.com/novnc/websockify/archive/refs/tags/v${WEBSOCKIFY_VERSION}.tar.gz\" \\\n \"$WEBSOCKIFY_SHA256\" \"$tmp/websockify.tgz\" || return 1\n rm -rf \"$dir\" && mkdir -p \"$dir/novnc\" \"$dir/websockify\" || return 1\n tar -xzf \"$tmp/novnc.tgz\" -C \"$dir/novnc\" --strip-components 1 || return 1\n tar -xzf \"$tmp/websockify.tgz\" -C \"$dir/websockify\" --strip-components 1 || return 1\n # Orca tab fit: title \"Remote desktop\" (Xvnc's -desktop name), no noVNC favicon, control bar on\n # the right (away from Orca's sidebar edge); a stale per-boot password ends the session with one\n # plain message instead of a reconnect loop. \"Unencrypted\" is noVNC's view of plain ws:// to\n # localhost; the hop to the sandbox rides the end-to-end encrypted runtime connection.\n sed -i -e 's/document.title = e.detail.name + \" - \" + PAGE_TITLE;/document.title = e.detail.name;/' \\\n -e \"s/WebUtil.readSetting('controlbar_pos') === 'right'/WebUtil.readSetting('controlbar_pos', 'right') === 'right'/\" \\\n -e 's/securityFailed(e) {/securityFailed(e) { UI.inhibitReconnect = true; UI.showStatus(\"This remote desktop session ended. Reopen it from the workspace menu.\", \"error\"); return;/' \\\n -e 's/_(\"Connected (unencrypted) to \")/_(\"Connected to \")/' \\\n \"$dir/novnc/app/ui.js\" || return 1\n sed -i '/rel=\"icon\"/d; /rel=\"apple-touch-icon\"/d' \"$dir/novnc/vnc.html\" || return 1\n rm -rf \"$tmp\"\n PYTHONPATH=\"$dir/websockify\" python3 -P -c 'import websockify' >/dev/null || return 1\n command -v Xvnc >/dev/null && test -s \"$dir/novnc/vnc.html\"\n}\ndesktop=false\nif [ -n \"${NOVNC_VERSION:-}\" ]; then\n log 'remote desktop'\n # Optional: a failure leaves an image without the desktop, never a failed build.\n if install_desktop; then\n desktop=true\n else\n log 'remote desktop install failed; continuing without it'\n rm -rf \"$ORCA_HOME/desktop\"\n fi\nfi\n\nlog 'Orca entry points'\nfor name in orca-sandbox-start orca-sandbox-drain orca-sandbox-env orca-session-env.sh orca-env orca-egress-probe orca-image-wipe orca-agent-signout orca-share-proxy orca-sshd orca-ssh-keys orca-desktop-start orca-desktop-proxy orca-desktop-page.js orca-sandbox-grant orca-sandbox-revoke orca-sandbox-members orca-sandbox-read-snapshot orca-read-snapshot.cjs orca-git-as orca-git-identity orcad-boot git; do\n var=\"ORCA_VM_SCRIPT_${name//[-.]/_}\"\n printf '%s' \"${!var}\" | base64 -d >\"$ORCA_HOME/bin/$name\"\n chmod 0755 \"$ORCA_HOME/bin/$name\"\ndone\n# The orca CLI (agents drive worktrees, terminals and the browser through it) talks to this VM's orcad.\ncli=\"$(find \"$ORCA_HOME/runtime\" -name orca-cli.cjs -type f | head -n 1)\"\nif [ -n \"$cli\" ]; then\n printf '#!/usr/bin/env bash\\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\\nexec \"%s\" \"%s\" \"$@\"\\n' \"$node\" \"$cli\" >\"$ORCA_HOME/bin/orca\"\n chmod 0755 \"$ORCA_HOME/bin/orca\"\nelse\n log 'bundle has no orca CLI (orca-cli.cjs): agents will not have `orca` on PATH'\nfi\n# The image's node/npm/npx live only on the build command's PATH; append them so agents (codex's\n# `env node` shebang) and stdio MCP servers launched with npx resolve them in Orca's login shells.\nsystem_node=\"$(command -v npx || command -v node || true)\"\nif [ -z \"$system_node\" ]; then\n echo 'no node/npx on the build PATH' >&2\n exit 1\nfi\nprintf 'export PATH=%s/tools/bin:%s/bin:$PATH:%s\\n' \"$ORCA_HOME\" \"$ORCA_HOME\" \"$(dirname \"$system_node\")\" |\n sudo tee /etc/profile.d/orca.sh >/dev/null\n# Every new shell (login or not: /etc/bashrc sources profile.d) re-reads the session env file.\nsudo install -m 0644 \"$ORCA_HOME/bin/orca-session-env.sh\" /etc/profile.d/zz-orca-session-env.sh\nif [ -f /etc/bash.bashrc ]; then\n # Ubuntu's bash.bashrc does not source profile.d for non-login interactive shells (AL2023's bashrc does).\n grep -q zz-orca-session-env /etc/bash.bashrc ||\n echo '[ -r /etc/profile.d/zz-orca-session-env.sh ] && . /etc/profile.d/zz-orca-session-env.sh' | sudo tee -a /etc/bash.bashrc >/dev/null\nfi\nif [ -f /etc/bash.bashrc ]; then\n # Ubuntu: zsh reads /etc/zsh/zshenv for every shell, so new zsh shells match bash (`orca-env` covers\n # shells that were already open).\n sudo install -d -m 0755 /etc/zsh\n sudo touch /etc/zsh/zshenv\n grep -q zz-orca-session-env /etc/zsh/zshenv ||\n echo '[ -r /etc/profile.d/zz-orca-session-env.sh ] && . /etc/profile.d/zz-orca-session-env.sh' | sudo tee -a /etc/zsh/zshenv >/dev/null\nfi\nsudo chown -R root:root \"$ORCA_HOME\"\n\nlog 'smoke: orcad reaches ready on loopback (and warms the V8 compile cache: ~1.5 s off every boot)'\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/compile-cache\"\n# The runtime is root-owned, so its startup-qualified marker lives here. The smoke run leaves one,\n# so every boot from the image skips orcad's disposable startup preflight (~0.6 s of wake).\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/startup-qualification\"\nsmoke_data=\"$(mktemp -d)\"\n# orcad-boot also writes orcad's full code cache as the smoke run exits (~0.3 s more off every boot).\nNODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_USER_DATA=\"$smoke_data\" timeout 60 \"$node\" \"$ORCA_HOME/bin/orcad-boot\" \\\n --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" --write-code-cache \"$ORCA_HOME/runtime/orcad/orcad-server.js\" \\\n --port 6799 --json >/tmp/orcad-smoke.out 2>/tmp/orcad-smoke.err &\nsmoke_pid=$!\nready=0\nfor _ in $(seq 1 600); do\n if grep -q '\"orca_server_ready\"' /tmp/orcad-smoke.out 2>/dev/null; then ready=1; break; fi\n sleep 0.1\ndone\n# orcad writes the marker just after readiness; best effort, a boot without one only re-qualifies.\nfor _ in $(seq 1 30); do\n [ \"$ready\" = 1 ] && [ ! -s \"$ORCA_HOME/startup-qualification/.orcad-startup-qualified\" ] || break\n sleep 0.1\ndone\nkill \"$smoke_pid\" 2>/dev/null || true\nwait \"$smoke_pid\" 2>/dev/null || true\nrm -rf \"$smoke_data\" /tmp/orcad-smoke.out\nif [ \"$ready\" != 1 ]; then\n tail -n 40 /tmp/orcad-smoke.err >&2; exit 1\nfi\n# Best effort: without it every boot loads orcad as before.\nif [ -s \"$ORCA_HOME/compile-cache/orcad-server.v8\" ]; then\n log \"orcad code cache: $(stat -c %s \"$ORCA_HOME/compile-cache/orcad-server.v8\") bytes\"\nelse\n log 'orcad code cache was not written; boots compile orcad without it'\n grep 'orcad-boot' /tmp/orcad-smoke.err >&2 || true\nfi\n\nlog 'versions'\nversions=\"{}\"\nfor bin in claude codex opencode gemini cursor-agent copilot gh; do\n if [ -x \"$ORCA_HOME/tools/bin/$bin\" ]; then\n v=\"$(\"$ORCA_HOME/tools/bin/$bin\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$bin\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\nfor sys in rg vim git-lfs google-chrome; do\n if command -v \"$sys\" >/dev/null; then\n v=\"$(\"$sys\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$sys\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\ncommand -v tmux >/dev/null && versions=\"$(jq -c --arg v \"$(tmux -V)\" '. + {tmux: $v}' <<<\"$versions\")\"\n[ -x \"$ORCA_HOME/bin/orca\" ] && versions=\"$(jq -c '. + {orca: \"bundled\"}' <<<\"$versions\")\"\njq -c --arg node \"$(\"$node\" --version)\" --arg disk \"$(df -h / | awk 'NR==2{print $2}')\" \\\n --argjson desktop \"$desktop\" '{node: $node, disk: $disk, tools: ., desktop: $desktop}' <<<\"$versions\"\n" export const VM_SCRIPT_SOURCES: BuildInputs['vmScripts'] = {"orca-sandbox-start":"#!/usr/bin/env bash\n# Starts orcad for this boot (idempotent) and prints its recipe line:\n# {\"schemaVersion\":1,\"pairingCode\":\"orca://pair?...\",\"projectRoot\":\"/vercel/sandbox/project\"}\n# Env from the control plane: ORCA_SANDBOX_ID, ORCA_PUBLIC_WSS, optional ORCA_REPO_URL/ORCA_REPO_REF,\n# ORCA_GITHUB_PLACEHOLDER, ORCA_SECRET_ENV (`NAME=` lines: org/personal/repo secrets for\n# orcad and its agents), ORCA_SHARE_PROXY_KEY (this session's share-link proxy key, port 6769).\n# Never prints anything else on stdout's last line.\n# With ORCA_READY_VIA=file it prints {\"schemaVersion\":1,\"readyFile\":\"\"} instead and the control\n# plane reads the offer with the files API: the provider keeps command stdout as logs, not files.\n# With ORCA_READY_KEY too (64 hex chars, this call's key; env is not kept) the pointer also carries\n# \"sealedOffer\": \".\", which saves that round trip.\n# Managed env for every process orcad starts: ORCA_IS_CLOUD=1, ORCA_SANDBOX_ID, ORCA_ROOT_PATH,\n# ORCA_WORKTREE_PATH, ORCA_WORKSPACE_PATH, ORCA_WORKSPACE_NAME, ORCA_DEFAULT_BRANCH, ORCA_PORT and the\n# CONDUCTOR_* names imported Conductor scripts read.\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nPROJECT=/vercel/sandbox/project\nmkdir -p \"$STATE\"\n# Only print_ready uses the key; nothing this script starts inherits it.\nready_key=\"${ORCA_READY_KEY:-}\"\nunset ORCA_READY_KEY\n[[ \"$ready_key\" =~ ^[0-9a-f]{64}$ ]] || ready_key=''\nexec 9>\"$STATE/start.lock\"\nflock -w 60 9\n# Background children close fd 9 (`9>&-`): an orcad that inherited it would hold the lock for its whole\n# life and every later start (resume of a running sandbox, a retried create) would wait out the 60 s.\n\n# orcad only lists a project once a client registers it (the desktop does on connect), so API, MCP,\n# routine and phone sessions saw no repo. Register the workspace project at every start, in the\n# background (ready is not delayed); `repo add` of an already-registered path is a no-op error.\nregister_project() {\n [ -x \"$ORCA_HOME/bin/orca\" ] && [ -d \"$PROJECT\" ] || return 0\n local kind=() name=()\n [ -e \"$PROJECT/.git\" ] || kind=(--kind folder)\n # The checkout lives at .../project; name it after the repository (owner/name.git -> name).\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n local base=\"${ORCA_REPO_URL%/}\"\n base=\"${base##*/}\"\n base=\"${base%.git}\"\n [ -n \"$base\" ] && name=(--display-name \"$base\")\n fi\n setsid \"$ORCA_HOME/bin/orca\" repo add --path \"$PROJECT\" \"${kind[@]}\" \"${name[@]}\" --json \\\n >\"$STATE/register-project.log\" 2>&1 &- &\n}\n\nprint_ready() {\n if [ \"${ORCA_READY_VIA:-}\" = file ]; then\n local sealed='' iv\n if [ -n \"$ready_key\" ] && command -v openssl >/dev/null; then\n iv=\"$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')\"\n # Best effort: without it the control plane reads the file, as before.\n sealed=\"$(tail -n 1 \"$STATE/ready.json\" | openssl enc -aes-256-ctr -K \"$ready_key\" -iv \"$iv\" -nosalt | base64 -w0)\" &&\n sealed=\"$iv.$sealed\" || sealed=''\n fi\n printf '{\"schemaVersion\":1,\"readyFile\":\"%s\"%s}\\n' \"$STATE/ready.json\" \"${sealed:+,\\\"sealedOffer\\\":\\\"$sealed\\\"}\"\n else\n tail -n 1 \"$STATE/ready.json\"\n fi\n}\n# Command stderr is kept by the provider: strip injected values and credential shapes from log tails.\nredact_log() {\n local text kv value\n text=\"$(cat)\"\n for kv in ${agent_env[@]+\"${agent_env[@]}\"}; do\n value=\"${kv#*=}\"\n if [ \"${#value}\" -ge 8 ]; then\n text=\"${text//\"$value\"/[REDACTED]}\"\n fi\n done\n printf '%s\\n' \"$text\" | sed -E \\\n -e 's#orca://[^[:space:]]+#[REDACTED_PAIRING]#g' \\\n -e 's#(gh[pousr]_|github_pat_|sk-|vc[kpiar]_)[A-Za-z0-9._-]{16,}#[REDACTED_TOKEN]#g' \\\n -e 's#eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}#[REDACTED_JWT]#g' \\\n -e 's#(Authorization|authorization):[[:space:]]*[A-Za-z]+[[:space:]]+[^[:space:]]+#\\1: [REDACTED]#g'\n}\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n\n# Share-link proxy (port 6769): answers only requests the control plane signed with this session's\n# key, so its public route is useless on its own. The key goes in on stdin (printf is a builtin), so\n# it never appears in any argv or in the proxy's /proc//environ.\nstart_share_proxy() {\n [ -n \"${ORCA_SHARE_PROXY_KEY:-}\" ] && [ -x \"$ORCA_HOME/bin/orca-share-proxy\" ] || return 0\n if [ \"$(cat \"$STATE/share-proxy.boot\" 2>/dev/null || true)\" = \"$boot_id\" ] \\\n && kill -0 \"$(cat \"$STATE/share-proxy.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n return 0\n fi\n printf '%s' \"$ORCA_SHARE_PROXY_KEY\" | env -i HOME=\"$HOME\" LANG=C.UTF-8 PATH=/usr/bin:/bin \\\n setsid \"$node\" \"$ORCA_HOME/bin/orca-share-proxy\" >\"$STATE/share-proxy.log\" 2>&1 9>&- &\n echo $! >\"$STATE/share-proxy.pid\"\n printf '%s' \"$boot_id\" >\"$STATE/share-proxy.boot\"\n}\n\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nstart_share_proxy\nunset ORCA_SHARE_PROXY_KEY\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" = \"$boot_id\" ] && [ -s \"$STATE/ready.json\" ] \\\n && kill -0 \"$(cat \"$STATE/orcad.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n print_ready\n exit 0\nfi\n# Resume = reboot from disk: locks and pids from the previous session name dead processes.\nrm -f \"$STATE/ready.json\" \"$STATE/orcad.pid\"\nprintf '%s' \"$boot_id\" >\"$STATE/boot-id\"\n\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n # Every github.com request carries the placeholder; the egress policy swaps in a 1h repo token.\n git config --global http.https://github.com/.extraheader \"$ORCA_GIT_EXTRAHEADER\"\nfi\n# Commits outside a teammate's turn (or before any member connected GitHub) need an author too.\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'cloud@users.noreply.onorca.dev'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca Cloud'\n# First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both.\nclone_pid=''\nif [ ! -d \"$PROJECT\" ]; then\n mkdir -p \"$PROJECT\"\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n git clone --quiet ${ORCA_REPO_REF:+--branch \"$ORCA_REPO_REF\"} -- \"$ORCA_REPO_URL\" \"$PROJECT\" 2>\"$STATE/clone.log\" 9>&- &\n clone_pid=$!\n fi\nfi\n\n# The clone may still be running here, so the name comes from the URL; the default branch is\n# filled in lazily by the session-env shell hook once the clone exists.\nif [ -n \"${ORCA_REPO_URL:-}\" ]; then\n workspace_name=\"$(basename \"${ORCA_REPO_URL%/}\" .git)\"\nelse\n workspace_name=\"$(basename \"$(git -C \"$PROJECT\" remote get-url origin 2>/dev/null || echo \"$PROJECT\")\" .git)\"\nfi\n# One workspace per VM: its preview ports start at 3000 (Conductor allots CONDUCTOR_PORT..+9).\nmanaged_env=(\n ORCA_IS_CLOUD=1\n ORCA_ROOT_PATH=\"$PROJECT\" ORCA_WORKTREE_PATH=\"$PROJECT\" ORCA_WORKSPACE_PATH=\"$PROJECT\"\n ORCA_WORKSPACE_NAME=\"$workspace_name\" ORCA_PORT=3000\n CONDUCTOR_IS_CLOUD=1\n # Agent CLIs are pinned by the image (smoke-tested); a self-update mid-session can break a running agent.\n DISABLE_AUTOUPDATER=1 OPENCODE_DISABLE_AUTOUPDATE=1 COPILOT_AUTO_UPDATE=false\n CONDUCTOR_ROOT_PATH=\"$PROJECT\" CONDUCTOR_WORKSPACE_PATH=\"$PROJECT\"\n CONDUCTOR_WORKSPACE_NAME=\"$workspace_name\" CONDUCTOR_PORT=3000\n)\n\nagent_env=()\nif command -v google-chrome >/dev/null; then\n # Orca's browser automation and agent browser tools use the image's headless Chrome.\n agent_env+=(\"ORCA_BROWSER_EXECUTABLE=$(command -v google-chrome)\")\nfi\nif [ -n \"${ORCA_GITHUB_PLACEHOLDER:-}\" ]; then\n # The egress layer swaps the placeholder for a short-lived GitHub token; none lives in the VM.\n agent_env+=(\"GH_TOKEN=$ORCA_GITHUB_PLACEHOLDER\" \"GITHUB_TOKEN=$ORCA_GITHUB_PLACEHOLDER\")\nfi\n\nsecret_names=()\nif [ -n \"${ORCA_SECRET_ENV:-}\" ]; then\n # Secrets live only in memory: orcad's process env and a tmpfs file new shells re-read\n # (orca-sandbox-env), never under $HOME or the project, so the stop snapshot never carries them.\n # Resolved per start (and per edit) by the control plane: no image rebuild, no restart.\n while IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\" # not IFS='=': read would strip base64 padding\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n agent_env+=(\"$name=$(printf '%s' \"$b64\" | base64 -d)\")\n secret_names+=(\"$name\")\n done < <(printf '%s\\n' \"$ORCA_SECRET_ENV\") # a pipe, not a here-string temp file\nfi\n# Always rewrite the file, so a resume with fewer secrets drops the old names too.\n\"$ORCA_HOME/bin/orca-sandbox-env\" >/dev/null || echo 'session env file unavailable; secrets apply at boot only' >&2\nunset ORCA_SECRET_ENV\n\n# Agent CLIs installed with the image's npm (codex, gemini, ...) are `#!/usr/bin/env node` scripts:\n# terminals need that node on PATH, not only orcad's bundled runtime.\nsystem_node=\"$(command -v node 2>/dev/null || echo \"$node\")\"\n# The egress proxy answers for hosts with credential rules (model APIs, api.github.com) with a\n# certificate from Vercel's CA, which this command's env trusts (Vercel sets these). Pure-Node clients\n# use Node's bundled roots otherwise: Gemini CLI retried forever (\"taking a bit longer\") in every\n# terminal while the same call worked here. Pass the provider's CA settings on to orcad and its shells.\nca_env=(NODE_USE_SYSTEM_CA=\"${NODE_USE_SYSTEM_CA:-1}\")\nfor name in NODE_EXTRA_CA_CERTS SSL_CERT_FILE; do\n if [ -n \"${!name:-}\" ]; then ca_env+=(\"$name=${!name}\"); fi\ndone\nenv -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 TERM=xterm-256color \"${ca_env[@]}\" \\\n PATH=\"$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname \"$system_node\"):/usr/local/bin:/usr/bin:/bin\" \\\n ORCA_USER_DATA=\"$HOME/.orcad-data\" ORCA_SANDBOX_ID=\"$ORCA_SANDBOX_ID\" \"${managed_env[@]}\" \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_SESSION_ENV_NAMES=\"${secret_names[*]}\" \"${agent_env[@]}\" \\\n setsid nohup \"$node\" \"$ORCA_HOME/bin/orcad-boot\" --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" \\\n \"$ORCA_HOME/runtime/orcad/orcad-server.js\" --port 6768 --bind 0.0.0.0 --pairing-address \"$ORCA_PUBLIC_WSS\" \\\n --recipe-json --project-root \"$PROJECT\" \\\n >\"$STATE/ready.json\" 2>\"$STATE/orcad.log\" &- &\necho $! >\"$STATE/orcad.pid\"\n\n# sshd for `orca ssh` (loopback only). Best effort: a workspace without it still serves orcad.\n\"$ORCA_HOME/bin/orca-sshd\" >/dev/null 2>\"$STATE/sshd-start.err\" || true\n\n# Polled every 10 ms (at least 60 s in all): ready is on the wake path, so detect it promptly.\nfor _ in $(seq 1 6000); do\n if grep -q '\"pairingCode\"' \"$STATE/ready.json\" 2>/dev/null; then\n if [ -n \"$clone_pid\" ] && ! wait \"$clone_pid\"; then\n echo 'repository clone failed' >&2\n tail -n 5 \"$STATE/clone.log\" | redact_log >&2\n exit 1\n fi\n register_project\n print_ready\n exit 0\n fi\n if ! kill -0 \"$(cat \"$STATE/orcad.pid\")\" 2>/dev/null; then\n echo 'orcad exited before ready' >&2\n tail -n 40 \"$STATE/orcad.log\" | redact_log >&2\n exit 1\n fi\n sleep 0.01\ndone\necho 'orcad start timed out' >&2\nexit 1\n","orca-sandbox-drain":"#!/usr/bin/env bash\n# Asks orcad to quit before the VM stops: its shutdown turns working agent chats into durable\n# restart offers and flushes terminal restore hints, which the desktop continues after resume.\nset -euo pipefail\nSTATE=\"$HOME/.orca-sandbox\"\nWAIT_SECONDS=\"${1:-280}\"\npid=\"$(cat \"$STATE/orcad.pid\" 2>/dev/null || true)\"\nif [ -z \"$pid\" ] || ! kill -0 \"$pid\" 2>/dev/null; then\n exit 0\nfi\nkill -TERM \"$pid\"\nfor _ in $(seq 1 $((WAIT_SECONDS * 10))); do\n if ! kill -0 \"$pid\" 2>/dev/null; then\n rm -f \"$STATE/orcad.pid\" \"$STATE/ready.json\"\n exit 0\n fi\n sleep 0.1\ndone\n# Leave it running: the provider stop ends it, and the drain already had its window.\necho 'orcad still draining at deadline' >&2\nexit 0\n","orca-sandbox-env":"#!/usr/bin/env bash\n# Writes this session's secret env where new shells and agent launches read it (orca-session-env.sh).\n# Input: ORCA_SECRET_ENV (`NAME=` lines) from the control plane, at boot (orca-sandbox-start)\n# and whenever a secret changes (POST /v1/sandboxes/:id/env/refresh). The file lives on tmpfs only:\n# never on the sandbox disk, so the stop snapshot never carries it. Prints {\"names\":N} on success.\n# Also keeps Codex pointed at a configured OpenAI-compatible provider (OPENAI_BASE_URL), since Codex\n# does not read that variable: a managed block in ~/.codex/config.toml naming only the env var.\nset -euo pipefail\numask 077\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\n# ORCA_SESSION_ENV_DIR: tests only (a scratch dir off tmpfs); the control plane never sets it.\ndir=\"${ORCA_SESSION_ENV_DIR:-/dev/shm/orca-env-$(id -u)}\"\nif [ -z \"${ORCA_SESSION_ENV_DIR:-}\" ] && [ \"$(stat -f -c %T /dev/shm 2>/dev/null || true)\" != tmpfs ]; then\n # No memory-only place to keep it: refuse rather than write secrets to disk.\n echo 'no tmpfs for the session env' >&2\n exit 3\nfi\nmkdir -p \"$dir\"\nchmod 700 \"$dir\"\n# Writes are ordered by the control plane's resolve time: an older refresh that lost a race is dropped.\ngeneration=\"${ORCA_ENV_GENERATION:-0}\"\ncase \"$generation\" in '' | *[!0-9]*) generation=0 ;; esac\ncurrent=\"$(cat \"$dir/generation\" 2>/dev/null || echo 0)\"\ncase \"$current\" in '' | *[!0-9]*) current=0 ;; esac\nif [ \"$generation\" -lt \"$current\" ]; then\n printf '{\"stale\":true}\\n'\n exit 0\nfi\ntmp=\"$(mktemp \"$dir/.session.env.XXXXXX\")\"\ncount=0\nopenai_base_url=''\nopenai_model=''\nanthropic_model=''\nanthropic_key_tail=''\ngateway_key=''\ngemini_key=''\ncodex_placeholder=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n # Not for shells: the Codex account placeholder becomes ~/.codex/auth.json below.\n if [ \"$name\" = ORCA_CODEX_AUTH_PLACEHOLDER ]; then\n codex_placeholder=\"$(printf '%s' \"$b64\" | base64 -d)\"\n case \"$codex_placeholder\" in *[!A-Za-z0-9._-]*) codex_placeholder='' ;; esac\n fi\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n # Values stay base64 in the file; the shell hook decodes them.\n printf '%s=%s\\n' \"$name\" \"$b64\" >>\"$tmp\"\n count=$((count + 1))\n case \"$name\" in\n OPENAI_BASE_URL) openai_base_url=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n OPENAI_MODEL) openai_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n ANTHROPIC_MODEL) anthropic_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n AI_GATEWAY_API_KEY) gateway_key=1 ;;\n GEMINI_API_KEY | GOOGLE_API_KEY) gemini_key=\"${gemini_key:-gemini-api-key}\" ;;\n GOOGLE_GENAI_USE_VERTEXAI) case \"$(printf '%s' \"$b64\" | base64 -d)\" in true | 1) gemini_key=vertex-ai ;; esac ;;\n # Claude Code asks once per key whether to use ANTHROPIC_API_KEY; it remembers the last 20 chars.\n ANTHROPIC_API_KEY) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\ndone < <(printf '%s\\n' \"${ORCA_SECRET_ENV:-}\")\nmv -f \"$tmp\" \"$dir/session.env\"\nprintf '%s' \"$generation\" >\"$dir/generation\"\n\n# ---- Codex: trust the workspace and use the configured provider (no secret values) ----\nPROJECT=/vercel/sandbox/project\ncodex_config=\"$HOME/.codex/config.toml\"\ntoml_string() { # TOML basic string; the control plane only accepts https URLs and plain model ids\n local value=\"${1//\\\\/\\\\\\\\}\"\n printf '\"%s\"' \"${value//\\\"/\\\\\\\"}\"\n}\nstrip_managed() { # drop the managed blocks and the blank lines written before them (no growth per refresh)\n awk '/^# >>> orca-cloud managed/{skip=1; blank=\"\"} skip{if (/^# <<< orca-cloud managed/) skip=0; next}\n /^[[:space:]]*$/{blank=blank $0 \"\\n\"; next} {printf \"%s\", blank; blank=\"\"; print}' \"$1\"\n}\n# Always managed: an agent launched from the phone or the API has no one to answer Codex's\n# \"trust this folder?\" screen, so the workspace project is trusted up front.\nif true; then\n mkdir -p \"$HOME/.codex\"\n user_part=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n if [ -f \"$codex_config\" ]; then strip_managed \"$codex_config\" >\"$user_part\"; fi\n next=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n openai_host=\"${openai_base_url#https://}\"\n openai_host=\"${openai_host%%/*}\"\n custom_provider=''\n if [ -n \"$openai_base_url\" ] && [ \"$openai_host\" != api.openai.com ]; then custom_provider=1; fi\n # Top-level keys must precede every table; each is skipped when the user already set it.\n head_keys=\"$(awk '/^\\[/{exit} {print}' \"$user_part\")\"\n has_key() { grep -Eq \"^[[:space:]]*$1[[:space:]]*=\" <<<\"$head_keys\"; }\n {\n printf '# >>> orca-cloud managed (Orca Cloud; edit in Orca settings)\\n'\n # The sandbox is the isolation boundary: Codex's own bwrap sandbox can't start in it (\"Unexpected\n # capabilities\"), and a prompt delivered from the phone or the API has no one to approve commands.\n has_key sandbox_mode || printf 'sandbox_mode = \"danger-full-access\"\\n'\n has_key approval_policy || printf 'approval_policy = \"never\"\\n'\n if [ -n \"$custom_provider\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_cloud\"\\n'\n if [ -n \"$openai_model\" ] && ! has_key model; then\n printf 'model = %s\\n' \"$(toml_string \"$openai_model\")\"\n fi\n elif [ -n \"$codex_placeholder\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_chatgpt\"\\n'\n fi\n printf '# <<< orca-cloud managed\\n'\n cat \"$user_part\"\n if [ -n \"$custom_provider\" ]; then\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_cloud]\\nname = \"Orca Cloud\"\\n'\n printf 'base_url = %s\\nenv_key = \"OPENAI_API_KEY\"\\nwire_api = \"responses\"\\n' \"$(toml_string \"$openai_base_url\")\"\n printf '# <<< orca-cloud managed\\n'\n elif [ -n \"$codex_placeholder\" ]; then\n # Codex via the Orca account: the ChatGPT backend over HTTPS. Its default Responses WebSocket can't\n # pass the egress proxy, where the placeholder becomes the real token (found live, Codex 0.166).\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_chatgpt]\\nname = \"OpenAI\"\\n'\n printf 'base_url = \"https://chatgpt.com/backend-api/codex\"\\nwire_api = \"responses\"\\nrequires_openai_auth = true\\nsupports_websockets = false\\n'\n printf '# <<< orca-cloud managed\\n'\n fi\n } >\"$next\"\n if ! grep -qF \"[projects.\\\"$PROJECT\\\"]\" \"$user_part\"; then\n printf '\\n# >>> orca-cloud managed trust\\n[projects.\"%s\"]\\ntrust_level = \"trusted\"\\n# <<< orca-cloud managed\\n' \"$PROJECT\" >>\"$next\"\n fi\n chmod 600 \"$next\"\n mv -f \"$next\" \"$codex_config\"\n rm -f \"$user_part\"\nfi\n# ---- Codex via the person's Orca account (contract D11): a placeholder ChatGPT login, no refresh token.\n# The egress proxy swaps the real access token on chatgpt.com; the real tokens never reach this VM. The\n# marker remembers which placeholder Orca wrote (a clone gets its own), so a login of the person's own\n# (kill-switch fallback, or `codex login` run here) is set aside while the account applies and put back after.\ncodex_auth=\"$HOME/.codex/auth.json\"\ncodex_saved=\"$HOME/.codex/auth.json.orca-saved\"\ncodex_marker=\"$HOME/.codex/.orca-account-placeholder\"\ncodex_ours=''\n# Ours: the marker's placeholder, or any Orca placeholder (all end in `.orca-placeholder`; a real token never does).\nif [ -f \"$codex_auth\" ] && { { [ -f \"$codex_marker\" ] && grep -qF \"\\\"$(cat \"$codex_marker\")\\\"\" \"$codex_auth\"; } || grep -q '\\.orca-placeholder\"' \"$codex_auth\"; }; then\n codex_ours=1\nfi\nif [ -n \"$codex_placeholder\" ]; then\n mkdir -p \"$HOME/.codex\"\n if [ -f \"$codex_auth\" ] && [ -z \"$codex_ours\" ]; then\n # Never overwrite a login already set aside: a second one gets its own name.\n if [ -e \"$codex_saved\" ]; then mv -f \"$codex_auth\" \"$codex_saved.$(date -u +%Y%m%d%H%M%S)\"; else mv -f \"$codex_auth\" \"$codex_saved\"; fi\n fi\n # Marker first: a run cut short after the swap still recognises the file as Orca's.\n printf '%s' \"$codex_placeholder\" >\"$codex_marker\"\n codex_tmp=\"$(mktemp \"$HOME/.codex/.auth.XXXXXX\")\"\n printf '{\\n \"OPENAI_API_KEY\": null,\\n \"tokens\": {\\n \"id_token\": \"%s\",\\n \"access_token\": \"%s\",\\n \"refresh_token\": \"\",\\n \"account_id\": null\\n },\\n \"last_refresh\": \"%s\"\\n}\\n' \\\n \"$codex_placeholder\" \"$codex_placeholder\" \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\" >\"$codex_tmp\"\n chmod 600 \"$codex_tmp\"\n mv -f \"$codex_tmp\" \"$codex_auth\"\nelif [ -f \"$codex_marker\" ] || [ -n \"$codex_ours\" ]; then\n if [ -n \"$codex_ours\" ]; then rm -f \"$codex_auth\"; fi\n rm -f \"$codex_marker\"\n if [ -f \"$codex_saved\" ] && [ ! -f \"$codex_auth\" ]; then mv -f \"$codex_saved\" \"$codex_auth\"; fi\nfi\n# ---- Claude Code, Gemini CLI, Cursor agent, Copilot CLI, OpenCode: first-run screens answered once\n# (Claude: theme picker, folder trust, bypass-mode warning, the \"use this API key?\" question; others:\n# folder trust, auth-method picker, self-update). A prompt delivered from the phone or the API has no one to click\n# through them, and the agent would sit there doing nothing. Merges; never touches credentials.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nif [ -n \"$node_bin\" ]; then\n ORCA_PROJECT=\"$PROJECT\" ORCA_KEY_TAIL=\"$anthropic_key_tail\" ORCA_GEMINI_KEY=\"$gemini_key\" \\\n ORCA_GATEWAY_MODEL=\"${gateway_key:+${anthropic_model:-$openai_model}}\" \"$node_bin\" -e '\nconst fs = require(\"fs\"), path = require(\"path\"), os = require(\"os\")\nconst home = os.homedir()\nconst readJson = (file) => { try { const v = JSON.parse(fs.readFileSync(file, \"utf8\")); return v && typeof v === \"object\" && !Array.isArray(v) ? v : {} } catch { return {} } }\nconst write = (file, value) => {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\nconst claudeFile = path.join(process.env.CLAUDE_CONFIG_DIR || home, \".claude.json\")\nconst c = readJson(claudeFile)\nconst before = JSON.stringify(c)\nc.hasCompletedOnboarding = true\nc.theme = c.theme || \"dark\"\nc.bypassPermissionsModeAccepted = true\nc.projects = c.projects && typeof c.projects === \"object\" ? c.projects : {}\nconst p = process.env.ORCA_PROJECT\nc.projects[p] = { ...(c.projects[p] || {}), hasTrustDialogAccepted: true, hasCompletedProjectOnboarding: true }\nconst tail = process.env.ORCA_KEY_TAIL\nif (tail) {\n const r = c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\" ? c.customApiKeyResponses : {}\n const approved = Array.isArray(r.approved) ? r.approved : []\n const rejected = Array.isArray(r.rejected) ? r.rejected.filter((t) => t !== tail) : []\n c.customApiKeyResponses = { ...r, approved: approved.includes(tail) ? approved : [...approved, tail], rejected }\n}\nif (JSON.stringify(c) !== before) write(claudeFile, c)\nconst settingsFile = path.join(home, \".claude\", \"settings.json\")\nconst s = readJson(settingsFile)\nif (s.skipDangerousModePermissionPrompt !== true) write(settingsFile, { ...s, skipDangerousModePermissionPrompt: true })\n\n// Each block below only fills in what is unset and leaves a file it cannot parse alone.\nconst readStrict = (file) => { try { return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, \"utf8\")) : {} } catch { return null } }\nconst isObject = (v) => v !== null && typeof v === \"object\" && !Array.isArray(v)\nconst section = (o, key) => (isObject(o[key]) ? o[key] : (o[key] = {}))\n\n// Gemini CLI: folder trust and the auth-method picker (only when a Gemini key is configured; a\n// Google sign-in picks its own method), no self-update, no usage stats (its host is not on the\n// egress allowlist, so every send would fail).\nconst geminiTrustFile = path.join(home, \".gemini\", \"trustedFolders.json\")\nconst geminiTrust = readStrict(geminiTrustFile)\nif (isObject(geminiTrust) && !geminiTrust[p]) write(geminiTrustFile, { ...geminiTrust, [p]: \"TRUST_FOLDER\" })\nconst geminiSettingsFile = path.join(home, \".gemini\", \"settings.json\")\nconst g = readStrict(geminiSettingsFile)\nif (isObject(g)) {\n const gBefore = JSON.stringify(g)\n const general = section(g, \"general\")\n general.disableAutoUpdate ??= true\n general.disableUpdateNag ??= true\n section(g, \"privacy\").usageStatisticsEnabled ??= false\n // gemini-api-key or vertex-ai (GOOGLE_GENAI_USE_VERTEXAI=true with an API key): headless runs\n // refuse to start without a method (\"Invalid auth method selected\").\n if (process.env.ORCA_GEMINI_KEY) section(section(g, \"security\"), \"auth\").selectedType ??= process.env.ORCA_GEMINI_KEY\n if (JSON.stringify(g) !== gBefore) write(geminiSettingsFile, g)\n}\n\n// Cursor agent: trust the workspace (cursor-agent keys trust by a slug of the path) and pin the\n// release channel to \"static\", which turns off its background self-update.\nconst cursorTrust = path.join(home, \".cursor\", \"projects\", p.replace(/^\\/+/, \"\").replace(/[^A-Za-z0-9]+/g, \"-\"), \".workspace-trusted\")\nif (!fs.existsSync(cursorTrust)) {\n fs.mkdirSync(path.dirname(cursorTrust), { recursive: true, mode: 0o700 })\n fs.writeFileSync(cursorTrust, JSON.stringify({ trustedAt: new Date().toISOString(), workspacePath: p }, null, 2) + \"\\n\", { mode: 0o600 })\n}\nconst cursorConfigFile = path.join(home, \".cursor\", \"cli-config.json\")\nconst cc = readStrict(cursorConfigFile)\nif (isObject(cc) && cc.channel === undefined) write(cursorConfigFile, { version: 1, ...cc, channel: \"static\" })\n\n// GitHub Copilot CLI: trusted folders live in ~/.copilot/config.json, which Copilot prefixes with\n// \"//\" comment lines; keep them.\nconst copilotFile = path.join(home, \".copilot\", \"config.json\")\nlet copilotHead = \"\"\nlet co = {}\ntry {\n const raw = fs.existsSync(copilotFile) ? fs.readFileSync(copilotFile, \"utf8\") : \"\"\n const lines = raw.split(\"\\n\")\n let i = 0\n while (i < lines.length && /^\\s*\\/\\//.test(lines[i])) i++\n copilotHead = lines.slice(0, i).map((l) => l + \"\\n\").join(\"\")\n const body = lines.slice(i).join(\"\\n\").trim()\n co = body ? JSON.parse(body) : {}\n} catch { co = null }\nif (isObject(co)) {\n const folders = Array.isArray(co.trustedFolders) ? co.trustedFolders : []\n if (!folders.includes(p)) {\n fs.mkdirSync(path.dirname(copilotFile), { recursive: true, mode: 0o700 })\n const tmp = `${copilotFile}.orca-${process.pid}`\n fs.writeFileSync(tmp, copilotHead + JSON.stringify({ ...co, trustedFolders: [...folders, p] }, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, copilotFile)\n }\n}\n\n// OpenCode: with the AI Gateway preset and a model secret (ANTHROPIC_MODEL, else OPENAI_MODEL), use\n// that model through the gateway unless the user picked one. A ledger remembers what Orca wrote, so a\n// changed model secret updates it and a model the user set is never touched.\nconst ocDir = path.join(home, \".config\", \"opencode\")\nconst ocFile = path.join(ocDir, \"opencode.json\")\nconst ocLedger = path.join(ocDir, \".orca-managed-model\")\nconst managedModel = process.env.ORCA_GATEWAY_MODEL ? `vercel/${process.env.ORCA_GATEWAY_MODEL}` : \"\"\nconst oc = readStrict(ocFile)\nlet jsoncHasModel = false\ntry { jsoncHasModel = /\"model\"\\s*:/.test(fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\")) } catch {}\nif (isObject(oc) && !jsoncHasModel) {\n let ours = \"\"\n try { ours = fs.readFileSync(ocLedger, \"utf8\").trim() } catch {}\n const userModel = typeof oc.model === \"string\" && oc.model !== ours\n if (!userModel && (oc.model ?? \"\") !== managedModel) {\n const next = { $schema: \"https://opencode.ai/config.json\", ...oc }\n if (managedModel) next.model = managedModel\n else delete next.model\n write(ocFile, next)\n }\n if (!userModel) {\n if (managedModel) fs.writeFileSync(ocLedger, managedModel + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocLedger, { force: true })\n }\n}\n\n// OpenCode: two built-in providers cannot work in Orca Cloud, and with no other credential OpenCode\n// picks one and fails (\"Authorization header is badly formatted\" / opencode.ai unreachable) instead\n// of showing \"Connect a provider\". GitHub Copilot reads GITHUB_TOKEN, which here is the stand-in for the\n// GitHub App token of the workspace, never a Copilot token; OpenCode Zen needs opencode.ai, which is not on the\n// egress allowlist. Both stay off unless the user connected them in OpenCode itself (auth.json).\nconst ocAuth = readStrict(path.join(process.env.XDG_DATA_HOME || path.join(home, \".local\", \"share\"), \"opencode\", \"auth.json\"))\nconst connected = new Set(isObject(ocAuth) ? Object.keys(ocAuth) : [])\nconst ocDisabledLedger = path.join(ocDir, \".orca-managed-disabled-providers\")\nconst ocNow = readStrict(ocFile)\nif (isObject(ocNow) && !/\"disabled_providers\"\\s*:/.test((() => { try { return fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\") } catch { return \"\" } })())) {\n let ours = []\n try { ours = fs.readFileSync(ocDisabledLedger, \"utf8\").split(\"\\n\").filter(Boolean) } catch {}\n const userList = (Array.isArray(ocNow.disabled_providers) ? ocNow.disabled_providers : []).filter((id) => typeof id === \"string\" && !ours.includes(id))\n const managed = [\"github-copilot\", \"opencode\"].filter((id) => !connected.has(id) && !userList.includes(id))\n const next = [...userList, ...managed]\n const before = JSON.stringify(ocNow.disabled_providers ?? [])\n if (JSON.stringify(next) !== before) {\n const updated = { $schema: \"https://opencode.ai/config.json\", ...ocNow }\n if (next.length > 0) updated.disabled_providers = next\n else delete updated.disabled_providers\n write(ocFile, updated)\n }\n if (managed.length > 0) fs.writeFileSync(ocDisabledLedger, managed.join(\"\\n\") + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocDisabledLedger, { force: true })\n}\n' || echo 'agent first-run state not seeded' >&2\nfi\nprintf '{\"names\":%d}\\n' \"$count\"\n","orca-session-env.sh":"# Orca Cloud: sourced by every new bash/zsh (via /etc/profile.d) so terminals and agents started\n# after a secret edit get the current values with no restart. The file is written by\n# /opt/orca/bin/orca-sandbox-env on tmpfs; names it no longer lists are unset. Cloud secrets win\n# over same-named values already in the environment.\n__orca_env_file=\"/dev/shm/orca-env-$(id -u 2>/dev/null)/session.env\"\nif [ -r \"$__orca_env_file\" ]; then\n # $(...) word-splits in both bash and zsh.\n for __orca_n in $(printf '%s' \"${ORCA_SESSION_ENV_NAMES-}\"); do\n unset \"$__orca_n\" 2>/dev/null || true\n done\n __orca_names=''\n while IFS= read -r __orca_line || [ -n \"$__orca_line\" ]; do\n __orca_n=\"${__orca_line%%=*}\"\n case \"$__orca_n\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n export \"$__orca_n=$(printf '%s' \"${__orca_line#*=}\" | base64 -d 2>/dev/null)\"\n __orca_names=\"$__orca_names $__orca_n\"\n done <\"$__orca_env_file\"\n export ORCA_SESSION_ENV_NAMES=\"${__orca_names# }\"\nfi\n# Default branch of the cloud workspace repo, once its first-boot clone exists (computed once per shell tree).\nif [ -n \"${ORCA_WORKSPACE_PATH-}\" ] && [ -z \"${ORCA_DEFAULT_BRANCH-}\" ]; then\n __orca_branch=\"$(git -C \"$ORCA_WORKSPACE_PATH\" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)\"\n if [ -n \"$__orca_branch\" ]; then\n export ORCA_DEFAULT_BRANCH=\"${__orca_branch#origin/}\" CONDUCTOR_DEFAULT_BRANCH=\"${__orca_branch#origin/}\"\n fi\nfi\nunset __orca_env_file __orca_line __orca_n __orca_names __orca_branch\n","orca-env":"#!/usr/bin/env bash\n# Prints shell lines that bring the current shell up to date with this session's cloud env (secrets\n# saved after the shell started): eval \"$(orca-env)\" or, in fish: orca-env --fish | source\n# Reads /dev/shm/orca-env-/session.env (written by orca-sandbox-env, `NAME=` lines) and\n# prints an export for each name, plus an unset for each name in $ORCA_SESSION_ENV_NAMES that is gone.\n# Never writes a file. Values are single-quoted, so quotes, newlines and $ in them stay literal.\nset -euo pipefail\nfish=''\ncase \"${1-}\" in\n '') ;;\n --fish) fish=1 ;;\n -h | --help)\n printf 'usage: eval \"$(orca-env)\" (fish: orca-env --fish | source)\\n'\n exit 0\n ;;\n *)\n printf 'orca-env: unknown option %s\\n' \"$1\" >&2\n exit 2\n ;;\nesac\n# ORCA_SESSION_ENV_FILE is for tests; secrets can't set ORCA_* names.\nfile=\"${ORCA_SESSION_ENV_FILE:-/dev/shm/orca-env-$(id -u)/session.env}\"\nset -f # names are split below, never globbed\n# Not written yet (or not a cloud VM): nothing to change, like the shell hook.\n[ -r \"$file\" ] || exit 0\n\n# 'it'\\''s' for POSIX shells; fish single quotes escape only \\ and '.\nquote() {\n local v=\"$1\"\n if [ -n \"$fish\" ]; then\n v=\"${v//\\\\/\\\\\\\\}\"\n v=\"${v//\\'/\\\\\\'}\"\n printf \"'%s'\" \"$v\"\n else\n printf \"'%s'\" \"${v//\\'/\\'\\\\\\'\\'}\"\n fi\n}\n\n# The control plane's reserved names and prefixes (cloud/apps/sandbox-control/src/secrets.ts; a test\n# keeps this in sync): a session file never sets what would hijack the shell or Orca's own processes.\nskip_name() {\n case \"$1\" in\n '' | *[!A-Z0-9_]* | [0-9]*) return 0 ;;\n LD_* | DYLD_* | ORCA_* | VERCEL_* | BASH_FUNC_* | GIT_CONFIG*) return 0 ;;\n PATH | HOME | USER | LOGNAME | SHELL | PWD | OLDPWD | LANG | TERM | TMPDIR | IFS | ENV | \\\n BASH_ENV | PS4 | PROMPT_COMMAND | SHELLOPTS | BASHOPTS | NODE_OPTIONS | NODE_PATH | \\\n NODE_EXTRA_CA_CERTS | NODE_TLS_REJECT_UNAUTHORIZED | SSL_CERT_FILE | SSL_CERT_DIR | \\\n CURL_CA_BUNDLE | REQUESTS_CA_BUNDLE | HTTP_PROXY | HTTPS_PROXY | ALL_PROXY | NO_PROXY | \\\n PYTHONPATH | PYTHONSTARTUP | PERL5OPT | RUBYOPT | JAVA_TOOL_OPTIONS | GIT_SSH | \\\n GIT_SSH_COMMAND | GIT_ASKPASS | GIT_EXEC_PATH | GIT_PROXY_COMMAND | SSH_AUTH_SOCK | \\\n GH_TOKEN | GITHUB_TOKEN) return 0 ;;\n # CLAUDE_CODE_OAUTH_TOKEN is reserved for users but set by the control plane itself: only ever the\n # Orca-account placeholder (contract D10), never a stored value.\n esac\n return 1\n}\n\nnames=' '\nwhile IFS= read -r line || [ -n \"$line\" ]; do\n name=\"${line%%=*}\"\n skip_name \"$name\" && continue\n # $(...) drops trailing newlines; the x keeps them.\n value=\"$(printf '%s' \"${line#*=}\" | base64 -d 2>/dev/null; printf x)\"\n value=\"${value%x}\"\n if [ -n \"$fish\" ]; then\n printf 'set -gx %s %s\\n' \"$name\" \"$(quote \"$value\")\"\n else\n printf 'export %s=%s\\n' \"$name\" \"$(quote \"$value\")\"\n fi\n names=\"$names$name \"\ndone <\"$file\"\nfor name in ${ORCA_SESSION_ENV_NAMES-}; do\n skip_name \"$name\" && continue\n case \"$names\" in *\" $name \"*) continue ;; esac\n if [ -n \"$fish\" ]; then\n printf 'set -e %s\\n' \"$name\"\n else\n printf 'unset %s\\n' \"$name\"\n fi\ndone\nnames=\"${names# }\"\nnames=\"${names% }\"\nif [ -n \"$fish\" ]; then\n printf 'set -gx ORCA_SESSION_ENV_NAMES %s\\n' \"$(quote \"$names\")\"\nelse\n printf 'export ORCA_SESSION_ENV_NAMES=%s\\n' \"$(quote \"$names\")\"\nfi\n","orca-egress-probe":"#!/usr/bin/env bash\n# Bounded Node fetch against each credential host. Vercel transform rules have made undici hang on\n# response bodies (no content-length / transfer-encoding); report it instead of letting agents hang.\n# Prints one JSON line: {\"host\":\"api.github.com\",\"status\":\"ok\"|\"egress_framing_hang\"|\"error\"}.\nset -euo pipefail\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\nfor host in \"$@\"; do\n \"$node\" -e '\n const host = process.argv[1]\n const timer = setTimeout(() => { console.log(JSON.stringify({ host, status: \"egress_framing_hang\" })); process.exit(0) }, 8000)\n fetch(`https://${host}/`, { headers: { authorization: process.env.ORCA_PROBE_AUTHORIZATION ?? \"\" } })\n .then((r) => r.arrayBuffer())\n .then(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"ok\" })) })\n .catch(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"error\" })) })\n ' \"$host\"\ndone\n","orca-image-wipe":"#!/usr/bin/env bash\n# Runs last before the golden snapshot. Every sandbox cloned from the image must start without an\n# orcad identity, device registry, agent sign-in or shell history (clone-safe identity, risk #1).\nset -euo pipefail\npkill -f orcad-server.js 2>/dev/null || true\nfor path in \\\n \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\" \"$HOME/.orca-desktop\" \"$HOME/.config/orca\" \"$HOME/.config/orca-dev\" \\\n \"$HOME/.claude\" \"$HOME/.claude.json\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.gemini\" \\\n \"$HOME/.local/share/opencode\" \"$HOME/.config/opencode\" \"$HOME/.cursor\" \"$HOME/.config/cursor\" \\\n \"$HOME/.local/share/cursor-agent\" \"$HOME/.copilot\" \"$HOME/.npm\" \"$HOME/.cache\" \"$HOME/.config/google-chrome\" \"$HOME/.bash_history\" \\\n /vercel/sandbox/project; do\n rm -rf -- \"$path\"\ndone\nsudo rm -rf /tmp/* /var/tmp/* 2>/dev/null || true\nfor leftover in \"$HOME/.orcad-data\" \"$HOME/.claude\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.cursor\" \"$HOME/.copilot\" \"$HOME/.gemini\"; do\n if [ -e \"$leftover\" ]; then\n echo \"identity survived wipe: $leftover\" >&2\n exit 1\n fi\ndone\necho '{\"wiped\":true}'\n","orca-agent-signout":"#!/usr/bin/env bash\n# Signs every agent out on this sandbox before Orca deletes it (A9): each agent's own logout, then\n# its credential files. Covers logins made inside the sandbox (the kill-switch fallback path).\n# Never fails: the sandbox is deleted next whatever happens. Values are never printed.\nset -u\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\nexport PATH=\"/opt/orca/tools/bin:$HOME/.local/bin:$HOME/.npm-global/bin:/usr/local/bin:/usr/bin:/bin:/opt/orca/bin:${PATH:-}\"\nclaude_dir=\"${CLAUDE_CONFIG_DIR:-$HOME/.claude}\"\nclaude_json=\"${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json\"\ncodex_dir=\"${CODEX_HOME:-$HOME/.codex}\"\n\nlogged_out=0\n# Each logout gets a few seconds; a hung CLI must not hold up the delete.\nif command -v claude >/dev/null 2>&1 && timeout 8 claude auth logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\nif command -v codex >/dev/null 2>&1 && timeout 8 codex logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\n\n# The files go whether or not a logout ran: an older CLI, a missing binary or no network leaves them.\nrm -f -- \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\" 2>/dev/null\n# Orca-managed Codex homes keep their own auth.json under orcad's data dir.\nif [ -d \"$HOME/.orcad-data\" ]; then\n find \"$HOME/.orcad-data\" -path '*codex*' -type f -name auth.json -delete 2>/dev/null\nfi\n# ~/.claude.json keeps settings Orca wrote (onboarding, trust); only the sign-in fields go.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nfor file in \"$claude_json\" \"$HOME/.claude.json\"; do\n [ -f \"$file\" ] || continue\n if [ -n \"$node_bin\" ]; then\n ORCA_FILE=\"$file\" \"$node_bin\" -e '\nconst fs = require(\"fs\")\nconst file = process.env.ORCA_FILE\nlet c\ntry { c = JSON.parse(fs.readFileSync(file, \"utf8\")) } catch { process.exit(2) }\nif (!c || typeof c !== \"object\" || Array.isArray(c)) process.exit(2)\nlet changed = false\nfor (const key of Object.keys(c)) {\n if (/oauth/i.test(key) || key === \"primaryApiKey\") { delete c[key]; changed = true }\n}\nif (changed) {\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(c, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\n' 2>/dev/null || rm -f -- \"$file\"\n else\n # No node to edit it safely: losing Orca's settings beats leaving a sign-in behind.\n rm -f -- \"$file\"\n fi\ndone\n\nleft=0\nfor file in \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\"; do\n [ -e \"$file\" ] && left=$((left + 1))\ndone\nprintf '{\"loggedOut\":%d,\"left\":%d}\\n' \"$logged_out\" \"$left\"\n","orca-share-proxy":"#!/usr/bin/env node\n// Share-link proxy for this VM. Listens on 0.0.0.0:6769 (its public *.vercel.run route) and only\n// serves requests the control plane's share gateway signed with this session's key:\n// x-orca-share: v2.....\n// A request must start before `expiresAt` (60s windows); its response or WebSocket is closed at\n// `until` (the link's expiry, at most 30 minutes out), so a revoked or expired link also loses open\n// streams. Signed requests are reverse-proxied to 127.0.0.1:: streaming both ways, no\n// buffering, WebSocket upgrades piped raw. Anything unsigned gets a bare 404.\n// The key arrives on stdin (orca-sandbox-start pipes it), so it is never in this process's\n// environment or argv; ORCA_SHARE_PROXY_KEY in the env is accepted for tests. Optional\n// ORCA_SHARE_PROXY_PORT (default 6769). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst crypto = process.getBuiltinModule('node:crypto')\nconst fs = process.getBuiltinModule('node:fs')\nconst http = process.getBuiltinModule('node:http')\nconst net = process.getBuiltinModule('node:net')\n\nconst LISTEN_PORT = Number(process.env.ORCA_SHARE_PROXY_PORT || 6769)\nconst KEY = Buffer.from((process.env.ORCA_SHARE_PROXY_KEY || fs.readFileSync(0, 'utf8')).trim(), 'base64url')\ndelete process.env.ORCA_SHARE_PROXY_KEY\n// Never proxy to the VM's sshd, orcad or this proxy itself.\n// 6080: the remote desktop (VNC behind a password) is for its owner's forward only.\nconst BLOCKED_PORTS = new Set([2222, 6080, 6768, LISTEN_PORT])\nconst MAX_SKEW_SECONDS = 300\nconst MAX_CONNECTION_SECONDS = 3600\nconst HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'te', 'trailer', 'upgrade']\n\nif (KEY.length < 32) {\n console.error('orca-share-proxy: share proxy key missing or short')\n process.exit(2)\n}\n\n/** The target port and close-by time (ms) for a validly signed request, else null. */\nfunction verify(header, nowMs) {\n if (typeof header !== 'string') {\n return null\n }\n const match = /^v2\\.(\\d{1,5})\\.(\\d{1,12})\\.(\\d{1,12})\\.([0-9a-f]{32})\\.([A-Za-z0-9_-]{43})$/.exec(header)\n if (!match) {\n return null\n }\n const now = Math.floor(nowMs / 1000)\n const port = Number(match[1])\n const expiresAt = Number(match[2])\n const until = Number(match[3])\n if (port < 1 || port > 65535 || BLOCKED_PORTS.has(port)) {\n return null\n }\n if (expiresAt < now || expiresAt > now + MAX_SKEW_SECONDS || until <= now || until > now + MAX_CONNECTION_SECONDS) {\n return null\n }\n const signed = header.slice(0, header.lastIndexOf('.'))\n const expected = crypto.createHmac('sha256', KEY).update(signed).digest()\n const given = Buffer.from(match[5], 'base64url')\n return given.length === expected.length && crypto.timingSafeEqual(given, expected) ? { port, untilMs: until * 1000 } : null\n}\n\nfunction upstreamHeaders(raw, port) {\n const headers = { ...raw }\n const connectionTokens = String(raw.connection || '')\n .split(',')\n .map((token) => token.trim().toLowerCase())\n for (const name of [...HOP_BY_HOP, ...connectionTokens, 'x-orca-share']) {\n delete headers[name]\n }\n // Dev servers (Vite, Next) allow localhost hosts by default; the public host rides x-forwarded-host.\n headers.host = `localhost:${port}`\n return headers\n}\n\nfunction refuse(res) {\n res.writeHead(404, { 'content-type': 'text/plain', 'cache-control': 'no-store' })\n res.end('not found')\n}\n\n/** Ends `close` at the grant's deadline; the timer goes away with the connection. */\nfunction deadline(untilMs, close, ...emitters) {\n const timer = setTimeout(close, Math.max(0, untilMs - Date.now()))\n for (const emitter of emitters) {\n emitter.once('close', () => clearTimeout(timer))\n }\n}\n\nconst server = http.createServer((req, res) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n return refuse(res)\n }\n const { port } = grant\n const upstream = http.request(\n { host: '127.0.0.1', port, method: req.method, path: req.url, headers: upstreamHeaders(req.headers, port) },\n (answer) => {\n const headers = { ...answer.headers }\n for (const name of HOP_BY_HOP) {\n delete headers[name]\n }\n // Marks the answer as the app's, so the gateway can tell it from a route with no proxy behind it.\n headers['x-orca-share-proxy'] = '1'\n res.writeHead(answer.statusCode || 502, answer.statusMessage, headers)\n answer.pipe(res)\n }\n )\n deadline(grant.untilMs, () => {\n upstream.destroy()\n res.destroy()\n }, res)\n upstream.on('error', (error) => {\n if (res.headersSent) {\n res.destroy()\n return\n }\n // The gateway renders its own page for this; the code tells it why. Status 200 on purpose: a 5xx\n // from the VM reaches a Worker as Vercel's own 502 with our headers gone (found live).\n res.writeHead(200, { 'content-type': 'text/plain', 'x-orca-share-proxy': '1', 'x-orca-share-error': error.code === 'ECONNREFUSED' ? 'no_listener' : 'upstream_failed' })\n res.end('upstream unavailable')\n })\n req.on('aborted', () => upstream.destroy())\n req.pipe(upstream)\n})\n\nserver.on('upgrade', (req, socket, head) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n socket.end('HTTP/1.1 404 Not Found\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n return\n }\n const { port } = grant\n const headers = upstreamHeaders(req.headers, port)\n const target = net.connect(port, '127.0.0.1', () => {\n const lines = [`${req.method} ${req.url} HTTP/1.1`, `connection: upgrade`, `upgrade: ${req.headers.upgrade || 'websocket'}`]\n for (const [name, value] of Object.entries(headers)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n lines.push(`${name}: ${item}`)\n }\n }\n target.write(`${lines.join('\\r\\n')}\\r\\n\\r\\n`)\n if (head && head.length > 0) {\n target.write(head)\n }\n socket.pipe(target)\n target.pipe(socket)\n })\n const close = () => {\n socket.destroy()\n target.destroy()\n }\n deadline(grant.untilMs, close, socket)\n target.on('error', () => {\n if (socket.writable) {\n socket.end('HTTP/1.1 200 OK\\r\\nx-orca-share-proxy: 1\\r\\nx-orca-share-error: no_listener\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n }\n close()\n })\n socket.on('error', close)\n target.on('close', () => socket.destroy())\n socket.on('close', () => target.destroy())\n})\n\nserver.keepAliveTimeout = 65_000\nserver.headersTimeout = 70_000\n// No request timeout: previews can stream (SSE, long polls) until the grant's deadline.\nserver.requestTimeout = 0\nserver.listen(LISTEN_PORT, '0.0.0.0', () => {\n console.log(`orca-share-proxy listening on ${LISTEN_PORT}`)\n})\n","orca-sshd":"#!/usr/bin/env bash\n# Starts this boot's unprivileged sshd on 127.0.0.1:2222 (idempotent). Nothing outside the VM can\n# reach that port: the desktop tunnels to it over orcad's runtime connection (`orca ssh-proxy`).\n# Key-only, single user (the sandbox user), no root. Its host key and authorized_keys live under\n# ~/.orca-sandbox/ssh on the persistent disk, so the host key stays the same across stop/resume;\n# orca-image-wipe removes that directory, so every VM cloned from the golden image makes its own.\n# Prints {\"port\":2222,\"user\":\"\",\"hostKey\":\"ssh-ed25519 AAAA...\"} on success.\nset -euo pipefail\numask 077\nOPENSSH=/opt/orca/openssh\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\nPORT=2222\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 8>\"$SSH_DIR/sshd.lock\"\nflock -w 30 8\n\nif [ ! -x \"$OPENSSH/sshd\" ]; then\n echo 'sshd is not installed in this image' >&2\n exit 3\nfi\nif [ ! -s \"$SSH_DIR/ssh_host_ed25519_key\" ]; then\n rm -f \"$SSH_DIR/ssh_host_ed25519_key\" \"$SSH_DIR/ssh_host_ed25519_key.pub\"\n ssh-keygen -q -t ed25519 -N '' -C \"orca-cloud-host\" -f \"$SSH_DIR/ssh_host_ed25519_key\"\nfi\ntouch \"$SSH_DIR/authorized_keys\"\nchmod 0600 \"$SSH_DIR/authorized_keys\"\n\n# Rewritten every start so an image update's settings apply to existing workspaces. PAM stays at\n# its compiled-in default (off): an unprivileged sshd cannot use it, and this build warns on `no`.\ncat >\"$SSH_DIR/sshd_config\" </dev/null || echo 0)\"\n# Resume reboots from disk, so a recorded pid can name a dead process or an unrelated one.\nif ! { kill -0 \"$pid\" 2>/dev/null && grep -q sshd \"/proc/$pid/cmdline\" 2>/dev/null; }; then\n rm -f \"$SSH_DIR/sshd.pid\"\n : >\"$SSH_DIR/sshd.log\"\n \"$OPENSSH/sshd\" -t -f \"$SSH_DIR/sshd_config\"\n \"$OPENSSH/sshd\" -f \"$SSH_DIR/sshd_config\" -E \"$SSH_DIR/sshd.log\"\n for _ in $(seq 1 100); do\n [ -s \"$SSH_DIR/sshd.pid\" ] && break\n sleep 0.02\n done\n [ -s \"$SSH_DIR/sshd.pid\" ] || { echo 'sshd did not start' >&2; tail -n 20 \"$SSH_DIR/sshd.log\" >&2; exit 1; }\nfi\n\nhost_key=\"$(cut -d' ' -f1-2 \"$SSH_DIR/ssh_host_ed25519_key.pub\")\"\nprintf '{\"port\":%s,\"user\":\"%s\",\"hostKey\":\"%s\"}\\n' \"$PORT\" \"$(id -un)\" \"$host_key\"\n","orca-ssh-keys":"#!/usr/bin/env bash\n# `orca-ssh-keys add|remove`: adds or removes one desktop's key in the Orca-managed authorized_keys\n# of this VM's sshd, then makes sure sshd runs. The control plane passes the key in\n# ORCA_SSH_PUBLIC_KEY (`ssh-ed25519 `), never on the command line. Keys are\n# matched by their base64 blob, so a renamed comment cannot keep a revoked key alive.\n# Prints orca-sshd's {\"port\":...,\"user\":...,\"hostKey\":...} line on success.\nset -euo pipefail\numask 077\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\naction=\"${1:-}\"\nkey=\"${ORCA_SSH_PUBLIC_KEY:-}\"\n# grep matches per line: a second line could carry key options past the check below.\ncase \"$key\" in *$'\\n'* | *$'\\r'*) echo 'invalid public key' >&2; exit 2 ;; esac\n# One line, ed25519 only, a plain comment: nothing that sshd would read as key options.\nif ! printf '%s' \"$key\" | grep -Eq '^ssh-ed25519 [A-Za-z0-9+/]{68} [A-Za-z0-9@._:+-]{1,200}$'; then\n echo 'invalid public key' >&2\n exit 2\nfi\nblob=\"$(printf '%s' \"$key\" | cut -d' ' -f2)\"\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 7>\"$SSH_DIR/keys.lock\"\nflock -w 30 7\ntouch \"$SSH_DIR/authorized_keys\"\nnext=\"$(mktemp \"$SSH_DIR/authorized_keys.XXXXXX\")\"\n# Drop the key wherever it appears (with or without options), then append it on add.\nawk -v blob=\"$blob\" '{ for (i = 1; i <= NF; i++) if ($i == blob) next; print }' \\\n \"$SSH_DIR/authorized_keys\" >\"$next\"\ncase \"$action\" in\n add) printf '%s\\n' \"$key\" >>\"$next\" ;;\n remove) ;;\n *) rm -f \"$next\"; echo 'usage: orca-ssh-keys add|remove' >&2; exit 2 ;;\nesac\nchmod 0600 \"$next\"\nmv -f \"$next\" \"$SSH_DIR/authorized_keys\"\nexec /opt/orca/bin/orca-sshd\n","orca-desktop-start":"#!/usr/bin/env bash\n# Starts the on-demand remote desktop (idempotent) and mints one connection ticket. Prints one line:\n# {\"schemaVersion\":2,\"port\":6080,\"display\":\":1\",\"path\":\"vnc.html\",\"ticket\":\"<43 chars>\",\"expiresInMs\":60000}\n# Xvnc (X server + VNC in one) listens on a 0600 unix socket only, with no VNC auth: only this uid\n# can open it. orca-desktop-proxy (websockify + a ticket gate) serves noVNC on 127.0.0.1 and\n# bridges WebSockets to that socket. Nothing is reachable from outside the VM: the desktop app\n# reaches it through Orca's port forward, a localhost port on the user's computer that any local\n# process or web page can reach, so each WebSocket needs a ticket from here: 32 random bytes,\n# single use, valid for 60 s, stored only as its sha256 (the file name; its content is the expiry).\n# The ticket goes to stdout only (the control plane hands it to the desktop app). Never started at boot.\nset -euo pipefail\numask 077\nDESKTOP=/opt/orca/desktop\nSTATE=\"$HOME/.orca-desktop\"\nPORT=\"${ORCA_DESKTOP_PORT:-6080}\"\nDISPLAY_NUM=\"${ORCA_DESKTOP_DISPLAY:-1}\"\nGEOMETRY=\"${ORCA_DESKTOP_GEOMETRY:-1280x800}\"\nSOCKET=\"$STATE/vnc.sock\"\n# The parent's DISPLAY must not leak into the WM/xterm below; they use ours.\nexport DISPLAY=\":$DISPLAY_NUM\"\n\n# Exit 3 = this image has no desktop (built before it, or its optional install failed).\nfail() { printf 'orca-desktop: %s\\n' \"$1\" >&2; exit \"${2:-1}\"; }\ncase \"$PORT\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_PORT must be a number' ;; esac\ncase \"$DISPLAY_NUM\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_DISPLAY must be a number' ;; esac\ncase \"$GEOMETRY\" in [0-9]*x[0-9]*) ;; *) fail 'ORCA_DESKTOP_GEOMETRY must look like 1280x800' ;; esac\ncommand -v Xvnc >/dev/null || fail 'not installed in this image (Xvnc missing)' 3\n[ -s \"$DESKTOP/novnc/vnc.html\" ] || fail 'not installed in this image (noVNC missing)' 3\nPROXY=\"$(dirname \"$(readlink -f \"$0\")\")/orca-desktop-proxy\"\n[ -x \"$PROXY\" ] || fail 'orca-desktop-proxy missing next to this script'\nTICKETS=\"$STATE/tickets\"\nTICKET_TTL_S=60\n# Xvnc's mode: a previous version of this script ran it with VncAuth; restart it in this mode.\nMODE=ticket-v1\n\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/start.lock\"\nflock -w 30 9 || fail 'another start is in progress'\n\npid_of() { # never \"0\": kill 0 targets our own process group\n local pid\n pid=\"$(cat \"$STATE/$1.pid\" 2>/dev/null || true)\"\n case \"$pid\" in '' | 0 | *[!0-9]*) return 1 ;; esac\n printf '%s' \"$pid\"\n}\nalive() { local pid; pid=\"$(pid_of \"$1\")\" && kill -0 \"$pid\" 2>/dev/null; }\nmint_ticket() { # prints the ticket; stores only its sha256, with the expiry as content\n local ticket now digest\n mkdir -p \"$TICKETS\"\n now=\"$(date +%s)\"\n # Expired or spent-but-unswept tickets; keep at most 16 live ones (oldest go first).\n for file in \"$TICKETS\"/*; do\n [ -f \"$file\" ] || continue\n [ \"$(cat \"$file\" 2>/dev/null || echo 0)\" -ge \"$now\" ] 2>/dev/null || rm -f \"$file\"\n done\n # shellcheck disable=SC2012 # names are hex digests\n ls -1t \"$TICKETS\" 2>/dev/null | tail -n +16 | while read -r old; do rm -f \"$TICKETS/$old\"; done\n ticket=\"$(head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\\n')\"\n [ \"${#ticket}\" = 43 ] || fail 'could not generate a ticket'\n digest=\"$(printf '%s' \"$ticket\" | sha256sum | cut -d' ' -f1)\"\n printf '%s' \"$((now + TICKET_TTL_S))\" >\"$TICKETS/.$digest\" && mv \"$TICKETS/.$digest\" \"$TICKETS/$digest\"\n printf '%s' \"$ticket\"\n}\nready_line() {\n local ticket\n ticket=\"$(mint_ticket)\" || exit 1\n printf '{\"schemaVersion\":2,\"port\":%s,\"display\":\":%s\",\"path\":\"vnc.html\",\"ticket\":\"%s\",\"expiresInMs\":%s}\\n' \\\n \"$PORT\" \"$DISPLAY_NUM\" \"$ticket\" \"$((TICKET_TTL_S * 1000))\"\n}\nlistening() { # the proxy answers HTTP on loopback\n curl -fsS -o /dev/null --max-time 1 \"http://127.0.0.1:$PORT/vnc.html\" 2>/dev/null\n}\n\n# Pids from a previous boot (resume = reboot from disk) name dead or unrelated processes.\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" != \"$boot_id\" ]; then\n rm -rf \"$STATE\"/*.pid \"$SOCKET\" \"$STATE/password\" \"$STATE/passwd\" \"$STATE/mode\" \"$TICKETS\"\n printf '%s' \"$boot_id\" >\"$STATE/boot-id\"\nfi\n\n# Same boot, older script: its websockify had no ticket gate and its Xvnc wanted a VNC password.\nrm -f \"$STATE/password\" \"$STATE/passwd\"\nif alive websockify; then kill \"$(pid_of websockify)\" 2>/dev/null || true; fi\nrm -f \"$STATE/websockify.pid\"\ncurrent_mode() { cat \"$STATE/mode\" 2>/dev/null || true; }\n\nif alive xvnc && alive proxy && listening && [ \"$(current_mode)\" = \"$MODE\" ]; then\n ready_line\n exit 0\nfi\n\nstart() { # name cmd... — detached, logs in $STATE/.log\n local name=$1; shift\n # 9>&-: children must not inherit the start lock, or the next call waits for them to exit.\n setsid nohup \"$@\" >\"$STATE/$name.log\" 2>&1 &- &\n echo $! >\"$STATE/$name.pid\"\n}\n\nif ! alive xvnc || [ \"$(current_mode)\" != \"$MODE\" ]; then\n if alive xvnc; then kill \"$(pid_of xvnc)\" 2>/dev/null || true; sleep 0.2; fi\n rm -f \"$SOCKET\"\n # -rfbport -1: no TCP VNC port at all, only a 0600 unix socket (in the 0700 state dir) for the\n # proxy. SecurityTypes None is safe only because of that: the ticket gate is in the proxy.\n # SendPrimary=0: only explicit copies (xterm copies its selection, below) leave the sandbox.\n # The X display itself takes a cookie from ~/.Xauthority (Xlib's default for this user), so only\n # this uid's processes (agents, apps they start on DISPLAY=:1) can open it.\n auth=()\n if command -v xauth >/dev/null && command -v mcookie >/dev/null; then\n xauth -q -f \"$HOME/.Xauthority\" add \":$DISPLAY_NUM\" . \"$(mcookie)\" 9>&- && auth=(-auth \"$HOME/.Xauthority\")\n fi\n start xvnc Xvnc \":$DISPLAY_NUM\" \"${auth[@]}\" -geometry \"$GEOMETRY\" -depth 24 -nolisten tcp \\\n -rfbport -1 -rfbunixpath \"$SOCKET\" -rfbunixmode 0600 \\\n -SecurityTypes None -SendPrimary=0 \\\n -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote desktop'\n printf '%s' \"$MODE\" >\"$STATE/mode\"\n for _ in $(seq 1 100); do\n [ -S \"$SOCKET\" ] && break\n alive xvnc || { tail -n 20 \"$STATE/xvnc.log\" >&2; fail 'Xvnc exited'; }\n sleep 0.05\n done\n [ -S \"$SOCKET\" ] || fail 'Xvnc did not create its socket'\n if command -v xsetroot >/dev/null; then xsetroot -solid '#1e1f22' 9>&- || true; fi\n if command -v openbox >/dev/null; then\n # Dark, flat theme to match Orca; the first terminal stays maximized as the tab resizes the screen.\n printf '%s\\n' '' \\\n 'Onyx' \\\n 'yes' \\\n '' >\"$STATE/openbox.xml\"\n start wm openbox --config-file \"$STATE/openbox.xml\"\n # Let it manage the screen before the terminal maps, so its maximize rule applies.\n sleep 0.2\n elif command -v twm >/dev/null; then\n start wm twm\n fi\n if command -v xterm >/dev/null; then\n # selectToClipboard: a selection is a copy (to CLIPBOARD, which reaches this computer).\n start xterm xterm -maximized -bg '#1e1f22' -fg '#d4d4d4' -fa 'Liberation Mono,Monospace' -fs 11 \\\n -xrm 'XTerm*selectToClipboard: true'\n fi\nfi\n\nif ! alive proxy || ! listening; then\n if alive proxy; then kill \"$(pid_of proxy)\" 2>/dev/null || true; sleep 0.1; fi\n mkdir -p \"$TICKETS\"\n PYTHONPATH=\"$DESKTOP/websockify\" start proxy python3 -P -W ignore::UserWarning \"$PROXY\" \\\n --listen \"$PORT\" --web \"$DESKTOP/novnc\" --unix-target \"$SOCKET\" --tickets \"$TICKETS\"\n for _ in $(seq 1 100); do\n listening && break\n alive proxy || { tail -n 20 \"$STATE/proxy.log\" >&2; fail 'orca-desktop-proxy exited'; }\n sleep 0.05\n done\n listening || fail \"orca-desktop-proxy is not answering on 127.0.0.1:$PORT\"\nfi\nready_line\n","orca-desktop-proxy":"#!/usr/bin/env python3\n# Remote desktop gateway, started by orca-desktop-start: serves noVNC on 127.0.0.1 and bridges one\n# WebSocket per single-use ticket to Xvnc's 0600 unix socket (Xvnc itself has no VNC auth: only this\n# uid can open the socket). The port is reached only through Orca's localhost forward on the user's\n# computer, where any local process or web page could knock, so every WebSocket must carry an\n# unused, unexpired ticket minted by orca-desktop-start (see consume_ticket), from a page on the same\n# localhost origin. Tickets never reach a log: paths are scrubbed before websockify logs them.\n# orca-desktop-proxy --listen PORT --web DIR --unix-target SOCKET --tickets DIR\n# stdlib + websockify (pinned tarball in /opt/orca/desktop/websockify, on PYTHONPATH) only.\nimport argparse\nimport hashlib\nimport hmac\nimport logging\nimport os\nimport re\nimport sys\nimport time\nfrom urllib.parse import parse_qs, urlsplit\n\nfrom websockify import websocketproxy\n\nTICKET_RE = re.compile(r'^[A-Za-z0-9_-]{43}$') # 32 random bytes, base64url without padding\nSCRUB_RE = re.compile(r'([?&]ticket=)[^&\\s\\'\"]*')\nLOOPBACK_HOST_RE = re.compile(r'^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:[0-9]{1,5})?$')\nWS_PATH = '/websockify'\nPAGE_SCRIPT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'orca-desktop-page.js')\n# The page may only talk to its own origin (its WebSocket included): even a URL that tries to point\n# noVNC elsewhere cannot carry a ticket or the user's keys off this forward.\nPAGE_CSP = \"connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'\"\nPAGE_TAG = b'\\n'\n\n\ndef scrub(text):\n return SCRUB_RE.sub(r'\\1', str(text))\n\n\ndef ticket_digest(ticket):\n return hashlib.sha256(ticket.encode('ascii')).hexdigest()\n\n\ndef consume_ticket(directory, ticket, now=None):\n \"\"\"True once per minted ticket, within its lifetime. The ticket file (named by the ticket's\n sha256, holding its expiry) is unlinked on first use, so a replay or a racing second\n connection finds nothing; each request runs in its own forked process, so state is on disk.\"\"\"\n if not isinstance(ticket, str) or not TICKET_RE.match(ticket):\n return False\n digest = ticket_digest(ticket)\n match = None\n try:\n names = os.listdir(directory)\n except OSError:\n return False\n for name in names:\n # Compare every entry in constant time; never short-circuit on a prefix.\n if hmac.compare_digest(name.encode('ascii', 'replace'), digest.encode('ascii')):\n match = name\n if match is None:\n return False\n path = os.path.join(directory, match)\n try:\n with open(path, 'r', encoding='ascii') as handle:\n expires_at = int(handle.read().strip() or '0')\n except (OSError, ValueError):\n expires_at = 0\n try:\n os.unlink(path) # the consume: only one caller can win this\n except FileNotFoundError:\n return False\n return (now if now is not None else time.time()) <= expires_at\n\n\ndef same_loopback_origin(headers):\n \"\"\"The page and the WebSocket share one localhost origin (blocks other local sites and DNS\n rebinding). The port is the user's local forward, which may differ from ours, so compare the\n Origin with the Host the browser dialed rather than with a fixed port.\"\"\"\n host = (headers.get('Host') or '').strip().lower()\n origin = (headers.get('Origin') or '').strip().lower()\n return loopback_host(host) and origin == 'http://' + host\n\n\ndef loopback_host(host):\n return bool(LOOPBACK_HOST_RE.match(host or ''))\n\n\nclass TicketedProxyHandler(websocketproxy.ProxyRequestHandler):\n \"\"\"websockify's proxy handler plus the ticket + origin gate. Module level (not a closure) so\n websockify's per-connection multiprocessing can pickle it under any start method.\"\"\"\n\n def log_message(self, format, *args): # noqa: A002 (websockify's signature)\n super().log_message('%s', scrub(format % args if args else format))\n\n def reject(self, code, reason):\n self.send_response(code)\n self.send_header('Content-Length', '0')\n self.send_header('Connection', 'close')\n self.end_headers()\n self.close_connection = True\n raise self.server.EClose('desktop: websocket refused (%s)' % reason)\n\n def validate_connection(self):\n parts = urlsplit(self.path)\n ticket = (parse_qs(parts.query).get('ticket') or [''])[0]\n # Drop it before anything below (websockify's own logging included) can see self.path.\n self.path = parts.path\n if parts.path != WS_PATH:\n self.reject(404, 'path')\n if not same_loopback_origin(self.headers):\n self.reject(403, 'origin')\n if not consume_ticket(self.server.orca_tickets_dir, ticket):\n self.reject(403, 'ticket')\n\n def loopback_request(self):\n if loopback_host((self.headers.get('Host') or '').strip().lower()):\n return True\n self.send_error(403)\n return False\n\n def do_GET(self):\n if not self.loopback_request():\n return None\n path = urlsplit(self.path).path\n if path == '/orca-desktop-page.js':\n return self.send_bytes(read_file(PAGE_SCRIPT), 'text/javascript; charset=utf-8')\n if path == '/vnc.html':\n page = read_file(os.path.join(self.server.web, 'vnc.html'))\n return self.send_bytes(page.replace(b'', PAGE_TAG, 1), 'text/html; charset=utf-8', PAGE_CSP)\n return super().do_GET()\n\n def do_HEAD(self):\n if not self.loopback_request():\n return None\n return super().do_HEAD()\n\n def send_bytes(self, body, content_type, csp=None):\n self.send_response(200)\n self.send_header('Content-Type', content_type)\n if csp:\n self.send_header('Content-Security-Policy', csp)\n self.send_header('Content-Length', str(len(body)))\n self.send_header('Cache-Control', 'no-store')\n self.send_header('Referrer-Policy', 'no-referrer')\n self.end_headers()\n self.wfile.write(body)\n return None\n\n\ndef read_file(path):\n with open(path, 'rb') as handle:\n return handle.read()\n\n\ndef main(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--listen', type=int, required=True)\n parser.add_argument('--web', required=True)\n parser.add_argument('--unix-target', required=True)\n parser.add_argument('--tickets', required=True)\n args = parser.parse_args(argv)\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n server = websocketproxy.WebSocketProxy(\n RequestHandlerClass=TicketedProxyHandler,\n listen_host='127.0.0.1',\n listen_port=args.listen,\n web=args.web,\n file_only=True,\n unix_target=args.unix_target,\n )\n server.orca_tickets_dir = os.path.abspath(args.tickets)\n server.start_server()\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","orca-desktop-page.js":"// Orca's glue for noVNC, injected into vnc.html by orca-desktop-proxy. Orca (the desktop app's\n// main process) drives it through window.orcaDesktop:\n// - tickets: the page never connects by itself. Each WebSocket needs a fresh single-use ticket,\n// which Orca hands over with connect(ticket) after nextTicketRequest() resolves: 'ticket' on\n// load or after a session dropped, 'retry' after an attempt that never connected. Tickets live\n// only in memory here: never in the URL, storage or noVNC's settings.\n// - pause(message, label): Orca stopped retrying; show why, with a Reconnect button. resume()\n// (Orca reopened the desktop) or the button asks for a ticket again.\n// - fit: resize=remote makes Xvnc follow the tab; a server without SetDesktopSize gets scaling.\n// - clipboard: a copy inside the desktop right after user input there goes to this computer's\n// clipboard; paste(text, chord) sets the sandbox's clipboard first, then replays the paste key.\nimport UI from './app/ui.js';\nimport * as WebUtil from './app/webutil.js';\n\nconst WS_PATH = 'websockify';\nconst RESIZE_FALLBACK_MS = 1500;\n// A copy inside the desktop follows a copy key or a selection (drag or double-click) there; other\n// clipboard changes (an agent in the sandbox running xclip) must not overwrite this computer's\n// clipboard. Plain typing does not open the window.\nconst USER_COPY_WINDOW_MS = 1500;\nconst DRAG_PX = 4;\nconst MAX_CLIPBOARD_CHARS = 1 << 20;\nconst TICKET_RE = /^[A-Za-z0-9_-]{43}$/;\nconst XK = { v: 0x0076, V: 0x0056, Insert: 0xff63, Shift_L: 0xffe1, Super_L: 0xffeb, Super_R: 0xffec };\n\nlet state = 'idle'; // idle | connecting | connected | disconnected | paused\nlet attemptConnected = true;\nlet ticketWaiters = [];\nlet lastCopyIntent = 0;\nlet pointerStart = null;\n\nconst style = document.createElement('style');\n// Orca owns connecting and the chrome: noVNC's Connect button would only try without a ticket,\n// and its control bar duplicates what the Orca tab does (fit, clipboard, keyboard release).\n// The pause card follows Orca's theme: Orca sets Electron's theme source from its own setting, so\n// prefers-color-scheme here is Orca's light or dark, and it follows a switch while paused. The\n// page cannot read Orca's tokens, so these mirror them (popover, border, focus ring).\nstyle.textContent = `\n#noVNC_connect_dlg, #noVNC_control_bar_anchor { display: none !important; }\n#orca_pause { --orca-scrim: rgb(10 10 10 / 0.88); --orca-card: #171717; --orca-text: #f0f0f0;\n --orca-border: rgb(255 255 255 / 0.1); --orca-control: rgb(255 255 255 / 0.25);\n --orca-control-hover: rgb(255 255 255 / 0.08); --orca-focus: color-mix(in oklab, #f0f0f0 65%, #0a0a0a);\n color-scheme: dark; position: fixed; inset: 0; display: none; align-items: center;\n justify-content: center; padding: 16px; background: var(--orca-scrim); z-index: 1000;\n font: 13px/1.5 system-ui, sans-serif; }\n@media (prefers-color-scheme: light) {\n #orca_pause { --orca-scrim: rgb(255 255 255 / 0.88); --orca-card: #fff; --orca-text: #0a0a0a;\n --orca-border: #e5e5e5; --orca-control: #a3a3a3; --orca-control-hover: #f5f5f5;\n --orca-focus: color-mix(in oklab, #0a0a0a 55%, #fff); color-scheme: light; }\n}\n#orca_pause.open { display: flex; }\n#orca_pause > div { max-width: 360px; padding: 16px; border: 1px solid var(--orca-border);\n border-radius: 8px; background: var(--orca-card); color: var(--orca-text); text-align: center;\n box-shadow: 0 8px 24px rgb(0 0 0 / 0.16); }\n#orca_pause p { margin: 0; }\n#orca_pause button { margin-top: 12px; padding: 4px 12px; border: 1px solid var(--orca-control);\n border-radius: 6px; background: transparent; color: var(--orca-text); font: inherit; cursor: pointer; }\n#orca_pause button:hover { background: var(--orca-control-hover); }\n#orca_pause button:focus-visible { outline: 2px solid var(--orca-focus); outline-offset: 2px; }\n@media (prefers-reduced-motion: no-preference) {\n #orca_pause.open > div { animation: orca-pause-in 120ms ease-out; }\n}\n@keyframes orca-pause-in { from { opacity: 0; transform: translateY(4px); } }\n`;\ndocument.head.appendChild(style);\n\nconst overlay = document.createElement('div');\noverlay.id = 'orca_pause';\noverlay.innerHTML = '

    ';\noverlay.querySelector('button').addEventListener('click', () => resume());\ndocument.addEventListener('DOMContentLoaded', () => document.body.appendChild(overlay));\n\nwindow.addEventListener('keydown', (event) => {\n if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.key === 'c' || event.key === 'C' || event.key === 'Insert')) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerdown', (event) => {\n pointerStart = { x: event.clientX, y: event.clientY };\n}, true);\n// A double- or triple-click selects a word or line (pointer events carry no click count).\nwindow.addEventListener('mousedown', (event) => {\n if (event.detail >= 2) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerup', (event) => {\n if (pointerStart && Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y) >= DRAG_PX) {\n lastCopyIntent = Date.now();\n }\n pointerStart = null;\n}, true);\n\nfunction requestTicket() {\n const answer = attemptConnected ? 'ticket' : 'retry';\n const waiters = ticketWaiters;\n ticketWaiters = [];\n waiters.forEach((resolve) => resolve(answer));\n}\n\nasync function whenStarted() {\n while (document.documentElement.classList.contains('noVNC_loading')) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n}\n\nfunction onConnect() {\n state = 'connected';\n attemptConnected = true;\n UI.hideStatus();\n setTimeout(() => {\n // Xvnc answers SetDesktopSize; anything that does not gets scaled into the tab instead.\n if (UI.rfb && state === 'connected' && !UI.rfb._supportsSetDesktopSize) {\n UI.rfb.scaleViewport = true;\n }\n }, RESIZE_FALLBACK_MS);\n}\n\nfunction onDisconnect() {\n if (state === 'paused') {\n return;\n }\n state = 'disconnected';\n // The ticket is spent: ask Orca for a new one (a dropped forward, a restart of the desktop).\n requestTicket();\n}\n\nfunction onClipboard(event) {\n const text = event.detail && event.detail.text;\n if (typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return;\n }\n if (Date.now() - lastCopyIntent > USER_COPY_WINDOW_MS || !document.hasFocus()) {\n return;\n }\n navigator.clipboard.writeText(text).catch(() => {});\n}\n\nasync function connect(ticket) {\n if (typeof ticket !== 'string' || !TICKET_RE.test(ticket)) {\n return 'invalid';\n }\n if (state === 'connecting' || state === 'connected' || state === 'paused') {\n return state;\n }\n await whenStarted();\n if (UI.rfb) {\n return 'connecting';\n }\n state = 'connecting';\n attemptConnected = false;\n // UI.connect reads the path setting synchronously and opens the WebSocket in RFB's constructor;\n // the in-memory setting is restored right after, so the ticket is never kept or shown.\n // Only ever this page's own origin: noVNC also reads host, port, encrypt, repeater and logging\n // from the URL, which must never send a ticketed session (and the user's keys) elsewhere.\n WebUtil.setSetting('host', '');\n WebUtil.setSetting('port', '');\n WebUtil.setSetting('encrypt', false);\n WebUtil.setSetting('repeaterID', '');\n WebUtil.setSetting('path', `${WS_PATH}?ticket=${ticket}`);\n try {\n UI.connect();\n } finally {\n WebUtil.setSetting('path', WS_PATH);\n }\n const rfb = UI.rfb;\n if (!rfb) {\n state = 'disconnected';\n requestTicket();\n return 'failed';\n }\n rfb.addEventListener('connect', onConnect);\n rfb.addEventListener('disconnect', onDisconnect);\n rfb.addEventListener('clipboard', onClipboard);\n return 'connecting';\n}\n\n/** Pastes this computer's clipboard: the sandbox's clipboard first, then the paste key itself. */\nfunction paste(text, chord) {\n const rfb = UI.rfb;\n if (!rfb || state !== 'connected' || typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return false;\n }\n rfb.clipboardPasteFrom(text);\n if (chord && chord.kind === 'mac') {\n // Cmd+V: Linux apps do not paste on Super+V, so release Super and send Shift+Insert.\n rfb.sendKey(XK.Super_L, 'MetaLeft', false);\n rfb.sendKey(XK.Super_R, 'MetaRight', false);\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', true);\n rfb.sendKey(XK.Insert, 'Insert');\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', false);\n } else if (chord && chord.kind === 'replay') {\n // Ctrl+V, Ctrl+Shift+V, Shift+Insert: the held modifiers already reached the sandbox.\n const insert = chord.key === 'Insert';\n rfb.sendKey(insert ? XK.Insert : chord.key === 'V' ? XK.V : XK.v, insert ? 'Insert' : 'KeyV');\n }\n return true;\n}\n\nfunction pause(message, label, tone) {\n state = 'paused';\n if (UI.rfb) {\n UI.rfb.disconnect();\n }\n UI.hideStatus();\n overlay.querySelector('p').textContent = String(message || '');\n overlay.querySelector('button').textContent = String(label || 'Reconnect');\n // Asleep and starting are states, not errors: announce them politely.\n overlay.firstElementChild.setAttribute('role', tone === 'neutral' ? 'status' : 'alert');\n overlay.classList.add('open');\n overlay.querySelector('button').focus();\n return true;\n}\n\nfunction resume() {\n if (state !== 'paused') {\n return false;\n }\n overlay.classList.remove('open');\n state = 'disconnected';\n attemptConnected = true; // a person asked: start the retry budget over\n requestTicket();\n return true;\n}\n\nObject.defineProperty(window, 'orcaDesktop', {\n value: Object.freeze({\n version: 1,\n state: () => state,\n /** Resolves when the page needs a ticket: now if it is not connected, else after a drop. */\n nextTicketRequest: () => new Promise((resolve) => {\n ticketWaiters.push(resolve);\n if (state === 'idle' || state === 'disconnected') {\n requestTicket();\n }\n }),\n connect,\n paste,\n pause,\n resume\n })\n});\n","orca-sandbox-grant":"#!/usr/bin/env bash\n# Mints a fresh, single-device orcad pairing offer for one org member's device and seals it to that\n# device's X25519 key, so the control plane relays only ciphertext (the VM owner's E2EE model holds:\n# every member device gets its own revocable orcad credential, nobody else can read it).\n# Env from the control plane: ORCA_GRANT_ID, ORCA_GRANT_RECIPIENT_KEY (base64 raw X25519 public\n# key), ORCA_GRANT_KIND (desktop|mobile), ORCA_PUBLIC_WSS. Prints one JSON line:\n# {\"deviceId\":\"…\",\"sealed\":{\"v\":1,\"ephemeralPublicKeyB64\":\"…\",\"nonceB64\":\"…\",\"ciphertextB64\":\"…\"}}\n# Sealing: ECDH(ephemeral, recipient) -> HKDF-SHA256(salt = eph||recipient, info\n# \"orca-cloud-grant-v1\") -> AES-256-GCM, AAD \"orca-cloud-grant-v1:\".\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nDATA=\"$HOME/.orcad-data\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\n# One mint at a time: --rotate retires unredeemed offers, so two members never share a credential.\nflock -w 30 9\n\ncase \"${ORCA_GRANT_ID:-}\" in '' | *[!A-Za-z0-9_-]*) echo 'bad grant id' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_KIND:-}\" in desktop) scope=() ;; mobile) scope=(--mobile) ;; *) echo 'bad kind' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_RECIPIENT_KEY:-}\" in '' | *[!A-Za-z0-9+/=]*) echo 'bad key' >&2; exit 2 ;; esac\ncase \"${ORCA_PUBLIC_WSS:-}\" in wss://*) ;; *) echo 'bad endpoint' >&2; exit 2 ;; esac\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\n# The workspace's project must exist on this orcad before a phone opens it: phones may not add\n# projects themselves (mobile RPC scope), and a phone may be the first client this VM ever sees.\nproject=/vercel/sandbox/project\nif [ -d \"$project\" ]; then\n kind=folder\n [ -d \"$project/.git\" ] && kind=git\n ORCA_USER_DATA_PATH=\"$DATA\" timeout 20 \"$node\" \"$cli\" repo add --path \"$project\" --kind \"$kind\" --json \\\n >/dev/null 2>&1 || true\nfi\noffer=\"$(ORCA_USER_DATA_PATH=\"$DATA\" timeout 30 \"$node\" \"$cli\" pair --json --rotate \"${scope[@]}\" \\\n --address \"$ORCA_PUBLIC_WSS\" 2>/dev/null)\" || { echo 'pair failed' >&2; exit 1; }\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" \\\n \"$node\" -e '\nconst crypto = require(\"node:crypto\")\nlet input = \"\"\nprocess.stdin.on(\"data\", (c) => (input += c)).on(\"end\", () => {\n const res = JSON.parse(input).result\n if (!res || res.available !== true || !res.pairingUrl || !res.deviceId) {\n console.error(\"offer unavailable\")\n process.exit(1)\n }\n const recipient = Buffer.from(process.env.ORCA_GRANT_RECIPIENT_KEY, \"base64\")\n if (recipient.length !== 32) { console.error(\"bad key length\"); process.exit(2) }\n const recipientKey = crypto.createPublicKey({ key: { kty: \"OKP\", crv: \"X25519\", x: recipient.toString(\"base64url\") }, format: \"jwk\" })\n const eph = crypto.generateKeyPairSync(\"x25519\")\n const ephRaw = Buffer.from(eph.publicKey.export({ format: \"jwk\" }).x, \"base64url\")\n const shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: recipientKey })\n const key = Buffer.from(crypto.hkdfSync(\"sha256\", shared, Buffer.concat([ephRaw, recipient]), \"orca-cloud-grant-v1\", 32))\n const nonce = crypto.randomBytes(12)\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce)\n cipher.setAAD(Buffer.from(\"orca-cloud-grant-v1:\" + process.env.ORCA_GRANT_ID))\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope }))\n const ct = Buffer.concat([cipher.update(body), cipher.final(), cipher.getAuthTag()])\n process.stdout.write(JSON.stringify({ deviceId: res.deviceId, sealed: { v: 1, ephemeralPublicKeyB64: ephRaw.toString(\"base64\"), nonceB64: nonce.toString(\"base64\"), ciphertextB64: ct.toString(\"base64\") } }) + \"\\n\")\n})'\n","orca-sandbox-revoke":"#!/usr/bin/env bash\n# Revokes member devices from orcad's device registry. orcad adopts on-disk removals at every auth\n# (an admin revoke, device-registry-store.ts), so this works whether or not orcad is running; the\n# control plane also runs it at boot, before orcad starts, for revokes queued while suspended.\n# Env: ORCA_REVOKE_DEVICE_IDS (comma list of orcad device ids). Prints {\"revoked\":,\"live\":}.\nset -euo pipefail\numask 077\nSTATE=\"$HOME/.orca-sandbox\"\nREGISTRY=\"$HOME/.orcad-data/orca-devices.json\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\nflock -w 30 9\n\nids=\"${ORCA_REVOKE_DEVICE_IDS:-}\"\ncase \"$ids\" in '' | *[!A-Za-z0-9,_-]*) echo 'bad device ids' >&2; exit 2 ;; esac\n# Live orcad first: `orca pair --revoke` also closes the device's open sockets now. Older orcad\n# builds lack it; the on-disk removal below still blocks their next sign-in.\nORCA_HOME=/opt/orca\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node 2>/dev/null | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\nlive=0\nif [ -n \"$node\" ] && [ -f \"$cli\" ] && [ -s \"$HOME/.orcad-data/orca-runtime.json\" ]; then\n for id in ${ids//,/ }; do\n if ORCA_USER_DATA_PATH=\"$HOME/.orcad-data\" timeout 15 \"$node\" \"$cli\" pair --revoke \"$id\" --json 2>/dev/null \\\n | jq -e '.ok == true and .result.revoked == true' >/dev/null 2>&1; then\n live=$((live + 1))\n fi\n done\nfi\nif [ ! -s \"$REGISTRY\" ]; then\n echo \"{\\\"revoked\\\":$live,\\\"live\\\":$live}\"\n exit 0\nfi\nids_json=\"$(jq -cn --arg ids \"$ids\" '$ids | split(\",\") | map(select(length > 0))')\"\nbefore=\"$(jq 'length' \"$REGISTRY\")\"\ntmp=\"$(mktemp \"$REGISTRY.revoke.XXXXXX\")\"\n# Removes the rows and any phones delegated through them (parentDeviceId), like orcad's own revoke.\njq --argjson ids \"$ids_json\" \\\n '[.[] | select((.deviceId as $d | $ids | index($d)) == null and ((.parentDeviceId // \"\") as $p | $ids | index($p)) == null)]' \\\n \"$REGISTRY\" >\"$tmp\"\nchmod 0600 \"$tmp\"\nsync \"$tmp\" 2>/dev/null || true\nmv -f \"$tmp\" \"$REGISTRY\"\nafter=\"$(jq 'length' \"$REGISTRY\")\"\necho \"{\\\"revoked\\\":$((live + before - after)),\\\"live\\\":$live}\"\n","orca-sandbox-members":"#!/usr/bin/env bash\n# Runs as root (control plane, sudo). Installs who-may-push-as-whom for `orca-git-as`:\n# /etc/orca/members/.gitconfig egress placeholder header + GitHub author identity\n# /etc/orca/members/devices.json {\"\": \"\"} (each member's paired devices)\n# Both root-only: agents never read another member's placeholder. `orca-git-identity` (root, via a\n# sudoers rule) hands an agent only the identity of the member whose device drove its turn, as orcad\n# attests it. No token lives here: the placeholder is swapped at egress, for this repository only.\n# Env: ORCA_MEMBERS_B64 = base64 JSON [{userId, name, email, authorization, deviceIds:[...]}]\n# The VM user agents run as is orcad's own user (detected). Prints {\"members\":,\"devices\":}.\nset -euo pipefail\numask 077\nDIR=/etc/orca/members\norcad_pid=\"$(pgrep -f orcad-server.js | head -n 1 || true)\"\nUSER_NAME=\"$( [ -n \"$orcad_pid\" ] && ps -o user= -p \"$orcad_pid\" | tr -d ' ' || true)\"\nUSER_NAME=\"${USER_NAME:-${ORCA_SANDBOX_USER:-${SUDO_USER:-}}}\"\ncase \"$USER_NAME\" in '' | *[!a-z0-9_-]*) echo 'bad user' >&2; exit 2 ;; esac\nmkdir -p /etc/orca\njson=\"$(printf '%s' \"${ORCA_MEMBERS_B64:-W10=}\" | base64 -d)\"\ntmp=\"$(mktemp -d /etc/orca/members.XXXXXX)\"\ncount=0\nwhile IFS= read -r row; do\n user=\"$(jq -r '.userId' <<<\"$row\")\"\n case \"$user\" in '' | *[!A-Za-z0-9_.:-]*) continue ;; esac\n file=\"$tmp/$(printf '%s' \"$user\" | tr ':' '_').gitconfig\"\n # An empty extraheader first resets the image-wide (app identity) header for this member's git.\n git config -f \"$file\" --add http.https://github.com/.extraheader ''\n git config -f \"$file\" --add http.https://github.com/.extraheader \"Authorization: $(jq -r '.authorization' <<<\"$row\")\"\n git config -f \"$file\" user.name \"$(jq -r '.name' <<<\"$row\")\"\n git config -f \"$file\" user.email \"$(jq -r '.email' <<<\"$row\")\"\n count=$((count + 1))\ndone < <(jq -c '.[]' <<<\"$json\")\njq -c '[.[] | select(.userId | test(\"^[A-Za-z0-9_.:-]+$\")) | .userId as $u | (.deviceIds // [])[] | select(test(\"^[A-Za-z0-9_-]{1,128}$\")) | {key: ., value: $u}] | from_entries' <<<\"$json\" >\"$tmp/devices.json\"\ndevices=\"$(jq 'length' \"$tmp/devices.json\")\"\nchmod 0700 \"$tmp\" && chmod 0600 \"$tmp\"/*\nrm -rf \"$DIR.old\"\n[ -d \"$DIR\" ] && mv \"$DIR\" \"$DIR.old\"\nmv \"$tmp\" \"$DIR\"\nrm -rf \"$DIR.old\"\n# Agents may ask for their own sender's identity, and only that (the helper checks with orcad).\nrule=\"$USER_NAME ALL=(root) NOPASSWD:SETENV: /opt/orca/bin/orca-git-identity\"\nprintf '%s\\n' \"$rule\" >/etc/sudoers.d/orca-git-identity.new\nchmod 0440 /etc/sudoers.d/orca-git-identity.new\nif visudo -cf /etc/sudoers.d/orca-git-identity.new >/dev/null; then\n mv -f /etc/sudoers.d/orca-git-identity.new /etc/sudoers.d/orca-git-identity\nelse\n rm -f /etc/sudoers.d/orca-git-identity.new\n echo 'sudoers rule rejected' >&2\n exit 1\nfi\n# Pre-attestation layout (agent-readable member files) must not linger.\nuser_home=\"$(getent passwd \"$USER_NAME\" | cut -d: -f6)\"\n[ -n \"$orcad_pid\" ] && user_home=\"$(tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n 's/^HOME=//p' | head -n 1)\"\n[ -n \"$user_home\" ] && rm -rf \"$user_home/.orca-sandbox/members\"\n# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default).\nif [ -n \"$user_home\" ]; then\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email 'cloud@users.noreply.onorca.dev'\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name 'Orca Cloud'\nfi\necho \"{\\\"members\\\":$count,\\\"devices\\\":$devices}\"\n","orca-sandbox-read-snapshot":"#!/usr/bin/env bash\n# Seals a read-only snapshot of this workspace (chats, agent status, git, PR) to the reader keys the\n# control plane passes, right before the drain. Only ciphertext is printed (one JSON line); see\n# orca-read-snapshot.cjs. Exit 3: orcad isn't running (nothing to read).\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n[ -n \"$node\" ] || { echo 'node not found' >&2; exit 1; }\nexec timeout 35 \"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\"\n","orca-read-snapshot.cjs":"#!/usr/bin/env node\n// Gathers what a sleeping workspace should still show (recent chats per agent session, agent\n// status, git status/diff summary, PR link) from the running orcad over its local socket, then seals\n// it to the reader keys the control plane passed, so only ciphertext leaves the VM.\n// Run by orca-sandbox-read-snapshot right before the drain. Env:\n// ORCA_READ_SNAPSHOT_ID rsn_<24 hex> ORCA_READ_WORKSPACE_ID sbx_<24 hex>\n// ORCA_READ_RECIPIENTS JSON [{keyId, publicKeyB64}] ORCA_READ_REASON sleep|rollover\n// ORCA_USER_DATA_PATH orcad's data dir (orca-runtime.json lives there)\n// Prints one JSON line: {v:1, snapshotId, workspaceId, nonceB64, ciphertextB64, recipients[], stats}.\n// Construction (keep in sync with src/shared/cloud-workspaces/read-snapshot.ts in the app):\n// body = AES-256-GCM(dek, nonce, JSON, AAD \"orca-cloud-read-v1::\")\n// wrapped = AES-256-GCM(HKDF-SHA256(X25519(eph, reader), eph||reader, \"orca-cloud-read-wrap-v1\"),\n// nonce_i, dek, AAD \"orca-cloud-read-wrap-v1:::\")\n'use strict'\nconst crypto = require('node:crypto')\nconst fs = require('node:fs')\nconst net = require('node:net')\nconst path = require('node:path')\n\nconst INFO = 'orca-cloud-read-v1'\nconst WRAP_INFO = 'orca-cloud-read-wrap-v1'\nconst PROJECT = '/vercel/sandbox/project'\nconst LIMITS = { sessions: 12, messagesPerSession: 60, messageChars: 4000, changes: 200, commits: 10 }\n/** Plaintext budget: sealed + base64 it stays under the control plane's 220 kB and the 256 kB stdout cap. */\nconst MAX_PLAIN_BYTES = 150_000\nconst CALL_TIMEOUT_MS = 5_000\nconst TOTAL_BUDGET_MS = 20_000\n\nfunction b64(bytes) {\n return Buffer.from(bytes).toString('base64')\n}\n\nfunction x25519PublicKey(raw) {\n return crypto.createPublicKey({ key: { kty: 'OKP', crv: 'X25519', x: Buffer.from(raw).toString('base64url') }, format: 'jwk' })\n}\n\nfunction gcmSeal(key, nonce, plain, aad) {\n const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce)\n cipher.setAAD(Buffer.from(aad))\n return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()])\n}\n\n/** Seals `payload` (an object) to every recipient; a malformed key is skipped, not fatal. */\nfunction seal(payload, recipients, workspaceId, snapshotId) {\n const scope = `${workspaceId}:${snapshotId}`\n const dek = crypto.randomBytes(32)\n const nonce = crypto.randomBytes(12)\n const ciphertext = gcmSeal(dek, nonce, Buffer.from(JSON.stringify(payload)), `${INFO}:${scope}`)\n const sealedTo = []\n for (const recipient of recipients) {\n const reader = Buffer.from(String(recipient.publicKeyB64 || ''), 'base64')\n if (reader.length !== 32 || !/^rk_[0-9a-f]{24}$/.test(String(recipient.keyId || ''))) {\n continue\n }\n let shared\n const eph = crypto.generateKeyPairSync('x25519')\n try {\n shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: x25519PublicKey(reader) })\n } catch {\n continue\n }\n if (shared.every((byte) => byte === 0)) {\n continue\n }\n const ephRaw = Buffer.from(eph.publicKey.export({ format: 'jwk' }).x, 'base64url')\n const kek = Buffer.from(crypto.hkdfSync('sha256', shared, Buffer.concat([ephRaw, reader]), WRAP_INFO, 32))\n const wrapNonce = crypto.randomBytes(12)\n const wrapped = gcmSeal(kek, wrapNonce, dek, `${WRAP_INFO}:${scope}:${recipient.keyId}`)\n sealedTo.push({ keyId: recipient.keyId, ephemeralPublicKeyB64: b64(ephRaw), nonceB64: b64(wrapNonce), wrappedKeyB64: b64(wrapped) })\n }\n dek.fill(0)\n return { v: 1, snapshotId, workspaceId, nonceB64: b64(nonce), ciphertextB64: b64(ciphertext), recipients: sealedTo }\n}\n\n// --- gathering -------------------------------------------------------------------------------\n\n/** One request per connection, like the CLI. A streaming method resolves on its first frame. */\nfunction rpc(metadata, method, params, timeoutMs = CALL_TIMEOUT_MS) {\n return new Promise((resolve) => {\n const transport = (metadata.transports || [metadata.transport]).find((t) => t && (t.kind === 'unix' || t.kind === 'named-pipe'))\n if (!transport) {\n resolve(null)\n return\n }\n const socket = net.createConnection(transport.endpoint)\n const id = crypto.randomUUID()\n let buffer = ''\n let done = false\n const finish = (value) => {\n if (!done) {\n done = true\n clearTimeout(timer)\n socket.destroy()\n resolve(value)\n }\n }\n const timer = setTimeout(() => finish(null), timeoutMs)\n socket.setEncoding('utf8')\n socket.on('error', () => finish(null))\n socket.on('close', () => finish(null))\n socket.on('connect', () => socket.write(`${JSON.stringify({ id, authToken: metadata.authToken, method, params })}\\n`))\n socket.on('data', (chunk) => {\n buffer += chunk\n let newline\n while ((newline = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, newline)\n buffer = buffer.slice(newline + 1)\n let frame\n try {\n frame = JSON.parse(line)\n } catch {\n continue\n }\n if (!frame || frame.id !== id) {\n continue\n }\n finish(frame.ok === true ? frame.result : null)\n return\n }\n })\n })\n}\n\nconst isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v)\nconst str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : null)\nconst num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null)\n\nfunction messagesOf(history) {\n const items = isObj(history) && isObj(history.page) && Array.isArray(history.page.items) ? history.page.items : []\n const out = []\n for (const item of items) {\n const body = isObj(item) && isObj(item.body) ? item.body : null\n if (!body || body.kind !== 'message' || !Array.isArray(body.blocks)) {\n continue\n }\n const role = body.role\n if (role !== 'user' && role !== 'assistant' && role !== 'system') {\n continue\n }\n const text = body.blocks\n .filter((b) => isObj(b) && b.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text)\n .join('\\n')\n .trim()\n if (text) {\n out.push({ itemId: String(item.itemId).slice(0, 200), role, text: text.slice(0, LIMITS.messageChars), at: num(item.observedAt) ?? 0 })\n }\n }\n return { messages: out, hasOlder: isObj(history) && isObj(history.page) && history.page.hasOlder === true }\n}\n\nfunction gitOf(status, log) {\n if (!isObj(status) && !isObj(log)) {\n return null\n }\n const entries = isObj(status) && Array.isArray(status.entries) ? status.entries.filter(isObj) : []\n let added = 0\n let removed = 0\n let counted = false\n const changes = entries.slice(0, LIMITS.changes).map((e) => {\n const a = num(e.added)\n const r = num(e.removed)\n if (a !== null || r !== null) {\n counted = true\n }\n return { path: String(e.path).slice(0, 1024), status: str(e.status, 20) || 'modified', area: str(e.area, 20) || 'unstaged', added: a, removed: r }\n })\n for (const e of entries) {\n added += num(e.added) || 0\n removed += num(e.removed) || 0\n }\n const items = isObj(log) && Array.isArray(log.items) ? log.items.filter(isObj) : []\n return {\n branch: isObj(status) && typeof status.branch === 'string' ? status.branch.replace(/^refs\\/heads\\//, '') : null,\n head: isObj(status) ? str(status.head, 64) : null,\n changes,\n changeCount: entries.length,\n added: counted ? added : null,\n removed: counted ? removed : null,\n commits: items.slice(0, LIMITS.commits).map((c) => ({\n id: String(c.id).slice(0, 64),\n subject: String(c.subject ?? '').slice(0, 300),\n author: str(c.author, 120),\n at: num(c.timestamp)\n }))\n }\n}\n\nfunction prOf(linked) {\n if (!isObj(linked) || num(linked.number) === null || typeof linked.url !== 'string' || !linked.url.startsWith('https://')) {\n return null\n }\n return {\n number: linked.number,\n title: String(linked.title ?? '').slice(0, 300),\n state: str(linked.state, 20) || 'open',\n url: linked.url.slice(0, 500),\n checksStatus: str(linked.checksStatus, 20),\n checksSummary: str(linked.checksSummary, 200)\n }\n}\n\nconst STATUSES = new Set(['working', 'attention', 'idle'])\nconst PANE_PREFIX = 'structured-agent-session-'\n\n/**\n * Chats as orcad stores them (agent-session-journal.db, read-only): every session's provider, name\n * and last turn, open tabs first. The local socket can't stream agentSession.subscribeStatus, and\n * worktree.ps lists only agents that are live right now, so this is the complete list.\n */\nfunction storedSessions(dataDir) {\n let db\n try {\n const { DatabaseSync } = require('node:sqlite')\n db = new DatabaseSync(path.join(dataDir, 'agent-session-journal.db'), { readOnly: true })\n const open = new Set(db.prepare('SELECT session_id FROM agent_session_tabs').all().map((r) => r.session_id))\n const out = []\n for (const row of db.prepare('SELECT session_id, record_json FROM agent_session_records').all()) {\n let record\n try {\n record = JSON.parse(row.record_json)\n } catch {\n continue\n }\n const last = isObj(record.lastTurn) ? record.lastTurn : {}\n out.push({\n sessionId: row.session_id,\n agent: str(record.provider, 40),\n title: str(record.conversationName, 200) || str(last.prompt, 200),\n status: last.state === 'running' || last.state === 'submitted' ? 'working' : last.state === 'settled' ? 'idle' : 'unknown',\n turnOutcome: str(last.outcome, 40),\n updatedAt: num(record.updatedAt),\n open: open.has(row.session_id),\n lastPrompt: str(last.prompt, LIMITS.messageChars),\n lastReply: str(last.reply, LIMITS.messageChars),\n lastAt: num(last.at)\n })\n }\n return out\n } catch {\n return []\n } finally {\n try {\n db && db.close()\n } catch {}\n }\n}\n\n/** Live agent rows from worktree.ps, keyed by session id (their status wins over the stored one). */\nfunction liveAgents(worktrees) {\n const out = new Map()\n for (const w of worktrees) {\n for (const a of Array.isArray(w.agents) ? w.agents.filter(isObj) : []) {\n const tab = typeof a.paneKey === 'string' ? a.paneKey.split(':')[0] : ''\n if (!tab.startsWith(PANE_PREFIX)) {\n continue\n }\n const state = a.mainAgent && typeof a.mainAgent.state === 'string' ? a.mainAgent.state : a.state\n out.set(tab.slice(PANE_PREFIX.length), {\n agent: str(a.agentType, 40),\n title: str(a.conversationName, 200) || str(a.taskTitle, 200) || str(a.displayName, 200),\n status: state === 'working' ? 'working' : state === 'blocked' || state === 'waiting' || state === 'attention' ? 'attention' : 'idle',\n updatedAt: num(a.updatedAt)\n })\n }\n }\n return out\n}\n\n/** `call(method, params)` -> result | null. Never throws: a missing piece is left out. */\nasync function gather(call, { workspaceId, snapshotId, reason, now, deadline, listSessions = () => [] }) {\n const timeLeft = () => deadline - Date.now()\n const ps = await call('worktree.ps', { limit: 20 })\n const worktrees = isObj(ps) && Array.isArray(ps.worktrees) ? ps.worktrees.filter(isObj) : []\n const project = worktrees.find((w) => w.path === PROJECT) || worktrees[0] || null\n const selector = project && typeof project.path === 'string' ? `path:${project.path}` : `path:${PROJECT}`\n const [status, log] = await Promise.all([\n call('git.status', { worktree: selector, includeLineStats: true }),\n call('git.history', { worktree: selector, limit: LIMITS.commits })\n ])\n const live = liveAgents(worktrees)\n const byId = new Map()\n for (const s of listSessions()) {\n byId.set(s.sessionId, s)\n }\n for (const [sessionId, a] of live) {\n byId.set(sessionId, { ...(byId.get(sessionId) || { sessionId, open: true }), ...Object.fromEntries(Object.entries(a).filter(([, v]) => v !== null)) })\n }\n // Open chats first, then newest activity.\n const picked = [...byId.values()]\n .filter((s) => typeof s.sessionId === 'string')\n .sort((a, b) => Number(Boolean(b.open)) - Number(Boolean(a.open)) || (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))\n .slice(0, LIMITS.sessions)\n const sessions = []\n for (const s of picked) {\n const history = timeLeft() > 1_000 ? await call('agentSession.history', { sessionId: s.sessionId, direction: 'tail', limit: LIMITS.messagesPerSession }) : null\n let { messages, hasOlder } = messagesOf(history)\n if (messages.length === 0) {\n // No readable history (or out of time): the stored last turn still says what happened.\n const at = s.lastAt || s.updatedAt || 0\n messages = [\n ...(s.lastPrompt ? [{ itemId: `${s.sessionId}:last-prompt`, role: 'user', text: s.lastPrompt, at }] : []),\n ...(s.lastReply ? [{ itemId: `${s.sessionId}:last-reply`, role: 'assistant', text: s.lastReply, at }] : [])\n ]\n hasOlder = hasOlder || messages.length > 0\n }\n sessions.push({\n sessionId: s.sessionId.slice(0, 200),\n agent: s.agent || null,\n title: s.title || null,\n status: STATUSES.has(s.status) ? s.status : 'unknown',\n turnOutcome: s.turnOutcome || null,\n updatedAt: num(s.updatedAt),\n messages: messages.slice(-LIMITS.messagesPerSession),\n truncated: hasOlder || messages.length > LIMITS.messagesPerSession\n })\n }\n return {\n v: 1,\n workspaceId,\n snapshotId,\n capturedAt: now,\n reason,\n git: gitOf(status, log),\n pr: prOf(project && project.linkedPR),\n sessions\n }\n}\n\n/** Cuts the oldest messages (then long texts, then sessions) until the JSON fits the budget. */\nfunction fitToBudget(payload, maxBytes = MAX_PLAIN_BYTES) {\n const size = () => Buffer.byteLength(JSON.stringify(payload))\n let guard = 0\n while (size() > maxBytes && guard++ < 10_000) {\n const longest = payload.sessions.reduce((best, s) => (!best || s.messages.length > best.messages.length ? s : best), null)\n if (longest && longest.messages.length > 4) {\n longest.messages.shift()\n longest.truncated = true\n continue\n }\n const longText = payload.sessions.flatMap((s) => s.messages).find((m) => m.text.length > 500)\n if (longText) {\n longText.text = `${longText.text.slice(0, 500)}…`\n continue\n }\n if (payload.git && payload.git.changes.length > 20) {\n payload.git.changes = payload.git.changes.slice(0, 20)\n continue\n }\n if (payload.sessions.length > 1) {\n payload.sessions.pop()\n continue\n }\n payload.sessions = []\n break\n }\n return payload\n}\n\nasync function main() {\n const started = Date.now()\n const env = process.env\n const snapshotId = env.ORCA_READ_SNAPSHOT_ID || ''\n const workspaceId = env.ORCA_READ_WORKSPACE_ID || ''\n if (!/^rsn_[0-9a-f]{24}$/.test(snapshotId) || !/^sbx_[0-9a-f]{24}$/.test(workspaceId)) {\n process.stderr.write('bad ids\\n')\n process.exit(2)\n }\n let recipients\n try {\n recipients = JSON.parse(env.ORCA_READ_RECIPIENTS || '[]')\n } catch {\n recipients = null\n }\n if (!Array.isArray(recipients) || recipients.length === 0) {\n process.stderr.write('no recipients\\n')\n process.exit(2)\n }\n const dataDir = env.ORCA_USER_DATA_PATH || path.join(env.HOME || '', '.orcad-data')\n let metadata\n try {\n metadata = JSON.parse(fs.readFileSync(path.join(dataDir, 'orca-runtime.json'), 'utf8'))\n } catch {\n metadata = null\n }\n if (!metadata || !metadata.authToken) {\n process.stderr.write('orcad not running\\n')\n process.exit(3)\n }\n const deadline = started + TOTAL_BUDGET_MS\n const call = (method, params) => rpc(metadata, method, params, Math.max(250, Math.min(CALL_TIMEOUT_MS, deadline - Date.now())))\n const payload = fitToBudget(\n await gather(call, { workspaceId, snapshotId, reason: (env.ORCA_READ_REASON || 'sleep').slice(0, 20), now: Date.now(), deadline, listSessions: () => storedSessions(dataDir) })\n )\n const out = seal(payload, recipients, workspaceId, snapshotId)\n // Timing only: counts and sizes would describe the plaintext to the control plane's logs.\n out.stats = { collectMs: Date.now() - started }\n process.stdout.write(`${JSON.stringify(out)}\\n`)\n}\n\nmodule.exports = { seal, gather, fitToBudget, messagesOf, gitOf, prOf, rpc, storedSessions, liveAgents }\n\nif (require.main === module) {\n // A fixed message: an error text could carry workspace content into the control plane's logs.\n main().catch(() => {\n process.stderr.write('read snapshot failed\\n')\n process.exit(1)\n })\n}\n","orca-git-as":"#!/usr/bin/env bash\n# Runs git as the teammate whose message started this agent's turn: their GitHub identity for\n# pushes/PRs (this repository only) and their commit author.\n# orca-git-as e.g. orca-git-as push origin HEAD\n# orca-git-as --as refuses unless that member really sent the message\n# Orca attests the sender from the paired device that sent the message, never from arguments or\n# message text. Without an attested sender (not run from an agent, or the owner's local session) it\n# runs plain git with the workspace identity.\nset -euo pipefail\nexpect=''\nif [ \"${1:-}\" = '--as' ]; then\n expect=\"${2:-}\"\n shift 2 || { echo 'usage: orca-git-as [--as ] ' >&2; exit 2; }\n case \"$expect\" in '' | *[!A-Za-z0-9_.:-]*) echo 'orca-git-as: bad member id' >&2; exit 2 ;; esac\nfi\nset +e\nfile=\"$(ORCA_GIT_AS=\"$expect\" sudo -n --preserve-env=ORCA_GIT_AS,ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity)\"\nstatus=$?\nset -e\ncase \"$status\" in\n 0)\n trap 'rm -f \"$file\"' EXIT\n git -c \"include.path=$file\" \"$@\"\n ;;\n 3)\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n exec git \"$@\"\n ;;\n *) exit 4 ;;\nesac\n","orca-git-identity":"#!/usr/bin/env bash\n# Root helper behind `orca-git-as` (sudoers: the VM user may run only this). Asks orcad, as the\n# calling agent, which paired device sent the message that started the agent's latest turn\n# (`orca sender`: orcad identifies the agent from its launch evidence, never from arguments), maps\n# that device to a workspace member, and prints that member's git config file for the caller to\n# include. Optional ORCA_GIT_AS: the member the agent expects; any other answer is refused.\n# Exit codes: 0 printed a config path; 3 no member identity (use the workspace identity); 4 refused.\nset -euo pipefail\nDIR=/etc/orca/members\ncaller=\"${SUDO_USER:-}\"\ncase \"$caller\" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac\n# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).\norcad_pid=\"$(pgrep -u \"$caller\" -f orcad-server.js | head -n 1 || true)\"\n[ -n \"$orcad_pid\" ] || exit 3\norcad_env() { tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n \"s/^$1=//p\" | head -n 1; }\nhome=\"$(orcad_env HOME)\"\ndata=\"$(orcad_env ORCA_USER_DATA)\"\ndata=\"${data:-$home/.orcad-data}\"\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\ncli=/opt/orca/runtime/orcad/out/cli/index.js\n# Only the evidence variables orcad needs reach the query, which runs as the caller, not root.\nanswer=\"$(sudo -u \"$caller\" env -i HOME=\"$home\" PATH=/usr/bin:/bin ORCA_USER_DATA_PATH=\"$data\" \\\n ${ORCA_TERMINAL_HANDLE:+ORCA_TERMINAL_HANDLE=\"$ORCA_TERMINAL_HANDLE\"} \\\n ${ORCA_PANE_KEY:+ORCA_PANE_KEY=\"$ORCA_PANE_KEY\"} \\\n ${ORCA_AGENT_LAUNCH_TOKEN:+ORCA_AGENT_LAUNCH_TOKEN=\"$ORCA_AGENT_LAUNCH_TOKEN\"} \\\n ${ORCA_AGENT_SESSION_ID:+ORCA_AGENT_SESSION_ID=\"$ORCA_AGENT_SESSION_ID\"} \\\n timeout 15 \"$node\" \"$cli\" sender --json 2>/dev/null || true)\"\ndevice=\"$(jq -r '.result.sender.deviceId // empty' <<<\"$answer\" 2>/dev/null || true)\"\nif [ -z \"$device\" ] || [ ! -s \"$DIR/devices.json\" ]; then\n if [ -n \"${ORCA_GIT_AS:-}\" ]; then\n echo \"orca-git-as: Orca cannot confirm that $ORCA_GIT_AS sent this agent's latest message; refusing to push as them.\" >&2\n exit 4\n fi\n exit 3\nfi\nmember=\"$(jq -r --arg d \"$device\" '.[$d] // empty' \"$DIR/devices.json\")\"\nif [ -z \"$member\" ]; then\n [ -n \"${ORCA_GIT_AS:-}\" ] && { echo \"orca-git-as: the sender's device is not linked to a workspace member; refusing.\" >&2; exit 4; }\n exit 3\nfi\nif [ -n \"${ORCA_GIT_AS:-}\" ] && [ \"$ORCA_GIT_AS\" != \"$member\" ]; then\n echo \"orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else.\" >&2\n exit 4\nfi\nfile=\"$DIR/$(printf '%s' \"$member\" | tr ':' '_').gitconfig\"\n[ -s \"$file\" ] || exit 3\n# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as).\nout=\"$(sudo -u \"$caller\" mktemp)\"\ncat \"$file\" >\"$out\"\necho \"$out\"\n","orcad-boot":"#!/usr/bin/env node\n// Starts orcad from a V8 code cache taken after a full startup, so a boot skips compiling the\n// functions startup runs. NODE_COMPILE_CACHE only stores what V8 compiles before the bundle runs\n// (about 5 of its 15 MB); every other function compiled lazily on every boot (~300 ms of wake).\n// orcad-boot --code-cache [--write-code-cache] [orcad args...]\n// orcad sees the argv `node [orcad args...]`, as if started directly.\n// --write-code-cache (the image's smoke run) writes the cache when orcad exits. The cache is used\n// only when its header matches this bundle's bytes and this Node; otherwise orcad loads exactly as\n// before (plain require, which NODE_COMPILE_CACHE still serves). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst fs = process.getBuiltinModule('node:fs')\nconst path = process.getBuiltinModule('node:path')\nconst vm = process.getBuiltinModule('node:vm')\nconst zlib = process.getBuiltinModule('node:zlib')\nconst { Module, createRequire } = process.getBuiltinModule('node:module')\n\nconst MAGIC = 'orcad-code-cache-v1'\n\nconst args = process.argv.slice(2)\nlet cacheFile = null\nlet writeCache = false\nwhile (args[0] === '--code-cache' || args[0] === '--write-code-cache') {\n if (args[0] === '--code-cache') {\n cacheFile = args[1]\n args.splice(0, 2)\n } else {\n writeCache = true\n args.shift()\n }\n}\nconst entry = args.shift()\nif (!entry || !cacheFile) {\n console.error('usage: orcad-boot --code-cache [--write-code-cache] [args...]')\n process.exit(2)\n}\n// As for `node `: argv[1] is the resolved path, __filename the real one.\nprocess.argv = [process.argv[0], path.resolve(entry), ...args]\nlet file = process.argv[1]\ntry {\n file = fs.realpathSync(file)\n} catch {\n // A missing bundle fails in require below, as it would under plain node.\n}\n\n// One line of identity: a cache from another bundle or Node must never run (V8 only checks length).\nfunction cacheHeader(bytes) {\n return `${MAGIC} ${process.version} ${process.arch} ${bytes.length} ${zlib.crc32(bytes)}\\n`\n}\n\nfunction readCache(header) {\n let data\n try {\n data = fs.readFileSync(cacheFile)\n } catch {\n return null\n }\n const headerLength = Buffer.byteLength(header)\n if (data.length <= headerLength || data.toString('latin1', 0, headerLength) !== header) {\n console.error('orcad-boot: code cache is for another orcad build; loading without it')\n return null\n }\n return data.subarray(headerLength)\n}\n\nfunction runCompiled(header, source, cachedData) {\n // A vm.Script can serialize what startup compiled; the CommonJS loader cannot. Same wrapper,\n // filename and require as the loader, and import() resolves from the bundle like it does there.\n const options = {\n filename: file,\n cachedData: cachedData ?? undefined,\n importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER\n }\n // Node flags the loader option experimental once, on the first import() through it. Spend that\n // one-time warning here, unprinted, so orcad's stderr stays as it was.\n const emitWarning = process.emitWarning\n process.emitWarning = (warning, ...rest) => {\n if (!String(warning?.message ?? warning).includes('USE_MAIN_CONTEXT_DEFAULT_LOADER')) {\n emitWarning.call(process, warning, ...rest)\n }\n }\n let script\n try {\n new vm.Script('import(\"node:path\")', {\n filename: file,\n importModuleDynamically: options.importModuleDynamically\n })\n .runInThisContext()\n .catch(() => {})\n script = new vm.Script(Module.wrap(source), options)\n } finally {\n process.emitWarning = emitWarning\n }\n if (cachedData && script.cachedDataRejected) {\n console.error('orcad-boot: V8 rejected the code cache (other V8 flags?); compiled without it')\n }\n if (writeCache) {\n process.on('exit', () => {\n try {\n const data = script.createCachedData()\n const temporary = `${cacheFile}.${process.pid}.tmp`\n fs.writeFileSync(temporary, Buffer.concat([Buffer.from(header, 'latin1'), data]))\n fs.renameSync(temporary, cacheFile)\n console.error(`orcad-boot: wrote ${data.length} bytes of code cache`)\n } catch (error) {\n console.error(`orcad-boot: could not write the code cache: ${error.message}`)\n }\n })\n }\n const module = new Module(file, null)\n module.filename = file\n module.paths = Module._nodeModulePaths(path.dirname(file))\n const compiled = script.runInThisContext()\n compiled.call(module.exports, module.exports, createRequire(file), module, file, path.dirname(file))\n}\n\n// Locals, so neither the bundle bytes nor the cache outlive the compile.\nfunction boot() {\n // Older Node (no crc32 or main-context import()) loads as before.\n if (typeof zlib.crc32 === 'function' && vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER) {\n let bytes = null\n try {\n bytes = fs.readFileSync(file)\n } catch {\n // Missing or unreadable: require reports it as plain node would.\n }\n if (bytes) {\n const header = cacheHeader(bytes)\n const cachedData = readCache(header)\n if (cachedData || writeCache) {\n runCompiled(header, bytes.toString('utf8'), cachedData)\n return\n }\n }\n }\n createRequire(file)(file)\n}\n\nboot()\n","git":"#!/usr/bin/env bash\n# git for agents in Orca Cloud workspaces (first on orcad's PATH). Commands that author or publish\n# work run as the teammate whose message started this agent's turn (orca-git-as: orcad attests the\n# sender's paired device; root-only member identities). Everything else is plain git, untouched.\nreal=/usr/bin/git\nsub=''\nskip=0\nfor arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n -*) ;;\n *) sub=\"$arg\"; break ;;\n esac\ndone\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n # Outside an agent turn (no attested sender) orca-git-as falls back to the workspace identity.\n if [ -n \"${ORCA_TERMINAL_HANDLE:-}${ORCA_AGENT_SESSION_ID:-}\" ] && [ -x /opt/orca/bin/orca-git-as ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec /opt/orca/bin/orca-git-as \"$@\" 2> >(grep -v '^orca-git-as: no teammate identity' >&2)\n fi\n ;;\nesac\nexec \"$real\" \"$@\"\n"} export const SOURCE_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Golden build from source, run by the Worker inside the build sandbox: orcad + the orca CLI from one\n# commit of the Orca repo (cloud/integration carries host RPCs no upstream release has), then the same\n# provision-golden.sh every image uses. Inputs (env):\n# ORCA_SRC_SHA (40-hex) and either ORCA_SRC_DIR (source already uploaded) or ORCA_SRC_REPO\n# (https://github.com//) + ORCA_SRC_AUTH (an\n# `Authorization: Basic …` header value for a 1 h read-only installation token; never printed),\n# ORCA_PROVISION_SCRIPT (base64 of provision-golden.sh) + everything provision-golden.sh reads.\nset -euo pipefail\n# Vercel can report a detached build command as still running after it exits, so the outcome is also\n# a file the caller polls: /tmp/source-build.exit (exit code), /tmp/source-build.report (the\n# provision report line).\nrm -f /tmp/source-build.exit /tmp/source-build.report\ntrap 'echo $? >/tmp/source-build.exit' EXIT\nlog() { printf '[source-build] %s\\n' \"$*\" >&2; }\nstart=$(date +%s)\n[[ \"$ORCA_SRC_SHA\" =~ ^[0-9a-f]{40}$ ]] || { log 'ORCA_SRC_SHA must be a full commit sha'; exit 2; }\n\nlog 'build tools'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n sudo apt-get update -qq\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends build-essential python3 git ca-certificates >/dev/null\nelse\n sudo dnf install -y -q gcc gcc-c++ make tar gzip python3 git >/dev/null\nfi\nsudo corepack enable >/dev/null 2>&1 || true\n\nsrc=\"$HOME/orca-src\"\nif [ -n \"${ORCA_SRC_DIR:-}\" ]; then\n # Operator rotation (image/rotate-golden-from-source.ts) uploaded `git archive ` here already.\n log \"uploaded source for $ORCA_SRC_SHA\"\n src=\"$ORCA_SRC_DIR\"\n cd \"$src\" && test -f package.json\n git init -q && git add -A && git -c user.email=build@orca -c user.name=build commit -qm \"$ORCA_SRC_SHA\"\nelse\n log \"fetch $ORCA_SRC_SHA\"\n rm -rf \"$src\" && mkdir -p \"$src\" && cd \"$src\"\n git init -q\n # The header lives only in this one command's config, not in .git/config.\n git -c \"http.https://github.com/.extraheader=$ORCA_SRC_AUTH\" fetch -q --depth 1 \"$ORCA_SRC_REPO\" \"$ORCA_SRC_SHA\"\n unset ORCA_SRC_AUTH\n git -c advice.detachedHead=false checkout -q FETCH_HEAD\n test \"$(git rev-parse HEAD)\" = \"$ORCA_SRC_SHA\"\nfi\n\n# The image files come from this commit too (VM scripts, provision, manifest pins). The env the\n# caller passed is only a fallback for commits from before commit-provision-env.mjs existed.\nimage_dir=\"$src/cloud/apps/sandbox-control/image\"\nif [ -f \"$image_dir/commit-provision-env.mjs\" ]; then\n node \"$image_dir/commit-provision-env.mjs\" \"$image_dir\" >/tmp/commit-provision.env\n # shellcheck disable=SC1091\n . /tmp/commit-provision.env\n rm -f /tmp/commit-provision.env\n log \"image files from $ORCA_SRC_SHA\"\nfi\n\nlog 'build orcad + CLI'\nexport CI=1 ELECTRON_SKIP_BINARY_DOWNLOAD=1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\ncorepack pnpm install --frozen-lockfile >/tmp/src-install.log 2>&1 || { tail -40 /tmp/src-install.log >&2; exit 1; }\ncorepack pnpm -C mobile install --frozen-lockfile >/tmp/src-mobile.log 2>&1 || { tail -40 /tmp/src-mobile.log >&2; exit 1; }\ncorepack pnpm build:mobile-web >/tmp/src-mobile-web.log 2>&1 || { tail -40 /tmp/src-mobile-web.log >&2; exit 1; }\ncorepack pnpm build:orcad >/tmp/src-orcad.log 2>&1 || { tail -60 /tmp/src-orcad.log >&2; exit 1; }\ncorepack pnpm build:cli >/tmp/src-cli.log 2>&1 || { tail -40 /tmp/src-cli.log >&2; exit 1; }\nmkdir -p out/orca-cli\nnode_modules/.bin/esbuild out/cli/index.js --bundle --platform=node --target=node22 --format=cjs \\\n --outfile=out/orca-cli/orca-cli.cjs --log-level=error\nprintf '%s\\n' \"$ORCA_SRC_SHA\" >out/orcad/SOURCE_COMMIT\ntar czf /tmp/orcad.tgz -C out orcad runtimes orca-cli\nlog \"built in $(( $(date +%s) - start ))s\"\n\nexport ORCAD_BUNDLE_URL=file:///tmp/orcad.tgz\nORCAD_BUNDLE_SHA256=\"$(sha256sum /tmp/orcad.tgz | cut -d' ' -f1)\"\nexport ORCAD_BUNDLE_SHA256\ncd \"$HOME\"\nprintf '%s' \"$ORCA_PROVISION_SCRIPT\" | base64 -d >/tmp/provision-golden.sh\nunset ORCA_PROVISION_SCRIPT\nbash /tmp/provision-golden.sh | tee /tmp/source-build.report\n# Build leftovers stay out of the image.\nrm -rf \"$src\" \"$HOME/.local/share/pnpm\" \"$HOME/.cache/pnpm\" /tmp/orcad.tgz /tmp/provision-golden.sh /tmp/src-*.log\nlog \"done in $(( $(date +%s) - start ))s\"\n" -export const ENVIRONMENT_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Environment build (\"Cloud Computer\"), run by the control plane in a VM booted from the golden image.\n# Clones every repo, runs the org's install script once with `set -euo pipefail`, then records what it\n# built from (commit + lockfile blob ids per repo) so the control plane can tell when a rebuild is due.\n# Everything printed here streams live to the desktop build log.\n#\n# Env from the control plane (validated there): ORCA_BUILD_REPOS (`|||\n# ` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER, plus\n# the org secrets the environment names. `::orca-step:: ` lines mark progress.\n# Exit codes: 10 clone, 20 install script, 30 recording the result.\nset -uo pipefail\numask 022\n# One stream: the provider replays stdout and stderr separately after the fact, so a failed build's\n# log would read out of order. `::orca-error::` lines carry Orca's own failure explanations.\nexec 2>&1\nOUT=/tmp/orca-build\nROOT=/vercel/sandbox/repos\nmkdir -p \"$OUT\" \"$ROOT\"\nstep() { printf '\\n::orca-step:: %s\\n' \"$1\"; }\nstarted=$(date +%s)\nexport PATH=\"/opt/orca/tools/bin:/opt/orca/bin:$PATH\"\nexport ORCA_REPOS_ROOT=\"$ROOT\" ORCA_ENVIRONMENT_BUILD=1 CI=1 GIT_TERMINAL_PROMPT=0\nrepos() { printf '%s\\n' \"$ORCA_BUILD_REPOS\"; }\n\n# Tell the script author (often an agent) what they are installing onto.\npm=$(for c in apt-get dnf yum apk; do command -v \"$c\" >/dev/null 2>&1 && { echo \"$c\"; break; }; done)\necho \"Base image: $(. /etc/os-release 2>/dev/null && echo \"$PRETTY_NAME\"), $(nproc) vCPU, package manager: ${pm:-none} (with sudo)\"\n\nstep clone\nfirst=\"\"\nwhile IFS='|' read -r url branch dir header; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n [ -n \"$first\" ] || first=\"$dest\"\n # The egress layer swaps the placeholder for a short-lived repo token; nothing real is on disk,\n # and the header is never written to the repo's config.\n git_auth=()\n [ -z \"${header:-}\" ] || git_auth=(-c \"http.https://github.com/.extraheader=$header\")\n echo \"Cloning $url${branch:+ ($branch)}\"\n rm -rf -- \"$dest\"\n # The clone's own error shows only when it really failed (an empty repo is recovered below).\n if ! git \"${git_auth[@]}\" clone --quiet ${branch:+--branch \"$branch\"} -- \"$url\" \"$dest\" 2>\"$OUT/clone.err\"; then\n refs=0\n git \"${git_auth[@]}\" ls-remote --exit-code -- \"$url\" >/dev/null 2>&1 || refs=$?\n if [ -n \"$branch\" ] && [ \"$refs\" -eq 2 ]; then\n # Reachable but no refs at all (ls-remote exits 2): a repo with no commits yet.\n echo \"$url has no commits yet; starting it empty on $branch.\"\n rm -rf -- \"$dest\"\n { git \"${git_auth[@]}\" clone --quiet -- \"$url\" \"$dest\" 2>/dev/null && git -C \"$dest\" checkout --quiet -b \"$branch\"; } || exit 10\n else\n cat \"$OUT/clone.err\"\n echo \"::orca-error:: Could not clone $url${branch:+ at $branch}. Check that the branch exists and Orca Cloud can reach the repository.\" \n exit 10\n fi\n fi\n git -C \"$dest\" log -1 --format=' at %h %s' 2>/dev/null || echo ' (no commits yet)'\ndone < <(repos)\n\nstep install\nprintf '%s' \"${ORCA_INSTALL_SCRIPT_B64:-}\" | base64 -d >\"$OUT/install.sh\"\nif [ -s \"$OUT/install.sh\" ]; then\n echo \"Running the install script in ${first:-$ROOT}\"\n (cd \"${first:-$ROOT}\" && exec bash -euo pipefail \"$OUT/install.sh\") /dev/null)\" || continue\n git -C \"$dest\" ls-files --others --ignored --exclude-standard --directory 2>/dev/null \\\n | sed 's#/$##' | grep -E \"$deps_re\" | head -n 500 >\"$common/orca-env-deps\" || true\n if [ -n \"${ORCA_DEPS_HOOK_B64:-}\" ]; then\n # A relative core.hooksPath (husky: .husky/_) names a gitignored folder a new worktree lacks; pin\n # it to the primary checkout so every worktree runs the same hooks, ours included.\n rel=\"$(git -C \"$dest\" config --get core.hooksPath 2>/dev/null || true)\"\n case \"$rel\" in '' | /*) ;; *) git -C \"$dest\" config core.hooksPath \"$dest/$rel\" ;; esac\n hooks=\"$(git -C \"$dest\" rev-parse --path-format=absolute --git-path hooks)\"\n mkdir -p \"$hooks\"\n if [ -e \"$hooks/post-checkout\" ] && ! grep -q 'orca-env-deps' \"$hooks/post-checkout\"; then\n mv -- \"$hooks/post-checkout\" \"$hooks/post-checkout.orca-chained\"\n fi\n printf '%s' \"$ORCA_DEPS_HOOK_B64\" | base64 -d >\"$hooks/post-checkout\" && chmod 0755 \"$hooks/post-checkout\"\n fi\n n=$(wc -l <\"$common/orca-env-deps\" | tr -d ' ')\n [ \"$n\" -gt 0 ] && echo \"$dir: $n installed folder(s) carried into new workspaces.\"\ndone < <(repos)\n{\n printf '{\"durationSec\":%d,\"repos\":[' \"$(( $(date +%s) - started ))\"\n sep=\"\"\n while IFS='|' read -r url branch dir _; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n commit=$(git -C \"$dest\" rev-parse --verify --quiet HEAD 2>/dev/null || true)\n head=$(git -C \"$dest\" symbolic-ref --quiet --short HEAD 2>/dev/null || true)\n printf '%s{\"url\":\"%s\",\"dir\":\"%s\",\"branch\":\"%s\",\"commit\":\"%s\",\"lockfiles\":{' \"$sep\" \"$url\" \"$dir\" \"$head\" \"$commit\"\n lsep=\"\"\n if [ -n \"$commit\" ]; then\n for f in ${ORCA_LOCKFILES:-}; do\n blob=$(git -C \"$dest\" rev-parse --verify --quiet \"HEAD:$f\" 2>/dev/null || true)\n if [ -n \"$blob\" ]; then printf '%s\"%s\":\"%s\"' \"$lsep\" \"$f\" \"$blob\"; lsep=\",\"; fi\n done\n fi\n printf '}}'\n sep=\",\"\n done < <(repos)\n printf '],\"diskUsedBytes\":%s,\"diskTotalBytes\":%s}\\n' \\\n \"$(df -B1 --output=used / | tail -n 1 | tr -d ' ')\" \"$(df -B1 --output=size / | tail -n 1 | tr -d ' ')\"\n} >\"$OUT/result.json\" || exit 30\n# Nothing from this VM's own session belongs in the image, only what the script installed.\nrm -rf -- \"$OUT/install.sh\" \"$HOME/.bash_history\" \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\"\necho \"Disk used: $(df -h --output=used / | tail -n 1 | tr -d ' ') of $(df -h --output=size / | tail -n 1 | tr -d ' ')\"\n" +export const ENVIRONMENT_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Environment build (\"Cloud Computer\"), run by the control plane in a VM booted from the golden image.\n# Clones every repo, runs the org's install script once with `set -euo pipefail`, then records what it\n# built from (commit + lockfile blob ids per repo) so the control plane can tell when a rebuild is due.\n# Everything printed here streams live to the desktop build log.\n#\n# Env from the control plane (validated there): ORCA_BUILD_REPOS (`|||\n# ` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER and ORCA_CLONE_FILTER, plus\n# the org secrets the environment names. `::orca-step:: ` lines mark progress.\n# Exit codes: 10 clone, 20 install script, 30 recording the result.\nset -uo pipefail\numask 022\n# One stream: the provider replays stdout and stderr separately after the fact, so a failed build's\n# log would read out of order. `::orca-error::` lines carry Orca's own failure explanations.\nexec 2>&1\nOUT=/tmp/orca-build\nROOT=/vercel/sandbox/repos\nmkdir -p \"$OUT\" \"$ROOT\"\nstep() { printf '\\n::orca-step:: %s\\n' \"$1\"; }\nstarted=$(date +%s)\nexport PATH=\"/opt/orca/tools/bin:/opt/orca/bin:$PATH\"\nexport ORCA_REPOS_ROOT=\"$ROOT\" ORCA_ENVIRONMENT_BUILD=1 CI=1 GIT_TERMINAL_PROMPT=0\nrepos() { printf '%s\\n' \"$ORCA_BUILD_REPOS\"; }\n\n# Tell the script author (often an agent) what they are installing onto.\npm=$(for c in apt-get dnf yum apk; do command -v \"$c\" >/dev/null 2>&1 && { echo \"$c\"; break; }; done)\necho \"Base image: $(. /etc/os-release 2>/dev/null && echo \"$PRETTY_NAME\"), $(nproc) vCPU, package manager: ${pm:-none} (with sudo)\"\n\nstep clone\nfirst=\"\"\nwhile IFS='|' read -r url branch dir header; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n [ -n \"$first\" ] || first=\"$dest\"\n # The egress layer swaps the placeholder for a short-lived repo token; nothing real is on disk,\n # and the header is never written to the repo's config.\n git_auth=()\n [ -z \"${header:-}\" ] || git_auth=(-c \"http.https://github.com/.extraheader=$header\")\n echo \"Cloning $url${branch:+ ($branch)}\"\n rm -rf -- \"$dest\"\n # The clone's own error shows only when it really failed (an empty repo is recovered below).\n # ORCA_CLONE_FILTER (automatic environments: blob:none) keeps history and trees, not every old blob.\n if ! git \"${git_auth[@]}\" clone --quiet ${ORCA_CLONE_FILTER:+--filter=\"$ORCA_CLONE_FILTER\"} ${branch:+--branch \"$branch\"} -- \"$url\" \"$dest\" 2>\"$OUT/clone.err\"; then\n refs=0\n git \"${git_auth[@]}\" ls-remote --exit-code -- \"$url\" >/dev/null 2>&1 || refs=$?\n if [ -n \"$branch\" ] && [ \"$refs\" -eq 2 ]; then\n # Reachable but no refs at all (ls-remote exits 2): a repo with no commits yet.\n echo \"$url has no commits yet; starting it empty on $branch.\"\n rm -rf -- \"$dest\"\n { git \"${git_auth[@]}\" clone --quiet -- \"$url\" \"$dest\" 2>/dev/null && git -C \"$dest\" checkout --quiet -b \"$branch\"; } || exit 10\n else\n cat \"$OUT/clone.err\"\n echo \"::orca-error:: Could not clone $url${branch:+ at $branch}. Check that the branch exists and Orca Cloud can reach the repository.\" \n exit 10\n fi\n fi\n git -C \"$dest\" log -1 --format=' at %h %s' 2>/dev/null || echo ' (no commits yet)'\ndone < <(repos)\n\nstep install\nprintf '%s' \"${ORCA_INSTALL_SCRIPT_B64:-}\" | base64 -d >\"$OUT/install.sh\"\nif [ -s \"$OUT/install.sh\" ]; then\n echo \"Running the install script in ${first:-$ROOT}\"\n (cd \"${first:-$ROOT}\" && exec bash -euo pipefail \"$OUT/install.sh\") /dev/null)\" || continue\n git -C \"$dest\" ls-files --others --ignored --exclude-standard --directory 2>/dev/null \\\n | sed 's#/$##' | grep -E \"$deps_re\" | head -n 500 >\"$common/orca-env-deps\" || true\n if [ -n \"${ORCA_DEPS_HOOK_B64:-}\" ]; then\n # A relative core.hooksPath (husky: .husky/_) names a gitignored folder a new worktree lacks; pin\n # it to the primary checkout so every worktree runs the same hooks, ours included.\n rel=\"$(git -C \"$dest\" config --get core.hooksPath 2>/dev/null || true)\"\n case \"$rel\" in '' | /*) ;; *) git -C \"$dest\" config core.hooksPath \"$dest/$rel\" ;; esac\n hooks=\"$(git -C \"$dest\" rev-parse --path-format=absolute --git-path hooks)\"\n mkdir -p \"$hooks\"\n if [ -e \"$hooks/post-checkout\" ] && ! grep -q 'orca-env-deps' \"$hooks/post-checkout\"; then\n mv -- \"$hooks/post-checkout\" \"$hooks/post-checkout.orca-chained\"\n fi\n printf '%s' \"$ORCA_DEPS_HOOK_B64\" | base64 -d >\"$hooks/post-checkout\" && chmod 0755 \"$hooks/post-checkout\"\n fi\n n=$(wc -l <\"$common/orca-env-deps\" | tr -d ' ')\n [ \"$n\" -gt 0 ] && echo \"$dir: $n installed folder(s) carried into new workspaces.\"\ndone < <(repos)\n{\n printf '{\"durationSec\":%d,\"repos\":[' \"$(( $(date +%s) - started ))\"\n sep=\"\"\n while IFS='|' read -r url branch dir _; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n commit=$(git -C \"$dest\" rev-parse --verify --quiet HEAD 2>/dev/null || true)\n head=$(git -C \"$dest\" symbolic-ref --quiet --short HEAD 2>/dev/null || true)\n printf '%s{\"url\":\"%s\",\"dir\":\"%s\",\"branch\":\"%s\",\"commit\":\"%s\",\"lockfiles\":{' \"$sep\" \"$url\" \"$dir\" \"$head\" \"$commit\"\n lsep=\"\"\n if [ -n \"$commit\" ]; then\n for f in ${ORCA_LOCKFILES:-}; do\n blob=$(git -C \"$dest\" rev-parse --verify --quiet \"HEAD:$f\" 2>/dev/null || true)\n if [ -n \"$blob\" ]; then printf '%s\"%s\":\"%s\"' \"$lsep\" \"$f\" \"$blob\"; lsep=\",\"; fi\n done\n fi\n printf '}}'\n sep=\",\"\n done < <(repos)\n printf '],\"diskUsedBytes\":%s,\"diskTotalBytes\":%s}\\n' \\\n \"$(df -B1 --output=used / | tail -n 1 | tr -d ' ')\" \"$(df -B1 --output=size / | tail -n 1 | tr -d ' ')\"\n} >\"$OUT/result.json\" || exit 30\n# Nothing from this VM's own session belongs in the image, only what the script installed.\nrm -rf -- \"$OUT/install.sh\" \"$HOME/.bash_history\" \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\"\necho \"Disk used: $(df -h --output=used / | tail -n 1 | tr -d ' ') of $(df -h --output=size / | tail -n 1 | tr -d ' ')\"\n" export const ENVIRONMENT_DEPS_HOOK: string = "#!/usr/bin/env bash\n# Installed by Orca environment builds as the repo's post-checkout hook. When git creates a new linked\n# worktree (`git worktree add` passes the null commit as the previous HEAD), give it the dependency\n# folders the build installed in the primary checkout, as hard links: near-instant, real paths (not\n# symlinks, so bundlers and native modules behave). Hard links share file contents: tools that rewrite\n# a file in place inside these folders change it for every worktree on this VM (one workspace per VM).\n# Any post-checkout hook the repo already had runs afterwards, unchanged.\nprev=\"${1:-}\"\nhere=\"$(dirname \"$0\")\"\nif [ \"$prev\" = \"0000000000000000000000000000000000000000\" ] && [ \"${ORCA_SKIP_DEPS_LINK:-}\" != 1 ]; then\n common=\"$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null || true)\"\n top=\"$(git rev-parse --show-toplevel 2>/dev/null || true)\"\n primary=\"$(dirname \"$common\")\"\n list=\"$common/orca-env-deps\"\n if [ -n \"$top\" ] && [ \"$top\" != \"$primary\" ] && [ -f \"$list\" ]; then\n started=$(date +%s%N)\n linked=0\n while IFS= read -r rel; do\n case \"$rel\" in '' | /* | *..*) continue ;; esac\n [ -e \"$primary/$rel\" ] && [ ! -e \"$top/$rel\" ] || continue\n mkdir -p \"$(dirname \"$top/$rel\")\"\n if [ -d \"$primary/$rel\" ]; then\n if ! cp -al -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null; then\n # A partial hard-link copy would make the fallback nest inside it: start clean.\n rm -rf -- \"$top/$rel\"\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || { rm -rf -- \"$top/$rel\"; continue; }\n fi\n else\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || continue\n fi\n linked=$((linked + 1))\n done <\"$list\"\n if [ \"$linked\" -gt 0 ]; then\n echo \"Orca: reused $linked installed dependency folder(s) from the environment build ($(( ($(date +%s%N) - started) / 1000000 )) ms).\" >&2\n fi\n fi\nfi\nif [ -x \"$here/post-checkout.orca-chained\" ]; then\n if head -n 1 \"$here/post-checkout.orca-chained\" | grep -Eq '^#!.*(ba|da|z)?sh'; then\n # Sourced, so $0 still names `post-checkout` (husky v9 finds the user's hook by basename \"$0\").\n ( . \"$here/post-checkout.orca-chained\" \"$@\" )\n exit $?\n fi\n exec \"$here/post-checkout.orca-chained\" \"$@\"\nfi\nexit 0\n" -export const WORKSPACE_PRELUDE_SCRIPT: string = "#!/usr/bin/env bash\n# Runs right before orca-sandbox-start on a workspace's first boot. Prints only to stderr: the start\n# script's last stdout line is the orcad recipe line the control plane parses.\n#\n# - Booted from an environment build (ORCA_ENV_REPO_DIR set): the repo is already cloned with its\n# dependencies installed under /vercel/sandbox/repos. Link it as the project (a link, not a move,\n# so absolute paths baked into installed dependencies keep working). No fetch when the build is\n# already on the requested branch: Orca fetches the base right before it adds the workspace's\n# worktree, so a fetch here would only delay orcad (measured ~0.5-1 s). Another branch is fetched\n# and checked out; if that fails the workspace still opens at the build's commit.\n# - Otherwise clone ORCA_REPO_URL here so a repo with no commits yet also opens: it gets an empty\n# first commit on the requested branch, which Orca needs to create the workspace's worktree.\n# The clone is blobless (--filter=blob:none): history and trees, file contents only for the\n# checkout. A full clone of a large repo (stablyai/orca, ~2.7 GB) outran the 120 s start timeout.\n# With ORCA_CLONE_BACKGROUND=1 the clone runs detached after this script returns, so orcad starts\n# at once; it reports through $CLONE_DIR (state: running | done | failed , plus git's\n# --progress output) and the control plane's GET /v1/sandboxes/:id/clone reads it.\nset -uo pipefail\nP=/vercel/sandbox/project\nROOT=/vercel/sandbox/repos\nCLONE_DIR=\"$HOME/.orca-sandbox/clone\"\n# A stuck clone fails with a reason instead of hanging forever.\nCLONE_TIMEOUT_S=\"${ORCA_CLONE_TIMEOUT_S:-900}\"\nexport GIT_TERMINAL_PROMPT=0\nauth=()\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n auth=(-c \"http.https://github.com/.extraheader=$ORCA_GIT_EXTRAHEADER\")\nfi\nref=\"${ORCA_REPO_REF:-}\"\n\nfirst_commit() {\n if ! git -C \"$P\" rev-parse --verify --quiet HEAD >/dev/null; then\n git -C \"$P\" checkout --quiet -B \"${ref:-main}\" 2>/dev/null || true\n git -C \"$P\" -c user.name='Orca' -c user.email='cloud@onorca.dev' \\\n commit --quiet --allow-empty -m 'Initial commit' && echo 'Empty repository: created a first commit.'\n fi\n}\n\n# Clones into $P (which may already exist, empty). Progress goes to stderr.\nclone_repo() {\n local opts=(--filter=blob:none --progress) status\n timeout \"$CLONE_TIMEOUT_S\" git ${auth[@]+\"${auth[@]}\"} clone \"${opts[@]}\" ${ref:+--branch \"$ref\"} -- \"$ORCA_REPO_URL\" \"$P\"\n status=$?\n if [ \"$status\" -ne 0 ]; then\n [ \"$status\" -eq 124 ] && return 124\n # Empty it in place: the start script must keep seeing the directory, or it would clone itself.\n find \"$P\" -mindepth 1 -delete 2>/dev/null || true\n # Branch missing (or a repo with no commits): clone the default branch, then switch.\n timeout \"$CLONE_TIMEOUT_S\" git ${auth[@]+\"${auth[@]}\"} clone \"${opts[@]}\" -- \"$ORCA_REPO_URL\" \"$P\" || return \"$?\"\n if [ -n \"$ref\" ] && ! git -C \"$P\" checkout --quiet \"$ref\" -- 2>/dev/null; then\n git -C \"$P\" checkout --quiet -b \"$ref\" -- || true\n fi\n fi\n first_commit\n}\n\n# The reason the control plane shows: never the raw log (it may echo URLs).\nclone_failure_reason() {\n local status=\"$1\" log=\"$2\"\n if [ \"$status\" -eq 124 ]; then\n echo 'clone_timeout'\n elif grep -qiE 'could not read Username|authentication failed|repository not found|403|denied' \"$log\" 2>/dev/null; then\n echo 'repo_unreachable'\n elif grep -qiE 'no space left' \"$log\" 2>/dev/null; then\n echo 'disk_full'\n else\n echo 'clone_failed'\n fi\n}\n\nif [ ! -e \"$P\" ] && [ -n \"${ORCA_ENV_REPO_DIR:-}\" ] && [ -d \"$ROOT/$ORCA_ENV_REPO_DIR/.git\" ]; then\n ln -s \"$ROOT/$ORCA_ENV_REPO_DIR\" \"$P\"\n if [ -n \"$ref\" ] && [ \"$(git -C \"$P\" symbolic-ref --quiet --short HEAD 2>/dev/null)\" != \"$ref\" ]; then\n if timeout 60 git \"${auth[@]}\" -C \"$P\" fetch --quiet origin \"+refs/heads/$ref:refs/remotes/origin/$ref\"; then\n # -f: the install may have rewritten tracked files (a lockfile); the branch's version wins.\n git -C \"$P\" checkout --quiet -f -B \"$ref\" \"origin/$ref\" -- ||\n echo \"Could not switch to $ref; the workspace starts at the build's commit.\"\n else\n echo \"Could not fetch $ref; the workspace starts at the build's commit.\"\n fi\n fi\n first_commit\nelif [ ! -e \"$P\" ] && [ -n \"${ORCA_REPO_URL:-}\" ]; then\n mkdir -p \"$P\" \"$CLONE_DIR\"\n if [ \"${ORCA_CLONE_BACKGROUND:-}\" = 1 ]; then\n echo running >\"$CLONE_DIR/state\"\n : >\"$CLONE_DIR/progress.log\"\n # Detached (own session, no inherited stdio): the start command returns while this runs.\n export -f clone_repo first_commit clone_failure_reason\n export P CLONE_DIR CLONE_TIMEOUT_S ORCA_REPO_URL ref\n export ORCA_PRELUDE_AUTH=\"${ORCA_GIT_EXTRAHEADER:-}\"\n setsid bash -c '\n auth=()\n [ -n \"$ORCA_PRELUDE_AUTH\" ] && auth=(-c \"http.https://github.com/.extraheader=$ORCA_PRELUDE_AUTH\")\n unset ORCA_PRELUDE_AUTH\n clone_repo >>\"$CLONE_DIR/progress.log\" 2>&1\n status=$?\n if [ \"$status\" -eq 0 ]; then\n echo done >\"$CLONE_DIR/state.next\"\n else\n echo \"failed $(clone_failure_reason \"$status\" \"$CLONE_DIR/progress.log\")\" >\"$CLONE_DIR/state.next\"\n fi\n mv -f \"$CLONE_DIR/state.next\" \"$CLONE_DIR/state\"\n ' /dev/null 2>&1 &\n else\n clone_repo 2>\"$CLONE_DIR/progress.log\" || exit 1\n fi\nfi\nexit 0\n" +export const WORKSPACE_PRELUDE_SCRIPT: string = "#!/usr/bin/env bash\n# Runs right before orca-sandbox-start on a workspace's first boot. Prints only to stderr: the start\n# script's last stdout line is the orcad recipe line the control plane parses.\n#\n# - Booted from an environment build (ORCA_ENV_REPO_DIR set): the repo is already cloned with its\n# dependencies installed under /vercel/sandbox/repos. Link it as the project (a link, not a move,\n# so absolute paths baked into installed dependencies keep working). No fetch when the build is\n# already on the requested branch: Orca fetches the base right before it adds the workspace's\n# worktree, so a fetch here would only delay orcad (measured ~0.5-1 s). Another branch is fetched\n# and checked out; if that fails the workspace still opens at the build's commit.\n# - Otherwise clone ORCA_REPO_URL here so a repo with no commits yet also opens: it gets an empty\n# first commit on the requested branch, which Orca needs to create the workspace's worktree.\n# The clone is blobless (--filter=blob:none): history and trees, file contents only for the\n# checkout. A full clone of a large repo (stablyai/orca, ~2.7 GB) outran the 120 s start timeout.\n# With ORCA_CLONE_BACKGROUND=1 the clone runs detached after this script returns, so orcad starts\n# at once; it reports through $CLONE_DIR (state: running | done | failed , plus git's\n# --progress output) and the control plane's GET /v1/sandboxes/:id/clone reads it.\nset -uo pipefail\nP=/vercel/sandbox/project\nROOT=/vercel/sandbox/repos\nCLONE_DIR=\"$HOME/.orca-sandbox/clone\"\n# A stuck clone fails with a reason instead of hanging forever.\nCLONE_TIMEOUT_S=\"${ORCA_CLONE_TIMEOUT_S:-900}\"\nexport GIT_TERMINAL_PROMPT=0\nauth=()\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n auth=(-c \"http.https://github.com/.extraheader=$ORCA_GIT_EXTRAHEADER\")\nfi\nref=\"${ORCA_REPO_REF:-}\"\n\nfirst_commit() {\n if ! git -C \"$P\" rev-parse --verify --quiet HEAD >/dev/null; then\n git -C \"$P\" checkout --quiet -B \"${ref:-main}\" 2>/dev/null || true\n git -C \"$P\" -c user.name='Orca' -c user.email='cloud@onorca.dev' \\\n commit --quiet --allow-empty -m 'Initial commit' && echo 'Empty repository: created a first commit.'\n fi\n}\n\n# Clones into $P (which may already exist, empty). Progress goes to stderr.\nclone_repo() {\n local opts=(--filter=blob:none --progress) status\n timeout \"$CLONE_TIMEOUT_S\" git ${auth[@]+\"${auth[@]}\"} clone \"${opts[@]}\" ${ref:+--branch \"$ref\"} -- \"$ORCA_REPO_URL\" \"$P\"\n status=$?\n if [ \"$status\" -ne 0 ]; then\n [ \"$status\" -eq 124 ] && return 124\n # Empty it in place: the start script must keep seeing the directory, or it would clone itself.\n find \"$P\" -mindepth 1 -delete 2>/dev/null || true\n # Branch missing (or a repo with no commits): clone the default branch, then switch.\n timeout \"$CLONE_TIMEOUT_S\" git ${auth[@]+\"${auth[@]}\"} clone \"${opts[@]}\" -- \"$ORCA_REPO_URL\" \"$P\" || return \"$?\"\n if [ -n \"$ref\" ] && ! git -C \"$P\" checkout --quiet \"$ref\" -- 2>/dev/null; then\n git -C \"$P\" checkout --quiet -b \"$ref\" -- || true\n fi\n fi\n first_commit\n}\n\n# The reason the control plane shows: never the raw log (it may echo URLs).\nclone_failure_reason() {\n local status=\"$1\" log=\"$2\"\n if [ \"$status\" -eq 124 ]; then\n echo 'clone_timeout'\n elif grep -qiE 'could not read Username|authentication failed|repository not found|403|denied' \"$log\" 2>/dev/null; then\n echo 'repo_unreachable'\n elif grep -qiE 'no space left' \"$log\" 2>/dev/null; then\n echo 'disk_full'\n else\n echo 'clone_failed'\n fi\n}\n\n\n# Brings a prebuilt checkout (environment build) up to date: fetches only what changed on the target\n# branch (ORCA_REPO_REF, else the build's branch) and checks it out. A branch the remote doesn't have\n# yet (a new workspace branch) starts from the build's branch, freshly fetched. Progress goes to stderr.\nupdate_repo() {\n local base target status\n base=\"$(git -C \"$P\" symbolic-ref --quiet --short HEAD 2>/dev/null || true)\"\n target=\"${ref:-$base}\"\n [ -n \"$target\" ] || return 0\n timeout \"$CLONE_TIMEOUT_S\" git ${auth[@]+\"${auth[@]}\"} -C \"$P\" fetch --progress origin \"+refs/heads/$target:refs/remotes/origin/$target\"\n status=$?\n if [ \"$status\" -eq 0 ]; then\n # -f: the install may have rewritten tracked files (a lockfile); the branch's version wins.\n git -C \"$P\" checkout --quiet -f -B \"$target\" \"origin/$target\" --\n return $?\n fi\n [ \"$status\" -eq 124 ] && return 124\n { [ -n \"$base\" ] && [ \"$base\" != \"$target\" ]; } || return \"$status\"\n timeout \"$CLONE_TIMEOUT_S\" git ${auth[@]+\"${auth[@]}\"} -C \"$P\" fetch --progress origin \"+refs/heads/$base:refs/remotes/origin/$base\" || return $?\n git -C \"$P\" checkout --quiet -f -B \"$target\" \"origin/$base\" --\n}\n\n# Runs clone_repo or update_repo detached (own session, no inherited stdio), so the start command\n# returns while it runs; $CLONE_DIR/state reads running, then done or \"failed \".\nrun_detached() {\n echo running >\"$CLONE_DIR/state\"\n : >\"$CLONE_DIR/progress.log\"\n export -f clone_repo update_repo first_commit clone_failure_reason\n export P CLONE_DIR CLONE_TIMEOUT_S ORCA_REPO_URL ref\n export ORCA_PRELUDE_AUTH=\"${ORCA_GIT_EXTRAHEADER:-}\" ORCA_PRELUDE_STEP=\"$1\"\n setsid bash -c '\n auth=()\n [ -n \"$ORCA_PRELUDE_AUTH\" ] && auth=(-c \"http.https://github.com/.extraheader=$ORCA_PRELUDE_AUTH\")\n unset ORCA_PRELUDE_AUTH\n \"$ORCA_PRELUDE_STEP\" >>\"$CLONE_DIR/progress.log\" 2>&1\n status=$?\n if [ \"$status\" -eq 0 ]; then\n echo done >\"$CLONE_DIR/state.next\"\n elif [ \"$ORCA_PRELUDE_STEP\" = update_repo ]; then\n # Not fatal: the build'\"'\"'s checkout is there, just older. The status says so; the create goes on.\n echo \"done stale\" >\"$CLONE_DIR/state.next\"\n else\n echo \"failed $(clone_failure_reason \"$status\" \"$CLONE_DIR/progress.log\")\" >\"$CLONE_DIR/state.next\"\n fi\n mv -f \"$CLONE_DIR/state.next\" \"$CLONE_DIR/state\"\n ' /dev/null 2>&1 &\n}\n\nif [ ! -e \"$P\" ] && [ -n \"${ORCA_ENV_REPO_DIR:-}\" ] && [ -d \"$ROOT/$ORCA_ENV_REPO_DIR/.git\" ]; then\n ln -s \"$ROOT/$ORCA_ENV_REPO_DIR\" \"$P\"\n if [ \"${ORCA_CLONE_BACKGROUND:-}\" = 1 ]; then\n # The desktop shows this as \"Update repository\" (GET /v1/sandboxes/:id/clone): fetch what changed\n # since the build, in the background. A failure leaves the build's commit, which still opens.\n mkdir -p \"$CLONE_DIR\"\n run_detached update_repo\n elif [ -n \"$ref\" ] && [ \"$(git -C \"$P\" symbolic-ref --quiet --short HEAD 2>/dev/null)\" != \"$ref\" ]; then\n if timeout 60 git \"${auth[@]}\" -C \"$P\" fetch --quiet origin \"+refs/heads/$ref:refs/remotes/origin/$ref\"; then\n # -f: the install may have rewritten tracked files (a lockfile); the branch's version wins.\n git -C \"$P\" checkout --quiet -f -B \"$ref\" \"origin/$ref\" -- ||\n echo \"Could not switch to $ref; the workspace starts at the build's commit.\"\n else\n echo \"Could not fetch $ref; the workspace starts at the build's commit.\"\n fi\n fi\n first_commit\nelif [ ! -e \"$P\" ] && [ -n \"${ORCA_REPO_URL:-}\" ]; then\n mkdir -p \"$P\" \"$CLONE_DIR\"\n if [ \"${ORCA_CLONE_BACKGROUND:-}\" = 1 ]; then\n run_detached clone_repo\n else\n clone_repo 2>\"$CLONE_DIR/progress.log\" || exit 1\n fi\nfi\nexit 0\n" diff --git a/cloud/apps/sandbox-control/migrations/0049_auto_environments.sql b/cloud/apps/sandbox-control/migrations/0049_auto_environments.sql new file mode 100644 index 00000000000..d07dcd0dfe1 --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0049_auto_environments.sql @@ -0,0 +1,8 @@ +-- Automatic environments (src/auto-environments.ts): the first create of a repo that no environment +-- lists makes a default environment for it (just the repo) and builds it in the background, so later +-- creates boot with the repo already checked out. 'org' rows are made or edited by an admin; 'auto' rows +-- were made by the system and are deleted after 14 days without a create (an admin's edit makes them 'org'). +ALTER TABLE environments ADD COLUMN kind TEXT NOT NULL DEFAULT 'org'; +-- Last create that booted from this environment (or asked for one for its repo). +ALTER TABLE environments ADD COLUMN last_used_at INTEGER; +CREATE INDEX environments_kind ON environments (kind, deleted_at); diff --git a/cloud/apps/sandbox-control/src/auto-environments.ts b/cloud/apps/sandbox-control/src/auto-environments.ts new file mode 100644 index 00000000000..76476b97ab5 --- /dev/null +++ b/cloud/apps/sandbox-control/src/auto-environments.ts @@ -0,0 +1,168 @@ +// Automatic environments: Conductor-style "the repo is already there". An environment build (golden + +// the repo checked out, snapshotted) is opt-in for admins; without one every create of a repo cloned it +// from scratch (stablyai/orca: ~55 s). So the first create of a repo that no environment of the account +// lists makes a default environment for it (just the repo, blobless, no install script) and builds it in +// the background. Later creates boot from its active build (environments.ts resolveEnvironmentBoot) and +// only fetch what changed. Scoped per account like every environment; the usual golden refresh keeps +// it on the current image. Unused for 14 days it is deleted with its snapshots, unless an admin edited +// it (that makes it an ordinary 'org' environment). +import type { SandboxCaller } from './auth' +import { listBuilds, startBuild, TERMINAL, type BuildConfig, type BuildDeps } from './environment-builds' +import { canonicalRepoUrl, parseRepos, repoDir, type EnvironmentRow } from './environments' +import { normalizeRepo } from './secrets' + +export const AUTO_ENVIRONMENT_USER = 'system:auto-environment' +export const AUTO_ENVIRONMENT_UNUSED_MS = 14 * 24 * 60 * 60_000 +/** A failed automatic build is retried by a later create, at most this often. */ +export const AUTO_RETRY_AFTER_MS = 60 * 60_000 +/** Same cap as admin-made environments. */ +const MAX_ENVIRONMENTS = 20 + +const log = (event: string, fields: Record) => console.log(JSON.stringify({ event, ...fields })) + +function randomId(): string { + const bytes = crypto.getRandomValues(new Uint8Array(10)) + return `env_${Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')}` +} + +function systemCaller(accountId: string): SandboxCaller { + // An org-less caller is its own admin (canAdminEnvironments); the build is billed to the account. + return { userId: AUTO_ENVIRONMENT_USER, accountId } +} + +function autoConfig(environment: EnvironmentRow): BuildConfig { + return { + revision: environment.revision, + repos: parseRepos(environment), + installScript: environment.install_script, + envVarNames: [], + machineSize: environment.machine_size, + // History and trees only: a smaller snapshot and a faster build; file contents load on demand. + cloneFilter: 'blob:none' + } +} + +export type AutoEnvironmentOutcome = 'created' | 'rebuilt' | 'exists' | 'skipped' + +/** + * A create of `repoUrl` booted without an environment: make (or retry building) the account's automatic + * environment for it. Never throws; the create it rides behind already succeeded. + */ +export async function ensureAutoEnvironment(deps: BuildDeps, accountId: string, repoUrl: string): Promise { + try { + return await ensure(deps, accountId, repoUrl) + } catch (error) { + log('auto_environment_failed', { error: String(error).slice(0, 200) }) + return 'skipped' + } +} + +async function ensure(deps: BuildDeps, accountId: string, repoUrl: string): Promise { + const url = canonicalRepoUrl(repoUrl) + const wanted = normalizeRepo(url) + if (!url || !wanted) { + return 'skipped' + } + const { results: environments } = await deps.db + .prepare('SELECT * FROM environments WHERE account_id = ? AND deleted_at IS NULL') + .bind(accountId) + .all() + const listing = environments.filter((row) => parseRepos(row).some((repo) => normalizeRepo(repo.url) === wanted)) + if (listing.some((row) => row.kind !== 'auto')) { + // An admin's environment lists the repo: theirs to build, never ours to shadow. + return 'exists' + } + const auto = listing[0] + if (auto) { + await touchEnvironment(deps.db, auto.id, deps.now()) + return (await retryFailedBuild(deps, auto)) ? 'rebuilt' : 'exists' + } + if (environments.length >= MAX_ENVIRONMENTS) { + return 'skipped' + } + const now = deps.now() + const id = randomId() + // UNIQUE(account_id, name): a concurrent first create of the same repo inserts nothing here. + await deps.db + .prepare( + `INSERT OR IGNORE INTO environments (id, account_id, name, repos, install_script, env_var_names, machine_size, + revision, next_build_number, created_by, updated_by, created_at, updated_at, kind, last_used_at) + VALUES (?, ?, ?, ?, '', '[]', 'standard', 1, 1, ?, ?, ?, ?, 'auto', ?)` + ) + .bind(id, accountId, repoDir(url), JSON.stringify([{ url, defaultBranch: null }]), AUTO_ENVIRONMENT_USER, + AUTO_ENVIRONMENT_USER, now, now, now) + .run() + const environment = await deps.db + .prepare('SELECT * FROM environments WHERE id = ? AND deleted_at IS NULL') + .bind(id) + .first() + if (!environment) { + return 'exists' + } + const build = await startBuild(deps, systemCaller(accountId), environment, { config: autoConfig(environment) }) + log('auto_environment_created', { environmentId: id, buildId: build.id }) + return 'created' +} + +/** No active build, none in flight, and the last one failed a while ago: try once more. */ +async function retryFailedBuild(deps: BuildDeps, environment: EnvironmentRow): Promise { + if (environment.active_build_id) { + return false + } + const [last] = await listBuilds(deps.db, environment.id, 1) + if (last && (!TERMINAL.has(last.status) || deps.now() - (last.finished_at ?? last.created_at) < AUTO_RETRY_AFTER_MS)) { + return false + } + await startBuild(deps, systemCaller(environment.account_id), environment, { config: autoConfig(environment) }) + return true +} + +/** A create booted from (or asked for) this environment. */ +export async function touchEnvironment(db: D1Database, environmentId: string, now: number): Promise { + await db.prepare('UPDATE environments SET last_used_at = ? WHERE id = ?').bind(now, environmentId).run() +} + +/** + * Deletes the environment and every snapshot it built (live workspaces run on their own disks). + * Shared by an admin's Delete and the automatic expiry. + */ +export async function deleteEnvironmentAndSnapshots( + deps: Pick, + environmentId: string +): Promise { + await deps.db + .prepare('UPDATE environments SET deleted_at = ?, active_build_id = NULL WHERE id = ?') + .bind(deps.now(), environmentId) + .run() + const { results } = await deps.db + .prepare(`SELECT id, snapshot_id FROM environment_builds WHERE environment_id = ? AND snapshot_id IS NOT NULL AND snapshot_deleted_at IS NULL`) + .bind(environmentId) + .all<{ id: string; snapshot_id: string }>() + for (const row of results) { + await deps.provider.deleteSnapshot(row.snapshot_id).catch(() => undefined) + await deps.db.prepare('UPDATE environment_builds SET snapshot_deleted_at = ? WHERE id = ?').bind(deps.now(), row.id).run() + } +} + +/** Cron: automatic environments no create used for 14 days go, with their snapshots. */ +export async function expireAutoEnvironments(deps: BuildDeps): Promise { + const cutoff = deps.now() - AUTO_ENVIRONMENT_UNUSED_MS + const { results } = await deps.db + .prepare( + `SELECT id FROM environments WHERE kind = 'auto' AND deleted_at IS NULL + AND COALESCE(last_used_at, created_at) < ? LIMIT 20` + ) + .bind(cutoff) + .all<{ id: string }>() + let expired = 0 + for (const { id } of results) { + const inFlight = (await listBuilds(deps.db, id, 5)).some((build) => !TERMINAL.has(build.status)) + if (inFlight) { + continue + } + await deleteEnvironmentAndSnapshots(deps, id) + log('auto_environment_expired', { environmentId: id }) + expired++ + } + return expired +} diff --git a/cloud/apps/sandbox-control/src/clone-status.ts b/cloud/apps/sandbox-control/src/clone-status.ts index 2e3411b24b5..b162cd27ae1 100644 --- a/cloud/apps/sandbox-control/src/clone-status.ts +++ b/cloud/apps/sandbox-control/src/clone-status.ts @@ -40,7 +40,8 @@ export function parseCloneStatus(stdout: string): CloneStatus { if (state === 'none' || state === '') { return { state: 'none' } } - if (state === 'done') { + if (state === 'done' || state.startsWith('done ')) { + // "done stale": an update after an environment boot failed; the build's checkout still opens. return { state: 'done' } } if (state.startsWith('failed')) { diff --git a/cloud/apps/sandbox-control/src/env.ts b/cloud/apps/sandbox-control/src/env.ts index 9223685fff2..daec7406e86 100644 --- a/cloud/apps/sandbox-control/src/env.ts +++ b/cloud/apps/sandbox-control/src/env.ts @@ -23,6 +23,8 @@ export type Env = { GOLDEN_SNAPSHOT_REGION?: string /** Non-prod only: pin this image over the rotated active one (preview versions testing new VM entry points). */ GOLDEN_SNAPSHOT_OVERRIDE?: string + /** 'off': no automatic environments (auto-environments.ts); creates without one keep cloning. */ + AUTO_ENVIRONMENTS?: string /** Git as the sender: `on`, `accounts:,` or off (default). See memberGitEnabled in index.ts. */ MEMBER_GIT_IDENTITY?: string /** How long after a member's own send their GitHub identity stays usable (default 30). */ diff --git a/cloud/apps/sandbox-control/src/environment-builds.ts b/cloud/apps/sandbox-control/src/environment-builds.ts index f0d02aaadcf..972bbd360f2 100644 --- a/cloud/apps/sandbox-control/src/environment-builds.ts +++ b/cloud/apps/sandbox-control/src/environment-builds.ts @@ -91,6 +91,8 @@ export type BuildConfig = { installScript: string envVarNames: string[] machineSize: MachineSize + /** `git clone --filter`: automatic environments clone blobless (auto-environments.ts). */ + cloneFilter?: 'blob:none' } export type BuildResult = { @@ -338,7 +340,8 @@ async function bootBuild(deps: BuildDeps, row: BuildRow, config: BuildConfig): P ORCA_BUILD_REPOS: lines.join('\n'), ORCA_INSTALL_SCRIPT_B64: base64(config.installScript), ORCA_LOCKFILES: LOCKFILES.join(' '), - ORCA_DEPS_HOOK_B64: base64(ENVIRONMENT_DEPS_HOOK) + ORCA_DEPS_HOOK_B64: base64(ENVIRONMENT_DEPS_HOOK), + ...(config.cloneFilter ? { ORCA_CLONE_FILTER: config.cloneFilter } : {}) } log('environment_build_secrets', { buildId: row.id, injected: Object.keys(secrets).length, named: config.envVarNames.length }) const commandId = await deps.provider.startCommand(box.session.id, { diff --git a/cloud/apps/sandbox-control/src/environment-routes.ts b/cloud/apps/sandbox-control/src/environment-routes.ts index c8120dbe085..a1edaae0abc 100644 --- a/cloud/apps/sandbox-control/src/environment-routes.ts +++ b/cloud/apps/sandbox-control/src/environment-routes.ts @@ -9,6 +9,7 @@ // GET /v1/environments/:id/builds/:bid/events -> ndjson stream (environment-builds.ts) // POST /v1/environments/:id/builds/:bid/cancel | /activate -> {build} | {environment} // GET /v1/environments/:id/staleness -> {staleness} +import { deleteEnvironmentAndSnapshots } from './auto-environments' import type { SandboxCaller } from './auth' import { activateBuild, @@ -163,16 +164,8 @@ export async function handleEnvironmentRoute( await cancelBuild(deps, caller, row).catch(() => undefined) } } - await db.prepare('UPDATE environments SET deleted_at = ?, active_build_id = NULL WHERE id = ?').bind(deps.now(), envId).run() // No kept window once deleted: every build snapshot goes (live workspaces run on their own disks). - const { results } = await db - .prepare(`SELECT * FROM environment_builds WHERE environment_id = ? AND snapshot_id IS NOT NULL AND snapshot_deleted_at IS NULL`) - .bind(envId) - .all() - for (const row of results) { - await deps.provider.deleteSnapshot(row.snapshot_id!).catch(() => undefined) - await db.prepare('UPDATE environment_builds SET snapshot_deleted_at = ? WHERE id = ?').bind(deps.now(), row.id).run() - } + await deleteEnvironmentAndSnapshots(deps, envId) return json({ deleted: true }) } return json({ error: 'not_found' }, 404) diff --git a/cloud/apps/sandbox-control/src/environments.ts b/cloud/apps/sandbox-control/src/environments.ts index 39674e57c5a..25a37008848 100644 --- a/cloud/apps/sandbox-control/src/environments.ts +++ b/cloud/apps/sandbox-control/src/environments.ts @@ -31,6 +31,12 @@ export type EnvironmentRow = { created_at: number updated_at: number deleted_at: number | null + /** + * 'org': made (or since edited) by an admin. 'auto': made by the first create of a repo no + * environment listed (auto-environments.ts); deleted after 14 days unused unless an admin edits it. + */ + kind?: 'org' | 'auto' + last_used_at?: number | null } export class EnvironmentError extends Error { @@ -223,10 +229,11 @@ export async function updateEnvironment( next.install_script !== row.install_script || next.env_var_names !== row.env_var_names || next.machine_size !== row.machine_size + // An admin's edit adopts an automatic environment: it stops expiring. const result = await db .prepare( `UPDATE environments SET name = ?, repos = ?, install_script = ?, env_var_names = ?, machine_size = ?, - revision = revision + ?, updated_by = ?, updated_at = ? WHERE id = ? AND revision = ?` + revision = revision + ?, updated_by = ?, updated_at = ?, kind = 'org' WHERE id = ? AND revision = ?` ) .bind(next.name, next.repos, next.install_script, next.env_var_names, next.machine_size, buildInputsChanged ? 1 : 0, caller.userId, now, row.id, row.revision) @@ -246,6 +253,8 @@ export type BootSource = { machineSize: MachineSize /** The build's snapshot only boots here, so the workspace is created here too. */ region: string + /** An automatic environment (auto-environments.ts): the caller's machine size stands. */ + auto?: boolean } type BootBuildRow = { @@ -288,7 +297,12 @@ function bootFrom(build: BootBuildRow, repoUrl: string | null | undefined): Boot export async function resolveEnvironmentBoot( db: D1Database, accountId: string, - request: { repoUrl?: string | null; buildId?: string | null } + request: { + repoUrl?: string | null + buildId?: string | null + /** An automatic environment only boots in its build's region: an explicit other region skips it. */ + region?: string | null + } ): Promise { if (request.buildId) { const build = await db @@ -308,20 +322,25 @@ export async function resolveEnvironmentBoot( if (!wanted) { return null } + // An admin's environment that lists the repo wins over an automatic one. const { results } = await db .prepare( - `SELECT e.repos AS repos, b.* FROM environments e JOIN environment_builds b ON b.id = e.active_build_id - WHERE e.account_id = ? AND e.deleted_at IS NULL ORDER BY e.updated_at DESC` + `SELECT e.repos AS repos, e.kind AS kind, b.* FROM environments e JOIN environment_builds b ON b.id = e.active_build_id + WHERE e.account_id = ? AND e.deleted_at IS NULL ORDER BY (e.kind = 'org') DESC, e.updated_at DESC` ) .bind(accountId) - .all() + .all() for (const row of results) { if (!parseRepos(row).some((repo) => normalizeRepo(repo.url) === wanted)) { continue } + // An automatic environment is only a speed-up: an explicit other region skips it. + if (row.kind === 'auto' && request.region && request.region !== row.region) { + continue + } const source = bootFrom(row, request.repoUrl) if (source?.repoDir) { - return source + return row.kind === 'auto' ? { ...source, auto: true } : source } } return null diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 255b4d8b6ec..8d833367e3e 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -141,6 +141,7 @@ import { credentialTargets, type CredentialTarget } from './provider-env' import type { Keyring } from './secrets-crypto' import { ProviderError, type SandboxProviderApi } from './sandbox-provider' import { readCloneStatus } from './clone-status' +import { ensureAutoEnvironment, expireAutoEnvironments, touchEnvironment } from './auto-environments' import { DesktopCommandError, VmCommandError, startDesktop } from './sandbox-vm-commands' import { forgetShareLink, handleShareGateway } from './share-gateway' import { handleShareRoute, revokeSandboxShares, sharePathMode, shareSecret, shareSecrets } from './share-links' @@ -742,8 +743,8 @@ function devCredentials(env: Env): CredentialBroker { } /** Ready answers carry phase timings as Server-Timing so clients and dashboards can see the slow step. */ -function readyResponse(ready: Ready): Response { - const response = json(readyView(ready.row, ready.connection, ready.cloning)) +function readyResponse(ready: Ready, updateAware = false): Response { + const response = json(readyView(ready.row, ready.connection, ready.cloning, updateAware)) const timing = Object.entries(ready.timings ?? {}) .map(([phase, ms]) => `${phase};dur=${ms}`) .join(', ') @@ -802,7 +803,7 @@ export async function lifecycleDeps(env: Env, deps: Deps): Promise ensureAutoEnvironment(buildDeps(life, deps, env), accountId, repoUrl), + touch: (environmentId) => touchEnvironment(env.SANDBOX_DB, environmentId, life.now()) + } + } + return life } /** @@ -1521,7 +1530,7 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) // Desktops that show the clone as its own step ask for it in the background (GET .../clone). const ready = await createSandbox(life, caller, { ...body.data, cloneInBackground: features.includes('clone-progress') }) await recordOwnerDeviceAndSync(life, ready.row, ready.connection.pairingCode) - return readyResponse(ready) + return readyResponse(ready, features.includes('repo-update')) } const row = await getSandbox(env.SANDBOX_DB, id) const route = `${request.method} ${action ?? ''}` @@ -2138,6 +2147,11 @@ export default { if (refresh.stale > 0) { console.log(JSON.stringify({ event: 'environment_golden_refresh', ...refresh })) } + // Automatic environments unused for 14 days go with their snapshots (storage). + const expired = await expireAutoEnvironments(buildDeps(fresh, {}, env)).catch(() => 0) + if (expired > 0) { + console.log(JSON.stringify({ event: 'auto_environments_expired', expired })) + } } }) ) diff --git a/cloud/apps/sandbox-control/src/lifecycle.ts b/cloud/apps/sandbox-control/src/lifecycle.ts index 9d3d7e4cf46..c2e9ed5032c 100644 --- a/cloud/apps/sandbox-control/src/lifecycle.ts +++ b/cloud/apps/sandbox-control/src/lifecycle.ts @@ -96,6 +96,14 @@ export type LifecycleDeps = { * error after boot. Absent: no check. */ publicRepoCheck?: (repoUrl: string) => Promise + /** + * Automatic environments (auto-environments.ts): `ensure` after a create of a repo no environment + * lists, `touch` when a create booted from an automatic one. Absent: neither happens. + */ + autoEnvironment?: { + ensure(accountId: string, repoUrl: string): Promise + touch(environmentId: string): Promise + } /** Work that may finish after the response (Worker ctx.waitUntil); absent means fire-and-forget. */ background?: (work: Promise) => void /** Best-effort side effects of a session starting or ending (workspace tokens, see api/settings.ts). */ @@ -156,8 +164,11 @@ export type Ready = { row: SandboxRow connection: OrcadReady timings?: Record - /** The repo is still cloning in the VM (create with cloneInBackground); GET /clone reports it. */ - cloning?: boolean + /** + * The repo is still being cloned ('clone') or, after an environment boot, brought up to date + * ('update') in the VM (create with cloneInBackground); GET /clone reports it. + */ + cloning?: 'clone' | 'update' } /** Phase durations for one lifecycle call (logged + Server-Timing); counts only, no ids or secrets. */ @@ -515,11 +526,13 @@ export async function createSandbox( ? await timer.time('environment', () => resolveEnvironmentBoot(deps.db, caller.accountId, { repoUrl: request.repo?.url, - buildId: request.environmentBuildId + buildId: request.environmentBuildId, + region: request.region }) ) : null - const machineSize = source?.machineSize ?? request.machineSize + // An automatic environment is only the repo checked out: the caller's machine size stands. + const machineSize = source && !source.auto ? source.machineSize : request.machineSize await timer.time('entitlement', () => requireStart(deps, caller.accountId, caller.userId, machineSize)) // A snapshot only boots in its own region: an environment build pins the region it was built in. const region = source?.region ?? request.region ?? deps.config.defaultRegion @@ -541,12 +554,16 @@ export async function createSandbox( deps.background?.(refill) } const claimedAt = deps.now() - // An environment build carries the repo prebuilt: nothing clones, so nothing runs in the background. - const cloneInBackground = Boolean(request.repo && request.cloneInBackground && !source?.repoDir) + // In the background after ready: a clone, or (an environment build carries the repo prebuilt) a fetch + // of what changed since the build. + const cloning: Ready['cloning'] = request.repo && request.cloneInBackground ? (source?.repoDir ? 'update' : 'clone') : undefined const prelude: StartInputs['prelude'] = request.repo ? { script: WORKSPACE_PRELUDE_SCRIPT, - env: source?.repoDir ? { ORCA_ENV_REPO_DIR: source.repoDir } : cloneInBackground ? { ORCA_CLONE_BACKGROUND: '1' } : {} + env: { + ...(source?.repoDir ? { ORCA_ENV_REPO_DIR: source.repoDir } : {}), + ...(cloning ? { ORCA_CLONE_BACKGROUND: '1' } : {}) + } } : undefined const id = pooled?.id ?? randomId() @@ -590,6 +607,18 @@ export async function createSandbox( throw error } }) + // The repo is reachable: the next create of it should find it prebuilt (auto-environments.ts). + if (request.repo && deps.autoEnvironment && !request.environmentBuildId && request.useEnvironment !== false) { + const work = source?.auto + ? deps.autoEnvironment.touch(source.environmentId) + : !source + ? deps.autoEnvironment.ensure(caller.accountId, request.repo.url) + : null + if (work) { + const settled = work.catch(() => undefined) + deps.background?.(settled) + } + } if (pooled) { try { const state = await timer.time('vm', () => @@ -597,7 +626,7 @@ export async function createSandbox( ) const ready = await boot(deps, row, state, prep, { repo: request.repo, policyApplied: true, timer, billFrom: claimedAt, prelude }) console.log(JSON.stringify({ event: 'lifecycle_timing', op: 'create', pooled: true, ms: timer.timings })) - return cloneInBackground ? { ...ready, cloning: true } : ready + return cloning ? { ...ready, cloning } : ready } catch (error) { // A pooled VM that will not take the session is discarded; the caller still gets a workspace. console.log(JSON.stringify({ event: 'pool_adopt_failed', error: String(error).slice(0, 200) })) @@ -647,7 +676,7 @@ export async function createSandbox( try { const ready = await boot(deps, row, state, prep, { repo: request.repo, policyApplied: true, timer, prelude }) console.log(JSON.stringify({ event: 'lifecycle_timing', op: 'create', fromBuild: source?.buildId ?? null, ms: timer.timings })) - return cloneInBackground ? { ...ready, cloning: true } : ready + return cloning ? { ...ready, cloning } : ready } catch (error) { await failAndRelease(deps, (await getSandbox(deps.db, row.id)) ?? row, createFailureReason(error)) throw error diff --git a/cloud/apps/sandbox-control/src/wire.ts b/cloud/apps/sandbox-control/src/wire.ts index efc6303704a..5d91dffaea7 100644 --- a/cloud/apps/sandbox-control/src/wire.ts +++ b/cloud/apps/sandbox-control/src/wire.ts @@ -75,7 +75,13 @@ export function sandboxView(row: SandboxRow, archivedAware = false) { } } -export function readyView(row: SandboxRow, connection: OrcadReady, cloning = false) { +export function readyView( + row: SandboxRow, + connection: OrcadReady, + cloning?: 'clone' | 'update', + /** The client knows `mode` (feature `repo-update`); older ones show an update as a clone. */ + updateAware = false +) { return { sandbox: sandboxView(row), connection: { @@ -84,7 +90,9 @@ export function readyView(row: SandboxRow, connection: OrcadReady, cloning = fal projectRoot: connection.projectRoot }, // Only for a create that asked (feature `clone-progress`): the repo is still cloning. - ...(cloning ? { clone: { state: 'running' as const } } : {}) + ...(cloning + ? { clone: { state: 'running' as const, ...(cloning === 'update' && updateAware ? { mode: 'update' as const } : {}) } } + : {}) } } diff --git a/cloud/apps/sandbox-control/test/auto-environments.test.ts b/cloud/apps/sandbox-control/test/auto-environments.test.ts new file mode 100644 index 00000000000..7e81974cbd6 --- /dev/null +++ b/cloud/apps/sandbox-control/test/auto-environments.test.ts @@ -0,0 +1,126 @@ +// Automatic environments: the first create of a repo builds it in the background; later creates boot +// with the repo checked out and only fetch what changed. +import { describe, expect, it } from 'vitest' +import { HostedSandboxReadyResponseSchema } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire' +import { AUTO_ENVIRONMENT_UNUSED_MS, expireAutoEnvironments } from '../src/auto-environments' +import { START_COMMAND } from '../src/sandbox-vm-commands' +import { GOLDEN, createHarness } from './harness' + +const REPO = 'https://github.com/acme/web.git' +const RESULT = JSON.stringify({ + durationSec: 3, + repos: [{ url: REPO, dir: 'acme/web', branch: 'main', commit: 'a'.repeat(40), lockfiles: {} }], + diskUsedBytes: 3_000_000_000, + diskTotalBytes: 34_000_000_000 +}) +const FEATURES = { 'x-orca-sandbox-features': 'clone-progress,repo-update' } + +async function setup() { + const pending: Promise[] = [] + const h = await createHarness({ AUTO_ENVIRONMENTS: 'on' }, { waitUntil: (work: Promise) => void pending.push(work) }) + h.vercel.buildResult = RESULT + const settle = async () => { + while (pending.length > 0) { + await Promise.all(pending.splice(0)) + } + } + const environments = () => + h.raw.prepare('SELECT id, account_id, kind, name, active_build_id, deleted_at, last_used_at FROM environments').all() as { + id: string + account_id: string + kind: string + name: string + active_build_id: string | null + deleted_at: number | null + last_used_at: number | null + }[] + /** Lets the auto build's VM command succeed and finalizes it. */ + async function finishBuild(as = 'alice') { + const env = environments().find((row) => row.deleted_at === null && !row.active_build_id)! + const build = h.raw.prepare('SELECT id FROM environment_builds WHERE environment_id = ? ORDER BY number DESC').get(env.id) as { id: string } + const command = [...h.vercel.buildCommands.values()].at(-1)! + command.logs = `${JSON.stringify({ data: '::orca-step:: clone\n', stream: 'stdout' })}\n` + command.exitCode = 0 + h.advance(1000) + const done = await h.call('GET', `/v1/environments/${env.id}/builds/${build.id}`, { as }) + expect(done.body.build.status).toBe('succeeded') + return { env, buildId: build.id } + } + return { h, settle, environments, finishBuild } +} + +describe('automatic environments', () => { + it('the first create of a repo builds it (blobless); the next boots with it checked out and fetches only changes', async () => { + const { h, settle, environments, finishBuild } = await setup() + const first = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w1', machineSize: 'standard', repo: { url: REPO } }, headers: FEATURES }) + expect(first.body.clone).toEqual({ state: 'running' }) + await settle() + expect(environments()).toMatchObject([{ kind: 'auto', name: 'acme/web', active_build_id: null }]) + const command = [...h.vercel.buildCommands.values()].at(-1)! + expect(command.env.ORCA_CLONE_FILTER).toBe('blob:none') + const { buildId } = await finishBuild() + + h.vercel.commands.length = 0 + const second = await h.call('POST', '/v1/sandboxes', { + body: { workspaceId: 'w2', machineSize: 'standard', repo: { url: REPO, ref: 'feature' } }, + headers: FEATURES + }) + expect(second.status).toBe(200) + expect(second.body.sandbox.environmentBuildId).toBe(buildId) + expect(second.body.clone).toEqual({ state: 'running', mode: 'update' }) + expect(HostedSandboxReadyResponseSchema.safeParse({ ...second.body, clone: { state: 'running' } }).success).toBe(true) + const start = h.vercel.commands.find((c) => c.command === START_COMMAND)! + expect(start.env).toMatchObject({ ORCA_ENV_REPO_DIR: 'acme/web', ORCA_CLONE_BACKGROUND: '1' }) + const box = [...h.vercel.boxes.values()].find((b) => b.params.tags.orcaSandbox === second.body.sandbox.id)! + expect(box.params.snapshotId).not.toBe(GOLDEN) + await settle() + expect(environments()[0]!.last_used_at).toBe(h.now()) + // A desktop without `repo-update` sees the plain clone shape it knows. + const older = await h.call('POST', '/v1/sandboxes', { + body: { workspaceId: 'w3', machineSize: 'standard', repo: { url: REPO } }, + headers: { 'x-orca-sandbox-features': 'clone-progress' } + }) + expect(older.body.clone).toEqual({ state: 'running' }) + }) + + it('is per account, never shadows an admin environment, and makes one environment per repo', async () => { + const { h, settle, environments } = await setup() + await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'a1', machineSize: 'standard', repo: { url: REPO } } }) + await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'a2', machineSize: 'standard', repo: { url: 'acme/web' } } }) + await settle() + const bob = await h.call('POST', '/v1/sandboxes', { as: 'bob', body: { workspaceId: 'b1', machineSize: 'standard', repo: { url: REPO } } }) + await settle() + expect(bob.body.sandbox.environmentBuildId).toBeUndefined() + const rows = environments() + expect(rows).toHaveLength(2) + expect(new Set(rows.map((row) => row.account_id)).size).toBe(2) + + // An org whose admin lists the repo: no automatic one next to it. + const admin = await h.token('carol', 'acme', 'sandbox', { orgRole: 'admin' }) + expect( + (await h.call('POST', '/v1/environments', { bearer: admin, body: { name: 'Web', repos: [{ url: 'acme/web' }], installScript: '' } })).status + ).toBe(200) + await h.call('POST', '/v1/sandboxes', { bearer: admin, body: { workspaceId: 'c1', machineSize: 'standard', repo: { url: REPO } } }) + await settle() + expect(environments().filter((row) => row.kind === 'auto')).toHaveLength(2) + }) + + it('goes after 14 days unused, with its snapshot', async () => { + const { h, settle, environments, finishBuild } = await setup() + await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w1', machineSize: 'standard', repo: { url: REPO } } }) + await settle() + const { buildId } = await finishBuild() + const snapshotId = (h.raw.prepare('SELECT snapshot_id FROM environment_builds WHERE id = ?').get(buildId) as { snapshot_id: string }).snapshot_id + h.advance(AUTO_ENVIRONMENT_UNUSED_MS + 60_000) + const deps = { + db: h.env.SANDBOX_DB, + provider: h.vercel, + entitlements: { checkStart: async () => h.billing.decision, reportUsage: async () => h.billing.usageAnswer, listSuspensions: async () => [] }, + now: h.now, + config: { environment: 'test', goldenSnapshotId: GOLDEN, region: 'iad1' } + } + expect(await expireAutoEnvironments(deps as never)).toBe(1) + expect(environments()[0]!.deleted_at).not.toBeNull() + expect(h.vercel.snapshots.get(snapshotId)?.status).not.toBe('created') + }) +}) diff --git a/cloud/apps/sandbox-control/test/harness.ts b/cloud/apps/sandbox-control/test/harness.ts index f741c315869..6687138c0e5 100644 --- a/cloud/apps/sandbox-control/test/harness.ts +++ b/cloud/apps/sandbox-control/test/harness.ts @@ -50,6 +50,8 @@ export async function createHarness(overrides: Partial = {}, extraDeps: Par GOLDEN_SNAPSHOT_ID: GOLDEN, VERCEL_TEAM_ID: 'team_orca', VERCEL_PROJECT_ID: 'prj_orca', + // Off unless a test turns it on (auto-environments.test.ts): it starts builds behind creates. + AUTO_ENVIRONMENTS: 'off', ...overrides } // No live github.com from tests: repos count as public unless a test says otherwise. diff --git a/src/main/environment-providers/environment-provider-driver.ts b/src/main/environment-providers/environment-provider-driver.ts index a722e77cee5..f731a2530b4 100644 --- a/src/main/environment-providers/environment-provider-driver.ts +++ b/src/main/environment-providers/environment-provider-driver.ts @@ -18,6 +18,8 @@ export type EnvironmentProviderPhase = | 'booting' /** The repo clones in the VM after it is up; `percent` is git's overall progress. */ | 'cloning' + /** The repo came prebuilt (an environment build): only what changed is fetched. */ + | 'updating' | 'connecting' | 'suspending' | 'resuming' diff --git a/src/main/hosted-sandbox/hosted-sandbox-control-plane-client.ts b/src/main/hosted-sandbox/hosted-sandbox-control-plane-client.ts index e5d8c232070..fb570800c43 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-control-plane-client.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-control-plane-client.ts @@ -139,7 +139,8 @@ export function createHostedSandboxControlPlaneClient( kind: 'boot', signal, // The repo clones after the sandbox is up; the driver shows it as its own step. - features: ['clone-progress'] + // An environment boot reports its incremental fetch as an update (`clone.mode`). + features: ['clone-progress', 'repo-update'] }), cloneStatus: async (id, signal) => ( diff --git a/src/main/hosted-sandbox/hosted-sandbox-driver.test.ts b/src/main/hosted-sandbox/hosted-sandbox-driver.test.ts index f4204d2d2b4..eba428ab237 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-driver.test.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-driver.test.ts @@ -205,6 +205,24 @@ describe('waitForClone', () => { expect(destroyed).toEqual([]) }) + it('an environment boot reports its fetch as an update', async () => { + const { client } = fakeClient([ + { state: 'running', percent: 30, stage: 'download' }, + { state: 'done' } + ]) + const progress: unknown[] = [] + await waitForClone( + client, + 'sbx_1', + { onProgress: (p) => progress.push(p) }, + { pollMs: 0, mode: 'update' } + ) + expect(progress).toEqual([ + { phase: 'updating' }, + { phase: 'updating', percent: 30, message: 'download' } + ]) + }) + it('a failed clone deletes the sandbox and fails with its reason', async () => { const { client, destroyed } = fakeClient([{ state: 'failed', reason: 'repo_unreachable' }]) const error = await rejection(waitForClone(client, 'sbx_1', {}, { pollMs: 0 })) diff --git a/src/main/hosted-sandbox/hosted-sandbox-driver.ts b/src/main/hosted-sandbox/hosted-sandbox-driver.ts index 08093cca61a..cfa0fc2c6b3 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-driver.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-driver.ts @@ -73,7 +73,7 @@ export function createHostedSandboxDriver( ctx?.signal ) if (ready.clone) { - await waitForClone(client, ready.sandbox.id, ctx) + await waitForClone(client, ready.sandbox.id, ctx, { mode: ready.clone.mode ?? 'clone' }) } ctx?.onProgress?.({ phase: 'connecting' }) return toReady(ready) @@ -175,9 +175,14 @@ export async function waitForClone( client: Pick, sandboxId: string, ctx?: EnvironmentProviderCallContext, - { now = Date.now, pollMs = CLONE_POLL_MS }: { now?: () => number; pollMs?: number } = {} + { + now = Date.now, + pollMs = CLONE_POLL_MS, + mode = 'clone' + }: { now?: () => number; pollMs?: number; mode?: 'clone' | 'update' } = {} ): Promise { - ctx?.onProgress?.({ phase: 'cloning' }) + const phase = mode === 'update' ? 'updating' : 'cloning' + ctx?.onProgress?.({ phase }) let lastProgress = '' let movedAt = now() try { @@ -203,7 +208,7 @@ export async function waitForClone( if (progress !== lastProgress) { lastProgress = progress movedAt = now() - ctx?.onProgress?.({ phase: 'cloning', percent: status.percent, message: status.stage }) + ctx?.onProgress?.({ phase, percent: status.percent, message: status.stage }) } } if (now() - movedAt > CLONE_STALL_MS) { diff --git a/src/main/hosted-sandbox/hosted-sandbox-recipe.ts b/src/main/hosted-sandbox/hosted-sandbox-recipe.ts index 4e416b7a71a..22e7317b088 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-recipe.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-recipe.ts @@ -170,7 +170,7 @@ export function createHostedSandboxStepProvider( message?: string }) => onStderr?.( - phase === 'cloning' && percent !== undefined + (phase === 'cloning' || phase === 'updating') && percent !== undefined ? `[orca-cloud] clone-progress ${percent} ${message === 'checkout' ? 'checkout' : 'download'}\n` : `[orca-cloud] ${phase}\n` ) diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx index 4cea68efd6d..7687377e8ac 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx @@ -248,7 +248,7 @@ export function VmBuildSheet({ cloud && step.id === 'provision' && step.state === 'running' ? latestOrcaCloudPhaseLabel(entry.provisioningLog ?? '', t) : step.id === 'clone' && step.state === 'running' - ? cloneStageLabel(step.stage, t) + ? cloneStageLabel(step.stage, t, step.cloneMode) : null } timing={timings[step.id] ?? null} diff --git a/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts b/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts index 91c7528e9d7..1813c60baa1 100644 --- a/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts +++ b/src/renderer/src/components/worktree-creation/orca-cloud-build-log.ts @@ -29,6 +29,11 @@ function phaseLabel(phase: string, t: Translate): string | null { 'auto.components.worktree.creation.orcaCloudBuildLog.cloning', 'Cloning the repository…' ) + case 'updating': + return t( + 'auto.components.worktree.creation.orcaCloudBuildLog.updating', + 'Updating the repository…' + ) case 'connecting': return t( 'auto.components.worktree.creation.orcaCloudBuildLog.connecting', diff --git a/src/renderer/src/components/worktree-creation/vm-build-sheet-copy.ts b/src/renderer/src/components/worktree-creation/vm-build-sheet-copy.ts index 3bf0f8fc750..dd34ad13bae 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-sheet-copy.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-sheet-copy.ts @@ -9,7 +9,9 @@ export function stepLabel(step: VmBuildStep, cloud: boolean, t: Translate): stri ? t('auto.components.worktree.creation.VmBuildSheet.provisionCloud', 'Start sandbox') : t('auto.components.worktree.creation.VmBuildSheet.provision', 'Provision VM') case 'clone': - return t('auto.components.worktree.creation.VmBuildSheet.cloneCloud', 'Clone repository') + return step.cloneMode === 'update' + ? t('auto.components.worktree.creation.VmBuildSheet.updateCloud', 'Update repository') + : t('auto.components.worktree.creation.VmBuildSheet.cloneCloud', 'Clone repository') case 'checks': return cloud ? t('auto.components.worktree.creation.VmBuildSheet.checksCloud', 'Prepare environment') @@ -87,8 +89,12 @@ export function headerTitle( /** What the running clone is doing, in plain words. */ export function cloneStageLabel( stage: 'counting' | 'download' | 'checkout' | undefined, - t: Translate + t: Translate, + mode: 'clone' | 'update' = 'clone' ): string { + if (mode === 'update' && stage !== 'checkout') { + return t('auto.components.worktree.creation.VmBuildSheet.updateFetching', 'Fetching changes…') + } if (stage === 'counting') { return t('auto.components.worktree.creation.VmBuildSheet.cloneCounting', 'Counting objects…') } diff --git a/src/renderer/src/components/worktree-creation/vm-build-steps.test.ts b/src/renderer/src/components/worktree-creation/vm-build-steps.test.ts index fa99cec518d..14bdf7d9bd9 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-steps.test.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-steps.test.ts @@ -7,6 +7,7 @@ import { deriveVmBuildSteps } from './vm-build-steps' import { classifyVmBuildFailure } from './vm-build-failure' import { holdRunningSteps } from './use-minimum-running-steps' import { humanizeOrcaCloudLogLine } from './orca-cloud-build-log' +import { cloneStageLabel, stepLabel } from './vm-build-sheet-copy' import type { Translate } from '@/i18n/use-translate' const base = { @@ -279,6 +280,27 @@ describe('Orca Cloud clone step', () => { ).toEqual({ kind: 'cloneFailed', reason: 'clone_timeout' }) }) + it('a prebuilt repo (environment build) shows as an update, not a clone', () => { + const t: Translate = (_key, fallback) => fallback + const steps = deriveVmBuildSteps( + { + ...base, + ...lines(['[orca-cloud] updating', 4000], ['[orca-cloud] clone-progress 40 download', 4500]) + }, + 5000, + { cloud: true } + ) + expect(steps[1]).toMatchObject({ + id: 'clone', + state: 'running', + percent: 40, + cloneMode: 'update' + }) + expect(stepLabel(steps[1]!, true, t)).toBe('Update repository') + expect(cloneStageLabel(steps[1]!.stage, t, steps[1]!.cloneMode)).toBe('Fetching changes…') + expect(humanizeOrcaCloudLogLine('[orca-cloud] updating', t)).toBe('Updating the repository…') + }) + it('shows counting (no frozen 0%) until git reports a percent', () => { const at = (...extra: [string, number][]) => deriveVmBuildSteps({ ...base, ...lines(['[orca-cloud] cloning', 6000], ...extra) }, 9000, { diff --git a/src/renderer/src/components/worktree-creation/vm-build-steps.ts b/src/renderer/src/components/worktree-creation/vm-build-steps.ts index dae5d53166c..1d2174290e3 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-steps.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-steps.ts @@ -26,6 +26,8 @@ export type VmBuildStep = { * percent yet (the row shows an indeterminate bar, never a frozen 0%). */ stage?: 'counting' | 'download' | 'checkout' + /** Clone only: 'update' when the repo came prebuilt and only changes are fetched. */ + cloneMode?: 'clone' | 'update' /** When the step started, if it has. */ startedAt: number | null } @@ -82,12 +84,14 @@ function runningClone( startedAt: number ): VmBuildStep { // No percent yet, or git's first 0% while GitHub counts objects: nothing to measure yet. + const cloneMode = clone?.mode ?? 'clone' if (!clone || (!clone.percent && clone.stage !== 'checkout')) { - return { ...step('clone', 'running', elapsedMs, startedAt), stage: 'counting' } + return { ...step('clone', 'running', elapsedMs, startedAt), stage: 'counting', cloneMode } } return { ...step('clone', 'running', elapsedMs, startedAt, { percent: clone.percent }), - stage: clone.stage ?? 'download' + stage: clone.stage ?? 'download', + cloneMode } } @@ -132,7 +136,10 @@ export function deriveVmBuildSteps( : cloneAt === undefined ? step('clone', provisionDone ? 'done' : 'pending', null, undefined) : clone?.ended || check || workspacePhase - ? step('clone', 'done', span(cloneAt, afterClone), cloneAt) + ? { + ...step('clone', 'done', span(cloneAt, afterClone), cloneAt), + cloneMode: clone?.mode ?? 'clone' + } : failed ? step('clone', 'failed', span(cloneAt, entry.errorAt), cloneAt) : runningClone(clone, span(cloneAt, now), cloneAt) diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 13ddd1561e6..ec448c98c22 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -2289,7 +2289,8 @@ "vmChecksFailed": "Environment checks failed", "preparingCloudEnvironment": "Preparing environment…", "startingSandbox": "Starting sandbox…", - "cloningRepository": "Cloning the repository…" + "cloningRepository": "Cloning the repository…", + "updatingRepository": "Updating the repository…" }, "duplicatePairedServers": { "ambiguousSameServer": "{{value0}} and {{value1}} are the same server paired twice. Remove one in Settings > Remote Orca Servers." @@ -4236,7 +4237,9 @@ "cloneCloud": "Clone repository", "cloneCheckout": "Checking out files…", "cloneDownload": "Downloading history…", - "cloneCounting": "Counting objects…" + "cloneCounting": "Counting objects…", + "updateCloud": "Update repository", + "updateFetching": "Fetching changes…" }, "VmBuildFailureCard": { "createFailedTitle": "Couldn’t create workspace", @@ -4348,7 +4351,8 @@ "denyMachineSize2": "This sandbox size isn’t part of your plan.", "refusedProvider2": "Orca Cloud is unavailable right now.", "rollingOver2": "Restarting the sandbox…", - "cloning": "Cloning the repository…" + "cloning": "Cloning the repository…", + "updating": "Updating the repository…" }, "environmentCheckCopy": { "gitMissing": "git isn’t installed.", diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-clone-progress.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-clone-progress.ts index b4bfe49ebb1..9ecfb2b5834 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-clone-progress.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-clone-progress.ts @@ -1,9 +1,11 @@ // The background clone of an Orca Cloud create, read from the provider's build-log lines -// (`[orca-cloud] cloning`, `[orca-cloud] clone-progress `, then the next phase). +// (`[orca-cloud] cloning` or `updating`, `[orca-cloud] clone-progress `, then the next phase). const PHASE_LINE = /^\[orca-cloud\] ([a-z-]+)$/ const CLONE_PROGRESS_LINE = /^\[orca-cloud\] clone-progress (\d{1,3}) (download|checkout)$/ export type OrcaCloudCloneProgress = { + /** 'update': the repo came prebuilt (an environment build) and only changes are fetched. */ + mode: 'clone' | 'update' startedAt: number | null /** The next phase began: the clone finished. */ ended: boolean @@ -26,8 +28,15 @@ export function orcaCloudCloneProgress( lines.forEach((raw, index) => { const line = raw.trim() const stamp = stamps[index] ?? null - if (line === '[orca-cloud] cloning') { - progress = { startedAt: stamp, ended: false, endedAt: null, percent: null, stage: null } + if (line === '[orca-cloud] cloning' || line === '[orca-cloud] updating') { + progress = { + mode: line.endsWith('updating') ? 'update' : 'clone', + startedAt: stamp, + ended: false, + endedAt: null, + percent: null, + stage: null + } return } if (!progress) { diff --git a/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts b/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts index 69555fda09f..412655cffd3 100644 --- a/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts +++ b/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts @@ -328,7 +328,9 @@ export function getCreationProgressLabel( ? null : orcaCloudCloneProgress(entry.provisioningLog ?? '', []) if (clone && !clone.ended) { - return t('auto.lib.pendingWorktreeCreation.cloningRepository', 'Cloning the repository…') + return clone.mode === 'update' + ? t('auto.lib.pendingWorktreeCreation.updatingRepository', 'Updating the repository…') + : t('auto.lib.pendingWorktreeCreation.cloningRepository', 'Cloning the repository…') } return entry.environmentCheck || clone ? t('auto.lib.pendingWorktreeCreation.preparingCloudEnvironment', 'Preparing environment…') diff --git a/src/shared/hosted-sandbox/hosted-sandbox-wire.ts b/src/shared/hosted-sandbox/hosted-sandbox-wire.ts index 6aa002aedcb..4798f922090 100644 --- a/src/shared/hosted-sandbox/hosted-sandbox-wire.ts +++ b/src/shared/hosted-sandbox/hosted-sandbox-wire.ts @@ -153,7 +153,11 @@ export const HostedSandboxReadyResponseSchema = z connection: HostedSandboxConnectionSchema, /** Create with feature `clone-progress`: the repo is still cloning; poll GET .../clone. */ clone: z - .object({ state: z.literal('running') }) + .object({ + state: z.literal('running'), + /** Booted from an environment build: only what changed since it is fetched (feature `repo-update`). */ + mode: z.literal('update').optional() + }) .strict() .optional() }) From 54961e4868e19720cc7f3a9298bdce2cc22fb7e1 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 19:16:19 -0800 Subject: [PATCH 029/149] wip(cloud): fixtures, tests, i18n --- src/preload/api/ephemeral-vm-api.ts | 5 - src/preload/api/ephemeral-vm-bridge.ts | 1 - .../orca-cloud/CloudSetupNotices.fixture.tsx | 58 +++++++++ .../BlockedSandboxHoursNote.tsx | 12 +- .../VmBuildErrorDetails.test.tsx | 1 + .../VmBuildFailureCard.test.tsx | 78 +++++++---- .../src/i18n/en-runtime-required.json | 8 +- src/renderer/src/i18n/locales/en.json | 74 +++++------ ...emeral-vm-environment-check-triage.test.ts | 63 +++++++++ .../ephemeral-vm-environment-check.test.ts | 122 ++++++++++++++++-- 10 files changed, 330 insertions(+), 92 deletions(-) create mode 100644 src/renderer/src/components/orca-cloud/CloudSetupNotices.fixture.tsx create mode 100644 src/renderer/src/lib/ephemeral-vm-environment-check-triage.test.ts diff --git a/src/preload/api/ephemeral-vm-api.ts b/src/preload/api/ephemeral-vm-api.ts index 8aeb073182f..12ae965adef 100644 --- a/src/preload/api/ephemeral-vm-api.ts +++ b/src/preload/api/ephemeral-vm-api.ts @@ -117,11 +117,6 @@ export type EphemeralVmApi = { * failed environment check). Optional: the web client has no VM lifecycle. */ suspendRuntime?: (args: { runtimeId: string }) => Promise<{ ok: boolean; error?: string }> - /** - * Orca Cloud: puts a sandbox that never became a workspace to sleep (a create blocked on a - * failed environment check). Optional: the web client has no VM lifecycle. - */ - suspendRuntime?: (args: { runtimeId: string }) => Promise<{ ok: boolean; error?: string }> cleanup: (args: { runtimeId: string }) => Promise /** Orca Cloud: before Delete drops the row, prove the signed-in identity can reach the sandbox. */ preflightCloudDelete?: (args: { diff --git a/src/preload/api/ephemeral-vm-bridge.ts b/src/preload/api/ephemeral-vm-bridge.ts index 3220045fa09..cf4e82a6289 100644 --- a/src/preload/api/ephemeral-vm-bridge.ts +++ b/src/preload/api/ephemeral-vm-bridge.ts @@ -57,7 +57,6 @@ export const ephemeralVmApi = { return () => ipcRenderer.removeListener(EPHEMERAL_VM_RUNTIMES_CHANGED_CHANNEL, listener) }, suspendRuntime: (args) => ipcRenderer.invoke('ephemeralVm:suspendRuntime', args), - suspendRuntime: (args) => ipcRenderer.invoke('ephemeralVm:suspendRuntime', args), cleanup: (args) => ipcRenderer.invoke('ephemeralVm:cleanup', args), preflightCloudDelete: (args) => ipcRenderer.invoke('ephemeralVm:preflightCloudDelete', args), stopCleanup: (args) => ipcRenderer.invoke('ephemeralVm:stopCleanup', args), diff --git a/src/renderer/src/components/orca-cloud/CloudSetupNotices.fixture.tsx b/src/renderer/src/components/orca-cloud/CloudSetupNotices.fixture.tsx new file mode 100644 index 00000000000..4cefdfa5a07 --- /dev/null +++ b/src/renderer/src/components/orca-cloud/CloudSetupNotices.fixture.tsx @@ -0,0 +1,58 @@ +import { defineFixture } from '../../component-fixtures/component-fixture' +import type { CloudSetupNotice } from '@/lib/ephemeral-vm-environment-check-triage' +import { CloudSetupNoticesView } from './CloudSetupNotices' + +const noop = (): void => {} + +const PUSH: CloudSetupNotice = { + id: 'git.push', + kind: 'push', + check: { id: 'git.push', category: 'git', status: 'fail', message: 'push refused' } +} +const SETUP: CloudSetupNotice = { + id: 'setup.run', + kind: 'setup', + check: { + id: 'setup.run', + category: 'setup', + status: 'warn', + message: 'Setup script is configured but has not run here.', + code: 'setupNotRun' + } +} +const DISK: CloudSetupNotice = { + id: 'disk.free', + kind: 'check', + check: { + id: 'disk.free', + category: 'disk', + status: 'warn', + message: 'Only 3.2 GB free.', + code: 'diskLow', + params: { free: '3.2' } + } +} + +function notices(list: readonly CloudSetupNotice[], installing = false) { + return defineFixture({ + width: 480, + render: () => ( +
    + +
    + ) + }) +} + +/** The push-access case Neil hit: public repo, App installed only on his personal account. */ +export const pushOnly = notices([PUSH]) +export const pushWaitingForGitHub = notices([PUSH], true) +export const setupOnly = notices([SETUP]) +export const allThree = notices([PUSH, SETUP, DISK]) diff --git a/src/renderer/src/components/worktree-creation/BlockedSandboxHoursNote.tsx b/src/renderer/src/components/worktree-creation/BlockedSandboxHoursNote.tsx index f660c0d868e..dd1a0373ba8 100644 --- a/src/renderer/src/components/worktree-creation/BlockedSandboxHoursNote.tsx +++ b/src/renderer/src/components/worktree-creation/BlockedSandboxHoursNote.tsx @@ -33,16 +33,16 @@ export function BlockedSandboxHoursNote({ 'Asleep. It isn’t using sandbox hours.' ) : sandbox === 'sleeping' - ? t( - 'auto.components.worktree.creation.BlockedSandboxHoursNote.sleeping', - 'Putting the sandbox to sleep…' - ) + ? t('auto.components.worktree.creation.BlockedSandboxHoursNote.sleeping', 'Going to sleep…') : sleepsAt === undefined ? null : t( 'auto.components.worktree.creation.BlockedSandboxHoursNote.sleepsIn', - 'Sleeps in {{count}} min if unused', - { count: minutesUntilSleep(sleepsAt, now) } + 'Sleeps in {{count}} minutes if unused.', + { + count: minutesUntilSleep(sleepsAt, now), + defaultValue_one: 'Sleeps in {{count}} minute if unused.' + } ) if (!text) { return null diff --git a/src/renderer/src/components/worktree-creation/VmBuildErrorDetails.test.tsx b/src/renderer/src/components/worktree-creation/VmBuildErrorDetails.test.tsx index 33ae558308d..c0c8205db76 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildErrorDetails.test.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildErrorDetails.test.tsx @@ -18,6 +18,7 @@ const actions = (): VmBuildFailureActions => ({ onRetry: vi.fn(), onEditRecipe: vi.fn(), onOpenAnyway: vi.fn(), + onStartAgain: vi.fn(), onDismiss: vi.fn(), onSeePlans: vi.fn(), onOpenBilling: vi.fn(), diff --git a/src/renderer/src/components/worktree-creation/VmBuildFailureCard.test.tsx b/src/renderer/src/components/worktree-creation/VmBuildFailureCard.test.tsx index 0ba3bc72fd9..affb1f62969 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildFailureCard.test.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildFailureCard.test.tsx @@ -15,6 +15,7 @@ const actions = (): VmBuildFailureActions => ({ onRetry: vi.fn(), onEditRecipe: vi.fn(), onOpenAnyway: vi.fn(), + onStartAgain: vi.fn(), onDismiss: vi.fn(), onSeePlans: vi.fn(), onOpenBilling: vi.fn(), @@ -116,23 +117,26 @@ it("keeps Use this computer instead beside an owner's billing fix", () => { expect(buttons.slice(0, 2)).toEqual(['Raise spend cap', 'Use this computer instead']) }) -const CHECKS: VmBuildFailure = { +const FATAL: VmBuildFailure = { kind: 'checks', problems: [ - { id: 'tool.pnpm', category: 'tools', status: 'fail', message: 'pnpm is missing.' }, - { id: 'agent.claude', category: 'agents', status: 'warn', message: 'Claude is signed out.' }, - { id: 'git.push', category: 'git', status: 'fail', message: 'Push was refused.' } - ] + { + id: 'environment.doctor', + category: 'workspace', + status: 'fail', + message: 'The environment checks could not finish: unreachable' + } + ], + sleepsAt: Date.now() + 5 * 60_000 } -it('counts only failed checks in the title and leads with Open anyway on a running sandbox', () => { - const handlers = actions() - render( +function cloudCard(failure: VmBuildFailure, handlers: VmBuildFailureActions, vmKept = true) { + return (
    ) +} + +it('Orca Cloud: an unusable sandbox leads with Start again and says when it sleeps', () => { + const handlers = actions() + render(cloudCard(FATAL, handlers)) const alert = screen.getByRole('alert') - expect(alert.textContent).toContain('The sandbox is up, but 2 environment checks failed') - // The check rows are read on demand, not announced with the cause. - expect(alert.textContent).not.toContain('pnpm is missing') + expect(alert.textContent).toContain('This sandbox can’t open your workspace') + expect(screen.getByText('Orca couldn’t reach the sandbox.')).toBeTruthy() + // Never "until you choose": the sandbox stops spending hours on its own. + expect(screen.getByText('Sleeps in 5 minutes if unused.')).toBeTruthy() const buttons = screen.getAllByRole('button').map((button) => button.textContent?.trim()) - expect(buttons).toEqual(['Open anyway', 'Run checks again', 'Delete sandbox']) - fireEvent.click(screen.getByRole('button', { name: 'Open anyway' })) - expect(handlers.onOpenAnyway).toHaveBeenCalledOnce() + expect(buttons).toEqual(['Start again', 'Run checks again', 'Delete sandbox']) + fireEvent.click(screen.getByRole('button', { name: 'Start again' })) + expect(handlers.onStartAgain).toHaveBeenCalledOnce() +}) + +it('Orca Cloud: once asleep, checking again is gone and the card says it uses no hours', () => { + render(cloudCard({ ...FATAL, sandbox: 'asleep' }, actions())) + expect(screen.getByText('Asleep. It isn’t using sandbox hours.')).toBeTruthy() + const buttons = screen.getAllByRole('button').map((button) => button.textContent?.trim()) + expect(buttons).toEqual(['Start again', 'Delete sandbox']) +}) + +it('Orca Cloud: a sandbox deleted instead of slept leaves nothing to delete', () => { + render(cloudCard({ ...FATAL, sandbox: 'deleted' }, actions(), false)) + expect(screen.getByRole('alert').textContent).toContain('The sandbox was deleted.') + const buttons = screen.getAllByRole('button').map((button) => button.textContent?.trim()) + expect(buttons).toEqual(['Start again', 'Dismiss']) }) it('reads an account limit as a neutral notice rather than an error', () => { @@ -170,16 +194,18 @@ it('says nothing was created only when no sandbox is left running', () => { expect(kept).toContain('delete the sandbox') }) -it('uses the singular for one failed check and names warnings-only runs as needing attention', () => { - const context = { cloud: true, canManageBilling: true, repoName: 'acme/web' } - const one: VmBuildFailure = { kind: 'checks', problems: CHECKS.problems.slice(0, 2) } - const copy = vmBuildFailureCopy(one, context, translate) - expect(copy.title).toBe('The sandbox is up, but 1 environment check failed') - expect(copy.body).toContain('fix them') - const warningOnly: VmBuildFailure = { kind: 'checks', problems: CHECKS.problems.slice(1, 2) } - const warned = vmBuildFailureCopy(warningOnly, context, translate) - expect(warned.title).toBe('The sandbox is up, but some environment checks need attention') - expect(warned.body).toContain('fix it inside') +it('recipe VMs keep counting failed checks in the title', () => { + const context = { cloud: false, canManageBilling: true, repoName: 'acme/web' } + const problems: VmBuildFailure = { + kind: 'checks', + problems: [ + { id: 'tool.pnpm', category: 'tools', status: 'fail', message: 'pnpm is missing.' }, + { id: 'disk.free', category: 'disk', status: 'warn', message: 'Low disk.' } + ] + } + expect(vmBuildFailureCopy(problems, context, translate).title).toBe( + 'The VM is up, but 1 environment check failed' + ) }) it('keeps InlineError announcing the whole box without children, and only the text with them', () => { diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 5a71a0907a4..1b5e8d1324b 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -1340,15 +1340,15 @@ }, "worktree": { "creation": { + "BlockedSandboxHoursNote": { + "sleepsIn_one": "Sleeps in {{count}} minute if unused.", + "sleepsIn_other": "Sleeps in {{count}} minutes if unused." + }, "VmBuildErrorDetails": { "earlierLines_one": "…{{count}} earlier line. Copy details includes it.", "earlierLines_other": "…{{count}} earlier lines. Copy details includes them." }, "VmBuildFailureCard": { - "checksBodyCloud2_one": "Open it anyway and fix it inside the workspace, or run the checks again after changing your project.", - "checksBodyCloud2_other": "Open it anyway and fix them inside the workspace, or run the checks again after changing your project.", - "checksCountTitleCloud_one": "The sandbox is up, but {{count}} environment check failed", - "checksCountTitleCloud_other": "The sandbox is up, but {{count}} environment checks failed", "checksCountTitleVm_one": "The VM is up, but {{count}} environment check failed", "checksCountTitleVm_other": "The VM is up, but {{count}} environment checks failed", "memberLimitBodyCount_one": "You can run {{count}} sandbox at once. Put it to sleep or delete it, then try again. Nothing was created, and you weren’t charged.", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 13ddd1561e6..9e375db7fc8 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -2330,7 +2330,8 @@ "ephemeralVmEnvironmentCheck": { "backgroundFailed": "Environment checks failed for a new VM workspace. Open it in the sidebar to continue.", "openedDegraded": "Creating the workspace on a VM whose environment checks failed.", - "unreachable": "The environment checks could not finish: {{error}}" + "unreachable": "The environment checks could not finish: {{error}}", + "backgroundFailedCloud": "A new cloud workspace couldn’t start. Open it in the sidebar to continue." }, "orcaCloudSession": { "seePlans": "See plans", @@ -4245,7 +4246,6 @@ "unavailableTitle": "Orca Cloud is unavailable right now", "networkTitle": "Couldn’t reach Orca Cloud", "snapshotTitle": "This project’s saved environment is missing", - "stillRunningCloud": "The sandbox is running and using sandbox hours until you choose.", "stillRunningLocal": "The VM is running and using hours until you choose.", "tryAgain": "Try again", "signIn": "Sign in", @@ -4288,14 +4288,9 @@ "outOfHoursBodyMember3": "Your team has used this month’s sandbox hours, so sandboxes can’t start or keep running. Nothing was created, and you weren’t charged. Ask an owner or admin to add hours.", "spendCapReachedBodyMember4": "Your team has reached this month’s spend cap, so sandboxes can’t start or keep running. Nothing was created, and you weren’t charged. Ask an owner or admin to raise the spend cap.", "paymentFailedBodyMember2": "New sandboxes can’t start until the payment goes through. Nothing was created, and you weren’t charged. Ask an owner or admin to update the payment method.", - "checksAttentionTitleCloud": "The sandbox is up, but some environment checks need attention", "checksAttentionTitleVm": "The VM is up, but some environment checks need attention", - "checksCountTitleCloud_one": "The sandbox is up, but {{count}} environment check failed", - "checksCountTitleCloud_other": "The sandbox is up, but {{count}} environment checks failed", "checksCountTitleVm_one": "The VM is up, but {{count}} environment check failed", "checksCountTitleVm_other": "The VM is up, but {{count}} environment checks failed", - "checksBodyCloud2_one": "Open it anyway and fix it inside the workspace, or run the checks again after changing your project.", - "checksBodyCloud2_other": "Open it anyway and fix them inside the workspace, or run the checks again after changing your project.", "provisionBodyCloudKept": "Something went wrong while starting the sandbox. Try again, or delete the sandbox to stop using sandbox hours.", "provisionBodyCloud2": "Something went wrong while starting the sandbox. Nothing was created, and you weren’t charged.", "provisionBodyVm": "Your VM recipe stopped with an error before the VM was ready.", @@ -4310,7 +4305,11 @@ "cloneDiskFullBody": "This repository doesn’t fit on the sandbox’s disk. The sandbox was deleted.", "cloneFailedBody": "Git stopped with an error while cloning, and the sandbox was deleted. Try again, or open the logs for details.", "githubNotConnectedBody2": "Orca Cloud clones your code from GitHub and needs access to this repository first. Install the Orca GitHub App on {{owner}}, then try again. Nothing was created, and you weren’t charged.", - "cloneFailedTitle": "Couldn’t clone {{repo}}" + "cloneFailedTitle": "Couldn’t clone {{repo}}", + "startAgain": "Start again", + "cloudUnusableTitle": "This sandbox can’t open your workspace", + "cloudUnusableDeletedBody": "The sandbox was deleted. Start again to try a new one.", + "cloudUnusableBody": "Start again on a new sandbox, or delete this one." }, "VmBuildLog": { "jumpToError": "Jump to first error", @@ -4366,7 +4365,12 @@ "failed": "Failed", "warning": "Warning", "passed": "Passed", - "toolMissingFixCloud": "Install {{command}} in the workspace, or add it to your project’s setup script." + "toolMissingFixCloud": "Install {{command}} in the workspace, or add it to your project’s setup script.", + "setupNotRun": "Setup script hasn’t run yet.", + "cloudUnreachable": "Orca couldn’t reach the sandbox.", + "cloudRepoMissing": "The repository isn’t in the sandbox.", + "cloudRepoUnreadable": "Git can’t read the repository in the sandbox.", + "cloudGitMissing": "git isn’t installed in the sandbox." }, "WorktreeCreationTabStrip": { "cancelLabel": "Cancel workspace creation" @@ -4386,6 +4390,12 @@ "copiedStatus": "Details copied", "earlierLines_one": "…{{count}} earlier line. Copy details includes it.", "earlierLines_other": "…{{count}} earlier lines. Copy details includes them." + }, + "BlockedSandboxHoursNote": { + "asleep": "Asleep. It isn’t using sandbox hours.", + "sleeping": "Going to sleep…", + "sleepsIn_one": "Sleeps in {{count}} minute if unused.", + "sleepsIn_other": "Sleeps in {{count}} minutes if unused." } } }, @@ -27367,6 +27377,19 @@ "public": "{{repo}} is public. Nothing to do.", "doneStatus": "Done" } + }, + "setupNotices": { + "pushNeedsApp": "Orca Cloud can read {{repo}} but can’t push yet. Install the Orca GitHub App on {{owner}} to push.", + "waitingForGitHub": "Waiting for GitHub…", + "installOn": "Install on {{owner}}", + "pushRefused": "Orca Cloud can’t push from this workspace.", + "setupNotRun": "Setup script hasn’t run yet", + "runSetup": "Run setup script", + "label": "Workspace setup", + "dismiss": "Dismiss", + "installFailed": "Couldn’t open GitHub. Check your connection and try again.", + "pushReady": "Orca Cloud can push to {{repo}} now.", + "setupMissing": "Couldn’t read the setup script from orca.yaml in this workspace." } }, "runActions": { @@ -27845,31 +27868,9 @@ "menu": { "notYet": "You can choose once the sandbox is created.", "failed": "Couldn’t read this workspace’s choice.", - "shared": "Personal accounts aren’t used in shared workspaces.", - "label": "Agent sign-in options", - "inThisWorkspace": "{{agent}} in this workspace", "yourAccount": "Your account", - "useKey": "Use an API key instead", - "manage": "Manage agent accounts…", "saveFailed": "Couldn’t change it. Nothing was changed." }, - "codeCopied": "Code copied", - "cancel": "Cancel", - "renew": "Renew", - "setUp": "Set up", - "openAgain": "Open again", - "copyAndOpen": "Copy code and open", - "pasteToken": "Paste token", - "tryAgain": "Try again", - "dismiss": "Dismiss", - "signInHere": "Sign in for this workspace", - "checking": "Checking agent sign-in", - "readyDetail": "Every cloud workspace uses it. Nothing to do here.", - "keyFailed": "Couldn’t save {{name}}. Nothing was changed.", - "queued": "Opens when the sandbox is ready. Keep Orca open until then.", - "deviceEnter": "Enter", - "deviceOn": "on {{host}}", - "manage": "Manage", "separator": " · ", "stepOf": "{{step}} of {{of}}", "settingUp": "Setting up {{agent}}", @@ -27987,17 +27988,6 @@ "cancelledToast": "The agent didn’t start. The shell is still open.", "expiredCompact": "{{agent}} sign-in expired" }, - "cloudAgentCheck": { - "keyAgentSignedOut": "{{agent}} isn’t signed in.", - "keyAgentFix": "Add its API key in Settings → Cloud secrets, or sign in when it starts in this workspace.", - "notSetUp": "{{agent}} isn’t set up for Orca Cloud yet.", - "notSetUpFix": "Set it up once in Settings → Agent accounts. Every cloud workspace uses it.", - "expired": "Your {{agent}} sign-in for Orca Cloud expired.", - "expiredFix": "Renew it once in Settings → Agent accounts. Every cloud workspace uses it.", - "signInHere": "{{agent}} isn’t signed in for this workspace.", - "pausedFix": "Orca account sign-in is paused. Sign in for this workspace; the sign-in stays with this workspace.", - "notOfferedFix": "Signs in for each cloud workspace for now. Sign in for this workspace; the sign-in stays with this workspace." - }, "cloudSetupPage": { "agent": { "lead": "Save your agent sign-in to your Orca account and every cloud workspace uses it. You can also skip this and sign in inside the workspace.", diff --git a/src/renderer/src/lib/ephemeral-vm-environment-check-triage.test.ts b/src/renderer/src/lib/ephemeral-vm-environment-check-triage.test.ts new file mode 100644 index 00000000000..e409bbeb535 --- /dev/null +++ b/src/renderer/src/lib/ephemeral-vm-environment-check-triage.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vitest' +import type { EnvironmentDoctorCheck } from '../../../shared/environment-doctor-types' +import { triageCloudEnvironmentChecks } from './ephemeral-vm-environment-check-triage' + +const c = ( + id: string, + status: EnvironmentDoctorCheck['status'], + category: EnvironmentDoctorCheck['category'] = 'tools' +): EnvironmentDoctorCheck => ({ id, category, status, message: id }) + +describe('triageCloudEnvironmentChecks', () => { + it('stops only on a sandbox nobody can work in', () => { + const { fatal } = triageCloudEnvironmentChecks( + [ + c('environment.doctor', 'fail', 'workspace'), + c('workspace.path', 'fail', 'workspace'), + c('git.repo', 'fail', 'git'), + c('tool.git', 'fail'), + c('git.push', 'fail', 'git'), + c('git.fetch', 'fail', 'git'), + c('tool.pnpm', 'fail'), + c('disk.free', 'fail', 'disk') + ], + { setupRunsOnCreate: true } + ) + expect(fatal.map((check) => check.id)).toEqual([ + 'environment.doctor', + 'workspace.path', + 'git.repo', + 'tool.git' + ]) + }) + + it('drops agent sign-in, advice, and passes; keeps push, setup and the rest as notices', () => { + const { fatal, notices } = triageCloudEnvironmentChecks( + [ + c('tool.git', 'pass'), + c('agent.claude', 'warn', 'agents'), + c('agent.cli', 'warn', 'agents'), + c('git.push', 'fail', 'git'), + c('setup.run', 'warn', 'setup'), + c('setup.script', 'warn', 'setup'), + c('git.remote', 'warn', 'git'), + c('disk.free', 'warn', 'disk') + ], + { setupRunsOnCreate: false } + ) + expect(fatal).toEqual([]) + expect(notices.map((notice) => [notice.id, notice.kind])).toEqual([ + ['git.push', 'push'], + ['setup.run', 'setup'], + ['disk.free', 'check'] + ]) + }) + + it('says nothing about a setup script the create is about to run, or a push with no commits', () => { + const { notices } = triageCloudEnvironmentChecks( + [c('setup.run', 'warn', 'setup'), c('git.push', 'warn', 'git')], + { setupRunsOnCreate: true } + ) + expect(notices).toEqual([]) + }) +}) diff --git a/src/renderer/src/lib/ephemeral-vm-environment-check.test.ts b/src/renderer/src/lib/ephemeral-vm-environment-check.test.ts index b4af3b7f4c9..56e777f5421 100644 --- a/src/renderer/src/lib/ephemeral-vm-environment-check.test.ts +++ b/src/renderer/src/lib/ephemeral-vm-environment-check.test.ts @@ -1,7 +1,17 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +type Entry = { + environmentCheck?: { + status: string + checks?: { id: string }[] + sleepsAt?: number + finishedAt?: number + sandbox?: string + } +} const { callRuntimeRpc, supportsCapability, store } = vi.hoisted(() => { - const entries: Record = {} + const entries: Record = {} return { callRuntimeRpc: vi.fn(), supportsCapability: vi.fn(async () => true), @@ -9,6 +19,7 @@ const { callRuntimeRpc, supportsCapability, store } = vi.hoisted(() => { entries, getState: () => ({ pendingWorktreeCreations: entries, + activePendingCreationId: 'c1', updatePendingWorktreeCreation: (id: string, patch: Record) => { if (entries[id]) { Object.assign(entries[id], patch) @@ -26,11 +37,19 @@ vi.mock('@/runtime/rpc/compatibility/runtime-capability-proof', () => ({ runtimeEnvironmentSupportsCapability: supportsCapability })) -import { gateVmCreateOnEnvironmentCheck } from './ephemeral-vm-environment-check' +import { + BLOCKED_SANDBOX_SLEEP_MS, + gateVmCreateOnEnvironmentCheck, + type CloudEnvironmentCheckContext +} from './ephemeral-vm-environment-check' import { cancelVmEnvironmentCheck, resolveVmEnvironmentCheckDecision } from './ephemeral-vm-environment-check-decision' +import { + getCloudSetupNoticesRecord, + resetCloudSetupNotices +} from './orca-cloud/cloud-setup-notices-store' const failing = { worktreePath: '/w', @@ -38,6 +57,31 @@ const failing = { checks: [{ id: 'tool.pnpm', category: 'tools', status: 'fail', message: 'pnpm missing' }] } const passing = { worktreePath: '/w', ok: true, checks: [] } +// What Neil saw: agents not set up, push refused, setup not run. None of it should stop the create. +const cloudWarnings = { + worktreePath: '/w', + ok: false, + checks: [ + { id: 'agent.claude', category: 'agents', status: 'warn', message: 'Claude signed out' }, + { id: 'git.push', category: 'git', status: 'fail', message: 'push refused' }, + { id: 'setup.run', category: 'setup', status: 'warn', message: 'not run', code: 'setupNotRun' } + ] +} +const cloudFatal = { + worktreePath: '/w', + ok: false, + checks: [ + { id: 'workspace.path', category: 'workspace', status: 'fail', message: 'no repo' }, + { id: 'git.push', category: 'git', status: 'fail', message: 'push refused' } + ] +} +const CLOUD: CloudEnvironmentCheckContext = { + runtimeId: 'rt-1', + setupRunsOnCreate: false, + repoId: 'repo-1', + hostId: 'runtime:env-1', + repoUrl: 'https://github.com/stablyai/orca' +} async function settle(): Promise { for (let i = 0; i < 10; i++) { @@ -53,6 +97,11 @@ describe('gateVmCreateOnEnvironmentCheck', () => { store.entries.c1 = {} callRuntimeRpc.mockReset() supportsCapability.mockResolvedValue(true) + resetCloudSetupNotices() + }) + afterEach(() => { + vi.useRealTimers() + vi.unstubAllGlobals() }) it('pauses on failed checks, re-runs them on retry, and continues once they pass', async () => { @@ -62,7 +111,7 @@ describe('gateVmCreateOnEnvironmentCheck', () => { expect(store.entries.c1.environmentCheck?.status).toBe('failed') resolveVmEnvironmentCheckDecision('c1', 'retry') - await expect(gate).resolves.toBe(true) + await expect(gate).resolves.toBe('proceed') expect(callRuntimeRpc).toHaveBeenCalledTimes(2) expect(store.entries.c1.environmentCheck?.status).toBe('passed') }) @@ -72,13 +121,13 @@ describe('gateVmCreateOnEnvironmentCheck', () => { const opened = gateVmCreateOnEnvironmentCheck('c1', 'env-1', '/w') await settle() resolveVmEnvironmentCheckDecision('c1', 'open-anyway') - await expect(opened).resolves.toBe(true) + await expect(opened).resolves.toBe('proceed') const dismissed = gateVmCreateOnEnvironmentCheck('c1', 'env-1', '/w') await settle() delete store.entries.c1 cancelVmEnvironmentCheck('c1') - await expect(dismissed).resolves.toBe(false) + await expect(dismissed).resolves.toBe('stop') }) it('aborts a running check when the build is dismissed', async () => { @@ -94,14 +143,71 @@ describe('gateVmCreateOnEnvironmentCheck', () => { await settle() delete store.entries.c1 cancelVmEnvironmentCheck('c1') - await expect(gate).resolves.toBe(false) + await expect(gate).resolves.toBe('stop') expect(signal?.aborted).toBe(true) }) it('skips the checks on a VM server that predates them', async () => { supportsCapability.mockResolvedValue(false) - await expect(gateVmCreateOnEnvironmentCheck('c1', 'env-1', '/w')).resolves.toBe(true) + await expect(gateVmCreateOnEnvironmentCheck('c1', 'env-1', '/w')).resolves.toBe('proceed') expect(callRuntimeRpc).not.toHaveBeenCalled() expect(store.entries.c1.environmentCheck?.status).toBe('skipped') }) + + it('Orca Cloud opens on warnings and a refused push, and hands them to the workspace', async () => { + callRuntimeRpc.mockResolvedValue(cloudWarnings) + await expect(gateVmCreateOnEnvironmentCheck('c1', 'env-1', '/w', CLOUD)).resolves.toBe( + 'proceed' + ) + expect(store.entries.c1.environmentCheck?.status).toBe('passed') + const record = getCloudSetupNoticesRecord('env-1') + expect(record?.repoUrl).toBe('https://github.com/stablyai/orca') + // Agent sign-in is never a notice; push and setup are. + expect(record?.notices.map((notice) => notice.kind)).toEqual(['push', 'setup']) + }) + + it('Orca Cloud stops only on a fatal check, lists just it, and can start over', async () => { + callRuntimeRpc.mockResolvedValue(cloudFatal) + const gate = gateVmCreateOnEnvironmentCheck('c1', 'env-1', '/w', CLOUD) + await settle() + const check = store.entries.c1.environmentCheck + expect(check?.status).toBe('failed') + expect(check?.checks?.map((c) => c.id)).toEqual(['workspace.path']) + expect(check?.sleepsAt).toBe((check?.finishedAt ?? 0) + BLOCKED_SANDBOX_SLEEP_MS) + + resolveVmEnvironmentCheckDecision('c1', 'restart') + await expect(gate).resolves.toBe('restart') + }) + + it('puts a blocked sandbox to sleep after five unused minutes', async () => { + vi.useFakeTimers() + const suspendRuntime = vi.fn(async () => ({ ok: true })) + vi.stubGlobal('window', { api: { ephemeralVm: { suspendRuntime } } }) + callRuntimeRpc.mockResolvedValue(cloudFatal) + const gate = gateVmCreateOnEnvironmentCheck('c1', 'env-1', '/w', CLOUD) + await vi.advanceTimersByTimeAsync(0) + expect(store.entries.c1.environmentCheck?.status).toBe('failed') + + await vi.advanceTimersByTimeAsync(BLOCKED_SANDBOX_SLEEP_MS - 1) + expect(suspendRuntime).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(1) + expect(suspendRuntime).toHaveBeenCalledWith({ runtimeId: 'rt-1' }) + expect(store.entries.c1.environmentCheck?.sandbox).toBe('asleep') + + // Still waiting on the user: Delete or Start again. + cancelVmEnvironmentCheck('c1') + await expect(gate).resolves.toBe('stop') + }) + + it('deletes a blocked sandbox that cannot sleep, so it never keeps billing', async () => { + vi.useFakeTimers() + const suspendRuntime = vi.fn(async () => ({ ok: false, error: 'nope' })) + vi.stubGlobal('window', { api: { ephemeralVm: { suspendRuntime } } }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + callRuntimeRpc.mockResolvedValue(cloudFatal) + const gate = gateVmCreateOnEnvironmentCheck('c1', 'env-1', '/w', CLOUD) + await vi.advanceTimersByTimeAsync(BLOCKED_SANDBOX_SLEEP_MS) + await expect(gate).resolves.toBe('stop') + expect(store.entries.c1.environmentCheck?.sandbox).toBe('deleted') + }) }) From 76e40f99ade6400cacceb880526f66b8f12fef14 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 19:16:53 -0800 Subject: [PATCH 030/149] chore(cloud): dev-only env-check fault for real-app proof --- src/renderer/src/lib/ephemeral-vm-environment-check.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/renderer/src/lib/ephemeral-vm-environment-check.ts b/src/renderer/src/lib/ephemeral-vm-environment-check.ts index 06bd91ec048..91f4a2c00a5 100644 --- a/src/renderer/src/lib/ephemeral-vm-environment-check.ts +++ b/src/renderer/src/lib/ephemeral-vm-environment-check.ts @@ -61,6 +61,14 @@ export async function runVmEnvironmentCheck( ): Promise { const signal = creationId ? beginVmEnvironmentCheckRun(creationId) : undefined try { + // Dev builds only: lets a real create exercise the unreachable-sandbox stop (and its sleep). + if ( + import.meta.env.DEV && + typeof localStorage !== 'undefined' && + localStorage.getItem('orca:dev:envCheckFault') === 'unreachable' + ) { + throw new Error('Simulated unreachable sandbox (orca:dev:envCheckFault).') + } return await callRuntimeRpc( { kind: 'environment', environmentId }, ENVIRONMENT_DOCTOR_METHOD, From 566cffda8e7b0f0066ab9ca64142280bbb0ac6f7 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 19:18:22 -0800 Subject: [PATCH 031/149] fix(cloud): a deleted blocked sandbox needs no delete confirm --- .../src/components/worktree-creation/WorktreeCreationPanel.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx b/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx index d7aca945fb2..e5770626f92 100644 --- a/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx +++ b/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx @@ -42,7 +42,7 @@ export default function WorktreeCreationPanel({ const dismiss = (): void => useAppStore.getState().removePendingWorktreeCreation(creationId) // A failed or paused VM build still holds a VM that dismissing deletes, so confirm first. const holdsVm = - entry.environmentCheck?.status === 'failed' || + (entry.environmentCheck?.status === 'failed' && entry.environmentCheck.sandbox !== 'deleted') || (entry.status === 'error' && Boolean(entry.request.ephemeralVmRuntimeId)) const leave = holdsVm ? () => setConfirmingDelete(true) : dismiss const isError = entry.status === 'error' From 46b467d84792d99b5c565e3b443c0964ff4eaba7 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 19:22:39 -0800 Subject: [PATCH 032/149] feat(cloud): workspace numbers (W-123), org slug links and synced sidebar prefs on the control plane (G13, G14) --- .../0051_workspace_numbers_prefs.sql | 40 ++++ cloud/apps/sandbox-control/src/index.ts | 37 +++- cloud/apps/sandbox-control/src/org-slugs.ts | 123 ++++++++++++ cloud/apps/sandbox-control/src/store.ts | 36 ++-- .../sandbox-control/src/workspace-prefs.ts | 86 +++++++++ cloud/apps/sandbox-control/src/workspaces.ts | 59 ++++-- .../test/workspace-numbers-prefs.test.ts | 175 ++++++++++++++++++ 7 files changed, 529 insertions(+), 27 deletions(-) create mode 100644 cloud/apps/sandbox-control/migrations/0051_workspace_numbers_prefs.sql create mode 100644 cloud/apps/sandbox-control/src/org-slugs.ts create mode 100644 cloud/apps/sandbox-control/src/workspace-prefs.ts create mode 100644 cloud/apps/sandbox-control/test/workspace-numbers-prefs.test.ts diff --git a/cloud/apps/sandbox-control/migrations/0051_workspace_numbers_prefs.sql b/cloud/apps/sandbox-control/migrations/0051_workspace_numbers_prefs.sql new file mode 100644 index 00000000000..329a96abb2d --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0051_workspace_numbers_prefs.sql @@ -0,0 +1,40 @@ +-- G14: every cloud workspace gets a short number in its account (W-123), allocated from a per-account +-- counter so a number is never reused, even after the row is destroyed. Orgs get a URL slug for links +-- (orca://cloud//W-123). G13: each member's sidebar prefs for cloud workspaces (pins, their +-- order, and the order of sections) live on the account so every device shows the same sidebar. +ALTER TABLE sandboxes ADD COLUMN number INTEGER; + +-- Backfill: existing rows numbered by creation order within their account. +UPDATE sandboxes SET number = ( + SELECT COUNT(*) FROM sandboxes AS earlier + WHERE earlier.account_id = sandboxes.account_id + AND (earlier.created_at < sandboxes.created_at OR (earlier.created_at = sandboxes.created_at AND earlier.id <= sandboxes.id)) +); + +CREATE UNIQUE INDEX sandboxes_account_number ON sandboxes (account_id, number) WHERE number IS NOT NULL; + +CREATE TABLE org_workspace_counters ( + account_id TEXT PRIMARY KEY, + last_number INTEGER NOT NULL +); + +INSERT INTO org_workspace_counters (account_id, last_number) + SELECT account_id, MAX(number) FROM sandboxes GROUP BY account_id; + +CREATE TABLE org_slugs ( + account_id TEXT PRIMARY KEY, + slug TEXT NOT NULL UNIQUE, + created_at INTEGER NOT NULL, + created_by TEXT NOT NULL, + updated_at INTEGER NOT NULL +); + +CREATE TABLE workspace_prefs ( + account_id TEXT NOT NULL, + user_id TEXT NOT NULL, + document TEXT NOT NULL, + revision INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + updated_by_device TEXT, + PRIMARY KEY (account_id, user_id) +); diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 8d833367e3e..6723096d443 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -24,7 +24,8 @@ // POST /v1/device-sessions | GET | DELETE /:id per-phone access (see device-sessions.ts) // Phones sign their own EdDSA tokens (device-sessions.ts) and act as their user, except that they // cannot enroll devices, manage secrets or connect GitHub. -// /v1/team/workspaces[/:id[/presence|wake|lease|grants[/:grantId]]], /v1/team/links/resolve, /v1/team/prompts +// /v1/team/workspaces[/:id[/presence|wake|lease|grants[/:grantId]]], /v1/team/links/resolve, /v1/team/prompts, +// /v1/team/prefs (src/workspace-prefs.ts), /v1/team/org (src/org-slugs.ts) // team workspace registry, presence, per-device grants (src/workspaces.ts, src/grants.ts) // POST /v1/team/workspaces/:id/wake?wait=30s: any member who can open it wakes it (single-flight, // billed to the account, counted on the owner's seat like every wake) -> {state, endpoint: null, …} @@ -186,7 +187,10 @@ import { userAuthorizeUrl } from './github-user-tokens' import { MEMBER_GIT_WINDOW_MS, memberGitRoutes, memberSentWithin, recordMemberSend } from './member-git' +import { getWorkspacePrefs, putWorkspacePrefs } from './workspace-prefs' +import { getOrgSlug, putOrgSlug } from './org-slugs' import { + LinkOtherOrgError, PatchSchema, PresenceSchema, WORKSPACE_ERROR_STATUS, @@ -1480,7 +1484,9 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) url.pathname === '/v1/team/workspaces' || url.pathname.startsWith('/v1/team/workspaces/') || url.pathname === '/v1/team/links/resolve' || - url.pathname === '/v1/team/prompts' + url.pathname === '/v1/team/prompts' || + url.pathname === '/v1/team/prefs' || + url.pathname === '/v1/team/org' ) { const caller = await authenticateDesktop(env, request, (deps.now ?? Date.now)()) if (!caller) { @@ -1818,7 +1824,32 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps, // Labels for teammates' lists; a failure here must never fail the request itself. await rememberCallerName(db, caller, now).catch((error: unknown) => console.warn('member_name_write_failed', String(error))) if (url.pathname === '/v1/team/links/resolve' && request.method === 'GET') { - return json(await resolveLink(db, caller, url, now)) + try { + return json(await resolveLink(db, caller, url, now)) + } catch (error) { + if (error instanceof LinkOtherOrgError) { + return json({ error: 'not_found', reason: 'other_org', orgId: error.orgId }, 404) + } + throw error + } + } + if (url.pathname === '/v1/team/prefs') { + if (request.method === 'GET') { + return json(await getWorkspacePrefs(db, caller)) + } + if (request.method === 'PUT') { + return json(await putWorkspacePrefs(db, caller, await readJson(request), now)) + } + return fail('not_found', 404) + } + if (url.pathname === '/v1/team/org') { + if (request.method === 'GET') { + return json(await getOrgSlug(db, caller, url, now)) + } + if (request.method === 'PUT') { + return json(await putOrgSlug(db, caller, await readJson(request), now)) + } + return fail('not_found', 404) } if (url.pathname === '/v1/team/prompts') { if (request.method === 'GET') { diff --git a/cloud/apps/sandbox-control/src/org-slugs.ts b/cloud/apps/sandbox-control/src/org-slugs.ts new file mode 100644 index 00000000000..90de39782e2 --- /dev/null +++ b/cloud/apps/sandbox-control/src/org-slugs.ts @@ -0,0 +1,123 @@ +// Org URL slugs for workspace links (orca://cloud//W-123). +// GET /v1/team/org?name= -> {slug, orgId}; the first call names it from `name` +// PUT /v1/team/org {slug} org owner/admin renames it (409 when another org has it) +// Auth owns orgs and knows their names; this Worker only sees ids. So the first member to ask +// proposes a slug from the name their client shows, and the Worker makes it unique. Personal +// accounts have no slug: their links keep the sandbox id form (orca://cloud/w/). +import { z } from 'zod' +import type { SandboxCaller } from './auth' +import { WorkspaceError, isOrgAdmin } from './workspaces' + +/** Path words a slug can't take: they'd read as a different link form. */ +const RESERVED = new Set(['w', 'c', 'me', 'api', 'app', 'new', 'org', 'team', 'settings', 'cloud', 'orca', 'admin', 'help']) + +export const SLUG = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/ + +export function isValidSlug(value: string): boolean { + return SLUG.test(value) && !value.includes('--') && !RESERVED.has(value) +} + +/** "Acme Labs, Inc." → "acme-labs-inc"; falls back to "team" when nothing usable is left. */ +export function slugify(name: string): string { + const base = name + .normalize('NFKD') + .replace(/[̀-ͯ]/g, '') + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + .slice(0, 32) + .replace(/-+$/g, '') + return base.length >= 2 && !RESERVED.has(base) ? base : base ? `${base}-team` : 'team' +} + +type Row = { account_id: string; slug: string } + +/** `org:abc` / `dev:org:abc` → `abc` (the id the desktop's org list uses). */ +export function orgIdOf(accountId: string): string | null { + const match = /^(?:dev:)?org:(.+)$/.exec(accountId) + return match ? match[1]! : null +} + +export async function slugForAccount(db: D1Database, accountId: string): Promise { + const row = await db.prepare('SELECT slug FROM org_slugs WHERE account_id = ?').bind(accountId).first<{ slug: string }>() + return row?.slug ?? null +} + +export async function accountForSlug(db: D1Database, slug: string): Promise { + if (!isValidSlug(slug)) { + return null + } + const row = await db.prepare('SELECT account_id FROM org_slugs WHERE slug = ?').bind(slug).first() + return row?.account_id ?? null +} + +const NameQuery = z.string().trim().min(1).max(120) + +export async function getOrgSlug(db: D1Database, caller: SandboxCaller, url: URL, now: number) { + const orgId = caller.orgId ? orgIdOf(caller.accountId) : null + if (!orgId) { + return { slug: null, orgId: null } + } + const existing = await slugForAccount(db, caller.accountId) + if (existing) { + return { slug: existing, orgId } + } + const name = NameQuery.safeParse(url.searchParams.get('name') ?? '') + if (!name.success) { + // Nothing to name it from yet; the next client that knows the org's name will. + return { slug: null, orgId } + } + const base = slugify(name.data) + for (let attempt = 0; attempt < 20; attempt += 1) { + const candidate = attempt === 0 ? base : `${base.slice(0, 32)}-${attempt + 1}` + const result = await db + .prepare('INSERT OR IGNORE INTO org_slugs (account_id, slug, created_at, created_by, updated_at) VALUES (?, ?, ?, ?, ?)') + .bind(caller.accountId, candidate, now, caller.userId, now) + .run() + if (result.meta.changes === 1) { + return { slug: candidate, orgId } + } + // Either another org holds this slug, or a teammate just named ours (then use theirs). + const raced = await slugForAccount(db, caller.accountId) + if (raced) { + return { slug: raced, orgId } + } + } + throw new WorkspaceError('conflict', 'slug_exhausted') +} + +const PutSchema = z.object({ slug: z.string().min(1).max(40) }).strict() + +export async function putOrgSlug(db: D1Database, caller: SandboxCaller, body: unknown, now: number) { + const orgId = caller.orgId ? orgIdOf(caller.accountId) : null + if (!orgId) { + throw new WorkspaceError('invalid_request', 'personal_account') + } + if (!isOrgAdmin(caller)) { + throw new WorkspaceError('forbidden', 'admin_only') + } + const parsed = PutSchema.safeParse(body) + if (!parsed.success || !isValidSlug(parsed.data.slug)) { + throw new WorkspaceError('invalid_request', 'invalid_slug') + } + const slug = parsed.data.slug + const holder = await accountForSlug(db, slug) + if (holder && holder !== caller.accountId) { + throw new WorkspaceError('conflict', 'slug_taken') + } + await db + .prepare( + `INSERT INTO org_slugs (account_id, slug, created_at, created_by, updated_at) VALUES (?, ?, ?, ?, ?) + ON CONFLICT (account_id) DO UPDATE SET slug = excluded.slug, updated_at = excluded.updated_at` + ) + .bind(caller.accountId, slug, now, caller.userId, now) + .run() + .catch((error: unknown) => { + // The UNIQUE index lost a race with another org claiming the same slug. + if (String(error).includes('UNIQUE')) { + throw new WorkspaceError('conflict', 'slug_taken') + } + throw error + }) + return { slug, orgId } +} diff --git a/cloud/apps/sandbox-control/src/store.ts b/cloud/apps/sandbox-control/src/store.ts index 14ec858457b..64a5c48b88a 100644 --- a/cloud/apps/sandbox-control/src/store.ts +++ b/cloud/apps/sandbox-control/src/store.ts @@ -71,6 +71,8 @@ export type SandboxRow = { last_activity_at: number | null last_activity_by: string | null token_usd_micros: number | null + /** 0051: this workspace's number in its account (shown as W-123); null only on rows from before it. */ + number?: number | null } export type WorkspaceVisibility = 'private' | 'team' @@ -118,18 +120,28 @@ export async function insertSandbox( Partial>, now: number ): Promise { - await db - .prepare( - `INSERT INTO sandboxes (id, account_id, user_id, workspace_id, provider, provider_name, status, - machine_size, region, generation, created_at, updated_at, repo_url, environment_id, environment_build_id, - source_snapshot_id, created_by, name, repo_branch, visibility, section, last_activity_at, last_activity_by) - VALUES (?, ?, ?, ?, ?, ?, 'creating', ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` - ) - .bind(row.id, row.account_id, row.user_id, row.workspace_id, row.provider, row.provider_name, - row.machine_size, row.region, now, now, row.repo_url, row.environment_id ?? null, - row.environment_build_id ?? null, row.source_snapshot_id ?? null, row.user_id, row.name ?? null, - row.repo_branch ?? null, row.visibility ?? 'private', row.section ?? null, now, row.user_id) - .run() + // One transaction: bump the account's counter, then take its value as this row's number (W-123). + // A failed insert rolls the bump back; a destroyed row keeps its number, so none is ever reused. + await db.batch([ + db + .prepare( + `INSERT INTO org_workspace_counters (account_id, last_number) VALUES (?, 1) + ON CONFLICT (account_id) DO UPDATE SET last_number = last_number + 1` + ) + .bind(row.account_id), + db + .prepare( + `INSERT INTO sandboxes (id, account_id, user_id, workspace_id, provider, provider_name, status, + machine_size, region, generation, created_at, updated_at, repo_url, environment_id, environment_build_id, + source_snapshot_id, created_by, name, repo_branch, visibility, section, last_activity_at, last_activity_by, number) + VALUES (?, ?, ?, ?, ?, ?, 'creating', ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, + (SELECT last_number FROM org_workspace_counters WHERE account_id = ?))` + ) + .bind(row.id, row.account_id, row.user_id, row.workspace_id, row.provider, row.provider_name, + row.machine_size, row.region, now, now, row.repo_url, row.environment_id ?? null, + row.environment_build_id ?? null, row.source_snapshot_id ?? null, row.user_id, row.name ?? null, + row.repo_branch ?? null, row.visibility ?? 'private', row.section ?? null, now, row.user_id, row.account_id) + ]) const inserted = await getSandbox(db, row.id) if (!inserted) { throw new Error('sandbox insert lost') diff --git a/cloud/apps/sandbox-control/src/workspace-prefs.ts b/cloud/apps/sandbox-control/src/workspace-prefs.ts new file mode 100644 index 00000000000..49fca99c3d0 --- /dev/null +++ b/cloud/apps/sandbox-control/src/workspace-prefs.ts @@ -0,0 +1,86 @@ +// A member's own sidebar arrangement of cloud workspaces, stored on the account so every device +// (desktops and the phone) shows the same pins, order and sections. +// GET /v1/team/prefs -> {document, revision, updatedAt} +// PUT /v1/team/prefs {document, revision} `revision` is the one the client edited (compare-and-set: +// a stale write gets 409 and the client re-applies its edit) +// Per member, per account: switching teams switches arrangements. Ids that no longer exist are +// harmless (clients skip them) and are dropped the next time that client writes. +import { z } from 'zod' +import type { SandboxCaller } from './auth' +import { WorkspaceError } from './workspaces' + +const SandboxId = z.string().regex(/^sbx_[0-9a-f]{24}$/) +const SectionName = z.string().trim().min(1).max(64).regex(/^[^\u0000-\u001f]+$/) + +const unique = (list: readonly string[]) => new Set(list).size === list.length + +export const WorkspacePrefsDocumentSchema = z + .object({ + /** Pinned workspaces, top to bottom. */ + pinned: z.array(SandboxId).max(200).refine(unique, 'duplicate id'), + /** Manual order of the rest (drag to reorder); workspaces not listed follow, newest first. */ + order: z.array(SandboxId).max(500).refine(unique, 'duplicate id'), + /** Section order, including sections that are empty right now. */ + sections: z.array(SectionName).max(50).refine(unique, 'duplicate section'), + /** Sections this member keeps collapsed. */ + collapsed: z.array(SectionName).max(50).refine(unique, 'duplicate section') + }) + .strict() + .refine((doc) => !doc.pinned.some((id) => doc.order.includes(id)), 'pinned ids stay out of order') + +export type WorkspacePrefsDocument = z.infer + +const PutSchema = z + .object({ + document: WorkspacePrefsDocumentSchema, + revision: z.number().int().min(0), + /** Which device wrote it (a label for debugging sync, never trusted for access). */ + deviceId: z.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/).optional() + }) + .strict() + +export const EMPTY_PREFS: WorkspacePrefsDocument = { pinned: [], order: [], sections: [], collapsed: [] } + +type Row = { document: string; revision: number; updated_at: number } + +export async function getWorkspacePrefs(db: D1Database, caller: SandboxCaller) { + const row = await db + .prepare('SELECT document, revision, updated_at FROM workspace_prefs WHERE account_id = ? AND user_id = ?') + .bind(caller.accountId, caller.userId) + .first() + if (!row) { + return { document: EMPTY_PREFS, revision: 0, updatedAt: null } + } + // A document from a newer schema parses leniently: unknown keys are ignored, bad ones reset. + const parsed = WorkspacePrefsDocumentSchema.safeParse(JSON.parse(row.document)) + return { document: parsed.success ? parsed.data : EMPTY_PREFS, revision: row.revision, updatedAt: row.updated_at } +} + +export async function putWorkspacePrefs(db: D1Database, caller: SandboxCaller, body: unknown, now: number) { + const parsed = PutSchema.safeParse(body) + if (!parsed.success) { + throw new WorkspaceError('invalid_request') + } + const { document, revision, deviceId } = parsed.data + const text = JSON.stringify(document) + const result = + revision === 0 + ? await db + .prepare( + `INSERT OR IGNORE INTO workspace_prefs (account_id, user_id, document, revision, updated_at, updated_by_device) + VALUES (?, ?, ?, 1, ?, ?)` + ) + .bind(caller.accountId, caller.userId, text, now, deviceId ?? null) + .run() + : await db + .prepare( + `UPDATE workspace_prefs SET document = ?, revision = revision + 1, updated_at = ?, updated_by_device = ? + WHERE account_id = ? AND user_id = ? AND revision = ?` + ) + .bind(text, now, deviceId ?? null, caller.accountId, caller.userId, revision) + .run() + if (result.meta.changes !== 1) { + throw new WorkspaceError('conflict', 'stale_revision') + } + return getWorkspacePrefs(db, caller) +} diff --git a/cloud/apps/sandbox-control/src/workspaces.ts b/cloud/apps/sandbox-control/src/workspaces.ts index f29d0c52e5c..880544bc536 100644 --- a/cloud/apps/sandbox-control/src/workspaces.ts +++ b/cloud/apps/sandbox-control/src/workspaces.ts @@ -4,7 +4,7 @@ // GET /v1/team/workspaces/:id // PATCH /v1/team/workspaces/:id {title?, branch?, visibility?, section?, archived?, ownerUserId?, tokenUsdMicros?} // POST /v1/team/workspaces/:id/presence {clientId, state: viewing|typing|left, chatId?} -// GET /v1/team/links/resolve?w=&c= +// GET /v1/team/links/resolve?w=&c= or ?org=&n=&c= // Access rule: a workspace is visible to its owner, and to every member of the owning org when // visibility is `team`. Org owners/admins additionally see private rows' metadata (scope=all) so a // departed member's workspaces can be reassigned or archived — metadata only, never access. @@ -15,6 +15,7 @@ import { getSandbox, touchActivity, updateRegistry, type SandboxRow } from './st import { memberNamesFor } from './member-names' import { readSnapshotTimes } from './read-snapshots' import { sandboxView } from './wire' +import { accountForSlug, orgIdOf, slugForAccount } from './org-slugs' import { ORCA_CLOUD_OVERAGE_CENTS_PER_HOUR } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire' export const PRESENCE_TTL_MS = 45_000 @@ -170,11 +171,12 @@ function repoView(row: SandboxRow) { export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows: readonly SandboxRow[], now: number) { const ids = rows.map((r) => r.id) - const [presence, compute, granted, readAt] = await Promise.all([ + const [presence, compute, granted, readAt, slug] = await Promise.all([ presenceFor(db, ids, now), computeMsFor(db, ids), activeGrantUsers(db, ids, caller.userId), - readSnapshotTimes(db, ids) + readSnapshotTimes(db, ids), + rows.length > 0 ? slugForAccount(db, caller.accountId) : Promise.resolve(null) ]) const referenced = (row: SandboxRow, live: readonly PresenceRow[]) => [row.user_id, row.created_by, row.last_activity_by, ...live.map((p) => p.user_id)].filter( @@ -196,6 +198,10 @@ export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows return { ...sandboxView(row), title: row.name, + // W-123 in its account; null only for a row that predates numbering and was never backfilled. + number: row.number ?? null, + // The link to copy: org slug + number when both exist, else the sandbox id form. + link: workspaceLink(row, slug), repo: repoView(row), visibility: row.visibility, section: row.section, @@ -368,27 +374,56 @@ export async function reportPresence( return { presence: view!.presence } } -const LinkQuery = z.object({ - w: z.string().regex(/^sbx_[0-9a-f]{24}$/), - c: z.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/).optional() -}) +const ChatParam = z.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/).optional() +const LinkQuery = z.union([ + z.object({ w: z.string().regex(/^sbx_[0-9a-f]{24}$/), c: ChatParam }), + z.object({ org: z.string().min(1).max(40), n: z.coerce.number().int().min(1).max(1e9), c: ChatParam }) +]) -/** orca://cloud/w/[/c/] → the workspace if the caller can see it; otherwise not_found. */ +/** A slug link that names a different org than the caller's current one. */ +export class LinkOtherOrgError extends WorkspaceError { + constructor(readonly orgId: string | null) { + super('not_found', 'other_org') + } +} + +/** + * orca://cloud/w/[/c/] or orca://cloud//W-[/c/] → the workspace if the caller + * can see it; otherwise not_found. A slug link for another org answers not_found with reason + * `other_org` and that org's id, so a client that belongs to it can offer to switch teams. + */ export async function resolveLink(db: D1Database, caller: SandboxCaller, url: URL, now: number) { const query = LinkQuery.safeParse(Object.fromEntries(url.searchParams)) if (!query.success) { throw new WorkspaceError('invalid_request') } - const row = await getSandbox(db, query.data.w) + const q = query.data + let row: SandboxRow | null + if ('w' in q) { + row = await getSandbox(db, q.w) + } else { + const accountId = await accountForSlug(db, q.org) + if (!accountId) { + throw new WorkspaceError('not_found') + } + if (accountId !== caller.accountId) { + throw new LinkOtherOrgError(orgIdOf(accountId)) + } + row = await db + .prepare('SELECT * FROM sandboxes WHERE account_id = ? AND number = ?') + .bind(accountId, q.n) + .first() + } if (!row || !canSee(caller, row)) { // Private, other org, or gone: the link reveals nothing about which. throw new WorkspaceError('not_found') } const [view] = await workspaceViews(db, caller, [row], now) - return { workspace: view, chatId: query.data.c ?? null } + return { workspace: view, chatId: q.c ?? null } } /** Canonical deep link for a workspace (and optionally a chat in it). */ -export function workspaceLink(id: string, chatId?: string): string { - return `orca://cloud/w/${id}${chatId ? `/c/${encodeURIComponent(chatId)}` : ''}` +export function workspaceLink(row: Pick, slug: string | null, chatId?: string): string { + const chat = chatId ? `/c/${encodeURIComponent(chatId)}` : '' + return slug && row.number ? `orca://cloud/${slug}/W-${row.number}${chat}` : `orca://cloud/w/${row.id}${chat}` } diff --git a/cloud/apps/sandbox-control/test/workspace-numbers-prefs.test.ts b/cloud/apps/sandbox-control/test/workspace-numbers-prefs.test.ts new file mode 100644 index 00000000000..270c1d2be83 --- /dev/null +++ b/cloud/apps/sandbox-control/test/workspace-numbers-prefs.test.ts @@ -0,0 +1,175 @@ +import { readFileSync, readdirSync } from 'node:fs' +import { DatabaseSync } from 'node:sqlite' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' +import { isValidSlug, slugify } from '../src/org-slugs' +import { createHarness } from './harness' + +type Role = 'owner' | 'admin' | 'member' +type Who = { sub: string; org?: string; role: Role } + +async function setup() { + const h = await createHarness() + const req = async (who: Who, method: string, path: string, body?: unknown) => + h.call(method, path, { bearer: await h.token(who.sub, who.org, 'sandbox', who.org ? { org_role: who.role } : {}), body }) + let n = 0 + const create = async (who: Who, extra: Record = {}) => { + n += 1 + const res = await req(who, 'POST', '/v1/sandboxes', { workspaceId: `ws-${n}`, machineSize: 'standard', ...extra }) + expect(res.status).toBe(200) + return res.body.sandbox.id as string + } + const alice: Who = { sub: 'alice', org: 'acme', role: 'member' } + const bob: Who = { sub: 'bob', org: 'acme', role: 'member' } + const admin: Who = { sub: 'carol', org: 'acme', role: 'admin' } + const eve: Who = { sub: 'eve', org: 'other', role: 'owner' } + const solo: Who = { sub: 'sam', role: 'member' } + return { h, req, create, alice, bob, admin, eve, solo } +} + +describe('workspace numbers (W-123)', () => { + it('numbers workspaces per account and never reuses a number', async () => { + const t = await setup() + const a1 = await t.create(t.alice) + const a2 = await t.create(t.bob, { visibility: 'team' }) + const e1 = await t.create(t.eve) + const view = async (who: Who, id: string) => (await t.req(who, 'GET', `/v1/team/workspaces/${id}`)).body.workspace + expect((await view(t.alice, a1)).number).toBe(1) + expect((await view(t.bob, a2)).number).toBe(2) + expect((await view(t.eve, e1)).number).toBe(1) + expect((await t.req(t.alice, 'DELETE', `/v1/sandboxes/${a1}`)).status).toBe(200) + const a3 = await t.create(t.alice) + expect((await view(t.alice, a3)).number).toBe(3) + }) + + it('backfills existing rows by creation order and seeds the counter', () => { + const raw = new DatabaseSync(':memory:') + const dir = fileURLToPath(new URL('../migrations/', import.meta.url).href) + const files = readdirSync(dir).filter((f) => f.endsWith('.sql')).sort() + const at = files.indexOf('0051_workspace_numbers_prefs.sql') + for (const file of files.slice(0, at)) { + raw.exec(readFileSync(`${dir}${file}`, 'utf8')) + } + const insert = raw.prepare( + `INSERT INTO sandboxes (id, account_id, user_id, workspace_id, provider, provider_name, status, machine_size, region, + generation, created_at, updated_at) VALUES (?, ?, 'u', ?, 'vercel', ?, 'destroyed', 'standard', 'iad1', 0, ?, ?)` + ) + insert.run('sbx_b', 'org:a', 'w2', 'p2', 20, 20) + insert.run('sbx_a', 'org:a', 'w1', 'p1', 10, 10) + insert.run('sbx_c', 'org:a', 'w3', 'p3', 20, 20) + insert.run('sbx_z', 'org:b', 'w1', 'pz', 5, 5) + for (const file of files.slice(at)) { + raw.exec(readFileSync(`${dir}${file}`, 'utf8')) + } + expect(raw.prepare('SELECT id, number FROM sandboxes ORDER BY id').all()).toEqual([ + { id: 'sbx_a', number: 1 }, + { id: 'sbx_b', number: 2 }, + { id: 'sbx_c', number: 3 }, + { id: 'sbx_z', number: 1 } + ]) + expect(raw.prepare('SELECT * FROM org_workspace_counters ORDER BY account_id').all()).toEqual([ + { account_id: 'org:a', last_number: 3 }, + { account_id: 'org:b', last_number: 1 } + ]) + }) +}) + +describe('org slugs', () => { + it('slugifies names and refuses reserved or malformed slugs', () => { + expect(slugify('Acme Labs, Inc.')).toBe('acme-labs-inc') + expect(slugify('Ünïcode Crew')).toBe('unicode-crew') + expect(slugify('!!!')).toBe('team') + expect(slugify('w')).toBe('w-team') + expect(isValidSlug('acme')).toBe(true) + expect(isValidSlug('w')).toBe(false) + expect(isValidSlug('-acme')).toBe(false) + expect(isValidSlug('a--b')).toBe(false) + expect(isValidSlug('Acme')).toBe(false) + }) + + it('names an org once from the first name it hears, uniquely across orgs', async () => { + const t = await setup() + expect((await t.req(t.alice, 'GET', '/v1/team/org')).body).toEqual({ slug: null, orgId: 'acme' }) + expect((await t.req(t.alice, 'GET', '/v1/team/org?name=Acme%20Labs')).body).toEqual({ slug: 'acme-labs', orgId: 'acme' }) + // A teammate whose client shows another name still gets the org's slug. + expect((await t.req(t.bob, 'GET', '/v1/team/org?name=Whatever')).body.slug).toBe('acme-labs') + expect((await t.req(t.eve, 'GET', '/v1/team/org?name=Acme%20Labs')).body.slug).toBe('acme-labs-2') + expect((await t.req(t.solo, 'GET', '/v1/team/org?name=Sam')).body).toEqual({ slug: null, orgId: null }) + }) + + it('lets only admins rename, and not onto another org', async () => { + const t = await setup() + await t.req(t.alice, 'GET', '/v1/team/org?name=Acme') + await t.req(t.eve, 'GET', '/v1/team/org?name=Other') + expect((await t.req(t.alice, 'PUT', '/v1/team/org', { slug: 'acme-co' })).status).toBe(403) + expect((await t.req(t.admin, 'PUT', '/v1/team/org', { slug: 'other' })).status).toBe(409) + expect((await t.req(t.admin, 'PUT', '/v1/team/org', { slug: 'w' })).status).toBe(400) + expect((await t.req(t.admin, 'PUT', '/v1/team/org', { slug: 'acme-co' })).body).toEqual({ slug: 'acme-co', orgId: 'acme' }) + expect((await t.req(t.bob, 'GET', '/v1/team/org')).body.slug).toBe('acme-co') + }) +}) + +describe('slug links', () => { + it('copies org slug links and resolves them only for those who can see the workspace', async () => { + const t = await setup() + const id = await t.create(t.alice) + const before = (await t.req(t.alice, 'GET', `/v1/team/workspaces/${id}`)).body.workspace + // No slug yet: the id form still works. + expect(before.link).toBe(`orca://cloud/w/${id}`) + await t.req(t.alice, 'GET', '/v1/team/org?name=Acme') + const after = (await t.req(t.alice, 'GET', '/v1/team/workspaces?scope=mine')).body.workspaces[0] + expect(after.link).toBe('orca://cloud/acme/W-1') + + const resolved = await t.req(t.alice, 'GET', '/v1/team/links/resolve?org=acme&n=1&c=s:abc') + expect(resolved.status).toBe(200) + expect(resolved.body).toMatchObject({ workspace: { id, number: 1 }, chatId: 's:abc' }) + // Private to Alice: Bob sees nothing until she shares it. + expect((await t.req(t.bob, 'GET', '/v1/team/links/resolve?org=acme&n=1')).status).toBe(404) + await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${id}`, { visibility: 'team' }) + expect((await t.req(t.bob, 'GET', '/v1/team/links/resolve?org=acme&n=1')).body.workspace.id).toBe(id) + expect((await t.req(t.bob, 'GET', '/v1/team/links/resolve?org=acme&n=2')).status).toBe(404) + // Another org: not found, but says which org so a member of both can switch. + const other = await t.req(t.eve, 'GET', '/v1/team/links/resolve?org=acme&n=1') + expect(other.status).toBe(404) + expect(other.body).toEqual({ error: 'not_found', reason: 'other_org', orgId: 'acme' }) + expect((await t.req(t.eve, 'GET', '/v1/team/links/resolve?org=nope&n=1')).body).toEqual({ error: 'not_found' }) + expect((await t.req(t.alice, 'GET', '/v1/team/links/resolve?org=acme&n=0')).status).toBe(400) + }) +}) + +describe('workspace prefs (synced pins and order)', () => { + const A = `sbx_${'a'.repeat(24)}` + const B = `sbx_${'b'.repeat(24)}` + + it('stores one document per member and account with compare-and-set', async () => { + const t = await setup() + expect((await t.req(t.alice, 'GET', '/v1/team/prefs')).body).toEqual({ + document: { pinned: [], order: [], sections: [], collapsed: [] }, + revision: 0, + updatedAt: null + }) + const doc = { pinned: [A], order: [B], sections: ['Auth', 'Billing'], collapsed: ['Billing'] } + const first = await t.req(t.alice, 'PUT', '/v1/team/prefs', { document: doc, revision: 0, deviceId: 'desk-1' }) + expect(first.status).toBe(200) + expect(first.body).toMatchObject({ document: doc, revision: 1 }) + // A second device that still holds revision 0 must re-read before writing. + const stale = await t.req(t.alice, 'PUT', '/v1/team/prefs', { document: { ...doc, pinned: [] }, revision: 0 }) + expect(stale.status).toBe(409) + const second = await t.req(t.alice, 'PUT', '/v1/team/prefs', { document: { ...doc, pinned: [B, A], order: [] }, revision: 1 }) + expect(second.body.revision).toBe(2) + expect((await t.req(t.alice, 'GET', '/v1/team/prefs')).body.document.pinned).toEqual([B, A]) + // Teammates and other accounts have their own. + expect((await t.req(t.bob, 'GET', '/v1/team/prefs')).body.revision).toBe(0) + expect((await t.req({ ...t.alice, org: 'other' }, 'GET', '/v1/team/prefs')).body.revision).toBe(0) + expect((await t.req(t.solo, 'PUT', '/v1/team/prefs', { document: doc, revision: 0 })).status).toBe(200) + }) + + it('rejects malformed documents', async () => { + const t = await setup() + const put = (document: unknown) => t.req(t.alice, 'PUT', '/v1/team/prefs', { document, revision: 0 }) + expect((await put({ pinned: [A], order: [A], sections: [], collapsed: [] })).status).toBe(400) + expect((await put({ pinned: [A, A], order: [], sections: [], collapsed: [] })).status).toBe(400) + expect((await put({ pinned: ['nope'], order: [], sections: [], collapsed: [] })).status).toBe(400) + expect((await put({ pinned: [], order: [], sections: ['x'], collapsed: [], extra: 1 })).status).toBe(400) + }) +}) From 1777d5af1d24585bdb65aa54be6ea952bc762e6e Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 19:23:18 -0800 Subject: [PATCH 033/149] feat(cloud): Remote desktop as a first-class tab in Orca Cloud workspaces - + menu: Open Remote Desktop / Go to Remote Desktop (one desktop tab per workspace) - desktop tab: own toolbar (Monitor, Beta, live status, Reconnect) instead of the address bar, Monitor icon and 'Remote desktop' label in the tab strip - asleep / waking / archived / couldn't-wake cover with Wake or Unarchive - reconnects by itself after a wake, a closed forward or an app restart (main now reports each desktop page's connection: none, connecting, connected, paused + reason) --- .../remote-desktop-guest.test.ts | 93 +++++- .../hosted-sandbox/remote-desktop-guest.ts | 125 +++++--- .../remote-desktop-pause-copy.ts | 34 +++ src/preload/api/browser/browser-api.ts | 5 +- ...er-bridge-page-interaction-and-sessions.ts | 11 +- .../assemble-chrome/browser-page-pane.tsx | 69 +++-- .../CloudDesktopTabChrome.tsx | 286 ++++++++++++++++++ .../CloudDesktopTabSurface.tsx | 48 +++ .../CloudRemoteDesktopToast.tsx | 6 +- .../cmd-j/remote-desktop-quick-action.ts | 2 +- .../src/components/tab-bar/BrowserTab.tsx | 18 +- .../tab-bar/TabBarCreateEntryRow.tsx | 3 + .../tab-bar/tab-bar-static-create-menu.tsx | 21 +- .../tab-bar/tab-create-menu-options.test.ts | 39 +++ .../tab-bar/tab-create-menu-options.ts | 20 ++ .../use-tab-bar-create-menu-controller.ts | 9 +- src/renderer/src/i18n/locales/en.json | 16 +- .../open-cloud-remote-desktop.tsx | 9 +- .../remote-desktop-page-state.ts | 56 ++++ .../remote-desktop-tab.ts | 67 ++++ .../use-cloud-desktop-connection.test.ts | 86 ++++++ .../use-cloud-desktop-connection.ts | 196 ++++++++++++ .../cloud-remote-desktop.test.ts | 31 ++ .../hosted-sandbox/cloud-remote-desktop.ts | 61 +++- 24 files changed, 1211 insertions(+), 100 deletions(-) create mode 100644 src/main/hosted-sandbox/remote-desktop-pause-copy.ts create mode 100644 src/renderer/src/components/cloud-remote-desktop/CloudDesktopTabChrome.tsx create mode 100644 src/renderer/src/components/cloud-remote-desktop/CloudDesktopTabSurface.tsx create mode 100644 src/renderer/src/components/tab-bar/tab-create-menu-options.test.ts create mode 100644 src/renderer/src/lib/cloud-remote-desktop/remote-desktop-page-state.ts create mode 100644 src/renderer/src/lib/cloud-remote-desktop/remote-desktop-tab.ts create mode 100644 src/renderer/src/lib/cloud-remote-desktop/use-cloud-desktop-connection.test.ts create mode 100644 src/renderer/src/lib/cloud-remote-desktop/use-cloud-desktop-connection.ts create mode 100644 src/shared/hosted-sandbox/cloud-remote-desktop.test.ts diff --git a/src/main/hosted-sandbox/remote-desktop-guest.test.ts b/src/main/hosted-sandbox/remote-desktop-guest.test.ts index c336278d881..e7ca3436614 100644 --- a/src/main/hosted-sandbox/remote-desktop-guest.test.ts +++ b/src/main/hosted-sandbox/remote-desktop-guest.test.ts @@ -31,6 +31,8 @@ class FakeGuest extends EventEmitter { private waiters: ((answer: string) => void)[] = [] connectAnswer = 'connecting' pasteAnswer = true + /** What window.orcaDesktop.state() answers (main watches a handed-over ticket connect). */ + pageState: unknown = true getURL(): string { return this.url @@ -55,6 +57,9 @@ class FakeGuest extends EventEmitter { if (code.includes('orcaDesktop.paste(')) { return this.pasteAnswer } + if (code.includes('orcaDesktop.state()')) { + return this.pageState + } return true } /** The page asks for a ticket ('ticket') or reports a failed attempt ('retry'). */ @@ -236,7 +241,7 @@ describe('remote desktop page driver', () => { guest.emit('focus') expect(events.at(-1)).toEqual({ kind: 'state', - state: { browserPageId: 'page-1', desktop: true, captured: true } + state: { browserPageId: 'page-1', desktop: true, captured: true, connection: 'connecting' } }) guest.key({ type: 'keyDown', key: 'Control', control: true }) guest.key({ type: 'keyDown', key: 'Meta', control: true, meta: true }) @@ -270,7 +275,91 @@ describe('remote desktop page driver', () => { expect(isRemoteDesktopGuest(asWebContents(guest))).toBe(false) expect(events.at(-1)).toEqual({ kind: 'state', - state: { browserPageId: 'page-1', desktop: false, captured: false } + state: { browserPageId: 'page-1', desktop: false, captured: false, connection: 'none' } }) }) + + it('reports connected once the page says its session is up', async () => { + const { guest, events } = setup() + guest.pageState = 'connected' + await flush() + guest.ask('ticket') + await flush() + expect(events.at(-1)).toEqual({ + kind: 'state', + state: { browserPageId: 'page-1', desktop: true, captured: false, connection: 'connected' } + }) + }) + + it('reports a pause with its reason, so the tab can show the asleep state', async () => { + const { guest, events, failMint } = setup() + await flush() + guest.ask('ticket') + await flush() + failMint('asleep') + guest.ask('ticket') + await flush() + expect(events.at(-1)).toEqual({ + kind: 'state', + state: { + browserPageId: 'page-1', + desktop: true, + captured: false, + connection: 'paused', + reason: 'asleep' + } + }) + }) + + it('reports no session for a desktop page this computer has no forward for (restored tab)', async () => { + resetRemoteDesktopSessionsForTest() + const guest = new FakeGuest() + const events: unknown[] = [] + const stop = setupRemoteDesktopGuest({ + browserPageId: 'page-3', + guest: asWebContents(guest), + notify: (event) => events.push(event), + sleep: async () => {} + }) + await flush() + expect(guest.calls).toEqual([]) + expect(events).toEqual([ + { + kind: 'state', + state: { browserPageId: 'page-3', desktop: false, captured: false, connection: 'none' } + } + ]) + stop() + }) + + it('drops to no session when the forward closed under a page that needs a new ticket', async () => { + resetRemoteDesktopSessionsForTest() + let live = true + registerRemoteDesktopSession( + { + environmentId: 'env-1', + localPort: 6081, + path: 'vnc.html', + mint: async () => ({ ok: true, ticket: ticket(9), expiresAt: FAR_FUTURE }), + isLive: () => live + }, + { ticket: ticket(1), expiresAt: FAR_FUTURE } + ) + const guest = new FakeGuest() + const events: { kind: string; state?: { connection: string } }[] = [] + setupRemoteDesktopGuest({ + browserPageId: 'page-4', + guest: asWebContents(guest), + notify: (event) => events.push(event), + sleep: async () => {} + }) + await flush() + guest.ask('ticket') + await flush() + live = false // the sandbox slept: its forward closed + guest.ask('ticket') + await flush() + expect(events.at(-1)?.state?.connection).toBe('none') + expect(isRemoteDesktopGuest(asWebContents(guest))).toBe(false) + }) }) diff --git a/src/main/hosted-sandbox/remote-desktop-guest.ts b/src/main/hosted-sandbox/remote-desktop-guest.ts index 2e07357d636..2f9b400e345 100644 --- a/src/main/hosted-sandbox/remote-desktop-guest.ts +++ b/src/main/hosted-sandbox/remote-desktop-guest.ts @@ -9,12 +9,18 @@ // - pastes this computer's clipboard into the sandbox only on a paste key in the desktop. import { clipboard } from 'electron' import { translateMain } from '../i18n/main-i18n' +import { remoteDesktopPauseMessage as pauseMessage } from './remote-desktop-pause-copy' import { isAgentInjectingInput } from '../browser/cdp/input/agent-input-injection' +import { + isCloudRemoteDesktopUrl, + type RemoteDesktopConnection, + type RemoteDesktopPageState, + type RemoteDesktopPauseReason +} from '../../shared/hosted-sandbox/cloud-remote-desktop' import { onRemoteDesktopSessionRefreshed, remoteDesktopSessionForUrl, takeRemoteDesktopTicket, - type RemoteDesktopMintFailure, type RemoteDesktopSession } from './remote-desktop-sessions' import { @@ -31,14 +37,11 @@ const MIN_MINT_INTERVAL_MS = 1_000 const MAX_MINTS_PER_MINUTE = 10 const MAX_PASTE_CHARS = 1 << 20 const PAGE_READY_TIMEOUT_MS = 10_000 +/** How long, and how often, main watches a handed-over ticket become a connected session. */ +const CONNECT_WATCH_MS = 20_000 +const CONNECT_POLL_MS = 150 -export type RemoteDesktopGuestState = { - browserPageId: string - /** The page is a remote desktop with Orca's page glue. */ - desktop: boolean - /** It has keyboard focus: Orca's shortcuts are off until the release chord. */ - captured: boolean -} +export type RemoteDesktopGuestState = RemoteDesktopPageState export type RemoteDesktopGuestDeps = { browserPageId: string @@ -64,37 +67,6 @@ const WAIT_FOR_REQUEST = `(async () => { return window.orcaDesktop ? window.orcaDesktop.nextTicketRequest() : 'missing' })()` -function pauseMessage(reason: RemoteDesktopMintFailure | 'failed'): string { - switch (reason) { - case 'asleep': - return translateMain( - 'components.cloudRemoteDesktop.pageAsleep', - 'This sandbox is asleep. Wake it in Orca, then reconnect.' - ) - case 'archived': - return translateMain( - 'components.cloudRemoteDesktop.pageArchived', - 'This workspace is archived. Unarchive it in Orca, then reconnect.' - ) - case 'starting': - return translateMain( - 'components.cloudRemoteDesktop.pageStarting', - 'The sandbox is starting or waking. Reconnect in a moment.' - ) - case 'signed_out': - return translateMain( - 'components.cloudRemoteDesktop.pageSignedOut', - 'You’re signed out of Orca Cloud. Sign in, then reconnect.' - ) - case 'failed': - case 'unavailable': - return translateMain( - 'components.cloudRemoteDesktop.pageDisconnected', - 'The remote desktop disconnected. Your files are safe.' - ) - } -} - export function setupRemoteDesktopGuest(deps: RemoteDesktopGuestDeps): () => void { const { guest, browserPageId, notify } = deps const platform = deps.platform ?? process.platform @@ -106,6 +78,10 @@ export function setupRemoteDesktopGuest(deps: RemoteDesktopGuestDeps): () => voi let stopRefreshListener = (): void => {} let disposed = false let published = '' + let connection: RemoteDesktopConnection = 'none' + let pauseReason: RemoteDesktopPauseReason | undefined + /** The page's URL is shaped like a desktop (with or without a session on this computer). */ + let shaped = false /** Settles every in-flight page call when the page goes away (a torn-down page may never answer). */ let cancelInFlight = (): void => {} let cancelled = new Promise((resolve) => { @@ -120,19 +96,48 @@ export function setupRemoteDesktopGuest(deps: RemoteDesktopGuestDeps): () => voi const alive = (gen: number): boolean => !disposed && gen === generation && !guest.isDestroyed() const publish = (): void => { - const state = { + const state: RemoteDesktopGuestState = { browserPageId, desktop: session !== null, - captured: session !== null && !guest.isDestroyed() && guest.isFocused() + captured: session !== null && !guest.isDestroyed() && guest.isFocused(), + connection: session || shaped ? connection : 'none', + ...(connection === 'paused' && pauseReason ? { reason: pauseReason } : {}) } // Only changes, and nothing at all for ordinary pages' focus churn. - const key = `${state.desktop}:${state.captured}` - if (key === published || (!state.desktop && published === '')) { + const key = `${state.desktop}:${state.captured}:${shaped}:${state.connection}:${state.reason ?? ''}` + if (key === published || (!state.desktop && !shaped && published === '')) { return } published = key notify({ kind: 'state', state }) } + const setConnection = ( + gen: number, + next: RemoteDesktopConnection, + reason?: RemoteDesktopPauseReason + ): void => { + if (!alive(gen)) { + return + } + connection = next + pauseReason = next === 'paused' ? reason : undefined + publish() + } + /** The page says when its session is up; main only knows it handed over a ticket. */ + const watchConnected = async (gen: number): Promise => { + const until = Date.now() + CONNECT_WATCH_MS + while (alive(gen) && connection === 'connecting' && Date.now() < until) { + const pageState = await run(gen, 'window.orcaDesktop && window.orcaDesktop.state()') + if (pageState === 'connected') { + setConnection(gen, 'connected') + return + } + if (pageState !== 'connecting' && pageState !== 'idle') { + return + } + await sleep(CONNECT_POLL_MS) + } + } const run = async (gen: number, code: string): Promise => { if (!alive(gen)) { return undefined @@ -154,6 +159,7 @@ export function setupRemoteDesktopGuest(deps: RemoteDesktopGuestDeps): () => voi if (!alive(gen) || (ask !== 'ticket' && ask !== 'retry')) { return } + setConnection(gen, 'connecting') // 'retry': the last ticket never got a session (refused, or the forward was down). failures = ask === 'retry' || refused ? failures + 1 : 0 refused = false @@ -167,6 +173,13 @@ export function setupRemoteDesktopGuest(deps: RemoteDesktopGuestDeps): () => voi await sleep(Math.max(RETRY_DELAYS_MS[failures] ?? 4_000, MIN_MINT_INTERVAL_MS - sinceLast)) // The forward may have closed meanwhile; a page now on that port gets nothing. if (!alive(gen) || remoteDesktopSessionForUrl(guest.getURL()) !== current) { + // Its forward closed (the sandbox slept, or this computer dropped it): the renderer + // reopens the desktop once the sandbox is awake. + if (alive(gen)) { + session = null + guestsWithDesktop.delete(guest) + setConnection(gen, 'none') + } return } mintTimes = mintTimes.filter((at) => Date.now() - at < 60_000) @@ -186,10 +199,14 @@ export function setupRemoteDesktopGuest(deps: RemoteDesktopGuestDeps): () => voi const started = await run(gen, `window.orcaDesktop.connect(${JSON.stringify(minted.ticket)})`) // Anything but a started attempt still counts against the budget, so this never spins. refused = started !== 'connecting' + if (!refused) { + void watchConnected(gen) + } } } - async function pause(gen: number, reason: RemoteDesktopMintFailure | 'failed'): Promise { + async function pause(gen: number, reason: RemoteDesktopPauseReason): Promise { + setConnection(gen, 'paused', reason) const label = translateMain('components.cloudRemoteDesktop.reconnect', 'Reconnect') await run( gen, @@ -203,12 +220,20 @@ export function setupRemoteDesktopGuest(deps: RemoteDesktopGuestDeps): () => voi const gen = generation stopRefreshListener() stopRefreshListener = () => {} - session = remoteDesktopSessionForUrl(guest.getURL()) + const url = guest.getURL() + session = remoteDesktopSessionForUrl(url) + shaped = isCloudRemoteDesktopUrl(url) + connection = session ? 'connecting' : 'none' + pauseReason = undefined if (session) { guestsWithDesktop.add(guest) // Reopening from the menu resumes a page that stopped retrying (asleep, then woken). stopRefreshListener = onRemoteDesktopSessionRefreshed(session.localPort, () => { - void run(gen, 'window.orcaDesktop && window.orcaDesktop.resume()') + void run(gen, 'window.orcaDesktop && window.orcaDesktop.resume()').then((resumed) => { + if (resumed === true) { + setConnection(gen, 'connecting') + } + }) }) void driveTickets(gen, session) } else { @@ -225,6 +250,9 @@ export function setupRemoteDesktopGuest(deps: RemoteDesktopGuestDeps): () => voi generation += 1 cancelPageCalls() session = null + shaped = false + connection = 'none' + pauseReason = undefined guestsWithDesktop.delete(guest) stopRefreshListener() publish() @@ -296,8 +324,11 @@ export function setupRemoteDesktopGuest(deps: RemoteDesktopGuestDeps): () => voi } catch { // The guest may already be destroyed. } - if (session) { + if (session || shaped) { session = null + shaped = false + connection = 'none' + pauseReason = undefined publish() } } diff --git a/src/main/hosted-sandbox/remote-desktop-pause-copy.ts b/src/main/hosted-sandbox/remote-desktop-pause-copy.ts new file mode 100644 index 00000000000..bd50b2619d0 --- /dev/null +++ b/src/main/hosted-sandbox/remote-desktop-pause-copy.ts @@ -0,0 +1,34 @@ +// What a remote desktop page says when main stops handing it tickets (remote-desktop-guest.ts). +import { translateMain } from '../i18n/main-i18n' +import type { RemoteDesktopPauseReason } from '../../shared/hosted-sandbox/cloud-remote-desktop' + +export function remoteDesktopPauseMessage(reason: RemoteDesktopPauseReason): string { + switch (reason) { + case 'asleep': + return translateMain( + 'components.cloudRemoteDesktop.pageAsleep', + 'This sandbox is asleep. Wake it in Orca, then reconnect.' + ) + case 'archived': + return translateMain( + 'components.cloudRemoteDesktop.pageArchived', + 'This workspace is archived. Unarchive it in Orca, then reconnect.' + ) + case 'starting': + return translateMain( + 'components.cloudRemoteDesktop.pageStarting', + 'The sandbox is starting or waking. Reconnect in a moment.' + ) + case 'signed_out': + return translateMain( + 'components.cloudRemoteDesktop.pageSignedOut', + 'You’re signed out of Orca Cloud. Sign in, then reconnect.' + ) + case 'failed': + case 'unavailable': + return translateMain( + 'components.cloudRemoteDesktop.pageDisconnected', + 'The remote desktop disconnected. Your files are safe.' + ) + } +} diff --git a/src/preload/api/browser/browser-api.ts b/src/preload/api/browser/browser-api.ts index 887ea272d3a..ed85892e5fc 100644 --- a/src/preload/api/browser/browser-api.ts +++ b/src/preload/api/browser/browser-api.ts @@ -1,3 +1,4 @@ +import type { RemoteDesktopPageState } from '../../../shared/hosted-sandbox/cloud-remote-desktop' import type { BrowserSessionCookieApi } from './browser-session-cookie-api' import type { BrowserDevToolsDockBounds } from '../../../shared/browser/devtools/browser-devtools-dock' import type { BrowserSetAnnotationViewportBridgeArgs } from '../../../shared/browser/annotations/browser-annotation-viewport-bridge' @@ -213,9 +214,7 @@ export type BrowserApi = { /** Escape pressed in a focused page; the page also receives it unless a grab pick is running. */ onGuestEscape: (callback: (args: { browserPageId: string }) => void) => () => void /** A browser page became (or stopped being) a remote desktop, or gained or lost the keyboard. */ - onRemoteDesktopState: ( - callback: (args: { browserPageId: string; desktop: boolean; captured: boolean }) => void - ) => () => void + onRemoteDesktopState: (callback: (args: RemoteDesktopPageState) => void) => () => void /** The release chord was pressed in a remote desktop: give the keyboard back to Orca. */ onRemoteDesktopRelease: (callback: (args: { browserPageId: string }) => void) => () => void sessionListProfiles: () => Promise diff --git a/src/preload/api/browser/browser-bridge-page-interaction-and-sessions.ts b/src/preload/api/browser/browser-bridge-page-interaction-and-sessions.ts index c6ce70adebb..e546b24839a 100644 --- a/src/preload/api/browser/browser-bridge-page-interaction-and-sessions.ts +++ b/src/preload/api/browser/browser-bridge-page-interaction-and-sessions.ts @@ -1,3 +1,4 @@ +import type { RemoteDesktopPageState } from '../../../shared/hosted-sandbox/cloud-remote-desktop' import type { GoogleCookieClearLocalTarget } from '../../../shared/browser/cookies/browser-google-cookie-clear' import { ipcRenderer } from 'electron' import { @@ -168,13 +169,9 @@ export const browserPageInteractionAndSessionsApi = { ipcRenderer.on('browser:guestEscape', listener) return () => ipcRenderer.removeListener('browser:guestEscape', listener) }, - onRemoteDesktopState: ( - callback: (args: { browserPageId: string; desktop: boolean; captured: boolean }) => void - ): (() => void) => { - const listener = ( - _event: Electron.IpcRendererEvent, - data: { browserPageId: string; desktop: boolean; captured: boolean } - ) => callback(data) + onRemoteDesktopState: (callback: (args: RemoteDesktopPageState) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, data: RemoteDesktopPageState) => + callback(data) ipcRenderer.on('browser:remoteDesktopState', listener) return () => ipcRenderer.removeListener('browser:remoteDesktopState', listener) }, diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-pane.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-pane.tsx index 015330ae64e..70a948cff4e 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-pane.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-pane.tsx @@ -22,6 +22,8 @@ import { getOpenableExternalUrl, toDisplayUrl } from '../describe-page/browser-p import type { BrowserOverlayViewport } from '../describe-page/browser-annotation-geometry' import type { BrowserPagePaneProps } from '../describe-page/browser-page-types' import { BrowserPageChromeHeader } from './browser-page-chrome-header' +import { CloudDesktopTabSurface } from '../../cloud-remote-desktop/CloudDesktopTabSurface' +import { isCloudRemoteDesktopUrl } from '../../../../../shared/hosted-sandbox/cloud-remote-desktop' import { BrowserPageContextMenu } from './browser-page-context-menu' import { BrowserPageViewportOverlays } from './browser-page-viewport-overlays' import { useBrowserPageAnnotationSend } from '../annotate/use-browser-page-annotation-send' @@ -329,33 +331,46 @@ export function BrowserPagePane({ webviewRef={webviewRef} onReload={() => reload.reloadWebviewOrRecoverGuest(false)} /> - setFindOpen(true)} - markupIsActive={markup.isActive} - markupStart={markup.start} - markupCancel={markup.cancel} - grabElementShortcut={grabElementShortcut} - shareableArtifactFile={shareableArtifactFile} - currentBrowserUrl={currentBrowserUrl} - externalUrl={externalUrl} - isBlankTab={isBlankTab} - resourceNotice={resourceNotice} - setResourceNotice={setResourceNotice} - /> + {isCloudRemoteDesktopUrl(browserTab.url) ? ( + // A remote desktop tab has no address bar: its own toolbar, and a cover while it can't show. + reload.reloadWebviewOrRecoverGuest(false)} + navigate={nav.navigateToUrl} + viewportContainer={pageViewport?.container ?? null} + /> + ) : ( + setFindOpen(true)} + markupIsActive={markup.isActive} + markupStart={markup.start} + markupCancel={markup.cancel} + grabElementShortcut={grabElementShortcut} + shareableArtifactFile={shareableArtifactFile} + currentBrowserUrl={currentBrowserUrl} + externalUrl={externalUrl} + isBlankTab={isBlankTab} + resourceNotice={resourceNotice} + setResourceNotice={setResourceNotice} + /> + )} {pageViewport?.container ? createPortal( + phase: CloudDesktopPhase + onReconnect: () => void +}): React.JSX.Element { + const t = useTranslate() + const busy = phase.kind === 'reconnecting' || phase.kind === 'waking' + const sandboxDown = + phase.kind === 'asleep' || phase.kind === 'archived' || phase.kind === 'wakeFailed' + return ( +
    +
    + + + {t('components.cloudRemoteDesktop.tabTitle', 'Remote desktop')} + + {t('components.cloudRemoteDesktop.beta', 'Beta')} + + + {phaseLabel(t, phase)} + + + {phase.kind === 'connected' ? ( + + {t( + 'components.cloudRemoteDesktop.tab.releaseHint', + '{{chord}} returns keys to Orca', + { + chord: remoteDesktopReleaseChordLabel() + } + )} + + ) : null} + + +
    +
    + ) +} + +function CoverCard({ + busy, + title, + detail, + action +}: { + busy?: boolean + title: string + detail?: string + action?: React.ReactNode +}): React.JSX.Element { + return ( +
    + + {busy ? ( + + ) : ( + + )} + +
    +

    {title}

    + {detail ?

    {detail}

    : null} +
    + {action} +
    + ) +} + +/** + * Over the desktop page whenever there is no live desktop to show: the sandbox is asleep (Wake), + * waking (it reconnects by itself), archived, or reopening it failed. Connected, connecting and + * paused pages show the page itself (noVNC paints its own connect and pause states). + */ +export function CloudDesktopTabCover({ + worktreeId, + phase, + onReconnect +}: { + worktreeId: string + phase: CloudDesktopPhase + onReconnect: () => void +}): React.JSX.Element | null { + const t = useTranslate() + let body: React.ReactNode + switch (phase.kind) { + case 'connected': + case 'connecting': + case 'paused': + return null + case 'reconnecting': + body = ( + + ) + break + case 'waking': + body = ( + + ) + break + case 'asleep': + case 'wakeFailed': { + const failed = phase.kind === 'wakeFailed' + body = ( + void wakeCloudWorkspace(worktreeId)} + > + + {failed + ? t('components.cloudRemoteDesktop.retry', 'Try again') + : t('orcaCloudWorkspace.wake', 'Wake')} + + } + /> + ) + break + } + case 'archived': + body = ( + void runUnarchiveCloudWorkspace(worktreeId)} + > + {t('components.cloudRemoteDesktop.unarchive', 'Unarchive')} + + } + /> + ) + break + case 'failed': { + const copy = failureCopy(t, phase.code) + const signIn = copy.action === 'sign_in' + body = ( +
    + + signIn ? void useAppStore.getState().connectCurrentOrcaProfile() : onReconnect() + } + > + {signIn + ? actionLabel(t, 'sign_in') + : t('components.cloudRemoteDesktop.reconnect', 'Reconnect')} + + } + /> +
    + ) + break + } + } + return ( +
    + {body} +
    + ) +} diff --git a/src/renderer/src/components/cloud-remote-desktop/CloudDesktopTabSurface.tsx b/src/renderer/src/components/cloud-remote-desktop/CloudDesktopTabSurface.tsx new file mode 100644 index 00000000000..9333e6b31c5 --- /dev/null +++ b/src/renderer/src/components/cloud-remote-desktop/CloudDesktopTabSurface.tsx @@ -0,0 +1,48 @@ +import type React from 'react' +import type { RefObject } from 'react' +import { createPortal } from 'react-dom' +import { useCloudDesktopConnection } from '@/lib/cloud-remote-desktop/use-cloud-desktop-connection' +import { CloudDesktopTabCover, CloudDesktopTabToolbar } from './CloudDesktopTabChrome' + +/** A remote desktop tab's chrome: a toolbar in place of the address bar, and a cover over the page. */ +export function CloudDesktopTabSurface({ + chromeHeaderRef, + worktreeId, + browserPageId, + url, + reload, + navigate, + viewportContainer +}: { + chromeHeaderRef: RefObject + worktreeId: string + browserPageId: string + url: string + reload: () => void + navigate: (url: string) => void + viewportContainer: HTMLElement | null +}): React.JSX.Element { + const { phase, reconnect } = useCloudDesktopConnection({ + enabled: true, + worktreeId, + browserPageId, + url, + reload, + navigate + }) + return ( + <> + + {viewportContainer + ? createPortal( + , + viewportContainer + ) + : null} + + ) +} diff --git a/src/renderer/src/components/cloud-remote-desktop/CloudRemoteDesktopToast.tsx b/src/renderer/src/components/cloud-remote-desktop/CloudRemoteDesktopToast.tsx index 80d1f85f836..3477fad70f5 100644 --- a/src/renderer/src/components/cloud-remote-desktop/CloudRemoteDesktopToast.tsx +++ b/src/renderer/src/components/cloud-remote-desktop/CloudRemoteDesktopToast.tsx @@ -21,7 +21,7 @@ export type CloudRemoteDesktopToastState = | { kind: 'waking'; via: 'wake' | 'unarchive' } | { kind: 'failed'; code: CloudRemoteDesktopToastFailure } -type FailureCopy = { +export type FailureCopy = { title: string detail: string action: CloudRemoteDesktopNextAction | null @@ -31,7 +31,7 @@ type FailureCopy = { tone?: 'neutral' } -function failureCopy(t: Translate, code: CloudRemoteDesktopToastFailure): FailureCopy { +export function failureCopy(t: Translate, code: CloudRemoteDesktopToastFailure): FailureCopy { switch (code) { case 'not_cloud': return { @@ -139,7 +139,7 @@ function failureCopy(t: Translate, code: CloudRemoteDesktopToastFailure): Failur } } -function actionLabel(t: Translate, action: CloudRemoteDesktopNextAction): string { +export function actionLabel(t: Translate, action: CloudRemoteDesktopNextAction): string { switch (action) { case 'wake': return t('components.cloudRemoteDesktop.wake', 'Wake sandbox') diff --git a/src/renderer/src/components/cmd-j/remote-desktop-quick-action.ts b/src/renderer/src/components/cmd-j/remote-desktop-quick-action.ts index fb7517c94cd..805f5612157 100644 --- a/src/renderer/src/components/cmd-j/remote-desktop-quick-action.ts +++ b/src/renderer/src/components/cmd-j/remote-desktop-quick-action.ts @@ -37,7 +37,7 @@ export function getRemoteDesktopQuickAction(): CmdJQuickAction { title: translate('components.cloudRemoteDesktop.openMenuItem', 'Open remote desktop'), description: translate( 'components.cloudRemoteDesktop.paletteDescription', - 'Open the sandbox’s desktop in a browser tab.' + 'Open the sandbox’s desktop in a tab.' ), icon: Monitor, verbKeywords: [ diff --git a/src/renderer/src/components/tab-bar/BrowserTab.tsx b/src/renderer/src/components/tab-bar/BrowserTab.tsx index 382282ae121..ea43c0abb82 100644 --- a/src/renderer/src/components/tab-bar/BrowserTab.tsx +++ b/src/renderer/src/components/tab-bar/BrowserTab.tsx @@ -1,6 +1,6 @@ import { useEffect, useState } from 'react' import { useSortable } from '@dnd-kit/sortable' -import { X, Pin, PinOff, Volume2, VolumeX } from 'lucide-react' +import { X, Pin, PinOff, Volume2, VolumeX, Monitor } from 'lucide-react' import { ContextMenu, ContextMenuContent, @@ -13,6 +13,7 @@ import '../../../../shared/constants' import { ORCA_BROWSER_BLANK_URL } from '../../../../shared/browser/browser-blank-page' import { redactKagiSessionToken } from '../../../../shared/browser-url' import type { BrowserWorkspace } from '../../../../shared/browser-workspace-types' +import { isCloudRemoteDesktopUrl } from '../../../../shared/hosted-sandbox/cloud-remote-desktop' import { CLOSE_ALL_CONTEXT_MENUS_EVENT } from '@/lib/close-all-context-menus' import { getLiveBrowserUrl } from '../browser-pane/describe-page/live-browser-url-registry' import type { TabDragItemData } from '../tab-group/useTabDragSplit' @@ -55,6 +56,10 @@ export function formatBrowserTabUrlLabel(url: string, t: Translate = translate): } export function getBrowserTabLabel(tab: BrowserWorkspace, t?: Translate): string { + // A remote desktop tab is named for what it is, not for its localhost forward. + if (isCloudRemoteDesktopUrl(tab.url)) { + return (t ?? translate)('components.cloudRemoteDesktop.tabTitle', 'Remote desktop') + } if ( !tab.title || tab.title === tab.url || @@ -122,6 +127,7 @@ export default function BrowserTab({ // invalid URL — leave disabled } const tabLabel = getBrowserTabLabel(tab, t) + const isRemoteDesktop = isCloudRemoteDesktopUrl(tab.url) const audible = useAppStore((s) => (s.browserPagesByWorkspace[tab.id] ?? []).some((page) => s.browserAudiblePageIds[page.id]) ) @@ -206,6 +212,8 @@ export default function BrowserTab({ /> + ) : isRemoteDesktop ? ( + ) : ( } + icon={ + isRemoteDesktop ? ( + + ) : ( + + ) + } programName={ agentDriving ? agentDrivingLabel diff --git a/src/renderer/src/components/tab-bar/TabBarCreateEntryRow.tsx b/src/renderer/src/components/tab-bar/TabBarCreateEntryRow.tsx index 31305c1f9ab..586400c1e40 100644 --- a/src/renderer/src/components/tab-bar/TabBarCreateEntryRow.tsx +++ b/src/renderer/src/components/tab-bar/TabBarCreateEntryRow.tsx @@ -8,6 +8,7 @@ import { Globe, Loader2, MessageSquare, + Monitor, Search, Smartphone, TerminalSquare @@ -279,6 +280,8 @@ function getActionPresentation( const icon = option.option.kind === 'new-browser' ? (
    - ) -} - -/** The fixed alert levels, shown as values rather than a sentence (owners and admins only). */ -function UsageAlertLevels(): React.JSX.Element { - const t = useTranslate() - const locale = useIntlLocale() - const percent = new Intl.NumberFormat(locale, { style: 'percent' }) - return ( -
    - - {t('auto.components.billing.overage.alertsLabel', 'Usage alerts')} - -
      - {ORCA_USAGE_ALERT_LEVELS.map((level) => ( -
    • - {percent.format(level / 100)} -
    • - ))} -
    - +

    {t( - 'auto.components.billing.overage.alertsHint', - 'of your team’s sandbox hours, sent to owners and admins in Orca.' + 'auto.components.billing.usageAlertsNote', + 'Owners and admins are alerted in Orca at 75%, 90% and 100% of your team’s sandbox hours.' )} - +

    ) } diff --git a/src/renderer/src/components/billing/PlanBillingUsageHistory.tsx b/src/renderer/src/components/billing/PlanBillingUsageHistory.tsx index 1a772acbea5..58e5a30e835 100644 --- a/src/renderer/src/components/billing/PlanBillingUsageHistory.tsx +++ b/src/renderer/src/components/billing/PlanBillingUsageHistory.tsx @@ -6,7 +6,7 @@ import { formatHours } from './plan-billing-format' import { topMemberRows, topWorkspaceRows, - usageTotalLine, + usageWindowTotalLine, yourUsageLine, type UsageBreakdownRow } from './plan-billing-usage-history' @@ -60,7 +60,7 @@ export function PlanBillingUsageHistory({ action={ empty ? null : ( - {usageTotalLine(history.totalSeconds, t)} + {usageWindowTotalLine(history.totalSeconds, t)} ) } diff --git a/src/renderer/src/components/billing/plan-billing-usage-history.test.ts b/src/renderer/src/components/billing/plan-billing-usage-history.test.ts index 6fd651a9552..05ec992a7a2 100644 --- a/src/renderer/src/components/billing/plan-billing-usage-history.test.ts +++ b/src/renderer/src/components/billing/plan-billing-usage-history.test.ts @@ -6,6 +6,7 @@ import { usageBarPercent, usageChartMaxHours, usageTotalLine, + usageWindowTotalLine, yourUsageLine } from './plan-billing-usage-history' import { sampleUsageHistory, sampleUsageNames } from './plan-billing-fixtures' @@ -14,12 +15,13 @@ const HOUR = 3600 const day = (hours: number) => ({ start: 0, seconds: hours * HOUR }) describe('usage chart scale', () => { - it('rounds the busiest day up to 1, 2 or 5 × a power of ten', () => { + it('tops the axis at the nearest clean value just above the busiest day', () => { expect(usageChartMaxHours([day(0)])).toBe(1) expect(usageChartMaxHours([day(0.4)])).toBe(1) expect(usageChartMaxHours([day(1.5), day(0.2)])).toBe(2) - expect(usageChartMaxHours([day(5.2)])).toBe(10) - expect(usageChartMaxHours([day(3)])).toBe(5) + expect(usageChartMaxHours([day(5.2)])).toBe(6) + expect(usageChartMaxHours([day(3)])).toBe(3) + expect(usageChartMaxHours([day(7)])).toBe(8) expect(usageChartMaxHours([day(48)])).toBe(50) expect(usageChartMaxHours([day(120)])).toBe(200) }) @@ -71,5 +73,6 @@ describe('top workspaces and members', () => { expect(usageTotalLine(48 * HOUR, translate)).toBe('48 sandbox hours') expect(usageTotalLine(HOUR, translate)).toBe('1 sandbox hour') expect(usageTotalLine(0.26 * HOUR, translate)).toBe('0.3 sandbox hours') + expect(usageWindowTotalLine(48 * HOUR, translate)).toBe('48 sandbox hours in 30 days') }) }) diff --git a/src/renderer/src/components/billing/plan-billing-usage-history.ts b/src/renderer/src/components/billing/plan-billing-usage-history.ts index 3d71ad56d0b..1e6907c56ce 100644 --- a/src/renderer/src/components/billing/plan-billing-usage-history.ts +++ b/src/renderer/src/components/billing/plan-billing-usage-history.ts @@ -6,19 +6,18 @@ import { formatHours } from './plan-billing-format' const HOUR = 3600 -/** The y-axis top in hours: the busiest day rounded up to 1, 2 or 5 × a power of ten (min 1). */ +// Axis tops whose half is also a clean tick (0 / mid / max), × a power of ten. +const NICE_TOPS = [1, 2, 3, 4, 5, 6, 8, 10] + +/** The y-axis top in hours: the nearest clean value at or above the busiest day (min 1). */ export function usageChartMaxHours(days: OrcaBillingUsageHistory['days']): number { const busiest = Math.max(0, ...days.map((day) => day.seconds)) / HOUR if (busiest <= 1) { return 1 } const power = 10 ** Math.floor(Math.log10(busiest)) - for (const step of [1, 2, 5, 10]) { - if (busiest <= step * power) { - return step * power - } - } - return 10 * power + const top = NICE_TOPS.find((step) => busiest <= step * power) ?? 10 + return top * power } /** A bar's height as a share of the axis (0..100); a day with any usage stays visible (2%). */ @@ -126,7 +125,16 @@ export function topWorkspaceRows( ) } -/** "41.5 sandbox hours" for the section's total. */ +/** "48 sandbox hours in 30 days": the chart's total, distinct from the month's meter above. */ +export function usageWindowTotalLine(seconds: number, t: Translate): string { + return t('auto.components.billing.usage.windowTotal', '{{value}} sandbox hours in 30 days', { + value: formatHours(seconds), + count: Number(formatHours(seconds)), + defaultValue_one: '{{value}} sandbox hour in 30 days' + }) +} + +/** "41.5 sandbox hours" (a day's readout). */ export function usageTotalLine(seconds: number, t: Translate): string { return t('auto.components.billing.usage.total', '{{value}} sandbox hours', { value: formatHours(seconds), From d029218f18fbb369471cfbafd2850bd52974e70e Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:10:47 -0800 Subject: [PATCH 065/149] fix(w3): keep pid-less user listeners visible; hide only declared platform ports Vercel's sandbox-init listens on 23456 as root (pid invisible to the user); the VM declares it via ORCA_HOST_MANAGED_UNOWNED_PORTS. Any other pid-less listener (root-run postgres, Docker-published ports) stays under External. --- .../image/vm-scripts.generated.ts | 2 +- .../image/vm/orca-sandbox-start | 4 +- src/main/ports/host-managed-listeners.test.ts | 78 +++++++++++++------ src/main/ports/host-managed-listeners.ts | 39 +++++++--- .../ports/local-workspace-port-scanner.ts | 6 +- .../local-workspace-port-sections.test.ts | 11 +-- .../local-workspace-port-sections.ts | 6 +- 7 files changed, 97 insertions(+), 49 deletions(-) diff --git a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts index 518af8eaba1..0b9452fc4f3 100644 --- a/cloud/apps/sandbox-control/image/vm-scripts.generated.ts +++ b/cloud/apps/sandbox-control/image/vm-scripts.generated.ts @@ -3,7 +3,7 @@ import type { BuildInputs, GoldenImageManifest } from './golden-image' export const MANIFEST: GoldenImageManifest = {"imageVersion":"2026-11-09.1","image":"vercel/sandbox/node:24","region":"iad1","vcpus":4,"orcad":{"bundleUrl":null,"sha256":null},"gh":{"version":"2.103.3","sha256":"4c806978ffce1cec70853302a56d70ac6da4f19bae7adca4e1a8ab00633dd91d"},"chrome":{"version":"157.0.8103.38-1","sha256":"a62b277dc03da2cff50cc04589deb66f6875be339c066d46adb49b49eedb629d"},"agentCliPackages":["@anthropic-ai/claude-code@2.1.319","@openai/codex@0.166.0","opencode-ai@1.19.5","@google/gemini-cli@0.67.0","@github/copilot@1.0.108"],"cursorAgent":{"version":"2026.11.05-86047df","sha256":"170b77786cbf4c93064d64fff12b71a178b968730561c64afc2e8e752535442e"},"desktop":{"novnc":{"version":"1.6.0","sha256":"5066103959ef4e9b10f37e5a148627360dd8414e4cf8a7db92bdbd022e728aaa"},"websockify":{"version":"0.13.0","sha256":"b6413e364efd04f3c92ec8c17747e3c4adc20157c2ef1c5d019a26d944a46df8"}}} export const PROVISION_SCRIPT: string = "#!/usr/bin/env bash\n# Runs once inside the build sandbox (as the sandbox user, with sudo). Installs the pinned orcad\n# bundle, agent CLIs and Orca's VM entry points into /opt/orca, then smoke-tests orcad.\n# Inputs (env, from image/golden-image.manifest.json via build-golden-image.ts):\n# ORCAD_BUNDLE_URL ORCAD_BUNDLE_SHA256 [GH_VERSION GH_SHA256] [CHROME_VERSION CHROME_SHA256]\n# AGENT_NPM_PACKAGES (space-separated\n# name@version), [CURSOR_AGENT_VERSION CURSOR_AGENT_SHA256], [NOVNC_VERSION NOVNC_SHA256 WEBSOCKIFY_VERSION WEBSOCKIFY_SHA256] and ORCA_VM_SCRIPT_ (base64) for each /opt/orca/bin entry point.\nset -euo pipefail\nORCA_HOME=/opt/orca\nlog() { printf '[golden] %s\\n' \"$*\" >&2; }\n\nsudo mkdir -p \"$ORCA_HOME/bin\" \"$ORCA_HOME/runtime\" \"$ORCA_HOME/tools\"\nsudo chown -R \"$(id -u):$(id -g)\" \"$ORCA_HOME\"\n\nlog 'system packages'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n # Sandbox egress is TLS-only: plain-http apt mirrors time out at runtime (W2, wake on SSH).\n sudo sed -i 's#http://#https://#g' /etc/apt/sources.list.d/*.sources /etc/apt/sources.list 2>/dev/null || true\n sudo DEBIAN_FRONTEND=noninteractive apt-get update -qq\n # Developer basics agents expect (Conductor parity): rg, tmux, vim, git-lfs alongside the build tools.\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n ca-certificates curl git git-lfs jq ripgrep tmux vim-nox less openssh-client openssh-server build-essential python3 \\\n unzip zip util-linux procps >/dev/null\n git lfs install --system --skip-repo >/dev/null\n # sshd is started on demand by the wake-on-SSH bridge (key-only, loopback); never at boot.\n sudo systemctl disable ssh.service ssh.socket >/dev/null 2>&1 || true\n # A locked password field (\"!\") makes sshd refuse even key logins; '*' = no password, not locked.\n sudo usermod -p '*' \"$(id -un)\"\nelif command -v dnf >/dev/null; then\n sudo dnf install -y -q ca-certificates curl-minimal git git-lfs jq tmux vim-enhanced gcc gcc-c++ make python3 \\\n unzip util-linux procps-ng >/dev/null\nelse\n log 'no supported package manager'; exit 1\nfi\n\n# Managed images have no /vercel/sandbox; the project lives at /vercel/sandbox/project on every image.\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" /vercel/sandbox\n\nfetch_verified() { # url sha256 dest\n curl -fsSL --retry 3 -o \"$3\" \"$1\"\n echo \"$2 $3\" | sha256sum -c --quiet -\n}\n\nlog 'orcad bundle'\nbundle=\"$(mktemp -d)/orcad.tgz\"\nfetch_verified \"$ORCAD_BUNDLE_URL\" \"$ORCAD_BUNDLE_SHA256\" \"$bundle\"\ntar -xzf \"$bundle\" -C \"$ORCA_HOME/runtime\"\nrm -rf \"$(dirname \"$bundle\")\"\n# Release tarballs (orca-server-linux-*) may nest the server; normalize to runtime/orcad + runtime/runtimes.\nif [ ! -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\" ]; then\n server=\"$(find \"$ORCA_HOME/runtime\" -name orcad-server.js -type f | head -n 1)\"\n [ -n \"$server\" ] || { log 'bundle has no orcad-server.js'; exit 1; }\n root=\"$(dirname \"$(dirname \"$server\")\")\"\n ln -sfn \"$(dirname \"$server\")\" \"$ORCA_HOME/runtime/orcad\"\n [ -d \"$ORCA_HOME/runtime/runtimes\" ] || ln -sfn \"$root/runtimes\" \"$ORCA_HOME/runtime/runtimes\"\nfi\ntest -s \"$ORCA_HOME/runtime/orcad/orcad-server.js\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ntest -x \"$node\"\n\nif [ -n \"${GH_VERSION:-}\" ]; then\n log \"gh $GH_VERSION\"\n fetch_verified \"https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_amd64.tar.gz\" \\\n \"$GH_SHA256\" /tmp/gh.tgz\n tar -xzf /tmp/gh.tgz -C /tmp\n mkdir -p \"$ORCA_HOME/tools/bin\"\n install -m 0755 \"/tmp/gh_${GH_VERSION}_linux_amd64/bin/gh\" \"$ORCA_HOME/tools/bin/gh\"\n rm -rf /tmp/gh.tgz \"/tmp/gh_${GH_VERSION}_linux_amd64\"\nfi\n\nif [ -n \"${CHROME_VERSION:-}\" ] && command -v apt-get >/dev/null; then\n log \"google-chrome $CHROME_VERSION (headless browser for agents and Orca browser automation)\"\n deb=\"$(mktemp -d)/chrome.deb\"\n fetch_verified \"https://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-stable/google-chrome-stable_${CHROME_VERSION}_amd64.deb\" \\\n \"$CHROME_SHA256\" \"$deb\"\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \"$deb\" >/dev/null\n rm -rf \"$(dirname \"$deb\")\"\n # The .deb adds Google's apt source; the image stays pinned, so drop it.\n sudo rm -f /etc/apt/sources.list.d/google-chrome.list /etc/cron.daily/google-chrome\n google-chrome --headless=new --no-sandbox --disable-gpu --dump-dom 'data:text/html,

    ok

    ' 2>/dev/null | grep -q '

    ok

    '\nfi\n\nlog 'agent CLIs'\n# The image's system npm installs them; agents later run on whatever node orcad puts on PATH.\n# shellcheck disable=SC2086 # word splitting is the package list\nnpm install --global --no-fund --no-audit --prefix \"$ORCA_HOME/tools\" $AGENT_NPM_PACKAGES\n# opencode-ai installs every linux-x64 build variant (~205 MB each) and hardlinks the one its\n# postinstall picked into bin/opencode.exe, a standalone binary: drop the variants it did not pick.\nopencode_pkg=\"$ORCA_HOME/tools/lib/node_modules/opencode-ai\"\nif [ -x \"$opencode_pkg/bin/opencode.exe\" ]; then\n picked=\"$(stat -c %i \"$opencode_pkg/bin/opencode.exe\")\"\n for variant in \"$opencode_pkg\"/node_modules/opencode-*; do\n [ -d \"$variant\" ] || continue\n [ \"$(stat -c %i \"$variant/bin/opencode\" 2>/dev/null)\" = \"$picked\" ] || rm -rf \"$variant\"\n done\n \"$opencode_pkg/bin/opencode.exe\" --version >/dev/null\nfi\n\n# Copilot CLI prefers GH_TOKEN/GITHUB_TOKEN over the user's own /login. In Orca Cloud those hold the\n# workspace's GitHub App placeholder, which Copilot can't use (\"Resource not accessible by\n# integration\"), so a signed-in user could never get past it. The wrapper drops them for Copilot\n# only (COPILOT_GITHUB_TOKEN, a /login and BYOK still work), unless BYOK is set up, which needs no\n# GitHub sign-in and keeps them so `gh` in Copilot's shell still works.\ncopilot_loader=\"$ORCA_HOME/tools/lib/node_modules/@github/copilot/npm-loader.js\"\nif [ -f \"$copilot_loader\" ]; then\n rm -f \"$ORCA_HOME/tools/bin/copilot\"\n cat >\"$ORCA_HOME/tools/bin/copilot\" </dev/null; fi\ndone\n\nif [ -n \"${CURSOR_AGENT_VERSION:-}\" ]; then\n # Cursor's agent CLI is a pinned tarball (its own node + bundle), not an npm package. The image\n # copy lives under /opt/orca (root-owned) and its release channel is set to \"static\" at boot\n # (orca-sandbox-env), so it never replaces itself mid-session.\n log \"cursor-agent $CURSOR_AGENT_VERSION\"\n tgz=\"$(mktemp -d)/cursor-agent.tgz\"\n fetch_verified \"https://downloads.cursor.com/lab/${CURSOR_AGENT_VERSION}/linux/x64/agent-cli-package.tar.gz\" \\\n \"$CURSOR_AGENT_SHA256\" \"$tgz\"\n rm -rf \"$ORCA_HOME/tools/cursor-agent\"\n mkdir -p \"$ORCA_HOME/tools/cursor-agent\" \"$ORCA_HOME/tools/bin\"\n tar --strip-components=1 -xzf \"$tgz\" -C \"$ORCA_HOME/tools/cursor-agent\"\n rm -rf \"$(dirname \"$tgz\")\"\n ln -sfn ../cursor-agent/cursor-agent \"$ORCA_HOME/tools/bin/cursor-agent\"\n \"$ORCA_HOME/tools/bin/cursor-agent\" --version >/dev/null\nfi\n\nlog 'openssh server (binaries only)'\n# For `orca ssh`: an unprivileged sshd on loopback (see vm/orca-sshd). Only the server binaries,\n# kept out of /usr: the packages would pull in systemd units, SELinux policy (~38 MB on AL2023) and\n# system host keys a user-run sshd never uses. Its libraries are already in the base image, except\n# tcp-wrappers on Ubuntu.\nmkdir -p \"$ORCA_HOME/openssh\"\npkgs=\"$(mktemp -d)\"\nif command -v dnf >/dev/null; then\n sudo dnf install -y -q --setopt=install_weak_deps=False cpio >/dev/null\n sudo dnf install -y -q --downloadonly --downloaddir=\"$pkgs\" openssh-server >/dev/null\n (cd \"$pkgs\" && rpm2cpio openssh-server-[0-9]*.rpm | cpio -idm --quiet)\n sudo dnf clean all -q >/dev/null 2>&1 || true\n libexec=\"$pkgs/usr/libexec/openssh\"\nelse\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends libwrap0 >/dev/null\n (cd \"$pkgs\" && apt-get download -qq openssh-server openssh-sftp-server >/dev/null)\n for deb in \"$pkgs\"/*.deb; do dpkg-deb -x \"$deb\" \"$pkgs\"; done\n libexec=\"$pkgs/usr/lib/openssh\"\nfi\ninstall -m 0755 \"$pkgs/usr/sbin/sshd\" \"$libexec/sshd-session\" \"$libexec/sftp-server\" \"$ORCA_HOME/openssh/\"\n# OpenSSH 10 splits authentication into its own binary.\nif [ -x \"$libexec/sshd-auth\" ]; then install -m 0755 \"$libexec/sshd-auth\" \"$ORCA_HOME/openssh/\"; fi\nsudo rm -rf \"$pkgs\"\n\"$ORCA_HOME/openssh/sshd\" -V 2>&1 | head -n 1 >&2 || true\n# sshd refuses a locked account ('!') even for key logins; '*' unlocks it with no usable password.\nsudo usermod -p '*' \"$(id -un)\"\n\ninstall_desktop() {\n # Remote desktop (~80 MB): Xvnc + openbox + xterm from the distro, noVNC + websockify pinned\n # tarballs. Only orca-desktop-start runs it, on demand; nothing starts at boot. Every step says\n # `|| return 1`: errexit does not apply inside an `if` condition.\n command -v apt-get >/dev/null || { log 'remote desktop: apt only'; return 1; }\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \\\n tigervnc-standalone-server tigervnc-tools openbox xterm x11-xserver-utils >/dev/null || return 1\n local tmp dir=\"$ORCA_HOME/desktop\"\n tmp=\"$(mktemp -d)\" || return 1\n fetch_verified \"https://github.com/novnc/noVNC/archive/refs/tags/v${NOVNC_VERSION}.tar.gz\" \\\n \"$NOVNC_SHA256\" \"$tmp/novnc.tgz\" || return 1\n fetch_verified \"https://github.com/novnc/websockify/archive/refs/tags/v${WEBSOCKIFY_VERSION}.tar.gz\" \\\n \"$WEBSOCKIFY_SHA256\" \"$tmp/websockify.tgz\" || return 1\n rm -rf \"$dir\" && mkdir -p \"$dir/novnc\" \"$dir/websockify\" || return 1\n tar -xzf \"$tmp/novnc.tgz\" -C \"$dir/novnc\" --strip-components 1 || return 1\n tar -xzf \"$tmp/websockify.tgz\" -C \"$dir/websockify\" --strip-components 1 || return 1\n # Orca tab fit: title \"Remote desktop\" (Xvnc's -desktop name), no noVNC favicon, control bar on\n # the right (away from Orca's sidebar edge); a stale per-boot password ends the session with one\n # plain message instead of a reconnect loop. \"Unencrypted\" is noVNC's view of plain ws:// to\n # localhost; the hop to the sandbox rides the end-to-end encrypted runtime connection.\n sed -i -e 's/document.title = e.detail.name + \" - \" + PAGE_TITLE;/document.title = e.detail.name;/' \\\n -e \"s/WebUtil.readSetting('controlbar_pos') === 'right'/WebUtil.readSetting('controlbar_pos', 'right') === 'right'/\" \\\n -e 's/securityFailed(e) {/securityFailed(e) { UI.inhibitReconnect = true; UI.showStatus(\"This remote desktop session ended. Reopen it from the workspace menu.\", \"error\"); return;/' \\\n -e 's/_(\"Connected (unencrypted) to \")/_(\"Connected to \")/' \\\n \"$dir/novnc/app/ui.js\" || return 1\n sed -i '/rel=\"icon\"/d; /rel=\"apple-touch-icon\"/d' \"$dir/novnc/vnc.html\" || return 1\n rm -rf \"$tmp\"\n PYTHONPATH=\"$dir/websockify\" python3 -P -c 'import websockify' >/dev/null || return 1\n command -v Xvnc >/dev/null && test -s \"$dir/novnc/vnc.html\"\n}\ndesktop=false\nif [ -n \"${NOVNC_VERSION:-}\" ]; then\n log 'remote desktop'\n # Optional: a failure leaves an image without the desktop, never a failed build.\n if install_desktop; then\n desktop=true\n else\n log 'remote desktop install failed; continuing without it'\n rm -rf \"$ORCA_HOME/desktop\"\n fi\nfi\n\nlog 'Orca entry points'\nfor name in orca-sandbox-start orca-sandbox-drain orca-sandbox-env orca-session-env.sh orca-env orca-egress-probe orca-image-wipe orca-agent-signout orca-share-proxy orca-sshd orca-ssh-keys orca-desktop-start orca-desktop-proxy orca-desktop-page.js orca-sandbox-grant orca-sandbox-revoke orca-sandbox-members orca-sandbox-read-snapshot orca-read-snapshot.cjs orca-git-as orca-git-identity orcad-boot git; do\n var=\"ORCA_VM_SCRIPT_${name//[-.]/_}\"\n printf '%s' \"${!var}\" | base64 -d >\"$ORCA_HOME/bin/$name\"\n chmod 0755 \"$ORCA_HOME/bin/$name\"\ndone\n# The orca CLI (agents drive worktrees, terminals and the browser through it) talks to this VM's orcad.\ncli=\"$(find \"$ORCA_HOME/runtime\" -name orca-cli.cjs -type f | head -n 1)\"\nif [ -n \"$cli\" ]; then\n printf '#!/usr/bin/env bash\\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\\nexec \"%s\" \"%s\" \"$@\"\\n' \"$node\" \"$cli\" >\"$ORCA_HOME/bin/orca\"\n chmod 0755 \"$ORCA_HOME/bin/orca\"\nelse\n log 'bundle has no orca CLI (orca-cli.cjs): agents will not have `orca` on PATH'\nfi\n# The image's node/npm/npx live only on the build command's PATH; append them so agents (codex's\n# `env node` shebang) and stdio MCP servers launched with npx resolve them in Orca's login shells.\nsystem_node=\"$(command -v npx || command -v node || true)\"\nif [ -z \"$system_node\" ]; then\n echo 'no node/npx on the build PATH' >&2\n exit 1\nfi\nprintf 'export PATH=%s/tools/bin:%s/bin:$PATH:%s\\n' \"$ORCA_HOME\" \"$ORCA_HOME\" \"$(dirname \"$system_node\")\" |\n sudo tee /etc/profile.d/orca.sh >/dev/null\n# Every new shell (login or not: /etc/bashrc sources profile.d) re-reads the session env file.\nsudo install -m 0644 \"$ORCA_HOME/bin/orca-session-env.sh\" /etc/profile.d/zz-orca-session-env.sh\nif [ -f /etc/bash.bashrc ]; then\n # Ubuntu's bash.bashrc does not source profile.d for non-login interactive shells (AL2023's bashrc does).\n grep -q zz-orca-session-env /etc/bash.bashrc ||\n echo '[ -r /etc/profile.d/zz-orca-session-env.sh ] && . /etc/profile.d/zz-orca-session-env.sh' | sudo tee -a /etc/bash.bashrc >/dev/null\nfi\nif [ -f /etc/bash.bashrc ]; then\n # Ubuntu: zsh reads /etc/zsh/zshenv for every shell, so new zsh shells match bash (`orca-env` covers\n # shells that were already open).\n sudo install -d -m 0755 /etc/zsh\n sudo touch /etc/zsh/zshenv\n grep -q zz-orca-session-env /etc/zsh/zshenv ||\n echo '[ -r /etc/profile.d/zz-orca-session-env.sh ] && . /etc/profile.d/zz-orca-session-env.sh' | sudo tee -a /etc/zsh/zshenv >/dev/null\nfi\nsudo chown -R root:root \"$ORCA_HOME\"\n\nlog 'smoke: orcad reaches ready on loopback (and warms the V8 compile cache: ~1.5 s off every boot)'\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/compile-cache\"\n# The runtime is root-owned, so its startup-qualified marker lives here. The smoke run leaves one,\n# so every boot from the image skips orcad's disposable startup preflight (~0.6 s of wake).\nsudo install -d -o \"$(id -u)\" -g \"$(id -g)\" \"$ORCA_HOME/startup-qualification\"\nsmoke_data=\"$(mktemp -d)\"\n# orcad-boot also writes orcad's full code cache as the smoke run exits (~0.3 s more off every boot).\nNODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_USER_DATA=\"$smoke_data\" timeout 60 \"$node\" \"$ORCA_HOME/bin/orcad-boot\" \\\n --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" --write-code-cache \"$ORCA_HOME/runtime/orcad/orcad-server.js\" \\\n --port 6799 --json >/tmp/orcad-smoke.out 2>/tmp/orcad-smoke.err &\nsmoke_pid=$!\nready=0\nfor _ in $(seq 1 600); do\n if grep -q '\"orca_server_ready\"' /tmp/orcad-smoke.out 2>/dev/null; then ready=1; break; fi\n sleep 0.1\ndone\n# orcad writes the marker just after readiness; best effort, a boot without one only re-qualifies.\nfor _ in $(seq 1 30); do\n [ \"$ready\" = 1 ] && [ ! -s \"$ORCA_HOME/startup-qualification/.orcad-startup-qualified\" ] || break\n sleep 0.1\ndone\nkill \"$smoke_pid\" 2>/dev/null || true\nwait \"$smoke_pid\" 2>/dev/null || true\nrm -rf \"$smoke_data\" /tmp/orcad-smoke.out\nif [ \"$ready\" != 1 ]; then\n tail -n 40 /tmp/orcad-smoke.err >&2; exit 1\nfi\n# Best effort: without it every boot loads orcad as before.\nif [ -s \"$ORCA_HOME/compile-cache/orcad-server.v8\" ]; then\n log \"orcad code cache: $(stat -c %s \"$ORCA_HOME/compile-cache/orcad-server.v8\") bytes\"\nelse\n log 'orcad code cache was not written; boots compile orcad without it'\n grep 'orcad-boot' /tmp/orcad-smoke.err >&2 || true\nfi\n\nlog 'versions'\nversions=\"{}\"\nfor bin in claude codex opencode gemini cursor-agent copilot gh; do\n if [ -x \"$ORCA_HOME/tools/bin/$bin\" ]; then\n v=\"$(\"$ORCA_HOME/tools/bin/$bin\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$bin\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\nfor sys in rg vim git-lfs google-chrome; do\n if command -v \"$sys\" >/dev/null; then\n v=\"$(\"$sys\" --version 2>/dev/null | head -n 1 || echo unknown)\"\n versions=\"$(jq -c --arg k \"$sys\" --arg v \"$v\" '. + {($k): $v}' <<<\"$versions\")\"\n fi\ndone\ncommand -v tmux >/dev/null && versions=\"$(jq -c --arg v \"$(tmux -V)\" '. + {tmux: $v}' <<<\"$versions\")\"\n[ -x \"$ORCA_HOME/bin/orca\" ] && versions=\"$(jq -c '. + {orca: \"bundled\"}' <<<\"$versions\")\"\njq -c --arg node \"$(\"$node\" --version)\" --arg disk \"$(df -h / | awk 'NR==2{print $2}')\" \\\n --argjson desktop \"$desktop\" '{node: $node, disk: $disk, tools: ., desktop: $desktop}' <<<\"$versions\"\n" -export const VM_SCRIPT_SOURCES: BuildInputs['vmScripts'] = {"orca-sandbox-start":"#!/usr/bin/env bash\n# Starts orcad for this boot (idempotent) and prints its recipe line:\n# {\"schemaVersion\":1,\"pairingCode\":\"orca://pair?...\",\"projectRoot\":\"/vercel/sandbox/project\"}\n# Env from the control plane: ORCA_SANDBOX_ID, ORCA_PUBLIC_WSS, optional ORCA_REPO_URL/ORCA_REPO_REF,\n# ORCA_GITHUB_PLACEHOLDER, ORCA_SECRET_ENV (`NAME=` lines: org/personal/repo secrets for\n# orcad and its agents), ORCA_SHARE_PROXY_KEY (this session's share-link proxy key, port 6769).\n# Never prints anything else on stdout's last line.\n# With ORCA_READY_VIA=file it prints {\"schemaVersion\":1,\"readyFile\":\"\"} instead and the control\n# plane reads the offer with the files API: the provider keeps command stdout as logs, not files.\n# With ORCA_READY_KEY too (64 hex chars, this call's key; env is not kept) the pointer also carries\n# \"sealedOffer\": \".\", which saves that round trip.\n# Managed env for every process orcad starts: ORCA_IS_CLOUD=1, ORCA_SANDBOX_ID, ORCA_ROOT_PATH,\n# ORCA_WORKTREE_PATH, ORCA_WORKSPACE_PATH, ORCA_WORKSPACE_NAME, ORCA_DEFAULT_BRANCH, ORCA_PORT and the\n# CONDUCTOR_* names imported Conductor scripts read.\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nPROJECT=/vercel/sandbox/project\nmkdir -p \"$STATE\"\n# Only print_ready uses the key; nothing this script starts inherits it.\nready_key=\"${ORCA_READY_KEY:-}\"\nunset ORCA_READY_KEY\n[[ \"$ready_key\" =~ ^[0-9a-f]{64}$ ]] || ready_key=''\nexec 9>\"$STATE/start.lock\"\nflock -w 60 9\n# Background children close fd 9 (`9>&-`): an orcad that inherited it would hold the lock for its whole\n# life and every later start (resume of a running sandbox, a retried create) would wait out the 60 s.\n\n# orcad only lists a project once a client registers it (the desktop does on connect), so API, MCP,\n# routine and phone sessions saw no repo. Register the workspace project at every start, in the\n# background (ready is not delayed); `repo add` of an already-registered path is a no-op error.\nregister_project() {\n [ -x \"$ORCA_HOME/bin/orca\" ] && [ -d \"$PROJECT\" ] || return 0\n local kind=() name=()\n [ -e \"$PROJECT/.git\" ] || kind=(--kind folder)\n # The checkout lives at .../project; name it after the repository (owner/name.git -> name).\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n local base=\"${ORCA_REPO_URL%/}\"\n base=\"${base##*/}\"\n base=\"${base%.git}\"\n [ -n \"$base\" ] && name=(--display-name \"$base\")\n fi\n setsid \"$ORCA_HOME/bin/orca\" repo add --path \"$PROJECT\" \"${kind[@]}\" \"${name[@]}\" --json \\\n >\"$STATE/register-project.log\" 2>&1 &- &\n}\n\nprint_ready() {\n if [ \"${ORCA_READY_VIA:-}\" = file ]; then\n local sealed='' iv\n if [ -n \"$ready_key\" ] && command -v openssl >/dev/null; then\n iv=\"$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')\"\n # Best effort: without it the control plane reads the file, as before.\n sealed=\"$(tail -n 1 \"$STATE/ready.json\" | openssl enc -aes-256-ctr -K \"$ready_key\" -iv \"$iv\" -nosalt | base64 -w0)\" &&\n sealed=\"$iv.$sealed\" || sealed=''\n fi\n printf '{\"schemaVersion\":1,\"readyFile\":\"%s\"%s}\\n' \"$STATE/ready.json\" \"${sealed:+,\\\"sealedOffer\\\":\\\"$sealed\\\"}\"\n else\n tail -n 1 \"$STATE/ready.json\"\n fi\n}\n# Command stderr is kept by the provider: strip injected values and credential shapes from log tails.\nredact_log() {\n local text kv value\n text=\"$(cat)\"\n for kv in ${agent_env[@]+\"${agent_env[@]}\"}; do\n value=\"${kv#*=}\"\n if [ \"${#value}\" -ge 8 ]; then\n text=\"${text//\"$value\"/[REDACTED]}\"\n fi\n done\n printf '%s\\n' \"$text\" | sed -E \\\n -e 's#orca://[^[:space:]]+#[REDACTED_PAIRING]#g' \\\n -e 's#(gh[pousr]_|github_pat_|sk-|vc[kpiar]_)[A-Za-z0-9._-]{16,}#[REDACTED_TOKEN]#g' \\\n -e 's#eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}#[REDACTED_JWT]#g' \\\n -e 's#(Authorization|authorization):[[:space:]]*[A-Za-z]+[[:space:]]+[^[:space:]]+#\\1: [REDACTED]#g'\n}\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n\n# Share-link proxy (port 6769): answers only requests the control plane signed with this session's\n# key, so its public route is useless on its own. The key goes in on stdin (printf is a builtin), so\n# it never appears in any argv or in the proxy's /proc//environ.\nstart_share_proxy() {\n [ -n \"${ORCA_SHARE_PROXY_KEY:-}\" ] && [ -x \"$ORCA_HOME/bin/orca-share-proxy\" ] || return 0\n if [ \"$(cat \"$STATE/share-proxy.boot\" 2>/dev/null || true)\" = \"$boot_id\" ] \\\n && kill -0 \"$(cat \"$STATE/share-proxy.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n return 0\n fi\n printf '%s' \"$ORCA_SHARE_PROXY_KEY\" | env -i HOME=\"$HOME\" LANG=C.UTF-8 PATH=/usr/bin:/bin \\\n setsid \"$node\" \"$ORCA_HOME/bin/orca-share-proxy\" >\"$STATE/share-proxy.log\" 2>&1 9>&- &\n echo $! >\"$STATE/share-proxy.pid\"\n printf '%s' \"$boot_id\" >\"$STATE/share-proxy.boot\"\n}\n\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nstart_share_proxy\nunset ORCA_SHARE_PROXY_KEY\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" = \"$boot_id\" ] && [ -s \"$STATE/ready.json\" ] \\\n && kill -0 \"$(cat \"$STATE/orcad.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n print_ready\n exit 0\nfi\n# Resume = reboot from disk: locks and pids from the previous session name dead processes.\nrm -f \"$STATE/ready.json\" \"$STATE/orcad.pid\"\nprintf '%s' \"$boot_id\" >\"$STATE/boot-id\"\n\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n # Every github.com request carries the placeholder; the egress policy swaps in a 1h repo token.\n git config --global http.https://github.com/.extraheader \"$ORCA_GIT_EXTRAHEADER\"\nfi\n# Commits outside a teammate's turn (or before any member connected GitHub) need an author too.\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'cloud@users.noreply.onorca.dev'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca Cloud'\n# First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both.\nclone_pid=''\nif [ ! -d \"$PROJECT\" ]; then\n mkdir -p \"$PROJECT\"\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n git clone --quiet ${ORCA_REPO_REF:+--branch \"$ORCA_REPO_REF\"} -- \"$ORCA_REPO_URL\" \"$PROJECT\" 2>\"$STATE/clone.log\" 9>&- &\n clone_pid=$!\n fi\nfi\n\n# The clone may still be running here, so the name comes from the URL; the default branch is\n# filled in lazily by the session-env shell hook once the clone exists.\nif [ -n \"${ORCA_REPO_URL:-}\" ]; then\n workspace_name=\"$(basename \"${ORCA_REPO_URL%/}\" .git)\"\nelse\n workspace_name=\"$(basename \"$(git -C \"$PROJECT\" remote get-url origin 2>/dev/null || echo \"$PROJECT\")\" .git)\"\nfi\n# One workspace per VM: its preview ports start at 3000 (Conductor allots CONDUCTOR_PORT..+9).\nmanaged_env=(\n ORCA_IS_CLOUD=1\n ORCA_ROOT_PATH=\"$PROJECT\" ORCA_WORKTREE_PATH=\"$PROJECT\" ORCA_WORKSPACE_PATH=\"$PROJECT\"\n ORCA_WORKSPACE_NAME=\"$workspace_name\" ORCA_PORT=3000\n CONDUCTOR_IS_CLOUD=1\n # Agent CLIs are pinned by the image (smoke-tested); a self-update mid-session can break a running agent.\n DISABLE_AUTOUPDATER=1 OPENCODE_DISABLE_AUTOUPDATE=1 COPILOT_AUTO_UPDATE=false\n CONDUCTOR_ROOT_PATH=\"$PROJECT\" CONDUCTOR_WORKSPACE_PATH=\"$PROJECT\"\n CONDUCTOR_WORKSPACE_NAME=\"$workspace_name\" CONDUCTOR_PORT=3000\n)\n\nagent_env=()\nif command -v google-chrome >/dev/null; then\n # Orca's browser automation and agent browser tools use the image's headless Chrome.\n agent_env+=(\"ORCA_BROWSER_EXECUTABLE=$(command -v google-chrome)\")\nfi\nif [ -n \"${ORCA_GITHUB_PLACEHOLDER:-}\" ]; then\n # The egress layer swaps the placeholder for a short-lived GitHub token; none lives in the VM.\n agent_env+=(\"GH_TOKEN=$ORCA_GITHUB_PLACEHOLDER\" \"GITHUB_TOKEN=$ORCA_GITHUB_PLACEHOLDER\")\nfi\n\nsecret_names=()\nif [ -n \"${ORCA_SECRET_ENV:-}\" ]; then\n # Secrets live only in memory: orcad's process env and a tmpfs file new shells re-read\n # (orca-sandbox-env), never under $HOME or the project, so the stop snapshot never carries them.\n # Resolved per start (and per edit) by the control plane: no image rebuild, no restart.\n while IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\" # not IFS='=': read would strip base64 padding\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n agent_env+=(\"$name=$(printf '%s' \"$b64\" | base64 -d)\")\n secret_names+=(\"$name\")\n done < <(printf '%s\\n' \"$ORCA_SECRET_ENV\") # a pipe, not a here-string temp file\nfi\n# Always rewrite the file, so a resume with fewer secrets drops the old names too.\n\"$ORCA_HOME/bin/orca-sandbox-env\" >/dev/null || echo 'session env file unavailable; secrets apply at boot only' >&2\nunset ORCA_SECRET_ENV\n\n# Agent CLIs installed with the image's npm (codex, gemini, ...) are `#!/usr/bin/env node` scripts:\n# terminals need that node on PATH, not only orcad's bundled runtime.\nsystem_node=\"$(command -v node 2>/dev/null || echo \"$node\")\"\n# The egress proxy answers for hosts with credential rules (model APIs, api.github.com) with a\n# certificate from Vercel's CA, which this command's env trusts (Vercel sets these). Pure-Node clients\n# use Node's bundled roots otherwise: Gemini CLI retried forever (\"taking a bit longer\") in every\n# terminal while the same call worked here. Pass the provider's CA settings on to orcad and its shells.\nca_env=(NODE_USE_SYSTEM_CA=\"${NODE_USE_SYSTEM_CA:-1}\")\nfor name in NODE_EXTRA_CA_CERTS SSL_CERT_FILE; do\n if [ -n \"${!name:-}\" ]; then ca_env+=(\"$name=${!name}\"); fi\ndone\nenv -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 TERM=xterm-256color \"${ca_env[@]}\" \\\n PATH=\"$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname \"$system_node\"):/usr/local/bin:/usr/bin:/bin\" \\\n ORCA_USER_DATA=\"$HOME/.orcad-data\" ORCA_SANDBOX_ID=\"$ORCA_SANDBOX_ID\" \"${managed_env[@]}\" \\\n ORCA_HOST_MANAGED_LISTENER_PATHS=\"$ORCA_HOME\" \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_SESSION_ENV_NAMES=\"${secret_names[*]}\" \"${agent_env[@]}\" \\\n setsid nohup \"$node\" \"$ORCA_HOME/bin/orcad-boot\" --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" \\\n \"$ORCA_HOME/runtime/orcad/orcad-server.js\" --port 6768 --bind 0.0.0.0 --pairing-address \"$ORCA_PUBLIC_WSS\" \\\n --recipe-json --project-root \"$PROJECT\" \\\n >\"$STATE/ready.json\" 2>\"$STATE/orcad.log\" &- &\necho $! >\"$STATE/orcad.pid\"\n\n# sshd for `orca ssh` (loopback only). Best effort: a workspace without it still serves orcad.\n\"$ORCA_HOME/bin/orca-sshd\" >/dev/null 2>\"$STATE/sshd-start.err\" || true\n\n# Polled every 10 ms (at least 60 s in all): ready is on the wake path, so detect it promptly.\nfor _ in $(seq 1 6000); do\n if grep -q '\"pairingCode\"' \"$STATE/ready.json\" 2>/dev/null; then\n if [ -n \"$clone_pid\" ] && ! wait \"$clone_pid\"; then\n echo 'repository clone failed' >&2\n tail -n 5 \"$STATE/clone.log\" | redact_log >&2\n exit 1\n fi\n register_project\n print_ready\n exit 0\n fi\n if ! kill -0 \"$(cat \"$STATE/orcad.pid\")\" 2>/dev/null; then\n echo 'orcad exited before ready' >&2\n tail -n 40 \"$STATE/orcad.log\" | redact_log >&2\n exit 1\n fi\n sleep 0.01\ndone\necho 'orcad start timed out' >&2\nexit 1\n","orca-sandbox-drain":"#!/usr/bin/env bash\n# Asks orcad to quit before the VM stops: its shutdown turns working agent chats into durable\n# restart offers and flushes terminal restore hints, which the desktop continues after resume.\nset -euo pipefail\nSTATE=\"$HOME/.orca-sandbox\"\nWAIT_SECONDS=\"${1:-280}\"\npid=\"$(cat \"$STATE/orcad.pid\" 2>/dev/null || true)\"\nif [ -z \"$pid\" ] || ! kill -0 \"$pid\" 2>/dev/null; then\n exit 0\nfi\nkill -TERM \"$pid\"\nfor _ in $(seq 1 $((WAIT_SECONDS * 10))); do\n if ! kill -0 \"$pid\" 2>/dev/null; then\n rm -f \"$STATE/orcad.pid\" \"$STATE/ready.json\"\n exit 0\n fi\n sleep 0.1\ndone\n# Leave it running: the provider stop ends it, and the drain already had its window.\necho 'orcad still draining at deadline' >&2\nexit 0\n","orca-sandbox-env":"#!/usr/bin/env bash\n# Writes this session's secret env where new shells and agent launches read it (orca-session-env.sh).\n# Input: ORCA_SECRET_ENV (`NAME=` lines) from the control plane, at boot (orca-sandbox-start)\n# and whenever a secret changes (POST /v1/sandboxes/:id/env/refresh). The file lives on tmpfs only:\n# never on the sandbox disk, so the stop snapshot never carries it. Prints {\"names\":N} on success.\n# Also keeps Codex pointed at a configured OpenAI-compatible provider (OPENAI_BASE_URL), since Codex\n# does not read that variable: a managed block in ~/.codex/config.toml naming only the env var.\nset -euo pipefail\numask 077\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\n# ORCA_SESSION_ENV_DIR: tests only (a scratch dir off tmpfs); the control plane never sets it.\ndir=\"${ORCA_SESSION_ENV_DIR:-/dev/shm/orca-env-$(id -u)}\"\nif [ -z \"${ORCA_SESSION_ENV_DIR:-}\" ] && [ \"$(stat -f -c %T /dev/shm 2>/dev/null || true)\" != tmpfs ]; then\n # No memory-only place to keep it: refuse rather than write secrets to disk.\n echo 'no tmpfs for the session env' >&2\n exit 3\nfi\nmkdir -p \"$dir\"\nchmod 700 \"$dir\"\n# Writes are ordered by the control plane's resolve time: an older refresh that lost a race is dropped.\ngeneration=\"${ORCA_ENV_GENERATION:-0}\"\ncase \"$generation\" in '' | *[!0-9]*) generation=0 ;; esac\ncurrent=\"$(cat \"$dir/generation\" 2>/dev/null || echo 0)\"\ncase \"$current\" in '' | *[!0-9]*) current=0 ;; esac\nif [ \"$generation\" -lt \"$current\" ]; then\n printf '{\"stale\":true}\\n'\n exit 0\nfi\ntmp=\"$(mktemp \"$dir/.session.env.XXXXXX\")\"\ncount=0\nopenai_base_url=''\nopenai_model=''\nanthropic_model=''\nanthropic_key_tail=''\ngateway_key=''\ngemini_key=''\ncodex_placeholder=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n # Not for shells: the Codex account placeholder becomes ~/.codex/auth.json below.\n if [ \"$name\" = ORCA_CODEX_AUTH_PLACEHOLDER ]; then\n codex_placeholder=\"$(printf '%s' \"$b64\" | base64 -d)\"\n case \"$codex_placeholder\" in *[!A-Za-z0-9._-]*) codex_placeholder='' ;; esac\n fi\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n # Values stay base64 in the file; the shell hook decodes them.\n printf '%s=%s\\n' \"$name\" \"$b64\" >>\"$tmp\"\n count=$((count + 1))\n case \"$name\" in\n OPENAI_BASE_URL) openai_base_url=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n OPENAI_MODEL) openai_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n ANTHROPIC_MODEL) anthropic_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n AI_GATEWAY_API_KEY) gateway_key=1 ;;\n GEMINI_API_KEY | GOOGLE_API_KEY) gemini_key=\"${gemini_key:-gemini-api-key}\" ;;\n GOOGLE_GENAI_USE_VERTEXAI) case \"$(printf '%s' \"$b64\" | base64 -d)\" in true | 1) gemini_key=vertex-ai ;; esac ;;\n # Claude Code asks once per key whether to use ANTHROPIC_API_KEY; it remembers the last 20 chars.\n ANTHROPIC_API_KEY) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\ndone < <(printf '%s\\n' \"${ORCA_SECRET_ENV:-}\")\nmv -f \"$tmp\" \"$dir/session.env\"\nprintf '%s' \"$generation\" >\"$dir/generation\"\n\n# ---- Codex: trust the workspace and use the configured provider (no secret values) ----\nPROJECT=/vercel/sandbox/project\ncodex_config=\"$HOME/.codex/config.toml\"\ntoml_string() { # TOML basic string; the control plane only accepts https URLs and plain model ids\n local value=\"${1//\\\\/\\\\\\\\}\"\n printf '\"%s\"' \"${value//\\\"/\\\\\\\"}\"\n}\nstrip_managed() { # drop the managed blocks and the blank lines written before them (no growth per refresh)\n awk '/^# >>> orca-cloud managed/{skip=1; blank=\"\"} skip{if (/^# <<< orca-cloud managed/) skip=0; next}\n /^[[:space:]]*$/{blank=blank $0 \"\\n\"; next} {printf \"%s\", blank; blank=\"\"; print}' \"$1\"\n}\n# Always managed: an agent launched from the phone or the API has no one to answer Codex's\n# \"trust this folder?\" screen, so the workspace project is trusted up front.\nif true; then\n mkdir -p \"$HOME/.codex\"\n user_part=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n if [ -f \"$codex_config\" ]; then strip_managed \"$codex_config\" >\"$user_part\"; fi\n next=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n openai_host=\"${openai_base_url#https://}\"\n openai_host=\"${openai_host%%/*}\"\n custom_provider=''\n if [ -n \"$openai_base_url\" ] && [ \"$openai_host\" != api.openai.com ]; then custom_provider=1; fi\n # Top-level keys must precede every table; each is skipped when the user already set it.\n head_keys=\"$(awk '/^\\[/{exit} {print}' \"$user_part\")\"\n has_key() { grep -Eq \"^[[:space:]]*$1[[:space:]]*=\" <<<\"$head_keys\"; }\n {\n printf '# >>> orca-cloud managed (Orca Cloud; edit in Orca settings)\\n'\n # The sandbox is the isolation boundary: Codex's own bwrap sandbox can't start in it (\"Unexpected\n # capabilities\"), and a prompt delivered from the phone or the API has no one to approve commands.\n has_key sandbox_mode || printf 'sandbox_mode = \"danger-full-access\"\\n'\n has_key approval_policy || printf 'approval_policy = \"never\"\\n'\n if [ -n \"$custom_provider\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_cloud\"\\n'\n if [ -n \"$openai_model\" ] && ! has_key model; then\n printf 'model = %s\\n' \"$(toml_string \"$openai_model\")\"\n fi\n elif [ -n \"$codex_placeholder\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_chatgpt\"\\n'\n fi\n printf '# <<< orca-cloud managed\\n'\n cat \"$user_part\"\n if [ -n \"$custom_provider\" ]; then\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_cloud]\\nname = \"Orca Cloud\"\\n'\n printf 'base_url = %s\\nenv_key = \"OPENAI_API_KEY\"\\nwire_api = \"responses\"\\n' \"$(toml_string \"$openai_base_url\")\"\n printf '# <<< orca-cloud managed\\n'\n elif [ -n \"$codex_placeholder\" ]; then\n # Codex via the Orca account: the ChatGPT backend over HTTPS. Its default Responses WebSocket can't\n # pass the egress proxy, where the placeholder becomes the real token (found live, Codex 0.166).\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_chatgpt]\\nname = \"OpenAI\"\\n'\n printf 'base_url = \"https://chatgpt.com/backend-api/codex\"\\nwire_api = \"responses\"\\nrequires_openai_auth = true\\nsupports_websockets = false\\n'\n printf '# <<< orca-cloud managed\\n'\n fi\n } >\"$next\"\n if ! grep -qF \"[projects.\\\"$PROJECT\\\"]\" \"$user_part\"; then\n printf '\\n# >>> orca-cloud managed trust\\n[projects.\"%s\"]\\ntrust_level = \"trusted\"\\n# <<< orca-cloud managed\\n' \"$PROJECT\" >>\"$next\"\n fi\n chmod 600 \"$next\"\n mv -f \"$next\" \"$codex_config\"\n rm -f \"$user_part\"\nfi\n# ---- Codex via the person's Orca account (contract D11): a placeholder ChatGPT login, no refresh token.\n# The egress proxy swaps the real access token on chatgpt.com; the real tokens never reach this VM. The\n# marker remembers which placeholder Orca wrote (a clone gets its own), so a login of the person's own\n# (kill-switch fallback, or `codex login` run here) is set aside while the account applies and put back after.\ncodex_auth=\"$HOME/.codex/auth.json\"\ncodex_saved=\"$HOME/.codex/auth.json.orca-saved\"\ncodex_marker=\"$HOME/.codex/.orca-account-placeholder\"\ncodex_ours=''\n# Ours: the marker's placeholder, or any Orca placeholder (all end in `.orca-placeholder`; a real token never does).\nif [ -f \"$codex_auth\" ] && { { [ -f \"$codex_marker\" ] && grep -qF \"\\\"$(cat \"$codex_marker\")\\\"\" \"$codex_auth\"; } || grep -q '\\.orca-placeholder\"' \"$codex_auth\"; }; then\n codex_ours=1\nfi\nif [ -n \"$codex_placeholder\" ]; then\n mkdir -p \"$HOME/.codex\"\n if [ -f \"$codex_auth\" ] && [ -z \"$codex_ours\" ]; then\n # Never overwrite a login already set aside: a second one gets its own name.\n if [ -e \"$codex_saved\" ]; then mv -f \"$codex_auth\" \"$codex_saved.$(date -u +%Y%m%d%H%M%S)\"; else mv -f \"$codex_auth\" \"$codex_saved\"; fi\n fi\n # Marker first: a run cut short after the swap still recognises the file as Orca's.\n printf '%s' \"$codex_placeholder\" >\"$codex_marker\"\n codex_tmp=\"$(mktemp \"$HOME/.codex/.auth.XXXXXX\")\"\n printf '{\\n \"OPENAI_API_KEY\": null,\\n \"tokens\": {\\n \"id_token\": \"%s\",\\n \"access_token\": \"%s\",\\n \"refresh_token\": \"\",\\n \"account_id\": null\\n },\\n \"last_refresh\": \"%s\"\\n}\\n' \\\n \"$codex_placeholder\" \"$codex_placeholder\" \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\" >\"$codex_tmp\"\n chmod 600 \"$codex_tmp\"\n mv -f \"$codex_tmp\" \"$codex_auth\"\nelif [ -f \"$codex_marker\" ] || [ -n \"$codex_ours\" ]; then\n if [ -n \"$codex_ours\" ]; then rm -f \"$codex_auth\"; fi\n rm -f \"$codex_marker\"\n if [ -f \"$codex_saved\" ] && [ ! -f \"$codex_auth\" ]; then mv -f \"$codex_saved\" \"$codex_auth\"; fi\nfi\n# ---- Claude Code, Gemini CLI, Cursor agent, Copilot CLI, OpenCode: first-run screens answered once\n# (Claude: theme picker, folder trust, bypass-mode warning, the \"use this API key?\" question; others:\n# folder trust, auth-method picker, self-update). A prompt delivered from the phone or the API has no one to click\n# through them, and the agent would sit there doing nothing. Merges; never touches credentials.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nif [ -n \"$node_bin\" ]; then\n ORCA_PROJECT=\"$PROJECT\" ORCA_KEY_TAIL=\"$anthropic_key_tail\" ORCA_GEMINI_KEY=\"$gemini_key\" \\\n ORCA_GATEWAY_MODEL=\"${gateway_key:+${anthropic_model:-$openai_model}}\" \"$node_bin\" -e '\nconst fs = require(\"fs\"), path = require(\"path\"), os = require(\"os\")\nconst home = os.homedir()\nconst readJson = (file) => { try { const v = JSON.parse(fs.readFileSync(file, \"utf8\")); return v && typeof v === \"object\" && !Array.isArray(v) ? v : {} } catch { return {} } }\nconst write = (file, value) => {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\nconst claudeFile = path.join(process.env.CLAUDE_CONFIG_DIR || home, \".claude.json\")\nconst c = readJson(claudeFile)\nconst before = JSON.stringify(c)\nc.hasCompletedOnboarding = true\nc.theme = c.theme || \"dark\"\nc.bypassPermissionsModeAccepted = true\nc.projects = c.projects && typeof c.projects === \"object\" ? c.projects : {}\nconst p = process.env.ORCA_PROJECT\nc.projects[p] = { ...(c.projects[p] || {}), hasTrustDialogAccepted: true, hasCompletedProjectOnboarding: true }\nconst tail = process.env.ORCA_KEY_TAIL\nif (tail) {\n const r = c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\" ? c.customApiKeyResponses : {}\n const approved = Array.isArray(r.approved) ? r.approved : []\n const rejected = Array.isArray(r.rejected) ? r.rejected.filter((t) => t !== tail) : []\n c.customApiKeyResponses = { ...r, approved: approved.includes(tail) ? approved : [...approved, tail], rejected }\n}\nif (JSON.stringify(c) !== before) write(claudeFile, c)\nconst settingsFile = path.join(home, \".claude\", \"settings.json\")\nconst s = readJson(settingsFile)\nif (s.skipDangerousModePermissionPrompt !== true) write(settingsFile, { ...s, skipDangerousModePermissionPrompt: true })\n\n// Each block below only fills in what is unset and leaves a file it cannot parse alone.\nconst readStrict = (file) => { try { return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, \"utf8\")) : {} } catch { return null } }\nconst isObject = (v) => v !== null && typeof v === \"object\" && !Array.isArray(v)\nconst section = (o, key) => (isObject(o[key]) ? o[key] : (o[key] = {}))\n\n// Gemini CLI: folder trust and the auth-method picker (only when a Gemini key is configured; a\n// Google sign-in picks its own method), no self-update, no usage stats (its host is not on the\n// egress allowlist, so every send would fail).\nconst geminiTrustFile = path.join(home, \".gemini\", \"trustedFolders.json\")\nconst geminiTrust = readStrict(geminiTrustFile)\nif (isObject(geminiTrust) && !geminiTrust[p]) write(geminiTrustFile, { ...geminiTrust, [p]: \"TRUST_FOLDER\" })\nconst geminiSettingsFile = path.join(home, \".gemini\", \"settings.json\")\nconst g = readStrict(geminiSettingsFile)\nif (isObject(g)) {\n const gBefore = JSON.stringify(g)\n const general = section(g, \"general\")\n general.disableAutoUpdate ??= true\n general.disableUpdateNag ??= true\n section(g, \"privacy\").usageStatisticsEnabled ??= false\n // gemini-api-key or vertex-ai (GOOGLE_GENAI_USE_VERTEXAI=true with an API key): headless runs\n // refuse to start without a method (\"Invalid auth method selected\").\n if (process.env.ORCA_GEMINI_KEY) section(section(g, \"security\"), \"auth\").selectedType ??= process.env.ORCA_GEMINI_KEY\n if (JSON.stringify(g) !== gBefore) write(geminiSettingsFile, g)\n}\n\n// Cursor agent: trust the workspace (cursor-agent keys trust by a slug of the path) and pin the\n// release channel to \"static\", which turns off its background self-update.\nconst cursorTrust = path.join(home, \".cursor\", \"projects\", p.replace(/^\\/+/, \"\").replace(/[^A-Za-z0-9]+/g, \"-\"), \".workspace-trusted\")\nif (!fs.existsSync(cursorTrust)) {\n fs.mkdirSync(path.dirname(cursorTrust), { recursive: true, mode: 0o700 })\n fs.writeFileSync(cursorTrust, JSON.stringify({ trustedAt: new Date().toISOString(), workspacePath: p }, null, 2) + \"\\n\", { mode: 0o600 })\n}\nconst cursorConfigFile = path.join(home, \".cursor\", \"cli-config.json\")\nconst cc = readStrict(cursorConfigFile)\nif (isObject(cc) && cc.channel === undefined) write(cursorConfigFile, { version: 1, ...cc, channel: \"static\" })\n\n// GitHub Copilot CLI: trusted folders live in ~/.copilot/config.json, which Copilot prefixes with\n// \"//\" comment lines; keep them.\nconst copilotFile = path.join(home, \".copilot\", \"config.json\")\nlet copilotHead = \"\"\nlet co = {}\ntry {\n const raw = fs.existsSync(copilotFile) ? fs.readFileSync(copilotFile, \"utf8\") : \"\"\n const lines = raw.split(\"\\n\")\n let i = 0\n while (i < lines.length && /^\\s*\\/\\//.test(lines[i])) i++\n copilotHead = lines.slice(0, i).map((l) => l + \"\\n\").join(\"\")\n const body = lines.slice(i).join(\"\\n\").trim()\n co = body ? JSON.parse(body) : {}\n} catch { co = null }\nif (isObject(co)) {\n const folders = Array.isArray(co.trustedFolders) ? co.trustedFolders : []\n if (!folders.includes(p)) {\n fs.mkdirSync(path.dirname(copilotFile), { recursive: true, mode: 0o700 })\n const tmp = `${copilotFile}.orca-${process.pid}`\n fs.writeFileSync(tmp, copilotHead + JSON.stringify({ ...co, trustedFolders: [...folders, p] }, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, copilotFile)\n }\n}\n\n// OpenCode: with the AI Gateway preset and a model secret (ANTHROPIC_MODEL, else OPENAI_MODEL), use\n// that model through the gateway unless the user picked one. A ledger remembers what Orca wrote, so a\n// changed model secret updates it and a model the user set is never touched.\nconst ocDir = path.join(home, \".config\", \"opencode\")\nconst ocFile = path.join(ocDir, \"opencode.json\")\nconst ocLedger = path.join(ocDir, \".orca-managed-model\")\nconst managedModel = process.env.ORCA_GATEWAY_MODEL ? `vercel/${process.env.ORCA_GATEWAY_MODEL}` : \"\"\nconst oc = readStrict(ocFile)\nlet jsoncHasModel = false\ntry { jsoncHasModel = /\"model\"\\s*:/.test(fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\")) } catch {}\nif (isObject(oc) && !jsoncHasModel) {\n let ours = \"\"\n try { ours = fs.readFileSync(ocLedger, \"utf8\").trim() } catch {}\n const userModel = typeof oc.model === \"string\" && oc.model !== ours\n if (!userModel && (oc.model ?? \"\") !== managedModel) {\n const next = { $schema: \"https://opencode.ai/config.json\", ...oc }\n if (managedModel) next.model = managedModel\n else delete next.model\n write(ocFile, next)\n }\n if (!userModel) {\n if (managedModel) fs.writeFileSync(ocLedger, managedModel + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocLedger, { force: true })\n }\n}\n\n// OpenCode: two built-in providers cannot work in Orca Cloud, and with no other credential OpenCode\n// picks one and fails (\"Authorization header is badly formatted\" / opencode.ai unreachable) instead\n// of showing \"Connect a provider\". GitHub Copilot reads GITHUB_TOKEN, which here is the stand-in for the\n// GitHub App token of the workspace, never a Copilot token; OpenCode Zen needs opencode.ai, which is not on the\n// egress allowlist. Both stay off unless the user connected them in OpenCode itself (auth.json).\nconst ocAuth = readStrict(path.join(process.env.XDG_DATA_HOME || path.join(home, \".local\", \"share\"), \"opencode\", \"auth.json\"))\nconst connected = new Set(isObject(ocAuth) ? Object.keys(ocAuth) : [])\nconst ocDisabledLedger = path.join(ocDir, \".orca-managed-disabled-providers\")\nconst ocNow = readStrict(ocFile)\nif (isObject(ocNow) && !/\"disabled_providers\"\\s*:/.test((() => { try { return fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\") } catch { return \"\" } })())) {\n let ours = []\n try { ours = fs.readFileSync(ocDisabledLedger, \"utf8\").split(\"\\n\").filter(Boolean) } catch {}\n const userList = (Array.isArray(ocNow.disabled_providers) ? ocNow.disabled_providers : []).filter((id) => typeof id === \"string\" && !ours.includes(id))\n const managed = [\"github-copilot\", \"opencode\"].filter((id) => !connected.has(id) && !userList.includes(id))\n const next = [...userList, ...managed]\n const before = JSON.stringify(ocNow.disabled_providers ?? [])\n if (JSON.stringify(next) !== before) {\n const updated = { $schema: \"https://opencode.ai/config.json\", ...ocNow }\n if (next.length > 0) updated.disabled_providers = next\n else delete updated.disabled_providers\n write(ocFile, updated)\n }\n if (managed.length > 0) fs.writeFileSync(ocDisabledLedger, managed.join(\"\\n\") + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocDisabledLedger, { force: true })\n}\n' || echo 'agent first-run state not seeded' >&2\nfi\nprintf '{\"names\":%d}\\n' \"$count\"\n","orca-session-env.sh":"# Orca Cloud: sourced by every new bash/zsh (via /etc/profile.d) so terminals and agents started\n# after a secret edit get the current values with no restart. The file is written by\n# /opt/orca/bin/orca-sandbox-env on tmpfs; names it no longer lists are unset. Cloud secrets win\n# over same-named values already in the environment.\n__orca_env_file=\"/dev/shm/orca-env-$(id -u 2>/dev/null)/session.env\"\nif [ -r \"$__orca_env_file\" ]; then\n # $(...) word-splits in both bash and zsh.\n for __orca_n in $(printf '%s' \"${ORCA_SESSION_ENV_NAMES-}\"); do\n unset \"$__orca_n\" 2>/dev/null || true\n done\n __orca_names=''\n while IFS= read -r __orca_line || [ -n \"$__orca_line\" ]; do\n __orca_n=\"${__orca_line%%=*}\"\n case \"$__orca_n\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n export \"$__orca_n=$(printf '%s' \"${__orca_line#*=}\" | base64 -d 2>/dev/null)\"\n __orca_names=\"$__orca_names $__orca_n\"\n done <\"$__orca_env_file\"\n export ORCA_SESSION_ENV_NAMES=\"${__orca_names# }\"\nfi\n# Default branch of the cloud workspace repo, once its first-boot clone exists (computed once per shell tree).\nif [ -n \"${ORCA_WORKSPACE_PATH-}\" ] && [ -z \"${ORCA_DEFAULT_BRANCH-}\" ]; then\n __orca_branch=\"$(git -C \"$ORCA_WORKSPACE_PATH\" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)\"\n if [ -n \"$__orca_branch\" ]; then\n export ORCA_DEFAULT_BRANCH=\"${__orca_branch#origin/}\" CONDUCTOR_DEFAULT_BRANCH=\"${__orca_branch#origin/}\"\n fi\nfi\nunset __orca_env_file __orca_line __orca_n __orca_names __orca_branch\n","orca-env":"#!/usr/bin/env bash\n# Prints shell lines that bring the current shell up to date with this session's cloud env (secrets\n# saved after the shell started): eval \"$(orca-env)\" or, in fish: orca-env --fish | source\n# Reads /dev/shm/orca-env-/session.env (written by orca-sandbox-env, `NAME=` lines) and\n# prints an export for each name, plus an unset for each name in $ORCA_SESSION_ENV_NAMES that is gone.\n# Never writes a file. Values are single-quoted, so quotes, newlines and $ in them stay literal.\nset -euo pipefail\nfish=''\ncase \"${1-}\" in\n '') ;;\n --fish) fish=1 ;;\n -h | --help)\n printf 'usage: eval \"$(orca-env)\" (fish: orca-env --fish | source)\\n'\n exit 0\n ;;\n *)\n printf 'orca-env: unknown option %s\\n' \"$1\" >&2\n exit 2\n ;;\nesac\n# ORCA_SESSION_ENV_FILE is for tests; secrets can't set ORCA_* names.\nfile=\"${ORCA_SESSION_ENV_FILE:-/dev/shm/orca-env-$(id -u)/session.env}\"\nset -f # names are split below, never globbed\n# Not written yet (or not a cloud VM): nothing to change, like the shell hook.\n[ -r \"$file\" ] || exit 0\n\n# 'it'\\''s' for POSIX shells; fish single quotes escape only \\ and '.\nquote() {\n local v=\"$1\"\n if [ -n \"$fish\" ]; then\n v=\"${v//\\\\/\\\\\\\\}\"\n v=\"${v//\\'/\\\\\\'}\"\n printf \"'%s'\" \"$v\"\n else\n printf \"'%s'\" \"${v//\\'/\\'\\\\\\'\\'}\"\n fi\n}\n\n# The control plane's reserved names and prefixes (cloud/apps/sandbox-control/src/secrets.ts; a test\n# keeps this in sync): a session file never sets what would hijack the shell or Orca's own processes.\nskip_name() {\n case \"$1\" in\n '' | *[!A-Z0-9_]* | [0-9]*) return 0 ;;\n LD_* | DYLD_* | ORCA_* | VERCEL_* | BASH_FUNC_* | GIT_CONFIG*) return 0 ;;\n PATH | HOME | USER | LOGNAME | SHELL | PWD | OLDPWD | LANG | TERM | TMPDIR | IFS | ENV | \\\n BASH_ENV | PS4 | PROMPT_COMMAND | SHELLOPTS | BASHOPTS | NODE_OPTIONS | NODE_PATH | \\\n NODE_EXTRA_CA_CERTS | NODE_TLS_REJECT_UNAUTHORIZED | SSL_CERT_FILE | SSL_CERT_DIR | \\\n CURL_CA_BUNDLE | REQUESTS_CA_BUNDLE | HTTP_PROXY | HTTPS_PROXY | ALL_PROXY | NO_PROXY | \\\n PYTHONPATH | PYTHONSTARTUP | PERL5OPT | RUBYOPT | JAVA_TOOL_OPTIONS | GIT_SSH | \\\n GIT_SSH_COMMAND | GIT_ASKPASS | GIT_EXEC_PATH | GIT_PROXY_COMMAND | SSH_AUTH_SOCK | \\\n GH_TOKEN | GITHUB_TOKEN) return 0 ;;\n # CLAUDE_CODE_OAUTH_TOKEN is reserved for users but set by the control plane itself: only ever the\n # Orca-account placeholder (contract D10), never a stored value.\n esac\n return 1\n}\n\nnames=' '\nwhile IFS= read -r line || [ -n \"$line\" ]; do\n name=\"${line%%=*}\"\n skip_name \"$name\" && continue\n # $(...) drops trailing newlines; the x keeps them.\n value=\"$(printf '%s' \"${line#*=}\" | base64 -d 2>/dev/null; printf x)\"\n value=\"${value%x}\"\n if [ -n \"$fish\" ]; then\n printf 'set -gx %s %s\\n' \"$name\" \"$(quote \"$value\")\"\n else\n printf 'export %s=%s\\n' \"$name\" \"$(quote \"$value\")\"\n fi\n names=\"$names$name \"\ndone <\"$file\"\nfor name in ${ORCA_SESSION_ENV_NAMES-}; do\n skip_name \"$name\" && continue\n case \"$names\" in *\" $name \"*) continue ;; esac\n if [ -n \"$fish\" ]; then\n printf 'set -e %s\\n' \"$name\"\n else\n printf 'unset %s\\n' \"$name\"\n fi\ndone\nnames=\"${names# }\"\nnames=\"${names% }\"\nif [ -n \"$fish\" ]; then\n printf 'set -gx ORCA_SESSION_ENV_NAMES %s\\n' \"$(quote \"$names\")\"\nelse\n printf 'export ORCA_SESSION_ENV_NAMES=%s\\n' \"$(quote \"$names\")\"\nfi\n","orca-egress-probe":"#!/usr/bin/env bash\n# Bounded Node fetch against each credential host. Vercel transform rules have made undici hang on\n# response bodies (no content-length / transfer-encoding); report it instead of letting agents hang.\n# Prints one JSON line: {\"host\":\"api.github.com\",\"status\":\"ok\"|\"egress_framing_hang\"|\"error\"}.\nset -euo pipefail\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\nfor host in \"$@\"; do\n \"$node\" -e '\n const host = process.argv[1]\n const timer = setTimeout(() => { console.log(JSON.stringify({ host, status: \"egress_framing_hang\" })); process.exit(0) }, 8000)\n fetch(`https://${host}/`, { headers: { authorization: process.env.ORCA_PROBE_AUTHORIZATION ?? \"\" } })\n .then((r) => r.arrayBuffer())\n .then(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"ok\" })) })\n .catch(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"error\" })) })\n ' \"$host\"\ndone\n","orca-image-wipe":"#!/usr/bin/env bash\n# Runs last before the golden snapshot. Every sandbox cloned from the image must start without an\n# orcad identity, device registry, agent sign-in or shell history (clone-safe identity, risk #1).\nset -euo pipefail\npkill -f orcad-server.js 2>/dev/null || true\nfor path in \\\n \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\" \"$HOME/.orca-desktop\" \"$HOME/.config/orca\" \"$HOME/.config/orca-dev\" \\\n \"$HOME/.claude\" \"$HOME/.claude.json\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.gemini\" \\\n \"$HOME/.local/share/opencode\" \"$HOME/.config/opencode\" \"$HOME/.cursor\" \"$HOME/.config/cursor\" \\\n \"$HOME/.local/share/cursor-agent\" \"$HOME/.copilot\" \"$HOME/.npm\" \"$HOME/.cache\" \"$HOME/.config/google-chrome\" \"$HOME/.bash_history\" \\\n /vercel/sandbox/project; do\n rm -rf -- \"$path\"\ndone\nsudo rm -rf /tmp/* /var/tmp/* 2>/dev/null || true\nfor leftover in \"$HOME/.orcad-data\" \"$HOME/.claude\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.cursor\" \"$HOME/.copilot\" \"$HOME/.gemini\"; do\n if [ -e \"$leftover\" ]; then\n echo \"identity survived wipe: $leftover\" >&2\n exit 1\n fi\ndone\necho '{\"wiped\":true}'\n","orca-agent-signout":"#!/usr/bin/env bash\n# Signs every agent out on this sandbox before Orca deletes it (A9): each agent's own logout, then\n# its credential files. Covers logins made inside the sandbox (the kill-switch fallback path).\n# Never fails: the sandbox is deleted next whatever happens. Values are never printed.\nset -u\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\nexport PATH=\"/opt/orca/tools/bin:$HOME/.local/bin:$HOME/.npm-global/bin:/usr/local/bin:/usr/bin:/bin:/opt/orca/bin:${PATH:-}\"\nclaude_dir=\"${CLAUDE_CONFIG_DIR:-$HOME/.claude}\"\nclaude_json=\"${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json\"\ncodex_dir=\"${CODEX_HOME:-$HOME/.codex}\"\n\nlogged_out=0\n# Each logout gets a few seconds; a hung CLI must not hold up the delete.\nif command -v claude >/dev/null 2>&1 && timeout 8 claude auth logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\nif command -v codex >/dev/null 2>&1 && timeout 8 codex logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\n\n# The files go whether or not a logout ran: an older CLI, a missing binary or no network leaves them.\nrm -f -- \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\" 2>/dev/null\n# Orca-managed Codex homes keep their own auth.json under orcad's data dir.\nif [ -d \"$HOME/.orcad-data\" ]; then\n find \"$HOME/.orcad-data\" -path '*codex*' -type f -name auth.json -delete 2>/dev/null\nfi\n# ~/.claude.json keeps settings Orca wrote (onboarding, trust); only the sign-in fields go.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nfor file in \"$claude_json\" \"$HOME/.claude.json\"; do\n [ -f \"$file\" ] || continue\n if [ -n \"$node_bin\" ]; then\n ORCA_FILE=\"$file\" \"$node_bin\" -e '\nconst fs = require(\"fs\")\nconst file = process.env.ORCA_FILE\nlet c\ntry { c = JSON.parse(fs.readFileSync(file, \"utf8\")) } catch { process.exit(2) }\nif (!c || typeof c !== \"object\" || Array.isArray(c)) process.exit(2)\nlet changed = false\nfor (const key of Object.keys(c)) {\n if (/oauth/i.test(key) || key === \"primaryApiKey\") { delete c[key]; changed = true }\n}\nif (changed) {\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(c, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\n' 2>/dev/null || rm -f -- \"$file\"\n else\n # No node to edit it safely: losing Orca's settings beats leaving a sign-in behind.\n rm -f -- \"$file\"\n fi\ndone\n\nleft=0\nfor file in \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\"; do\n [ -e \"$file\" ] && left=$((left + 1))\ndone\nprintf '{\"loggedOut\":%d,\"left\":%d}\\n' \"$logged_out\" \"$left\"\n","orca-share-proxy":"#!/usr/bin/env node\n// Share-link proxy for this VM. Listens on 0.0.0.0:6769 (its public *.vercel.run route) and only\n// serves requests the control plane's share gateway signed with this session's key:\n// x-orca-share: v2.....\n// A request must start before `expiresAt` (60s windows); its response or WebSocket is closed at\n// `until` (the link's expiry, at most 30 minutes out), so a revoked or expired link also loses open\n// streams. Signed requests are reverse-proxied to 127.0.0.1:: streaming both ways, no\n// buffering, WebSocket upgrades piped raw. Anything unsigned gets a bare 404.\n// The key arrives on stdin (orca-sandbox-start pipes it), so it is never in this process's\n// environment or argv; ORCA_SHARE_PROXY_KEY in the env is accepted for tests. Optional\n// ORCA_SHARE_PROXY_PORT (default 6769). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst crypto = process.getBuiltinModule('node:crypto')\nconst fs = process.getBuiltinModule('node:fs')\nconst http = process.getBuiltinModule('node:http')\nconst net = process.getBuiltinModule('node:net')\n\nconst LISTEN_PORT = Number(process.env.ORCA_SHARE_PROXY_PORT || 6769)\nconst KEY = Buffer.from((process.env.ORCA_SHARE_PROXY_KEY || fs.readFileSync(0, 'utf8')).trim(), 'base64url')\ndelete process.env.ORCA_SHARE_PROXY_KEY\n// Never proxy to the VM's sshd, orcad or this proxy itself.\n// 6080: the remote desktop (VNC behind a password) is for its owner's forward only.\nconst BLOCKED_PORTS = new Set([2222, 6080, 6768, LISTEN_PORT])\nconst MAX_SKEW_SECONDS = 300\nconst MAX_CONNECTION_SECONDS = 3600\nconst HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'te', 'trailer', 'upgrade']\n\nif (KEY.length < 32) {\n console.error('orca-share-proxy: share proxy key missing or short')\n process.exit(2)\n}\n\n/** The target port and close-by time (ms) for a validly signed request, else null. */\nfunction verify(header, nowMs) {\n if (typeof header !== 'string') {\n return null\n }\n const match = /^v2\\.(\\d{1,5})\\.(\\d{1,12})\\.(\\d{1,12})\\.([0-9a-f]{32})\\.([A-Za-z0-9_-]{43})$/.exec(header)\n if (!match) {\n return null\n }\n const now = Math.floor(nowMs / 1000)\n const port = Number(match[1])\n const expiresAt = Number(match[2])\n const until = Number(match[3])\n if (port < 1 || port > 65535 || BLOCKED_PORTS.has(port)) {\n return null\n }\n if (expiresAt < now || expiresAt > now + MAX_SKEW_SECONDS || until <= now || until > now + MAX_CONNECTION_SECONDS) {\n return null\n }\n const signed = header.slice(0, header.lastIndexOf('.'))\n const expected = crypto.createHmac('sha256', KEY).update(signed).digest()\n const given = Buffer.from(match[5], 'base64url')\n return given.length === expected.length && crypto.timingSafeEqual(given, expected) ? { port, untilMs: until * 1000 } : null\n}\n\nfunction upstreamHeaders(raw, port) {\n const headers = { ...raw }\n const connectionTokens = String(raw.connection || '')\n .split(',')\n .map((token) => token.trim().toLowerCase())\n for (const name of [...HOP_BY_HOP, ...connectionTokens, 'x-orca-share']) {\n delete headers[name]\n }\n // Dev servers (Vite, Next) allow localhost hosts by default; the public host rides x-forwarded-host.\n headers.host = `localhost:${port}`\n return headers\n}\n\nfunction refuse(res) {\n res.writeHead(404, { 'content-type': 'text/plain', 'cache-control': 'no-store' })\n res.end('not found')\n}\n\n/** Ends `close` at the grant's deadline; the timer goes away with the connection. */\nfunction deadline(untilMs, close, ...emitters) {\n const timer = setTimeout(close, Math.max(0, untilMs - Date.now()))\n for (const emitter of emitters) {\n emitter.once('close', () => clearTimeout(timer))\n }\n}\n\nconst server = http.createServer((req, res) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n return refuse(res)\n }\n const { port } = grant\n const upstream = http.request(\n { host: '127.0.0.1', port, method: req.method, path: req.url, headers: upstreamHeaders(req.headers, port) },\n (answer) => {\n const headers = { ...answer.headers }\n for (const name of HOP_BY_HOP) {\n delete headers[name]\n }\n // Marks the answer as the app's, so the gateway can tell it from a route with no proxy behind it.\n headers['x-orca-share-proxy'] = '1'\n res.writeHead(answer.statusCode || 502, answer.statusMessage, headers)\n answer.pipe(res)\n }\n )\n deadline(grant.untilMs, () => {\n upstream.destroy()\n res.destroy()\n }, res)\n upstream.on('error', (error) => {\n if (res.headersSent) {\n res.destroy()\n return\n }\n // The gateway renders its own page for this; the code tells it why. Status 200 on purpose: a 5xx\n // from the VM reaches a Worker as Vercel's own 502 with our headers gone (found live).\n res.writeHead(200, { 'content-type': 'text/plain', 'x-orca-share-proxy': '1', 'x-orca-share-error': error.code === 'ECONNREFUSED' ? 'no_listener' : 'upstream_failed' })\n res.end('upstream unavailable')\n })\n req.on('aborted', () => upstream.destroy())\n req.pipe(upstream)\n})\n\nserver.on('upgrade', (req, socket, head) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n socket.end('HTTP/1.1 404 Not Found\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n return\n }\n const { port } = grant\n const headers = upstreamHeaders(req.headers, port)\n const target = net.connect(port, '127.0.0.1', () => {\n const lines = [`${req.method} ${req.url} HTTP/1.1`, `connection: upgrade`, `upgrade: ${req.headers.upgrade || 'websocket'}`]\n for (const [name, value] of Object.entries(headers)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n lines.push(`${name}: ${item}`)\n }\n }\n target.write(`${lines.join('\\r\\n')}\\r\\n\\r\\n`)\n if (head && head.length > 0) {\n target.write(head)\n }\n socket.pipe(target)\n target.pipe(socket)\n })\n const close = () => {\n socket.destroy()\n target.destroy()\n }\n deadline(grant.untilMs, close, socket)\n target.on('error', () => {\n if (socket.writable) {\n socket.end('HTTP/1.1 200 OK\\r\\nx-orca-share-proxy: 1\\r\\nx-orca-share-error: no_listener\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n }\n close()\n })\n socket.on('error', close)\n target.on('close', () => socket.destroy())\n socket.on('close', () => target.destroy())\n})\n\nserver.keepAliveTimeout = 65_000\nserver.headersTimeout = 70_000\n// No request timeout: previews can stream (SSE, long polls) until the grant's deadline.\nserver.requestTimeout = 0\nserver.listen(LISTEN_PORT, '0.0.0.0', () => {\n console.log(`orca-share-proxy listening on ${LISTEN_PORT}`)\n})\n","orca-sshd":"#!/usr/bin/env bash\n# Starts this boot's unprivileged sshd on 127.0.0.1:2222 (idempotent). Nothing outside the VM can\n# reach that port: the desktop tunnels to it over orcad's runtime connection (`orca ssh-proxy`).\n# Key-only, single user (the sandbox user), no root. Its host key and authorized_keys live under\n# ~/.orca-sandbox/ssh on the persistent disk, so the host key stays the same across stop/resume;\n# orca-image-wipe removes that directory, so every VM cloned from the golden image makes its own.\n# Prints {\"port\":2222,\"user\":\"\",\"hostKey\":\"ssh-ed25519 AAAA...\"} on success.\nset -euo pipefail\numask 077\nOPENSSH=/opt/orca/openssh\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\nPORT=2222\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 8>\"$SSH_DIR/sshd.lock\"\nflock -w 30 8\n\nif [ ! -x \"$OPENSSH/sshd\" ]; then\n echo 'sshd is not installed in this image' >&2\n exit 3\nfi\nif [ ! -s \"$SSH_DIR/ssh_host_ed25519_key\" ]; then\n rm -f \"$SSH_DIR/ssh_host_ed25519_key\" \"$SSH_DIR/ssh_host_ed25519_key.pub\"\n ssh-keygen -q -t ed25519 -N '' -C \"orca-cloud-host\" -f \"$SSH_DIR/ssh_host_ed25519_key\"\nfi\ntouch \"$SSH_DIR/authorized_keys\"\nchmod 0600 \"$SSH_DIR/authorized_keys\"\n\n# Rewritten every start so an image update's settings apply to existing workspaces. PAM stays at\n# its compiled-in default (off): an unprivileged sshd cannot use it, and this build warns on `no`.\ncat >\"$SSH_DIR/sshd_config\" </dev/null || echo 0)\"\n# Resume reboots from disk, so a recorded pid can name a dead process or an unrelated one.\nif ! { kill -0 \"$pid\" 2>/dev/null && grep -q sshd \"/proc/$pid/cmdline\" 2>/dev/null; }; then\n rm -f \"$SSH_DIR/sshd.pid\"\n : >\"$SSH_DIR/sshd.log\"\n \"$OPENSSH/sshd\" -t -f \"$SSH_DIR/sshd_config\"\n \"$OPENSSH/sshd\" -f \"$SSH_DIR/sshd_config\" -E \"$SSH_DIR/sshd.log\"\n for _ in $(seq 1 100); do\n [ -s \"$SSH_DIR/sshd.pid\" ] && break\n sleep 0.02\n done\n [ -s \"$SSH_DIR/sshd.pid\" ] || { echo 'sshd did not start' >&2; tail -n 20 \"$SSH_DIR/sshd.log\" >&2; exit 1; }\nfi\n\nhost_key=\"$(cut -d' ' -f1-2 \"$SSH_DIR/ssh_host_ed25519_key.pub\")\"\nprintf '{\"port\":%s,\"user\":\"%s\",\"hostKey\":\"%s\"}\\n' \"$PORT\" \"$(id -un)\" \"$host_key\"\n","orca-ssh-keys":"#!/usr/bin/env bash\n# `orca-ssh-keys add|remove`: adds or removes one desktop's key in the Orca-managed authorized_keys\n# of this VM's sshd, then makes sure sshd runs. The control plane passes the key in\n# ORCA_SSH_PUBLIC_KEY (`ssh-ed25519 `), never on the command line. Keys are\n# matched by their base64 blob, so a renamed comment cannot keep a revoked key alive.\n# Prints orca-sshd's {\"port\":...,\"user\":...,\"hostKey\":...} line on success.\nset -euo pipefail\numask 077\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\naction=\"${1:-}\"\nkey=\"${ORCA_SSH_PUBLIC_KEY:-}\"\n# grep matches per line: a second line could carry key options past the check below.\ncase \"$key\" in *$'\\n'* | *$'\\r'*) echo 'invalid public key' >&2; exit 2 ;; esac\n# One line, ed25519 only, a plain comment: nothing that sshd would read as key options.\nif ! printf '%s' \"$key\" | grep -Eq '^ssh-ed25519 [A-Za-z0-9+/]{68} [A-Za-z0-9@._:+-]{1,200}$'; then\n echo 'invalid public key' >&2\n exit 2\nfi\nblob=\"$(printf '%s' \"$key\" | cut -d' ' -f2)\"\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 7>\"$SSH_DIR/keys.lock\"\nflock -w 30 7\ntouch \"$SSH_DIR/authorized_keys\"\nnext=\"$(mktemp \"$SSH_DIR/authorized_keys.XXXXXX\")\"\n# Drop the key wherever it appears (with or without options), then append it on add.\nawk -v blob=\"$blob\" '{ for (i = 1; i <= NF; i++) if ($i == blob) next; print }' \\\n \"$SSH_DIR/authorized_keys\" >\"$next\"\ncase \"$action\" in\n add) printf '%s\\n' \"$key\" >>\"$next\" ;;\n remove) ;;\n *) rm -f \"$next\"; echo 'usage: orca-ssh-keys add|remove' >&2; exit 2 ;;\nesac\nchmod 0600 \"$next\"\nmv -f \"$next\" \"$SSH_DIR/authorized_keys\"\nexec /opt/orca/bin/orca-sshd\n","orca-desktop-start":"#!/usr/bin/env bash\n# Starts the on-demand remote desktop (idempotent) and mints one connection ticket. Prints one line:\n# {\"schemaVersion\":2,\"port\":6080,\"display\":\":1\",\"path\":\"vnc.html\",\"ticket\":\"<43 chars>\",\"expiresInMs\":60000}\n# Xvnc (X server + VNC in one) listens on a 0600 unix socket only, with no VNC auth: only this uid\n# can open it. orca-desktop-proxy (websockify + a ticket gate) serves noVNC on 127.0.0.1 and\n# bridges WebSockets to that socket. Nothing is reachable from outside the VM: the desktop app\n# reaches it through Orca's port forward, a localhost port on the user's computer that any local\n# process or web page can reach, so each WebSocket needs a ticket from here: 32 random bytes,\n# single use, valid for 60 s, stored only as its sha256 (the file name; its content is the expiry).\n# The ticket goes to stdout only (the control plane hands it to the desktop app). Never started at boot.\nset -euo pipefail\numask 077\nDESKTOP=/opt/orca/desktop\nSTATE=\"$HOME/.orca-desktop\"\nPORT=\"${ORCA_DESKTOP_PORT:-6080}\"\nDISPLAY_NUM=\"${ORCA_DESKTOP_DISPLAY:-1}\"\nGEOMETRY=\"${ORCA_DESKTOP_GEOMETRY:-1280x800}\"\nSOCKET=\"$STATE/vnc.sock\"\n# The parent's DISPLAY must not leak into the WM/xterm below; they use ours.\nexport DISPLAY=\":$DISPLAY_NUM\"\n\n# Exit 3 = this image has no desktop (built before it, or its optional install failed).\nfail() { printf 'orca-desktop: %s\\n' \"$1\" >&2; exit \"${2:-1}\"; }\ncase \"$PORT\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_PORT must be a number' ;; esac\ncase \"$DISPLAY_NUM\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_DISPLAY must be a number' ;; esac\ncase \"$GEOMETRY\" in [0-9]*x[0-9]*) ;; *) fail 'ORCA_DESKTOP_GEOMETRY must look like 1280x800' ;; esac\ncommand -v Xvnc >/dev/null || fail 'not installed in this image (Xvnc missing)' 3\n[ -s \"$DESKTOP/novnc/vnc.html\" ] || fail 'not installed in this image (noVNC missing)' 3\nPROXY=\"$(dirname \"$(readlink -f \"$0\")\")/orca-desktop-proxy\"\n[ -x \"$PROXY\" ] || fail 'orca-desktop-proxy missing next to this script'\nTICKETS=\"$STATE/tickets\"\nTICKET_TTL_S=60\n# Xvnc's mode: a previous version of this script ran it with VncAuth; restart it in this mode.\nMODE=ticket-v1\n\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/start.lock\"\nflock -w 30 9 || fail 'another start is in progress'\n\npid_of() { # never \"0\": kill 0 targets our own process group\n local pid\n pid=\"$(cat \"$STATE/$1.pid\" 2>/dev/null || true)\"\n case \"$pid\" in '' | 0 | *[!0-9]*) return 1 ;; esac\n printf '%s' \"$pid\"\n}\nalive() { local pid; pid=\"$(pid_of \"$1\")\" && kill -0 \"$pid\" 2>/dev/null; }\nmint_ticket() { # prints the ticket; stores only its sha256, with the expiry as content\n local ticket now digest\n mkdir -p \"$TICKETS\"\n now=\"$(date +%s)\"\n # Expired or spent-but-unswept tickets; keep at most 16 live ones (oldest go first).\n for file in \"$TICKETS\"/*; do\n [ -f \"$file\" ] || continue\n [ \"$(cat \"$file\" 2>/dev/null || echo 0)\" -ge \"$now\" ] 2>/dev/null || rm -f \"$file\"\n done\n # shellcheck disable=SC2012 # names are hex digests\n ls -1t \"$TICKETS\" 2>/dev/null | tail -n +16 | while read -r old; do rm -f \"$TICKETS/$old\"; done\n ticket=\"$(head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\\n')\"\n [ \"${#ticket}\" = 43 ] || fail 'could not generate a ticket'\n digest=\"$(printf '%s' \"$ticket\" | sha256sum | cut -d' ' -f1)\"\n printf '%s' \"$((now + TICKET_TTL_S))\" >\"$TICKETS/.$digest\" && mv \"$TICKETS/.$digest\" \"$TICKETS/$digest\"\n printf '%s' \"$ticket\"\n}\nready_line() {\n local ticket\n ticket=\"$(mint_ticket)\" || exit 1\n printf '{\"schemaVersion\":2,\"port\":%s,\"display\":\":%s\",\"path\":\"vnc.html\",\"ticket\":\"%s\",\"expiresInMs\":%s}\\n' \\\n \"$PORT\" \"$DISPLAY_NUM\" \"$ticket\" \"$((TICKET_TTL_S * 1000))\"\n}\nlistening() { # the proxy answers HTTP on loopback\n curl -fsS -o /dev/null --max-time 1 \"http://127.0.0.1:$PORT/vnc.html\" 2>/dev/null\n}\n\n# Pids from a previous boot (resume = reboot from disk) name dead or unrelated processes.\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" != \"$boot_id\" ]; then\n rm -rf \"$STATE\"/*.pid \"$SOCKET\" \"$STATE/password\" \"$STATE/passwd\" \"$STATE/mode\" \"$TICKETS\"\n printf '%s' \"$boot_id\" >\"$STATE/boot-id\"\nfi\n\n# Same boot, older script: its websockify had no ticket gate and its Xvnc wanted a VNC password.\nrm -f \"$STATE/password\" \"$STATE/passwd\"\nif alive websockify; then kill \"$(pid_of websockify)\" 2>/dev/null || true; fi\nrm -f \"$STATE/websockify.pid\"\ncurrent_mode() { cat \"$STATE/mode\" 2>/dev/null || true; }\n\nif alive xvnc && alive proxy && listening && [ \"$(current_mode)\" = \"$MODE\" ]; then\n ready_line\n exit 0\nfi\n\nstart() { # name cmd... — detached, logs in $STATE/.log\n local name=$1; shift\n # 9>&-: children must not inherit the start lock, or the next call waits for them to exit.\n setsid nohup \"$@\" >\"$STATE/$name.log\" 2>&1 &- &\n echo $! >\"$STATE/$name.pid\"\n}\n\nif ! alive xvnc || [ \"$(current_mode)\" != \"$MODE\" ]; then\n if alive xvnc; then kill \"$(pid_of xvnc)\" 2>/dev/null || true; sleep 0.2; fi\n rm -f \"$SOCKET\"\n # -rfbport -1: no TCP VNC port at all, only a 0600 unix socket (in the 0700 state dir) for the\n # proxy. SecurityTypes None is safe only because of that: the ticket gate is in the proxy.\n # SendPrimary=0: only explicit copies (xterm copies its selection, below) leave the sandbox.\n # The X display itself takes a cookie from ~/.Xauthority (Xlib's default for this user), so only\n # this uid's processes (agents, apps they start on DISPLAY=:1) can open it.\n auth=()\n if command -v xauth >/dev/null && command -v mcookie >/dev/null; then\n xauth -q -f \"$HOME/.Xauthority\" add \":$DISPLAY_NUM\" . \"$(mcookie)\" 9>&- && auth=(-auth \"$HOME/.Xauthority\")\n fi\n start xvnc Xvnc \":$DISPLAY_NUM\" \"${auth[@]}\" -geometry \"$GEOMETRY\" -depth 24 -nolisten tcp \\\n -rfbport -1 -rfbunixpath \"$SOCKET\" -rfbunixmode 0600 \\\n -SecurityTypes None -SendPrimary=0 \\\n -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote desktop'\n printf '%s' \"$MODE\" >\"$STATE/mode\"\n for _ in $(seq 1 100); do\n [ -S \"$SOCKET\" ] && break\n alive xvnc || { tail -n 20 \"$STATE/xvnc.log\" >&2; fail 'Xvnc exited'; }\n sleep 0.05\n done\n [ -S \"$SOCKET\" ] || fail 'Xvnc did not create its socket'\n if command -v xsetroot >/dev/null; then xsetroot -solid '#1e1f22' 9>&- || true; fi\n if command -v openbox >/dev/null; then\n # Dark, flat theme to match Orca; the first terminal stays maximized as the tab resizes the screen.\n printf '%s\\n' '' \\\n 'Onyx' \\\n 'yes' \\\n '' >\"$STATE/openbox.xml\"\n start wm openbox --config-file \"$STATE/openbox.xml\"\n # Let it manage the screen before the terminal maps, so its maximize rule applies.\n sleep 0.2\n elif command -v twm >/dev/null; then\n start wm twm\n fi\n if command -v xterm >/dev/null; then\n # selectToClipboard: a selection is a copy (to CLIPBOARD, which reaches this computer).\n start xterm xterm -maximized -bg '#1e1f22' -fg '#d4d4d4' -fa 'Liberation Mono,Monospace' -fs 11 \\\n -xrm 'XTerm*selectToClipboard: true'\n fi\nfi\n\nif ! alive proxy || ! listening; then\n if alive proxy; then kill \"$(pid_of proxy)\" 2>/dev/null || true; sleep 0.1; fi\n mkdir -p \"$TICKETS\"\n PYTHONPATH=\"$DESKTOP/websockify\" start proxy python3 -P -W ignore::UserWarning \"$PROXY\" \\\n --listen \"$PORT\" --web \"$DESKTOP/novnc\" --unix-target \"$SOCKET\" --tickets \"$TICKETS\"\n for _ in $(seq 1 100); do\n listening && break\n alive proxy || { tail -n 20 \"$STATE/proxy.log\" >&2; fail 'orca-desktop-proxy exited'; }\n sleep 0.05\n done\n listening || fail \"orca-desktop-proxy is not answering on 127.0.0.1:$PORT\"\nfi\nready_line\n","orca-desktop-proxy":"#!/usr/bin/env python3\n# Remote desktop gateway, started by orca-desktop-start: serves noVNC on 127.0.0.1 and bridges one\n# WebSocket per single-use ticket to Xvnc's 0600 unix socket (Xvnc itself has no VNC auth: only this\n# uid can open the socket). The port is reached only through Orca's localhost forward on the user's\n# computer, where any local process or web page could knock, so every WebSocket must carry an\n# unused, unexpired ticket minted by orca-desktop-start (see consume_ticket), from a page on the same\n# localhost origin. Tickets never reach a log: paths are scrubbed before websockify logs them.\n# orca-desktop-proxy --listen PORT --web DIR --unix-target SOCKET --tickets DIR\n# stdlib + websockify (pinned tarball in /opt/orca/desktop/websockify, on PYTHONPATH) only.\nimport argparse\nimport hashlib\nimport hmac\nimport logging\nimport os\nimport re\nimport sys\nimport time\nfrom urllib.parse import parse_qs, urlsplit\n\nfrom websockify import websocketproxy\n\nTICKET_RE = re.compile(r'^[A-Za-z0-9_-]{43}$') # 32 random bytes, base64url without padding\nSCRUB_RE = re.compile(r'([?&]ticket=)[^&\\s\\'\"]*')\nLOOPBACK_HOST_RE = re.compile(r'^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:[0-9]{1,5})?$')\nWS_PATH = '/websockify'\nPAGE_SCRIPT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'orca-desktop-page.js')\n# The page may only talk to its own origin (its WebSocket included): even a URL that tries to point\n# noVNC elsewhere cannot carry a ticket or the user's keys off this forward.\nPAGE_CSP = \"connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'\"\nPAGE_TAG = b'\\n'\n\n\ndef scrub(text):\n return SCRUB_RE.sub(r'\\1', str(text))\n\n\ndef ticket_digest(ticket):\n return hashlib.sha256(ticket.encode('ascii')).hexdigest()\n\n\ndef consume_ticket(directory, ticket, now=None):\n \"\"\"True once per minted ticket, within its lifetime. The ticket file (named by the ticket's\n sha256, holding its expiry) is unlinked on first use, so a replay or a racing second\n connection finds nothing; each request runs in its own forked process, so state is on disk.\"\"\"\n if not isinstance(ticket, str) or not TICKET_RE.match(ticket):\n return False\n digest = ticket_digest(ticket)\n match = None\n try:\n names = os.listdir(directory)\n except OSError:\n return False\n for name in names:\n # Compare every entry in constant time; never short-circuit on a prefix.\n if hmac.compare_digest(name.encode('ascii', 'replace'), digest.encode('ascii')):\n match = name\n if match is None:\n return False\n path = os.path.join(directory, match)\n try:\n with open(path, 'r', encoding='ascii') as handle:\n expires_at = int(handle.read().strip() or '0')\n except (OSError, ValueError):\n expires_at = 0\n try:\n os.unlink(path) # the consume: only one caller can win this\n except FileNotFoundError:\n return False\n return (now if now is not None else time.time()) <= expires_at\n\n\ndef same_loopback_origin(headers):\n \"\"\"The page and the WebSocket share one localhost origin (blocks other local sites and DNS\n rebinding). The port is the user's local forward, which may differ from ours, so compare the\n Origin with the Host the browser dialed rather than with a fixed port.\"\"\"\n host = (headers.get('Host') or '').strip().lower()\n origin = (headers.get('Origin') or '').strip().lower()\n return loopback_host(host) and origin == 'http://' + host\n\n\ndef loopback_host(host):\n return bool(LOOPBACK_HOST_RE.match(host or ''))\n\n\nclass TicketedProxyHandler(websocketproxy.ProxyRequestHandler):\n \"\"\"websockify's proxy handler plus the ticket + origin gate. Module level (not a closure) so\n websockify's per-connection multiprocessing can pickle it under any start method.\"\"\"\n\n def log_message(self, format, *args): # noqa: A002 (websockify's signature)\n super().log_message('%s', scrub(format % args if args else format))\n\n def reject(self, code, reason):\n self.send_response(code)\n self.send_header('Content-Length', '0')\n self.send_header('Connection', 'close')\n self.end_headers()\n self.close_connection = True\n raise self.server.EClose('desktop: websocket refused (%s)' % reason)\n\n def validate_connection(self):\n parts = urlsplit(self.path)\n ticket = (parse_qs(parts.query).get('ticket') or [''])[0]\n # Drop it before anything below (websockify's own logging included) can see self.path.\n self.path = parts.path\n if parts.path != WS_PATH:\n self.reject(404, 'path')\n if not same_loopback_origin(self.headers):\n self.reject(403, 'origin')\n if not consume_ticket(self.server.orca_tickets_dir, ticket):\n self.reject(403, 'ticket')\n\n def loopback_request(self):\n if loopback_host((self.headers.get('Host') or '').strip().lower()):\n return True\n self.send_error(403)\n return False\n\n def do_GET(self):\n if not self.loopback_request():\n return None\n path = urlsplit(self.path).path\n if path == '/orca-desktop-page.js':\n return self.send_bytes(read_file(PAGE_SCRIPT), 'text/javascript; charset=utf-8')\n if path == '/vnc.html':\n page = read_file(os.path.join(self.server.web, 'vnc.html'))\n return self.send_bytes(page.replace(b'', PAGE_TAG, 1), 'text/html; charset=utf-8', PAGE_CSP)\n return super().do_GET()\n\n def do_HEAD(self):\n if not self.loopback_request():\n return None\n return super().do_HEAD()\n\n def send_bytes(self, body, content_type, csp=None):\n self.send_response(200)\n self.send_header('Content-Type', content_type)\n if csp:\n self.send_header('Content-Security-Policy', csp)\n self.send_header('Content-Length', str(len(body)))\n self.send_header('Cache-Control', 'no-store')\n self.send_header('Referrer-Policy', 'no-referrer')\n self.end_headers()\n self.wfile.write(body)\n return None\n\n\ndef read_file(path):\n with open(path, 'rb') as handle:\n return handle.read()\n\n\ndef main(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--listen', type=int, required=True)\n parser.add_argument('--web', required=True)\n parser.add_argument('--unix-target', required=True)\n parser.add_argument('--tickets', required=True)\n args = parser.parse_args(argv)\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n server = websocketproxy.WebSocketProxy(\n RequestHandlerClass=TicketedProxyHandler,\n listen_host='127.0.0.1',\n listen_port=args.listen,\n web=args.web,\n file_only=True,\n unix_target=args.unix_target,\n )\n server.orca_tickets_dir = os.path.abspath(args.tickets)\n server.start_server()\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","orca-desktop-page.js":"// Orca's glue for noVNC, injected into vnc.html by orca-desktop-proxy. Orca (the desktop app's\n// main process) drives it through window.orcaDesktop:\n// - tickets: the page never connects by itself. Each WebSocket needs a fresh single-use ticket,\n// which Orca hands over with connect(ticket) after nextTicketRequest() resolves: 'ticket' on\n// load or after a session dropped, 'retry' after an attempt that never connected. Tickets live\n// only in memory here: never in the URL, storage or noVNC's settings.\n// - pause(message, label): Orca stopped retrying; show why, with a Reconnect button. resume()\n// (Orca reopened the desktop) or the button asks for a ticket again.\n// - fit: resize=remote makes Xvnc follow the tab; a server without SetDesktopSize gets scaling.\n// - clipboard: a copy inside the desktop right after user input there goes to this computer's\n// clipboard; paste(text, chord) sets the sandbox's clipboard first, then replays the paste key.\nimport UI from './app/ui.js';\nimport * as WebUtil from './app/webutil.js';\n\nconst WS_PATH = 'websockify';\nconst RESIZE_FALLBACK_MS = 1500;\n// A copy inside the desktop follows a copy key or a selection (drag or double-click) there; other\n// clipboard changes (an agent in the sandbox running xclip) must not overwrite this computer's\n// clipboard. Plain typing does not open the window.\nconst USER_COPY_WINDOW_MS = 1500;\nconst DRAG_PX = 4;\nconst MAX_CLIPBOARD_CHARS = 1 << 20;\nconst TICKET_RE = /^[A-Za-z0-9_-]{43}$/;\nconst XK = { v: 0x0076, V: 0x0056, Insert: 0xff63, Shift_L: 0xffe1, Super_L: 0xffeb, Super_R: 0xffec };\n\nlet state = 'idle'; // idle | connecting | connected | disconnected | paused\nlet attemptConnected = true;\nlet ticketWaiters = [];\nlet lastCopyIntent = 0;\nlet pointerStart = null;\n\nconst style = document.createElement('style');\n// Orca owns connecting and the chrome: noVNC's Connect button would only try without a ticket,\n// and its control bar duplicates what the Orca tab does (fit, clipboard, keyboard release).\n// The pause card follows Orca's theme: Orca sets Electron's theme source from its own setting, so\n// prefers-color-scheme here is Orca's light or dark, and it follows a switch while paused. The\n// page cannot read Orca's tokens, so these mirror them (popover, border, focus ring).\nstyle.textContent = `\n#noVNC_connect_dlg, #noVNC_control_bar_anchor { display: none !important; }\n#orca_pause { --orca-scrim: rgb(10 10 10 / 0.88); --orca-card: #171717; --orca-text: #f0f0f0;\n --orca-border: rgb(255 255 255 / 0.1); --orca-control: rgb(255 255 255 / 0.25);\n --orca-control-hover: rgb(255 255 255 / 0.08); --orca-focus: color-mix(in oklab, #f0f0f0 65%, #0a0a0a);\n color-scheme: dark; position: fixed; inset: 0; display: none; align-items: center;\n justify-content: center; padding: 16px; background: var(--orca-scrim); z-index: 1000;\n font: 13px/1.5 system-ui, sans-serif; }\n@media (prefers-color-scheme: light) {\n #orca_pause { --orca-scrim: rgb(255 255 255 / 0.88); --orca-card: #fff; --orca-text: #0a0a0a;\n --orca-border: #e5e5e5; --orca-control: #a3a3a3; --orca-control-hover: #f5f5f5;\n --orca-focus: color-mix(in oklab, #0a0a0a 55%, #fff); color-scheme: light; }\n}\n#orca_pause.open { display: flex; }\n#orca_pause > div { max-width: 360px; padding: 16px; border: 1px solid var(--orca-border);\n border-radius: 8px; background: var(--orca-card); color: var(--orca-text); text-align: center;\n box-shadow: 0 8px 24px rgb(0 0 0 / 0.16); }\n#orca_pause p { margin: 0; }\n#orca_pause button { margin-top: 12px; padding: 4px 12px; border: 1px solid var(--orca-control);\n border-radius: 6px; background: transparent; color: var(--orca-text); font: inherit; cursor: pointer; }\n#orca_pause button:hover { background: var(--orca-control-hover); }\n#orca_pause button:focus-visible { outline: 2px solid var(--orca-focus); outline-offset: 2px; }\n@media (prefers-reduced-motion: no-preference) {\n #orca_pause.open > div { animation: orca-pause-in 120ms ease-out; }\n}\n@keyframes orca-pause-in { from { opacity: 0; transform: translateY(4px); } }\n`;\ndocument.head.appendChild(style);\n\nconst overlay = document.createElement('div');\noverlay.id = 'orca_pause';\noverlay.innerHTML = '

    ';\noverlay.querySelector('button').addEventListener('click', () => resume());\ndocument.addEventListener('DOMContentLoaded', () => document.body.appendChild(overlay));\n\nwindow.addEventListener('keydown', (event) => {\n if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.key === 'c' || event.key === 'C' || event.key === 'Insert')) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerdown', (event) => {\n pointerStart = { x: event.clientX, y: event.clientY };\n}, true);\n// A double- or triple-click selects a word or line (pointer events carry no click count).\nwindow.addEventListener('mousedown', (event) => {\n if (event.detail >= 2) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerup', (event) => {\n if (pointerStart && Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y) >= DRAG_PX) {\n lastCopyIntent = Date.now();\n }\n pointerStart = null;\n}, true);\n\nfunction requestTicket() {\n const answer = attemptConnected ? 'ticket' : 'retry';\n const waiters = ticketWaiters;\n ticketWaiters = [];\n waiters.forEach((resolve) => resolve(answer));\n}\n\nasync function whenStarted() {\n while (document.documentElement.classList.contains('noVNC_loading')) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n}\n\nfunction onConnect() {\n state = 'connected';\n attemptConnected = true;\n UI.hideStatus();\n setTimeout(() => {\n // Xvnc answers SetDesktopSize; anything that does not gets scaled into the tab instead.\n if (UI.rfb && state === 'connected' && !UI.rfb._supportsSetDesktopSize) {\n UI.rfb.scaleViewport = true;\n }\n }, RESIZE_FALLBACK_MS);\n}\n\nfunction onDisconnect() {\n if (state === 'paused') {\n return;\n }\n state = 'disconnected';\n // The ticket is spent: ask Orca for a new one (a dropped forward, a restart of the desktop).\n requestTicket();\n}\n\nfunction onClipboard(event) {\n const text = event.detail && event.detail.text;\n if (typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return;\n }\n if (Date.now() - lastCopyIntent > USER_COPY_WINDOW_MS || !document.hasFocus()) {\n return;\n }\n navigator.clipboard.writeText(text).catch(() => {});\n}\n\nasync function connect(ticket) {\n if (typeof ticket !== 'string' || !TICKET_RE.test(ticket)) {\n return 'invalid';\n }\n if (state === 'connecting' || state === 'connected' || state === 'paused') {\n return state;\n }\n await whenStarted();\n if (UI.rfb) {\n return 'connecting';\n }\n state = 'connecting';\n attemptConnected = false;\n // UI.connect reads the path setting synchronously and opens the WebSocket in RFB's constructor;\n // the in-memory setting is restored right after, so the ticket is never kept or shown.\n // Only ever this page's own origin: noVNC also reads host, port, encrypt, repeater and logging\n // from the URL, which must never send a ticketed session (and the user's keys) elsewhere.\n WebUtil.setSetting('host', '');\n WebUtil.setSetting('port', '');\n WebUtil.setSetting('encrypt', false);\n WebUtil.setSetting('repeaterID', '');\n WebUtil.setSetting('path', `${WS_PATH}?ticket=${ticket}`);\n try {\n UI.connect();\n } finally {\n WebUtil.setSetting('path', WS_PATH);\n }\n const rfb = UI.rfb;\n if (!rfb) {\n state = 'disconnected';\n requestTicket();\n return 'failed';\n }\n rfb.addEventListener('connect', onConnect);\n rfb.addEventListener('disconnect', onDisconnect);\n rfb.addEventListener('clipboard', onClipboard);\n return 'connecting';\n}\n\n/** Pastes this computer's clipboard: the sandbox's clipboard first, then the paste key itself. */\nfunction paste(text, chord) {\n const rfb = UI.rfb;\n if (!rfb || state !== 'connected' || typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return false;\n }\n rfb.clipboardPasteFrom(text);\n if (chord && chord.kind === 'mac') {\n // Cmd+V: Linux apps do not paste on Super+V, so release Super and send Shift+Insert.\n rfb.sendKey(XK.Super_L, 'MetaLeft', false);\n rfb.sendKey(XK.Super_R, 'MetaRight', false);\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', true);\n rfb.sendKey(XK.Insert, 'Insert');\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', false);\n } else if (chord && chord.kind === 'replay') {\n // Ctrl+V, Ctrl+Shift+V, Shift+Insert: the held modifiers already reached the sandbox.\n const insert = chord.key === 'Insert';\n rfb.sendKey(insert ? XK.Insert : chord.key === 'V' ? XK.V : XK.v, insert ? 'Insert' : 'KeyV');\n }\n return true;\n}\n\nfunction pause(message, label, tone) {\n state = 'paused';\n if (UI.rfb) {\n UI.rfb.disconnect();\n }\n UI.hideStatus();\n overlay.querySelector('p').textContent = String(message || '');\n overlay.querySelector('button').textContent = String(label || 'Reconnect');\n // Asleep and starting are states, not errors: announce them politely.\n overlay.firstElementChild.setAttribute('role', tone === 'neutral' ? 'status' : 'alert');\n overlay.classList.add('open');\n overlay.querySelector('button').focus();\n return true;\n}\n\nfunction resume() {\n if (state !== 'paused') {\n return false;\n }\n overlay.classList.remove('open');\n state = 'disconnected';\n attemptConnected = true; // a person asked: start the retry budget over\n requestTicket();\n return true;\n}\n\nObject.defineProperty(window, 'orcaDesktop', {\n value: Object.freeze({\n version: 1,\n state: () => state,\n /** Resolves when the page needs a ticket: now if it is not connected, else after a drop. */\n nextTicketRequest: () => new Promise((resolve) => {\n ticketWaiters.push(resolve);\n if (state === 'idle' || state === 'disconnected') {\n requestTicket();\n }\n }),\n connect,\n paste,\n pause,\n resume\n })\n});\n","orca-sandbox-grant":"#!/usr/bin/env bash\n# Mints a fresh, single-device orcad pairing offer for one org member's device and seals it to that\n# device's X25519 key, so the control plane relays only ciphertext (the VM owner's E2EE model holds:\n# every member device gets its own revocable orcad credential, nobody else can read it).\n# Env from the control plane: ORCA_GRANT_ID, ORCA_GRANT_RECIPIENT_KEY (base64 raw X25519 public\n# key), ORCA_GRANT_KIND (desktop|mobile), ORCA_PUBLIC_WSS. Prints one JSON line:\n# {\"deviceId\":\"…\",\"sealed\":{\"v\":1,\"ephemeralPublicKeyB64\":\"…\",\"nonceB64\":\"…\",\"ciphertextB64\":\"…\"}}\n# Sealing: ECDH(ephemeral, recipient) -> HKDF-SHA256(salt = eph||recipient, info\n# \"orca-cloud-grant-v1\") -> AES-256-GCM, AAD \"orca-cloud-grant-v1:\".\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nDATA=\"$HOME/.orcad-data\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\n# One mint at a time: --rotate retires unredeemed offers, so two members never share a credential.\nflock -w 30 9\n\ncase \"${ORCA_GRANT_ID:-}\" in '' | *[!A-Za-z0-9_-]*) echo 'bad grant id' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_KIND:-}\" in desktop) scope=() ;; mobile) scope=(--mobile) ;; *) echo 'bad kind' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_RECIPIENT_KEY:-}\" in '' | *[!A-Za-z0-9+/=]*) echo 'bad key' >&2; exit 2 ;; esac\ncase \"${ORCA_PUBLIC_WSS:-}\" in wss://*) ;; *) echo 'bad endpoint' >&2; exit 2 ;; esac\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\n# The workspace's project must exist on this orcad before a phone opens it: phones may not add\n# projects themselves (mobile RPC scope), and a phone may be the first client this VM ever sees.\nproject=/vercel/sandbox/project\nif [ -d \"$project\" ]; then\n kind=folder\n [ -d \"$project/.git\" ] && kind=git\n ORCA_USER_DATA_PATH=\"$DATA\" timeout 20 \"$node\" \"$cli\" repo add --path \"$project\" --kind \"$kind\" --json \\\n >/dev/null 2>&1 || true\nfi\noffer=\"$(ORCA_USER_DATA_PATH=\"$DATA\" timeout 30 \"$node\" \"$cli\" pair --json --rotate \"${scope[@]}\" \\\n --address \"$ORCA_PUBLIC_WSS\" 2>/dev/null)\" || { echo 'pair failed' >&2; exit 1; }\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" \\\n \"$node\" -e '\nconst crypto = require(\"node:crypto\")\nlet input = \"\"\nprocess.stdin.on(\"data\", (c) => (input += c)).on(\"end\", () => {\n const res = JSON.parse(input).result\n if (!res || res.available !== true || !res.pairingUrl || !res.deviceId) {\n console.error(\"offer unavailable\")\n process.exit(1)\n }\n const recipient = Buffer.from(process.env.ORCA_GRANT_RECIPIENT_KEY, \"base64\")\n if (recipient.length !== 32) { console.error(\"bad key length\"); process.exit(2) }\n const recipientKey = crypto.createPublicKey({ key: { kty: \"OKP\", crv: \"X25519\", x: recipient.toString(\"base64url\") }, format: \"jwk\" })\n const eph = crypto.generateKeyPairSync(\"x25519\")\n const ephRaw = Buffer.from(eph.publicKey.export({ format: \"jwk\" }).x, \"base64url\")\n const shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: recipientKey })\n const key = Buffer.from(crypto.hkdfSync(\"sha256\", shared, Buffer.concat([ephRaw, recipient]), \"orca-cloud-grant-v1\", 32))\n const nonce = crypto.randomBytes(12)\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce)\n cipher.setAAD(Buffer.from(\"orca-cloud-grant-v1:\" + process.env.ORCA_GRANT_ID))\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope }))\n const ct = Buffer.concat([cipher.update(body), cipher.final(), cipher.getAuthTag()])\n process.stdout.write(JSON.stringify({ deviceId: res.deviceId, sealed: { v: 1, ephemeralPublicKeyB64: ephRaw.toString(\"base64\"), nonceB64: nonce.toString(\"base64\"), ciphertextB64: ct.toString(\"base64\") } }) + \"\\n\")\n})'\n","orca-sandbox-revoke":"#!/usr/bin/env bash\n# Revokes member devices from orcad's device registry. orcad adopts on-disk removals at every auth\n# (an admin revoke, device-registry-store.ts), so this works whether or not orcad is running; the\n# control plane also runs it at boot, before orcad starts, for revokes queued while suspended.\n# Env: ORCA_REVOKE_DEVICE_IDS (comma list of orcad device ids). Prints {\"revoked\":,\"live\":}.\nset -euo pipefail\numask 077\nSTATE=\"$HOME/.orca-sandbox\"\nREGISTRY=\"$HOME/.orcad-data/orca-devices.json\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\nflock -w 30 9\n\nids=\"${ORCA_REVOKE_DEVICE_IDS:-}\"\ncase \"$ids\" in '' | *[!A-Za-z0-9,_-]*) echo 'bad device ids' >&2; exit 2 ;; esac\n# Live orcad first: `orca pair --revoke` also closes the device's open sockets now. Older orcad\n# builds lack it; the on-disk removal below still blocks their next sign-in.\nORCA_HOME=/opt/orca\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node 2>/dev/null | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\nlive=0\nif [ -n \"$node\" ] && [ -f \"$cli\" ] && [ -s \"$HOME/.orcad-data/orca-runtime.json\" ]; then\n for id in ${ids//,/ }; do\n if ORCA_USER_DATA_PATH=\"$HOME/.orcad-data\" timeout 15 \"$node\" \"$cli\" pair --revoke \"$id\" --json 2>/dev/null \\\n | jq -e '.ok == true and .result.revoked == true' >/dev/null 2>&1; then\n live=$((live + 1))\n fi\n done\nfi\nif [ ! -s \"$REGISTRY\" ]; then\n echo \"{\\\"revoked\\\":$live,\\\"live\\\":$live}\"\n exit 0\nfi\nids_json=\"$(jq -cn --arg ids \"$ids\" '$ids | split(\",\") | map(select(length > 0))')\"\nbefore=\"$(jq 'length' \"$REGISTRY\")\"\ntmp=\"$(mktemp \"$REGISTRY.revoke.XXXXXX\")\"\n# Removes the rows and any phones delegated through them (parentDeviceId), like orcad's own revoke.\njq --argjson ids \"$ids_json\" \\\n '[.[] | select((.deviceId as $d | $ids | index($d)) == null and ((.parentDeviceId // \"\") as $p | $ids | index($p)) == null)]' \\\n \"$REGISTRY\" >\"$tmp\"\nchmod 0600 \"$tmp\"\nsync \"$tmp\" 2>/dev/null || true\nmv -f \"$tmp\" \"$REGISTRY\"\nafter=\"$(jq 'length' \"$REGISTRY\")\"\necho \"{\\\"revoked\\\":$((live + before - after)),\\\"live\\\":$live}\"\n","orca-sandbox-members":"#!/usr/bin/env bash\n# Runs as root (control plane, sudo). Installs who-may-push-as-whom for `orca-git-as`:\n# /etc/orca/members/.gitconfig egress placeholder header + GitHub author identity\n# /etc/orca/members/devices.json {\"\": \"\"} (each member's paired devices)\n# Both root-only: agents never read another member's placeholder. `orca-git-identity` (root, via a\n# sudoers rule) hands an agent only the identity of the member whose device drove its turn, as orcad\n# attests it. No token lives here: the placeholder is swapped at egress, for this repository only.\n# Env: ORCA_MEMBERS_B64 = base64 JSON [{userId, name, email, authorization, deviceIds:[...]}]\n# The VM user agents run as is orcad's own user (detected). Prints {\"members\":,\"devices\":}.\nset -euo pipefail\numask 077\nDIR=/etc/orca/members\norcad_pid=\"$(pgrep -f orcad-server.js | head -n 1 || true)\"\nUSER_NAME=\"$( [ -n \"$orcad_pid\" ] && ps -o user= -p \"$orcad_pid\" | tr -d ' ' || true)\"\nUSER_NAME=\"${USER_NAME:-${ORCA_SANDBOX_USER:-${SUDO_USER:-}}}\"\ncase \"$USER_NAME\" in '' | *[!a-z0-9_-]*) echo 'bad user' >&2; exit 2 ;; esac\nmkdir -p /etc/orca\njson=\"$(printf '%s' \"${ORCA_MEMBERS_B64:-W10=}\" | base64 -d)\"\ntmp=\"$(mktemp -d /etc/orca/members.XXXXXX)\"\ncount=0\nwhile IFS= read -r row; do\n user=\"$(jq -r '.userId' <<<\"$row\")\"\n case \"$user\" in '' | *[!A-Za-z0-9_.:-]*) continue ;; esac\n file=\"$tmp/$(printf '%s' \"$user\" | tr ':' '_').gitconfig\"\n # An empty extraheader first resets the image-wide (app identity) header for this member's git.\n git config -f \"$file\" --add http.https://github.com/.extraheader ''\n git config -f \"$file\" --add http.https://github.com/.extraheader \"Authorization: $(jq -r '.authorization' <<<\"$row\")\"\n git config -f \"$file\" user.name \"$(jq -r '.name' <<<\"$row\")\"\n git config -f \"$file\" user.email \"$(jq -r '.email' <<<\"$row\")\"\n count=$((count + 1))\ndone < <(jq -c '.[]' <<<\"$json\")\njq -c '[.[] | select(.userId | test(\"^[A-Za-z0-9_.:-]+$\")) | .userId as $u | (.deviceIds // [])[] | select(test(\"^[A-Za-z0-9_-]{1,128}$\")) | {key: ., value: $u}] | from_entries' <<<\"$json\" >\"$tmp/devices.json\"\ndevices=\"$(jq 'length' \"$tmp/devices.json\")\"\nchmod 0700 \"$tmp\" && chmod 0600 \"$tmp\"/*\nrm -rf \"$DIR.old\"\n[ -d \"$DIR\" ] && mv \"$DIR\" \"$DIR.old\"\nmv \"$tmp\" \"$DIR\"\nrm -rf \"$DIR.old\"\n# Agents may ask for their own sender's identity, and only that (the helper checks with orcad).\nrule=\"$USER_NAME ALL=(root) NOPASSWD:SETENV: /opt/orca/bin/orca-git-identity\"\nprintf '%s\\n' \"$rule\" >/etc/sudoers.d/orca-git-identity.new\nchmod 0440 /etc/sudoers.d/orca-git-identity.new\nif visudo -cf /etc/sudoers.d/orca-git-identity.new >/dev/null; then\n mv -f /etc/sudoers.d/orca-git-identity.new /etc/sudoers.d/orca-git-identity\nelse\n rm -f /etc/sudoers.d/orca-git-identity.new\n echo 'sudoers rule rejected' >&2\n exit 1\nfi\n# Pre-attestation layout (agent-readable member files) must not linger.\nuser_home=\"$(getent passwd \"$USER_NAME\" | cut -d: -f6)\"\n[ -n \"$orcad_pid\" ] && user_home=\"$(tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n 's/^HOME=//p' | head -n 1)\"\n[ -n \"$user_home\" ] && rm -rf \"$user_home/.orca-sandbox/members\"\n# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default).\nif [ -n \"$user_home\" ]; then\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email 'cloud@users.noreply.onorca.dev'\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name 'Orca Cloud'\nfi\necho \"{\\\"members\\\":$count,\\\"devices\\\":$devices}\"\n","orca-sandbox-read-snapshot":"#!/usr/bin/env bash\n# Seals a read-only snapshot of this workspace (chats, agent status, git, PR) to the reader keys the\n# control plane passes, right before the drain. Only ciphertext is printed (one JSON line); see\n# orca-read-snapshot.cjs. Exit 3: orcad isn't running (nothing to read).\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n[ -n \"$node\" ] || { echo 'node not found' >&2; exit 1; }\nexec timeout 35 \"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\"\n","orca-read-snapshot.cjs":"#!/usr/bin/env node\n// Gathers what a sleeping workspace should still show (recent chats per agent session, agent\n// status, git status/diff summary, PR link) from the running orcad over its local socket, then seals\n// it to the reader keys the control plane passed, so only ciphertext leaves the VM.\n// Run by orca-sandbox-read-snapshot right before the drain. Env:\n// ORCA_READ_SNAPSHOT_ID rsn_<24 hex> ORCA_READ_WORKSPACE_ID sbx_<24 hex>\n// ORCA_READ_RECIPIENTS JSON [{keyId, publicKeyB64}] ORCA_READ_REASON sleep|rollover\n// ORCA_USER_DATA_PATH orcad's data dir (orca-runtime.json lives there)\n// Prints one JSON line: {v:1, snapshotId, workspaceId, nonceB64, ciphertextB64, recipients[], stats}.\n// Construction (keep in sync with src/shared/cloud-workspaces/read-snapshot.ts in the app):\n// body = AES-256-GCM(dek, nonce, JSON, AAD \"orca-cloud-read-v1::\")\n// wrapped = AES-256-GCM(HKDF-SHA256(X25519(eph, reader), eph||reader, \"orca-cloud-read-wrap-v1\"),\n// nonce_i, dek, AAD \"orca-cloud-read-wrap-v1:::\")\n'use strict'\nconst crypto = require('node:crypto')\nconst fs = require('node:fs')\nconst net = require('node:net')\nconst path = require('node:path')\n\nconst INFO = 'orca-cloud-read-v1'\nconst WRAP_INFO = 'orca-cloud-read-wrap-v1'\nconst PROJECT = '/vercel/sandbox/project'\nconst LIMITS = { sessions: 12, messagesPerSession: 60, messageChars: 4000, changes: 200, commits: 10 }\n/** Plaintext budget: sealed + base64 it stays under the control plane's 220 kB and the 256 kB stdout cap. */\nconst MAX_PLAIN_BYTES = 150_000\nconst CALL_TIMEOUT_MS = 5_000\nconst TOTAL_BUDGET_MS = 20_000\n\nfunction b64(bytes) {\n return Buffer.from(bytes).toString('base64')\n}\n\nfunction x25519PublicKey(raw) {\n return crypto.createPublicKey({ key: { kty: 'OKP', crv: 'X25519', x: Buffer.from(raw).toString('base64url') }, format: 'jwk' })\n}\n\nfunction gcmSeal(key, nonce, plain, aad) {\n const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce)\n cipher.setAAD(Buffer.from(aad))\n return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()])\n}\n\n/** Seals `payload` (an object) to every recipient; a malformed key is skipped, not fatal. */\nfunction seal(payload, recipients, workspaceId, snapshotId) {\n const scope = `${workspaceId}:${snapshotId}`\n const dek = crypto.randomBytes(32)\n const nonce = crypto.randomBytes(12)\n const ciphertext = gcmSeal(dek, nonce, Buffer.from(JSON.stringify(payload)), `${INFO}:${scope}`)\n const sealedTo = []\n for (const recipient of recipients) {\n const reader = Buffer.from(String(recipient.publicKeyB64 || ''), 'base64')\n if (reader.length !== 32 || !/^rk_[0-9a-f]{24}$/.test(String(recipient.keyId || ''))) {\n continue\n }\n let shared\n const eph = crypto.generateKeyPairSync('x25519')\n try {\n shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: x25519PublicKey(reader) })\n } catch {\n continue\n }\n if (shared.every((byte) => byte === 0)) {\n continue\n }\n const ephRaw = Buffer.from(eph.publicKey.export({ format: 'jwk' }).x, 'base64url')\n const kek = Buffer.from(crypto.hkdfSync('sha256', shared, Buffer.concat([ephRaw, reader]), WRAP_INFO, 32))\n const wrapNonce = crypto.randomBytes(12)\n const wrapped = gcmSeal(kek, wrapNonce, dek, `${WRAP_INFO}:${scope}:${recipient.keyId}`)\n sealedTo.push({ keyId: recipient.keyId, ephemeralPublicKeyB64: b64(ephRaw), nonceB64: b64(wrapNonce), wrappedKeyB64: b64(wrapped) })\n }\n dek.fill(0)\n return { v: 1, snapshotId, workspaceId, nonceB64: b64(nonce), ciphertextB64: b64(ciphertext), recipients: sealedTo }\n}\n\n// --- gathering -------------------------------------------------------------------------------\n\n/** One request per connection, like the CLI. A streaming method resolves on its first frame. */\nfunction rpc(metadata, method, params, timeoutMs = CALL_TIMEOUT_MS) {\n return new Promise((resolve) => {\n const transport = (metadata.transports || [metadata.transport]).find((t) => t && (t.kind === 'unix' || t.kind === 'named-pipe'))\n if (!transport) {\n resolve(null)\n return\n }\n const socket = net.createConnection(transport.endpoint)\n const id = crypto.randomUUID()\n let buffer = ''\n let done = false\n const finish = (value) => {\n if (!done) {\n done = true\n clearTimeout(timer)\n socket.destroy()\n resolve(value)\n }\n }\n const timer = setTimeout(() => finish(null), timeoutMs)\n socket.setEncoding('utf8')\n socket.on('error', () => finish(null))\n socket.on('close', () => finish(null))\n socket.on('connect', () => socket.write(`${JSON.stringify({ id, authToken: metadata.authToken, method, params })}\\n`))\n socket.on('data', (chunk) => {\n buffer += chunk\n let newline\n while ((newline = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, newline)\n buffer = buffer.slice(newline + 1)\n let frame\n try {\n frame = JSON.parse(line)\n } catch {\n continue\n }\n if (!frame || frame.id !== id) {\n continue\n }\n finish(frame.ok === true ? frame.result : null)\n return\n }\n })\n })\n}\n\nconst isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v)\nconst str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : null)\nconst num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null)\n\nfunction messagesOf(history) {\n const items = isObj(history) && isObj(history.page) && Array.isArray(history.page.items) ? history.page.items : []\n const out = []\n for (const item of items) {\n const body = isObj(item) && isObj(item.body) ? item.body : null\n if (!body || body.kind !== 'message' || !Array.isArray(body.blocks)) {\n continue\n }\n const role = body.role\n if (role !== 'user' && role !== 'assistant' && role !== 'system') {\n continue\n }\n const text = body.blocks\n .filter((b) => isObj(b) && b.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text)\n .join('\\n')\n .trim()\n if (text) {\n out.push({ itemId: String(item.itemId).slice(0, 200), role, text: text.slice(0, LIMITS.messageChars), at: num(item.observedAt) ?? 0 })\n }\n }\n return { messages: out, hasOlder: isObj(history) && isObj(history.page) && history.page.hasOlder === true }\n}\n\nfunction gitOf(status, log) {\n if (!isObj(status) && !isObj(log)) {\n return null\n }\n const entries = isObj(status) && Array.isArray(status.entries) ? status.entries.filter(isObj) : []\n let added = 0\n let removed = 0\n let counted = false\n const changes = entries.slice(0, LIMITS.changes).map((e) => {\n const a = num(e.added)\n const r = num(e.removed)\n if (a !== null || r !== null) {\n counted = true\n }\n return { path: String(e.path).slice(0, 1024), status: str(e.status, 20) || 'modified', area: str(e.area, 20) || 'unstaged', added: a, removed: r }\n })\n for (const e of entries) {\n added += num(e.added) || 0\n removed += num(e.removed) || 0\n }\n const items = isObj(log) && Array.isArray(log.items) ? log.items.filter(isObj) : []\n return {\n branch: isObj(status) && typeof status.branch === 'string' ? status.branch.replace(/^refs\\/heads\\//, '') : null,\n head: isObj(status) ? str(status.head, 64) : null,\n changes,\n changeCount: entries.length,\n added: counted ? added : null,\n removed: counted ? removed : null,\n commits: items.slice(0, LIMITS.commits).map((c) => ({\n id: String(c.id).slice(0, 64),\n subject: String(c.subject ?? '').slice(0, 300),\n author: str(c.author, 120),\n at: num(c.timestamp)\n }))\n }\n}\n\nfunction prOf(linked) {\n if (!isObj(linked) || num(linked.number) === null || typeof linked.url !== 'string' || !linked.url.startsWith('https://')) {\n return null\n }\n return {\n number: linked.number,\n title: String(linked.title ?? '').slice(0, 300),\n state: str(linked.state, 20) || 'open',\n url: linked.url.slice(0, 500),\n checksStatus: str(linked.checksStatus, 20),\n checksSummary: str(linked.checksSummary, 200)\n }\n}\n\nconst STATUSES = new Set(['working', 'attention', 'idle'])\nconst PANE_PREFIX = 'structured-agent-session-'\n\n/**\n * Chats as orcad stores them (agent-session-journal.db, read-only): every session's provider, name\n * and last turn, open tabs first. The local socket can't stream agentSession.subscribeStatus, and\n * worktree.ps lists only agents that are live right now, so this is the complete list.\n */\nfunction storedSessions(dataDir) {\n let db\n try {\n const { DatabaseSync } = require('node:sqlite')\n db = new DatabaseSync(path.join(dataDir, 'agent-session-journal.db'), { readOnly: true })\n const open = new Set(db.prepare('SELECT session_id FROM agent_session_tabs').all().map((r) => r.session_id))\n const out = []\n for (const row of db.prepare('SELECT session_id, record_json FROM agent_session_records').all()) {\n let record\n try {\n record = JSON.parse(row.record_json)\n } catch {\n continue\n }\n const last = isObj(record.lastTurn) ? record.lastTurn : {}\n out.push({\n sessionId: row.session_id,\n agent: str(record.provider, 40),\n title: str(record.conversationName, 200) || str(last.prompt, 200),\n status: last.state === 'running' || last.state === 'submitted' ? 'working' : last.state === 'settled' ? 'idle' : 'unknown',\n turnOutcome: str(last.outcome, 40),\n updatedAt: num(record.updatedAt),\n open: open.has(row.session_id),\n lastPrompt: str(last.prompt, LIMITS.messageChars),\n lastReply: str(last.reply, LIMITS.messageChars),\n lastAt: num(last.at)\n })\n }\n return out\n } catch {\n return []\n } finally {\n try {\n db && db.close()\n } catch {}\n }\n}\n\n/** Live agent rows from worktree.ps, keyed by session id (their status wins over the stored one). */\nfunction liveAgents(worktrees) {\n const out = new Map()\n for (const w of worktrees) {\n for (const a of Array.isArray(w.agents) ? w.agents.filter(isObj) : []) {\n const tab = typeof a.paneKey === 'string' ? a.paneKey.split(':')[0] : ''\n if (!tab.startsWith(PANE_PREFIX)) {\n continue\n }\n const state = a.mainAgent && typeof a.mainAgent.state === 'string' ? a.mainAgent.state : a.state\n out.set(tab.slice(PANE_PREFIX.length), {\n agent: str(a.agentType, 40),\n title: str(a.conversationName, 200) || str(a.taskTitle, 200) || str(a.displayName, 200),\n status: state === 'working' ? 'working' : state === 'blocked' || state === 'waiting' || state === 'attention' ? 'attention' : 'idle',\n updatedAt: num(a.updatedAt)\n })\n }\n }\n return out\n}\n\n/** `call(method, params)` -> result | null. Never throws: a missing piece is left out. */\nasync function gather(call, { workspaceId, snapshotId, reason, now, deadline, listSessions = () => [] }) {\n const timeLeft = () => deadline - Date.now()\n const ps = await call('worktree.ps', { limit: 20 })\n const worktrees = isObj(ps) && Array.isArray(ps.worktrees) ? ps.worktrees.filter(isObj) : []\n const project = worktrees.find((w) => w.path === PROJECT) || worktrees[0] || null\n const selector = project && typeof project.path === 'string' ? `path:${project.path}` : `path:${PROJECT}`\n const [status, log] = await Promise.all([\n call('git.status', { worktree: selector, includeLineStats: true }),\n call('git.history', { worktree: selector, limit: LIMITS.commits })\n ])\n const live = liveAgents(worktrees)\n const byId = new Map()\n for (const s of listSessions()) {\n byId.set(s.sessionId, s)\n }\n for (const [sessionId, a] of live) {\n byId.set(sessionId, { ...(byId.get(sessionId) || { sessionId, open: true }), ...Object.fromEntries(Object.entries(a).filter(([, v]) => v !== null)) })\n }\n // Open chats first, then newest activity.\n const picked = [...byId.values()]\n .filter((s) => typeof s.sessionId === 'string')\n .sort((a, b) => Number(Boolean(b.open)) - Number(Boolean(a.open)) || (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))\n .slice(0, LIMITS.sessions)\n const sessions = []\n for (const s of picked) {\n const history = timeLeft() > 1_000 ? await call('agentSession.history', { sessionId: s.sessionId, direction: 'tail', limit: LIMITS.messagesPerSession }) : null\n let { messages, hasOlder } = messagesOf(history)\n if (messages.length === 0) {\n // No readable history (or out of time): the stored last turn still says what happened.\n const at = s.lastAt || s.updatedAt || 0\n messages = [\n ...(s.lastPrompt ? [{ itemId: `${s.sessionId}:last-prompt`, role: 'user', text: s.lastPrompt, at }] : []),\n ...(s.lastReply ? [{ itemId: `${s.sessionId}:last-reply`, role: 'assistant', text: s.lastReply, at }] : [])\n ]\n hasOlder = hasOlder || messages.length > 0\n }\n sessions.push({\n sessionId: s.sessionId.slice(0, 200),\n agent: s.agent || null,\n title: s.title || null,\n status: STATUSES.has(s.status) ? s.status : 'unknown',\n turnOutcome: s.turnOutcome || null,\n updatedAt: num(s.updatedAt),\n messages: messages.slice(-LIMITS.messagesPerSession),\n truncated: hasOlder || messages.length > LIMITS.messagesPerSession\n })\n }\n return {\n v: 1,\n workspaceId,\n snapshotId,\n capturedAt: now,\n reason,\n git: gitOf(status, log),\n pr: prOf(project && project.linkedPR),\n sessions\n }\n}\n\n/** Cuts the oldest messages (then long texts, then sessions) until the JSON fits the budget. */\nfunction fitToBudget(payload, maxBytes = MAX_PLAIN_BYTES) {\n const size = () => Buffer.byteLength(JSON.stringify(payload))\n let guard = 0\n while (size() > maxBytes && guard++ < 10_000) {\n const longest = payload.sessions.reduce((best, s) => (!best || s.messages.length > best.messages.length ? s : best), null)\n if (longest && longest.messages.length > 4) {\n longest.messages.shift()\n longest.truncated = true\n continue\n }\n const longText = payload.sessions.flatMap((s) => s.messages).find((m) => m.text.length > 500)\n if (longText) {\n longText.text = `${longText.text.slice(0, 500)}…`\n continue\n }\n if (payload.git && payload.git.changes.length > 20) {\n payload.git.changes = payload.git.changes.slice(0, 20)\n continue\n }\n if (payload.sessions.length > 1) {\n payload.sessions.pop()\n continue\n }\n payload.sessions = []\n break\n }\n return payload\n}\n\nasync function main() {\n const started = Date.now()\n const env = process.env\n const snapshotId = env.ORCA_READ_SNAPSHOT_ID || ''\n const workspaceId = env.ORCA_READ_WORKSPACE_ID || ''\n if (!/^rsn_[0-9a-f]{24}$/.test(snapshotId) || !/^sbx_[0-9a-f]{24}$/.test(workspaceId)) {\n process.stderr.write('bad ids\\n')\n process.exit(2)\n }\n let recipients\n try {\n recipients = JSON.parse(env.ORCA_READ_RECIPIENTS || '[]')\n } catch {\n recipients = null\n }\n if (!Array.isArray(recipients) || recipients.length === 0) {\n process.stderr.write('no recipients\\n')\n process.exit(2)\n }\n const dataDir = env.ORCA_USER_DATA_PATH || path.join(env.HOME || '', '.orcad-data')\n let metadata\n try {\n metadata = JSON.parse(fs.readFileSync(path.join(dataDir, 'orca-runtime.json'), 'utf8'))\n } catch {\n metadata = null\n }\n if (!metadata || !metadata.authToken) {\n process.stderr.write('orcad not running\\n')\n process.exit(3)\n }\n const deadline = started + TOTAL_BUDGET_MS\n const call = (method, params) => rpc(metadata, method, params, Math.max(250, Math.min(CALL_TIMEOUT_MS, deadline - Date.now())))\n const payload = fitToBudget(\n await gather(call, { workspaceId, snapshotId, reason: (env.ORCA_READ_REASON || 'sleep').slice(0, 20), now: Date.now(), deadline, listSessions: () => storedSessions(dataDir) })\n )\n const out = seal(payload, recipients, workspaceId, snapshotId)\n // Timing only: counts and sizes would describe the plaintext to the control plane's logs.\n out.stats = { collectMs: Date.now() - started }\n process.stdout.write(`${JSON.stringify(out)}\\n`)\n}\n\nmodule.exports = { seal, gather, fitToBudget, messagesOf, gitOf, prOf, rpc, storedSessions, liveAgents }\n\nif (require.main === module) {\n // A fixed message: an error text could carry workspace content into the control plane's logs.\n main().catch(() => {\n process.stderr.write('read snapshot failed\\n')\n process.exit(1)\n })\n}\n","orca-git-as":"#!/usr/bin/env bash\n# Runs git as the teammate whose message started this agent's turn: their GitHub identity for\n# pushes/PRs (this repository only) and their commit author.\n# orca-git-as e.g. orca-git-as push origin HEAD\n# orca-git-as --as refuses unless that member really sent the message\n# Orca attests the sender from the paired device that sent the message, never from arguments or\n# message text. Without an attested sender (not run from an agent, or the owner's local session) it\n# runs plain git with the workspace identity.\nset -euo pipefail\nexpect=''\nif [ \"${1:-}\" = '--as' ]; then\n expect=\"${2:-}\"\n shift 2 || { echo 'usage: orca-git-as [--as ] ' >&2; exit 2; }\n case \"$expect\" in '' | *[!A-Za-z0-9_.:-]*) echo 'orca-git-as: bad member id' >&2; exit 2 ;; esac\nfi\nset +e\nfile=\"$(ORCA_GIT_AS=\"$expect\" sudo -n --preserve-env=ORCA_GIT_AS,ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity)\"\nstatus=$?\nset -e\ncase \"$status\" in\n 0)\n trap 'rm -f \"$file\"' EXIT\n git -c \"include.path=$file\" \"$@\"\n ;;\n 3)\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n exec git \"$@\"\n ;;\n *) exit 4 ;;\nesac\n","orca-git-identity":"#!/usr/bin/env bash\n# Root helper behind `orca-git-as` (sudoers: the VM user may run only this). Asks orcad, as the\n# calling agent, which paired device sent the message that started the agent's latest turn\n# (`orca sender`: orcad identifies the agent from its launch evidence, never from arguments), maps\n# that device to a workspace member, and prints that member's git config file for the caller to\n# include. Optional ORCA_GIT_AS: the member the agent expects; any other answer is refused.\n# Exit codes: 0 printed a config path; 3 no member identity (use the workspace identity); 4 refused.\nset -euo pipefail\nDIR=/etc/orca/members\ncaller=\"${SUDO_USER:-}\"\ncase \"$caller\" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac\n# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).\norcad_pid=\"$(pgrep -u \"$caller\" -f orcad-server.js | head -n 1 || true)\"\n[ -n \"$orcad_pid\" ] || exit 3\norcad_env() { tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n \"s/^$1=//p\" | head -n 1; }\nhome=\"$(orcad_env HOME)\"\ndata=\"$(orcad_env ORCA_USER_DATA)\"\ndata=\"${data:-$home/.orcad-data}\"\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\ncli=/opt/orca/runtime/orcad/out/cli/index.js\n# Only the evidence variables orcad needs reach the query, which runs as the caller, not root.\nanswer=\"$(sudo -u \"$caller\" env -i HOME=\"$home\" PATH=/usr/bin:/bin ORCA_USER_DATA_PATH=\"$data\" \\\n ${ORCA_TERMINAL_HANDLE:+ORCA_TERMINAL_HANDLE=\"$ORCA_TERMINAL_HANDLE\"} \\\n ${ORCA_PANE_KEY:+ORCA_PANE_KEY=\"$ORCA_PANE_KEY\"} \\\n ${ORCA_AGENT_LAUNCH_TOKEN:+ORCA_AGENT_LAUNCH_TOKEN=\"$ORCA_AGENT_LAUNCH_TOKEN\"} \\\n ${ORCA_AGENT_SESSION_ID:+ORCA_AGENT_SESSION_ID=\"$ORCA_AGENT_SESSION_ID\"} \\\n timeout 15 \"$node\" \"$cli\" sender --json 2>/dev/null || true)\"\ndevice=\"$(jq -r '.result.sender.deviceId // empty' <<<\"$answer\" 2>/dev/null || true)\"\nif [ -z \"$device\" ] || [ ! -s \"$DIR/devices.json\" ]; then\n if [ -n \"${ORCA_GIT_AS:-}\" ]; then\n echo \"orca-git-as: Orca cannot confirm that $ORCA_GIT_AS sent this agent's latest message; refusing to push as them.\" >&2\n exit 4\n fi\n exit 3\nfi\nmember=\"$(jq -r --arg d \"$device\" '.[$d] // empty' \"$DIR/devices.json\")\"\nif [ -z \"$member\" ]; then\n [ -n \"${ORCA_GIT_AS:-}\" ] && { echo \"orca-git-as: the sender's device is not linked to a workspace member; refusing.\" >&2; exit 4; }\n exit 3\nfi\nif [ -n \"${ORCA_GIT_AS:-}\" ] && [ \"$ORCA_GIT_AS\" != \"$member\" ]; then\n echo \"orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else.\" >&2\n exit 4\nfi\nfile=\"$DIR/$(printf '%s' \"$member\" | tr ':' '_').gitconfig\"\n[ -s \"$file\" ] || exit 3\n# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as).\nout=\"$(sudo -u \"$caller\" mktemp)\"\ncat \"$file\" >\"$out\"\necho \"$out\"\n","orcad-boot":"#!/usr/bin/env node\n// Starts orcad from a V8 code cache taken after a full startup, so a boot skips compiling the\n// functions startup runs. NODE_COMPILE_CACHE only stores what V8 compiles before the bundle runs\n// (about 5 of its 15 MB); every other function compiled lazily on every boot (~300 ms of wake).\n// orcad-boot --code-cache [--write-code-cache] [orcad args...]\n// orcad sees the argv `node [orcad args...]`, as if started directly.\n// --write-code-cache (the image's smoke run) writes the cache when orcad exits. The cache is used\n// only when its header matches this bundle's bytes and this Node; otherwise orcad loads exactly as\n// before (plain require, which NODE_COMPILE_CACHE still serves). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst fs = process.getBuiltinModule('node:fs')\nconst path = process.getBuiltinModule('node:path')\nconst vm = process.getBuiltinModule('node:vm')\nconst zlib = process.getBuiltinModule('node:zlib')\nconst { Module, createRequire } = process.getBuiltinModule('node:module')\n\nconst MAGIC = 'orcad-code-cache-v1'\n\nconst args = process.argv.slice(2)\nlet cacheFile = null\nlet writeCache = false\nwhile (args[0] === '--code-cache' || args[0] === '--write-code-cache') {\n if (args[0] === '--code-cache') {\n cacheFile = args[1]\n args.splice(0, 2)\n } else {\n writeCache = true\n args.shift()\n }\n}\nconst entry = args.shift()\nif (!entry || !cacheFile) {\n console.error('usage: orcad-boot --code-cache [--write-code-cache] [args...]')\n process.exit(2)\n}\n// As for `node `: argv[1] is the resolved path, __filename the real one.\nprocess.argv = [process.argv[0], path.resolve(entry), ...args]\nlet file = process.argv[1]\ntry {\n file = fs.realpathSync(file)\n} catch {\n // A missing bundle fails in require below, as it would under plain node.\n}\n\n// One line of identity: a cache from another bundle or Node must never run (V8 only checks length).\nfunction cacheHeader(bytes) {\n return `${MAGIC} ${process.version} ${process.arch} ${bytes.length} ${zlib.crc32(bytes)}\\n`\n}\n\nfunction readCache(header) {\n let data\n try {\n data = fs.readFileSync(cacheFile)\n } catch {\n return null\n }\n const headerLength = Buffer.byteLength(header)\n if (data.length <= headerLength || data.toString('latin1', 0, headerLength) !== header) {\n console.error('orcad-boot: code cache is for another orcad build; loading without it')\n return null\n }\n return data.subarray(headerLength)\n}\n\nfunction runCompiled(header, source, cachedData) {\n // A vm.Script can serialize what startup compiled; the CommonJS loader cannot. Same wrapper,\n // filename and require as the loader, and import() resolves from the bundle like it does there.\n const options = {\n filename: file,\n cachedData: cachedData ?? undefined,\n importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER\n }\n // Node flags the loader option experimental once, on the first import() through it. Spend that\n // one-time warning here, unprinted, so orcad's stderr stays as it was.\n const emitWarning = process.emitWarning\n process.emitWarning = (warning, ...rest) => {\n if (!String(warning?.message ?? warning).includes('USE_MAIN_CONTEXT_DEFAULT_LOADER')) {\n emitWarning.call(process, warning, ...rest)\n }\n }\n let script\n try {\n new vm.Script('import(\"node:path\")', {\n filename: file,\n importModuleDynamically: options.importModuleDynamically\n })\n .runInThisContext()\n .catch(() => {})\n script = new vm.Script(Module.wrap(source), options)\n } finally {\n process.emitWarning = emitWarning\n }\n if (cachedData && script.cachedDataRejected) {\n console.error('orcad-boot: V8 rejected the code cache (other V8 flags?); compiled without it')\n }\n if (writeCache) {\n process.on('exit', () => {\n try {\n const data = script.createCachedData()\n const temporary = `${cacheFile}.${process.pid}.tmp`\n fs.writeFileSync(temporary, Buffer.concat([Buffer.from(header, 'latin1'), data]))\n fs.renameSync(temporary, cacheFile)\n console.error(`orcad-boot: wrote ${data.length} bytes of code cache`)\n } catch (error) {\n console.error(`orcad-boot: could not write the code cache: ${error.message}`)\n }\n })\n }\n const module = new Module(file, null)\n module.filename = file\n module.paths = Module._nodeModulePaths(path.dirname(file))\n const compiled = script.runInThisContext()\n compiled.call(module.exports, module.exports, createRequire(file), module, file, path.dirname(file))\n}\n\n// Locals, so neither the bundle bytes nor the cache outlive the compile.\nfunction boot() {\n // Older Node (no crc32 or main-context import()) loads as before.\n if (typeof zlib.crc32 === 'function' && vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER) {\n let bytes = null\n try {\n bytes = fs.readFileSync(file)\n } catch {\n // Missing or unreadable: require reports it as plain node would.\n }\n if (bytes) {\n const header = cacheHeader(bytes)\n const cachedData = readCache(header)\n if (cachedData || writeCache) {\n runCompiled(header, bytes.toString('utf8'), cachedData)\n return\n }\n }\n }\n createRequire(file)(file)\n}\n\nboot()\n","git":"#!/usr/bin/env bash\n# git for agents in Orca Cloud workspaces (first on orcad's PATH). Commands that author or publish\n# work run as the teammate whose message started this agent's turn (orca-git-as: orcad attests the\n# sender's paired device; root-only member identities). Everything else is plain git, untouched.\nreal=/usr/bin/git\nsub=''\nskip=0\nfor arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n -*) ;;\n *) sub=\"$arg\"; break ;;\n esac\ndone\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n # Outside an agent turn (no attested sender) orca-git-as falls back to the workspace identity.\n if [ -n \"${ORCA_TERMINAL_HANDLE:-}${ORCA_AGENT_SESSION_ID:-}\" ] && [ -x /opt/orca/bin/orca-git-as ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec /opt/orca/bin/orca-git-as \"$@\" 2> >(grep -v '^orca-git-as: no teammate identity' >&2)\n fi\n ;;\nesac\nexec \"$real\" \"$@\"\n"} +export const VM_SCRIPT_SOURCES: BuildInputs['vmScripts'] = {"orca-sandbox-start":"#!/usr/bin/env bash\n# Starts orcad for this boot (idempotent) and prints its recipe line:\n# {\"schemaVersion\":1,\"pairingCode\":\"orca://pair?...\",\"projectRoot\":\"/vercel/sandbox/project\"}\n# Env from the control plane: ORCA_SANDBOX_ID, ORCA_PUBLIC_WSS, optional ORCA_REPO_URL/ORCA_REPO_REF,\n# ORCA_GITHUB_PLACEHOLDER, ORCA_SECRET_ENV (`NAME=` lines: org/personal/repo secrets for\n# orcad and its agents), ORCA_SHARE_PROXY_KEY (this session's share-link proxy key, port 6769).\n# Never prints anything else on stdout's last line.\n# With ORCA_READY_VIA=file it prints {\"schemaVersion\":1,\"readyFile\":\"\"} instead and the control\n# plane reads the offer with the files API: the provider keeps command stdout as logs, not files.\n# With ORCA_READY_KEY too (64 hex chars, this call's key; env is not kept) the pointer also carries\n# \"sealedOffer\": \".\", which saves that round trip.\n# Managed env for every process orcad starts: ORCA_IS_CLOUD=1, ORCA_SANDBOX_ID, ORCA_ROOT_PATH,\n# ORCA_WORKTREE_PATH, ORCA_WORKSPACE_PATH, ORCA_WORKSPACE_NAME, ORCA_DEFAULT_BRANCH, ORCA_PORT and the\n# CONDUCTOR_* names imported Conductor scripts read.\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nPROJECT=/vercel/sandbox/project\nmkdir -p \"$STATE\"\n# Only print_ready uses the key; nothing this script starts inherits it.\nready_key=\"${ORCA_READY_KEY:-}\"\nunset ORCA_READY_KEY\n[[ \"$ready_key\" =~ ^[0-9a-f]{64}$ ]] || ready_key=''\nexec 9>\"$STATE/start.lock\"\nflock -w 60 9\n# Background children close fd 9 (`9>&-`): an orcad that inherited it would hold the lock for its whole\n# life and every later start (resume of a running sandbox, a retried create) would wait out the 60 s.\n\n# orcad only lists a project once a client registers it (the desktop does on connect), so API, MCP,\n# routine and phone sessions saw no repo. Register the workspace project at every start, in the\n# background (ready is not delayed); `repo add` of an already-registered path is a no-op error.\nregister_project() {\n [ -x \"$ORCA_HOME/bin/orca\" ] && [ -d \"$PROJECT\" ] || return 0\n local kind=() name=()\n [ -e \"$PROJECT/.git\" ] || kind=(--kind folder)\n # The checkout lives at .../project; name it after the repository (owner/name.git -> name).\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n local base=\"${ORCA_REPO_URL%/}\"\n base=\"${base##*/}\"\n base=\"${base%.git}\"\n [ -n \"$base\" ] && name=(--display-name \"$base\")\n fi\n setsid \"$ORCA_HOME/bin/orca\" repo add --path \"$PROJECT\" \"${kind[@]}\" \"${name[@]}\" --json \\\n >\"$STATE/register-project.log\" 2>&1 &- &\n}\n\nprint_ready() {\n if [ \"${ORCA_READY_VIA:-}\" = file ]; then\n local sealed='' iv\n if [ -n \"$ready_key\" ] && command -v openssl >/dev/null; then\n iv=\"$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')\"\n # Best effort: without it the control plane reads the file, as before.\n sealed=\"$(tail -n 1 \"$STATE/ready.json\" | openssl enc -aes-256-ctr -K \"$ready_key\" -iv \"$iv\" -nosalt | base64 -w0)\" &&\n sealed=\"$iv.$sealed\" || sealed=''\n fi\n printf '{\"schemaVersion\":1,\"readyFile\":\"%s\"%s}\\n' \"$STATE/ready.json\" \"${sealed:+,\\\"sealedOffer\\\":\\\"$sealed\\\"}\"\n else\n tail -n 1 \"$STATE/ready.json\"\n fi\n}\n# Command stderr is kept by the provider: strip injected values and credential shapes from log tails.\nredact_log() {\n local text kv value\n text=\"$(cat)\"\n for kv in ${agent_env[@]+\"${agent_env[@]}\"}; do\n value=\"${kv#*=}\"\n if [ \"${#value}\" -ge 8 ]; then\n text=\"${text//\"$value\"/[REDACTED]}\"\n fi\n done\n printf '%s\\n' \"$text\" | sed -E \\\n -e 's#orca://[^[:space:]]+#[REDACTED_PAIRING]#g' \\\n -e 's#(gh[pousr]_|github_pat_|sk-|vc[kpiar]_)[A-Za-z0-9._-]{16,}#[REDACTED_TOKEN]#g' \\\n -e 's#eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}#[REDACTED_JWT]#g' \\\n -e 's#(Authorization|authorization):[[:space:]]*[A-Za-z]+[[:space:]]+[^[:space:]]+#\\1: [REDACTED]#g'\n}\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n\n# Share-link proxy (port 6769): answers only requests the control plane signed with this session's\n# key, so its public route is useless on its own. The key goes in on stdin (printf is a builtin), so\n# it never appears in any argv or in the proxy's /proc//environ.\nstart_share_proxy() {\n [ -n \"${ORCA_SHARE_PROXY_KEY:-}\" ] && [ -x \"$ORCA_HOME/bin/orca-share-proxy\" ] || return 0\n if [ \"$(cat \"$STATE/share-proxy.boot\" 2>/dev/null || true)\" = \"$boot_id\" ] \\\n && kill -0 \"$(cat \"$STATE/share-proxy.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n return 0\n fi\n printf '%s' \"$ORCA_SHARE_PROXY_KEY\" | env -i HOME=\"$HOME\" LANG=C.UTF-8 PATH=/usr/bin:/bin \\\n setsid \"$node\" \"$ORCA_HOME/bin/orca-share-proxy\" >\"$STATE/share-proxy.log\" 2>&1 9>&- &\n echo $! >\"$STATE/share-proxy.pid\"\n printf '%s' \"$boot_id\" >\"$STATE/share-proxy.boot\"\n}\n\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nstart_share_proxy\nunset ORCA_SHARE_PROXY_KEY\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" = \"$boot_id\" ] && [ -s \"$STATE/ready.json\" ] \\\n && kill -0 \"$(cat \"$STATE/orcad.pid\" 2>/dev/null || echo 0)\" 2>/dev/null; then\n print_ready\n exit 0\nfi\n# Resume = reboot from disk: locks and pids from the previous session name dead processes.\nrm -f \"$STATE/ready.json\" \"$STATE/orcad.pid\"\nprintf '%s' \"$boot_id\" >\"$STATE/boot-id\"\n\nif [ -n \"${ORCA_GIT_EXTRAHEADER:-}\" ]; then\n # Every github.com request carries the placeholder; the egress policy swaps in a 1h repo token.\n git config --global http.https://github.com/.extraheader \"$ORCA_GIT_EXTRAHEADER\"\nfi\n# Commits outside a teammate's turn (or before any member connected GitHub) need an author too.\ngit config --global user.email >/dev/null 2>&1 || git config --global user.email 'cloud@users.noreply.onorca.dev'\ngit config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca Cloud'\n# First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both.\nclone_pid=''\nif [ ! -d \"$PROJECT\" ]; then\n mkdir -p \"$PROJECT\"\n if [ -n \"${ORCA_REPO_URL:-}\" ]; then\n git clone --quiet ${ORCA_REPO_REF:+--branch \"$ORCA_REPO_REF\"} -- \"$ORCA_REPO_URL\" \"$PROJECT\" 2>\"$STATE/clone.log\" 9>&- &\n clone_pid=$!\n fi\nfi\n\n# The clone may still be running here, so the name comes from the URL; the default branch is\n# filled in lazily by the session-env shell hook once the clone exists.\nif [ -n \"${ORCA_REPO_URL:-}\" ]; then\n workspace_name=\"$(basename \"${ORCA_REPO_URL%/}\" .git)\"\nelse\n workspace_name=\"$(basename \"$(git -C \"$PROJECT\" remote get-url origin 2>/dev/null || echo \"$PROJECT\")\" .git)\"\nfi\n# One workspace per VM: its preview ports start at 3000 (Conductor allots CONDUCTOR_PORT..+9).\nmanaged_env=(\n ORCA_IS_CLOUD=1\n ORCA_ROOT_PATH=\"$PROJECT\" ORCA_WORKTREE_PATH=\"$PROJECT\" ORCA_WORKSPACE_PATH=\"$PROJECT\"\n ORCA_WORKSPACE_NAME=\"$workspace_name\" ORCA_PORT=3000\n CONDUCTOR_IS_CLOUD=1\n # Agent CLIs are pinned by the image (smoke-tested); a self-update mid-session can break a running agent.\n DISABLE_AUTOUPDATER=1 OPENCODE_DISABLE_AUTOUPDATE=1 COPILOT_AUTO_UPDATE=false\n CONDUCTOR_ROOT_PATH=\"$PROJECT\" CONDUCTOR_WORKSPACE_PATH=\"$PROJECT\"\n CONDUCTOR_WORKSPACE_NAME=\"$workspace_name\" CONDUCTOR_PORT=3000\n)\n\nagent_env=()\nif command -v google-chrome >/dev/null; then\n # Orca's browser automation and agent browser tools use the image's headless Chrome.\n agent_env+=(\"ORCA_BROWSER_EXECUTABLE=$(command -v google-chrome)\")\nfi\nif [ -n \"${ORCA_GITHUB_PLACEHOLDER:-}\" ]; then\n # The egress layer swaps the placeholder for a short-lived GitHub token; none lives in the VM.\n agent_env+=(\"GH_TOKEN=$ORCA_GITHUB_PLACEHOLDER\" \"GITHUB_TOKEN=$ORCA_GITHUB_PLACEHOLDER\")\nfi\n\nsecret_names=()\nif [ -n \"${ORCA_SECRET_ENV:-}\" ]; then\n # Secrets live only in memory: orcad's process env and a tmpfs file new shells re-read\n # (orca-sandbox-env), never under $HOME or the project, so the stop snapshot never carries them.\n # Resolved per start (and per edit) by the control plane: no image rebuild, no restart.\n while IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\" # not IFS='=': read would strip base64 padding\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n agent_env+=(\"$name=$(printf '%s' \"$b64\" | base64 -d)\")\n secret_names+=(\"$name\")\n done < <(printf '%s\\n' \"$ORCA_SECRET_ENV\") # a pipe, not a here-string temp file\nfi\n# Always rewrite the file, so a resume with fewer secrets drops the old names too.\n\"$ORCA_HOME/bin/orca-sandbox-env\" >/dev/null || echo 'session env file unavailable; secrets apply at boot only' >&2\nunset ORCA_SECRET_ENV\n\n# Agent CLIs installed with the image's npm (codex, gemini, ...) are `#!/usr/bin/env node` scripts:\n# terminals need that node on PATH, not only orcad's bundled runtime.\nsystem_node=\"$(command -v node 2>/dev/null || echo \"$node\")\"\n# The egress proxy answers for hosts with credential rules (model APIs, api.github.com) with a\n# certificate from Vercel's CA, which this command's env trusts (Vercel sets these). Pure-Node clients\n# use Node's bundled roots otherwise: Gemini CLI retried forever (\"taking a bit longer\") in every\n# terminal while the same call worked here. Pass the provider's CA settings on to orcad and its shells.\nca_env=(NODE_USE_SYSTEM_CA=\"${NODE_USE_SYSTEM_CA:-1}\")\nfor name in NODE_EXTRA_CA_CERTS SSL_CERT_FILE; do\n if [ -n \"${!name:-}\" ]; then ca_env+=(\"$name=${!name}\"); fi\ndone\n# Ports panel: programs under $ORCA_HOME are the image's own services, and 23456 is Vercel's\n# sandbox-init (root, pid invisible to this user); neither is listed as the user's port.\nenv -i HOME=\"$HOME\" USER=\"$(id -un)\" LANG=C.UTF-8 TERM=xterm-256color \"${ca_env[@]}\" \\\n PATH=\"$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname \"$system_node\"):/usr/local/bin:/usr/bin:/bin\" \\\n ORCA_USER_DATA=\"$HOME/.orcad-data\" ORCA_SANDBOX_ID=\"$ORCA_SANDBOX_ID\" \"${managed_env[@]}\" \\\n ORCA_HOST_MANAGED_LISTENER_PATHS=\"$ORCA_HOME\" ORCA_HOST_MANAGED_UNOWNED_PORTS=23456 \\\n NODE_COMPILE_CACHE=\"$ORCA_HOME/compile-cache\" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR=\"$ORCA_HOME/startup-qualification\" \\\n ORCA_SESSION_ENV_NAMES=\"${secret_names[*]}\" \"${agent_env[@]}\" \\\n setsid nohup \"$node\" \"$ORCA_HOME/bin/orcad-boot\" --code-cache \"$ORCA_HOME/compile-cache/orcad-server.v8\" \\\n \"$ORCA_HOME/runtime/orcad/orcad-server.js\" --port 6768 --bind 0.0.0.0 --pairing-address \"$ORCA_PUBLIC_WSS\" \\\n --recipe-json --project-root \"$PROJECT\" \\\n >\"$STATE/ready.json\" 2>\"$STATE/orcad.log\" &- &\necho $! >\"$STATE/orcad.pid\"\n\n# sshd for `orca ssh` (loopback only). Best effort: a workspace without it still serves orcad.\n\"$ORCA_HOME/bin/orca-sshd\" >/dev/null 2>\"$STATE/sshd-start.err\" || true\n\n# Polled every 10 ms (at least 60 s in all): ready is on the wake path, so detect it promptly.\nfor _ in $(seq 1 6000); do\n if grep -q '\"pairingCode\"' \"$STATE/ready.json\" 2>/dev/null; then\n if [ -n \"$clone_pid\" ] && ! wait \"$clone_pid\"; then\n echo 'repository clone failed' >&2\n tail -n 5 \"$STATE/clone.log\" | redact_log >&2\n exit 1\n fi\n register_project\n print_ready\n exit 0\n fi\n if ! kill -0 \"$(cat \"$STATE/orcad.pid\")\" 2>/dev/null; then\n echo 'orcad exited before ready' >&2\n tail -n 40 \"$STATE/orcad.log\" | redact_log >&2\n exit 1\n fi\n sleep 0.01\ndone\necho 'orcad start timed out' >&2\nexit 1\n","orca-sandbox-drain":"#!/usr/bin/env bash\n# Asks orcad to quit before the VM stops: its shutdown turns working agent chats into durable\n# restart offers and flushes terminal restore hints, which the desktop continues after resume.\nset -euo pipefail\nSTATE=\"$HOME/.orca-sandbox\"\nWAIT_SECONDS=\"${1:-280}\"\npid=\"$(cat \"$STATE/orcad.pid\" 2>/dev/null || true)\"\nif [ -z \"$pid\" ] || ! kill -0 \"$pid\" 2>/dev/null; then\n exit 0\nfi\nkill -TERM \"$pid\"\nfor _ in $(seq 1 $((WAIT_SECONDS * 10))); do\n if ! kill -0 \"$pid\" 2>/dev/null; then\n rm -f \"$STATE/orcad.pid\" \"$STATE/ready.json\"\n exit 0\n fi\n sleep 0.1\ndone\n# Leave it running: the provider stop ends it, and the drain already had its window.\necho 'orcad still draining at deadline' >&2\nexit 0\n","orca-sandbox-env":"#!/usr/bin/env bash\n# Writes this session's secret env where new shells and agent launches read it (orca-session-env.sh).\n# Input: ORCA_SECRET_ENV (`NAME=` lines) from the control plane, at boot (orca-sandbox-start)\n# and whenever a secret changes (POST /v1/sandboxes/:id/env/refresh). The file lives on tmpfs only:\n# never on the sandbox disk, so the stop snapshot never carries it. Prints {\"names\":N} on success.\n# Also keeps Codex pointed at a configured OpenAI-compatible provider (OPENAI_BASE_URL), since Codex\n# does not read that variable: a managed block in ~/.codex/config.toml naming only the env var.\nset -euo pipefail\numask 077\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\n# ORCA_SESSION_ENV_DIR: tests only (a scratch dir off tmpfs); the control plane never sets it.\ndir=\"${ORCA_SESSION_ENV_DIR:-/dev/shm/orca-env-$(id -u)}\"\nif [ -z \"${ORCA_SESSION_ENV_DIR:-}\" ] && [ \"$(stat -f -c %T /dev/shm 2>/dev/null || true)\" != tmpfs ]; then\n # No memory-only place to keep it: refuse rather than write secrets to disk.\n echo 'no tmpfs for the session env' >&2\n exit 3\nfi\nmkdir -p \"$dir\"\nchmod 700 \"$dir\"\n# Writes are ordered by the control plane's resolve time: an older refresh that lost a race is dropped.\ngeneration=\"${ORCA_ENV_GENERATION:-0}\"\ncase \"$generation\" in '' | *[!0-9]*) generation=0 ;; esac\ncurrent=\"$(cat \"$dir/generation\" 2>/dev/null || echo 0)\"\ncase \"$current\" in '' | *[!0-9]*) current=0 ;; esac\nif [ \"$generation\" -lt \"$current\" ]; then\n printf '{\"stale\":true}\\n'\n exit 0\nfi\ntmp=\"$(mktemp \"$dir/.session.env.XXXXXX\")\"\ncount=0\nopenai_base_url=''\nopenai_model=''\nanthropic_model=''\nanthropic_key_tail=''\ngateway_key=''\ngemini_key=''\ncodex_placeholder=''\nwhile IFS= read -r line; do\n name=\"${line%%=*}\" b64=\"${line#*=}\"\n # Not for shells: the Codex account placeholder becomes ~/.codex/auth.json below.\n if [ \"$name\" = ORCA_CODEX_AUTH_PLACEHOLDER ]; then\n codex_placeholder=\"$(printf '%s' \"$b64\" | base64 -d)\"\n case \"$codex_placeholder\" in *[!A-Za-z0-9._-]*) codex_placeholder='' ;; esac\n fi\n case \"$name\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n # Values stay base64 in the file; the shell hook decodes them.\n printf '%s=%s\\n' \"$name\" \"$b64\" >>\"$tmp\"\n count=$((count + 1))\n case \"$name\" in\n OPENAI_BASE_URL) openai_base_url=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n OPENAI_MODEL) openai_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n ANTHROPIC_MODEL) anthropic_model=\"$(printf '%s' \"$b64\" | base64 -d)\" ;;\n AI_GATEWAY_API_KEY) gateway_key=1 ;;\n GEMINI_API_KEY | GOOGLE_API_KEY) gemini_key=\"${gemini_key:-gemini-api-key}\" ;;\n GOOGLE_GENAI_USE_VERTEXAI) case \"$(printf '%s' \"$b64\" | base64 -d)\" in true | 1) gemini_key=vertex-ai ;; esac ;;\n # Claude Code asks once per key whether to use ANTHROPIC_API_KEY; it remembers the last 20 chars.\n ANTHROPIC_API_KEY) anthropic_key_tail=\"$(printf '%s' \"$b64\" | base64 -d | tail -c 20)\" ;;\n esac\ndone < <(printf '%s\\n' \"${ORCA_SECRET_ENV:-}\")\nmv -f \"$tmp\" \"$dir/session.env\"\nprintf '%s' \"$generation\" >\"$dir/generation\"\n\n# ---- Codex: trust the workspace and use the configured provider (no secret values) ----\nPROJECT=/vercel/sandbox/project\ncodex_config=\"$HOME/.codex/config.toml\"\ntoml_string() { # TOML basic string; the control plane only accepts https URLs and plain model ids\n local value=\"${1//\\\\/\\\\\\\\}\"\n printf '\"%s\"' \"${value//\\\"/\\\\\\\"}\"\n}\nstrip_managed() { # drop the managed blocks and the blank lines written before them (no growth per refresh)\n awk '/^# >>> orca-cloud managed/{skip=1; blank=\"\"} skip{if (/^# <<< orca-cloud managed/) skip=0; next}\n /^[[:space:]]*$/{blank=blank $0 \"\\n\"; next} {printf \"%s\", blank; blank=\"\"; print}' \"$1\"\n}\n# Always managed: an agent launched from the phone or the API has no one to answer Codex's\n# \"trust this folder?\" screen, so the workspace project is trusted up front.\nif true; then\n mkdir -p \"$HOME/.codex\"\n user_part=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n if [ -f \"$codex_config\" ]; then strip_managed \"$codex_config\" >\"$user_part\"; fi\n next=\"$(mktemp \"$HOME/.codex/.config.XXXXXX\")\"\n openai_host=\"${openai_base_url#https://}\"\n openai_host=\"${openai_host%%/*}\"\n custom_provider=''\n if [ -n \"$openai_base_url\" ] && [ \"$openai_host\" != api.openai.com ]; then custom_provider=1; fi\n # Top-level keys must precede every table; each is skipped when the user already set it.\n head_keys=\"$(awk '/^\\[/{exit} {print}' \"$user_part\")\"\n has_key() { grep -Eq \"^[[:space:]]*$1[[:space:]]*=\" <<<\"$head_keys\"; }\n {\n printf '# >>> orca-cloud managed (Orca Cloud; edit in Orca settings)\\n'\n # The sandbox is the isolation boundary: Codex's own bwrap sandbox can't start in it (\"Unexpected\n # capabilities\"), and a prompt delivered from the phone or the API has no one to approve commands.\n has_key sandbox_mode || printf 'sandbox_mode = \"danger-full-access\"\\n'\n has_key approval_policy || printf 'approval_policy = \"never\"\\n'\n if [ -n \"$custom_provider\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_cloud\"\\n'\n if [ -n \"$openai_model\" ] && ! has_key model; then\n printf 'model = %s\\n' \"$(toml_string \"$openai_model\")\"\n fi\n elif [ -n \"$codex_placeholder\" ]; then\n has_key model_provider || printf 'model_provider = \"orca_chatgpt\"\\n'\n fi\n printf '# <<< orca-cloud managed\\n'\n cat \"$user_part\"\n if [ -n \"$custom_provider\" ]; then\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_cloud]\\nname = \"Orca Cloud\"\\n'\n printf 'base_url = %s\\nenv_key = \"OPENAI_API_KEY\"\\nwire_api = \"responses\"\\n' \"$(toml_string \"$openai_base_url\")\"\n printf '# <<< orca-cloud managed\\n'\n elif [ -n \"$codex_placeholder\" ]; then\n # Codex via the Orca account: the ChatGPT backend over HTTPS. Its default Responses WebSocket can't\n # pass the egress proxy, where the placeholder becomes the real token (found live, Codex 0.166).\n printf '\\n# >>> orca-cloud managed provider\\n[model_providers.orca_chatgpt]\\nname = \"OpenAI\"\\n'\n printf 'base_url = \"https://chatgpt.com/backend-api/codex\"\\nwire_api = \"responses\"\\nrequires_openai_auth = true\\nsupports_websockets = false\\n'\n printf '# <<< orca-cloud managed\\n'\n fi\n } >\"$next\"\n if ! grep -qF \"[projects.\\\"$PROJECT\\\"]\" \"$user_part\"; then\n printf '\\n# >>> orca-cloud managed trust\\n[projects.\"%s\"]\\ntrust_level = \"trusted\"\\n# <<< orca-cloud managed\\n' \"$PROJECT\" >>\"$next\"\n fi\n chmod 600 \"$next\"\n mv -f \"$next\" \"$codex_config\"\n rm -f \"$user_part\"\nfi\n# ---- Codex via the person's Orca account (contract D11): a placeholder ChatGPT login, no refresh token.\n# The egress proxy swaps the real access token on chatgpt.com; the real tokens never reach this VM. The\n# marker remembers which placeholder Orca wrote (a clone gets its own), so a login of the person's own\n# (kill-switch fallback, or `codex login` run here) is set aside while the account applies and put back after.\ncodex_auth=\"$HOME/.codex/auth.json\"\ncodex_saved=\"$HOME/.codex/auth.json.orca-saved\"\ncodex_marker=\"$HOME/.codex/.orca-account-placeholder\"\ncodex_ours=''\n# Ours: the marker's placeholder, or any Orca placeholder (all end in `.orca-placeholder`; a real token never does).\nif [ -f \"$codex_auth\" ] && { { [ -f \"$codex_marker\" ] && grep -qF \"\\\"$(cat \"$codex_marker\")\\\"\" \"$codex_auth\"; } || grep -q '\\.orca-placeholder\"' \"$codex_auth\"; }; then\n codex_ours=1\nfi\nif [ -n \"$codex_placeholder\" ]; then\n mkdir -p \"$HOME/.codex\"\n if [ -f \"$codex_auth\" ] && [ -z \"$codex_ours\" ]; then\n # Never overwrite a login already set aside: a second one gets its own name.\n if [ -e \"$codex_saved\" ]; then mv -f \"$codex_auth\" \"$codex_saved.$(date -u +%Y%m%d%H%M%S)\"; else mv -f \"$codex_auth\" \"$codex_saved\"; fi\n fi\n # Marker first: a run cut short after the swap still recognises the file as Orca's.\n printf '%s' \"$codex_placeholder\" >\"$codex_marker\"\n codex_tmp=\"$(mktemp \"$HOME/.codex/.auth.XXXXXX\")\"\n printf '{\\n \"OPENAI_API_KEY\": null,\\n \"tokens\": {\\n \"id_token\": \"%s\",\\n \"access_token\": \"%s\",\\n \"refresh_token\": \"\",\\n \"account_id\": null\\n },\\n \"last_refresh\": \"%s\"\\n}\\n' \\\n \"$codex_placeholder\" \"$codex_placeholder\" \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\" >\"$codex_tmp\"\n chmod 600 \"$codex_tmp\"\n mv -f \"$codex_tmp\" \"$codex_auth\"\nelif [ -f \"$codex_marker\" ] || [ -n \"$codex_ours\" ]; then\n if [ -n \"$codex_ours\" ]; then rm -f \"$codex_auth\"; fi\n rm -f \"$codex_marker\"\n if [ -f \"$codex_saved\" ] && [ ! -f \"$codex_auth\" ]; then mv -f \"$codex_saved\" \"$codex_auth\"; fi\nfi\n# ---- Claude Code, Gemini CLI, Cursor agent, Copilot CLI, OpenCode: first-run screens answered once\n# (Claude: theme picker, folder trust, bypass-mode warning, the \"use this API key?\" question; others:\n# folder trust, auth-method picker, self-update). A prompt delivered from the phone or the API has no one to click\n# through them, and the agent would sit there doing nothing. Merges; never touches credentials.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nif [ -n \"$node_bin\" ]; then\n ORCA_PROJECT=\"$PROJECT\" ORCA_KEY_TAIL=\"$anthropic_key_tail\" ORCA_GEMINI_KEY=\"$gemini_key\" \\\n ORCA_GATEWAY_MODEL=\"${gateway_key:+${anthropic_model:-$openai_model}}\" \"$node_bin\" -e '\nconst fs = require(\"fs\"), path = require(\"path\"), os = require(\"os\")\nconst home = os.homedir()\nconst readJson = (file) => { try { const v = JSON.parse(fs.readFileSync(file, \"utf8\")); return v && typeof v === \"object\" && !Array.isArray(v) ? v : {} } catch { return {} } }\nconst write = (file, value) => {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\nconst claudeFile = path.join(process.env.CLAUDE_CONFIG_DIR || home, \".claude.json\")\nconst c = readJson(claudeFile)\nconst before = JSON.stringify(c)\nc.hasCompletedOnboarding = true\nc.theme = c.theme || \"dark\"\nc.bypassPermissionsModeAccepted = true\nc.projects = c.projects && typeof c.projects === \"object\" ? c.projects : {}\nconst p = process.env.ORCA_PROJECT\nc.projects[p] = { ...(c.projects[p] || {}), hasTrustDialogAccepted: true, hasCompletedProjectOnboarding: true }\nconst tail = process.env.ORCA_KEY_TAIL\nif (tail) {\n const r = c.customApiKeyResponses && typeof c.customApiKeyResponses === \"object\" ? c.customApiKeyResponses : {}\n const approved = Array.isArray(r.approved) ? r.approved : []\n const rejected = Array.isArray(r.rejected) ? r.rejected.filter((t) => t !== tail) : []\n c.customApiKeyResponses = { ...r, approved: approved.includes(tail) ? approved : [...approved, tail], rejected }\n}\nif (JSON.stringify(c) !== before) write(claudeFile, c)\nconst settingsFile = path.join(home, \".claude\", \"settings.json\")\nconst s = readJson(settingsFile)\nif (s.skipDangerousModePermissionPrompt !== true) write(settingsFile, { ...s, skipDangerousModePermissionPrompt: true })\n\n// Each block below only fills in what is unset and leaves a file it cannot parse alone.\nconst readStrict = (file) => { try { return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, \"utf8\")) : {} } catch { return null } }\nconst isObject = (v) => v !== null && typeof v === \"object\" && !Array.isArray(v)\nconst section = (o, key) => (isObject(o[key]) ? o[key] : (o[key] = {}))\n\n// Gemini CLI: folder trust and the auth-method picker (only when a Gemini key is configured; a\n// Google sign-in picks its own method), no self-update, no usage stats (its host is not on the\n// egress allowlist, so every send would fail).\nconst geminiTrustFile = path.join(home, \".gemini\", \"trustedFolders.json\")\nconst geminiTrust = readStrict(geminiTrustFile)\nif (isObject(geminiTrust) && !geminiTrust[p]) write(geminiTrustFile, { ...geminiTrust, [p]: \"TRUST_FOLDER\" })\nconst geminiSettingsFile = path.join(home, \".gemini\", \"settings.json\")\nconst g = readStrict(geminiSettingsFile)\nif (isObject(g)) {\n const gBefore = JSON.stringify(g)\n const general = section(g, \"general\")\n general.disableAutoUpdate ??= true\n general.disableUpdateNag ??= true\n section(g, \"privacy\").usageStatisticsEnabled ??= false\n // gemini-api-key or vertex-ai (GOOGLE_GENAI_USE_VERTEXAI=true with an API key): headless runs\n // refuse to start without a method (\"Invalid auth method selected\").\n if (process.env.ORCA_GEMINI_KEY) section(section(g, \"security\"), \"auth\").selectedType ??= process.env.ORCA_GEMINI_KEY\n if (JSON.stringify(g) !== gBefore) write(geminiSettingsFile, g)\n}\n\n// Cursor agent: trust the workspace (cursor-agent keys trust by a slug of the path) and pin the\n// release channel to \"static\", which turns off its background self-update.\nconst cursorTrust = path.join(home, \".cursor\", \"projects\", p.replace(/^\\/+/, \"\").replace(/[^A-Za-z0-9]+/g, \"-\"), \".workspace-trusted\")\nif (!fs.existsSync(cursorTrust)) {\n fs.mkdirSync(path.dirname(cursorTrust), { recursive: true, mode: 0o700 })\n fs.writeFileSync(cursorTrust, JSON.stringify({ trustedAt: new Date().toISOString(), workspacePath: p }, null, 2) + \"\\n\", { mode: 0o600 })\n}\nconst cursorConfigFile = path.join(home, \".cursor\", \"cli-config.json\")\nconst cc = readStrict(cursorConfigFile)\nif (isObject(cc) && cc.channel === undefined) write(cursorConfigFile, { version: 1, ...cc, channel: \"static\" })\n\n// GitHub Copilot CLI: trusted folders live in ~/.copilot/config.json, which Copilot prefixes with\n// \"//\" comment lines; keep them.\nconst copilotFile = path.join(home, \".copilot\", \"config.json\")\nlet copilotHead = \"\"\nlet co = {}\ntry {\n const raw = fs.existsSync(copilotFile) ? fs.readFileSync(copilotFile, \"utf8\") : \"\"\n const lines = raw.split(\"\\n\")\n let i = 0\n while (i < lines.length && /^\\s*\\/\\//.test(lines[i])) i++\n copilotHead = lines.slice(0, i).map((l) => l + \"\\n\").join(\"\")\n const body = lines.slice(i).join(\"\\n\").trim()\n co = body ? JSON.parse(body) : {}\n} catch { co = null }\nif (isObject(co)) {\n const folders = Array.isArray(co.trustedFolders) ? co.trustedFolders : []\n if (!folders.includes(p)) {\n fs.mkdirSync(path.dirname(copilotFile), { recursive: true, mode: 0o700 })\n const tmp = `${copilotFile}.orca-${process.pid}`\n fs.writeFileSync(tmp, copilotHead + JSON.stringify({ ...co, trustedFolders: [...folders, p] }, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, copilotFile)\n }\n}\n\n// OpenCode: with the AI Gateway preset and a model secret (ANTHROPIC_MODEL, else OPENAI_MODEL), use\n// that model through the gateway unless the user picked one. A ledger remembers what Orca wrote, so a\n// changed model secret updates it and a model the user set is never touched.\nconst ocDir = path.join(home, \".config\", \"opencode\")\nconst ocFile = path.join(ocDir, \"opencode.json\")\nconst ocLedger = path.join(ocDir, \".orca-managed-model\")\nconst managedModel = process.env.ORCA_GATEWAY_MODEL ? `vercel/${process.env.ORCA_GATEWAY_MODEL}` : \"\"\nconst oc = readStrict(ocFile)\nlet jsoncHasModel = false\ntry { jsoncHasModel = /\"model\"\\s*:/.test(fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\")) } catch {}\nif (isObject(oc) && !jsoncHasModel) {\n let ours = \"\"\n try { ours = fs.readFileSync(ocLedger, \"utf8\").trim() } catch {}\n const userModel = typeof oc.model === \"string\" && oc.model !== ours\n if (!userModel && (oc.model ?? \"\") !== managedModel) {\n const next = { $schema: \"https://opencode.ai/config.json\", ...oc }\n if (managedModel) next.model = managedModel\n else delete next.model\n write(ocFile, next)\n }\n if (!userModel) {\n if (managedModel) fs.writeFileSync(ocLedger, managedModel + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocLedger, { force: true })\n }\n}\n\n// OpenCode: two built-in providers cannot work in Orca Cloud, and with no other credential OpenCode\n// picks one and fails (\"Authorization header is badly formatted\" / opencode.ai unreachable) instead\n// of showing \"Connect a provider\". GitHub Copilot reads GITHUB_TOKEN, which here is the stand-in for the\n// GitHub App token of the workspace, never a Copilot token; OpenCode Zen needs opencode.ai, which is not on the\n// egress allowlist. Both stay off unless the user connected them in OpenCode itself (auth.json).\nconst ocAuth = readStrict(path.join(process.env.XDG_DATA_HOME || path.join(home, \".local\", \"share\"), \"opencode\", \"auth.json\"))\nconst connected = new Set(isObject(ocAuth) ? Object.keys(ocAuth) : [])\nconst ocDisabledLedger = path.join(ocDir, \".orca-managed-disabled-providers\")\nconst ocNow = readStrict(ocFile)\nif (isObject(ocNow) && !/\"disabled_providers\"\\s*:/.test((() => { try { return fs.readFileSync(path.join(ocDir, \"opencode.jsonc\"), \"utf8\") } catch { return \"\" } })())) {\n let ours = []\n try { ours = fs.readFileSync(ocDisabledLedger, \"utf8\").split(\"\\n\").filter(Boolean) } catch {}\n const userList = (Array.isArray(ocNow.disabled_providers) ? ocNow.disabled_providers : []).filter((id) => typeof id === \"string\" && !ours.includes(id))\n const managed = [\"github-copilot\", \"opencode\"].filter((id) => !connected.has(id) && !userList.includes(id))\n const next = [...userList, ...managed]\n const before = JSON.stringify(ocNow.disabled_providers ?? [])\n if (JSON.stringify(next) !== before) {\n const updated = { $schema: \"https://opencode.ai/config.json\", ...ocNow }\n if (next.length > 0) updated.disabled_providers = next\n else delete updated.disabled_providers\n write(ocFile, updated)\n }\n if (managed.length > 0) fs.writeFileSync(ocDisabledLedger, managed.join(\"\\n\") + \"\\n\", { mode: 0o600 })\n else fs.rmSync(ocDisabledLedger, { force: true })\n}\n' || echo 'agent first-run state not seeded' >&2\nfi\nprintf '{\"names\":%d}\\n' \"$count\"\n","orca-session-env.sh":"# Orca Cloud: sourced by every new bash/zsh (via /etc/profile.d) so terminals and agents started\n# after a secret edit get the current values with no restart. The file is written by\n# /opt/orca/bin/orca-sandbox-env on tmpfs; names it no longer lists are unset. Cloud secrets win\n# over same-named values already in the environment.\n__orca_env_file=\"/dev/shm/orca-env-$(id -u 2>/dev/null)/session.env\"\nif [ -r \"$__orca_env_file\" ]; then\n # $(...) word-splits in both bash and zsh.\n for __orca_n in $(printf '%s' \"${ORCA_SESSION_ENV_NAMES-}\"); do\n unset \"$__orca_n\" 2>/dev/null || true\n done\n __orca_names=''\n while IFS= read -r __orca_line || [ -n \"$__orca_line\" ]; do\n __orca_n=\"${__orca_line%%=*}\"\n case \"$__orca_n\" in '' | *[!A-Z0-9_]* | [0-9]* | ORCA_* | PATH | HOME | LD_* | DYLD_*) continue ;; esac\n export \"$__orca_n=$(printf '%s' \"${__orca_line#*=}\" | base64 -d 2>/dev/null)\"\n __orca_names=\"$__orca_names $__orca_n\"\n done <\"$__orca_env_file\"\n export ORCA_SESSION_ENV_NAMES=\"${__orca_names# }\"\nfi\n# Default branch of the cloud workspace repo, once its first-boot clone exists (computed once per shell tree).\nif [ -n \"${ORCA_WORKSPACE_PATH-}\" ] && [ -z \"${ORCA_DEFAULT_BRANCH-}\" ]; then\n __orca_branch=\"$(git -C \"$ORCA_WORKSPACE_PATH\" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)\"\n if [ -n \"$__orca_branch\" ]; then\n export ORCA_DEFAULT_BRANCH=\"${__orca_branch#origin/}\" CONDUCTOR_DEFAULT_BRANCH=\"${__orca_branch#origin/}\"\n fi\nfi\nunset __orca_env_file __orca_line __orca_n __orca_names __orca_branch\n","orca-env":"#!/usr/bin/env bash\n# Prints shell lines that bring the current shell up to date with this session's cloud env (secrets\n# saved after the shell started): eval \"$(orca-env)\" or, in fish: orca-env --fish | source\n# Reads /dev/shm/orca-env-/session.env (written by orca-sandbox-env, `NAME=` lines) and\n# prints an export for each name, plus an unset for each name in $ORCA_SESSION_ENV_NAMES that is gone.\n# Never writes a file. Values are single-quoted, so quotes, newlines and $ in them stay literal.\nset -euo pipefail\nfish=''\ncase \"${1-}\" in\n '') ;;\n --fish) fish=1 ;;\n -h | --help)\n printf 'usage: eval \"$(orca-env)\" (fish: orca-env --fish | source)\\n'\n exit 0\n ;;\n *)\n printf 'orca-env: unknown option %s\\n' \"$1\" >&2\n exit 2\n ;;\nesac\n# ORCA_SESSION_ENV_FILE is for tests; secrets can't set ORCA_* names.\nfile=\"${ORCA_SESSION_ENV_FILE:-/dev/shm/orca-env-$(id -u)/session.env}\"\nset -f # names are split below, never globbed\n# Not written yet (or not a cloud VM): nothing to change, like the shell hook.\n[ -r \"$file\" ] || exit 0\n\n# 'it'\\''s' for POSIX shells; fish single quotes escape only \\ and '.\nquote() {\n local v=\"$1\"\n if [ -n \"$fish\" ]; then\n v=\"${v//\\\\/\\\\\\\\}\"\n v=\"${v//\\'/\\\\\\'}\"\n printf \"'%s'\" \"$v\"\n else\n printf \"'%s'\" \"${v//\\'/\\'\\\\\\'\\'}\"\n fi\n}\n\n# The control plane's reserved names and prefixes (cloud/apps/sandbox-control/src/secrets.ts; a test\n# keeps this in sync): a session file never sets what would hijack the shell or Orca's own processes.\nskip_name() {\n case \"$1\" in\n '' | *[!A-Z0-9_]* | [0-9]*) return 0 ;;\n LD_* | DYLD_* | ORCA_* | VERCEL_* | BASH_FUNC_* | GIT_CONFIG*) return 0 ;;\n PATH | HOME | USER | LOGNAME | SHELL | PWD | OLDPWD | LANG | TERM | TMPDIR | IFS | ENV | \\\n BASH_ENV | PS4 | PROMPT_COMMAND | SHELLOPTS | BASHOPTS | NODE_OPTIONS | NODE_PATH | \\\n NODE_EXTRA_CA_CERTS | NODE_TLS_REJECT_UNAUTHORIZED | SSL_CERT_FILE | SSL_CERT_DIR | \\\n CURL_CA_BUNDLE | REQUESTS_CA_BUNDLE | HTTP_PROXY | HTTPS_PROXY | ALL_PROXY | NO_PROXY | \\\n PYTHONPATH | PYTHONSTARTUP | PERL5OPT | RUBYOPT | JAVA_TOOL_OPTIONS | GIT_SSH | \\\n GIT_SSH_COMMAND | GIT_ASKPASS | GIT_EXEC_PATH | GIT_PROXY_COMMAND | SSH_AUTH_SOCK | \\\n GH_TOKEN | GITHUB_TOKEN) return 0 ;;\n # CLAUDE_CODE_OAUTH_TOKEN is reserved for users but set by the control plane itself: only ever the\n # Orca-account placeholder (contract D10), never a stored value.\n esac\n return 1\n}\n\nnames=' '\nwhile IFS= read -r line || [ -n \"$line\" ]; do\n name=\"${line%%=*}\"\n skip_name \"$name\" && continue\n # $(...) drops trailing newlines; the x keeps them.\n value=\"$(printf '%s' \"${line#*=}\" | base64 -d 2>/dev/null; printf x)\"\n value=\"${value%x}\"\n if [ -n \"$fish\" ]; then\n printf 'set -gx %s %s\\n' \"$name\" \"$(quote \"$value\")\"\n else\n printf 'export %s=%s\\n' \"$name\" \"$(quote \"$value\")\"\n fi\n names=\"$names$name \"\ndone <\"$file\"\nfor name in ${ORCA_SESSION_ENV_NAMES-}; do\n skip_name \"$name\" && continue\n case \"$names\" in *\" $name \"*) continue ;; esac\n if [ -n \"$fish\" ]; then\n printf 'set -e %s\\n' \"$name\"\n else\n printf 'unset %s\\n' \"$name\"\n fi\ndone\nnames=\"${names# }\"\nnames=\"${names% }\"\nif [ -n \"$fish\" ]; then\n printf 'set -gx ORCA_SESSION_ENV_NAMES %s\\n' \"$(quote \"$names\")\"\nelse\n printf 'export ORCA_SESSION_ENV_NAMES=%s\\n' \"$(quote \"$names\")\"\nfi\n","orca-egress-probe":"#!/usr/bin/env bash\n# Bounded Node fetch against each credential host. Vercel transform rules have made undici hang on\n# response bodies (no content-length / transfer-encoding); report it instead of letting agents hang.\n# Prints one JSON line: {\"host\":\"api.github.com\",\"status\":\"ok\"|\"egress_framing_hang\"|\"error\"}.\nset -euo pipefail\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\nfor host in \"$@\"; do\n \"$node\" -e '\n const host = process.argv[1]\n const timer = setTimeout(() => { console.log(JSON.stringify({ host, status: \"egress_framing_hang\" })); process.exit(0) }, 8000)\n fetch(`https://${host}/`, { headers: { authorization: process.env.ORCA_PROBE_AUTHORIZATION ?? \"\" } })\n .then((r) => r.arrayBuffer())\n .then(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"ok\" })) })\n .catch(() => { clearTimeout(timer); console.log(JSON.stringify({ host, status: \"error\" })) })\n ' \"$host\"\ndone\n","orca-image-wipe":"#!/usr/bin/env bash\n# Runs last before the golden snapshot. Every sandbox cloned from the image must start without an\n# orcad identity, device registry, agent sign-in or shell history (clone-safe identity, risk #1).\nset -euo pipefail\npkill -f orcad-server.js 2>/dev/null || true\nfor path in \\\n \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\" \"$HOME/.orca-desktop\" \"$HOME/.config/orca\" \"$HOME/.config/orca-dev\" \\\n \"$HOME/.claude\" \"$HOME/.claude.json\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.gemini\" \\\n \"$HOME/.local/share/opencode\" \"$HOME/.config/opencode\" \"$HOME/.cursor\" \"$HOME/.config/cursor\" \\\n \"$HOME/.local/share/cursor-agent\" \"$HOME/.copilot\" \"$HOME/.npm\" \"$HOME/.cache\" \"$HOME/.config/google-chrome\" \"$HOME/.bash_history\" \\\n /vercel/sandbox/project; do\n rm -rf -- \"$path\"\ndone\nsudo rm -rf /tmp/* /var/tmp/* 2>/dev/null || true\nfor leftover in \"$HOME/.orcad-data\" \"$HOME/.claude\" \"$HOME/.codex\" \"$HOME/.config/gh\" \"$HOME/.cursor\" \"$HOME/.copilot\" \"$HOME/.gemini\"; do\n if [ -e \"$leftover\" ]; then\n echo \"identity survived wipe: $leftover\" >&2\n exit 1\n fi\ndone\necho '{\"wiped\":true}'\n","orca-agent-signout":"#!/usr/bin/env bash\n# Signs every agent out on this sandbox before Orca deletes it (A9): each agent's own logout, then\n# its credential files. Covers logins made inside the sandbox (the kill-switch fallback path).\n# Never fails: the sandbox is deleted next whatever happens. Values are never printed.\nset -u\nHOME=\"${HOME:-$(getent passwd \"$(id -u)\" | cut -d: -f6)}\"\nexport PATH=\"/opt/orca/tools/bin:$HOME/.local/bin:$HOME/.npm-global/bin:/usr/local/bin:/usr/bin:/bin:/opt/orca/bin:${PATH:-}\"\nclaude_dir=\"${CLAUDE_CONFIG_DIR:-$HOME/.claude}\"\nclaude_json=\"${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json\"\ncodex_dir=\"${CODEX_HOME:-$HOME/.codex}\"\n\nlogged_out=0\n# Each logout gets a few seconds; a hung CLI must not hold up the delete.\nif command -v claude >/dev/null 2>&1 && timeout 8 claude auth logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\nif command -v codex >/dev/null 2>&1 && timeout 8 codex logout /dev/null 2>&1; then\n logged_out=$((logged_out + 1))\nfi\n\n# The files go whether or not a logout ran: an older CLI, a missing binary or no network leaves them.\nrm -f -- \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\" 2>/dev/null\n# Orca-managed Codex homes keep their own auth.json under orcad's data dir.\nif [ -d \"$HOME/.orcad-data\" ]; then\n find \"$HOME/.orcad-data\" -path '*codex*' -type f -name auth.json -delete 2>/dev/null\nfi\n# ~/.claude.json keeps settings Orca wrote (onboarding, trust); only the sign-in fields go.\nnode_bin=\"$(command -v node || find /opt/orca/runtime/runtimes -type f -name node 2>/dev/null | head -n 1)\"\nfor file in \"$claude_json\" \"$HOME/.claude.json\"; do\n [ -f \"$file\" ] || continue\n if [ -n \"$node_bin\" ]; then\n ORCA_FILE=\"$file\" \"$node_bin\" -e '\nconst fs = require(\"fs\")\nconst file = process.env.ORCA_FILE\nlet c\ntry { c = JSON.parse(fs.readFileSync(file, \"utf8\")) } catch { process.exit(2) }\nif (!c || typeof c !== \"object\" || Array.isArray(c)) process.exit(2)\nlet changed = false\nfor (const key of Object.keys(c)) {\n if (/oauth/i.test(key) || key === \"primaryApiKey\") { delete c[key]; changed = true }\n}\nif (changed) {\n const tmp = `${file}.orca-${process.pid}`\n fs.writeFileSync(tmp, JSON.stringify(c, null, 2) + \"\\n\", { mode: 0o600 })\n fs.renameSync(tmp, file)\n}\n' 2>/dev/null || rm -f -- \"$file\"\n else\n # No node to edit it safely: losing Orca's settings beats leaving a sign-in behind.\n rm -f -- \"$file\"\n fi\ndone\n\nleft=0\nfor file in \"$claude_dir\"/.credentials* \"$HOME/.claude\"/.credentials* \"$codex_dir/auth.json\" \"$HOME/.codex/auth.json\"; do\n [ -e \"$file\" ] && left=$((left + 1))\ndone\nprintf '{\"loggedOut\":%d,\"left\":%d}\\n' \"$logged_out\" \"$left\"\n","orca-share-proxy":"#!/usr/bin/env node\n// Share-link proxy for this VM. Listens on 0.0.0.0:6769 (its public *.vercel.run route) and only\n// serves requests the control plane's share gateway signed with this session's key:\n// x-orca-share: v2.....\n// A request must start before `expiresAt` (60s windows); its response or WebSocket is closed at\n// `until` (the link's expiry, at most 30 minutes out), so a revoked or expired link also loses open\n// streams. Signed requests are reverse-proxied to 127.0.0.1:: streaming both ways, no\n// buffering, WebSocket upgrades piped raw. Anything unsigned gets a bare 404.\n// The key arrives on stdin (orca-sandbox-start pipes it), so it is never in this process's\n// environment or argv; ORCA_SHARE_PROXY_KEY in the env is accepted for tests. Optional\n// ORCA_SHARE_PROXY_PORT (default 6769). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst crypto = process.getBuiltinModule('node:crypto')\nconst fs = process.getBuiltinModule('node:fs')\nconst http = process.getBuiltinModule('node:http')\nconst net = process.getBuiltinModule('node:net')\n\nconst LISTEN_PORT = Number(process.env.ORCA_SHARE_PROXY_PORT || 6769)\nconst KEY = Buffer.from((process.env.ORCA_SHARE_PROXY_KEY || fs.readFileSync(0, 'utf8')).trim(), 'base64url')\ndelete process.env.ORCA_SHARE_PROXY_KEY\n// Never proxy to the VM's sshd, orcad or this proxy itself.\n// 6080: the remote desktop (VNC behind a password) is for its owner's forward only.\nconst BLOCKED_PORTS = new Set([2222, 6080, 6768, LISTEN_PORT])\nconst MAX_SKEW_SECONDS = 300\nconst MAX_CONNECTION_SECONDS = 3600\nconst HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'te', 'trailer', 'upgrade']\n\nif (KEY.length < 32) {\n console.error('orca-share-proxy: share proxy key missing or short')\n process.exit(2)\n}\n\n/** The target port and close-by time (ms) for a validly signed request, else null. */\nfunction verify(header, nowMs) {\n if (typeof header !== 'string') {\n return null\n }\n const match = /^v2\\.(\\d{1,5})\\.(\\d{1,12})\\.(\\d{1,12})\\.([0-9a-f]{32})\\.([A-Za-z0-9_-]{43})$/.exec(header)\n if (!match) {\n return null\n }\n const now = Math.floor(nowMs / 1000)\n const port = Number(match[1])\n const expiresAt = Number(match[2])\n const until = Number(match[3])\n if (port < 1 || port > 65535 || BLOCKED_PORTS.has(port)) {\n return null\n }\n if (expiresAt < now || expiresAt > now + MAX_SKEW_SECONDS || until <= now || until > now + MAX_CONNECTION_SECONDS) {\n return null\n }\n const signed = header.slice(0, header.lastIndexOf('.'))\n const expected = crypto.createHmac('sha256', KEY).update(signed).digest()\n const given = Buffer.from(match[5], 'base64url')\n return given.length === expected.length && crypto.timingSafeEqual(given, expected) ? { port, untilMs: until * 1000 } : null\n}\n\nfunction upstreamHeaders(raw, port) {\n const headers = { ...raw }\n const connectionTokens = String(raw.connection || '')\n .split(',')\n .map((token) => token.trim().toLowerCase())\n for (const name of [...HOP_BY_HOP, ...connectionTokens, 'x-orca-share']) {\n delete headers[name]\n }\n // Dev servers (Vite, Next) allow localhost hosts by default; the public host rides x-forwarded-host.\n headers.host = `localhost:${port}`\n return headers\n}\n\nfunction refuse(res) {\n res.writeHead(404, { 'content-type': 'text/plain', 'cache-control': 'no-store' })\n res.end('not found')\n}\n\n/** Ends `close` at the grant's deadline; the timer goes away with the connection. */\nfunction deadline(untilMs, close, ...emitters) {\n const timer = setTimeout(close, Math.max(0, untilMs - Date.now()))\n for (const emitter of emitters) {\n emitter.once('close', () => clearTimeout(timer))\n }\n}\n\nconst server = http.createServer((req, res) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n return refuse(res)\n }\n const { port } = grant\n const upstream = http.request(\n { host: '127.0.0.1', port, method: req.method, path: req.url, headers: upstreamHeaders(req.headers, port) },\n (answer) => {\n const headers = { ...answer.headers }\n for (const name of HOP_BY_HOP) {\n delete headers[name]\n }\n // Marks the answer as the app's, so the gateway can tell it from a route with no proxy behind it.\n headers['x-orca-share-proxy'] = '1'\n res.writeHead(answer.statusCode || 502, answer.statusMessage, headers)\n answer.pipe(res)\n }\n )\n deadline(grant.untilMs, () => {\n upstream.destroy()\n res.destroy()\n }, res)\n upstream.on('error', (error) => {\n if (res.headersSent) {\n res.destroy()\n return\n }\n // The gateway renders its own page for this; the code tells it why. Status 200 on purpose: a 5xx\n // from the VM reaches a Worker as Vercel's own 502 with our headers gone (found live).\n res.writeHead(200, { 'content-type': 'text/plain', 'x-orca-share-proxy': '1', 'x-orca-share-error': error.code === 'ECONNREFUSED' ? 'no_listener' : 'upstream_failed' })\n res.end('upstream unavailable')\n })\n req.on('aborted', () => upstream.destroy())\n req.pipe(upstream)\n})\n\nserver.on('upgrade', (req, socket, head) => {\n const grant = verify(req.headers['x-orca-share'], Date.now())\n if (grant === null) {\n socket.end('HTTP/1.1 404 Not Found\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n return\n }\n const { port } = grant\n const headers = upstreamHeaders(req.headers, port)\n const target = net.connect(port, '127.0.0.1', () => {\n const lines = [`${req.method} ${req.url} HTTP/1.1`, `connection: upgrade`, `upgrade: ${req.headers.upgrade || 'websocket'}`]\n for (const [name, value] of Object.entries(headers)) {\n for (const item of Array.isArray(value) ? value : [value]) {\n lines.push(`${name}: ${item}`)\n }\n }\n target.write(`${lines.join('\\r\\n')}\\r\\n\\r\\n`)\n if (head && head.length > 0) {\n target.write(head)\n }\n socket.pipe(target)\n target.pipe(socket)\n })\n const close = () => {\n socket.destroy()\n target.destroy()\n }\n deadline(grant.untilMs, close, socket)\n target.on('error', () => {\n if (socket.writable) {\n socket.end('HTTP/1.1 200 OK\\r\\nx-orca-share-proxy: 1\\r\\nx-orca-share-error: no_listener\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n')\n }\n close()\n })\n socket.on('error', close)\n target.on('close', () => socket.destroy())\n socket.on('close', () => target.destroy())\n})\n\nserver.keepAliveTimeout = 65_000\nserver.headersTimeout = 70_000\n// No request timeout: previews can stream (SSE, long polls) until the grant's deadline.\nserver.requestTimeout = 0\nserver.listen(LISTEN_PORT, '0.0.0.0', () => {\n console.log(`orca-share-proxy listening on ${LISTEN_PORT}`)\n})\n","orca-sshd":"#!/usr/bin/env bash\n# Starts this boot's unprivileged sshd on 127.0.0.1:2222 (idempotent). Nothing outside the VM can\n# reach that port: the desktop tunnels to it over orcad's runtime connection (`orca ssh-proxy`).\n# Key-only, single user (the sandbox user), no root. Its host key and authorized_keys live under\n# ~/.orca-sandbox/ssh on the persistent disk, so the host key stays the same across stop/resume;\n# orca-image-wipe removes that directory, so every VM cloned from the golden image makes its own.\n# Prints {\"port\":2222,\"user\":\"\",\"hostKey\":\"ssh-ed25519 AAAA...\"} on success.\nset -euo pipefail\numask 077\nOPENSSH=/opt/orca/openssh\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\nPORT=2222\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 8>\"$SSH_DIR/sshd.lock\"\nflock -w 30 8\n\nif [ ! -x \"$OPENSSH/sshd\" ]; then\n echo 'sshd is not installed in this image' >&2\n exit 3\nfi\nif [ ! -s \"$SSH_DIR/ssh_host_ed25519_key\" ]; then\n rm -f \"$SSH_DIR/ssh_host_ed25519_key\" \"$SSH_DIR/ssh_host_ed25519_key.pub\"\n ssh-keygen -q -t ed25519 -N '' -C \"orca-cloud-host\" -f \"$SSH_DIR/ssh_host_ed25519_key\"\nfi\ntouch \"$SSH_DIR/authorized_keys\"\nchmod 0600 \"$SSH_DIR/authorized_keys\"\n\n# Rewritten every start so an image update's settings apply to existing workspaces. PAM stays at\n# its compiled-in default (off): an unprivileged sshd cannot use it, and this build warns on `no`.\ncat >\"$SSH_DIR/sshd_config\" </dev/null || echo 0)\"\n# Resume reboots from disk, so a recorded pid can name a dead process or an unrelated one.\nif ! { kill -0 \"$pid\" 2>/dev/null && grep -q sshd \"/proc/$pid/cmdline\" 2>/dev/null; }; then\n rm -f \"$SSH_DIR/sshd.pid\"\n : >\"$SSH_DIR/sshd.log\"\n \"$OPENSSH/sshd\" -t -f \"$SSH_DIR/sshd_config\"\n \"$OPENSSH/sshd\" -f \"$SSH_DIR/sshd_config\" -E \"$SSH_DIR/sshd.log\"\n for _ in $(seq 1 100); do\n [ -s \"$SSH_DIR/sshd.pid\" ] && break\n sleep 0.02\n done\n [ -s \"$SSH_DIR/sshd.pid\" ] || { echo 'sshd did not start' >&2; tail -n 20 \"$SSH_DIR/sshd.log\" >&2; exit 1; }\nfi\n\nhost_key=\"$(cut -d' ' -f1-2 \"$SSH_DIR/ssh_host_ed25519_key.pub\")\"\nprintf '{\"port\":%s,\"user\":\"%s\",\"hostKey\":\"%s\"}\\n' \"$PORT\" \"$(id -un)\" \"$host_key\"\n","orca-ssh-keys":"#!/usr/bin/env bash\n# `orca-ssh-keys add|remove`: adds or removes one desktop's key in the Orca-managed authorized_keys\n# of this VM's sshd, then makes sure sshd runs. The control plane passes the key in\n# ORCA_SSH_PUBLIC_KEY (`ssh-ed25519 `), never on the command line. Keys are\n# matched by their base64 blob, so a renamed comment cannot keep a revoked key alive.\n# Prints orca-sshd's {\"port\":...,\"user\":...,\"hostKey\":...} line on success.\nset -euo pipefail\numask 077\nSSH_DIR=\"$HOME/.orca-sandbox/ssh\"\naction=\"${1:-}\"\nkey=\"${ORCA_SSH_PUBLIC_KEY:-}\"\n# grep matches per line: a second line could carry key options past the check below.\ncase \"$key\" in *$'\\n'* | *$'\\r'*) echo 'invalid public key' >&2; exit 2 ;; esac\n# One line, ed25519 only, a plain comment: nothing that sshd would read as key options.\nif ! printf '%s' \"$key\" | grep -Eq '^ssh-ed25519 [A-Za-z0-9+/]{68} [A-Za-z0-9@._:+-]{1,200}$'; then\n echo 'invalid public key' >&2\n exit 2\nfi\nblob=\"$(printf '%s' \"$key\" | cut -d' ' -f2)\"\nmkdir -p \"$SSH_DIR\"\nchmod 0700 \"$HOME/.orca-sandbox\" \"$SSH_DIR\"\nexec 7>\"$SSH_DIR/keys.lock\"\nflock -w 30 7\ntouch \"$SSH_DIR/authorized_keys\"\nnext=\"$(mktemp \"$SSH_DIR/authorized_keys.XXXXXX\")\"\n# Drop the key wherever it appears (with or without options), then append it on add.\nawk -v blob=\"$blob\" '{ for (i = 1; i <= NF; i++) if ($i == blob) next; print }' \\\n \"$SSH_DIR/authorized_keys\" >\"$next\"\ncase \"$action\" in\n add) printf '%s\\n' \"$key\" >>\"$next\" ;;\n remove) ;;\n *) rm -f \"$next\"; echo 'usage: orca-ssh-keys add|remove' >&2; exit 2 ;;\nesac\nchmod 0600 \"$next\"\nmv -f \"$next\" \"$SSH_DIR/authorized_keys\"\nexec /opt/orca/bin/orca-sshd\n","orca-desktop-start":"#!/usr/bin/env bash\n# Starts the on-demand remote desktop (idempotent) and mints one connection ticket. Prints one line:\n# {\"schemaVersion\":2,\"port\":6080,\"display\":\":1\",\"path\":\"vnc.html\",\"ticket\":\"<43 chars>\",\"expiresInMs\":60000}\n# Xvnc (X server + VNC in one) listens on a 0600 unix socket only, with no VNC auth: only this uid\n# can open it. orca-desktop-proxy (websockify + a ticket gate) serves noVNC on 127.0.0.1 and\n# bridges WebSockets to that socket. Nothing is reachable from outside the VM: the desktop app\n# reaches it through Orca's port forward, a localhost port on the user's computer that any local\n# process or web page can reach, so each WebSocket needs a ticket from here: 32 random bytes,\n# single use, valid for 60 s, stored only as its sha256 (the file name; its content is the expiry).\n# The ticket goes to stdout only (the control plane hands it to the desktop app). Never started at boot.\nset -euo pipefail\numask 077\nDESKTOP=/opt/orca/desktop\nSTATE=\"$HOME/.orca-desktop\"\nPORT=\"${ORCA_DESKTOP_PORT:-6080}\"\nDISPLAY_NUM=\"${ORCA_DESKTOP_DISPLAY:-1}\"\nGEOMETRY=\"${ORCA_DESKTOP_GEOMETRY:-1280x800}\"\nSOCKET=\"$STATE/vnc.sock\"\n# The parent's DISPLAY must not leak into the WM/xterm below; they use ours.\nexport DISPLAY=\":$DISPLAY_NUM\"\n\n# Exit 3 = this image has no desktop (built before it, or its optional install failed).\nfail() { printf 'orca-desktop: %s\\n' \"$1\" >&2; exit \"${2:-1}\"; }\ncase \"$PORT\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_PORT must be a number' ;; esac\ncase \"$DISPLAY_NUM\" in '' | *[!0-9]*) fail 'ORCA_DESKTOP_DISPLAY must be a number' ;; esac\ncase \"$GEOMETRY\" in [0-9]*x[0-9]*) ;; *) fail 'ORCA_DESKTOP_GEOMETRY must look like 1280x800' ;; esac\ncommand -v Xvnc >/dev/null || fail 'not installed in this image (Xvnc missing)' 3\n[ -s \"$DESKTOP/novnc/vnc.html\" ] || fail 'not installed in this image (noVNC missing)' 3\nPROXY=\"$(dirname \"$(readlink -f \"$0\")\")/orca-desktop-proxy\"\n[ -x \"$PROXY\" ] || fail 'orca-desktop-proxy missing next to this script'\nTICKETS=\"$STATE/tickets\"\nTICKET_TTL_S=60\n# Xvnc's mode: a previous version of this script ran it with VncAuth; restart it in this mode.\nMODE=ticket-v1\n\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/start.lock\"\nflock -w 30 9 || fail 'another start is in progress'\n\npid_of() { # never \"0\": kill 0 targets our own process group\n local pid\n pid=\"$(cat \"$STATE/$1.pid\" 2>/dev/null || true)\"\n case \"$pid\" in '' | 0 | *[!0-9]*) return 1 ;; esac\n printf '%s' \"$pid\"\n}\nalive() { local pid; pid=\"$(pid_of \"$1\")\" && kill -0 \"$pid\" 2>/dev/null; }\nmint_ticket() { # prints the ticket; stores only its sha256, with the expiry as content\n local ticket now digest\n mkdir -p \"$TICKETS\"\n now=\"$(date +%s)\"\n # Expired or spent-but-unswept tickets; keep at most 16 live ones (oldest go first).\n for file in \"$TICKETS\"/*; do\n [ -f \"$file\" ] || continue\n [ \"$(cat \"$file\" 2>/dev/null || echo 0)\" -ge \"$now\" ] 2>/dev/null || rm -f \"$file\"\n done\n # shellcheck disable=SC2012 # names are hex digests\n ls -1t \"$TICKETS\" 2>/dev/null | tail -n +16 | while read -r old; do rm -f \"$TICKETS/$old\"; done\n ticket=\"$(head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\\n')\"\n [ \"${#ticket}\" = 43 ] || fail 'could not generate a ticket'\n digest=\"$(printf '%s' \"$ticket\" | sha256sum | cut -d' ' -f1)\"\n printf '%s' \"$((now + TICKET_TTL_S))\" >\"$TICKETS/.$digest\" && mv \"$TICKETS/.$digest\" \"$TICKETS/$digest\"\n printf '%s' \"$ticket\"\n}\nready_line() {\n local ticket\n ticket=\"$(mint_ticket)\" || exit 1\n printf '{\"schemaVersion\":2,\"port\":%s,\"display\":\":%s\",\"path\":\"vnc.html\",\"ticket\":\"%s\",\"expiresInMs\":%s}\\n' \\\n \"$PORT\" \"$DISPLAY_NUM\" \"$ticket\" \"$((TICKET_TTL_S * 1000))\"\n}\nlistening() { # the proxy answers HTTP on loopback\n curl -fsS -o /dev/null --max-time 1 \"http://127.0.0.1:$PORT/vnc.html\" 2>/dev/null\n}\n\n# Pids from a previous boot (resume = reboot from disk) name dead or unrelated processes.\nboot_id=\"$(cat /proc/sys/kernel/random/boot_id)\"\nif [ \"$(cat \"$STATE/boot-id\" 2>/dev/null || true)\" != \"$boot_id\" ]; then\n rm -rf \"$STATE\"/*.pid \"$SOCKET\" \"$STATE/password\" \"$STATE/passwd\" \"$STATE/mode\" \"$TICKETS\"\n printf '%s' \"$boot_id\" >\"$STATE/boot-id\"\nfi\n\n# Same boot, older script: its websockify had no ticket gate and its Xvnc wanted a VNC password.\nrm -f \"$STATE/password\" \"$STATE/passwd\"\nif alive websockify; then kill \"$(pid_of websockify)\" 2>/dev/null || true; fi\nrm -f \"$STATE/websockify.pid\"\ncurrent_mode() { cat \"$STATE/mode\" 2>/dev/null || true; }\n\nif alive xvnc && alive proxy && listening && [ \"$(current_mode)\" = \"$MODE\" ]; then\n ready_line\n exit 0\nfi\n\nstart() { # name cmd... — detached, logs in $STATE/.log\n local name=$1; shift\n # 9>&-: children must not inherit the start lock, or the next call waits for them to exit.\n setsid nohup \"$@\" >\"$STATE/$name.log\" 2>&1 &- &\n echo $! >\"$STATE/$name.pid\"\n}\n\nif ! alive xvnc || [ \"$(current_mode)\" != \"$MODE\" ]; then\n if alive xvnc; then kill \"$(pid_of xvnc)\" 2>/dev/null || true; sleep 0.2; fi\n rm -f \"$SOCKET\"\n # -rfbport -1: no TCP VNC port at all, only a 0600 unix socket (in the 0700 state dir) for the\n # proxy. SecurityTypes None is safe only because of that: the ticket gate is in the proxy.\n # SendPrimary=0: only explicit copies (xterm copies its selection, below) leave the sandbox.\n # The X display itself takes a cookie from ~/.Xauthority (Xlib's default for this user), so only\n # this uid's processes (agents, apps they start on DISPLAY=:1) can open it.\n auth=()\n if command -v xauth >/dev/null && command -v mcookie >/dev/null; then\n xauth -q -f \"$HOME/.Xauthority\" add \":$DISPLAY_NUM\" . \"$(mcookie)\" 9>&- && auth=(-auth \"$HOME/.Xauthority\")\n fi\n start xvnc Xvnc \":$DISPLAY_NUM\" \"${auth[@]}\" -geometry \"$GEOMETRY\" -depth 24 -nolisten tcp \\\n -rfbport -1 -rfbunixpath \"$SOCKET\" -rfbunixmode 0600 \\\n -SecurityTypes None -SendPrimary=0 \\\n -AlwaysShared -AcceptSetDesktopSize -desktop 'Remote desktop'\n printf '%s' \"$MODE\" >\"$STATE/mode\"\n for _ in $(seq 1 100); do\n [ -S \"$SOCKET\" ] && break\n alive xvnc || { tail -n 20 \"$STATE/xvnc.log\" >&2; fail 'Xvnc exited'; }\n sleep 0.05\n done\n [ -S \"$SOCKET\" ] || fail 'Xvnc did not create its socket'\n if command -v xsetroot >/dev/null; then xsetroot -solid '#1e1f22' 9>&- || true; fi\n if command -v openbox >/dev/null; then\n # Dark, flat theme to match Orca; the first terminal stays maximized as the tab resizes the screen.\n printf '%s\\n' '' \\\n 'Onyx' \\\n 'yes' \\\n '' >\"$STATE/openbox.xml\"\n start wm openbox --config-file \"$STATE/openbox.xml\"\n # Let it manage the screen before the terminal maps, so its maximize rule applies.\n sleep 0.2\n elif command -v twm >/dev/null; then\n start wm twm\n fi\n if command -v xterm >/dev/null; then\n # selectToClipboard: a selection is a copy (to CLIPBOARD, which reaches this computer).\n start xterm xterm -maximized -bg '#1e1f22' -fg '#d4d4d4' -fa 'Liberation Mono,Monospace' -fs 11 \\\n -xrm 'XTerm*selectToClipboard: true'\n fi\nfi\n\nif ! alive proxy || ! listening; then\n if alive proxy; then kill \"$(pid_of proxy)\" 2>/dev/null || true; sleep 0.1; fi\n mkdir -p \"$TICKETS\"\n PYTHONPATH=\"$DESKTOP/websockify\" start proxy python3 -P -W ignore::UserWarning \"$PROXY\" \\\n --listen \"$PORT\" --web \"$DESKTOP/novnc\" --unix-target \"$SOCKET\" --tickets \"$TICKETS\"\n for _ in $(seq 1 100); do\n listening && break\n alive proxy || { tail -n 20 \"$STATE/proxy.log\" >&2; fail 'orca-desktop-proxy exited'; }\n sleep 0.05\n done\n listening || fail \"orca-desktop-proxy is not answering on 127.0.0.1:$PORT\"\nfi\nready_line\n","orca-desktop-proxy":"#!/usr/bin/env python3\n# Remote desktop gateway, started by orca-desktop-start: serves noVNC on 127.0.0.1 and bridges one\n# WebSocket per single-use ticket to Xvnc's 0600 unix socket (Xvnc itself has no VNC auth: only this\n# uid can open the socket). The port is reached only through Orca's localhost forward on the user's\n# computer, where any local process or web page could knock, so every WebSocket must carry an\n# unused, unexpired ticket minted by orca-desktop-start (see consume_ticket), from a page on the same\n# localhost origin. Tickets never reach a log: paths are scrubbed before websockify logs them.\n# orca-desktop-proxy --listen PORT --web DIR --unix-target SOCKET --tickets DIR\n# stdlib + websockify (pinned tarball in /opt/orca/desktop/websockify, on PYTHONPATH) only.\nimport argparse\nimport hashlib\nimport hmac\nimport logging\nimport os\nimport re\nimport sys\nimport time\nfrom urllib.parse import parse_qs, urlsplit\n\nfrom websockify import websocketproxy\n\nTICKET_RE = re.compile(r'^[A-Za-z0-9_-]{43}$') # 32 random bytes, base64url without padding\nSCRUB_RE = re.compile(r'([?&]ticket=)[^&\\s\\'\"]*')\nLOOPBACK_HOST_RE = re.compile(r'^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:[0-9]{1,5})?$')\nWS_PATH = '/websockify'\nPAGE_SCRIPT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'orca-desktop-page.js')\n# The page may only talk to its own origin (its WebSocket included): even a URL that tries to point\n# noVNC elsewhere cannot carry a ticket or the user's keys off this forward.\nPAGE_CSP = \"connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'\"\nPAGE_TAG = b'\\n'\n\n\ndef scrub(text):\n return SCRUB_RE.sub(r'\\1', str(text))\n\n\ndef ticket_digest(ticket):\n return hashlib.sha256(ticket.encode('ascii')).hexdigest()\n\n\ndef consume_ticket(directory, ticket, now=None):\n \"\"\"True once per minted ticket, within its lifetime. The ticket file (named by the ticket's\n sha256, holding its expiry) is unlinked on first use, so a replay or a racing second\n connection finds nothing; each request runs in its own forked process, so state is on disk.\"\"\"\n if not isinstance(ticket, str) or not TICKET_RE.match(ticket):\n return False\n digest = ticket_digest(ticket)\n match = None\n try:\n names = os.listdir(directory)\n except OSError:\n return False\n for name in names:\n # Compare every entry in constant time; never short-circuit on a prefix.\n if hmac.compare_digest(name.encode('ascii', 'replace'), digest.encode('ascii')):\n match = name\n if match is None:\n return False\n path = os.path.join(directory, match)\n try:\n with open(path, 'r', encoding='ascii') as handle:\n expires_at = int(handle.read().strip() or '0')\n except (OSError, ValueError):\n expires_at = 0\n try:\n os.unlink(path) # the consume: only one caller can win this\n except FileNotFoundError:\n return False\n return (now if now is not None else time.time()) <= expires_at\n\n\ndef same_loopback_origin(headers):\n \"\"\"The page and the WebSocket share one localhost origin (blocks other local sites and DNS\n rebinding). The port is the user's local forward, which may differ from ours, so compare the\n Origin with the Host the browser dialed rather than with a fixed port.\"\"\"\n host = (headers.get('Host') or '').strip().lower()\n origin = (headers.get('Origin') or '').strip().lower()\n return loopback_host(host) and origin == 'http://' + host\n\n\ndef loopback_host(host):\n return bool(LOOPBACK_HOST_RE.match(host or ''))\n\n\nclass TicketedProxyHandler(websocketproxy.ProxyRequestHandler):\n \"\"\"websockify's proxy handler plus the ticket + origin gate. Module level (not a closure) so\n websockify's per-connection multiprocessing can pickle it under any start method.\"\"\"\n\n def log_message(self, format, *args): # noqa: A002 (websockify's signature)\n super().log_message('%s', scrub(format % args if args else format))\n\n def reject(self, code, reason):\n self.send_response(code)\n self.send_header('Content-Length', '0')\n self.send_header('Connection', 'close')\n self.end_headers()\n self.close_connection = True\n raise self.server.EClose('desktop: websocket refused (%s)' % reason)\n\n def validate_connection(self):\n parts = urlsplit(self.path)\n ticket = (parse_qs(parts.query).get('ticket') or [''])[0]\n # Drop it before anything below (websockify's own logging included) can see self.path.\n self.path = parts.path\n if parts.path != WS_PATH:\n self.reject(404, 'path')\n if not same_loopback_origin(self.headers):\n self.reject(403, 'origin')\n if not consume_ticket(self.server.orca_tickets_dir, ticket):\n self.reject(403, 'ticket')\n\n def loopback_request(self):\n if loopback_host((self.headers.get('Host') or '').strip().lower()):\n return True\n self.send_error(403)\n return False\n\n def do_GET(self):\n if not self.loopback_request():\n return None\n path = urlsplit(self.path).path\n if path == '/orca-desktop-page.js':\n return self.send_bytes(read_file(PAGE_SCRIPT), 'text/javascript; charset=utf-8')\n if path == '/vnc.html':\n page = read_file(os.path.join(self.server.web, 'vnc.html'))\n return self.send_bytes(page.replace(b'', PAGE_TAG, 1), 'text/html; charset=utf-8', PAGE_CSP)\n return super().do_GET()\n\n def do_HEAD(self):\n if not self.loopback_request():\n return None\n return super().do_HEAD()\n\n def send_bytes(self, body, content_type, csp=None):\n self.send_response(200)\n self.send_header('Content-Type', content_type)\n if csp:\n self.send_header('Content-Security-Policy', csp)\n self.send_header('Content-Length', str(len(body)))\n self.send_header('Cache-Control', 'no-store')\n self.send_header('Referrer-Policy', 'no-referrer')\n self.end_headers()\n self.wfile.write(body)\n return None\n\n\ndef read_file(path):\n with open(path, 'rb') as handle:\n return handle.read()\n\n\ndef main(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--listen', type=int, required=True)\n parser.add_argument('--web', required=True)\n parser.add_argument('--unix-target', required=True)\n parser.add_argument('--tickets', required=True)\n args = parser.parse_args(argv)\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n server = websocketproxy.WebSocketProxy(\n RequestHandlerClass=TicketedProxyHandler,\n listen_host='127.0.0.1',\n listen_port=args.listen,\n web=args.web,\n file_only=True,\n unix_target=args.unix_target,\n )\n server.orca_tickets_dir = os.path.abspath(args.tickets)\n server.start_server()\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","orca-desktop-page.js":"// Orca's glue for noVNC, injected into vnc.html by orca-desktop-proxy. Orca (the desktop app's\n// main process) drives it through window.orcaDesktop:\n// - tickets: the page never connects by itself. Each WebSocket needs a fresh single-use ticket,\n// which Orca hands over with connect(ticket) after nextTicketRequest() resolves: 'ticket' on\n// load or after a session dropped, 'retry' after an attempt that never connected. Tickets live\n// only in memory here: never in the URL, storage or noVNC's settings.\n// - pause(message, label): Orca stopped retrying; show why, with a Reconnect button. resume()\n// (Orca reopened the desktop) or the button asks for a ticket again.\n// - fit: resize=remote makes Xvnc follow the tab; a server without SetDesktopSize gets scaling.\n// - clipboard: a copy inside the desktop right after user input there goes to this computer's\n// clipboard; paste(text, chord) sets the sandbox's clipboard first, then replays the paste key.\nimport UI from './app/ui.js';\nimport * as WebUtil from './app/webutil.js';\n\nconst WS_PATH = 'websockify';\nconst RESIZE_FALLBACK_MS = 1500;\n// A copy inside the desktop follows a copy key or a selection (drag or double-click) there; other\n// clipboard changes (an agent in the sandbox running xclip) must not overwrite this computer's\n// clipboard. Plain typing does not open the window.\nconst USER_COPY_WINDOW_MS = 1500;\nconst DRAG_PX = 4;\nconst MAX_CLIPBOARD_CHARS = 1 << 20;\nconst TICKET_RE = /^[A-Za-z0-9_-]{43}$/;\nconst XK = { v: 0x0076, V: 0x0056, Insert: 0xff63, Shift_L: 0xffe1, Super_L: 0xffeb, Super_R: 0xffec };\n\nlet state = 'idle'; // idle | connecting | connected | disconnected | paused\nlet attemptConnected = true;\nlet ticketWaiters = [];\nlet lastCopyIntent = 0;\nlet pointerStart = null;\n\nconst style = document.createElement('style');\n// Orca owns connecting and the chrome: noVNC's Connect button would only try without a ticket,\n// and its control bar duplicates what the Orca tab does (fit, clipboard, keyboard release).\n// The pause card follows Orca's theme: Orca sets Electron's theme source from its own setting, so\n// prefers-color-scheme here is Orca's light or dark, and it follows a switch while paused. The\n// page cannot read Orca's tokens, so these mirror them (popover, border, focus ring).\nstyle.textContent = `\n#noVNC_connect_dlg, #noVNC_control_bar_anchor { display: none !important; }\n#orca_pause { --orca-scrim: rgb(10 10 10 / 0.88); --orca-card: #171717; --orca-text: #f0f0f0;\n --orca-border: rgb(255 255 255 / 0.1); --orca-control: rgb(255 255 255 / 0.25);\n --orca-control-hover: rgb(255 255 255 / 0.08); --orca-focus: color-mix(in oklab, #f0f0f0 65%, #0a0a0a);\n color-scheme: dark; position: fixed; inset: 0; display: none; align-items: center;\n justify-content: center; padding: 16px; background: var(--orca-scrim); z-index: 1000;\n font: 13px/1.5 system-ui, sans-serif; }\n@media (prefers-color-scheme: light) {\n #orca_pause { --orca-scrim: rgb(255 255 255 / 0.88); --orca-card: #fff; --orca-text: #0a0a0a;\n --orca-border: #e5e5e5; --orca-control: #a3a3a3; --orca-control-hover: #f5f5f5;\n --orca-focus: color-mix(in oklab, #0a0a0a 55%, #fff); color-scheme: light; }\n}\n#orca_pause.open { display: flex; }\n#orca_pause > div { max-width: 360px; padding: 16px; border: 1px solid var(--orca-border);\n border-radius: 8px; background: var(--orca-card); color: var(--orca-text); text-align: center;\n box-shadow: 0 8px 24px rgb(0 0 0 / 0.16); }\n#orca_pause p { margin: 0; }\n#orca_pause button { margin-top: 12px; padding: 4px 12px; border: 1px solid var(--orca-control);\n border-radius: 6px; background: transparent; color: var(--orca-text); font: inherit; cursor: pointer; }\n#orca_pause button:hover { background: var(--orca-control-hover); }\n#orca_pause button:focus-visible { outline: 2px solid var(--orca-focus); outline-offset: 2px; }\n@media (prefers-reduced-motion: no-preference) {\n #orca_pause.open > div { animation: orca-pause-in 120ms ease-out; }\n}\n@keyframes orca-pause-in { from { opacity: 0; transform: translateY(4px); } }\n`;\ndocument.head.appendChild(style);\n\nconst overlay = document.createElement('div');\noverlay.id = 'orca_pause';\noverlay.innerHTML = '

    ';\noverlay.querySelector('button').addEventListener('click', () => resume());\ndocument.addEventListener('DOMContentLoaded', () => document.body.appendChild(overlay));\n\nwindow.addEventListener('keydown', (event) => {\n if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.key === 'c' || event.key === 'C' || event.key === 'Insert')) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerdown', (event) => {\n pointerStart = { x: event.clientX, y: event.clientY };\n}, true);\n// A double- or triple-click selects a word or line (pointer events carry no click count).\nwindow.addEventListener('mousedown', (event) => {\n if (event.detail >= 2) {\n lastCopyIntent = Date.now();\n }\n}, true);\nwindow.addEventListener('pointerup', (event) => {\n if (pointerStart && Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y) >= DRAG_PX) {\n lastCopyIntent = Date.now();\n }\n pointerStart = null;\n}, true);\n\nfunction requestTicket() {\n const answer = attemptConnected ? 'ticket' : 'retry';\n const waiters = ticketWaiters;\n ticketWaiters = [];\n waiters.forEach((resolve) => resolve(answer));\n}\n\nasync function whenStarted() {\n while (document.documentElement.classList.contains('noVNC_loading')) {\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n}\n\nfunction onConnect() {\n state = 'connected';\n attemptConnected = true;\n UI.hideStatus();\n setTimeout(() => {\n // Xvnc answers SetDesktopSize; anything that does not gets scaled into the tab instead.\n if (UI.rfb && state === 'connected' && !UI.rfb._supportsSetDesktopSize) {\n UI.rfb.scaleViewport = true;\n }\n }, RESIZE_FALLBACK_MS);\n}\n\nfunction onDisconnect() {\n if (state === 'paused') {\n return;\n }\n state = 'disconnected';\n // The ticket is spent: ask Orca for a new one (a dropped forward, a restart of the desktop).\n requestTicket();\n}\n\nfunction onClipboard(event) {\n const text = event.detail && event.detail.text;\n if (typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return;\n }\n if (Date.now() - lastCopyIntent > USER_COPY_WINDOW_MS || !document.hasFocus()) {\n return;\n }\n navigator.clipboard.writeText(text).catch(() => {});\n}\n\nasync function connect(ticket) {\n if (typeof ticket !== 'string' || !TICKET_RE.test(ticket)) {\n return 'invalid';\n }\n if (state === 'connecting' || state === 'connected' || state === 'paused') {\n return state;\n }\n await whenStarted();\n if (UI.rfb) {\n return 'connecting';\n }\n state = 'connecting';\n attemptConnected = false;\n // UI.connect reads the path setting synchronously and opens the WebSocket in RFB's constructor;\n // the in-memory setting is restored right after, so the ticket is never kept or shown.\n // Only ever this page's own origin: noVNC also reads host, port, encrypt, repeater and logging\n // from the URL, which must never send a ticketed session (and the user's keys) elsewhere.\n WebUtil.setSetting('host', '');\n WebUtil.setSetting('port', '');\n WebUtil.setSetting('encrypt', false);\n WebUtil.setSetting('repeaterID', '');\n WebUtil.setSetting('path', `${WS_PATH}?ticket=${ticket}`);\n try {\n UI.connect();\n } finally {\n WebUtil.setSetting('path', WS_PATH);\n }\n const rfb = UI.rfb;\n if (!rfb) {\n state = 'disconnected';\n requestTicket();\n return 'failed';\n }\n rfb.addEventListener('connect', onConnect);\n rfb.addEventListener('disconnect', onDisconnect);\n rfb.addEventListener('clipboard', onClipboard);\n return 'connecting';\n}\n\n/** Pastes this computer's clipboard: the sandbox's clipboard first, then the paste key itself. */\nfunction paste(text, chord) {\n const rfb = UI.rfb;\n if (!rfb || state !== 'connected' || typeof text !== 'string' || text.length > MAX_CLIPBOARD_CHARS) {\n return false;\n }\n rfb.clipboardPasteFrom(text);\n if (chord && chord.kind === 'mac') {\n // Cmd+V: Linux apps do not paste on Super+V, so release Super and send Shift+Insert.\n rfb.sendKey(XK.Super_L, 'MetaLeft', false);\n rfb.sendKey(XK.Super_R, 'MetaRight', false);\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', true);\n rfb.sendKey(XK.Insert, 'Insert');\n rfb.sendKey(XK.Shift_L, 'ShiftLeft', false);\n } else if (chord && chord.kind === 'replay') {\n // Ctrl+V, Ctrl+Shift+V, Shift+Insert: the held modifiers already reached the sandbox.\n const insert = chord.key === 'Insert';\n rfb.sendKey(insert ? XK.Insert : chord.key === 'V' ? XK.V : XK.v, insert ? 'Insert' : 'KeyV');\n }\n return true;\n}\n\nfunction pause(message, label, tone) {\n state = 'paused';\n if (UI.rfb) {\n UI.rfb.disconnect();\n }\n UI.hideStatus();\n overlay.querySelector('p').textContent = String(message || '');\n overlay.querySelector('button').textContent = String(label || 'Reconnect');\n // Asleep and starting are states, not errors: announce them politely.\n overlay.firstElementChild.setAttribute('role', tone === 'neutral' ? 'status' : 'alert');\n overlay.classList.add('open');\n overlay.querySelector('button').focus();\n return true;\n}\n\nfunction resume() {\n if (state !== 'paused') {\n return false;\n }\n overlay.classList.remove('open');\n state = 'disconnected';\n attemptConnected = true; // a person asked: start the retry budget over\n requestTicket();\n return true;\n}\n\nObject.defineProperty(window, 'orcaDesktop', {\n value: Object.freeze({\n version: 1,\n state: () => state,\n /** Resolves when the page needs a ticket: now if it is not connected, else after a drop. */\n nextTicketRequest: () => new Promise((resolve) => {\n ticketWaiters.push(resolve);\n if (state === 'idle' || state === 'disconnected') {\n requestTicket();\n }\n }),\n connect,\n paste,\n pause,\n resume\n })\n});\n","orca-sandbox-grant":"#!/usr/bin/env bash\n# Mints a fresh, single-device orcad pairing offer for one org member's device and seals it to that\n# device's X25519 key, so the control plane relays only ciphertext (the VM owner's E2EE model holds:\n# every member device gets its own revocable orcad credential, nobody else can read it).\n# Env from the control plane: ORCA_GRANT_ID, ORCA_GRANT_RECIPIENT_KEY (base64 raw X25519 public\n# key), ORCA_GRANT_KIND (desktop|mobile), ORCA_PUBLIC_WSS. Prints one JSON line:\n# {\"deviceId\":\"…\",\"sealed\":{\"v\":1,\"ephemeralPublicKeyB64\":\"…\",\"nonceB64\":\"…\",\"ciphertextB64\":\"…\"}}\n# Sealing: ECDH(ephemeral, recipient) -> HKDF-SHA256(salt = eph||recipient, info\n# \"orca-cloud-grant-v1\") -> AES-256-GCM, AAD \"orca-cloud-grant-v1:\".\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nSTATE=\"$HOME/.orca-sandbox\"\nDATA=\"$HOME/.orcad-data\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\n# One mint at a time: --rotate retires unredeemed offers, so two members never share a credential.\nflock -w 30 9\n\ncase \"${ORCA_GRANT_ID:-}\" in '' | *[!A-Za-z0-9_-]*) echo 'bad grant id' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_KIND:-}\" in desktop) scope=() ;; mobile) scope=(--mobile) ;; *) echo 'bad kind' >&2; exit 2 ;; esac\ncase \"${ORCA_GRANT_RECIPIENT_KEY:-}\" in '' | *[!A-Za-z0-9+/=]*) echo 'bad key' >&2; exit 2 ;; esac\ncase \"${ORCA_PUBLIC_WSS:-}\" in wss://*) ;; *) echo 'bad endpoint' >&2; exit 2 ;; esac\n\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\n# The workspace's project must exist on this orcad before a phone opens it: phones may not add\n# projects themselves (mobile RPC scope), and a phone may be the first client this VM ever sees.\nproject=/vercel/sandbox/project\nif [ -d \"$project\" ]; then\n kind=folder\n [ -d \"$project/.git\" ] && kind=git\n ORCA_USER_DATA_PATH=\"$DATA\" timeout 20 \"$node\" \"$cli\" repo add --path \"$project\" --kind \"$kind\" --json \\\n >/dev/null 2>&1 || true\nfi\noffer=\"$(ORCA_USER_DATA_PATH=\"$DATA\" timeout 30 \"$node\" \"$cli\" pair --json --rotate \"${scope[@]}\" \\\n --address \"$ORCA_PUBLIC_WSS\" 2>/dev/null)\" || { echo 'pair failed' >&2; exit 1; }\n# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.\nprintf '%s' \"$offer\" | ORCA_GRANT_ID=\"$ORCA_GRANT_ID\" ORCA_GRANT_RECIPIENT_KEY=\"$ORCA_GRANT_RECIPIENT_KEY\" \\\n \"$node\" -e '\nconst crypto = require(\"node:crypto\")\nlet input = \"\"\nprocess.stdin.on(\"data\", (c) => (input += c)).on(\"end\", () => {\n const res = JSON.parse(input).result\n if (!res || res.available !== true || !res.pairingUrl || !res.deviceId) {\n console.error(\"offer unavailable\")\n process.exit(1)\n }\n const recipient = Buffer.from(process.env.ORCA_GRANT_RECIPIENT_KEY, \"base64\")\n if (recipient.length !== 32) { console.error(\"bad key length\"); process.exit(2) }\n const recipientKey = crypto.createPublicKey({ key: { kty: \"OKP\", crv: \"X25519\", x: recipient.toString(\"base64url\") }, format: \"jwk\" })\n const eph = crypto.generateKeyPairSync(\"x25519\")\n const ephRaw = Buffer.from(eph.publicKey.export({ format: \"jwk\" }).x, \"base64url\")\n const shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: recipientKey })\n const key = Buffer.from(crypto.hkdfSync(\"sha256\", shared, Buffer.concat([ephRaw, recipient]), \"orca-cloud-grant-v1\", 32))\n const nonce = crypto.randomBytes(12)\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce)\n cipher.setAAD(Buffer.from(\"orca-cloud-grant-v1:\" + process.env.ORCA_GRANT_ID))\n const body = Buffer.from(JSON.stringify({ pairingUrl: res.pairingUrl, deviceId: res.deviceId, scope: res.scope }))\n const ct = Buffer.concat([cipher.update(body), cipher.final(), cipher.getAuthTag()])\n process.stdout.write(JSON.stringify({ deviceId: res.deviceId, sealed: { v: 1, ephemeralPublicKeyB64: ephRaw.toString(\"base64\"), nonceB64: nonce.toString(\"base64\"), ciphertextB64: ct.toString(\"base64\") } }) + \"\\n\")\n})'\n","orca-sandbox-revoke":"#!/usr/bin/env bash\n# Revokes member devices from orcad's device registry. orcad adopts on-disk removals at every auth\n# (an admin revoke, device-registry-store.ts), so this works whether or not orcad is running; the\n# control plane also runs it at boot, before orcad starts, for revokes queued while suspended.\n# Env: ORCA_REVOKE_DEVICE_IDS (comma list of orcad device ids). Prints {\"revoked\":,\"live\":}.\nset -euo pipefail\numask 077\nSTATE=\"$HOME/.orca-sandbox\"\nREGISTRY=\"$HOME/.orcad-data/orca-devices.json\"\nmkdir -p \"$STATE\"\nexec 9>\"$STATE/grant.lock\"\nflock -w 30 9\n\nids=\"${ORCA_REVOKE_DEVICE_IDS:-}\"\ncase \"$ids\" in '' | *[!A-Za-z0-9,_-]*) echo 'bad device ids' >&2; exit 2 ;; esac\n# Live orcad first: `orca pair --revoke` also closes the device's open sockets now. Older orcad\n# builds lack it; the on-disk removal below still blocks their next sign-in.\nORCA_HOME=/opt/orca\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node 2>/dev/null | head -n 1)\"\ncli=\"$ORCA_HOME/runtime/orcad/out/cli/index.js\"\nlive=0\nif [ -n \"$node\" ] && [ -f \"$cli\" ] && [ -s \"$HOME/.orcad-data/orca-runtime.json\" ]; then\n for id in ${ids//,/ }; do\n if ORCA_USER_DATA_PATH=\"$HOME/.orcad-data\" timeout 15 \"$node\" \"$cli\" pair --revoke \"$id\" --json 2>/dev/null \\\n | jq -e '.ok == true and .result.revoked == true' >/dev/null 2>&1; then\n live=$((live + 1))\n fi\n done\nfi\nif [ ! -s \"$REGISTRY\" ]; then\n echo \"{\\\"revoked\\\":$live,\\\"live\\\":$live}\"\n exit 0\nfi\nids_json=\"$(jq -cn --arg ids \"$ids\" '$ids | split(\",\") | map(select(length > 0))')\"\nbefore=\"$(jq 'length' \"$REGISTRY\")\"\ntmp=\"$(mktemp \"$REGISTRY.revoke.XXXXXX\")\"\n# Removes the rows and any phones delegated through them (parentDeviceId), like orcad's own revoke.\njq --argjson ids \"$ids_json\" \\\n '[.[] | select((.deviceId as $d | $ids | index($d)) == null and ((.parentDeviceId // \"\") as $p | $ids | index($p)) == null)]' \\\n \"$REGISTRY\" >\"$tmp\"\nchmod 0600 \"$tmp\"\nsync \"$tmp\" 2>/dev/null || true\nmv -f \"$tmp\" \"$REGISTRY\"\nafter=\"$(jq 'length' \"$REGISTRY\")\"\necho \"{\\\"revoked\\\":$((live + before - after)),\\\"live\\\":$live}\"\n","orca-sandbox-members":"#!/usr/bin/env bash\n# Runs as root (control plane, sudo). Installs who-may-push-as-whom for `orca-git-as`:\n# /etc/orca/members/.gitconfig egress placeholder header + GitHub author identity\n# /etc/orca/members/devices.json {\"\": \"\"} (each member's paired devices)\n# Both root-only: agents never read another member's placeholder. `orca-git-identity` (root, via a\n# sudoers rule) hands an agent only the identity of the member whose device drove its turn, as orcad\n# attests it. No token lives here: the placeholder is swapped at egress, for this repository only.\n# Env: ORCA_MEMBERS_B64 = base64 JSON [{userId, name, email, authorization, deviceIds:[...]}]\n# The VM user agents run as is orcad's own user (detected). Prints {\"members\":,\"devices\":}.\nset -euo pipefail\numask 077\nDIR=/etc/orca/members\norcad_pid=\"$(pgrep -f orcad-server.js | head -n 1 || true)\"\nUSER_NAME=\"$( [ -n \"$orcad_pid\" ] && ps -o user= -p \"$orcad_pid\" | tr -d ' ' || true)\"\nUSER_NAME=\"${USER_NAME:-${ORCA_SANDBOX_USER:-${SUDO_USER:-}}}\"\ncase \"$USER_NAME\" in '' | *[!a-z0-9_-]*) echo 'bad user' >&2; exit 2 ;; esac\nmkdir -p /etc/orca\njson=\"$(printf '%s' \"${ORCA_MEMBERS_B64:-W10=}\" | base64 -d)\"\ntmp=\"$(mktemp -d /etc/orca/members.XXXXXX)\"\ncount=0\nwhile IFS= read -r row; do\n user=\"$(jq -r '.userId' <<<\"$row\")\"\n case \"$user\" in '' | *[!A-Za-z0-9_.:-]*) continue ;; esac\n file=\"$tmp/$(printf '%s' \"$user\" | tr ':' '_').gitconfig\"\n # An empty extraheader first resets the image-wide (app identity) header for this member's git.\n git config -f \"$file\" --add http.https://github.com/.extraheader ''\n git config -f \"$file\" --add http.https://github.com/.extraheader \"Authorization: $(jq -r '.authorization' <<<\"$row\")\"\n git config -f \"$file\" user.name \"$(jq -r '.name' <<<\"$row\")\"\n git config -f \"$file\" user.email \"$(jq -r '.email' <<<\"$row\")\"\n count=$((count + 1))\ndone < <(jq -c '.[]' <<<\"$json\")\njq -c '[.[] | select(.userId | test(\"^[A-Za-z0-9_.:-]+$\")) | .userId as $u | (.deviceIds // [])[] | select(test(\"^[A-Za-z0-9_-]{1,128}$\")) | {key: ., value: $u}] | from_entries' <<<\"$json\" >\"$tmp/devices.json\"\ndevices=\"$(jq 'length' \"$tmp/devices.json\")\"\nchmod 0700 \"$tmp\" && chmod 0600 \"$tmp\"/*\nrm -rf \"$DIR.old\"\n[ -d \"$DIR\" ] && mv \"$DIR\" \"$DIR.old\"\nmv \"$tmp\" \"$DIR\"\nrm -rf \"$DIR.old\"\n# Agents may ask for their own sender's identity, and only that (the helper checks with orcad).\nrule=\"$USER_NAME ALL=(root) NOPASSWD:SETENV: /opt/orca/bin/orca-git-identity\"\nprintf '%s\\n' \"$rule\" >/etc/sudoers.d/orca-git-identity.new\nchmod 0440 /etc/sudoers.d/orca-git-identity.new\nif visudo -cf /etc/sudoers.d/orca-git-identity.new >/dev/null; then\n mv -f /etc/sudoers.d/orca-git-identity.new /etc/sudoers.d/orca-git-identity\nelse\n rm -f /etc/sudoers.d/orca-git-identity.new\n echo 'sudoers rule rejected' >&2\n exit 1\nfi\n# Pre-attestation layout (agent-readable member files) must not linger.\nuser_home=\"$(getent passwd \"$USER_NAME\" | cut -d: -f6)\"\n[ -n \"$orcad_pid\" ] && user_home=\"$(tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n 's/^HOME=//p' | head -n 1)\"\n[ -n \"$user_home\" ] && rm -rf \"$user_home/.orca-sandbox/members\"\n# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default).\nif [ -n \"$user_home\" ]; then\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.email 'cloud@users.noreply.onorca.dev'\n sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name >/dev/null 2>&1 \\\n || sudo -u \"$USER_NAME\" env HOME=\"$user_home\" git config --global user.name 'Orca Cloud'\nfi\necho \"{\\\"members\\\":$count,\\\"devices\\\":$devices}\"\n","orca-sandbox-read-snapshot":"#!/usr/bin/env bash\n# Seals a read-only snapshot of this workspace (chats, agent status, git, PR) to the reader keys the\n# control plane passes, right before the drain. Only ciphertext is printed (one JSON line); see\n# orca-read-snapshot.cjs. Exit 3: orcad isn't running (nothing to read).\nset -euo pipefail\numask 077\nORCA_HOME=/opt/orca\nexport ORCA_USER_DATA_PATH=\"${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}\"\nnode=\"$(find \"$ORCA_HOME/runtime/runtimes\" -type f -name node | head -n 1)\"\n[ -n \"$node\" ] || { echo 'node not found' >&2; exit 1; }\nexec timeout 35 \"$node\" \"$ORCA_HOME/bin/orca-read-snapshot.cjs\"\n","orca-read-snapshot.cjs":"#!/usr/bin/env node\n// Gathers what a sleeping workspace should still show (recent chats per agent session, agent\n// status, git status/diff summary, PR link) from the running orcad over its local socket, then seals\n// it to the reader keys the control plane passed, so only ciphertext leaves the VM.\n// Run by orca-sandbox-read-snapshot right before the drain. Env:\n// ORCA_READ_SNAPSHOT_ID rsn_<24 hex> ORCA_READ_WORKSPACE_ID sbx_<24 hex>\n// ORCA_READ_RECIPIENTS JSON [{keyId, publicKeyB64}] ORCA_READ_REASON sleep|rollover\n// ORCA_USER_DATA_PATH orcad's data dir (orca-runtime.json lives there)\n// Prints one JSON line: {v:1, snapshotId, workspaceId, nonceB64, ciphertextB64, recipients[], stats}.\n// Construction (keep in sync with src/shared/cloud-workspaces/read-snapshot.ts in the app):\n// body = AES-256-GCM(dek, nonce, JSON, AAD \"orca-cloud-read-v1::\")\n// wrapped = AES-256-GCM(HKDF-SHA256(X25519(eph, reader), eph||reader, \"orca-cloud-read-wrap-v1\"),\n// nonce_i, dek, AAD \"orca-cloud-read-wrap-v1:::\")\n'use strict'\nconst crypto = require('node:crypto')\nconst fs = require('node:fs')\nconst net = require('node:net')\nconst path = require('node:path')\n\nconst INFO = 'orca-cloud-read-v1'\nconst WRAP_INFO = 'orca-cloud-read-wrap-v1'\nconst PROJECT = '/vercel/sandbox/project'\nconst LIMITS = { sessions: 12, messagesPerSession: 60, messageChars: 4000, changes: 200, commits: 10 }\n/** Plaintext budget: sealed + base64 it stays under the control plane's 220 kB and the 256 kB stdout cap. */\nconst MAX_PLAIN_BYTES = 150_000\nconst CALL_TIMEOUT_MS = 5_000\nconst TOTAL_BUDGET_MS = 20_000\n\nfunction b64(bytes) {\n return Buffer.from(bytes).toString('base64')\n}\n\nfunction x25519PublicKey(raw) {\n return crypto.createPublicKey({ key: { kty: 'OKP', crv: 'X25519', x: Buffer.from(raw).toString('base64url') }, format: 'jwk' })\n}\n\nfunction gcmSeal(key, nonce, plain, aad) {\n const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce)\n cipher.setAAD(Buffer.from(aad))\n return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()])\n}\n\n/** Seals `payload` (an object) to every recipient; a malformed key is skipped, not fatal. */\nfunction seal(payload, recipients, workspaceId, snapshotId) {\n const scope = `${workspaceId}:${snapshotId}`\n const dek = crypto.randomBytes(32)\n const nonce = crypto.randomBytes(12)\n const ciphertext = gcmSeal(dek, nonce, Buffer.from(JSON.stringify(payload)), `${INFO}:${scope}`)\n const sealedTo = []\n for (const recipient of recipients) {\n const reader = Buffer.from(String(recipient.publicKeyB64 || ''), 'base64')\n if (reader.length !== 32 || !/^rk_[0-9a-f]{24}$/.test(String(recipient.keyId || ''))) {\n continue\n }\n let shared\n const eph = crypto.generateKeyPairSync('x25519')\n try {\n shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: x25519PublicKey(reader) })\n } catch {\n continue\n }\n if (shared.every((byte) => byte === 0)) {\n continue\n }\n const ephRaw = Buffer.from(eph.publicKey.export({ format: 'jwk' }).x, 'base64url')\n const kek = Buffer.from(crypto.hkdfSync('sha256', shared, Buffer.concat([ephRaw, reader]), WRAP_INFO, 32))\n const wrapNonce = crypto.randomBytes(12)\n const wrapped = gcmSeal(kek, wrapNonce, dek, `${WRAP_INFO}:${scope}:${recipient.keyId}`)\n sealedTo.push({ keyId: recipient.keyId, ephemeralPublicKeyB64: b64(ephRaw), nonceB64: b64(wrapNonce), wrappedKeyB64: b64(wrapped) })\n }\n dek.fill(0)\n return { v: 1, snapshotId, workspaceId, nonceB64: b64(nonce), ciphertextB64: b64(ciphertext), recipients: sealedTo }\n}\n\n// --- gathering -------------------------------------------------------------------------------\n\n/** One request per connection, like the CLI. A streaming method resolves on its first frame. */\nfunction rpc(metadata, method, params, timeoutMs = CALL_TIMEOUT_MS) {\n return new Promise((resolve) => {\n const transport = (metadata.transports || [metadata.transport]).find((t) => t && (t.kind === 'unix' || t.kind === 'named-pipe'))\n if (!transport) {\n resolve(null)\n return\n }\n const socket = net.createConnection(transport.endpoint)\n const id = crypto.randomUUID()\n let buffer = ''\n let done = false\n const finish = (value) => {\n if (!done) {\n done = true\n clearTimeout(timer)\n socket.destroy()\n resolve(value)\n }\n }\n const timer = setTimeout(() => finish(null), timeoutMs)\n socket.setEncoding('utf8')\n socket.on('error', () => finish(null))\n socket.on('close', () => finish(null))\n socket.on('connect', () => socket.write(`${JSON.stringify({ id, authToken: metadata.authToken, method, params })}\\n`))\n socket.on('data', (chunk) => {\n buffer += chunk\n let newline\n while ((newline = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, newline)\n buffer = buffer.slice(newline + 1)\n let frame\n try {\n frame = JSON.parse(line)\n } catch {\n continue\n }\n if (!frame || frame.id !== id) {\n continue\n }\n finish(frame.ok === true ? frame.result : null)\n return\n }\n })\n })\n}\n\nconst isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v)\nconst str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : null)\nconst num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null)\n\nfunction messagesOf(history) {\n const items = isObj(history) && isObj(history.page) && Array.isArray(history.page.items) ? history.page.items : []\n const out = []\n for (const item of items) {\n const body = isObj(item) && isObj(item.body) ? item.body : null\n if (!body || body.kind !== 'message' || !Array.isArray(body.blocks)) {\n continue\n }\n const role = body.role\n if (role !== 'user' && role !== 'assistant' && role !== 'system') {\n continue\n }\n const text = body.blocks\n .filter((b) => isObj(b) && b.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text)\n .join('\\n')\n .trim()\n if (text) {\n out.push({ itemId: String(item.itemId).slice(0, 200), role, text: text.slice(0, LIMITS.messageChars), at: num(item.observedAt) ?? 0 })\n }\n }\n return { messages: out, hasOlder: isObj(history) && isObj(history.page) && history.page.hasOlder === true }\n}\n\nfunction gitOf(status, log) {\n if (!isObj(status) && !isObj(log)) {\n return null\n }\n const entries = isObj(status) && Array.isArray(status.entries) ? status.entries.filter(isObj) : []\n let added = 0\n let removed = 0\n let counted = false\n const changes = entries.slice(0, LIMITS.changes).map((e) => {\n const a = num(e.added)\n const r = num(e.removed)\n if (a !== null || r !== null) {\n counted = true\n }\n return { path: String(e.path).slice(0, 1024), status: str(e.status, 20) || 'modified', area: str(e.area, 20) || 'unstaged', added: a, removed: r }\n })\n for (const e of entries) {\n added += num(e.added) || 0\n removed += num(e.removed) || 0\n }\n const items = isObj(log) && Array.isArray(log.items) ? log.items.filter(isObj) : []\n return {\n branch: isObj(status) && typeof status.branch === 'string' ? status.branch.replace(/^refs\\/heads\\//, '') : null,\n head: isObj(status) ? str(status.head, 64) : null,\n changes,\n changeCount: entries.length,\n added: counted ? added : null,\n removed: counted ? removed : null,\n commits: items.slice(0, LIMITS.commits).map((c) => ({\n id: String(c.id).slice(0, 64),\n subject: String(c.subject ?? '').slice(0, 300),\n author: str(c.author, 120),\n at: num(c.timestamp)\n }))\n }\n}\n\nfunction prOf(linked) {\n if (!isObj(linked) || num(linked.number) === null || typeof linked.url !== 'string' || !linked.url.startsWith('https://')) {\n return null\n }\n return {\n number: linked.number,\n title: String(linked.title ?? '').slice(0, 300),\n state: str(linked.state, 20) || 'open',\n url: linked.url.slice(0, 500),\n checksStatus: str(linked.checksStatus, 20),\n checksSummary: str(linked.checksSummary, 200)\n }\n}\n\nconst STATUSES = new Set(['working', 'attention', 'idle'])\nconst PANE_PREFIX = 'structured-agent-session-'\n\n/**\n * Chats as orcad stores them (agent-session-journal.db, read-only): every session's provider, name\n * and last turn, open tabs first. The local socket can't stream agentSession.subscribeStatus, and\n * worktree.ps lists only agents that are live right now, so this is the complete list.\n */\nfunction storedSessions(dataDir) {\n let db\n try {\n const { DatabaseSync } = require('node:sqlite')\n db = new DatabaseSync(path.join(dataDir, 'agent-session-journal.db'), { readOnly: true })\n const open = new Set(db.prepare('SELECT session_id FROM agent_session_tabs').all().map((r) => r.session_id))\n const out = []\n for (const row of db.prepare('SELECT session_id, record_json FROM agent_session_records').all()) {\n let record\n try {\n record = JSON.parse(row.record_json)\n } catch {\n continue\n }\n const last = isObj(record.lastTurn) ? record.lastTurn : {}\n out.push({\n sessionId: row.session_id,\n agent: str(record.provider, 40),\n title: str(record.conversationName, 200) || str(last.prompt, 200),\n status: last.state === 'running' || last.state === 'submitted' ? 'working' : last.state === 'settled' ? 'idle' : 'unknown',\n turnOutcome: str(last.outcome, 40),\n updatedAt: num(record.updatedAt),\n open: open.has(row.session_id),\n lastPrompt: str(last.prompt, LIMITS.messageChars),\n lastReply: str(last.reply, LIMITS.messageChars),\n lastAt: num(last.at)\n })\n }\n return out\n } catch {\n return []\n } finally {\n try {\n db && db.close()\n } catch {}\n }\n}\n\n/** Live agent rows from worktree.ps, keyed by session id (their status wins over the stored one). */\nfunction liveAgents(worktrees) {\n const out = new Map()\n for (const w of worktrees) {\n for (const a of Array.isArray(w.agents) ? w.agents.filter(isObj) : []) {\n const tab = typeof a.paneKey === 'string' ? a.paneKey.split(':')[0] : ''\n if (!tab.startsWith(PANE_PREFIX)) {\n continue\n }\n const state = a.mainAgent && typeof a.mainAgent.state === 'string' ? a.mainAgent.state : a.state\n out.set(tab.slice(PANE_PREFIX.length), {\n agent: str(a.agentType, 40),\n title: str(a.conversationName, 200) || str(a.taskTitle, 200) || str(a.displayName, 200),\n status: state === 'working' ? 'working' : state === 'blocked' || state === 'waiting' || state === 'attention' ? 'attention' : 'idle',\n updatedAt: num(a.updatedAt)\n })\n }\n }\n return out\n}\n\n/** `call(method, params)` -> result | null. Never throws: a missing piece is left out. */\nasync function gather(call, { workspaceId, snapshotId, reason, now, deadline, listSessions = () => [] }) {\n const timeLeft = () => deadline - Date.now()\n const ps = await call('worktree.ps', { limit: 20 })\n const worktrees = isObj(ps) && Array.isArray(ps.worktrees) ? ps.worktrees.filter(isObj) : []\n const project = worktrees.find((w) => w.path === PROJECT) || worktrees[0] || null\n const selector = project && typeof project.path === 'string' ? `path:${project.path}` : `path:${PROJECT}`\n const [status, log] = await Promise.all([\n call('git.status', { worktree: selector, includeLineStats: true }),\n call('git.history', { worktree: selector, limit: LIMITS.commits })\n ])\n const live = liveAgents(worktrees)\n const byId = new Map()\n for (const s of listSessions()) {\n byId.set(s.sessionId, s)\n }\n for (const [sessionId, a] of live) {\n byId.set(sessionId, { ...(byId.get(sessionId) || { sessionId, open: true }), ...Object.fromEntries(Object.entries(a).filter(([, v]) => v !== null)) })\n }\n // Open chats first, then newest activity.\n const picked = [...byId.values()]\n .filter((s) => typeof s.sessionId === 'string')\n .sort((a, b) => Number(Boolean(b.open)) - Number(Boolean(a.open)) || (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))\n .slice(0, LIMITS.sessions)\n const sessions = []\n for (const s of picked) {\n const history = timeLeft() > 1_000 ? await call('agentSession.history', { sessionId: s.sessionId, direction: 'tail', limit: LIMITS.messagesPerSession }) : null\n let { messages, hasOlder } = messagesOf(history)\n if (messages.length === 0) {\n // No readable history (or out of time): the stored last turn still says what happened.\n const at = s.lastAt || s.updatedAt || 0\n messages = [\n ...(s.lastPrompt ? [{ itemId: `${s.sessionId}:last-prompt`, role: 'user', text: s.lastPrompt, at }] : []),\n ...(s.lastReply ? [{ itemId: `${s.sessionId}:last-reply`, role: 'assistant', text: s.lastReply, at }] : [])\n ]\n hasOlder = hasOlder || messages.length > 0\n }\n sessions.push({\n sessionId: s.sessionId.slice(0, 200),\n agent: s.agent || null,\n title: s.title || null,\n status: STATUSES.has(s.status) ? s.status : 'unknown',\n turnOutcome: s.turnOutcome || null,\n updatedAt: num(s.updatedAt),\n messages: messages.slice(-LIMITS.messagesPerSession),\n truncated: hasOlder || messages.length > LIMITS.messagesPerSession\n })\n }\n return {\n v: 1,\n workspaceId,\n snapshotId,\n capturedAt: now,\n reason,\n git: gitOf(status, log),\n pr: prOf(project && project.linkedPR),\n sessions\n }\n}\n\n/** Cuts the oldest messages (then long texts, then sessions) until the JSON fits the budget. */\nfunction fitToBudget(payload, maxBytes = MAX_PLAIN_BYTES) {\n const size = () => Buffer.byteLength(JSON.stringify(payload))\n let guard = 0\n while (size() > maxBytes && guard++ < 10_000) {\n const longest = payload.sessions.reduce((best, s) => (!best || s.messages.length > best.messages.length ? s : best), null)\n if (longest && longest.messages.length > 4) {\n longest.messages.shift()\n longest.truncated = true\n continue\n }\n const longText = payload.sessions.flatMap((s) => s.messages).find((m) => m.text.length > 500)\n if (longText) {\n longText.text = `${longText.text.slice(0, 500)}…`\n continue\n }\n if (payload.git && payload.git.changes.length > 20) {\n payload.git.changes = payload.git.changes.slice(0, 20)\n continue\n }\n if (payload.sessions.length > 1) {\n payload.sessions.pop()\n continue\n }\n payload.sessions = []\n break\n }\n return payload\n}\n\nasync function main() {\n const started = Date.now()\n const env = process.env\n const snapshotId = env.ORCA_READ_SNAPSHOT_ID || ''\n const workspaceId = env.ORCA_READ_WORKSPACE_ID || ''\n if (!/^rsn_[0-9a-f]{24}$/.test(snapshotId) || !/^sbx_[0-9a-f]{24}$/.test(workspaceId)) {\n process.stderr.write('bad ids\\n')\n process.exit(2)\n }\n let recipients\n try {\n recipients = JSON.parse(env.ORCA_READ_RECIPIENTS || '[]')\n } catch {\n recipients = null\n }\n if (!Array.isArray(recipients) || recipients.length === 0) {\n process.stderr.write('no recipients\\n')\n process.exit(2)\n }\n const dataDir = env.ORCA_USER_DATA_PATH || path.join(env.HOME || '', '.orcad-data')\n let metadata\n try {\n metadata = JSON.parse(fs.readFileSync(path.join(dataDir, 'orca-runtime.json'), 'utf8'))\n } catch {\n metadata = null\n }\n if (!metadata || !metadata.authToken) {\n process.stderr.write('orcad not running\\n')\n process.exit(3)\n }\n const deadline = started + TOTAL_BUDGET_MS\n const call = (method, params) => rpc(metadata, method, params, Math.max(250, Math.min(CALL_TIMEOUT_MS, deadline - Date.now())))\n const payload = fitToBudget(\n await gather(call, { workspaceId, snapshotId, reason: (env.ORCA_READ_REASON || 'sleep').slice(0, 20), now: Date.now(), deadline, listSessions: () => storedSessions(dataDir) })\n )\n const out = seal(payload, recipients, workspaceId, snapshotId)\n // Timing only: counts and sizes would describe the plaintext to the control plane's logs.\n out.stats = { collectMs: Date.now() - started }\n process.stdout.write(`${JSON.stringify(out)}\\n`)\n}\n\nmodule.exports = { seal, gather, fitToBudget, messagesOf, gitOf, prOf, rpc, storedSessions, liveAgents }\n\nif (require.main === module) {\n // A fixed message: an error text could carry workspace content into the control plane's logs.\n main().catch(() => {\n process.stderr.write('read snapshot failed\\n')\n process.exit(1)\n })\n}\n","orca-git-as":"#!/usr/bin/env bash\n# Runs git as the teammate whose message started this agent's turn: their GitHub identity for\n# pushes/PRs (this repository only) and their commit author.\n# orca-git-as e.g. orca-git-as push origin HEAD\n# orca-git-as --as refuses unless that member really sent the message\n# Orca attests the sender from the paired device that sent the message, never from arguments or\n# message text. Without an attested sender (not run from an agent, or the owner's local session) it\n# runs plain git with the workspace identity.\nset -euo pipefail\nexpect=''\nif [ \"${1:-}\" = '--as' ]; then\n expect=\"${2:-}\"\n shift 2 || { echo 'usage: orca-git-as [--as ] ' >&2; exit 2; }\n case \"$expect\" in '' | *[!A-Za-z0-9_.:-]*) echo 'orca-git-as: bad member id' >&2; exit 2 ;; esac\nfi\nset +e\nfile=\"$(ORCA_GIT_AS=\"$expect\" sudo -n --preserve-env=ORCA_GIT_AS,ORCA_TERMINAL_HANDLE,ORCA_PANE_KEY,ORCA_AGENT_LAUNCH_TOKEN,ORCA_AGENT_SESSION_ID \\\n /opt/orca/bin/orca-git-identity)\"\nstatus=$?\nset -e\ncase \"$status\" in\n 0)\n trap 'rm -f \"$file\"' EXIT\n git -c \"include.path=$file\" \"$@\"\n ;;\n 3)\n echo 'orca-git-as: no teammate identity for this turn; using the workspace identity' >&2\n exec git \"$@\"\n ;;\n *) exit 4 ;;\nesac\n","orca-git-identity":"#!/usr/bin/env bash\n# Root helper behind `orca-git-as` (sudoers: the VM user may run only this). Asks orcad, as the\n# calling agent, which paired device sent the message that started the agent's latest turn\n# (`orca sender`: orcad identifies the agent from its launch evidence, never from arguments), maps\n# that device to a workspace member, and prints that member's git config file for the caller to\n# include. Optional ORCA_GIT_AS: the member the agent expects; any other answer is refused.\n# Exit codes: 0 printed a config path; 3 no member identity (use the workspace identity); 4 refused.\nset -euo pipefail\nDIR=/etc/orca/members\ncaller=\"${SUDO_USER:-}\"\ncase \"$caller\" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac\n# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).\norcad_pid=\"$(pgrep -u \"$caller\" -f orcad-server.js | head -n 1 || true)\"\n[ -n \"$orcad_pid\" ] || exit 3\norcad_env() { tr '\\0' '\\n' <\"/proc/$orcad_pid/environ\" | sed -n \"s/^$1=//p\" | head -n 1; }\nhome=\"$(orcad_env HOME)\"\ndata=\"$(orcad_env ORCA_USER_DATA)\"\ndata=\"${data:-$home/.orcad-data}\"\nnode=\"$(find /opt/orca/runtime/runtimes -type f -name node | head -n 1)\"\ncli=/opt/orca/runtime/orcad/out/cli/index.js\n# Only the evidence variables orcad needs reach the query, which runs as the caller, not root.\nanswer=\"$(sudo -u \"$caller\" env -i HOME=\"$home\" PATH=/usr/bin:/bin ORCA_USER_DATA_PATH=\"$data\" \\\n ${ORCA_TERMINAL_HANDLE:+ORCA_TERMINAL_HANDLE=\"$ORCA_TERMINAL_HANDLE\"} \\\n ${ORCA_PANE_KEY:+ORCA_PANE_KEY=\"$ORCA_PANE_KEY\"} \\\n ${ORCA_AGENT_LAUNCH_TOKEN:+ORCA_AGENT_LAUNCH_TOKEN=\"$ORCA_AGENT_LAUNCH_TOKEN\"} \\\n ${ORCA_AGENT_SESSION_ID:+ORCA_AGENT_SESSION_ID=\"$ORCA_AGENT_SESSION_ID\"} \\\n timeout 15 \"$node\" \"$cli\" sender --json 2>/dev/null || true)\"\ndevice=\"$(jq -r '.result.sender.deviceId // empty' <<<\"$answer\" 2>/dev/null || true)\"\nif [ -z \"$device\" ] || [ ! -s \"$DIR/devices.json\" ]; then\n if [ -n \"${ORCA_GIT_AS:-}\" ]; then\n echo \"orca-git-as: Orca cannot confirm that $ORCA_GIT_AS sent this agent's latest message; refusing to push as them.\" >&2\n exit 4\n fi\n exit 3\nfi\nmember=\"$(jq -r --arg d \"$device\" '.[$d] // empty' \"$DIR/devices.json\")\"\nif [ -z \"$member\" ]; then\n [ -n \"${ORCA_GIT_AS:-}\" ] && { echo \"orca-git-as: the sender's device is not linked to a workspace member; refusing.\" >&2; exit 4; }\n exit 3\nfi\nif [ -n \"${ORCA_GIT_AS:-}\" ] && [ \"$ORCA_GIT_AS\" != \"$member\" ]; then\n echo \"orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else.\" >&2\n exit 4\nfi\nfile=\"$DIR/$(printf '%s' \"$member\" | tr ':' '_').gitconfig\"\n[ -s \"$file\" ] || exit 3\n# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as).\nout=\"$(sudo -u \"$caller\" mktemp)\"\ncat \"$file\" >\"$out\"\necho \"$out\"\n","orcad-boot":"#!/usr/bin/env node\n// Starts orcad from a V8 code cache taken after a full startup, so a boot skips compiling the\n// functions startup runs. NODE_COMPILE_CACHE only stores what V8 compiles before the bundle runs\n// (about 5 of its 15 MB); every other function compiled lazily on every boot (~300 ms of wake).\n// orcad-boot --code-cache [--write-code-cache] [orcad args...]\n// orcad sees the argv `node [orcad args...]`, as if started directly.\n// --write-code-cache (the image's smoke run) writes the cache when orcad exits. The cache is used\n// only when its header matches this bundle's bytes and this Node; otherwise orcad loads exactly as\n// before (plain require, which NODE_COMPILE_CACHE still serves). Plain Node, no dependencies.\n// getBuiltinModule (Node >= 22.3) works whether node loads this extensionless file as CommonJS\n// (in the VM) or as an ES module (under this repo's type:module package, in tests).\nconst fs = process.getBuiltinModule('node:fs')\nconst path = process.getBuiltinModule('node:path')\nconst vm = process.getBuiltinModule('node:vm')\nconst zlib = process.getBuiltinModule('node:zlib')\nconst { Module, createRequire } = process.getBuiltinModule('node:module')\n\nconst MAGIC = 'orcad-code-cache-v1'\n\nconst args = process.argv.slice(2)\nlet cacheFile = null\nlet writeCache = false\nwhile (args[0] === '--code-cache' || args[0] === '--write-code-cache') {\n if (args[0] === '--code-cache') {\n cacheFile = args[1]\n args.splice(0, 2)\n } else {\n writeCache = true\n args.shift()\n }\n}\nconst entry = args.shift()\nif (!entry || !cacheFile) {\n console.error('usage: orcad-boot --code-cache [--write-code-cache] [args...]')\n process.exit(2)\n}\n// As for `node `: argv[1] is the resolved path, __filename the real one.\nprocess.argv = [process.argv[0], path.resolve(entry), ...args]\nlet file = process.argv[1]\ntry {\n file = fs.realpathSync(file)\n} catch {\n // A missing bundle fails in require below, as it would under plain node.\n}\n\n// One line of identity: a cache from another bundle or Node must never run (V8 only checks length).\nfunction cacheHeader(bytes) {\n return `${MAGIC} ${process.version} ${process.arch} ${bytes.length} ${zlib.crc32(bytes)}\\n`\n}\n\nfunction readCache(header) {\n let data\n try {\n data = fs.readFileSync(cacheFile)\n } catch {\n return null\n }\n const headerLength = Buffer.byteLength(header)\n if (data.length <= headerLength || data.toString('latin1', 0, headerLength) !== header) {\n console.error('orcad-boot: code cache is for another orcad build; loading without it')\n return null\n }\n return data.subarray(headerLength)\n}\n\nfunction runCompiled(header, source, cachedData) {\n // A vm.Script can serialize what startup compiled; the CommonJS loader cannot. Same wrapper,\n // filename and require as the loader, and import() resolves from the bundle like it does there.\n const options = {\n filename: file,\n cachedData: cachedData ?? undefined,\n importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER\n }\n // Node flags the loader option experimental once, on the first import() through it. Spend that\n // one-time warning here, unprinted, so orcad's stderr stays as it was.\n const emitWarning = process.emitWarning\n process.emitWarning = (warning, ...rest) => {\n if (!String(warning?.message ?? warning).includes('USE_MAIN_CONTEXT_DEFAULT_LOADER')) {\n emitWarning.call(process, warning, ...rest)\n }\n }\n let script\n try {\n new vm.Script('import(\"node:path\")', {\n filename: file,\n importModuleDynamically: options.importModuleDynamically\n })\n .runInThisContext()\n .catch(() => {})\n script = new vm.Script(Module.wrap(source), options)\n } finally {\n process.emitWarning = emitWarning\n }\n if (cachedData && script.cachedDataRejected) {\n console.error('orcad-boot: V8 rejected the code cache (other V8 flags?); compiled without it')\n }\n if (writeCache) {\n process.on('exit', () => {\n try {\n const data = script.createCachedData()\n const temporary = `${cacheFile}.${process.pid}.tmp`\n fs.writeFileSync(temporary, Buffer.concat([Buffer.from(header, 'latin1'), data]))\n fs.renameSync(temporary, cacheFile)\n console.error(`orcad-boot: wrote ${data.length} bytes of code cache`)\n } catch (error) {\n console.error(`orcad-boot: could not write the code cache: ${error.message}`)\n }\n })\n }\n const module = new Module(file, null)\n module.filename = file\n module.paths = Module._nodeModulePaths(path.dirname(file))\n const compiled = script.runInThisContext()\n compiled.call(module.exports, module.exports, createRequire(file), module, file, path.dirname(file))\n}\n\n// Locals, so neither the bundle bytes nor the cache outlive the compile.\nfunction boot() {\n // Older Node (no crc32 or main-context import()) loads as before.\n if (typeof zlib.crc32 === 'function' && vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER) {\n let bytes = null\n try {\n bytes = fs.readFileSync(file)\n } catch {\n // Missing or unreadable: require reports it as plain node would.\n }\n if (bytes) {\n const header = cacheHeader(bytes)\n const cachedData = readCache(header)\n if (cachedData || writeCache) {\n runCompiled(header, bytes.toString('utf8'), cachedData)\n return\n }\n }\n }\n createRequire(file)(file)\n}\n\nboot()\n","git":"#!/usr/bin/env bash\n# git for agents in Orca Cloud workspaces (first on orcad's PATH). Commands that author or publish\n# work run as the teammate whose message started this agent's turn (orca-git-as: orcad attests the\n# sender's paired device; root-only member identities). Everything else is plain git, untouched.\nreal=/usr/bin/git\nsub=''\nskip=0\nfor arg in \"$@\"; do\n if [ \"$skip\" = 1 ]; then skip=0; continue; fi\n case \"$arg\" in\n -C | -c | --git-dir | --work-tree | --namespace | --exec-path | --config-env) skip=1 ;;\n -*) ;;\n *) sub=\"$arg\"; break ;;\n esac\ndone\ncase \"$sub\" in\n commit | push | merge | rebase | cherry-pick | revert | am | pull | tag)\n # Outside an agent turn (no attested sender) orca-git-as falls back to the workspace identity.\n if [ -n \"${ORCA_TERMINAL_HANDLE:-}${ORCA_AGENT_SESSION_ID:-}\" ] && [ -x /opt/orca/bin/orca-git-as ]; then\n PATH=\"/usr/bin:/bin:$PATH\" exec /opt/orca/bin/orca-git-as \"$@\" 2> >(grep -v '^orca-git-as: no teammate identity' >&2)\n fi\n ;;\nesac\nexec \"$real\" \"$@\"\n"} export const SOURCE_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Golden build from source, run by the Worker inside the build sandbox: orcad + the orca CLI from one\n# commit of the Orca repo (cloud/integration carries host RPCs no upstream release has), then the same\n# provision-golden.sh every image uses. Inputs (env):\n# ORCA_SRC_SHA (40-hex) and either ORCA_SRC_DIR (source already uploaded) or ORCA_SRC_REPO\n# (https://github.com//) + ORCA_SRC_AUTH (an\n# `Authorization: Basic …` header value for a 1 h read-only installation token; never printed),\n# ORCA_PROVISION_SCRIPT (base64 of provision-golden.sh) + everything provision-golden.sh reads.\nset -euo pipefail\n# Vercel can report a detached build command as still running after it exits, so the outcome is also\n# a file the caller polls: /tmp/source-build.exit (exit code), /tmp/source-build.report (the\n# provision report line).\nrm -f /tmp/source-build.exit /tmp/source-build.report\ntrap 'echo $? >/tmp/source-build.exit' EXIT\nlog() { printf '[source-build] %s\\n' \"$*\" >&2; }\nstart=$(date +%s)\n[[ \"$ORCA_SRC_SHA\" =~ ^[0-9a-f]{40}$ ]] || { log 'ORCA_SRC_SHA must be a full commit sha'; exit 2; }\n\nlog 'build tools'\nif command -v apt-get >/dev/null; then\n # Transient mirror errors and dpkg lock contention made apt exit 100 (2 of ~10 golden builds):\n # retry downloads and wait for the lock instead of failing the build.\n printf 'Acquire::Retries \"5\";\\nDPkg::Lock::Timeout \"180\";\\n' | sudo tee /etc/apt/apt.conf.d/80-orca-retries >/dev/null\n sudo apt-get update -qq\n sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends build-essential python3 git ca-certificates >/dev/null\nelse\n sudo dnf install -y -q gcc gcc-c++ make tar gzip python3 git >/dev/null\nfi\nsudo corepack enable >/dev/null 2>&1 || true\n\nsrc=\"$HOME/orca-src\"\nif [ -n \"${ORCA_SRC_DIR:-}\" ]; then\n # Operator rotation (image/rotate-golden-from-source.ts) uploaded `git archive ` here already.\n log \"uploaded source for $ORCA_SRC_SHA\"\n src=\"$ORCA_SRC_DIR\"\n cd \"$src\" && test -f package.json\n git init -q && git add -A && git -c user.email=build@orca -c user.name=build commit -qm \"$ORCA_SRC_SHA\"\nelse\n log \"fetch $ORCA_SRC_SHA\"\n rm -rf \"$src\" && mkdir -p \"$src\" && cd \"$src\"\n git init -q\n # The header lives only in this one command's config, not in .git/config.\n git -c \"http.https://github.com/.extraheader=$ORCA_SRC_AUTH\" fetch -q --depth 1 \"$ORCA_SRC_REPO\" \"$ORCA_SRC_SHA\"\n unset ORCA_SRC_AUTH\n git -c advice.detachedHead=false checkout -q FETCH_HEAD\n test \"$(git rev-parse HEAD)\" = \"$ORCA_SRC_SHA\"\nfi\n\n# The image files come from this commit too (VM scripts, provision, manifest pins). The env the\n# caller passed is only a fallback for commits from before commit-provision-env.mjs existed.\nimage_dir=\"$src/cloud/apps/sandbox-control/image\"\nif [ -f \"$image_dir/commit-provision-env.mjs\" ]; then\n node \"$image_dir/commit-provision-env.mjs\" \"$image_dir\" >/tmp/commit-provision.env\n # shellcheck disable=SC1091\n . /tmp/commit-provision.env\n rm -f /tmp/commit-provision.env\n log \"image files from $ORCA_SRC_SHA\"\nfi\n\nlog 'build orcad + CLI'\nexport CI=1 ELECTRON_SKIP_BINARY_DOWNLOAD=1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\ncorepack pnpm install --frozen-lockfile >/tmp/src-install.log 2>&1 || { tail -40 /tmp/src-install.log >&2; exit 1; }\ncorepack pnpm -C mobile install --frozen-lockfile >/tmp/src-mobile.log 2>&1 || { tail -40 /tmp/src-mobile.log >&2; exit 1; }\ncorepack pnpm build:mobile-web >/tmp/src-mobile-web.log 2>&1 || { tail -40 /tmp/src-mobile-web.log >&2; exit 1; }\ncorepack pnpm build:orcad >/tmp/src-orcad.log 2>&1 || { tail -60 /tmp/src-orcad.log >&2; exit 1; }\ncorepack pnpm build:cli >/tmp/src-cli.log 2>&1 || { tail -40 /tmp/src-cli.log >&2; exit 1; }\nmkdir -p out/orca-cli\nnode_modules/.bin/esbuild out/cli/index.js --bundle --platform=node --target=node22 --format=cjs \\\n --outfile=out/orca-cli/orca-cli.cjs --log-level=error\nprintf '%s\\n' \"$ORCA_SRC_SHA\" >out/orcad/SOURCE_COMMIT\ntar czf /tmp/orcad.tgz -C out orcad runtimes orca-cli\nlog \"built in $(( $(date +%s) - start ))s\"\n\nexport ORCAD_BUNDLE_URL=file:///tmp/orcad.tgz\nORCAD_BUNDLE_SHA256=\"$(sha256sum /tmp/orcad.tgz | cut -d' ' -f1)\"\nexport ORCAD_BUNDLE_SHA256\ncd \"$HOME\"\nprintf '%s' \"$ORCA_PROVISION_SCRIPT\" | base64 -d >/tmp/provision-golden.sh\nunset ORCA_PROVISION_SCRIPT\nbash /tmp/provision-golden.sh | tee /tmp/source-build.report\n# Build leftovers stay out of the image.\nrm -rf \"$src\" \"$HOME/.local/share/pnpm\" \"$HOME/.cache/pnpm\" /tmp/orcad.tgz /tmp/provision-golden.sh /tmp/src-*.log\nlog \"done in $(( $(date +%s) - start ))s\"\n" export const ENVIRONMENT_BUILD_SCRIPT: string = "#!/usr/bin/env bash\n# Environment build (\"Cloud Computer\"), run by the control plane in a VM booted from the golden image.\n# Clones every repo, runs the org's install script once with `set -euo pipefail`, then records what it\n# built from (commit + lockfile blob ids per repo) so the control plane can tell when a rebuild is due.\n# Everything printed here streams live to the desktop build log.\n#\n# Env from the control plane (validated there): ORCA_BUILD_REPOS (`|||\n# ` lines: each private repo gets its own placeholder the egress swaps), ORCA_INSTALL_SCRIPT_B64, ORCA_LOCKFILES (space list), optional ORCA_GIT_EXTRAHEADER and ORCA_CLONE_FILTER, plus\n# the org secrets the environment names. `::orca-step:: ` lines mark progress.\n# Exit codes: 10 clone, 20 install script, 30 recording the result.\nset -uo pipefail\numask 022\n# One stream: the provider replays stdout and stderr separately after the fact, so a failed build's\n# log would read out of order. `::orca-error::` lines carry Orca's own failure explanations.\nexec 2>&1\nOUT=/tmp/orca-build\nROOT=/vercel/sandbox/repos\nmkdir -p \"$OUT\" \"$ROOT\"\nstep() { printf '\\n::orca-step:: %s\\n' \"$1\"; }\nstarted=$(date +%s)\nexport PATH=\"/opt/orca/tools/bin:/opt/orca/bin:$PATH\"\nexport ORCA_REPOS_ROOT=\"$ROOT\" ORCA_ENVIRONMENT_BUILD=1 CI=1 GIT_TERMINAL_PROMPT=0\nrepos() { printf '%s\\n' \"$ORCA_BUILD_REPOS\"; }\n\n# Tell the script author (often an agent) what they are installing onto.\npm=$(for c in apt-get dnf yum apk; do command -v \"$c\" >/dev/null 2>&1 && { echo \"$c\"; break; }; done)\necho \"Base image: $(. /etc/os-release 2>/dev/null && echo \"$PRETTY_NAME\"), $(nproc) vCPU, package manager: ${pm:-none} (with sudo)\"\n\nstep clone\nfirst=\"\"\nwhile IFS='|' read -r url branch dir header; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n [ -n \"$first\" ] || first=\"$dest\"\n # The egress layer swaps the placeholder for a short-lived repo token; nothing real is on disk,\n # and the header is never written to the repo's config.\n git_auth=()\n [ -z \"${header:-}\" ] || git_auth=(-c \"http.https://github.com/.extraheader=$header\")\n echo \"Cloning $url${branch:+ ($branch)}\"\n rm -rf -- \"$dest\"\n # The clone's own error shows only when it really failed (an empty repo is recovered below).\n # ORCA_CLONE_FILTER (automatic environments: blob:none) keeps history and trees, not every old blob.\n if ! git \"${git_auth[@]}\" clone --quiet ${ORCA_CLONE_FILTER:+--filter=\"$ORCA_CLONE_FILTER\"} ${branch:+--branch \"$branch\"} -- \"$url\" \"$dest\" 2>\"$OUT/clone.err\"; then\n refs=0\n git \"${git_auth[@]}\" ls-remote --exit-code -- \"$url\" >/dev/null 2>&1 || refs=$?\n if [ -n \"$branch\" ] && [ \"$refs\" -eq 2 ]; then\n # Reachable but no refs at all (ls-remote exits 2): a repo with no commits yet.\n echo \"$url has no commits yet; starting it empty on $branch.\"\n rm -rf -- \"$dest\"\n { git \"${git_auth[@]}\" clone --quiet -- \"$url\" \"$dest\" 2>/dev/null && git -C \"$dest\" checkout --quiet -b \"$branch\"; } || exit 10\n else\n cat \"$OUT/clone.err\"\n echo \"::orca-error:: Could not clone $url${branch:+ at $branch}. Check that the branch exists and Orca Cloud can reach the repository.\" \n exit 10\n fi\n fi\n git -C \"$dest\" log -1 --format=' at %h %s' 2>/dev/null || echo ' (no commits yet)'\ndone < <(repos)\n\nstep install\nprintf '%s' \"${ORCA_INSTALL_SCRIPT_B64:-}\" | base64 -d >\"$OUT/install.sh\"\nif [ -s \"$OUT/install.sh\" ]; then\n echo \"Running the install script in ${first:-$ROOT}\"\n (cd \"${first:-$ROOT}\" && exec bash -euo pipefail \"$OUT/install.sh\") /dev/null)\" || continue\n git -C \"$dest\" ls-files --others --ignored --exclude-standard --directory 2>/dev/null \\\n | sed 's#/$##' | grep -E \"$deps_re\" | head -n 500 >\"$common/orca-env-deps\" || true\n if [ -n \"${ORCA_DEPS_HOOK_B64:-}\" ]; then\n # A relative core.hooksPath (husky: .husky/_) names a gitignored folder a new worktree lacks; pin\n # it to the primary checkout so every worktree runs the same hooks, ours included.\n rel=\"$(git -C \"$dest\" config --get core.hooksPath 2>/dev/null || true)\"\n case \"$rel\" in '' | /*) ;; *) git -C \"$dest\" config core.hooksPath \"$dest/$rel\" ;; esac\n hooks=\"$(git -C \"$dest\" rev-parse --path-format=absolute --git-path hooks)\"\n mkdir -p \"$hooks\"\n if [ -e \"$hooks/post-checkout\" ] && ! grep -q 'orca-env-deps' \"$hooks/post-checkout\"; then\n mv -- \"$hooks/post-checkout\" \"$hooks/post-checkout.orca-chained\"\n fi\n printf '%s' \"$ORCA_DEPS_HOOK_B64\" | base64 -d >\"$hooks/post-checkout\" && chmod 0755 \"$hooks/post-checkout\"\n fi\n n=$(wc -l <\"$common/orca-env-deps\" | tr -d ' ')\n [ \"$n\" -gt 0 ] && echo \"$dir: $n installed folder(s) carried into new workspaces.\"\ndone < <(repos)\n{\n printf '{\"durationSec\":%d,\"repos\":[' \"$(( $(date +%s) - started ))\"\n sep=\"\"\n while IFS='|' read -r url branch dir _; do\n [ -n \"$url\" ] || continue\n dest=\"$ROOT/$dir\"\n commit=$(git -C \"$dest\" rev-parse --verify --quiet HEAD 2>/dev/null || true)\n head=$(git -C \"$dest\" symbolic-ref --quiet --short HEAD 2>/dev/null || true)\n printf '%s{\"url\":\"%s\",\"dir\":\"%s\",\"branch\":\"%s\",\"commit\":\"%s\",\"lockfiles\":{' \"$sep\" \"$url\" \"$dir\" \"$head\" \"$commit\"\n lsep=\"\"\n if [ -n \"$commit\" ]; then\n for f in ${ORCA_LOCKFILES:-}; do\n blob=$(git -C \"$dest\" rev-parse --verify --quiet \"HEAD:$f\" 2>/dev/null || true)\n if [ -n \"$blob\" ]; then printf '%s\"%s\":\"%s\"' \"$lsep\" \"$f\" \"$blob\"; lsep=\",\"; fi\n done\n fi\n printf '}}'\n sep=\",\"\n done < <(repos)\n printf '],\"diskUsedBytes\":%s,\"diskTotalBytes\":%s}\\n' \\\n \"$(df -B1 --output=used / | tail -n 1 | tr -d ' ')\" \"$(df -B1 --output=size / | tail -n 1 | tr -d ' ')\"\n} >\"$OUT/result.json\" || exit 30\n# Nothing from this VM's own session belongs in the image, only what the script installed.\nrm -rf -- \"$OUT/install.sh\" \"$HOME/.bash_history\" \"$HOME/.orcad-data\" \"$HOME/.orca-sandbox\"\necho \"Disk used: $(df -h --output=used / | tail -n 1 | tr -d ' ') of $(df -h --output=size / | tail -n 1 | tr -d ' ')\"\n" export const ENVIRONMENT_DEPS_HOOK: string = "#!/usr/bin/env bash\n# Installed by Orca environment builds as the repo's post-checkout hook. When git creates a new linked\n# worktree (`git worktree add` passes the null commit as the previous HEAD), give it the dependency\n# folders the build installed in the primary checkout, as hard links: near-instant, real paths (not\n# symlinks, so bundlers and native modules behave). Hard links share file contents: tools that rewrite\n# a file in place inside these folders change it for every worktree on this VM (one workspace per VM).\n# Any post-checkout hook the repo already had runs afterwards, unchanged.\nprev=\"${1:-}\"\nhere=\"$(dirname \"$0\")\"\nif [ \"$prev\" = \"0000000000000000000000000000000000000000\" ] && [ \"${ORCA_SKIP_DEPS_LINK:-}\" != 1 ]; then\n common=\"$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null || true)\"\n top=\"$(git rev-parse --show-toplevel 2>/dev/null || true)\"\n primary=\"$(dirname \"$common\")\"\n list=\"$common/orca-env-deps\"\n if [ -n \"$top\" ] && [ \"$top\" != \"$primary\" ] && [ -f \"$list\" ]; then\n started=$(date +%s%N)\n linked=0\n while IFS= read -r rel; do\n case \"$rel\" in '' | /* | *..*) continue ;; esac\n [ -e \"$primary/$rel\" ] && [ ! -e \"$top/$rel\" ] || continue\n mkdir -p \"$(dirname \"$top/$rel\")\"\n if [ -d \"$primary/$rel\" ]; then\n if ! cp -al -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null; then\n # A partial hard-link copy would make the fallback nest inside it: start clean.\n rm -rf -- \"$top/$rel\"\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || { rm -rf -- \"$top/$rel\"; continue; }\n fi\n else\n cp -a -- \"$primary/$rel\" \"$top/$rel\" 2>/dev/null || continue\n fi\n linked=$((linked + 1))\n done <\"$list\"\n if [ \"$linked\" -gt 0 ]; then\n echo \"Orca: reused $linked installed dependency folder(s) from the environment build ($(( ($(date +%s%N) - started) / 1000000 )) ms).\" >&2\n fi\n fi\nfi\nif [ -x \"$here/post-checkout.orca-chained\" ]; then\n if head -n 1 \"$here/post-checkout.orca-chained\" | grep -Eq '^#!.*(ba|da|z)?sh'; then\n # Sourced, so $0 still names `post-checkout` (husky v9 finds the user's hook by basename \"$0\").\n ( . \"$here/post-checkout.orca-chained\" \"$@\" )\n exit $?\n fi\n exec \"$here/post-checkout.orca-chained\" \"$@\"\nfi\nexit 0\n" diff --git a/cloud/apps/sandbox-control/image/vm/orca-sandbox-start b/cloud/apps/sandbox-control/image/vm/orca-sandbox-start index becf750535d..349492fcae7 100755 --- a/cloud/apps/sandbox-control/image/vm/orca-sandbox-start +++ b/cloud/apps/sandbox-control/image/vm/orca-sandbox-start @@ -178,10 +178,12 @@ ca_env=(NODE_USE_SYSTEM_CA="${NODE_USE_SYSTEM_CA:-1}") for name in NODE_EXTRA_CA_CERTS SSL_CERT_FILE; do if [ -n "${!name:-}" ]; then ca_env+=("$name=${!name}"); fi done +# Ports panel: programs under $ORCA_HOME are the image's own services, and 23456 is Vercel's +# sandbox-init (root, pid invisible to this user); neither is listed as the user's port. env -i HOME="$HOME" USER="$(id -un)" LANG=C.UTF-8 TERM=xterm-256color "${ca_env[@]}" \ PATH="$ORCA_HOME/tools/bin:$ORCA_HOME/bin:$(dirname "$system_node"):/usr/local/bin:/usr/bin:/bin" \ ORCA_USER_DATA="$HOME/.orcad-data" ORCA_SANDBOX_ID="$ORCA_SANDBOX_ID" "${managed_env[@]}" \ - ORCA_HOST_MANAGED_LISTENER_PATHS="$ORCA_HOME" \ + ORCA_HOST_MANAGED_LISTENER_PATHS="$ORCA_HOME" ORCA_HOST_MANAGED_UNOWNED_PORTS=23456 \ NODE_COMPILE_CACHE="$ORCA_HOME/compile-cache" ORCA_ORCAD_STARTUP_QUALIFICATION_DIR="$ORCA_HOME/startup-qualification" \ ORCA_SESSION_ENV_NAMES="${secret_names[*]}" "${agent_env[@]}" \ setsid nohup "$node" "$ORCA_HOME/bin/orcad-boot" --code-cache "$ORCA_HOME/compile-cache/orcad-server.v8" \ diff --git a/src/main/ports/host-managed-listeners.test.ts b/src/main/ports/host-managed-listeners.test.ts index 20d404f0239..366458ce6c5 100644 --- a/src/main/ports/host-managed-listeners.test.ts +++ b/src/main/ports/host-managed-listeners.test.ts @@ -1,50 +1,78 @@ import { describe, expect, it } from 'vitest' -import { hostManagedListenerRoots, isHostManagedListener } from './host-managed-listeners' +import { hostManagedListenerConfig, isHostManagedListener } from './host-managed-listeners' + +const config = (roots: string[] = ['/opt/orca'], unownedPorts: number[] = [23456]) => ({ + roots, + unownedPorts: new Set(unownedPorts) +}) describe('host-managed listeners', () => { - it('reads absolute roots from the environment', () => { - expect( - hostManagedListenerRoots({ - ORCA_HOST_MANAGED_LISTENER_PATHS: '/opt/orca/:relative:/srv/tools' - }) - ).toEqual(['/opt/orca', '/srv/tools']) - expect(hostManagedListenerRoots({})).toEqual([]) + it('reads absolute roots and platform ports from the environment', () => { + const parsed = hostManagedListenerConfig({ + ORCA_HOST_MANAGED_LISTENER_PATHS: '/opt/orca/:relative:/srv/tools', + ORCA_HOST_MANAGED_UNOWNED_PORTS: '23456, x,70000' + }) + expect(parsed.roots).toEqual(['/opt/orca', '/srv/tools']) + expect([...parsed.unownedPorts]).toEqual([23456]) + expect(hostManagedListenerConfig({})).toEqual({ roots: [], unownedPorts: new Set() }) }) it('marks the server itself and programs started from a managed root', () => { - const roots = ['/opt/orca'] - expect(isHostManagedListener({ pid: 27 }, roots, 27)).toBe(true) + expect(isHostManagedListener({ pid: 27, port: 6768 }, config(), 27)).toBe(true) expect( isHostManagedListener( - { pid: 90, commandLine: '/opt/orca/openssh/sbin/sshd -D -f x' }, - roots, + { pid: 90, port: 2222, commandLine: '/opt/orca/openssh/sbin/sshd -D -f x' }, + config(), 27 ) ).toBe(true) expect( isHostManagedListener( - { pid: 91, commandLine: 'python3 /opt/orca/bin/orca-desktop-proxy --port 6080' }, - roots, + { + pid: 91, + port: 6080, + commandLine: 'python3 /opt/orca/bin/orca-desktop-proxy --port 6080' + }, + config(), 27 ) ).toBe(true) }) - it('leaves user servers alone, including ones whose arguments mention a managed path later', () => { - const roots = ['/opt/orca'] - expect( - isHostManagedListener({ pid: 92, commandLine: 'python3 -m http.server 3000' }, roots, 27) - ).toBe(false) + it('marks a pid-less listener only on a declared platform port', () => { + expect(isHostManagedListener({ port: 23456 }, config(), 27)).toBe(true) + // A root-run postgres or Docker-published port has no visible pid but is the user's. + expect(isHostManagedListener({ port: 5432 }, config(), 27)).toBe(false) + expect(isHostManagedListener({ port: 23456 }, config(['/opt/orca'], []), 27)).toBe(false) + }) + + it('leaves user servers alone, matching by program path rather than port', () => { expect( isHostManagedListener( - { pid: 93, commandLine: 'node vite --config /opt/orca/x.js' }, - roots, + { pid: 92, port: 6768, commandLine: 'python3 -m http.server 6768' }, + config(), 27 ) ).toBe(false) - expect(isHostManagedListener({ pid: 94, commandLine: '/opt/orcaother/bin/x' }, roots, 27)).toBe( - false - ) - expect(isHostManagedListener({ pid: 95, commandLine: '/opt/orca/bin/x' }, [], 27)).toBe(false) + expect( + isHostManagedListener( + { pid: 92, port: 23456, commandLine: 'python3 -m http.server 23456' }, + config(), + 27 + ) + ).toBe(false) + expect( + isHostManagedListener( + { pid: 93, port: 5173, commandLine: 'node vite --config /opt/orca/x.js' }, + config(), + 27 + ) + ).toBe(false) + expect( + isHostManagedListener({ pid: 94, port: 1, commandLine: '/opt/orcaother/bin/x' }, config(), 27) + ).toBe(false) + expect( + isHostManagedListener({ pid: 95, port: 1, commandLine: '/opt/orca/bin/x' }, config([]), 27) + ).toBe(false) }) }) diff --git a/src/main/ports/host-managed-listeners.ts b/src/main/ports/host-managed-listeners.ts index 095bc65fd37..fcdfe7fdb21 100644 --- a/src/main/ports/host-managed-listeners.ts +++ b/src/main/ports/host-managed-listeners.ts @@ -2,34 +2,53 @@ import type { RawListeningPort } from './local-workspace-port-scan-state' /** Colon-separated install roots whose binaries are the host's own services (e.g. a sandbox image's tools). */ export const HOST_MANAGED_LISTENER_PATHS_ENV = 'ORCA_HOST_MANAGED_LISTENER_PATHS' +/** Comma-separated ports the host's platform listens on from a process this user cannot see (no pid). */ +export const HOST_MANAGED_UNOWNED_PORTS_ENV = 'ORCA_HOST_MANAGED_UNOWNED_PORTS' -export function hostManagedListenerRoots( +export type HostManagedListenerConfig = { + roots: readonly string[] + unownedPorts: ReadonlySet +} + +export function hostManagedListenerConfig( env: Record = process.env -): string[] { - return (env[HOST_MANAGED_LISTENER_PATHS_ENV] ?? '') +): HostManagedListenerConfig { + const roots = (env[HOST_MANAGED_LISTENER_PATHS_ENV] ?? '') .split(':') .map((root) => root.trim().replace(/\/+$/, '')) .filter((root) => root.startsWith('/') && root.length > 1) + const unownedPorts = new Set( + (env[HOST_MANAGED_UNOWNED_PORTS_ENV] ?? '') + .split(',') + .map((port) => Number(port.trim())) + .filter((port) => Number.isInteger(port) && port > 0 && port < 65536) + ) + return { roots, unownedPorts } } /** - * Listeners the host runs itself: this server process, or a program started from a managed root - * (checked on argv[0] and argv[1], so `python3 /root/bin/tool` counts too). + * Listeners the host runs itself: this server process, a program started from a managed root + * (checked on argv[0] and argv[1], so `python3 /root/bin/tool` counts too), or a declared platform + * port whose owner is invisible. A pid-less listener on any other port (a root-run postgres or + * Docker-published port) is still the user's. */ export function isHostManagedListener( - port: Pick, - roots: readonly string[], + port: Pick, + config: HostManagedListenerConfig, serverPid: number = process.pid ): boolean { - if (port.pid !== undefined && port.pid === serverPid) { + if (port.pid === undefined) { + return config.unownedPorts.has(port.port) + } + if (port.pid === serverPid) { return true } - if (roots.length === 0 || !port.commandLine) { + if (config.roots.length === 0 || !port.commandLine) { return false } return port.commandLine .trim() .split(/\s+/) .slice(0, 2) - .some((token) => roots.some((root) => token === root || token.startsWith(`${root}/`))) + .some((token) => config.roots.some((root) => token === root || token.startsWith(`${root}/`))) } diff --git a/src/main/ports/local-workspace-port-scanner.ts b/src/main/ports/local-workspace-port-scanner.ts index 9367fd5641b..5b85224fda5 100644 --- a/src/main/ports/local-workspace-port-scanner.ts +++ b/src/main/ports/local-workspace-port-scanner.ts @@ -8,7 +8,7 @@ import { reconcileAdvertisedUrls } from './local-workspace-port-attribution' import { scanPlatformListeningPorts } from './local-workspace-platform-port-scanner' -import { hostManagedListenerRoots, isHostManagedListener } from './host-managed-listeners' +import { hostManagedListenerConfig, isHostManagedListener } from './host-managed-listeners' import { getWorkspacePortScanCooldown, isWorkspacePortScanCommandTimeout, @@ -41,10 +41,10 @@ export async function scanWorkspacePorts( worktrees, options.requireMetadata ) - const roots = hostManagedListenerRoots() + const hostManaged = hostManagedListenerConfig() const managed = new Set( rawPorts - .filter((port) => isHostManagedListener(port, roots)) + .filter((port) => isHostManagedListener(port, hostManaged)) .map((port) => `${port.host}:${port.port}:${port.pid ?? 'unknown'}`) ) // Orca's own listeners (runtime socket, hook server) run with a workspace in their command line but are not its servers. diff --git a/src/renderer/src/components/right-sidebar/local-workspace-port-sections.test.ts b/src/renderer/src/components/right-sidebar/local-workspace-port-sections.test.ts index 905fe9de9f0..8cb8520514e 100644 --- a/src/renderer/src/components/right-sidebar/local-workspace-port-sections.test.ts +++ b/src/renderer/src/components/right-sidebar/local-workspace-port-sections.test.ts @@ -19,19 +19,20 @@ const external = ( const scan = { ports: [ external(6768, { hostManaged: true }), - external(23456, { pid: undefined }), - external(5432) + external(23456, { pid: undefined, hostManaged: true }), + external(5432, { pid: undefined }), + external(8123) ] } describe('getLocalWorkspacePortSections', () => { - it('hides a sandbox host’s own services and pid-less root listeners from External', () => { + it('hides only host-marked services from External, keeping a pid-less user port', () => { const sections = getLocalWorkspacePortSections(scan, 'r', 'w', true) - expect(sections.externalPorts.map((port) => port.port)).toEqual([5432]) + expect(sections.externalPorts.map((port) => port.port)).toEqual([5432, 8123]) }) it('keeps every listener on other hosts', () => { const sections = getLocalWorkspacePortSections(scan, 'r', 'w') - expect(sections.externalPorts.map((port) => port.port)).toEqual([6768, 23456, 5432]) + expect(sections.externalPorts.map((port) => port.port)).toEqual([6768, 23456, 5432, 8123]) }) }) diff --git a/src/renderer/src/components/right-sidebar/local-workspace-port-sections.ts b/src/renderer/src/components/right-sidebar/local-workspace-port-sections.ts index 6deb3b371a2..3aefcbecda9 100644 --- a/src/renderer/src/components/right-sidebar/local-workspace-port-sections.ts +++ b/src/renderer/src/components/right-sidebar/local-workspace-port-sections.ts @@ -4,16 +4,14 @@ export function getLocalWorkspacePortSections( scan: { ports: WorkspacePort[] } | null | undefined, activeRepoId: string | null | undefined, activeWorktreeId: string | null | undefined, - /** Orca Cloud: the sandbox's own services (and root listeners nobody here started) are not the user's ports. */ + /** Orca Cloud: the sandbox's own services (marked host-managed by the host) are not the user's ports. */ hideHostServices = false ): { activePorts: WorkspacePort[] otherWorkspacePorts: WorkspacePort[] externalPorts: WorkspacePort[] } { - const ports = (scan?.ports ?? []).filter( - (port) => !hideHostServices || (port.hostManaged !== true && port.pid !== undefined) - ) + const ports = (scan?.ports ?? []).filter((port) => !hideHostServices || port.hostManaged !== true) return { activePorts: ports.filter( (port) => From bd6cd6e7f82915c0a8bdeb2d2a864c3e1a712e8d Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:11:12 -0800 Subject: [PATCH 066/149] feat(cloud): JA-04 sheet 600px wide; sidebar row 'Set up once' opens the sheet too --- .../src/components/orca-cloud/CloudAgentRowSignInTarget.tsx | 4 +--- .../agent-accounts/sign-in-sheet/OrcaCloudSignInSheet.tsx | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/renderer/src/components/orca-cloud/CloudAgentRowSignInTarget.tsx b/src/renderer/src/components/orca-cloud/CloudAgentRowSignInTarget.tsx index daba491c714..03c6030286a 100644 --- a/src/renderer/src/components/orca-cloud/CloudAgentRowSignInTarget.tsx +++ b/src/renderer/src/components/orca-cloud/CloudAgentRowSignInTarget.tsx @@ -1,7 +1,6 @@ // The status (dot and text) of a cloud agent row that needs sign-in: clicking it opens // Settings → Agent accounts, where the fix lives. The rest of the row still opens the pane. import React, { useCallback } from 'react' -import { useAppStore } from '@/store' import { cn } from '@/lib/utils' import { AgentStateDot } from '@/components/AgentStateDot' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' @@ -11,10 +10,9 @@ import { openOrcaCloudAgentAccounts } from '@/components/new-workspace/OrcaCloud /** What the status shows: its label, the agent's catalog name, and the tooltip naming the fix. */ export type CloudAgentRowStatusText = { label: string; agentName: string; tooltip: string | null } -/** The composer's "Set up once" target, plus opening Settings, which the sidebar has closed. */ +/** The sidebar row's "Set up once": the focused Orca Cloud sign-in sheet (JA-04). */ export function openCloudAgentAccountsSettings(): void { openOrcaCloudAgentAccounts() - useAppStore.getState().openSettingsPage() } /** diff --git a/src/renderer/src/components/settings/agent-accounts/sign-in-sheet/OrcaCloudSignInSheet.tsx b/src/renderer/src/components/settings/agent-accounts/sign-in-sheet/OrcaCloudSignInSheet.tsx index 67ba6b64dfd..ebec6ee976d 100644 --- a/src/renderer/src/components/settings/agent-accounts/sign-in-sheet/OrcaCloudSignInSheet.tsx +++ b/src/renderer/src/components/settings/agent-accounts/sign-in-sheet/OrcaCloudSignInSheet.tsx @@ -33,7 +33,7 @@ export function OrcaCloudSignInSheetView({ const t = useTranslate() const titleId = React.useId() return ( - +
    From 9ac48491aa96435c571f0dca9dd6ebc64238a3f9 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:11:33 -0800 Subject: [PATCH 067/149] chore(cloud): localization catalogs, no casts in tests, section menu button keeps its own styling --- config/localization-coverage-allowlist.json | 7 +++ .../src/cloud/cloud-workspace-prefs.test.ts | 25 +++++--- mobile/src/i18n/locales/en.json | 16 +++++- .../cloud-workspaces/CloudWorkspaceGroup.tsx | 57 ++++++++++--------- .../cloud-workspace-prefs.test.ts | 4 +- src/renderer/src/i18n/locales/en.json | 23 +++++++- .../cloud-workspace-arrangement.test.ts | 5 +- 7 files changed, 92 insertions(+), 45 deletions(-) diff --git a/config/localization-coverage-allowlist.json b/config/localization-coverage-allowlist.json index abfae50fd7f..d6960e64ae5 100644 --- a/config/localization-coverage-allowlist.json +++ b/config/localization-coverage-allowlist.json @@ -188,6 +188,13 @@ "dynamic": false, "count": 1 }, + { + "filePath": "src/renderer/src/lib/workspace/search/worktrees/worktree-palette-evidence.ts", + "kind": "object-property:accessibilityLabel", + "text": "Cloud workspace number", + "dynamic": false, + "count": 1 + }, { "filePath": "src/renderer/src/components/agent/launch-settings/AgentDefaultSurfacePreviews.tsx", "kind": "jsx-attribute:title", diff --git a/mobile/src/cloud/cloud-workspace-prefs.test.ts b/mobile/src/cloud/cloud-workspace-prefs.test.ts index e7a621cbcdb..3e835be9771 100644 --- a/mobile/src/cloud/cloud-workspace-prefs.test.ts +++ b/mobile/src/cloud/cloud-workspace-prefs.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it, vi } from 'vitest' +import { z } from 'zod' vi.mock('./cloud-session', () => ({ loadCloudControlPlane: vi.fn() })) @@ -6,13 +7,23 @@ import { setPinned } from '../../../src/shared/cloud-workspaces/cloud-workspace- import { editCloudWorkspacePrefsOn, resolveCloudWorkspaceLink } from './cloud-workspace-prefs' import type { CloudControlPlane } from './cloud-control-plane-request' +const PutBody = z.object({ + document: z.object({ + pinned: z.array(z.string()), + order: z.array(z.string()), + sections: z.array(z.string()), + collapsed: z.array(z.string()) + }), + revision: z.number() +}) + const A = `sbx_${'a'.repeat(24)}` const B = `sbx_${'b'.repeat(24)}` function plane(handler: (method: string, url: URL, body: unknown) => [number, unknown]) { const calls: string[] = [] - const fetchFn = vi.fn(async (input: string, init: RequestInit) => { - const url = new URL(input) + const fetchFn: typeof fetch = async (input, init = {}) => { + const url = new URL(String(input)) calls.push(`${init.method} ${url.pathname}${url.search}`) const [status, body] = handler( init.method ?? 'GET', @@ -20,18 +31,14 @@ function plane(handler: (method: string, url: URL, body: unknown) => [number, un init.body ? JSON.parse(String(init.body)) : undefined ) return new Response(JSON.stringify(body), { status }) - }) - const p: CloudControlPlane = { - baseUrl: 'https://cp.example', - token: () => 't', - fetch: fetchFn as unknown as typeof fetch } + const p: CloudControlPlane = { baseUrl: 'https://cp.example', token: () => 't', fetch: fetchFn } return { plane: p, calls } } describe('phone prefs sync', () => { it('re-applies a pin on top of a desktop that wrote first', async () => { - let server = { + let server: z.infer = { document: { pinned: [B], order: [], sections: [], collapsed: [] }, revision: 3 } @@ -40,7 +47,7 @@ describe('phone prefs sync', () => { if (method === 'GET') { return [200, { ...server, updatedAt: 1 }] } - const put = body as { document: typeof server.document; revision: number } + const put = PutBody.parse(body) if (firstPut) { // A desktop wrote between our read and our write. firstPut = false diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index d3411f6ac91..584bf445524 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -5020,7 +5020,8 @@ "actions": { "sleep": "Sleep", "sleepCaption": "Sandbox hours stop. Files are kept; agents restart when it wakes.", - "archive": "Archive" + "archive": "Archive", + "pinCaption": "On all your devices. Only you see your pins." }, "sleep": { "title": "Sleep {{title}}?", @@ -5122,7 +5123,12 @@ "new": "New cloud workspace", "createdAgo": "Created {{ago}} ago", "createdJustNow": "Created just now", - "workspaceRowLabel": "Cloud workspace, {{title}}, {{detail}}" + "workspaceRowLabel": "Cloud workspace, {{title}}, {{detail}}", + "unpin": "Unpin", + "pin": "Pin to top", + "pinFailed": "Couldn’t save that change", + "pinFailedDetail": "Check your connection and try again.", + "pinnedHint": "Pinned" }, "connect": { "signedOut": "Sign in to Orca on {{desktop}}, then try again.", @@ -5231,6 +5237,12 @@ "idle": { "sleeps_one": "Sleeps after {{count}} minute idle.", "sleeps_other": "Sleeps after {{count}} minutes idle." + }, + "link": { + "opening": "Opening workspace…", + "missingTitle": "Can’t open this workspace", + "missing": "It’s private, in another team, or deleted. If it’s in another team, switch to it on your computer first.", + "home": "Go to Home" } } } diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceGroup.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceGroup.tsx index b3d60a06fc3..712e2d735fb 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceGroup.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceGroup.tsx @@ -133,33 +133,36 @@ export function CloudWorkspaceGroupView({ )} {collapsible && (canMoveUp || canMoveDown) && ( - - - - - - onMoveSection(-1)}> - {t('auto.components.cloudWorkspaces.moveSectionUp', 'Move section up')} - - onMoveSection(1)}> - {t('auto.components.cloudWorkspaces.moveSectionDown', 'Move section down')} - - - + + + + + + + onMoveSection(-1)}> + {t('auto.components.cloudWorkspaces.moveSectionUp', 'Move section up')} + + onMoveSection(1)}> + {t('auto.components.cloudWorkspaces.moveSectionDown', 'Move section down')} + + + + )}
    )} diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspace-prefs.test.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspace-prefs.test.ts index 31faa3ac23a..413889c9978 100644 --- a/src/renderer/src/components/cloud-workspaces/cloud-workspace-prefs.test.ts +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspace-prefs.test.ts @@ -20,8 +20,8 @@ const B = `sbx_${'b'.repeat(24)}` /** A control plane with compare-and-set, plus a hook to simulate another device writing first. */ function fakeServer() { - const server = { - document: EMPTY_CLOUD_WORKSPACE_PREFS as CloudWorkspacePrefsDocument, + const server: { document: CloudWorkspacePrefsDocument; revision: number } = { + document: EMPTY_CLOUD_WORKSPACE_PREFS, revision: 0 } const view = () => ({ ok: true as const, value: { ...server, updatedAt: null } }) diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index ec448c98c22..6172283d14f 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -1469,7 +1469,8 @@ "port": "Port", "pr": "PR", "task": "Task", - "automationItem": "Automation" + "automationItem": "Automation", + "cloudWorkspace": "Cloud workspace" }, "linearIssue": { "createLabel": "Create worktree from Linear issue {{value0}}: {{value1}}", @@ -21012,7 +21013,25 @@ "errorSeatSandboxLimitSelf_one": "You already have {{count}} sandbox running, the most one seat can run. Put it to sleep or delete it, then try again.", "errorSeatSandboxLimitSelf_other": "You already have {{count}} sandboxes running, the most one seat can run. Put one to sleep or delete it, then try again.", "errorSeatSandboxLimitOwner_one": "{{name}} already has {{count}} sandbox running. This workspace runs on their seat, so ask them to put it to sleep, then try again.", - "errorSeatSandboxLimitOwner_other": "{{name}} already has {{count}} sandboxes running. This workspace runs on their seat, so ask them to put one to sleep, then try again." + "errorSeatSandboxLimitOwner_other": "{{name}} already has {{count}} sandboxes running. This workspace runs on their seat, so ask them to put one to sleep, then try again.", + "pinned": "Pinned", + "sectionActions": "Actions for section {{name}}", + "moveSectionUp": "Move section up", + "moveSectionDown": "Move section down", + "linkCopiedShort": "Link copied", + "copyLinkTo": "Copy link to {{number}}", + "unpin": "Unpin", + "pin": "Pin", + "moveUp": "Move up", + "moveDown": "Move down", + "linkNoAccess": "You don't have access to {{number}}.", + "linkOtherTeam2": "{{number}} is in {{team}}.", + "linkSwitchTeam": "Switch and open", + "prefsSaveFailed": "Couldn't save that change, so your other devices won't show it. Try again.", + "movedTo": "Moved {{name}} to position {{position}} in {{group}}", + "pinLimit": "You can pin up to {{count}} workspaces. Unpin one first.", + "pinnedName": "Pinned {{name}}", + "unpinnedName": "Unpinned {{name}}" }, "orcaCloud": { "QueuedPrompt": { diff --git a/src/shared/cloud-workspaces/cloud-workspace-arrangement.test.ts b/src/shared/cloud-workspaces/cloud-workspace-arrangement.test.ts index 9ea52f03bfd..2fcf3dfdf87 100644 --- a/src/shared/cloud-workspaces/cloud-workspace-arrangement.test.ts +++ b/src/shared/cloud-workspaces/cloud-workspace-arrangement.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it } from 'vitest' import { EMPTY_CLOUD_WORKSPACE_PREFS, - type CloudWorkspace, type CloudWorkspacePrefsDocument } from './cloud-workspaces-wire' import { @@ -15,8 +14,8 @@ import { } from './cloud-workspace-arrangement' const id = (n: number) => `sbx_${String(n).padStart(24, '0')}` -function ws(n: number, section: string | null = null, archived = false): CloudWorkspace { - return { id: id(n), section, archivedAt: archived ? 1 : null } as CloudWorkspace +function ws(n: number, section: string | null = null, archived = false) { + return { id: id(n), section, archivedAt: archived ? 1 : null } } const doc = (patch: Partial): CloudWorkspacePrefsDocument => ({ ...EMPTY_CLOUD_WORKSPACE_PREFS, From ff5648f7e397bd6a6b3ac0c1ef3e0dc7ef69a46b Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:13:40 -0800 Subject: [PATCH 068/149] refactor(cloud): type the handoff timer instead of casting --- .../orca-cloud-setup/CloudSetupPageLayer.tsx | 2 +- .../orca-cloud-setup/cloud-setup-handoff.test.ts | 2 +- .../components/orca-cloud-setup/cloud-setup-handoff.ts | 10 +++++----- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx b/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx index 2d020a2b30f..3672eddd32d 100644 --- a/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx +++ b/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx @@ -43,7 +43,7 @@ function reopenComposer(request: CloudSetupPageRequest, autoStart: boolean): voi startScreenShown: () => document.querySelector('[data-vm-build-sheet]') !== null, closePage: closeCloudSetupPage, setTimer: (callback, ms) => window.setTimeout(callback, ms), - clearTimer: (handle) => window.clearTimeout(handle as number) + clearTimer: (handle) => window.clearTimeout(handle) }) } } diff --git a/src/renderer/src/components/orca-cloud-setup/cloud-setup-handoff.test.ts b/src/renderer/src/components/orca-cloud-setup/cloud-setup-handoff.test.ts index 0b2e1230a49..720992382cf 100644 --- a/src/renderer/src/components/orca-cloud-setup/cloud-setup-handoff.test.ts +++ b/src/renderer/src/components/orca-cloud-setup/cloud-setup-handoff.test.ts @@ -25,7 +25,7 @@ function harness(initial: { activePendingCreationId: string | null; activeModal: startScreenShown: () => painted, closePage, setTimer: (callback, ms) => setTimeout(callback, ms), - clearTimer: (handle) => clearTimeout(handle as ReturnType) + clearTimer: (handle) => clearTimeout(handle) }) return { set, paint: () => (painted = true), closePage, cancel, listeners } } diff --git a/src/renderer/src/components/orca-cloud-setup/cloud-setup-handoff.ts b/src/renderer/src/components/orca-cloud-setup/cloud-setup-handoff.ts index 7504f132fef..884c4470a93 100644 --- a/src/renderer/src/components/orca-cloud-setup/cloud-setup-handoff.ts +++ b/src/renderer/src/components/orca-cloud-setup/cloud-setup-handoff.ts @@ -5,14 +5,14 @@ type HandoffState = { activePendingCreationId: string | null; activeModal: string } -export type HandoffDeps = { +export type HandoffDeps = { getState: () => HandoffState subscribe: (listener: (state: HandoffState) => void) => () => void /** True once the start screen is in the DOM (its lazy chunk may land a few frames later). */ startScreenShown: () => boolean closePage: () => void - setTimer: (callback: () => void, ms: number) => unknown - clearTimer: (handle: unknown) => void + setTimer: (callback: () => void, ms: number) => Timer + clearTimer: (handle: Timer) => void } /** The hidden composer reveals itself after 8 s; past that the dialog sits over the page anyway. */ @@ -23,10 +23,10 @@ const PAINT_POLL_MS = 16 const COMPOSER_MODAL = 'new-workspace-composer' /** Call right after opening the auto-starting composer. Returns a cancel. */ -export function closeSetupPageWhenCreateTakesOver(deps: HandoffDeps): () => void { +export function closeSetupPageWhenCreateTakesOver(deps: HandoffDeps): () => void { const before = deps.getState().activePendingCreationId let done = false - const timers = new Set() + const timers = new Set() const later = (callback: () => void, ms: number): void => { const handle = deps.setTimer(() => { timers.delete(handle) From ec5e81bdf145db5716055cf3b4ac30b54fbc14b7 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:13:59 -0800 Subject: [PATCH 069/149] fix(cloud): W-number chip sits beside Run in the workspace's tab bar --- src/renderer/src/components/tab-group/TabGroupPanel.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/renderer/src/components/tab-group/TabGroupPanel.tsx b/src/renderer/src/components/tab-group/TabGroupPanel.tsx index a9833916be1..52dfacdf116 100644 --- a/src/renderer/src/components/tab-group/TabGroupPanel.tsx +++ b/src/renderer/src/components/tab-group/TabGroupPanel.tsx @@ -27,6 +27,7 @@ import { useWindowBackdropActive } from '@/lib/window-backdrop' import { useThemeBackgroundStore } from '@/store/appearance/theme-background' import { EditorRevealFlash } from './EditorRevealFlash' import { SplitPaneLanding } from './SplitPaneLanding' +import { CloudWorkspaceNumberChip } from '../cloud-workspaces/CloudWorkspaceNumberChip' import { isSplitLandingGroup } from '@/store/slices/tabs/split-landing-groups' const EditorPanel = lazy(() => import('../editor/EditorPanel')) @@ -310,7 +311,10 @@ export default function TabGroupPanel({ className={actionChromeClassName} style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties} > - {/* One Run button per workspace: in the focused split, or the only group. */} + {/* One W-number and Run button per workspace: in the focused split, or the only group. */} + {!hasSplitGroups || isFocused ? ( + + ) : null} {!hasSplitGroups || isFocused ? : null} Date: Tue, 10 Nov 2026 20:20:01 -0800 Subject: [PATCH 070/149] fix(teammates): Poke reads as unavailable when the teammate hasn't opted in design-squad P3 on #336: aria-disabled with the muted look (still focusable), a tooltip and aria-describedby with the footer sentence, and clicks do nothing. --- .../teammates/TeammateProfileView.test.tsx | 12 +++++- .../teammates/TeammateProfileView.tsx | 42 ++++++++++++------- 2 files changed, 38 insertions(+), 16 deletions(-) diff --git a/src/renderer/src/components/teammates/TeammateProfileView.test.tsx b/src/renderer/src/components/teammates/TeammateProfileView.test.tsx index 240b1a48207..440735453ba 100644 --- a/src/renderer/src/components/teammates/TeammateProfileView.test.tsx +++ b/src/renderer/src/components/teammates/TeammateProfileView.test.tsx @@ -58,9 +58,17 @@ it('sends you to Settings when your Pokes are off, and disables Poke when theirs fireEvent.click(screen.getByRole('button', { name: 'Open settings' })) expect(onTurnOnPokes).toHaveBeenCalledOnce() cleanup() - view({ profile: profile({ pokes: { enabled: true, teammateEnabled: false } }) }) + const { onPoke } = view({ + profile: profile({ pokes: { enabled: true, teammateEnabled: false } }) + }) expect(screen.getByText('Grace Hopper hasn’t turned on Pokes yet.')).toBeTruthy() - expect(screen.getByRole('button', { name: /Poke/ }).hasAttribute('disabled')).toBe(true) + const poke = screen.getByRole('button', { name: /Poke/ }) + // Muted and explained, but still focusable; a click does nothing. + expect(poke.getAttribute('aria-disabled')).toBe('true') + expect(poke.hasAttribute('disabled')).toBe(false) + expect(poke.getAttribute('aria-describedby')).toBeTruthy() + fireEvent.click(poke) + expect(onPoke).not.toHaveBeenCalled() }) it('says when a teammate has not shared their activity', () => { diff --git a/src/renderer/src/components/teammates/TeammateProfileView.tsx b/src/renderer/src/components/teammates/TeammateProfileView.tsx index c7142879d79..a6ad5b56b97 100644 --- a/src/renderer/src/components/teammates/TeammateProfileView.tsx +++ b/src/renderer/src/components/teammates/TeammateProfileView.tsx @@ -1,8 +1,10 @@ +import { useId } from 'react' import { ArrowUpRight, Hand } from 'lucide-react' import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' import { InlineError } from '@/components/ui/inline-error' import { Skeleton } from '@/components/ui/skeleton' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useIntlLocale, useTranslate, type Translate } from '@/i18n/use-translate' import { cn } from '@/lib/utils' import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' @@ -135,6 +137,7 @@ export function TeammateProfileView(props: TeammateProfileViewProps): React.JSX. const { profile } = props const self = profile?.self ?? false const footer = pokeFooterCopy(props, t) + const pokeNoteId = useId() const loading = profile === null && props.error === null return (
    @@ -275,6 +278,7 @@ export function TeammateProfileView(props: TeammateProfileViewProps): React.JSX. props.poke.kind === 'refused' ? 'text-foreground' : 'text-muted-foreground' )} role="status" + id={pokeNoteId} > {footer.note ?? t( @@ -288,20 +292,30 @@ export function TeammateProfileView(props: TeammateProfileViewProps): React.JSX. {t('auto.components.teammates.openExperimental', 'Open settings')} ) : ( - + + + {/* aria-disabled, not disabled: it stays focusable and hoverable so the tooltip can + say why it can't poke, with the muted disabled look. */} + + + {!footer.canPoke && footer.note ? ( + {footer.note} + ) : null} + )} ) : null} From e7ea9f5f73f1190ece98762af797edc656f173e2 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:12:50 -0800 Subject: [PATCH 071/149] fix(cloud-create): 'usually ~Ns' from this computer's own start times; warn past p95 or 30 s (JA-11) The hint used the control plane's create_ms (row to orcad ready, ~2-3 s) for a step the sheet measures end to end (~6 s), so every normal start read as 'Taking longer than usual'. The sheet now records its own 'Start sandbox' durations (local, durations only, last 40), hints from their p50 once there are 5, and warns past their p95; with no measurement yet, only past 30 s. --- .../worktree-creation/VmBuildFailureCard.tsx | 8 +- .../worktree-creation/VmBuildSheet.tsx | 15 ++- .../worktree-creation/VmBuildStepRow.tsx | 19 +++- .../vm-build-sheet-fixture-support.tsx | 1 - .../vm-build-timing.test.tsx | 93 ++++++++++------ .../worktree-creation/vm-build-timing.ts | 105 +++++++++++------- 6 files changed, 155 insertions(+), 86 deletions(-) diff --git a/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx b/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx index a78278f84b0..dc7e71887db 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx @@ -112,13 +112,7 @@ export function VmBuildFailureCard({ {visible.kind === 'checks' ? (
      {visible.problems.map((check, index) => ( - + ))}
    ) : null} diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx index e30da2a0085..6c2a46b3e57 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx @@ -40,7 +40,11 @@ import { orcaCloudRepoName, PUSH_TO_GITHUB_URL } from './vm-build-repo-actions' -import { useVmBuildStepTimings, type VmBuildStepTimings } from './vm-build-timing' +import { + recordCloudStartSample, + useVmBuildStepTimings, + type VmBuildStepTimings +} from './vm-build-timing' import { cloneStageLabel, headerTitle, stepLabel, type SheetState } from './vm-build-sheet-copy' import { humanizeOrcaCloudLogLine, latestOrcaCloudPhaseLabel } from './orca-cloud-build-log' @@ -150,6 +154,15 @@ export function VmBuildSheet({ : step ) const steps = useMinimumRunningSteps(derived, failure === null, now) + // JA-11: this computer's own "Start sandbox" durations drive the next sheet's hint. + const provisionMs = cloud + ? derived.find((step) => step.id === 'provision' && step.state === 'done')?.elapsedMs + : null + React.useEffect(() => { + if (provisionMs) { + recordCloudStartSample(creationId, provisionMs) + } + }, [creationId, provisionMs]) const state: SheetState = failure ? failure.kind === 'checks' ? 'attention' diff --git a/src/renderer/src/components/worktree-creation/VmBuildStepRow.tsx b/src/renderer/src/components/worktree-creation/VmBuildStepRow.tsx index c0803e10056..97d57a66ab1 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildStepRow.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildStepRow.tsx @@ -6,7 +6,11 @@ import { Progress } from '@/components/ui/progress' import { Skeleton } from '@/components/ui/skeleton' import { StepIcon } from './WorktreeSetupSteps' import type { VmBuildStep } from './vm-build-steps' -import { typicalStepSeconds, type VmBuildStepTiming } from './vm-build-timing' +import { + SLOW_WITHOUT_MEASURE_MS, + typicalStepSeconds, + type VmBuildStepTiming +} from './vm-build-timing' import { formatElapsedTime } from './worktree-creation-clock' import { stepLabel, stepStateLabel } from './vm-build-sheet-copy' @@ -44,8 +48,13 @@ export function VmBuildStepRow({ }): React.JSX.Element { const labelId = React.useId() // A live percent already says how far along the step is. - const hint = step.state === 'running' && step.percent === null ? timing : null - const slow = hint !== null && step.elapsedMs !== null && step.elapsedMs > hint.p95Ms + const measuring = step.state === 'running' && step.percent === null + const hint = measuring ? timing : null + // Past the measured p95; with no measurement yet, a sandbox start only after 30 s (JA-11). + const slowAfterMs = + timing?.p95Ms ?? (cloud && step.id === 'provision' ? SLOW_WITHOUT_MEASURE_MS : null) + const slow = + measuring && slowAfterMs !== null && step.elapsedMs !== null && step.elapsedMs > slowAfterMs const modeUnknown = cloud && step.id === 'clone' && step.state === 'pending' && !step.cloneMode const placeholderDue = useDelayedFlag(modeUnknown, PLACEHOLDER_DELAY_MS) @@ -99,9 +108,9 @@ export function VmBuildStepRow({ {t('auto.components.worktree.creation.VmBuildSheet.stateSkipped', 'Skipped')} ) : null} - {hint ? ( + {slow || hint ? ( - {slow + {slow || !hint ? t('auto.components.worktree.creation.VmBuildSheet.slow', 'Taking longer than usual') : t( 'auto.components.worktree.creation.VmBuildSheet.usually', diff --git a/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx b/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx index 51dba4f9da5..879850cdce2 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx +++ b/src/renderer/src/components/worktree-creation/vm-build-sheet-fixture-support.tsx @@ -115,4 +115,3 @@ export const CLOUD_FAILED_LOG = [ 'Orca Cloud refused the request (provider_unavailable).' ].join('\n') export const FAILED_LOG = `${LOG}\nError: snapshot snap_7f2c not found` - diff --git a/src/renderer/src/components/worktree-creation/vm-build-timing.test.tsx b/src/renderer/src/components/worktree-creation/vm-build-timing.test.tsx index d63db26cebc..1a836b19e05 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-timing.test.tsx +++ b/src/renderer/src/components/worktree-creation/vm-build-timing.test.tsx @@ -1,37 +1,66 @@ // @vitest-environment happy-dom -import { cleanup, renderHook, waitFor } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import { useVmBuildStepTimings } from './vm-build-timing' +import { cleanup, render, renderHook } from '@testing-library/react' +import { afterEach, beforeEach, expect, it } from 'vitest' +import type { Translate } from '@/i18n/use-translate' +import { + measuredCloudStart, + recordCloudStartSample, + resetCloudStartSamplesForTests, + useVmBuildStepTimings +} from './vm-build-timing' +import { VmBuildStepRow } from './VmBuildStepRow' +import type { VmBuildStep } from './vm-build-steps' -afterEach(() => { +beforeEach(() => { + window.localStorage.clear() + resetCloudStartSamplesForTests() +}) +afterEach(cleanup) + +const t: Translate = (_key, fallback, params) => + fallback.replace( + '{{seconds}}', + String((params as { seconds?: number } | undefined)?.seconds ?? '') + ) + +it('hints from this computer’s own end-to-end starts, once there are enough of them (JA-11)', () => { + for (const [index, ms] of [6100, 5200, 7000, 6400].entries()) { + recordCloudStartSample(`c${index}`, ms) + } + expect(measuredCloudStart()).toBeNull() + recordCloudStartSample('c4', 8700) + // The same creation never counts twice. + recordCloudStartSample('c4', 8700) + expect(measuredCloudStart()).toEqual({ p50Ms: 6400, p95Ms: 8700 }) + expect(renderHook(() => useVmBuildStepTimings(true)).result.current.provision?.p50Ms).toBe(6400) + expect(renderHook(() => useVmBuildStepTimings(false)).result.current).toEqual({}) + // Persisted across restarts. + resetCloudStartSamplesForTests() + expect(measuredCloudStart()).toEqual({ p50Ms: 6400, p95Ms: 8700 }) +}) + +const running = (elapsedMs: number): VmBuildStep => ({ + id: 'provision', + state: 'running', + skipped: false, + elapsedMs, + percent: null, + startedAt: 0 +}) +const rowText = (step: VmBuildStep, timing: { p50Ms: number; p95Ms: number } | null) => + render( +
      + +
    + ).container.textContent + +it('warns only past the measured p95, or past 30 s with no measurement (JA-11)', () => { + expect(rowText(running(7000), null)).not.toContain('Taking longer') cleanup() - vi.unstubAllGlobals() -}) - -it('asks for the measured timing on every new build sheet, never for VM recipes', async () => { - const getConfig = vi - .fn() - .mockResolvedValueOnce({ - idleSleepMinutes: 15, - createTiming: { p50Ms: 3000, p95Ms: 9000, samples: 40 } - }) - .mockResolvedValueOnce({ - idleSleepMinutes: 15, - createTiming: { p50Ms: 5000, p95Ms: 9000, samples: 41 } - }) - vi.stubGlobal('window', Object.assign(window, { api: { orcaCloudWorkspace: { getConfig } } })) - - const first = renderHook(() => useVmBuildStepTimings(true)) - await waitFor(() => expect(first.result.current.provision?.p50Ms).toBe(3000)) - first.unmount() - - const second = renderHook(() => useVmBuildStepTimings(true)) - // The last answer shows at once, then the fresh one replaces it. - expect(second.result.current.provision?.p50Ms).toBe(3000) - await waitFor(() => expect(second.result.current.provision?.p50Ms).toBe(5000)) - expect(getConfig).toHaveBeenCalledTimes(2) - - renderHook(() => useVmBuildStepTimings(false)) - expect(getConfig).toHaveBeenCalledTimes(2) + expect(rowText(running(31_000), null)).toContain('Taking longer than usual') + cleanup() + expect(rowText(running(7000), { p50Ms: 6000, p95Ms: 9000 })).toContain('usually ~6s') + cleanup() + expect(rowText(running(9500), { p50Ms: 6000, p95Ms: 9000 })).toContain('Taking longer than usual') }) diff --git a/src/renderer/src/components/worktree-creation/vm-build-timing.ts b/src/renderer/src/components/worktree-creation/vm-build-timing.ts index da4495fad67..3031386edb9 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-timing.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-timing.ts @@ -7,52 +7,71 @@ export type VmBuildStepTiming = Pick export type VmBuildStepTimings = Partial> +/** With no measured p95 yet, a running step reads as slow only past this. */ +export const SLOW_WITHOUT_MEASURE_MS = 30_000 + const NONE: VmBuildStepTimings = {} +const STORAGE_KEY = 'orca.cloud.startSamples.v1' +const MAX_SAMPLES = 40 +/** Fewer starts than this say nothing about "usually". */ +const MIN_SAMPLES = 5 -// Each new build sheet asks again: the control plane re-measures recent sandbox starts -// (GET /v1/config) and main caches the answer for 5 minutes. The last answer shows meanwhile. -let measured: VmBuildStepTimings | null = null -let pending: Promise | null = null +// JA-11: the hint used the control plane's create_ms (write-ahead row to orcad ready, ~2-3 s), while +// "Start sandbox" on this sheet runs end to end (token, entitlement, VM, orcad, network: ~6 s). A +// normal start read as "Taking longer than usual". So the hint is this computer's own measurement of +// the very step it labels: the last starts' durations, kept locally (durations only, nothing else). +let samples: number[] | null = null +const recorded = new Set() -function loadMeasuredTimings(): Promise { - pending ??= (window.api.orcaCloudWorkspace?.getConfig?.() ?? Promise.resolve(null)) - .then((config) => { - if (!config) { - // Unreachable now says nothing about later: the next sheet asks again. - pending = null - return measured ?? NONE - } - // Only "Start sandbox" is measured. Without a measurement there is no hint, never a guess. - measured = config.createTiming ? { provision: config.createTiming } : NONE - pending = null - return measured - }) - .catch(() => { - pending = null - return measured ?? NONE - }) - return pending +function load(): number[] { + if (samples) { + return samples + } + try { + const parsed: unknown = JSON.parse(window.localStorage.getItem(STORAGE_KEY) ?? '[]') + samples = Array.isArray(parsed) + ? parsed.filter((v): v is number => typeof v === 'number' && v > 0).slice(-MAX_SAMPLES) + : [] + } catch { + samples = [] + } + return samples } -/** Measured Orca Cloud step timings; empty for VM recipes and until the control plane answers. */ +/** One finished "Start sandbox" of `creationId`, measured on this sheet; each creation counts once. */ +export function recordCloudStartSample(creationId: string, ms: number): void { + if (recorded.has(creationId) || !(ms > 0)) { + return + } + recorded.add(creationId) + samples = [...load(), Math.round(ms)].slice(-MAX_SAMPLES) + try { + window.localStorage.setItem(STORAGE_KEY, JSON.stringify(samples)) + } catch { + // Storage full or unavailable: the hint just stays off. + } +} + +function percentile(sorted: number[], p: number): number { + return sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))]! +} + +/** p50/p95 of this computer's recent starts; null until there are enough of them. */ +export function measuredCloudStart(): VmBuildStepTiming | null { + const values = [...load()].sort((a, b) => a - b) + if (values.length < MIN_SAMPLES) { + return null + } + return { p50Ms: percentile(values, 0.5), p95Ms: percentile(values, 0.95) } +} + +/** Measured Orca Cloud step timings; empty for VM recipes and until enough starts were measured. */ export function useVmBuildStepTimings(cloud: boolean): VmBuildStepTimings { - const [timings, setTimings] = React.useState(() => - cloud ? (measured ?? NONE) : NONE - ) - React.useEffect(() => { - if (!cloud) { - return - } - let live = true - void loadMeasuredTimings().then((next) => { - if (live) { - setTimings(next) - } - }) - return () => { - live = false - } - }, [cloud]) + // Read once per sheet: a start that finishes while it is open must not move its own hint. + const [timings] = React.useState(() => { + const start = cloud ? measuredCloudStart() : null + return start ? { provision: start } : NONE + }) return cloud ? timings : NONE } @@ -60,3 +79,9 @@ export function useVmBuildStepTimings(cloud: boolean): VmBuildStepTimings { export function typicalStepSeconds(timing: VmBuildStepTiming): number { return Math.max(1, Math.round(timing.p50Ms / 1000)) } + +/** Tests: forget what this module read or recorded. */ +export function resetCloudStartSamplesForTests(): void { + samples = null + recorded.clear() +} From c60468e96e63077dfe4f55b01b575233219f3870 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:15:55 -0800 Subject: [PATCH 072/149] test: no type assertion in JA-11 timing test --- .../worktree-creation/vm-build-timing.test.tsx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/renderer/src/components/worktree-creation/vm-build-timing.test.tsx b/src/renderer/src/components/worktree-creation/vm-build-timing.test.tsx index 1a836b19e05..5e17745bf1c 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-timing.test.tsx +++ b/src/renderer/src/components/worktree-creation/vm-build-timing.test.tsx @@ -18,11 +18,11 @@ beforeEach(() => { }) afterEach(cleanup) -const t: Translate = (_key, fallback, params) => - fallback.replace( - '{{seconds}}', - String((params as { seconds?: number } | undefined)?.seconds ?? '') - ) +const t: Translate = (_key, fallback, params) => { + const seconds = + params && typeof params === 'object' && 'seconds' in params ? String(params.seconds) : '' + return fallback.replace('{{seconds}}', seconds) +} it('hints from this computer’s own end-to-end starts, once there are enough of them (JA-11)', () => { for (const [index, ms] of [6100, 5200, 7000, 6400].entries()) { From 60f7d15d3d35fab98c9cea380f5cce0f7b5fe90e Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:26:00 -0800 Subject: [PATCH 073/149] fix(cloud-create): JA-11 stats per kind (clone vs update), rolling last 20, threshold >= 1.5x median under 10 samples (design-squad) --- .../worktree-creation/VmBuildSheet.tsx | 17 ++++- .../vm-build-timing.test.tsx | 29 +++++--- .../worktree-creation/vm-build-timing.ts | 74 +++++++++++++------ 3 files changed, 85 insertions(+), 35 deletions(-) diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx index 6c2a46b3e57..d77200a36ad 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx @@ -47,6 +47,10 @@ import { } from './vm-build-timing' import { cloneStageLabel, headerTitle, stepLabel, type SheetState } from './vm-build-sheet-copy' import { humanizeOrcaCloudLogLine, latestOrcaCloudPhaseLabel } from './orca-cloud-build-log' +import { + orcaCloudCloneProgress, + orcaCloudPlannedRepoMode +} from '@/lib/orca-cloud/orca-cloud-clone-progress' const NO_STAMPS: readonly number[] = [] const SUPPORT_URL = 'https://github.com/stablyai/orca/issues/new' @@ -133,7 +137,12 @@ export function VmBuildSheet({ [entry.provisioningLog] ) const cloud = isOrcaCloudBuild(entry) - const measuredTimings = useVmBuildStepTimings(cloud && stepTimings === undefined) + // Clone and update starts are measured apart (the boot plan names the kind before the step runs). + const startKind = cloud + ? (orcaCloudCloneProgress(entry.provisioningLog ?? '', [])?.mode ?? + orcaCloudPlannedRepoMode(entry.provisioningLog ?? '')) + : null + const measuredTimings = useVmBuildStepTimings(cloud && stepTimings === undefined, startKind) const timings = stepTimings ?? measuredTimings const formatLine = React.useMemo( () => (cloud ? (line: string) => humanizeOrcaCloudLogLine(line, t) : undefined), @@ -159,10 +168,10 @@ export function VmBuildSheet({ ? derived.find((step) => step.id === 'provision' && step.state === 'done')?.elapsedMs : null React.useEffect(() => { - if (provisionMs) { - recordCloudStartSample(creationId, provisionMs) + if (provisionMs && startKind) { + recordCloudStartSample(creationId, startKind, provisionMs) } - }, [creationId, provisionMs]) + }, [creationId, provisionMs, startKind]) const state: SheetState = failure ? failure.kind === 'checks' ? 'attention' diff --git a/src/renderer/src/components/worktree-creation/vm-build-timing.test.tsx b/src/renderer/src/components/worktree-creation/vm-build-timing.test.tsx index 5e17745bf1c..a459eb8bdaf 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-timing.test.tsx +++ b/src/renderer/src/components/worktree-creation/vm-build-timing.test.tsx @@ -24,20 +24,31 @@ const t: Translate = (_key, fallback, params) => { return fallback.replace('{{seconds}}', seconds) } -it('hints from this computer’s own end-to-end starts, once there are enough of them (JA-11)', () => { +it('hints from this computer’s own end-to-end starts per kind, rolling, once there are enough (JA-11)', () => { for (const [index, ms] of [6100, 5200, 7000, 6400].entries()) { - recordCloudStartSample(`c${index}`, ms) + recordCloudStartSample(`c${index}`, 'clone', ms) } - expect(measuredCloudStart()).toBeNull() - recordCloudStartSample('c4', 8700) + expect(measuredCloudStart('clone')).toBeNull() + recordCloudStartSample('c4', 'clone', 6600) // The same creation never counts twice. - recordCloudStartSample('c4', 8700) - expect(measuredCloudStart()).toEqual({ p50Ms: 6400, p95Ms: 8700 }) - expect(renderHook(() => useVmBuildStepTimings(true)).result.current.provision?.p50Ms).toBe(6400) - expect(renderHook(() => useVmBuildStepTimings(false)).result.current).toEqual({}) + recordCloudStartSample('c4', 'clone', 6600) + // Few samples: the warning threshold is at least 1.5x the median, so one outlier can't swing it. + expect(measuredCloudStart('clone')).toEqual({ p50Ms: 6400, p95Ms: 9600 }) + // Updates (repo prebuilt) are measured apart. + expect(measuredCloudStart('update')).toBeNull() + expect( + renderHook(() => useVmBuildStepTimings(true, 'clone')).result.current.provision?.p50Ms + ).toBe(6400) + expect(renderHook(() => useVmBuildStepTimings(true, null)).result.current).toEqual({}) + expect(renderHook(() => useVmBuildStepTimings(false, 'clone')).result.current).toEqual({}) + // Rolling: only the last 20 count, so an old slow day falls out. + for (let index = 0; index < 20; index++) { + recordCloudStartSample(`fast${index}`, 'clone', 3000) + } + expect(measuredCloudStart('clone')).toEqual({ p50Ms: 3000, p95Ms: 3000 }) // Persisted across restarts. resetCloudStartSamplesForTests() - expect(measuredCloudStart()).toEqual({ p50Ms: 6400, p95Ms: 8700 }) + expect(measuredCloudStart('clone')?.p50Ms).toBe(3000) }) const running = (elapsedMs: number): VmBuildStep => ({ diff --git a/src/renderer/src/components/worktree-creation/vm-build-timing.ts b/src/renderer/src/components/worktree-creation/vm-build-timing.ts index 3031386edb9..cf1138f331e 100644 --- a/src/renderer/src/components/worktree-creation/vm-build-timing.ts +++ b/src/renderer/src/components/worktree-creation/vm-build-timing.ts @@ -11,40 +11,59 @@ export type VmBuildStepTimings = Partial +let samples: Samples | null = null const recorded = new Set() -function load(): number[] { +function clean(value: unknown): number[] { + return Array.isArray(value) + ? value.filter((v): v is number => typeof v === 'number' && v > 0).slice(-MAX_SAMPLES) + : [] +} + +function load(): Samples { if (samples) { return samples } try { - const parsed: unknown = JSON.parse(window.localStorage.getItem(STORAGE_KEY) ?? '[]') - samples = Array.isArray(parsed) - ? parsed.filter((v): v is number => typeof v === 'number' && v > 0).slice(-MAX_SAMPLES) - : [] + const parsed: unknown = JSON.parse(window.localStorage.getItem(STORAGE_KEY) ?? '{}') + const record = parsed && typeof parsed === 'object' ? parsed : {} + samples = { + clone: clean('clone' in record ? record.clone : []), + update: clean('update' in record ? record.update : []) + } } catch { - samples = [] + samples = { clone: [], update: [] } } return samples } /** One finished "Start sandbox" of `creationId`, measured on this sheet; each creation counts once. */ -export function recordCloudStartSample(creationId: string, ms: number): void { +export function recordCloudStartSample(creationId: string, kind: CloudStartKind, ms: number): void { if (recorded.has(creationId) || !(ms > 0)) { return } recorded.add(creationId) - samples = [...load(), Math.round(ms)].slice(-MAX_SAMPLES) + const current = load() + samples = { ...current, [kind]: [...current[kind], Math.round(ms)].slice(-MAX_SAMPLES) } try { window.localStorage.setItem(STORAGE_KEY, JSON.stringify(samples)) } catch { @@ -56,22 +75,33 @@ function percentile(sorted: number[], p: number): number { return sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))]! } -/** p50/p95 of this computer's recent starts; null until there are enough of them. */ -export function measuredCloudStart(): VmBuildStepTiming | null { - const values = [...load()].sort((a, b) => a - b) +/** p50/p95 of this computer's recent starts of `kind`; null until there are enough of them. */ +export function measuredCloudStart(kind: CloudStartKind): VmBuildStepTiming | null { + const values = [...load()[kind]].sort((a, b) => a - b) if (values.length < MIN_SAMPLES) { return null } - return { p50Ms: percentile(values, 0.5), p95Ms: percentile(values, 0.95) } + const p50Ms = percentile(values, 0.5) + const p95Ms = percentile(values, 0.95) + return { + p50Ms, + p95Ms: values.length <= SMALL_SAMPLE ? Math.max(p95Ms, Math.round(1.5 * p50Ms)) : p95Ms + } } -/** Measured Orca Cloud step timings; empty for VM recipes and until enough starts were measured. */ -export function useVmBuildStepTimings(cloud: boolean): VmBuildStepTimings { - // Read once per sheet: a start that finishes while it is open must not move its own hint. - const [timings] = React.useState(() => { - const start = cloud ? measuredCloudStart() : null +/** + * Measured Orca Cloud step timings for a start of `kind` (unknown until the boot plan answers: no + * hint meanwhile); empty for VM recipes and until enough starts of that kind were measured. + */ +export function useVmBuildStepTimings( + cloud: boolean, + kind: CloudStartKind | null = null +): VmBuildStepTimings { + // Read once per kind and sheet: a start that finishes while it is open must not move its own hint. + const timings = React.useMemo(() => { + const start = cloud && kind ? measuredCloudStart(kind) : null return start ? { provision: start } : NONE - }) + }, [cloud, kind]) return cloud ? timings : NONE } From 3e5fa71c071c2ad196d9e18342f92e5f86b6cef5 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 19:16:39 -0800 Subject: [PATCH 074/149] =?UTF-8?q?fix(cloud):=20one=20post-create=20agent?= =?UTF-8?q?=20prompt=20=E2=80=94=20exact=20copy,=20names=20the=20workspace?= =?UTF-8?q?=20after=20a=20switch,=20clears=20when=20the=20account=20turns?= =?UTF-8?q?=20active?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../run-on/use-cloud-start-composer.ts | 41 ++----- src/renderer/src/i18n/locales/en.json | 5 +- .../cloud-agent-not-started-toast.test.ts | 81 ++++++++++++++ .../cloud-agent-not-started-toast.ts | 101 ++++++++++++++++++ 4 files changed, 192 insertions(+), 36 deletions(-) create mode 100644 src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.test.ts create mode 100644 src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.ts diff --git a/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts b/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts index 28cc960bfd6..2f4a600a969 100644 --- a/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts +++ b/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts @@ -25,41 +25,16 @@ import { cloudSetupRequired } from '../../orca-cloud-setup/cloud-setup-page-mode import { useRunOnDefault } from './use-run-on-default' import { useCloudOnlyCreate, useCloudOnlyRepo } from './use-cloud-only-repo' import type { CloudStartView } from './cloud-start-view' -import { openOrcaCloudAgentAccounts } from '../OrcaCloudAgentSetupRow' -import { agentName } from '../../settings/agent-accounts/orca-cloud-accounts-copy' +import { showCloudAgentNotStartedToast } from '@/lib/orca-cloud/cloud-agent-not-started-toast' import { isOrcaCloudAccountAgent } from '../../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' export type { CloudStartView } from './cloud-start-view' -/** The workspace started without its agent: one clear way to set the agent up for next time. */ -function showAgentNotStartedToast(agent: string | null): void { - const name = isOrcaCloudAccountAgent(agent) ? agentName(agent, translate) : null - toast.message( - name - ? translate( - 'components.newWorkspace.cloudStart.agentNotStarted', - '{{agent}} isn’t set up for Orca Cloud, so it didn’t start. The workspace has a terminal.', - { agent: name } - ) - : translate( - 'components.newWorkspace.cloudStart.agentNotStartedGeneric', - 'Your agent isn’t set up for Orca Cloud, so it didn’t start. The workspace has a terminal.' - ), - { - action: { - label: name - ? translate( - 'components.newWorkspace.cloudStart.setUpAgentOnce', - 'Set up {{agent}} once', - { - agent: name - } - ) - : translate('components.newWorkspace.cloudStart.setUpAgentOnceGeneric', 'Set up once'), - onClick: openOrcaCloudAgentAccounts - } - } - ) +/** The workspace started without its agent: the one prompt to set it up (design-squad journey). */ +function showAgentNotStartedToast(agent: string | null, workspaceName: string): void { + if (isOrcaCloudAccountAgent(agent)) { + showCloudAgentNotStartedToast(agent, workspaceName) + } } export function useCloudStartComposer({ @@ -157,8 +132,8 @@ export function useCloudStartComposer({ } else { onCreateWithoutAgent() } - showAgentNotStartedToast(agent) - }, [agent, agentUnset, cloudOnly.picked, onCreateRaw, onCreateWithoutAgent]) + showAgentNotStartedToast(agent, prompt) + }, [agent, agentUnset, cloudOnly.picked, onCreateRaw, onCreateWithoutAgent, prompt]) const { markTouched } = useRunOnDefault({ active, diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 3193a98dc26..4bf4c0cd4f1 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -23237,10 +23237,9 @@ "folderDetail": "Orca Cloud starts from a GitHub repository. This project is a folder on this computer." }, "cloudStart": { - "agentNotStarted": "{{agent}} isn’t set up for Orca Cloud, so it didn’t start. The workspace has a terminal.", - "agentNotStartedGeneric": "Your agent isn’t set up for Orca Cloud, so it didn’t start. The workspace has a terminal.", "setUpAgentOnce": "Set up {{agent}} once", - "setUpAgentOnceGeneric": "Set up once" + "agentNotStartedShort": "{{agent}} isn’t set up for Orca Cloud, so it didn’t start.", + "agentNotStartedIn": "{{agent}} isn’t set up for Orca Cloud, so it didn’t start in {{workspace}}." } }, "JiraIssueWorkspace": { diff --git a/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.test.ts b/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.test.ts new file mode 100644 index 00000000000..c39b9cb0317 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.test.ts @@ -0,0 +1,81 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const toastMock = vi.hoisted(() => ({ message: vi.fn(), dismiss: vi.fn() })) +vi.mock('sonner', () => ({ toast: toastMock })) +vi.mock('@/components/new-workspace/OrcaCloudAgentSetupRow', () => ({ + openOrcaCloudAgentAccounts: vi.fn() +})) + +import { useAppStore } from '@/store/index' +import type { OrcaCloudAgentsStatus } from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' +import { + setOrcaCloudAgentAccountsStateForTest, + type OrcaCloudAgentAccountsState +} from './orca-cloud-agent-accounts-store' +import { + cloudAgentNotStartedMessage, + showCloudAgentNotStartedToast +} from './cloud-agent-not-started-toast' + +function accounts( + claude: OrcaCloudAgentsStatus['credentials']['claude'] +): OrcaCloudAgentAccountsState { + return { + load: { + kind: 'ready', + status: { + credentials: { + claude, + codex: { state: 'none' }, + providerEnabled: { claude: true, codex: true } + }, + sources: { defaults: {}, coveredByKey: { claude: false, codex: false } } + } + }, + setups: { claude: { phase: 'idle' }, codex: { phase: 'idle' } }, + keyKinds: { claude: null, codex: null }, + queue: { agents: [], index: 0 } + } +} + +describe('cloud agent not-started toast', () => { + beforeEach(() => { + toastMock.message.mockClear() + toastMock.dismiss.mockClear() + setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'none' })) + useAppStore.setState({ activeWorktreeId: null }) + }) + + it('says it once, with no extra sentence, and names the workspace only after a switch', () => { + expect(cloudAgentNotStartedMessage('Claude', null)).toBe( + 'Claude isn’t set up for Orca Cloud, so it didn’t start.' + ) + expect(cloudAgentNotStartedMessage('Claude', 'fix-readme-typo')).toBe( + 'Claude isn’t set up for Orca Cloud, so it didn’t start in fix-readme-typo.' + ) + showCloudAgentNotStartedToast('claude', 'fix-readme-typo') + expect(toastMock.message).toHaveBeenLastCalledWith( + 'Claude isn’t set up for Orca Cloud, so it didn’t start.', + expect.objectContaining({ + id: 'orca-cloud-agent-not-started', + action: expect.objectContaining({ label: 'Set up Claude once' }) + }) + ) + // The create activates the new workspace, then the user moves elsewhere. + useAppStore.setState({ activeWorktreeId: 'repo::new' }) + expect(toastMock.message).toHaveBeenCalledTimes(1) + useAppStore.setState({ activeWorktreeId: 'repo::other' }) + expect(toastMock.message).toHaveBeenLastCalledWith( + 'Claude isn’t set up for Orca Cloud, so it didn’t start in fix-readme-typo.', + expect.anything() + ) + }) + + it('clears itself once the agent account turns active', () => { + showCloudAgentNotStartedToast('claude', 'w') + setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'expired' })) + expect(toastMock.dismiss).not.toHaveBeenCalled() + setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'active' })) + expect(toastMock.dismiss).toHaveBeenCalledWith('orca-cloud-agent-not-started') + }) +}) diff --git a/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.ts b/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.ts new file mode 100644 index 00000000000..897b5d01690 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.ts @@ -0,0 +1,101 @@ +// After a cloud create whose agent has no Orca Cloud account: the workspace starts with a terminal +// (never the agent's /login) and this one toast is the only sign-in prompt (design-squad journey +// rule). It names the workspace once the user has moved to another one, and clears itself as soon +// as the agent's account turns active. +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' +import { useAppStore } from '@/store/index' +import { openOrcaCloudAgentAccounts } from '@/components/new-workspace/OrcaCloudAgentSetupRow' +import { agentName } from '@/components/settings/agent-accounts/orca-cloud-accounts-copy' +import type { OrcaCloudAccountAgent } from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' +import { orcaCloudAgentCoverageFromAccounts } from './orca-cloud-agent-accounts-model' +import { + readOrcaCloudAgentAccounts, + subscribeOrcaCloudAgentAccounts +} from './orca-cloud-agent-accounts-store' + +const TOAST_ID = 'orca-cloud-agent-not-started' + +let teardown: (() => void) | null = null + +export function cloudAgentNotStartedMessage(agent: string, workspaceName: string | null): string { + return workspaceName + ? translate( + 'components.newWorkspace.cloudStart.agentNotStartedIn', + '{{agent}} isn’t set up for Orca Cloud, so it didn’t start in {{workspace}}.', + { agent, workspace: workspaceName } + ) + : translate( + 'components.newWorkspace.cloudStart.agentNotStartedShort', + '{{agent}} isn’t set up for Orca Cloud, so it didn’t start.', + { agent } + ) +} + +/** True once the agent signs in from the Orca account or a key covers it. */ +export function isCloudAgentCovered(agent: OrcaCloudAccountAgent): boolean { + const coverage = orcaCloudAgentCoverageFromAccounts(agent, readOrcaCloudAgentAccounts()) + return coverage?.kind === 'account' || coverage?.kind === 'key' +} + +export function showCloudAgentNotStartedToast( + agent: OrcaCloudAccountAgent, + workspaceName: string +): void { + teardown?.() + const name = agentName(agent, translate) + const render = (switchedAway: boolean): void => { + toast.message( + cloudAgentNotStartedMessage( + name, + switchedAway && workspaceName.trim() ? workspaceName : null + ), + { + id: TOAST_ID, + // Stays until the user acts on it or the account turns active. + duration: Number.POSITIVE_INFINITY, + action: { + label: translate( + 'components.newWorkspace.cloudStart.setUpAgentOnce', + 'Set up {{agent}} once', + { + agent: name + } + ), + onClick: openOrcaCloudAgentAccounts + }, + onDismiss: () => teardown?.() + } + ) + } + render(false) + + // The create activates the new workspace (first change); any later change means the user moved. + let createdOn: string | null | undefined + let switchedAway = false + const stopWorkspace = useAppStore.subscribe((state, previous) => { + if (state.activeWorktreeId === previous.activeWorktreeId) { + return + } + if (createdOn === undefined) { + createdOn = state.activeWorktreeId ?? null + return + } + const away = state.activeWorktreeId !== createdOn + if (away !== switchedAway) { + switchedAway = away + render(away) + } + }) + const stopAccounts = subscribeOrcaCloudAgentAccounts(() => { + if (isCloudAgentCovered(agent)) { + toast.dismiss(TOAST_ID) + teardown?.() + } + }) + teardown = () => { + stopWorkspace() + stopAccounts() + teardown = null + } +} From 1742f7b6678fc09c2c7dfc01ed90bb41a0877c5d Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:18:32 -0800 Subject: [PATCH 075/149] =?UTF-8?q?fix(cloud):=20Neil's=20build=20gate=20?= =?UTF-8?q?=E2=80=94=20Set=20up=20once=20works,=20no=20setup=20page=20when?= =?UTF-8?q?=20only=20the=20agent=20is=20missing,=20one=20Create=20=3D=20on?= =?UTF-8?q?e=20sandbox,=20no=20hours=20toast?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Set up once: Settings actually opens (the target alone did nothing); the post-create prompt now runs the agent sign-in inline (Claude setup-token, Codex device code) with progress and Try again, and stays until acted on or dismissed (PC-3 interim) - PC-1: the Agent step is never a setup-page step and never gates a start - PC-8: one Create press is one intent, single-flight across the setup page, its auto-start, reveal, Exit and Back; nothing creates while the setup page is open; the intent is the create's Idempotency-Key (preload → IPC → recipe context, create-speed's #345) - PC-5: no 'Using sandbox hours' start toast - setup page: fixed top offset, header line instead of the prompt card, right-aligned actions, Back walks the steps, × Exit keeps the draft without ever auto-running, done steps clickable --- src/main/ephemeral-vm/runtime-service.ts | 3 + src/main/ipc/ephemeral-vm-recipe-context.ts | 2 + src/main/ipc/ephemeral-vm.ts | 1 + src/preload/api/ephemeral-vm-api.ts | 2 + .../new-workspace/OrcaCloudAgentSetupRow.tsx | 7 +- .../new-workspace/composer-modal-data.ts | 2 + .../run-on/cloud-start-model.test.ts | 14 +- .../run-on/orca-cloud-hours-copy.ts | 31 --- .../run-on/use-cloud-only-repo.ts | 9 +- .../run-on/use-cloud-start-composer.ts | 103 +++++---- .../run-on/use-composer-cloud-start.ts | 2 +- .../orca-cloud-setup/CloudSetupPage.tsx | 203 ++++++++++++------ .../orca-cloud-setup/CloudSetupPageLayer.tsx | 35 ++- .../orca-cloud-setup/cloud-setup-page-copy.ts | 63 ++++-- .../cloud-setup-page-model.test.ts | 21 +- .../cloud-setup-page-model.ts | 50 ++--- .../orca-cloud-setup/use-cloud-setup-flow.ts | 18 +- .../src/i18n/en-runtime-required.json | 6 +- src/renderer/src/i18n/locales/en.json | 41 ++-- .../src/lib/ephemeral-vm-workspace-target.ts | 5 +- .../src/lib/ephemeral-vm-worktree-creation.ts | 12 ++ .../cloud-agent-not-started-toast.test.ts | 29 +++ .../cloud-agent-not-started-toast.ts | 197 ++++++++++++++--- .../orca-cloud/cloud-create-intent.test.ts | 115 ++++++++++ .../src/lib/orca-cloud/cloud-create-intent.ts | 110 ++++++++++ .../lib/orca-cloud/cloud-setup-page-store.ts | 32 +-- 26 files changed, 790 insertions(+), 323 deletions(-) create mode 100644 src/renderer/src/lib/orca-cloud/cloud-create-intent.test.ts create mode 100644 src/renderer/src/lib/orca-cloud/cloud-create-intent.ts diff --git a/src/main/ephemeral-vm/runtime-service.ts b/src/main/ephemeral-vm/runtime-service.ts index cb87758dd92..573704383fd 100644 --- a/src/main/ephemeral-vm/runtime-service.ts +++ b/src/main/ephemeral-vm/runtime-service.ts @@ -33,6 +33,8 @@ export type ProvisionEphemeralVmRuntimeArgs = { projectId?: string workspaceId?: string workspaceName?: string + /** One per Create press (Orca Cloud): the create's Idempotency-Key. */ + idempotencyKey?: string repoUrl?: string branch?: string ref?: string @@ -102,6 +104,7 @@ export async function provisionEphemeralVmRuntime( projectId: args.projectId, workspaceId: args.workspaceId, workspaceName: args.workspaceName, + ...(args.idempotencyKey ? { idempotencyKey: args.idempotencyKey } : {}), repoUrl: args.repoUrl, branch: args.branch, ref: args.ref, diff --git a/src/main/ipc/ephemeral-vm-recipe-context.ts b/src/main/ipc/ephemeral-vm-recipe-context.ts index a1b8be2e052..1ede359801d 100644 --- a/src/main/ipc/ephemeral-vm-recipe-context.ts +++ b/src/main/ipc/ephemeral-vm-recipe-context.ts @@ -36,6 +36,8 @@ export type EphemeralVmProvisionArgs = { branch?: string ref?: string provisionId?: string + /** Orca Cloud: the Create press's key; a re-fired create gets the first one's sandbox. */ + idempotencyKey?: string } export type EphemeralVmRecipeCatalogEntry = { diff --git a/src/main/ipc/ephemeral-vm.ts b/src/main/ipc/ephemeral-vm.ts index 15af546b10e..5f831e464e4 100644 --- a/src/main/ipc/ephemeral-vm.ts +++ b/src/main/ipc/ephemeral-vm.ts @@ -195,6 +195,7 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin projectId: args.projectId, workspaceId: args.workspaceId, workspaceName: args.workspaceName, + ...(args.idempotencyKey ? { idempotencyKey: args.idempotencyKey } : {}), ...(repoUrl ? { repoUrl } : {}), ...(args.branch ? { branch: args.branch } : {}), ...(sourceRef ? { ref: sourceRef } : {}), diff --git a/src/preload/api/ephemeral-vm-api.ts b/src/preload/api/ephemeral-vm-api.ts index 12ae965adef..e212d012f1e 100644 --- a/src/preload/api/ephemeral-vm-api.ts +++ b/src/preload/api/ephemeral-vm-api.ts @@ -58,6 +58,8 @@ export type EphemeralVmApi = { branch?: string ref?: string provisionId?: string + /** Orca Cloud: one per Create press, sent as the create's Idempotency-Key. */ + idempotencyKey?: string }) => Promise< | { ok: true diff --git a/src/renderer/src/components/new-workspace/OrcaCloudAgentSetupRow.tsx b/src/renderer/src/components/new-workspace/OrcaCloudAgentSetupRow.tsx index e3d3b0efcd9..4c4de67f66f 100644 --- a/src/renderer/src/components/new-workspace/OrcaCloudAgentSetupRow.tsx +++ b/src/renderer/src/components/new-workspace/OrcaCloudAgentSetupRow.tsx @@ -21,9 +21,10 @@ import { agentName, keySourceLabel } from '../settings/agent-accounts/orca-cloud /** Settings → Agent accounts, scrolled to the Orca Cloud section (S0). The composer stays open. */ export function openOrcaCloudAgentAccounts(): void { - useAppStore - .getState() - .openSettingsTarget({ pane: 'accounts', repoId: null, sectionId: 'orca-cloud' }) + const state = useAppStore.getState() + state.openSettingsTarget({ pane: 'accounts', repoId: null, sectionId: 'orca-cloud' }) + // The target alone only pre-selects the pane; the page has to open too (Neil, P0: "does nothing"). + state.openSettingsPage() } export function orcaCloudAgentCoveredLabel( diff --git a/src/renderer/src/components/new-workspace/composer-modal-data.ts b/src/renderer/src/components/new-workspace/composer-modal-data.ts index 0a2a0f21224..fbf97f38b09 100644 --- a/src/renderer/src/components/new-workspace/composer-modal-data.ts +++ b/src/renderer/src/components/new-workspace/composer-modal-data.ts @@ -40,4 +40,6 @@ export type ComposerModalData = { setupGuideTourRequestId?: string /** Orca Cloud setup finished on its page: submit without showing the dialog (falls back to it). */ cloudAutoStart?: boolean + /** The Create press's intent the auto-start may use, once (one press, one server create). */ + cloudCreateIntent?: string } diff --git a/src/renderer/src/components/new-workspace/run-on/cloud-start-model.test.ts b/src/renderer/src/components/new-workspace/run-on/cloud-start-model.test.ts index 7cb5e31ca4b..71d1f4f0a35 100644 --- a/src/renderer/src/components/new-workspace/run-on/cloud-start-model.test.ts +++ b/src/renderer/src/components/new-workspace/run-on/cloud-start-model.test.ts @@ -24,24 +24,25 @@ describe('Orca Cloud availability', () => { describe('setup rows and the setup page', () => { const page = (steps: Parameters[0]) => - cloudSetupPageModel(steps, { agentSkipped: true }).action + cloudSetupPageModel(steps).action it('starts directly when the account is entitled', () => { const steps = deriveCloudSetupSteps({ availability: 'offered', access: { state: 'entitled', remainingSeconds: 3600 } }) - expect(cloudSetupRequired(steps, { agentSkipped: true })).toBe(false) + expect(cloudSetupRequired(steps)).toBe(false) expect(page(steps)).toBe('done') }) - it('an agent with no account opens the page until it is skipped once', () => { + it('an agent with no account never opens the page (PC-1): the create starts at once', () => { const steps = deriveCloudSetupSteps({ availability: 'offered', access: { state: 'entitled', remainingSeconds: 3600 } }) - expect(cloudSetupRequired(steps)).toBe(true) - expect(cloudSetupPageModel(steps).action).toBe('agent') + expect(steps.find((s) => s.id === 'agent')?.state).toBe('optional') + expect(cloudSetupRequired(steps)).toBe(false) + expect(cloudSetupPageModel(steps).action).toBe('done') }) it('signed out: sign-in first, plan checked after sign-in', () => { @@ -148,7 +149,7 @@ describe('setup rows and the setup page', () => { access: { state: 'entitled', remainingSeconds: 3600 }, github: { id: 'github', state: 'pending', need: 'github', blocksStart: true } }) - expect(cloudSetupRequired(steps, { agentSkipped: true })).toBe(true) + expect(cloudSetupRequired(steps)).toBe(true) expect(page(steps)).toBe('github-waiting') }) @@ -189,6 +190,7 @@ describe('setup rows and the setup page', () => { { id: 'agent', state: 'loading' } ] expect(cloudSetupRequired(steps)).toBe(false) + expect(cloudSetupPageModel(steps).action).toBe('done') }) }) diff --git a/src/renderer/src/components/new-workspace/run-on/orca-cloud-hours-copy.ts b/src/renderer/src/components/new-workspace/run-on/orca-cloud-hours-copy.ts index 6362baa6e36..641e0cbb14b 100644 --- a/src/renderer/src/components/new-workspace/run-on/orca-cloud-hours-copy.ts +++ b/src/renderer/src/components/new-workspace/run-on/orca-cloud-hours-copy.ts @@ -37,37 +37,6 @@ export function getOrcaCloudHoursChip( }) } -/** The start toast: "Using sandbox hours · 2 sandbox hours left in your trial". */ -export function getOrcaCloudStartToast( - access: OrcaCloudRunTargetAccess, - t: Translate, - locale: string -): string | null { - if (access.state !== 'entitled') { - return null - } - const args = hoursArgs(access.remainingSeconds, locale) - return access.trial - ? t( - 'components.newWorkspace.cloudHours.trialToast', - 'Using sandbox hours · {{hours}} sandbox hours left in your trial', - { - count: args.count, - hours: args.hours, - defaultValue_one: 'Using sandbox hours · {{hours}} sandbox hour left in your trial' - } - ) - : t( - 'components.newWorkspace.cloudHours.planToast', - 'Using sandbox hours · {{hours}} sandbox hours left', - { - count: args.count, - hours: args.hours, - defaultValue_one: 'Using sandbox hours · {{hours}} sandbox hour left' - } - ) -} - /** T1: under half an hour of trial left, the hint turns to a warning with the fix. */ export const ORCA_CLOUD_TRIAL_LOW_SECONDS = 30 * 60 diff --git a/src/renderer/src/components/new-workspace/run-on/use-cloud-only-repo.ts b/src/renderer/src/components/new-workspace/run-on/use-cloud-only-repo.ts index 7326ddc2015..1378325d091 100644 --- a/src/renderer/src/components/new-workspace/run-on/use-cloud-only-repo.ts +++ b/src/renderer/src/components/new-workspace/run-on/use-cloud-only-repo.ts @@ -2,7 +2,6 @@ // repositories with no clone here. Picking one keeps Orca Cloud and starts it from GitHub. import { useCallback, useMemo, useState } from 'react' import { useAppStore } from '@/store' -import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import { clearCloudStartDraft } from '@/lib/orca-cloud/cloud-start-draft' import { @@ -102,7 +101,6 @@ export function useCloudOnlyCreate({ prompt, agent, profileId, - hoursToast, onClose }: { cloudOnly: CloudOnlyRepo @@ -110,8 +108,6 @@ export function useCloudOnlyCreate({ prompt: string agent: string | null profileId: string | null - /** "Using sandbox hours · …", or null before billing answers. */ - hoursToast: string | null onClose?: () => void }): () => void { const { picked, start } = cloudOnly @@ -121,12 +117,9 @@ export function useCloudOnlyCreate({ return } clearCloudStartDraft(profileId) - if (hoursToast) { - toast.message(hoursToast) - } void start({ prompt, agent }) onClose?.() - }, [agent, createWorkspace, hoursToast, onClose, picked, profileId, prompt, start]) + }, [agent, createWorkspace, onClose, picked, profileId, prompt, start]) } /** diff --git a/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts b/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts index 2f4a600a969..c37f84d5485 100644 --- a/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts +++ b/src/renderer/src/components/new-workspace/run-on/use-cloud-start-composer.ts @@ -2,15 +2,18 @@ // dialog: Start either creates the workspace (everything is set up) or saves the draft, closes the // dialog and opens the full-page setup, which starts the prompt by itself when done. Also: where // each project last started (O5), the remembered default (D7) and GitHub-only repositories (D4). -import { useCallback, useEffect, useMemo, useRef } from 'react' -import { toast } from 'sonner' +import { useCallback, useEffect, useMemo } from 'react' import { useAppStore } from '@/store/index' -import { translate } from '@/i18n/i18n' import { clearCloudStartDraft, saveCloudStartDraft } from '@/lib/orca-cloud/cloud-start-draft' import { - isCloudSetupAgentSkipped, + getCloudSetupPageRequest, openCloudSetupPage } from '@/lib/orca-cloud/cloud-setup-page-store' +import { + armCloudCreateIdempotency, + consumeCloudCreateIntent, + startCloudCreate +} from '@/lib/orca-cloud/cloud-create-intent' import { recordSuccessfulRunOn } from '@/lib/orca-cloud/run-on-memory' import { ORCA_CLOUD_RECIPE_ID } from '../../../../../shared/hosted-sandbox/orca-cloud-recipe-id' import type { OrcaCloudAvailability } from '../../../../../shared/orca-yaml-hook-types' @@ -18,7 +21,6 @@ import { useOrcaCloudRunTargetAccess } from '../orca-cloud-billing-cache' import type { OrcaCloudRunTargetAccess } from '../orca-cloud-run-target-access' import type { ComposerModalData } from '../composer-modal-data' import { getOrcaCloudSegmentState } from './cloud-start-model' -import { getOrcaCloudStartToast } from './orca-cloud-hours-copy' import { useCloudStartSteps } from './use-cloud-start-steps' import { useSwitchTeamSteps } from '../cloud-setup/use-cloud-setup-tracker' import { cloudSetupRequired } from '../../orca-cloud-setup/cloud-setup-page-model' @@ -46,7 +48,7 @@ export function useCloudStartComposer({ prompt, agent, initialTargetFixed, - autoStart = false, + autoStartIntent = null, createReady = true, composerSnapshot, onCreate: createWorkspace, @@ -63,8 +65,11 @@ export function useCloudStartComposer({ agent: string | null /** The composer was opened on an explicit target (Landing card, a recovery). */ initialTargetFixed: boolean - /** Reopened by the setup page once everything is done: submit as soon as the form is ready. */ - autoStart?: boolean + /** + * Reopened by the setup page once everything is done: the Create press's intent, submitted once + * the form is ready (and only if nothing has used it yet). + */ + autoStartIntent?: string | null /** The composer's own create would run now (project picked, agent resolved). */ createReady?: boolean /** The composer as it is now, for the setup page's Back and its auto-start. */ @@ -104,10 +109,7 @@ export function useCloudStartComposer({ githubOverride: cloudOnly.githubStep }) const { steps, held: switchTeam } = useSwitchTeamSteps(rowSteps, cloudSelected) - const setupNeeded = cloudSetupRequired(steps, { - teamSwitch: switchTeam !== null, - agentSkipped: isCloudSetupAgentSkipped(agent) - }) + const setupNeeded = cloudSetupRequired(steps, { teamSwitch: switchTeam !== null }) // The agent has no Orca Cloud account (the user skipped setting it up): never launch it into its // /login. Start a plain terminal and say how to set the agent up once. const agentUnset = @@ -118,7 +120,6 @@ export function useCloudStartComposer({ prompt, agent: agentUnset ? null : agent, profileId, - hoursToast: getOrcaCloudStartToast(access, translate, navigator.language), onClose }) const onCreate = useCallback(() => { @@ -151,40 +152,54 @@ export function useCloudStartComposer({ }, [markTouched, setRecipeId]) // Start with setup still open: the dialog closes and the page takes over, prompt kept (N6). - const openSetup = useCallback(() => { - saveCloudStartDraft(profileId, { - prompt, - repoId, - agent, - target: 'orca-cloud', - setupSessionId: null, - createdAt: Date.now() - }) - openCloudSetupPage({ - prompt, - repoId, - agent, - availability, - cloudOnlyRepo: cloudOnly.picked?.fullName ?? null, - composer: composerSnapshot() - }) - onClose?.() - }, [agent, availability, cloudOnly.picked, composerSnapshot, onClose, profileId, prompt, repoId]) + const openSetup = useCallback( + (intentId: string) => { + saveCloudStartDraft(profileId, { + prompt, + repoId, + agent, + target: 'orca-cloud', + setupSessionId: null, + createdAt: Date.now() + }) + openCloudSetupPage({ + prompt, + repoId, + agent, + availability, + cloudOnlyRepo: cloudOnly.picked?.fullName ?? null, + composer: composerSnapshot(), + intentId + }) + onClose?.() + }, + [agent, availability, cloudOnly.picked, composerSnapshot, onClose, profileId, prompt, repoId] + ) // Reopened by the setup page: submit once the account and form are ready. Anything still open // (a race, a revoked grant) leaves the composer for the user, never a second trip on its own. - const autoStartedRef = useRef(false) + // One Create press is one server create (P0): the intent is consumed here or nowhere. const stepsSettled = !steps.some((step) => step.state === 'loading' && step.id !== 'agent') useEffect(() => { - if (!autoStart || autoStartedRef.current || !cloudSelected || !createReady || !stepsSettled) { + if (!autoStartIntent || !cloudSelected || !createReady || !stepsSettled || setupNeeded) { return } - if (setupNeeded) { - return + if (consumeCloudCreateIntent(autoStartIntent)) { + armCloudCreateIdempotency(autoStartIntent) + onCreate() } - autoStartedRef.current = true - onCreate() - }, [autoStart, cloudSelected, createReady, onCreate, setupNeeded, stepsSettled]) + }, [autoStartIntent, cloudSelected, createReady, onCreate, setupNeeded, stepsSettled]) + + const onCloudPrimary = useCallback( + () => + startCloudCreate({ + setupOpen: getCloudSetupPageRequest() !== null, + setupNeeded, + openSetup, + create: () => onCreate() + }), + [onCreate, openSetup, setupNeeded] + ) const recordCreated = useCallback(() => { if (!repoId) { @@ -195,12 +210,8 @@ export function useCloudStartComposer({ return } clearCloudStartDraft(profileId) - // O4: the start always says which hours it spends. - const message = getOrcaCloudStartToast(access, translate, navigator.language) - if (message) { - toast.message(message) - } - }, [access, cloudSelected, profileId, repoId]) + // PC-5: no "Using sandbox hours" toast on start; hours live in billing (Neil: noise). + }, [cloudSelected, profileId, repoId]) const view = useMemo( () => @@ -217,5 +228,5 @@ export function useCloudStartComposer({ if (!view || !cloudSelected) { return { view, onPrimary: null, recordCreated } } - return { view, onPrimary: setupNeeded ? openSetup : onCreate, recordCreated } + return { view, onPrimary: onCloudPrimary, recordCreated } } diff --git a/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts b/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts index fd9ec93edc9..6e6f291d5c1 100644 --- a/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts +++ b/src/renderer/src/components/new-workspace/run-on/use-composer-cloud-start.ts @@ -66,7 +66,7 @@ export function useComposerCloudStart({ initialTargetFixed: Boolean( modalData.initialEphemeralVmRecipeId || modalData.initialWorkspaceTarget || modalData.recovery ), - autoStart: modalData.cloudAutoStart === true, + autoStartIntent: modalData.cloudAutoStart ? (modalData.cloudCreateIntent ?? null) : null, createReady: !createDisabled, composerSnapshot, onCreate: runCreate, diff --git a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx index d9dabad6168..6c0301cabbc 100644 --- a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx +++ b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx @@ -3,24 +3,28 @@ // steps are ticks in the stepper. Browser hops only for sign-in, Stripe and GitHub. When every // step is done, the saved prompt starts by itself. import React from 'react' -import { ArrowLeft, Check, Cloud, Copy, ExternalLink, LoaderCircle } from 'lucide-react' +import { ArrowLeft, Check, Copy, ExternalLink, LoaderCircle, X } from 'lucide-react' import { Button } from '@/components/ui/button' import { Skeleton } from '@/components/ui/skeleton' import { cn } from '@/lib/utils' import { useTranslate } from '@/i18n/use-translate' -import type { CloudSetupStep } from '@/components/new-workspace/run-on/cloud-start-model' +import type { + CloudSetupStep, + CloudSetupStepId +} from '@/components/new-workspace/run-on/cloud-start-model' import { CloudSetupErrorNotice } from '@/components/new-workspace/cloud-setup/CloudSetupErrorNotice' -import { currentStepCopy, stepLabel } from './cloud-setup-page-copy' +import { currentStepCopy, doneStepCopy, stepLabel, type StepCopy } from './cloud-setup-page-copy' import type { CloudSetupFlow } from './use-cloud-setup-flow' -import { openOrcaCloudAgentAccounts } from '@/components/new-workspace/OrcaCloudAgentSetupRow' export type CloudSetupPageProps = { flow: CloudSetupFlow projectName: string | null prompt: string agentLabel: string | null - /** Back to the composer with the prompt, project and agent as they were. */ - onBack: () => void + /** Back from the first step: Create workspace again, with the prompt, project and agent kept. */ + onBackToComposer: () => void + /** The × in the corner: leave setup, keep the draft (nothing starts). */ + onExit: () => void /** "All set": shown for a moment before the workspace starts. */ starting: boolean } @@ -30,11 +34,17 @@ type StepState = 'done' | 'current' | 'todo' function SetupStepper({ steps, current, - allDone + viewing, + allDone, + onView }: { steps: readonly CloudSetupStep[] current: CloudSetupStep | null + /** A finished step being revisited. */ + viewing: CloudSetupStepId | null allDone: boolean + /** Revisit a finished step; null returns to the current one. */ + onView: (id: CloudSetupStepId | null) => void }): React.JSX.Element { const t = useTranslate() const currentIndex = current ? steps.findIndex((step) => step.id === current.id) : steps.length @@ -47,9 +57,9 @@ function SetupStepper({ const state: StepState = allDone || index < currentIndex ? 'done' : index === currentIndex ? 'current' : 'todo' const label = stepLabel(step, t) - return ( -
  • - {index > 0 ? : null} + const shownHere = viewing ? viewing === step.id : state === 'current' + const mark = ( + <> {label} @@ -79,6 +89,31 @@ function SetupStepper({ : ''} + + ) + // Finished steps (and the current one, to come back to it) open; future ones don't. + const clickable = + !allDone && (state === 'done' || (state === 'current' && viewing !== null)) + return ( +
  • + {index > 0 ? : null} + {clickable ? ( + + ) : ( + + {mark} + + )}
  • ) })} @@ -152,20 +187,6 @@ function StepActions({ flow }: { flow: CloudSetupFlow }): React.JSX.Element | nu ) case 'switch-team': return
    {flow.teamAction}
    - case 'agent': - return ( -
    - - -
    - ) case 'needs-repository': return flow.current?.action ? ( - - - {t('cloudSetupPage.eyebrow', 'Orca Cloud setup')} - -
    +
    + + + {context} + + +
    -
    - -
    + {/* The same optically-centred top offset on every step, so nothing jumps between them. */} +
    +

    {copy.title}

    - {shown.action === 'checking' ? ( - - ) : copy.lead ? ( -

    {copy.lead}

    - ) : null} - {copy.note ?

    {copy.note}

    : null} +
    - {flow.error && !starting ? ( + {flow.error && !starting && !viewed ? ( ) : null} -
    - -
    - -
    -
    -
    - {t('cloudSetupPage.startsAfter', 'Starts when setup is done')} -
    -
    - {prompt.trim() || t('cloudSetupPage.untitled', 'New cloud workspace')} -
    -
    - {[projectName, agentLabel, t('cloudSetupPage.orcaCloud', 'Orca Cloud')] - .filter(Boolean) - .join(' · ')} -
    -
    +
    + {viewed ? ( + + ) : ( + + )}
    diff --git a/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx b/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx index 3672eddd32d..c57f661d8ad 100644 --- a/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx +++ b/src/renderer/src/components/orca-cloud-setup/CloudSetupPageLayer.tsx @@ -4,6 +4,10 @@ import React, { useCallback, useEffect, useRef, useState } from 'react' import { useAppStore } from '@/store' import { useTranslate } from '@/i18n/use-translate' +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' +import { clearCloudStartDraft } from '@/lib/orca-cloud/cloud-start-draft' +import { cancelCloudCreateIntent } from '@/lib/orca-cloud/cloud-create-intent' import { closeCloudSetupPage, useCloudSetupPageRequest, @@ -21,11 +25,33 @@ import { useCloudSetupFlow } from './use-cloud-setup-flow' /** How long every row must read done before the page starts the workspace. */ const SETTLE_MS = 1_500 +/** + * The × leaves setup. Nothing starts later (JA-01): the page and its auto-start go away, and the + * on-disk draft is dropped. The draft stays one click away in a toast, as a filled composer. + */ +function exitSetup(request: CloudSetupPageRequest): void { + cancelCloudCreateIntent(request.intentId) + closeCloudSetupPage() + clearCloudStartDraft(useAppStore.getState().activeOrcaProfileId ?? null) + toast.message( + translate('cloudSetupPage.exited', 'Orca Cloud setup closed. Your draft is kept.'), + { + action: { + label: translate('cloudSetupPage.resumeDraft', 'Open draft'), + onClick: () => reopenComposer(request, false) + } + } + ) +} + function reopenComposer(request: CloudSetupPageRequest, autoStart: boolean): void { // A GitHub-only repository can't be preselected; the composer opens for one more Start. const hiddenStart = autoStart && !request.cloudOnlyRepo if (!hiddenStart) { + // Back, or a start that needs one more press: this setup's intent can never create. + cancelCloudCreateIntent(request.intentId) closeCloudSetupPage() + clearCloudStartDraft(useAppStore.getState().activeOrcaProfileId ?? null) } else { // Warm the start screen's chunk so it is ready the frame the create takes over. void import('@/components/worktree-creation/WorktreeCreationPanel').catch(() => undefined) @@ -33,7 +59,7 @@ function reopenComposer(request: CloudSetupPageRequest, autoStart: boolean): voi useAppStore.getState().openModal('new-workspace-composer', { ...request.composer, initialEphemeralVmRecipeId: ORCA_CLOUD_RECIPE_ID, - ...(hiddenStart ? { cloudAutoStart: true } : {}) + ...(hiddenStart ? { cloudAutoStart: true, cloudCreateIntent: request.intentId } : {}) }) if (hiddenStart) { // The page stays up until the start screen has painted: nothing under it may flash. @@ -76,14 +102,16 @@ function ActiveCloudSetupPage({ request }: { request: CloudSetupPageRequest }): ) return () => window.clearTimeout(timer) }, [request, starting]) - const onBack = useCallback(() => reopenComposer(request, false), [request]) + const onBackToComposer = useCallback(() => reopenComposer(request, false), [request]) + const onExit = useCallback(() => exitSetup(request), [request]) return ( ) @@ -104,6 +132,7 @@ export function CloudSetupPageLayer(): React.JSX.Element | null { return } if (openedOnRef.current !== activeWorktreeId) { + cancelCloudCreateIntent(request.intentId) closeCloudSetupPage() } }, [activeWorktreeId, request]) diff --git a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-copy.ts b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-copy.ts index edd0e67a473..4ad8ab0224f 100644 --- a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-copy.ts +++ b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-copy.ts @@ -22,7 +22,13 @@ export function stepLabel(step: CloudSetupStep, t: Translate): string { } } -type StepCopy = { title: string; lead: string | null; note?: string | null } +export type StepCopy = { + title: string + lead: string | null + note?: string | null + /** A gentle option under the lead, set apart in muted italics (the agent step's skip hint). */ + aside?: string | null +} function trialHours(step: CloudSetupStep): string | null { return step.trialSeconds ? String(Math.round((step.trialSeconds / 3600) * 10) / 10) : null @@ -30,8 +36,7 @@ function trialHours(step: CloudSetupStep): string | null { export function currentStepCopy( flow: Pick, - t: Translate, - agentLabel: string | null + t: Translate ): StepCopy { const step = flow.current const detail = step @@ -146,16 +151,6 @@ export function currentStepCopy( 'Orca Cloud needs a Team plan. Only owners and admins can choose one.' ) } - case 'agent': - return { - title: agentLabel - ? t('cloudSetupPage.agent.title', 'Sign in to {{agent}} once', { agent: agentLabel }) - : t('cloudSetupPage.agent.titleGeneric', 'Sign in to your agent once'), - lead: t( - 'cloudSetupPage.agent.lead', - 'Save your agent sign-in to your Orca account and every cloud workspace uses it. You can also skip this and sign in inside the workspace.' - ) - } case 'checking': return { title: t('cloudSetupPage.checking.title', 'Checking your Orca Cloud account…'), @@ -168,3 +163,45 @@ export function currentStepCopy( } } } + +/** A finished step revisited from the stepper or Back: what it settled, in one calm line. */ +export function doneStepCopy( + step: CloudSetupStep, + t: Translate, + agentLabel: string | null +): StepCopy { + switch (step.id) { + case 'account': + return { + title: t('cloudSetupPage.done.accountTitle', 'You’re signed in'), + lead: t('cloudSetupPage.done.accountLead', 'Your Orca account is ready for Orca Cloud.') + } + case 'team': + return { + title: t('cloudSetupPage.done.teamTitle', 'Team selected'), + lead: step.detail ?? null + } + case 'plan': + return { + title: + step.detail === 'trial' || step.need === 'trial' + ? t('cloudSetupPage.done.trialTitle', 'Your trial is on') + : t('cloudSetupPage.done.planTitle', 'Your team has Orca Cloud'), + lead: null + } + case 'github': + return { + title: t('cloudSetupPage.done.githubTitle', 'Orca Cloud can reach this repository'), + lead: null + } + case 'agent': + return { + title: agentLabel + ? t('cloudSetupPage.done.agentTitle', '{{agent}} is set up for Orca Cloud', { + agent: agentLabel + }) + : t('cloudSetupPage.done.agentTitleGeneric', 'Your agent is set up for Orca Cloud'), + lead: null + } + } +} diff --git a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.test.ts b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.test.ts index 1fbeb8eca20..f1606a782b1 100644 --- a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.test.ts +++ b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.test.ts @@ -16,17 +16,15 @@ describe('cloudSetupPageModel', () => { expect(sessionNeedsFrom(steps)).toEqual(['plan', 'github']) }) - it('a skipped agent finishes setup', () => { + it('the agent is never a page step and never holds the start (PC-1)', () => { const steps: CloudSetupStep[] = [ { id: 'account', state: 'done' }, { id: 'plan', state: 'done' }, { id: 'agent', state: 'optional' } ] - expect(cloudSetupPageModel(steps).action).toBe('agent') - expect(cloudSetupPageModel(steps, { agentSkipped: true })).toMatchObject({ - current: null, - action: 'done' - }) + const model = cloudSetupPageModel(steps) + expect(model.steps.map((step) => step.id)).toEqual(['account', 'plan']) + expect(model).toMatchObject({ current: null, action: 'done' }) }) it('maps each blocker to its one action', () => { @@ -41,14 +39,3 @@ describe('cloudSetupPageModel', () => { expect(actionForStep({ id: 'github', state: 'loading' })).toBe('checking') }) }) - -describe('page settles before it starts', () => { - it('a still-loading agent row reads Checking, not All set', () => { - const steps: CloudSetupStep[] = [ - { id: 'account', state: 'done' }, - { id: 'plan', state: 'done' }, - { id: 'agent', state: 'loading' } - ] - expect(cloudSetupPageModel(steps).action).toBe('checking') - }) -}) diff --git a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.ts b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.ts index ca7c8884e5f..584e1f86269 100644 --- a/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.ts +++ b/src/renderer/src/components/orca-cloud-setup/cloud-setup-page-model.ts @@ -22,8 +22,6 @@ export type CloudSetupPageAction = | 'needs-repository' /** A member can't fix billing; an owner or admin has to. */ | 'ask-owner' - /** Optional agent account: set it up once, or skip. */ - | 'agent' /** Still reading account, plan or repository state. */ | 'checking' /** Every step is done: the prompt starts. */ @@ -35,17 +33,6 @@ export type CloudSetupPageModel = { action: CloudSetupPageAction } -function isFinished(step: CloudSetupStep, agentSkipped: boolean): boolean { - if (step.state === 'done') { - return true - } - if (step.id === 'agent') { - // Still loading reads "Checking": the page only says All set once every row has answered. - return agentSkipped && step.state !== 'loading' - } - return false -} - export function actionForStep( step: CloudSetupStep, { teamSwitch = false }: { teamSwitch?: boolean } = {} @@ -90,23 +77,23 @@ export function actionForStep( } return 'github-install' case 'agent': - return 'agent' + // Never a page step (PC-1): agent sign-in is offered after create. + return 'done' } } /** - * The page's state from the setup rows. Steps come in walk order (account, team, plan, GitHub, - * agent); the first unfinished one is current. A signed-out plan row is "pending" until sign-in, so - * account stays current until then. + * The page's state from the setup rows. Steps come in walk order (account, team, plan, GitHub); the + * first unfinished one is current. The agent row is never a step (PC-1): it never gates a start, and + * its sign-in is offered after create. A signed-out plan row is "pending" until sign-in, so account + * stays current until then. */ export function cloudSetupPageModel( - steps: readonly CloudSetupStep[], - { - agentSkipped = false, - teamSwitch = false - }: { agentSkipped?: boolean; teamSwitch?: boolean } = {} + rows: readonly CloudSetupStep[], + { teamSwitch = false }: { teamSwitch?: boolean } = {} ): CloudSetupPageModel { - const current = steps.find((step) => !isFinished(step, agentSkipped)) ?? null + const steps = rows.filter((step) => step.id !== 'agent') + const current = steps.find((step) => step.state !== 'done') ?? null if (!current) { return { steps, current: null, action: 'done' } } @@ -121,23 +108,16 @@ export function sessionNeedsFrom(steps: readonly CloudSetupStep[]): CloudSetupSt } /** - * Pressing Start goes straight to create only when nothing is open. An agent without an account - * counts until the user skips it once; a still-loading agent row never holds a start. + * Pressing Start opens the setup page only when the account, team, plan or GitHub is missing. The + * agent never holds a start (PC-1): without an Orca Cloud account it starts as a plain terminal and + * the post-create prompt offers the sign-in. */ export function cloudSetupRequired( steps: readonly CloudSetupStep[], - { - teamSwitch = false, - agentSkipped = false - }: { teamSwitch?: boolean; agentSkipped?: boolean } = {} + { teamSwitch = false }: { teamSwitch?: boolean } = {} ): boolean { if (teamSwitch) { return true } - return steps.some((step) => { - if (step.id === 'agent') { - return step.state === 'optional' && !agentSkipped - } - return step.state !== 'done' - }) + return steps.some((step) => step.id !== 'agent' && step.state !== 'done') } diff --git a/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts b/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts index 165dbd03b21..680274cf170 100644 --- a/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts +++ b/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts @@ -20,11 +20,7 @@ import { reopenCloudSetup } from '@/components/new-workspace/cloud-setup/cloud-setup-tracker-actions' import { getCloudSetupStarter } from '@/lib/orca-cloud/cloud-setup-session-seam' -import { - isCloudSetupAgentSkipped, - rememberCloudSetupAgentSkipped, - type CloudSetupPageRequest -} from '@/lib/orca-cloud/cloud-setup-page-store' +import type { CloudSetupPageRequest } from '@/lib/orca-cloud/cloud-setup-page-store' import { reportCloudSetupProgress } from '@/lib/orca-cloud/cloud-setup-telemetry' import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' import type { OrcaCloudAvailability } from '../../../../shared/orca-yaml-hook-types' @@ -89,7 +85,6 @@ export type CloudSetupFlow = CloudSetupPageModel & { startTrial: () => void fixBilling: () => void installGitHub: () => void - skipAgent: () => void checkAgain: () => void copyLink: (() => void) | null reopenBrowser: () => void @@ -108,7 +103,6 @@ export function useCloudSetupFlow( // opened for, so it waits on all of them; a single hop (GitHub install, billing) only on its own. const [browserStep, setBrowserStep] = useState(null) const [busy, setBusy] = useState(false) - const [agentSkipped, setAgentSkipped] = useState(() => isCloudSetupAgentSkipped(request.agent)) const githubOverride = useMemo( () => (request.cloudOnlyRepo ? { id: 'github', state: 'done' } : null), [request.cloudOnlyRepo] @@ -127,14 +121,14 @@ export function useCloudSetupFlow( githubOverride }) const { steps, held: switchTeam } = useSwitchTeamSteps(rowSteps, !session) - const model = cloudSetupPageModel(steps, { agentSkipped, teamSwitch: switchTeam !== null }) + const model = cloudSetupPageModel(steps, { teamSwitch: switchTeam !== null }) const error = useMemo(() => { const parsed = parseCloudSetupError(session?.error) return parsed && session?.teamName ? { ...parsed, teamName: session.teamName } : parsed }, [session?.error, session?.teamName]) // Rows derived from billing tick on their own: re-read while a step is waiting elsewhere. - const waiting = model.action !== 'done' && model.action !== 'agent' + const waiting = model.action !== 'done' useEffect(() => { if (!waiting || accessOverride) { return @@ -217,11 +211,6 @@ export function useCloudSetupFlow( void openInstall() }, [markInBrowser, openInstall]) - const skipAgent = useCallback(() => { - rememberCloudSetupAgentSkipped(request.agent) - setAgentSkipped(true) - }, [request.agent]) - const checkAgain = useCallback(() => void prefetchOrcaCloudBilling(true), []) return { @@ -235,7 +224,6 @@ export function useCloudSetupFlow( startTrial, fixBilling, installGitHub, - skipAgent, checkAgain, copyLink: sessionId && canCopyCloudSetupLink(sessionId) diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 671c08689c0..7208c28db92 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -2131,14 +2131,10 @@ "cloudHours": { "planChip_one": "{{hours}} sandbox hour left", "planChip_other": "{{hours}} sandbox hours left", - "planToast_one": "Using sandbox hours · {{hours}} sandbox hour left", - "planToast_other": "Using sandbox hours · {{hours}} sandbox hours left", "trialChip_one": "Trial · {{hours}} sandbox hour left", "trialChip_other": "Trial · {{hours}} sandbox hours left", "trialOffered_one": "Trial · {{hours}} sandbox hour left · No card needed", - "trialOffered_other": "Trial · {{hours}} sandbox hours left · No card needed", - "trialToast_one": "Using sandbox hours · {{hours}} sandbox hour left in your trial", - "trialToast_other": "Using sandbox hours · {{hours}} sandbox hours left in your trial" + "trialOffered_other": "Trial · {{hours}} sandbox hours left · No card needed" }, "cloudSetup": { "trialOffer_one": "{{hours}} sandbox hour to try Orca Cloud", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 4bf4c0cd4f1..69dd241e41b 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -23211,10 +23211,6 @@ "trialChip_other": "Trial · {{hours}} sandbox hours left", "planChip_one": "{{hours}} sandbox hour left", "planChip_other": "{{hours}} sandbox hours left", - "trialToast_one": "Using sandbox hours · {{hours}} sandbox hour left in your trial", - "trialToast_other": "Using sandbox hours · {{hours}} sandbox hours left in your trial", - "planToast_one": "Using sandbox hours · {{hours}} sandbox hour left", - "planToast_other": "Using sandbox hours · {{hours}} sandbox hours left", "trialOffered_one": "Trial · {{hours}} sandbox hour left · No card needed", "trialOffered_other": "Trial · {{hours}} sandbox hours left · No card needed" }, @@ -23239,7 +23235,13 @@ "cloudStart": { "setUpAgentOnce": "Set up {{agent}} once", "agentNotStartedShort": "{{agent}} isn’t set up for Orca Cloud, so it didn’t start.", - "agentNotStartedIn": "{{agent}} isn’t set up for Orca Cloud, so it didn’t start in {{workspace}}." + "agentNotStartedIn": "{{agent}} isn’t set up for Orca Cloud, so it didn’t start in {{workspace}}.", + "copyCode": "Copy code", + "openSettings": "Open Settings", + "signInBrowser": "Finish signing in to {{agent}} in your browser…", + "signInDevice": "Enter {{code}} at {{host}} to sign in to {{agent}}.", + "signInPaste": "Paste the {{agent}} setup token in Settings to finish.", + "signInSaving": "Saving…" } }, "JiraIssueWorkspace": { @@ -28071,13 +28073,6 @@ "expiredCompact": "{{agent}} sign-in expired" }, "cloudSetupPage": { - "agent": { - "lead": "Save your agent sign-in to your Orca account and every cloud workspace uses it. You can also skip this and sign in inside the workspace.", - "setUp": "Set up once", - "skip": "Skip for now", - "title": "Sign in to {{agent}} once", - "titleGeneric": "Sign in to your agent once" - }, "back": "Back", "billing": { "capLead": "Raise the spend cap to start this workspace.", @@ -28096,16 +28091,22 @@ "copyLink": "Copy link", "done": { "lead": "Starting your cloud workspace…", - "title": "All set" + "title": "All set", + "accountLead": "Your Orca account is ready for Orca Cloud.", + "accountTitle": "You’re signed in", + "agentTitle": "{{agent}} is set up for Orca Cloud", + "agentTitleGeneric": "Your agent is set up for Orca Cloud", + "githubTitle": "Orca Cloud can reach this repository", + "planTitle": "Your team has Orca Cloud", + "teamTitle": "Team selected", + "trialTitle": "Your trial is on" }, - "eyebrow": "Orca Cloud setup", "github": { "lead": "Orca Cloud clones your code from GitHub. Install the Orca Cloud app on this repository once.", "title": "Give Orca Cloud access on GitHub", "waiting": "This page starts the workspace once they approve.", "waitingTitle": "Waiting for approval on GitHub" }, - "orcaCloud": "Orca Cloud", "owner": { "lead": "Orca Cloud needs a Team plan. Only owners and admins can choose one.", "title": "An owner or admin needs to fix this" @@ -28128,7 +28129,6 @@ "title": "Sign in to Orca" }, "starting": "Starting…", - "startsAfter": "Starts when setup is done", "step": { "account": "Account", "agent": "Agent", @@ -28152,7 +28152,12 @@ "lead_one": "{{hours}} sandbox hour to try Orca Cloud. No card needed.", "lead_other": "{{hours}} sandbox hours to try Orca Cloud. No card needed." }, - "untitled": "New cloud workspace", - "waitingBrowser": "Waiting for your browser…" + "waitingBrowser": "Waiting for your browser…", + "continue": "Continue", + "exit": "Exit setup", + "exited": "Orca Cloud setup closed. Your draft is kept.", + "header": "Setting up Orca Cloud", + "headerFor": "Setting up Orca Cloud for {{name}}", + "resumeDraft": "Open draft" } } diff --git a/src/renderer/src/lib/ephemeral-vm-workspace-target.ts b/src/renderer/src/lib/ephemeral-vm-workspace-target.ts index ad0f768f2a1..15b11617c65 100644 --- a/src/renderer/src/lib/ephemeral-vm-workspace-target.ts +++ b/src/renderer/src/lib/ephemeral-vm-workspace-target.ts @@ -28,6 +28,8 @@ export type PrepareEphemeralVmWorkspaceTargetArgs = { branch?: string ref?: string provisionId?: string + /** Orca Cloud: the Create press's key (one press, one sandbox). */ + idempotencyKey?: string setupExistingFolder: ( args: ProjectHostSetupExistingFolderArgs ) => Promise @@ -62,7 +64,8 @@ export async function prepareEphemeralVmWorkspaceTarget( workspaceName: args.workspaceName, ...(args.branch ? { branch: args.branch } : {}), ...(args.ref ? { ref: args.ref } : {}), - ...(args.provisionId ? { provisionId: args.provisionId } : {}) + ...(args.provisionId ? { provisionId: args.provisionId } : {}), + ...(args.idempotencyKey ? { idempotencyKey: args.idempotencyKey } : {}) }) if (!provisioned.ok) { return { diff --git a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts b/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts index 084094691a3..b03c9e01085 100644 --- a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts +++ b/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts @@ -19,6 +19,8 @@ import { appendProvisioningLog, appendProvisioningWarnings } from '@/lib/pending-creation-provisioning-log' +import { cloudCreateIdempotencyKey } from '@/lib/orca-cloud/cloud-create-intent' +import { ORCA_CLOUD_RECIPE_ID } from '../../../shared/hosted-sandbox/orca-cloud-recipe-id' export async function prepareRequestForCreate( creationId: string, @@ -71,6 +73,7 @@ async function prepareEphemeralVmRecipeRequest( } : {}), provisionId: creationId, + ...cloudCreateIdempotency(recipe.recipeId, creationId), setupExistingFolder: async (args) => { // The VM's checkout folder is named "project"; register it under the real project's name. const displayName = @@ -268,3 +271,12 @@ export function getProvisionedRootSparseCheckoutError(): string { 'Provisioned-root recipes do not support sparse checkout.' ) } + +/** Orca Cloud creates carry the Create press's Idempotency-Key; other recipes don't. */ +function cloudCreateIdempotency(recipeId: string, creationId: string): { idempotencyKey?: string } { + if (recipeId !== ORCA_CLOUD_RECIPE_ID) { + return {} + } + const key = cloudCreateIdempotencyKey(creationId) + return key ? { idempotencyKey: key } : {} +} diff --git a/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.test.ts b/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.test.ts index c39b9cb0317..8352e50e713 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.test.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.test.ts @@ -1,3 +1,4 @@ +// @vitest-environment happy-dom import { beforeEach, describe, expect, it, vi } from 'vitest' const toastMock = vi.hoisted(() => ({ message: vi.fn(), dismiss: vi.fn() })) @@ -78,4 +79,32 @@ describe('cloud agent not-started toast', () => { setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'active' })) expect(toastMock.dismiss).toHaveBeenCalledWith('orca-cloud-agent-not-started') }) + + it('"Set up Claude once" starts the sign-in right from the toast, which stays up', () => { + const start = vi.fn(async () => undefined) + Object.assign(window, { + api: { ...(window as { api?: object }).api, orcaCloudAgents: { start } } + }) + showCloudAgentNotStartedToast('claude', 'w') + const options: { + duration: number + action: { onClick: (event: { preventDefault: () => void }) => void } + } = toastMock.message.mock.calls.at(-1)?.[1] + expect(options.duration).toBe(Number.POSITIVE_INFINITY) + const preventDefault = vi.fn() + options.action.onClick({ preventDefault }) + expect(preventDefault).toHaveBeenCalled() + expect(start).toHaveBeenCalledWith({ agent: 'claude' }) + }) + + it('in the workspace itself it stays hidden (its pane strip asks); away, it names it', () => { + showCloudAgentNotStartedToast('claude', 'fix-readme-typo', { onlyWhenAway: true }) + expect(toastMock.message).not.toHaveBeenCalled() + useAppStore.setState({ activeWorktreeId: 'repo::new' }) + useAppStore.setState({ activeWorktreeId: 'repo::other' }) + expect(toastMock.message).toHaveBeenLastCalledWith( + 'Claude isn’t set up for Orca Cloud, so it didn’t start in fix-readme-typo.', + expect.anything() + ) + }) }) diff --git a/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.ts b/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.ts index 897b5d01690..30024fddd20 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.ts @@ -1,13 +1,23 @@ -// After a cloud create whose agent has no Orca Cloud account: the workspace starts with a terminal -// (never the agent's /login) and this one toast is the only sign-in prompt (design-squad journey -// rule). It names the workspace once the user has moved to another one, and clears itself as soon -// as the agent's account turns active. +// After a cloud create whose agent has no Orca Cloud account, the workspace starts with a terminal +// (never the agent's /login). This one toast is the only sign-in prompt (design-squad journey rule; +// PC-1, PC-3). +// - It stays until the user acts on it or dismisses it. +// - It names the workspace once the user has moved to another one. +// - "Set up Claude once" runs the S0 sign-in right from the toast: Claude via setup-token in the +// browser, Codex via a device code. The toast shows progress and errors, with Try again. +// - It clears itself as soon as the account turns active. import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import { useAppStore } from '@/store/index' import { openOrcaCloudAgentAccounts } from '@/components/new-workspace/OrcaCloudAgentSetupRow' -import { agentName } from '@/components/settings/agent-accounts/orca-cloud-accounts-copy' -import type { OrcaCloudAccountAgent } from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' +import { + agentName, + setupFailureCopy +} from '@/components/settings/agent-accounts/orca-cloud-accounts-copy' +import type { + OrcaCloudAccountAgent, + OrcaCloudAgentSetup +} from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' import { orcaCloudAgentCoverageFromAccounts } from './orca-cloud-agent-accounts-model' import { readOrcaCloudAgentAccounts, @@ -38,41 +48,163 @@ export function isCloudAgentCovered(agent: OrcaCloudAccountAgent): boolean { return coverage?.kind === 'account' || coverage?.kind === 'key' } +type ToastView = { + message: string + description?: string + action?: { label: string; run: () => void } +} + +function deviceHost(url: string): string { + try { + return new URL(url).hostname + } catch { + return url + } +} + +/** What the toast says while the S0 sign-in runs; null while it is idle (the plain prompt). */ +export function cloudAgentSignInView( + agent: OrcaCloudAccountAgent, + setup: OrcaCloudAgentSetup +): ToastView | null { + const api = globalThis.window?.api?.orcaCloudAgents + const name = agentName(agent, translate) + switch (setup.phase) { + case 'idle': + case 'saved': + return null + case 'browser': + return { + message: translate( + 'components.newWorkspace.cloudStart.signInBrowser', + 'Finish signing in to {{agent}} in your browser…', + { agent: name } + ), + ...(setup.canReopen + ? { + action: { + label: translate('orcaCloudAccounts.openAgain', 'Open again'), + run: () => void api?.reopen({ agent }) + } + } + : {}) + } + case 'preparing': + return { + message: translate('orcaCloudAccounts.preparing', 'Getting ChatGPT sign-in ready') + } + case 'device': + return { + message: translate( + 'components.newWorkspace.cloudStart.signInDevice', + 'Enter {{code}} at {{host}} to sign in to {{agent}}.', + { code: setup.userCode, host: deviceHost(setup.verificationUrl), agent: name } + ), + action: { + label: translate('components.newWorkspace.cloudStart.copyCode', 'Copy code'), + run: () => void window.api.ui.writeClipboardText(setup.userCode).catch(() => {}) + } + } + case 'paste': + // The token goes in Settings' masked field, never in a toast. + return { + message: translate( + 'components.newWorkspace.cloudStart.signInPaste', + 'Paste the {{agent}} setup token in Settings to finish.', + { agent: name } + ), + action: { + label: translate('components.newWorkspace.cloudStart.openSettings', 'Open Settings'), + run: openOrcaCloudAgentAccounts + } + } + case 'saving': + return { + message: translate('components.newWorkspace.cloudStart.signInSaving', 'Saving…') + } + case 'failed': { + const copy = setupFailureCopy(agent, setup.error, translate) + return { + message: copy.title, + ...(copy.detail ? { description: copy.detail } : {}), + action: { + label: translate('orcaCloudAccounts.tryAgain', 'Try again'), + run: () => void api?.start({ agent }) + } + } + } + } +} + export function showCloudAgentNotStartedToast( agent: OrcaCloudAccountAgent, - workspaceName: string + workspaceName: string, + { + onlyWhenAway = false + }: { + /** + * The workspace's agent pane shows its own held strip (PC-3), so the toast appears only while + * the user is in another workspace, naming this one. + */ + onlyWhenAway?: boolean + } = {} ): void { teardown?.() const name = agentName(agent, translate) - const render = (switchedAway: boolean): void => { - toast.message( - cloudAgentNotStartedMessage( + let switchedAway = false + const render = (): void => { + const signIn = cloudAgentSignInView(agent, readOrcaCloudAgentAccounts().setups[agent]) + const view: ToastView = signIn ?? { + message: cloudAgentNotStartedMessage( name, switchedAway && workspaceName.trim() ? workspaceName : null ), - { - id: TOAST_ID, - // Stays until the user acts on it or the account turns active. - duration: Number.POSITIVE_INFINITY, - action: { - label: translate( - 'components.newWorkspace.cloudStart.setUpAgentOnce', - 'Set up {{agent}} once', - { - agent: name - } - ), - onClick: openOrcaCloudAgentAccounts - }, - onDismiss: () => teardown?.() + action: { + label: translate( + 'components.newWorkspace.cloudStart.setUpAgentOnce', + 'Set up {{agent}} once', + { agent: name } + ), + run: () => void globalThis.window?.api?.orcaCloudAgents?.start({ agent }) } - ) + } + toast.message(view.message, { + id: TOAST_ID, + ...(view.description ? { description: view.description } : {}), + // Persistent (PC-3): it stays until the user acts on it, closes it, or the account is active. + duration: Number.POSITIVE_INFINITY, + closeButton: true, + ...(view.action + ? { + action: { + label: view.action.label, + onClick: (event: { preventDefault: () => void }) => { + // Keep the toast: it turns into the sign-in's progress. + event.preventDefault() + view.action?.run() + } + } + } + : {}), + // A close by the user ends it; a hide on returning to the workspace (onlyWhenAway) doesn't. + onDismiss: () => { + if (!onlyWhenAway || switchedAway) { + teardown?.() + } + } + }) } - render(false) + const update = (): void => { + if (onlyWhenAway && !switchedAway) { + toast.dismiss(TOAST_ID) + return + } + render() + } + update() // The create activates the new workspace (first change); any later change means the user moved. let createdOn: string | null | undefined - let switchedAway = false const stopWorkspace = useAppStore.subscribe((state, previous) => { if (state.activeWorktreeId === previous.activeWorktreeId) { return @@ -84,13 +216,20 @@ export function showCloudAgentNotStartedToast( const away = state.activeWorktreeId !== createdOn if (away !== switchedAway) { switchedAway = away - render(away) + update() } }) + let lastPhase = readOrcaCloudAgentAccounts().setups[agent].phase const stopAccounts = subscribeOrcaCloudAgentAccounts(() => { if (isCloudAgentCovered(agent)) { toast.dismiss(TOAST_ID) teardown?.() + return + } + const phase = readOrcaCloudAgentAccounts().setups[agent].phase + if (phase !== lastPhase) { + lastPhase = phase + update() } }) teardown = () => { diff --git a/src/renderer/src/lib/orca-cloud/cloud-create-intent.test.ts b/src/renderer/src/lib/orca-cloud/cloud-create-intent.test.ts new file mode 100644 index 00000000000..8536db819c5 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-create-intent.test.ts @@ -0,0 +1,115 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { + cancelCloudCreateIntent, + cloudCreateIdempotencyKey, + consumeCloudCreateIntent, + resetCloudCreateIntentsForTest, + startCloudCreate +} from './cloud-create-intent' +import { + closeCloudSetupPage, + getCloudSetupPageRequest, + openCloudSetupPage +} from './cloud-setup-page-store' + +// One Create press makes exactly one server create, across sign-in, the setup page, its auto-start, +// a reveal, Exit, Back and a re-open (P0, JA-01/PC-8). `create` stands in for the server create. +function press(create: (id: string) => void, setupNeeded: boolean): void { + startCloudCreate({ + setupOpen: getCloudSetupPageRequest() !== null, + setupNeeded, + openSetup: (intentId) => + openCloudSetupPage({ + prompt: 'p', + repoId: 'r', + agent: 'claude', + availability: 'needs-sign-in', + cloudOnlyRepo: null, + composer: {}, + intentId + }), + create + }) +} + +describe('one Create, one server create', () => { + beforeEach(() => { + resetCloudCreateIntentsForTest() + closeCloudSetupPage() + }) + + it('a ready account creates once, and a double press makes two separate intents', () => { + const create = vi.fn() + press(create, false) + expect(create).toHaveBeenCalledTimes(1) + const [intent] = create.mock.calls[0] ?? [] + expect(consumeCloudCreateIntent(intent)).toBe(false) + }) + + it('setup: nothing creates while the page is open; the auto-start creates once', () => { + const create = vi.fn() + press(create, true) + const request = getCloudSetupPageRequest() + expect(request).not.toBeNull() + expect(create).not.toHaveBeenCalled() + // Another press while the page is open (a stale composer, a keyboard repeat) does nothing. + press(create, false) + expect(create).not.toHaveBeenCalled() + // Sign-in lands and the page reopens the hidden composer: the auto-start consumes the intent. + closeCloudSetupPage() + if (consumeCloudCreateIntent(request?.intentId)) { + create(request?.intentId) + } + // The 8 s reveal remounts the composer, and its effect runs again: no second create. + if (consumeCloudCreateIntent(request?.intentId)) { + create(request?.intentId) + } + expect(create).toHaveBeenCalledTimes(1) + }) + + it('Exit or Back cancels the start for real, even after a later sign-in', () => { + const create = vi.fn() + press(create, true) + const request = getCloudSetupPageRequest() + cancelCloudCreateIntent(request?.intentId) + closeCloudSetupPage() + // A later sign-in elsewhere, or a stale auto-start, finds nothing to run. + expect(consumeCloudCreateIntent(request?.intentId)).toBe(false) + expect(create).not.toHaveBeenCalled() + }) + + it('a new Start replaces the old setup, and the old press can never create', () => { + const create = vi.fn() + press(create, true) + const first = getCloudSetupPageRequest() + closeCloudSetupPage() + press(create, true) + const second = getCloudSetupPageRequest() + expect(second?.intentId).not.toBe(first?.intentId) + expect(consumeCloudCreateIntent(second?.intentId)).toBe(true) + expect(create).not.toHaveBeenCalled() + }) +}) + +describe('Idempotency-Key per Create press', () => { + beforeEach(() => { + resetCloudCreateIntentsForTest() + closeCloudSetupPage() + }) + + it('every creation fired by one press sends the same key; an explicit retry gets its own', () => { + const create = vi.fn() + press(create, false) + const [intent] = create.mock.calls[0] ?? [] + expect(intent).toMatch(/^create:[A-Za-z0-9_.:-]{8,120}$/) + expect(cloudCreateIdempotencyKey('creation-1')).toBe(intent) + // A re-fired start (another creation for the same press) dedupes on the server. + expect(cloudCreateIdempotencyKey('creation-2')).toBe(intent) + // Retry of creation-1 after a failure is a new attempt. + expect(cloudCreateIdempotencyKey('creation-1')).toBe(`${intent}:retry-1`) + }) + + it('no armed press, no key', () => { + expect(cloudCreateIdempotencyKey('creation-x')).toBeNull() + }) +}) diff --git a/src/renderer/src/lib/orca-cloud/cloud-create-intent.ts b/src/renderer/src/lib/orca-cloud/cloud-create-intent.ts new file mode 100644 index 00000000000..f7fb4b06be3 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-create-intent.ts @@ -0,0 +1,110 @@ +// One Create press on Orca Cloud is one intent, and one intent makes at most one server create, ever +// (P0, JA-01/PC-8). The intent travels from the composer through the setup page to the hidden +// auto-start; whichever path creates first consumes it, and every later attempt is dropped. Exit, +// Back and Cancel consume it without creating. The id doubles as the create's idempotency key. + +import { createNonSecureContextUuid } from '../../../../shared/non-secure-context-uuid' + +type IntentState = 'pending' | 'consumed' + +const intents = new Map() + +/** `create:`, within the server's Idempotency-Key format (8–128 of [A-Za-z0-9_.:-]). */ +function newIntentId(): string { + return `create:${createNonSecureContextUuid()}` +} + +/** A fresh intent for one Create press. */ +export function beginCloudCreateIntent(): string { + const id = newIntentId() + intents.set(id, 'pending') + return id +} + +/** True exactly once per intent: the caller may create now. Unknown or used intents are refused. */ +export function consumeCloudCreateIntent(id: string | null | undefined): boolean { + if (!id || intents.get(id) !== 'pending') { + return false + } + intents.set(id, 'consumed') + return true +} + +/** Exit, Back or Cancel: the intent can never create. */ +export function cancelCloudCreateIntent(id: string | null | undefined): void { + if (id) { + intents.set(id, 'consumed') + } +} + +export function isCloudCreateIntentPending(id: string | null | undefined): boolean { + return id ? intents.get(id) === 'pending' : false +} + +/** + * The server backstop (create-speed's Idempotency-Key): the intent a create was started with is + * armed for a while, and every creation launched under it sends the same key, so a re-fired start + * gets back the first sandbox instead of a second one. An explicit Retry of the same creation is a + * new attempt and gets its own suffix. + */ +const ARMED_FOR_MS = 10 * 60_000 +let armed: { key: string; at: number } | null = null +const keyByCreation = new Map() + +/** The composer calls this right before it creates with an intent. */ +export function armCloudCreateIdempotency(intentId: string, now: number = Date.now()): void { + armed = { key: intentId, at: now } +} + +/** The key to send for a creation's provision; null with no armed intent. */ +export function cloudCreateIdempotencyKey( + creationId: string, + now: number = Date.now() +): string | null { + const bound = keyByCreation.get(creationId) + if (bound) { + bound.attempts += 1 + return `${bound.key}:retry-${bound.attempts}` + } + if (!armed || now - armed.at > ARMED_FOR_MS) { + return null + } + keyByCreation.set(creationId, { key: armed.key, attempts: 0 }) + return armed.key +} + +/** Tests only. */ +export function resetCloudCreateIntentsForTest(): void { + intents.clear() + armed = null + keyByCreation.clear() +} + +/** + * The composer's primary on Orca Cloud. Never creates while a setup page is open; otherwise starts + * one intent and either hands it to the setup page or creates with it, once. + */ +export function startCloudCreate({ + setupOpen, + setupNeeded, + openSetup, + create +}: { + setupOpen: boolean + setupNeeded: boolean + openSetup: (intentId: string) => void + create: (intentId: string) => void +}): void { + if (setupOpen) { + return + } + const id = beginCloudCreateIntent() + if (setupNeeded) { + openSetup(id) + return + } + if (consumeCloudCreateIntent(id)) { + armCloudCreateIdempotency(id) + create(id) + } +} diff --git a/src/renderer/src/lib/orca-cloud/cloud-setup-page-store.ts b/src/renderer/src/lib/orca-cloud/cloud-setup-page-store.ts index 1a927a81feb..579777be94c 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-setup-page-store.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-setup-page-store.ts @@ -6,6 +6,7 @@ import type { OrcaCloudAvailability } from '../../../../shared/orca-yaml-hook-ty import type { ComposerModalData } from '@/components/new-workspace/composer-modal-data' import type { OrcaCloudRunTargetAccess } from '@/components/new-workspace/orca-cloud-run-target-access' import { e2eConfig } from '@/lib/e2e-config' +import { cancelCloudCreateIntent } from './cloud-create-intent' export type CloudSetupPageRequest = { prompt: string @@ -17,6 +18,8 @@ export type CloudSetupPageRequest = { cloudOnlyRepo: string | null /** The composer as it was: Back and the auto-start reopen it with everything kept. */ composer: ComposerModalData + /** The Create press this setup belongs to: its start uses it once; Exit and Back cancel it. */ + intentId: string /** * Dev and e2e only: pins the account's billing answer so every step can be walked against the * real page (dev sign-in has no billing). Never set by the app. @@ -35,6 +38,10 @@ function emit(): void { } export function openCloudSetupPage(request: Omit): void { + // A newer Start replaces an older setup: the older press can never create. + if (current && current.intentId !== request.intentId) { + cancelCloudCreateIntent(current.intentId) + } current = { ...request, openedAt: Date.now() } emit() } @@ -61,31 +68,6 @@ export function useCloudSetupPageRequest(): CloudSetupPageRequest | null { ) } -const AGENT_SKIP_KEY = 'orca.cloudSetup.agentSkipped.v1' - -/** "Skip for now" on the agent step is remembered, so a ready account isn't asked on every Start. */ -export function isCloudSetupAgentSkipped(agent: string | null): boolean { - if (!agent || typeof localStorage === 'undefined') { - return false - } - try { - return localStorage.getItem(`${AGENT_SKIP_KEY}:${agent}`) === '1' - } catch { - return false - } -} - -export function rememberCloudSetupAgentSkipped(agent: string | null): void { - if (!agent || typeof localStorage === 'undefined') { - return - } - try { - localStorage.setItem(`${AGENT_SKIP_KEY}:${agent}`, '1') - } catch { - // Private mode: the step asks again next time. - } -} - // Dev and e2e: drive the page from the console or CDP (as `__store` is), e.g. to walk the trial step. if ((import.meta.env.DEV || e2eConfig.exposeStore) && typeof window !== 'undefined') { Object.assign(window, { From 7857c54b05c47d29a5e77fd4cce37aad17c0798a Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:26:02 -0800 Subject: [PATCH 076/149] test(cloud): toast test without casts --- .../lib/orca-cloud/cloud-agent-not-started-toast.test.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.test.ts b/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.test.ts index 8352e50e713..d5d634403c9 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.test.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.test.ts @@ -83,7 +83,13 @@ describe('cloud agent not-started toast', () => { it('"Set up Claude once" starts the sign-in right from the toast, which stays up', () => { const start = vi.fn(async () => undefined) Object.assign(window, { - api: { ...(window as { api?: object }).api, orcaCloudAgents: { start } } + api: { + orcaCloudAgents: { + start, + setups: vi.fn(async () => ({ claude: { phase: 'idle' }, codex: { phase: 'idle' } })), + onSetupChanged: vi.fn(() => () => undefined) + } + } }) showCloudAgentNotStartedToast('claude', 'w') const options: { From 48b51db33511c7d7bd27b0a3b7a9c3a217a6a4d4 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:27:04 -0800 Subject: [PATCH 077/149] fix(cloud-routines): Run now no longer reports invalid-response for a started run The control plane sends a run's triggerDetail as an object ({requestedBy}, {event, target}, {scheduledFor}); the desktop schema wanted a string, so POST /run and run history failed to parse although the run had started, inviting a duplicate run. Accept the object and show one short label. --- src/main/cloud-api/cloud-api-client.test.ts | 43 +++++++++++++++++++ .../cloud-api/cloud-api-routine-types.ts | 26 ++++++++++- 2 files changed, 67 insertions(+), 2 deletions(-) diff --git a/src/main/cloud-api/cloud-api-client.test.ts b/src/main/cloud-api/cloud-api-client.test.ts index 3097e205518..6cae58ad6fb 100644 --- a/src/main/cloud-api/cloud-api-client.test.ts +++ b/src/main/cloud-api/cloud-api-client.test.ts @@ -195,6 +195,49 @@ describe('response hardening', () => { expect(parsed.result?.prUrl).toBeUndefined() expect(parsed.status).toBe('succeeded') }) + + it('accepts the run the control plane answers Run now with (object trigger detail)', async () => { + // Exactly what POST /v1/routines/:id/run returns (routines/store.ts runView, private view). + const queued = { + id: 'run_9', + routineId: 'rt_1', + trigger: 'manual', + triggerDetail: { requestedBy: 'usr_1' }, + status: 'queued', + workspaceId: null, + result: null, + error: null, + createdAt: 5, + startedAt: null, + finishedAt: null, + durationMs: null + } + const fetchImpl = vi.fn(async () => respond(202, { run: queued })) + const { run } = await client(fetchImpl).runRoutine('rt_1') + expect(run).toMatchObject({ id: 'run_9', status: 'queued', triggerDetail: null }) + + const github = { + ...queued, + trigger: 'github', + triggerDetail: { + event: 'pull_request.labeled', + delivery: 'd1', + target: { repo: 'acme/web', number: 482, kind: 'pull_request' }, + context: { anything: true } + } + } + const page = vi.fn(async () => + respond(200, { + runs: [github, { ...queued, triggerDetail: 'POST from ci' }], + nextBefore: null + }) + ) + const { runs } = await client(page).listRoutineRuns('rt_1') + expect(runs.map((r) => r.triggerDetail)).toEqual([ + 'acme/web#482 pull_request.labeled', + 'POST from ci' + ]) + }) }) describe('classifyCloudApiResponse', () => { diff --git a/src/shared/cloud-api/cloud-api-routine-types.ts b/src/shared/cloud-api/cloud-api-routine-types.ts index 39f8109580b..d77aafc2782 100644 --- a/src/shared/cloud-api/cloud-api-routine-types.ts +++ b/src/shared/cloud-api/cloud-api-routine-types.ts @@ -1,7 +1,7 @@ // Orca Cloud routines: /v1/routines wire shapes and the editor's request bodies. import { z } from 'zod' import { ORCA_CLOUD_IMAGE_AGENTS } from '../hosted-sandbox/orca-cloud-image-agents' -import { HttpsUrl, Id, Millis, PersonName, ShortText } from './cloud-api-primitives' +import { HttpsUrl, Id, Millis, PersonName } from './cloud-api-primitives' // ── Routines ──────────────────────────────────────────────────────────────── @@ -115,11 +115,33 @@ export const RoutineCreatedSchema = z.object({ export type RoutineCreated = z.infer export const RoutineWebhookSchema = z.object({ url: HttpsUrl }) +const TriggerTarget = z.object({ repo: z.string().max(200), number: z.number().int() }) +const TriggerDetailObject = z.object({ + event: z.string().max(100).optional(), + target: TriggerTarget.optional().catch(undefined) +}) + +/** "acme/web#482 pull_request.labeled" for GitHub runs; null when there is nothing worth showing. */ +export function triggerLabel(detail: unknown): string | null { + if (typeof detail === 'string') { + return detail.slice(0, 500) || null + } + const parsed = TriggerDetailObject.safeParse(detail) + if (!parsed.success) { + return null + } + const { event, target } = parsed.data + const where = target ? `${target.repo}#${target.number}` : null + return [where, event].filter(Boolean).join(' ') || null +} + export const RoutineRunSchema = z.object({ id: Id, routineId: Id, trigger: z.enum(ROUTINE_RUN_TRIGGERS), - triggerDetail: ShortText.nullable(), + // The control plane sends what fired the run as an object ({requestedBy} for manual runs, + // {event, target} for GitHub, {scheduledFor} for schedules); the UI shows one short label. + triggerDetail: z.unknown().transform(triggerLabel), status: z.enum(ROUTINE_RUN_STATUSES), workspaceId: Id.nullable(), result: z From 7d3a8140d4d352de762ca8242aea89f194b2cd96 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:27:22 -0800 Subject: [PATCH 078/149] chore(billing): JA-18 localization catalog and lint fixes --- .../billing/PlanBillingUsage.test.tsx | 6 ++- .../src/i18n/en-runtime-required.json | 12 +++++- src/renderer/src/i18n/locales/en.json | 43 +++++++++++++++---- 3 files changed, 51 insertions(+), 10 deletions(-) diff --git a/src/renderer/src/components/billing/PlanBillingUsage.test.tsx b/src/renderer/src/components/billing/PlanBillingUsage.test.tsx index 19293abef85..31f0aa5e1ac 100644 --- a/src/renderer/src/components/billing/PlanBillingUsage.test.tsx +++ b/src/renderer/src/components/billing/PlanBillingUsage.test.tsx @@ -16,7 +16,11 @@ const overageOn: OrcaBillingEntitlement = { } function capField(): HTMLInputElement { - return screen.getByLabelText('Monthly spend cap') as HTMLInputElement + const field = screen.getByLabelText('Monthly spend cap') + if (!(field instanceof HTMLInputElement)) { + throw new Error('the spend cap is not an input') + } + return field } describe('spend cap field', () => { diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 5a71a0907a4..1da04ca5f20 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -254,7 +254,17 @@ "trialHoursLeft_one": "Trial · {{count}} sandbox hour left", "trialHoursLeft_other": "Trial · {{count}} sandbox hours left", "trialHoursUsed_one": "{{used}} of {{count}} sandbox hour used", - "trialHoursUsed_other": "{{used}} of {{count}} sandbox hours used" + "trialHoursUsed_other": "{{used}} of {{count}} sandbox hours used", + "usage": { + "otherMembers_one": "{{count}} other", + "otherMembers_other": "{{count}} others", + "otherWorkspaces_one": "{{count}} other workspace", + "otherWorkspaces_other": "{{count}} other workspaces", + "total_one": "{{value}} sandbox hour", + "total_other": "{{value}} sandbox hours", + "windowTotal_one": "{{value}} sandbox hour in 30 days", + "windowTotal_other": "{{value}} sandbox hours in 30 days" + } }, "browser-pane": { "markup": { diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index ec448c98c22..c8f7938e49f 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -20550,7 +20550,6 @@ "renewsOn": "Renews {{value0}}", "continueInBrowser": "Continue in your browser. This updates when you come back.", "title": "Plan & billing", - "refresh": "Refresh plan", "menuItem": "Plan & billing", "statusActive": "Active", "statusTrial": "Trial", @@ -20560,7 +20559,6 @@ "overageNoPlan": "Overage needs an active plan.", "resets": "Hours reset {{value0}}", "overageTitle": "Overage", - "overageToggle": "Allow overage", "overageSpent": "{{value0}} of {{value1}} monthly cap spent", "saveCap": "Save", "monthly": "Monthly", @@ -20817,10 +20815,6 @@ "openForbidden2": "Only an owner or admin can manage billing.", "openTeamRequired": "Plans belong to a team. Create a team, then choose a plan.", "openSignedOut2": "Sign in to Orca again to manage your team.", - "overageDescription7": "Optional overage at {{rate}} per sandbox hour, billed by the minute, up to a monthly spend cap you set ({{cap}} by default).", - "overageMemberHint": "Owners and admins can change overage.", - "overageOffRead": "Off", - "overageOnRead": "On", "overagePaymentFailed": "Update the payment method before changing overage.", "paymentAsleepBody": "New sandboxes can’t start and running sandboxes are asleep. They can wake again once the payment goes through. Your files are safe.", "paymentGraceBody2": "New sandboxes can’t start. Running sandboxes go to sleep on {{value0}} unless the payment goes through.", @@ -20833,7 +20827,6 @@ "resetsEnds": "Hours reset {{value0}} · Plan ends {{value1}}", "resetsRenews": "Hours reset {{value0}} · Renews {{value1}}", "sandboxHoursUsedMonth": "{{value0}} of {{value1}} sandbox hours used this month", - "overageDescriptionOn4": "Optional overage at {{rate}} per sandbox hour, billed by the minute, up to a monthly spend cap you set.", "reasonCapMember4": "Spend cap reached. Running sandboxes go to sleep and new ones can’t start. Nothing is deleted, and your files are safe. Ask an owner or admin to raise the spend cap.", "reasonGraceExpired3": "Payment failed. New sandboxes can’t start and running sandboxes are asleep. Update your payment method. Your files are safe.", "reasonGraceExpiredMember2": "Payment failed. New sandboxes can’t start and running sandboxes are asleep. Ask an owner or admin to update the payment method. Your files are safe.", @@ -20868,7 +20861,41 @@ "trialProduct": "Orca Cloud", "trialRowChoosePlan": "{{trial}}. Choose plan", "trialUsedUpTitle": "Your trial is used up", - "unconfigured": "Billing isn’t available in this build of Orca." + "unconfigured": "Billing isn’t available in this build of Orca.", + "teamPlanTitle": "{{team}} · {{plan}} plan", + "planTitle": "{{plan}} plan", + "overage": { + "capHint": "{{rate}} per sandbox hour after your included hours, billed by the minute. $0 keeps overage off.", + "memberOn": "On, up to {{cap}} a month.", + "memberOff2": "Off. Ask an owner or admin to turn it on.", + "turnOn": "Turn on with a {{cap}} cap" + }, + "usage": { + "title": "Last 30 days", + "loadFailed": "Couldn’t load your usage history", + "loading": "Loading your usage history…", + "empty": "No sandbox hours yet. Usage shows here once your team runs cloud workspaces.", + "topWorkspaces": "Top workspaces", + "topMembers": "Top members", + "hoursColumn": "Sandbox hours", + "chartLabel": "Sandbox hours per day, last 30 days. Use the arrow keys to read each day.", + "today": "Today", + "tableCaption": "Sandbox hours per day", + "you": "You", + "formerMember": "Former member", + "otherMembers_one": "{{count}} other", + "otherMembers_other": "{{count}} others", + "unattributed": "Not attributed to a member", + "deletedWorkspace": "Deleted workspace", + "otherWorkspaces_one": "{{count}} other workspace", + "otherWorkspaces_other": "{{count}} other workspaces", + "windowTotal_one": "{{value}} sandbox hour in 30 days", + "windowTotal_other": "{{value}} sandbox hours in 30 days", + "total_one": "{{value}} sandbox hour", + "total_other": "{{value}} sandbox hours", + "yours": "You used {{yours}} of your team’s {{total}} sandbox hours.", + "dayLine": "{{date}} · {{hours}}" + } }, "ports": { "RuntimePortAutoForwarder": { From 27c2dbcbec6eee3d915f9d1201d892cee8ad68c8 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:28:47 -0800 Subject: [PATCH 079/149] feat(cloud): env-check follow-up: no blank before the terminal, no setup nudge in cloud, notices bottom-right, one title on failure cards, Couldn't open row --- .../src/app-shell/AppWorkspaceShell.tsx | 4 + .../orca-cloud/CloudSetupNotices.tsx | 14 ++- .../orca-cloud/OrcaCloudWorkspaceSurface.tsx | 9 +- .../sidebar/SetupScriptPromptCard.tsx | 12 ++ .../worktree-creation/CloudOpenCoverBody.tsx | 44 +++++++ .../worktree-creation/CloudOpenCoverLayer.tsx | 80 +++++++++++++ .../worktree-creation/VmBuildSheet.tsx | 89 +++++++------- .../WorktreeCreationPanel.tsx | 8 ++ src/renderer/src/i18n/locales/en.json | 4 +- .../ephemeral-vm-worktree-creation.test.ts | 113 ++++++++++++++++++ .../orca-cloud/cloud-open-cover-store.test.ts | 36 ++++++ .../lib/orca-cloud/cloud-open-cover-store.ts | 73 +++++++++++ .../creation/pending-worktree-creation.ts | 6 + .../creation/worktree-creation-completion.ts | 11 ++ 14 files changed, 453 insertions(+), 50 deletions(-) create mode 100644 src/renderer/src/components/worktree-creation/CloudOpenCoverBody.tsx create mode 100644 src/renderer/src/components/worktree-creation/CloudOpenCoverLayer.tsx create mode 100644 src/renderer/src/lib/ephemeral-vm-worktree-creation.test.ts create mode 100644 src/renderer/src/lib/orca-cloud/cloud-open-cover-store.test.ts create mode 100644 src/renderer/src/lib/orca-cloud/cloud-open-cover-store.ts diff --git a/src/renderer/src/app-shell/AppWorkspaceShell.tsx b/src/renderer/src/app-shell/AppWorkspaceShell.tsx index cddedd2a414..3b58c35221f 100644 --- a/src/renderer/src/app-shell/AppWorkspaceShell.tsx +++ b/src/renderer/src/app-shell/AppWorkspaceShell.tsx @@ -11,6 +11,7 @@ import { FloatingTerminalToggleButton } from '../components/floating-terminal/Fl import { TerminalWorkbenchContainer } from '../components/TerminalWorkbenchContainer' import { WorkspaceLowDiskBanner } from '../components/low-disk/WorkspaceLowDiskBanner' import { CloudSetupPageLayer } from '../components/orca-cloud-setup/CloudSetupPageLayer' +import { CloudOpenCoverLayer } from '../components/worktree-creation/CloudOpenCoverLayer' import type { VirtualizedScrollAnchor } from '../hooks/useVirtualizedScrollAnchor' import { TitlebarLeftControls } from './TitlebarLeftControls' import { RightSidebarToggle, TitlebarMainStrip } from './TitlebarMainStrip' @@ -248,6 +249,9 @@ export function AppWorkspaceShell(props: {
    + {floatingWorkspace.showToggleButton && !capturingPluginShot ? ( + +
    + ) +} + export function CloudSetupNoticesView({ record, notices, @@ -207,7 +219,7 @@ export function CloudSetupNoticesView({ role="status" aria-labelledby={labelId} data-cloud-notice="setup" - className="pointer-events-auto w-[26rem] max-w-[calc(100%-1.5rem)] rounded-lg border border-border bg-card text-card-foreground shadow-[0_8px_24px_rgba(0,0,0,0.12)] dark:shadow-[0_8px_24px_rgba(0,0,0,0.4)] motion-safe:animate-in motion-safe:fade-in-0 motion-safe:slide-in-from-top-1" + className="pointer-events-auto w-[26rem] max-w-[calc(100%-1.5rem)] rounded-lg border border-border bg-card text-card-foreground shadow-[0_8px_24px_rgba(0,0,0,0.12)] dark:shadow-[0_8px_24px_rgba(0,0,0,0.4)] motion-safe:animate-in motion-safe:fade-in-0 motion-safe:slide-in-from-bottom-1" >

    {t('orcaCloud.setupNotices.label', 'Workspace setup')} diff --git a/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx b/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx index f2223d64523..6d86e12acc1 100644 --- a/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx +++ b/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx @@ -22,7 +22,7 @@ import type { CloudWakeProgressEvent } from '../../../../shared/hosted-sandbox/c import { CloudArchivedWorkspaceView, type ArchiveLoad } from './CloudArchivedWorkspaceView' import { CloudWakingOverlay } from './CloudWakingOverlay' import { CloudWorkspaceNotice } from './CloudWorkspaceNotice' -import { CloudSetupNotices } from './CloudSetupNotices' +import { CloudSetupNoticesDock } from './CloudSetupNotices' import { useConfirmedRestart } from './use-cloud-panel-actions' import { useCloudVersionSkewNotice } from './use-cloud-version-skew-notice' import { CloudWorkspaceOfflineView } from './offline/CloudWorkspaceOfflineView' @@ -339,10 +339,8 @@ function CloudSurface({ workspaceId }: { workspaceId: string }): React.JSX.Eleme if (layer === null && versionSkewNotice) { notices.push(versionSkewNotice) } - if (layer === null && view.state !== 'sleeping' && view.state !== 'archived') { - // What the environment check found that didn't need to stop the create (env-check-ux). - notices.push() - } + // What the environment check found that didn't need to stop the create (env-check-ux). + const showSetupNotices = layer === null && view.state !== 'sleeping' && view.state !== 'archived' if (layer === null && view.oom) { notices.push( ) : null} + {showSetupNotices ? : null} {notices.length > 0 ? (
    {} + +/** The creation panel's last frame, laid out exactly like WorktreeCreationPanel. */ +export default function CloudOpenCoverBody({ + cover, + now, + reserveCollapsedSidebarHeaderSpace +}: { + cover: CloudOpenCover + now: number + reserveCollapsedSidebarHeaderSpace: boolean +}): React.JSX.Element { + const { entry } = cover + return ( +
    + + {/* A picture of the last frame: nothing in it is interactive. */} +
    + +
    +
    + ) +} diff --git a/src/renderer/src/components/worktree-creation/CloudOpenCoverLayer.tsx b/src/renderer/src/components/worktree-creation/CloudOpenCoverLayer.tsx new file mode 100644 index 00000000000..5d8808e91d8 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/CloudOpenCoverLayer.tsx @@ -0,0 +1,80 @@ +import React, { useEffect, useSyncExternalStore } from 'react' +import { useAppStore } from '@/store' +import { useNow } from '@/hooks/use-now' +import { + CLOUD_OPEN_COVER_MAX_MS, + releaseCloudOpenCover, + useCloudOpenCover, + workspaceHasAttachedPty +} from '@/lib/orca-cloud/cloud-open-cover-store' +import type CloudOpenCoverBodyComponent from './CloudOpenCoverBody' + +// The body pulls in the build sheet, which the shell must not load at boot. The creation panel +// preloads it, so it is ready (no Suspense frame) by the time a create hands over. +let Body: typeof CloudOpenCoverBodyComponent | null = null +let loading: Promise | null = null +const bodyListeners = new Set<() => void>() + +export function preloadCloudOpenCover(): Promise { + loading ??= import('./CloudOpenCoverBody') + .then((module) => { + Body = module.default + for (const listener of bodyListeners) { + listener() + } + }) + .catch(() => { + loading = null + }) + return loading +} + +function useBody(): typeof CloudOpenCoverBodyComponent | null { + return useSyncExternalStore( + (listener) => { + bodyListeners.add(listener) + return () => bodyListeners.delete(listener) + }, + () => Body + ) +} + +/** + * Keeps the Orca Cloud start screen over a just-created workspace until its terminal's PTY is + * attached (JA-12), so "Open workspace" goes straight to a live prompt with no blank pane between. + */ +export function CloudOpenCoverLayer({ + reserveCollapsedSidebarHeaderSpace +}: { + reserveCollapsedSidebarHeaderSpace: boolean +}): React.JSX.Element | null { + const worktreeId = useAppStore((s) => (s.activeView === 'terminal' ? s.activeWorktreeId : null)) + const cover = useCloudOpenCover(worktreeId) + const attached = useAppStore((s) => + cover ? workspaceHasAttachedPty(s, cover.worktreeId) : false + ) + const BodyComponent = useBody() + const now = useNow(1_000, cover !== null) + useEffect(() => { + if (!cover) { + return + } + if (attached) { + releaseCloudOpenCover(cover.worktreeId) + return + } + void preloadCloudOpenCover() + const left = Math.max(0, cover.heldAt + CLOUD_OPEN_COVER_MAX_MS - Date.now()) + const timer = window.setTimeout(() => releaseCloudOpenCover(cover.worktreeId), left) + return () => window.clearTimeout(timer) + }, [attached, cover]) + if (!cover || attached || !BodyComponent) { + return null + } + // The body is a module-level component loaded once, not one made during render. + return React.createElement(BodyComponent, { + cover, + now: Math.max(now, cover.heldAt), + reserveCollapsedSidebarHeaderSpace + }) +} diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx index e30da2a0085..4efc743720e 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx @@ -187,51 +187,54 @@ export function VmBuildSheet({ return (
    -
    -
    - - {building ? ( - - ) : state === 'ready' ? ( - - ) : gated ? ( - - ) : ( - + {/* JA-24: on Orca Cloud a failure card carries the one title; no page title above it. */} + {cloud && failure ? null : ( +
    +
    + + {building ? ( + + ) : state === 'ready' ? ( + + ) : gated ? ( + + ) : ( + + )} + + {/* Retry lands focus here once the failure card collapses. The card announces failures. */} +

    + {headerTitle(state, cloud, t, failure?.kind === 'create')} +

    + {/* Orca Cloud: each step carries its own timer, so the header has none. */} + {gated || cloud ? null : ( + {elapsedLabel} )} - - {/* Retry lands focus here once the failure card collapses. The card announces failures. */} -

    - {headerTitle(state, cloud, t, failure?.kind === 'create')} -

    - {/* Orca Cloud: each step carries its own timer, so the header has none. */} - {gated || cloud ? null : ( - {elapsedLabel} - )} +
    + {building ? ( + + ) : null}
    - {building ? ( - - ) : null} -
    + )}
    {/* An account refusal happens before anything starts, so there are no steps to show. */} diff --git a/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx b/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx index e5770626f92..056300b2d23 100644 --- a/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx +++ b/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx @@ -16,6 +16,7 @@ import { } from './worktree-creation-clock' import { VmBuildSheet } from './VmBuildSheet' import { VmDeleteConfirmDialog } from './VmDeleteConfirmDialog' +import { preloadCloudOpenCover } from './CloudOpenCoverLayer' import { composerDataFromRefusedCreate } from './vm-build-composer-return' /** Debounced in-frame creation placeholder: tab strip names the workspace while body shows status, enabling same-frame handoff without duplicating labels. */ @@ -35,6 +36,13 @@ export default function WorktreeCreationPanel({ const now = useWorktreeCreationClock( entry?.status === 'creating' && entry.waitingSince === undefined ) + const cloudCreate = entry?.request.ephemeralVmRecipe?.provider === 'orca-cloud' + React.useEffect(() => { + // The open cover takes over from this panel when the create finishes (JA-12). + if (cloudCreate) { + void preloadCloudOpenCover() + } + }, [cloudCreate]) if (!entry) { return null } diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 0d1e058e6ce..c7b3c5dba1a 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -2290,7 +2290,9 @@ "preparingCloudEnvironment": "Preparing environment…", "startingSandbox": "Starting sandbox…", "cloningRepository": "Cloning the repository…", - "updatingRepository": "Updating the repository…" + "updatingRepository": "Updating the repository…", + "cloudBlockedAsleep": "Asleep", + "cloudCouldNotOpen": "Couldn’t open" }, "duplicatePairedServers": { "ambiguousSameServer": "{{value0}} and {{value1}} are the same server paired twice. Remove one in Settings > Remote Orca Servers." diff --git a/src/renderer/src/lib/ephemeral-vm-worktree-creation.test.ts b/src/renderer/src/lib/ephemeral-vm-worktree-creation.test.ts new file mode 100644 index 00000000000..f94f1ffff1e --- /dev/null +++ b/src/renderer/src/lib/ephemeral-vm-worktree-creation.test.ts @@ -0,0 +1,113 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +// JA-01 tail: Delete sandbox on a create stopped by its environment check must delete THAT sandbox +// (its runtime, hence its control-plane record), and the restart path must delete it before retrying. + +const { state, gate, cleanup, retry } = vi.hoisted(() => { + const entries: Record> = {} + return { + state: { + entries, + repos: [ + { + id: 'repo-src', + displayName: 'Hello-World', + gitRemoteIdentity: { remoteUrl: 'https://github.com/octocat/Hello-World.git' } + } + ] + }, + gate: vi.fn(), + cleanup: vi.fn(async () => true), + retry: vi.fn() + } +}) + +vi.mock('@/store', () => ({ + useAppStore: { + getState: () => ({ + pendingWorktreeCreations: state.entries, + repos: state.repos, + projects: [], + activePendingCreationId: 'c1', + updatePendingWorktreeCreation: (id: string, patch: Record) => { + if (state.entries[id]) { + Object.assign(state.entries[id], patch) + } + }, + setRuntimeEnvironments: vi.fn(), + setupProjectExistingFolder: vi.fn(), + deleteProjectHostSetup: vi.fn() + }) + } +})) +vi.mock('sonner', () => ({ toast: { error: vi.fn(), warning: vi.fn() } })) +vi.mock('@/lib/ephemeral-vm-environment-check', () => ({ gateVmCreateOnEnvironmentCheck: gate })) +vi.mock('@/lib/ephemeral-vm-failed-create-cleanup', () => ({ + cleanupFailedEphemeralVmWorkspace: cleanup +})) +vi.mock('@/lib/vm-create-hidden-checkouts', () => ({ + hideVmCreateCheckout: vi.fn(), + settleVmCreateCheckoutAfterCleanup: vi.fn() +})) +vi.mock('@/lib/workspace/creation/worktree-creation-flow', () => ({ + retryBackgroundWorktreeCreation: retry +})) +vi.mock('@/lib/ephemeral-vm-workspace-target', () => ({ + prepareEphemeralVmWorkspaceTarget: vi.fn(async () => ({ + ok: true, + setup: { + repo: { id: 'repo-vm', path: '/vercel/orca/workspaces/Hello-World/project' }, + setup: { id: 'setup-1', projectId: 'p1', hostId: 'runtime:env-1' } + }, + runtimeId: 'rt-blocked', + checkoutMode: 'provisioned-root', + environmentId: 'env-1', + stderr: '', + warnings: [] + })) +})) + +import { prepareRequestForCreate } from './ephemeral-vm-worktree-creation' +import type { WorktreeCreationRequest } from '@/lib/workspace/creation/pending-worktree-creation' + +// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the create path reads only these fields. +const request = { + name: 'elephantfish', + setupDecision: 'inherit', + ephemeralVmRecipe: { + sourceRepoId: 'repo-src', + recipeId: 'cloud', + projectId: 'p1', + checkoutMode: 'provisioned-root', + provider: 'orca-cloud' + } +} as unknown as WorktreeCreationRequest + +describe('prepareRequestForCreate on a create stopped by its environment check', () => { + beforeEach(() => { + state.entries.c1 = { request } + vi.stubGlobal('window', { + api: { ephemeralVm: {}, runtimeEnvironments: { list: async () => [] } } + }) + }) + afterEach(() => { + vi.unstubAllGlobals() + vi.clearAllMocks() + }) + + it('Delete sandbox removes that very sandbox and creates nothing', async () => { + gate.mockResolvedValue('stop') + await expect(prepareRequestForCreate('c1', request)).resolves.toBeNull() + expect(cleanup).toHaveBeenCalledOnce() + expect(cleanup.mock.calls[0][0]).toMatchObject({ ephemeralVmRuntimeId: 'rt-blocked' }) + expect(retry).not.toHaveBeenCalled() + }) + + it('Start again deletes the blocked sandbox before starting a new one', async () => { + gate.mockResolvedValue('restart') + await expect(prepareRequestForCreate('c1', request)).resolves.toBeNull() + expect(cleanup.mock.calls[0][0]).toMatchObject({ ephemeralVmRuntimeId: 'rt-blocked' }) + expect(retry).toHaveBeenCalledWith('c1') + expect(cleanup.mock.invocationCallOrder[0]).toBeLessThan(retry.mock.invocationCallOrder[0]) + }) +}) diff --git a/src/renderer/src/lib/orca-cloud/cloud-open-cover-store.test.ts b/src/renderer/src/lib/orca-cloud/cloud-open-cover-store.test.ts new file mode 100644 index 00000000000..83b6cac5ee9 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-open-cover-store.test.ts @@ -0,0 +1,36 @@ +import { afterEach, describe, expect, it } from 'vitest' +import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation' +import { + getCloudOpenCover, + holdCloudOpenCover, + releaseCloudOpenCover, + resetCloudOpenCovers, + workspaceHasAttachedPty +} from './cloud-open-cover-store' + +// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the store only keeps the entry. +const entry = { creationId: 'c1' } as PendingWorktreeCreation + +afterEach(resetCloudOpenCovers) + +describe('cloud open cover', () => { + it('holds the start screen for one workspace until released', () => { + holdCloudOpenCover('w1', entry, 1_000) + expect(getCloudOpenCover('w1')).toMatchObject({ worktreeId: 'w1', heldAt: 1_000 }) + expect(getCloudOpenCover('w2')).toBeNull() + releaseCloudOpenCover('w1') + expect(getCloudOpenCover('w1')).toBeNull() + }) + + it('counts the workspace as open only once one of its terminals has a PTY', () => { + const state = { + tabsByWorktree: { w1: [{ id: 't1' }, { id: 't2' }] }, + ptyIdsByTabId: { t1: [] as string[] } + } + expect(workspaceHasAttachedPty(state, 'w1')).toBe(false) + expect( + workspaceHasAttachedPty({ ...state, ptyIdsByTabId: { t1: [], t2: ['pty-1'] } }, 'w1') + ).toBe(true) + expect(workspaceHasAttachedPty(state, 'missing')).toBe(false) + }) +}) diff --git a/src/renderer/src/lib/orca-cloud/cloud-open-cover-store.ts b/src/renderer/src/lib/orca-cloud/cloud-open-cover-store.ts new file mode 100644 index 00000000000..d170d38e3e1 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-open-cover-store.ts @@ -0,0 +1,73 @@ +// JA-12: a just-created Orca Cloud workspace showed a blank pane for ~1 s between the start screen +// and its terminal (the create finishes, then the terminal's PTY attaches over the network). The +// start screen's last frame stays up over the new workspace until its PTY is attached, or a cap. +import { useSyncExternalStore } from 'react' +import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation' + +/** Never cover longer than this: a terminal that is slow to attach shows its own state. */ +export const CLOUD_OPEN_COVER_MAX_MS = 6_000 + +export type CloudOpenCover = { + worktreeId: string + /** The start screen as it was when the create finished ("Open workspace" running). */ + entry: PendingWorktreeCreation + heldAt: number +} + +let covers: Readonly> = {} +const listeners = new Set<() => void>() + +function emit(next: Readonly>): void { + covers = next + for (const listener of listeners) { + listener() + } +} + +export function holdCloudOpenCover( + worktreeId: string, + entry: PendingWorktreeCreation, + now = Date.now() +): void { + emit({ ...covers, [worktreeId]: { worktreeId, entry, heldAt: now } }) +} + +export function releaseCloudOpenCover(worktreeId: string): void { + if (!covers[worktreeId]) { + return + } + const { [worktreeId]: _released, ...rest } = covers + emit(rest) +} + +export function getCloudOpenCover(worktreeId: string | null): CloudOpenCover | null { + return worktreeId ? (covers[worktreeId] ?? null) : null +} + +export function useCloudOpenCover(worktreeId: string | null): CloudOpenCover | null { + return useSyncExternalStore( + (listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, + () => getCloudOpenCover(worktreeId) + ) +} + +/** True once any terminal of the workspace has a PTY attached. */ +export function workspaceHasAttachedPty( + state: { + tabsByWorktree: Readonly> + ptyIdsByTabId: Readonly> + }, + worktreeId: string +): boolean { + return (state.tabsByWorktree[worktreeId] ?? []).some( + (tab) => (state.ptyIdsByTabId[tab.id]?.length ?? 0) > 0 + ) +} + +/** Test seam. */ +export function resetCloudOpenCovers(): void { + emit({}) +} diff --git a/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts b/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts index e0857e3bf00..5bdd5cb0571 100644 --- a/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts +++ b/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts @@ -323,6 +323,12 @@ export function getCreationProgressLabel( } if (entry.phase === 'provisioning-vm') { if (entry.environmentCheck?.status === 'failed') { + // Orca Cloud stops only on an unusable sandbox; the row says what the card says. + if (entry.request.ephemeralVmRecipe?.provider === 'orca-cloud') { + return entry.environmentCheck.sandbox === 'asleep' + ? t('auto.lib.pendingWorktreeCreation.cloudBlockedAsleep', 'Asleep') + : t('auto.lib.pendingWorktreeCreation.cloudCouldNotOpen', 'Couldn’t open') + } return t('auto.lib.pendingWorktreeCreation.vmChecksFailed', 'Environment checks failed') } // Glossary: an Orca Cloud machine is a sandbox; "VM" stays only for bring-your-own recipes. diff --git a/src/renderer/src/lib/workspace/creation/worktree-creation-completion.ts b/src/renderer/src/lib/workspace/creation/worktree-creation-completion.ts index 87579aeeca0..4fb4bf1f71f 100644 --- a/src/renderer/src/lib/workspace/creation/worktree-creation-completion.ts +++ b/src/renderer/src/lib/workspace/creation/worktree-creation-completion.ts @@ -2,6 +2,7 @@ import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-ag import { parseExecutionHostId } from '../../../../../shared/execution-host' import { runtimeEnvironmentIdOrLocalUnlessTwin } from '@/lib/workspace/ownership/worktree-runtime-owner' import { useAppStore } from '@/store/index' +import { holdCloudOpenCover } from '@/lib/orca-cloud/cloud-open-cover-store' import { ensureAgentStartupInTerminal } from '@/lib/new-workspace' import { queueWorkspaceActivationTerminalFocus } from '@/lib/workspace/activation/workspace-activation-terminal-focus' import { seedAgentTabStateAfterWorktreeCreate } from '@/lib/workspace/creation/worktree-creation-agent-seeds' @@ -23,6 +24,16 @@ export async function completeWorktreeCreation(args: { focusOnCompletion: boolean }): Promise { const { request } = args + // Orca Cloud: the start screen stays over the new workspace until its PTY attaches (JA-12). + const pending = useAppStore.getState().pendingWorktreeCreations[args.creationId] + if ( + pending && + args.focusOnCompletion && + !args.structuredLaunchAccepted && + request.ephemeralVmRecipe?.provider === 'orca-cloud' + ) { + holdCloudOpenCover(args.worktreeId, pending) + } // Why: clearing synchronously after activation lets React commit the panel-to-terminal swap in one frame. useAppStore.getState().removePendingWorktreeCreation(args.creationId, { cleanupVm: false }) // Why: an agent the host planned but did not start has no tab to seed and is not the window's to start. From ed46c5e14985d5fac9c63f14bc5473e36246b1c2 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:21:32 -0800 Subject: [PATCH 080/149] fix(cloud): VM hostname is the workspace's name, not the provider's per-boot id (JA-27, hostname half) Terminal prompts read ubuntu@ and changed after every wake. Each start (create and wake) now sets the hostname to the workspace's title (else its repo's name) as a hostname label, plus an /etc/hosts entry, inline before orcad starts: no image change. Verified on a dev VM: hostname ja-hello, 127.0.1.1 ja-hello, no sudo warnings. --- cloud/apps/sandbox-control/src/lifecycle.ts | 3 ++ .../src/sandbox-vm-commands.ts | 38 ++++++++++++++++++- .../sandbox-control/test/create-speed.test.ts | 15 ++++++++ 3 files changed, 54 insertions(+), 2 deletions(-) diff --git a/cloud/apps/sandbox-control/src/lifecycle.ts b/cloud/apps/sandbox-control/src/lifecycle.ts index c2e9ed5032c..7532dda648e 100644 --- a/cloud/apps/sandbox-control/src/lifecycle.ts +++ b/cloud/apps/sandbox-control/src/lifecycle.ts @@ -28,6 +28,7 @@ import { ORCAD_PORT, SHARE_PROXY_PORT, VmCommandError, + workspaceHostname, drainOrcad, runningOrcad, startOrcad, @@ -387,6 +388,8 @@ async function boot( options.timer.time('orcad', async () => startOrcad(deps.provider, state, { sandboxId: row.id, + // The workspace's name, else its repo's: never the provider's per-boot VM id. + hostname: workspaceHostname(row.name ?? (row.repo_url ? parseGitHubRepo(row.repo_url)?.repo : null)), repo: options.repo, // Repos hosted outside github.com get no GitHub credential, not even the placeholder. githubPlaceholder: deps.config.egressProxyUrl && parseGitHubRepo(row.repo_url ?? '') ? githubPlaceholderToken(row) : undefined, diff --git a/cloud/apps/sandbox-control/src/sandbox-vm-commands.ts b/cloud/apps/sandbox-control/src/sandbox-vm-commands.ts index 3e54d4266b6..0cb3c5c5c82 100644 --- a/cloud/apps/sandbox-control/src/sandbox-vm-commands.ts +++ b/cloud/apps/sandbox-control/src/sandbox-vm-commands.ts @@ -49,8 +49,33 @@ export type StartInputs = { prelude?: { script: string; env?: Record } /** This session's share-proxy key (src/share-crypto.ts); the proxy keeps it in memory only. */ shareProxyKey?: string + /** + * The VM's hostname for this boot (workspaceHostname): terminal prompts read `ubuntu@` + * instead of the provider's VM id, which changes on every wake (JA-27). Set before orcad starts, so + * every shell it opens sees it. Best effort: a failure keeps the provider's name. + */ + hostname?: string } +/** A hostname label from a workspace name: lowercase letters, digits and dashes, at most 63 chars. */ +export function workspaceHostname(name: string | null | undefined): string | undefined { + const label = (name ?? '') + .toLowerCase() + .replace(/[^a-z0-9-]+/g, '-') + .replace(/-+/g, '-') + .replace(/^-+/, '') + .slice(0, 63) + .replace(/-+$/, '') + return label.length > 0 ? label : undefined +} + +// Inline per boot, no image change: hostname plus an /etc/hosts entry (sudo would warn without one). +const HOSTNAME_STEP = [ + '{ [ -n "${ORCA_HOSTNAME:-}" ] && sudo -n hostname "$ORCA_HOSTNAME" &&', + '{ grep -q "[[:space:]]$ORCA_HOSTNAME\\$" /etc/hosts || printf "127.0.1.1 %s\\n" "$ORCA_HOSTNAME" | sudo -n tee -a /etc/hosts; }; }', + '>/dev/null 2>&1 || true; unset ORCA_HOSTNAME' +].join(' ') + /** `NAME=` lines, so values with newlines or quotes survive bash intact. */ export function encodeSecretEnv(env: Record): string { return Object.entries(env) @@ -100,6 +125,10 @@ export async function startOrcad( if (inputs.shareProxyKey) { env.ORCA_SHARE_PROXY_KEY = inputs.shareProxyKey } + if (inputs.hostname) { + env.ORCA_HOSTNAME = inputs.hostname + } + const hostnameStep = inputs.hostname ? `${HOSTNAME_STEP}; ` : '' // The prelude rides in an env var (the start script's `env -i` keeps it out of orcad) so one // round trip both prepares the checkout and starts orcad. const result = await provider.runCommand( @@ -108,11 +137,16 @@ export async function startOrcad( ? { command: 'bash', // The prelude never sees the share-proxy or ready keys; only the start script gets them. - args: ['-c', `env -u ORCA_SHARE_PROXY_KEY -u ORCA_READY_KEY bash -c "$ORCA_PRELUDE" 1>&2 || true; unset ORCA_PRELUDE; exec ${START_COMMAND}`], + args: [ + '-c', + `${hostnameStep}env -u ORCA_SHARE_PROXY_KEY -u ORCA_READY_KEY bash -c "$ORCA_PRELUDE" 1>&2 || true; unset ORCA_PRELUDE; exec ${START_COMMAND}` + ], env: { ...env, ...inputs.prelude.env, ORCA_PRELUDE: inputs.prelude.script }, timeoutMs: START_TIMEOUT_MS } - : { command: START_COMMAND, env, timeoutMs: START_TIMEOUT_MS } + : hostnameStep + ? { command: 'bash', args: ['-c', `${hostnameStep}exec ${START_COMMAND}`], env, timeoutMs: START_TIMEOUT_MS } + : { command: START_COMMAND, env, timeoutMs: START_TIMEOUT_MS } ) if (result.exitCode !== 0) { throw new VmCommandError('orcad_start_failed') diff --git a/cloud/apps/sandbox-control/test/create-speed.test.ts b/cloud/apps/sandbox-control/test/create-speed.test.ts index 94e72d4d0be..fb5d963451c 100644 --- a/cloud/apps/sandbox-control/test/create-speed.test.ts +++ b/cloud/apps/sandbox-control/test/create-speed.test.ts @@ -175,3 +175,18 @@ describe('repo-backed create', () => { expect(h.vercel.boxes.size).toBe(0) }) }) + +describe('VM hostname (JA-27)', () => { + it('is the workspace name (else the repo), as a hostname label, set at every start', async () => { + const { workspaceHostname } = await import('../src/sandbox-vm-commands') + expect(workspaceHostname('Fix Login Bug!')).toBe('fix-login-bug') + expect(workspaceHostname('--ja_hello--')).toBe('ja-hello') + expect(workspaceHostname('🙂')).toBeUndefined() + expect(workspaceHostname('a'.repeat(80))).toHaveLength(63) + const h = await createHarness() + await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w1', machineSize: 'standard', title: 'Ja Hello', repo } }) + const start = h.vercel.commands.find((c) => c.command === START_COMMAND)! + expect(start.env.ORCA_HOSTNAME).toBe('ja-hello') + expect(start.args?.[1]).toContain('sudo -n hostname "$ORCA_HOSTNAME"') + }) +}) From bfd50797c383832ce09b65cd6a19e5e0f98c1553 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:07:06 -0800 Subject: [PATCH 081/149] fix(cloud): first-prompt hold says workspace, not worktree, on Orca Cloud creates (JA-25 glossary) --- .../PendingNativeChatCreation.tsx | 28 ++++++++++++++----- src/renderer/src/i18n/locales/en.json | 6 ++++ 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/src/renderer/src/components/worktree-creation/PendingNativeChatCreation.tsx b/src/renderer/src/components/worktree-creation/PendingNativeChatCreation.tsx index 1cb9539469c..825401a4a29 100644 --- a/src/renderer/src/components/worktree-creation/PendingNativeChatCreation.tsx +++ b/src/renderer/src/components/worktree-creation/PendingNativeChatCreation.tsx @@ -29,6 +29,7 @@ import type { NativeChatMessage } from '../../../../shared/native-chat/native-ch import { deriveNativeChatRowContent } from '../../../../shared/native-chat/transcript/native-chat-row-content' import WorktreeCreationTabStrip from './WorktreeCreationTabStrip' import { WorktreeSetupSteps } from './WorktreeSetupSteps' +import { isOrcaCloudBuild } from './vm-build-steps' import { deriveWorktreeSetupSteps } from './worktree-setup-steps' import { useWorktreeCreationClock } from './worktree-creation-clock' import { getRepoMainWorktreeId } from '../../../../shared/worktree/id' @@ -84,6 +85,8 @@ export default function PendingNativeChatCreation({ const handedOff = entry?.chatInputHandedOff === true const heldMessage = entry ? pendingCreationHeldChatMessage(entry) : null const held = heldMessage !== null + // Glossary: cloud copy says workspace, never worktree (JA-25). + const cloud = entry ? isOrcaCloudBuild(entry) : false // Like t3code, progress shows only in the steps card after a send, never above the composer. const now = useWorktreeCreationClock(status === 'creating' && held) const suppressFocus = entry?.request.suppressTerminalFocusOnCompletion === true @@ -96,15 +99,25 @@ export default function PendingNativeChatCreation({ 'Opening chat…' ) : status === 'error' - ? translate( - 'auto.components.worktree.creation.PendingNativeChatCreation.sendBlockedFailed', - 'Retry creating the worktree to send' - ) - : held + ? cloud ? translate( - 'auto.components.worktree.creation.PendingNativeChatCreation.sendBlockedHeld', - 'Sends when the worktree is ready' + 'components.worktreeCreation.pendingNativeChat.sendBlockedFailedCloud', + 'Retry creating the workspace to send' ) + : translate( + 'auto.components.worktree.creation.PendingNativeChatCreation.sendBlockedFailed', + 'Retry creating the worktree to send' + ) + : held + ? cloud + ? translate( + 'components.worktreeCreation.pendingNativeChat.sendBlockedHeldCloud', + 'Sends when the workspace is ready' + ) + : translate( + 'auto.components.worktree.creation.PendingNativeChatCreation.sendBlockedHeld', + 'Sends when the worktree is ready' + ) : undefined return { capturePresentation: () => () => true, @@ -147,6 +160,7 @@ export default function PendingNativeChatCreation({ runtimeEnvironmentId: null } }, [ + cloud, creationId, handedOff, held, diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 3193a98dc26..aa4242fd021 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -23622,6 +23622,12 @@ "cloudWorkspaces": { "emptyMineStartBody": "Start one and it keeps running while your laptop sleeps.", "newCloudWorkspace": "New cloud workspace" + }, + "worktreeCreation": { + "pendingNativeChat": { + "sendBlockedFailedCloud": "Retry creating the workspace to send", + "sendBlockedHeldCloud": "Sends when the workspace is ready" + } } }, "dashboardPopout": { From 01fafa1fe5d3109fab23d6e81464703b353e0f25 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:14:09 -0800 Subject: [PATCH 082/149] test(cloud): glossary string lint for Orca Cloud surfaces (design-squad spec); 'Claude' not 'Claude Code' in MCP sync (JA-25) --- .../cloud-mcp/cloud-mcp-sync-copy.ts | 2 +- .../src/i18n/en-runtime-required.json | 1 + .../orca-cloud/cloud-glossary-allowlist.json | 9 + .../orca-cloud/cloud-glossary-lint.test.ts | 185 ++++++++++++++++++ 4 files changed, 196 insertions(+), 1 deletion(-) create mode 100644 src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist.json create mode 100644 src/renderer/src/lib/orca-cloud/cloud-glossary-lint.test.ts diff --git a/src/renderer/src/components/settings/runtime-environments/cloud-mcp/cloud-mcp-sync-copy.ts b/src/renderer/src/components/settings/runtime-environments/cloud-mcp/cloud-mcp-sync-copy.ts index 3f1fbd77de1..efe62bf195f 100644 --- a/src/renderer/src/components/settings/runtime-environments/cloud-mcp/cloud-mcp-sync-copy.ts +++ b/src/renderer/src/components/settings/runtime-environments/cloud-mcp/cloud-mcp-sync-copy.ts @@ -28,7 +28,7 @@ export function mcpSyncSummary(status: McpSyncStatus, t: Translate = translate): if (status.rows.length === 0) { return t( 'cloudMcpSync.summary.none', - 'None found in Claude Code or Codex on this computer. Servers you add there show up here.' + 'None found in Claude or Codex on this computer. Servers you add there show up here.' ) } if (status.error === 'host-outdated' && status.lastSyncedAt === null) { diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 671c08689c0..501157fa702 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -1525,6 +1525,7 @@ "found": "{{count}} found", "found_one": "{{count}} found", "found_other": "{{count}} found", + "none": "None found in Claude Code or Codex on this computer. Servers you add there show up here.", "notSynced": "{{count}} found, not synced yet", "notSynced_one": "{{count}} found, not synced yet", "notSynced_other": "{{count}} found, not synced yet", diff --git a/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist.json b/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist.json new file mode 100644 index 00000000000..d1541f22e7c --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist.json @@ -0,0 +1,9 @@ +[ + { "path": "src/renderer/src/components/cloud-environment/EnvironmentForm.tsx", "line": 127, "term": "container", "reason": "\"dev container\" is the Dev Containers spec name (an import source), not the sandbox." }, + { "path": "src/renderer/src/components/settings/virtual-machines/runtimes/CloudVmSetupGuide.tsx", "line": 20, "term": "VM", "reason": "BYOC / recipe-VM settings (Custom environments), where the glossary allows VM." }, + { "path": "src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx", "line": 365, "term": "VM", "reason": "Recipe-VM branch; the Orca Cloud branch says \"Delete sandbox\"." }, + { "path": "src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx", "line": 143, "term": "VM", "reason": "Recipe-VM branch; Orca Cloud renders BlockedSandboxHoursNote instead." }, + { "path": "src/renderer/src/components/worktree-creation/VmDeleteConfirmDialog.tsx", "line": 38, "term": "VM", "reason": "Recipe-VM branch; the Orca Cloud branch says \"Delete this sandbox?\"." }, + { "path": "src/renderer/src/components/worktree-creation/VmDeleteConfirmDialog.tsx", "line": 49, "term": "VM", "reason": "Recipe-VM branch; the Orca Cloud branch says the sandbox is deleted." }, + { "path": "src/renderer/src/components/worktree-creation/VmDeleteConfirmDialog.tsx", "line": 63, "term": "VM", "reason": "Recipe-VM branch; the Orca Cloud branch says \"Delete sandbox\"." } +] diff --git a/src/renderer/src/lib/orca-cloud/cloud-glossary-lint.test.ts b/src/renderer/src/lib/orca-cloud/cloud-glossary-lint.test.ts new file mode 100644 index 00000000000..25f028b1897 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-glossary-lint.test.ts @@ -0,0 +1,185 @@ +// Cloud glossary lint (design-squad spec, JA-25): user-visible strings on Orca Cloud surfaces must +// use the glossary's words (.context/cloud/specs/glossary.md). Scans translate()/t() fallbacks, +// i18n plural defaults, JSX text and user-facing JSX attributes; never identifiers or imports. +import { readFileSync } from 'node:fs' +import path from 'node:path' +import ts from 'typescript-api' +import { globSync } from 'glob' +import { describe, expect, it } from 'vitest' +import allowlist from './cloud-glossary-allowlist.json' + +const ROOT = path.resolve(__dirname, '../../../../..') + +const SCOPE = [ + 'src/renderer/src/components/**/{orca-cloud,cloud,billing,hosted-sandbox}*/**/*.{ts,tsx}', + 'src/renderer/src/components/settings/**/{OrcaCloud,Cloud,PlanBilling,AgentAccounts,Accounts}*.tsx', + 'src/renderer/src/components/worktree-creation/Vm*.tsx', + 'src/renderer/src/components/worktree-creation/*Cloud*.tsx', + 'src/renderer/src/lib/*cloud*.ts', + 'mobile/src/**/*{Cloud,cloud}*.tsx' +] +const EXCLUDE = ['**/__tests__/**', '**/*.test.*', '**/*.fixture.tsx', '**/*.stories.tsx'] + +type Rule = { term: string; pattern: RegExp; use: string; row: string } + +const RULES: Rule[] = [ + { term: 'VM', pattern: /\bVMs?\b|virtual machine/i, use: 'sandbox', row: 'The machine' }, + { term: 'worktree', pattern: /\bworktrees?\b/i, use: 'workspace', row: 'Unit of work' }, + { term: 'Claude Code', pattern: /\bClaude Code\b/i, use: 'Claude', row: 'Agent source' }, + { term: 'suspend', pattern: /\bsuspend(ed|s|ing)?\b/i, use: 'asleep / go to sleep', row: 'Lifecycle verbs' }, + { term: 'hibernate', pattern: /\bhibernat/i, use: 'asleep / go to sleep', row: 'Lifecycle verbs' }, + { + term: 'per hour', + pattern: /\/hr\b|\$\d+(\.\d+)?\/hour|(? span.literal.text)].join(' ') + } + return null +} + +/** User-visible strings in one file, with their 1-based lines. */ +export function visibleStrings(file: string, source: string): { line: number; text: string }[] { + const sf = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX) + const out: { line: number; text: string }[] = [] + const push = (node: ts.Node, text: string | null): void => { + if (text && /[A-Za-z]/.test(text)) { + out.push({ line: sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1, text }) + } + } + const visit = (node: ts.Node): void => { + if (ts.isJsxText(node)) { + push(node, node.text.trim()) + } else if (ts.isJsxAttribute(node) && node.initializer) { + const name = node.name.getText(sf) + if (TEXT_ATTRIBUTES.has(name)) { + const init = node.initializer + push( + init, + ts.isJsxExpression(init) && init.expression + ? stringValue(init.expression) + : stringValue(init) + ) + } + } else if (ts.isCallExpression(node)) { + const callee = node.expression + const name = ts.isIdentifier(callee) + ? callee.text + : ts.isPropertyAccessExpression(callee) + ? callee.name.text + : '' + if (TRANSLATE_CALLEES.has(name) && node.arguments.length >= 2) { + push(node.arguments[1], stringValue(node.arguments[1])) + const options = node.arguments[2] + if (options && ts.isObjectLiteralExpression(options)) { + for (const prop of options.properties) { + if ( + ts.isPropertyAssignment(prop) && + /^defaultValue/.test(prop.name.getText(sf).replace(/['"]/g, '')) + ) { + push(prop.initializer, stringValue(prop.initializer)) + } + } + } + } + } + ts.forEachChild(node, visit) + } + visit(sf) + return out +} + +function scopeFiles(): string[] { + return [...new Set(SCOPE.flatMap((g) => globSync(g, { cwd: ROOT, ignore: EXCLUDE })))].sort() +} + +function findHits(): Hit[] { + const hits: Hit[] = [] + for (const file of scopeFiles()) { + const source = readFileSync(path.join(ROOT, file), 'utf8') + for (const { line, text } of visibleStrings(file, source)) { + for (const rule of RULES) { + if (rule.pattern.test(text)) { + hits.push({ file, line, term: rule.term, text, rule }) + } + } + } + } + return hits +} + +const ALLOW = allowlist as AllowEntry[] +const allowKey = (e: { path: string; line: number; term: string }): string => + `${e.path}:${e.line}:${e.term}` + +describe('cloud glossary lint', () => { + const hits = findHits() + + it('scans a real scope', () => { + expect(scopeFiles().length).toBeGreaterThan(20) + }) + + it('every allowlist entry has a reason and still matches a string', () => { + const live = new Set(hits.map((h) => allowKey({ path: h.file, line: h.line, term: h.term }))) + const problems = ALLOW.filter((e) => !e.reason?.trim() || !live.has(allowKey(e))).map( + (e) => `stale or unexplained allowlist entry: ${allowKey(e)}` + ) + expect(problems).toEqual([]) + }) + + it('cloud strings use glossary words', () => { + const allowed = new Set(ALLOW.map(allowKey)) + const failures = hits + .filter((h) => !allowed.has(allowKey({ path: h.file, line: h.line, term: h.term }))) + .map( + (h) => + `cloud glossary: "${h.term}" at ${h.file}:${h.line}; use "${h.rule.use}" (glossary row: ${h.rule.row}). ` + + `Allowlist with a reason only if this string is not shown in Orca Cloud. Text: ${JSON.stringify(h.text.slice(0, 120))}` + ) + expect(failures).toEqual([]) + }) +}) From 6902aba99c9348ac074f36ff4476da8251159079 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:18:22 -0800 Subject: [PATCH 083/149] test(cloud): glossary lint scans every copy literal + vm-*.ts copy tables; Claude not Claude Code in MCP panel; Dev Container; recipe 'VM is running until you choose' (design-squad rulings) --- .../cloud-environment/EnvironmentForm.tsx | 2 +- .../cloud-mcp/CloudMcpSyncPanel.tsx | 3 +- .../worktree-creation/VmBuildFailureCard.tsx | 4 +- .../src/i18n/en-runtime-required.json | 4 + src/renderer/src/i18n/locales/en.json | 3 +- .../orca-cloud/cloud-glossary-allowlist.json | 133 +++++++++++++++++- .../orca-cloud/cloud-glossary-lint.test.ts | 69 ++++++++- 7 files changed, 204 insertions(+), 14 deletions(-) diff --git a/src/renderer/src/components/cloud-environment/EnvironmentForm.tsx b/src/renderer/src/components/cloud-environment/EnvironmentForm.tsx index fc7fb97d2fc..c31b1d202ec 100644 --- a/src/renderer/src/components/cloud-environment/EnvironmentForm.tsx +++ b/src/renderer/src/components/cloud-environment/EnvironmentForm.tsx @@ -124,7 +124,7 @@ export function EnvironmentForm({ {t( 'cloudEnvironment.form.importHint', - 'Reads Conductor and dev container setup from a local project.' + 'Reads Conductor and Dev Container setup from a local project.' )} {importProjects.map((project) => ( diff --git a/src/renderer/src/components/settings/runtime-environments/cloud-mcp/CloudMcpSyncPanel.tsx b/src/renderer/src/components/settings/runtime-environments/cloud-mcp/CloudMcpSyncPanel.tsx index ef2ecb15032..d6ffb508ff8 100644 --- a/src/renderer/src/components/settings/runtime-environments/cloud-mcp/CloudMcpSyncPanel.tsx +++ b/src/renderer/src/components/settings/runtime-environments/cloud-mcp/CloudMcpSyncPanel.tsx @@ -22,7 +22,8 @@ import { mcpSyncTimeLabel } from './cloud-mcp-sync-copy' -const AGENT_LABEL = { claude: 'Claude Code', codex: 'Codex' } as const +// Glossary: the catalog name is "Claude", never "Claude Code". +const AGENT_LABEL = { claude: 'Claude', codex: 'Codex' } as const export type CloudMcpSyncPanelProps = { status: McpSyncStatus diff --git a/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx b/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx index dc7e71887db..68b455047af 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx @@ -133,8 +133,8 @@ export function VmBuildFailureCard({ ) : (

    {t( - 'auto.components.worktree.creation.VmBuildFailureCard.stillRunningLocal', - 'The VM is running and using hours until you choose.' + 'auto.components.worktree.creation.VmBuildFailureCard.stillRunningLocal2', + 'The VM is running until you choose.' )}

    ) diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 501157fa702..181e3d98c3e 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -1357,6 +1357,7 @@ "checksCountTitleVm_other": "The VM is up, but {{count}} environment checks failed", "memberLimitBodyCount_one": "You can run {{count}} sandbox at once. Put it to sleep or delete it, then try again. Nothing was created, and you weren’t charged.", "memberLimitBodyCount_other": "You can run {{count}} sandboxes at once. Put one to sleep or delete it, then try again. Nothing was created, and you weren’t charged.", + "stillRunningLocal": "The VM is running and using hours until you choose.", "teamLimitBodyCount_one": "Your team can run {{count}} sandbox at once ({{value1}} per seat). Put it to sleep or delete it, then try again. Nothing was created, and you weren’t charged.", "teamLimitBodyCount_other": "Your team can run {{count}} sandboxes at once ({{value1}} per seat). Put one to sleep or delete it, then try again. Nothing was created, and you weren’t charged." }, @@ -1513,6 +1514,9 @@ } }, "cloudEnvironment": { + "form": { + "importHint": "Reads Conductor and dev container setup from a local project." + }, "staleness": { "branchMovedInRepo_one": "{{branch}} in {{repo}} is {{count}} commit ahead of build #{{number}}", "branchMovedInRepo_other": "{{branch}} in {{repo}} is {{count}} commits ahead of build #{{number}}", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index aa4242fd021..b1a84bc6961 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -4313,7 +4313,8 @@ "startAgain": "Start again", "cloudUnusableTitle": "This sandbox can’t open your workspace", "cloudUnusableDeletedBody": "The sandbox was deleted. Start again to try a new one.", - "cloudUnusableBody": "Start again on a new sandbox, or delete this one." + "cloudUnusableBody": "Start again on a new sandbox, or delete this one.", + "stillRunningLocal2": "The VM is running until you choose." }, "VmBuildLog": { "jumpToError": "Jump to first error", diff --git a/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist.json b/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist.json index d1541f22e7c..5f7f7951cc3 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist.json +++ b/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist.json @@ -1,9 +1,128 @@ [ - { "path": "src/renderer/src/components/cloud-environment/EnvironmentForm.tsx", "line": 127, "term": "container", "reason": "\"dev container\" is the Dev Containers spec name (an import source), not the sandbox." }, - { "path": "src/renderer/src/components/settings/virtual-machines/runtimes/CloudVmSetupGuide.tsx", "line": 20, "term": "VM", "reason": "BYOC / recipe-VM settings (Custom environments), where the glossary allows VM." }, - { "path": "src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx", "line": 365, "term": "VM", "reason": "Recipe-VM branch; the Orca Cloud branch says \"Delete sandbox\"." }, - { "path": "src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx", "line": 143, "term": "VM", "reason": "Recipe-VM branch; Orca Cloud renders BlockedSandboxHoursNote instead." }, - { "path": "src/renderer/src/components/worktree-creation/VmDeleteConfirmDialog.tsx", "line": 38, "term": "VM", "reason": "Recipe-VM branch; the Orca Cloud branch says \"Delete this sandbox?\"." }, - { "path": "src/renderer/src/components/worktree-creation/VmDeleteConfirmDialog.tsx", "line": 49, "term": "VM", "reason": "Recipe-VM branch; the Orca Cloud branch says the sandbox is deleted." }, - { "path": "src/renderer/src/components/worktree-creation/VmDeleteConfirmDialog.tsx", "line": 63, "term": "VM", "reason": "Recipe-VM branch; the Orca Cloud branch says \"Delete sandbox\"." } + { + "path": "src/renderer/src/components/cloud-environment/EnvironmentForm.tsx", + "line": 127, + "term": "container", + "reason": "Dev Containers spec name" + }, + { + "path": "src/renderer/src/components/settings/virtual-machines/runtimes/CloudVmSetupGuide.tsx", + "line": 20, + "term": "VM", + "reason": "BYOC recipe VMs (experimental), not Orca Cloud" + }, + { + "path": "src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx", + "line": 365, + "term": "VM", + "reason": "recipe-VM branch; cloud branch says sandbox" + }, + { + "path": "src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx", + "line": 143, + "term": "VM", + "reason": "recipe-VM branch; cloud branch says sandbox" + }, + { + "path": "src/renderer/src/components/worktree-creation/VmDeleteConfirmDialog.tsx", + "line": 38, + "term": "VM", + "reason": "recipe-VM branch; cloud branch says sandbox" + }, + { + "path": "src/renderer/src/components/worktree-creation/VmDeleteConfirmDialog.tsx", + "line": 49, + "term": "VM", + "reason": "recipe-VM branch; cloud branch says sandbox" + }, + { + "path": "src/renderer/src/components/worktree-creation/VmDeleteConfirmDialog.tsx", + "line": 63, + "term": "VM", + "reason": "recipe-VM branch; cloud branch says sandbox" + }, + { + "path": "src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts", + "line": 85, + "term": "VM", + "reason": "recipe-VM branch; cloud branch says sandbox" + }, + { + "path": "src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts", + "line": 89, + "term": "VM", + "reason": "recipe-VM branch; cloud branch says sandbox" + }, + { + "path": "src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts", + "line": 92, + "term": "VM", + "reason": "recipe-VM branch; cloud branch says sandbox" + }, + { + "path": "src/renderer/src/components/worktree-creation/vm-build-recipe-failure-copy.ts", + "line": 15, + "term": "VM", + "reason": "recipe-VM branch; cloud branch says sandbox" + }, + { + "path": "src/renderer/src/components/worktree-creation/vm-build-recipe-failure-copy.ts", + "line": 19, + "term": "VM", + "reason": "recipe-VM branch; cloud branch says sandbox" + }, + { + "path": "src/renderer/src/components/worktree-creation/vm-build-recipe-failure-copy.ts", + "line": 25, + "term": "VM", + "reason": "recipe-VM branch; cloud branch says sandbox" + }, + { + "path": "src/renderer/src/components/worktree-creation/vm-build-recipe-failure-copy.ts", + "line": 29, + "term": "VM", + "reason": "recipe-VM branch; cloud branch says sandbox" + }, + { + "path": "src/renderer/src/components/worktree-creation/vm-build-sheet-copy.ts", + "line": 10, + "term": "VM", + "reason": "recipe-VM branch; cloud branch says sandbox" + }, + { + "path": "src/renderer/src/components/worktree-creation/vm-build-sheet-copy.ts", + "line": 69, + "term": "VM", + "reason": "recipe-VM branch; cloud branch says sandbox" + }, + { + "path": "src/renderer/src/components/worktree-creation/vm-build-sheet-copy.ts", + "line": 74, + "term": "VM", + "reason": "recipe-VM branch; cloud branch says sandbox" + }, + { + "path": "src/renderer/src/components/worktree-creation/vm-build-sheet-copy.ts", + "line": 79, + "term": "VM", + "reason": "recipe-VM branch; cloud branch says sandbox" + }, + { + "path": "src/renderer/src/components/worktree-creation/vm-build-sheet-copy.ts", + "line": 84, + "term": "VM", + "reason": "recipe-VM branch; cloud branch says sandbox" + }, + { + "path": "src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.ts", + "line": 13, + "term": "VM", + "reason": "Matcher for older builds' saved terminal errors so they stay hidden; never displayed" + }, + { + "path": "src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.ts", + "line": 14, + "term": "VM", + "reason": "Matcher for older builds' saved terminal errors so they stay hidden; never displayed" + } ] diff --git a/src/renderer/src/lib/orca-cloud/cloud-glossary-lint.test.ts b/src/renderer/src/lib/orca-cloud/cloud-glossary-lint.test.ts index 25f028b1897..f89e041067f 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-glossary-lint.test.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-glossary-lint.test.ts @@ -15,6 +15,8 @@ const SCOPE = [ 'src/renderer/src/components/settings/**/{OrcaCloud,Cloud,PlanBilling,AgentAccounts,Accounts}*.tsx', 'src/renderer/src/components/worktree-creation/Vm*.tsx', 'src/renderer/src/components/worktree-creation/*Cloud*.tsx', + // Copy tables behind the Vm* components (design-squad scope fix). + 'src/renderer/src/components/worktree-creation/vm-*.ts', 'src/renderer/src/lib/*cloud*.ts', 'mobile/src/**/*{Cloud,cloud}*.tsx' ] @@ -82,6 +84,58 @@ function stringValue(node: ts.Node): string | null { return null } +const SKIP_ATTRIBUTES = /^(className|class|id|key|testId|data-.*|href|src|role|type|name|variant|size|side|align)$/ +const SKIP_PROPERTIES = /^(className|id|key|testId|kind|type|variant|status|state|icon|href|path|url|pane|section|sectionId)$/ + +/** A string literal that could be user-visible copy: has a space, isn't a key, import or styling. */ +function isCopyLiteral(node: ts.Node): boolean { + if ( + !ts.isStringLiteral(node) && + !ts.isNoSubstitutionTemplateLiteral(node) && + !ts.isTemplateExpression(node) + ) { + return false + } + const text = stringValue(node) ?? '' + if (!/\s/.test(text.trim()) || !/[A-Za-z]/.test(text)) { + return false // pure identifiers, ids and paths + } + const parent = node.parent + if ( + ts.isImportDeclaration(parent) || + ts.isExportDeclaration(parent) || + ts.isExternalModuleReference(parent) || + ts.isLiteralTypeNode(parent) + ) { + return false + } + if (ts.isPropertyAssignment(parent) && parent.name === node) { + return false // object keys + } + if (ts.isPropertyAssignment(parent) && SKIP_PROPERTIES.test(parent.name.getText().replace(/['"]/g, ''))) { + return false + } + const attr = ts.isJsxAttribute(parent) + ? parent + : ts.isJsxExpression(parent) && ts.isJsxAttribute(parent.parent) + ? parent.parent + : null + if (attr && SKIP_ATTRIBUTES.test(attr.name.getText())) { + return false + } + // cn()/clsx() class lists and translation keys (the first argument of t()). + if (ts.isCallExpression(parent)) { + const callee = parent.expression.getText() + if (/^(cn|clsx|cva|twMerge)$/.test(callee)) { + return false + } + if (TRANSLATE_CALLEES.has(callee.split('.').pop() ?? '') && parent.arguments[0] === node) { + return false + } + } + return true +} + /** User-visible strings in one file, with their 1-based lines. */ export function visibleStrings(file: string, source: string): { line: number; text: string }[] { const sf = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX) @@ -92,7 +146,10 @@ export function visibleStrings(file: string, source: string): { line: number; te } } const visit = (node: ts.Node): void => { - if (ts.isJsxText(node)) { + if (isCopyLiteral(node)) { + // Copy tables, object-literal values and template parts: anywhere these terms can hide. + push(node, stringValue(node)) + } else if (ts.isJsxText(node)) { push(node, node.text.trim()) } else if (ts.isJsxAttribute(node) && node.initializer) { const name = node.name.getText(sf) @@ -130,7 +187,15 @@ export function visibleStrings(file: string, source: string): { line: number; te ts.forEachChild(node, visit) } visit(sf) - return out + const seen = new Set() + return out.filter((entry) => { + const key = `${entry.line}:${entry.text}` + if (seen.has(key)) { + return false + } + seen.add(key) + return true + }) } function scopeFiles(): string[] { From a7e46748b02def1d12fff80c71add227cb41ea61 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:20:42 -0800 Subject: [PATCH 084/149] test(cloud): assert the legacy 'VM' sleep-error patterns are never rendered (glossary allowlist guard) --- .../use-cloud-terminal-error-override.test.tsx | 14 ++++++++++++++ .../lib/orca-cloud/cloud-glossary-allowlist.json | 4 ++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.test.tsx b/src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.test.tsx index 1269ffd960e..72562a2a0be 100644 --- a/src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.test.tsx +++ b/src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.test.tsx @@ -73,4 +73,18 @@ describe('terminal error toast on an Orca Cloud workspace that sleeps', () => { const unrelated = render(toast('ws', 'spawn failed: ENOENT')) expect(unrelated.container.querySelector('[data-terminal-error-toast]')).not.toBeNull() }) + + // Glossary lint allowlists these two "VM" match patterns because they are never rendered. If + // that ever changes, this fails before the banned word reaches a cloud user. + it('never renders the legacy "VM" sleep errors it matches (glossary allowlist)', () => { + seed('sleeping') + for (const error of [ + "This workspace's VM is asleep", + "This workspace's VM could not wake up" + ]) { + const { container, unmount } = render(toast('ws', error)) + expect(container.textContent).not.toMatch(/\bVM\b/) + unmount() + } + }) }) diff --git a/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist.json b/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist.json index 5f7f7951cc3..e39cfa66bfd 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist.json +++ b/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist.json @@ -117,12 +117,12 @@ "path": "src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.ts", "line": 13, "term": "VM", - "reason": "Matcher for older builds' saved terminal errors so they stay hidden; never displayed" + "reason": "match pattern for older builds' saved terminal errors; never rendered" }, { "path": "src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.ts", "line": 14, "term": "VM", - "reason": "Matcher for older builds' saved terminal errors so they stay hidden; never displayed" + "reason": "match pattern for older builds' saved terminal errors; never rendered" } ] From c5725b02c3384ce885cde8bb384c1620d67e4ee1 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:36:37 -0800 Subject: [PATCH 085/149] fix(cloud-auth): Cancel always ends a pending Orca sign-in; a second click replaces it; calm timeout (JA-02) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Main: Cancel aborts the attempt at any stage and clears progress at once; a newer sign-in cancels the older one (its loopback listener closes); sign-out cancels a pending sign-in; a timeout says 'Sign-in didn't finish. Try again.' instead of an error toast. - Setup page: a cancelled/timed-out/replaced sign-in no longer falls back to opening a second sign-in (the root cause of the stuck 'Signing in…'); the waiting row has Cancel; Back cancels a sign-in the page started. - Sign in buttons stay clickable while a sign-in is pending. --- .../orca-profile-auth-status-broadcast.ts | 6 +- .../orca-profiles/profile-cloud-pkce.test.ts | 59 +++++- src/main/orca-profiles/profile-cloud-pkce.ts | 18 +- ...file-cloud-service-connect-overlap.test.ts | 5 +- ...ofile-cloud-service-sign-in-cancel.test.ts | 168 ++++++++++++++++++ .../orca-profiles/profile-cloud-service.ts | 36 ++-- .../profile-cloud-sign-in-progress.test.ts | 73 ++++++++ .../profile-cloud-sign-in-progress.ts | 42 ++++- src/preload/api/orca-profile-api.ts | 4 +- src/preload/api/orca-profiles-bridge.ts | 10 +- .../src/components/OrcaSignInProgress.tsx | 67 +++---- .../billing/checkout/use-checkout-flow.ts | 2 +- .../orca-cloud-setup/CloudSetupPage.tsx | 28 ++- .../orca-cloud-setup/use-cloud-setup-flow.ts | 55 +++++- .../orca-profile-auth-ipc-bridge.test.ts | 30 +++- .../orca-profile-auth-ipc-bridge.ts | 8 +- src/renderer/src/i18n/locales/en.json | 12 +- .../orca-cloud/cloud-setup-session-seam.ts | 14 +- .../orca-cloud/cloud-setup-session.test.ts | 4 + .../src/lib/orca-cloud/cloud-setup-session.ts | 14 +- .../create-orca-profiles-slice.ts | 4 + .../orca-profiles-auth-actions.ts | 8 +- src/shared/orca-profiles.ts | 3 + 23 files changed, 578 insertions(+), 92 deletions(-) create mode 100644 src/main/orca-profiles/profile-cloud-service-sign-in-cancel.test.ts create mode 100644 src/main/orca-profiles/profile-cloud-sign-in-progress.test.ts diff --git a/src/main/ipc/profiles/orca-profile-auth-status-broadcast.ts b/src/main/ipc/profiles/orca-profile-auth-status-broadcast.ts index efee902a662..b88fc0aa0b6 100644 --- a/src/main/ipc/profiles/orca-profile-auth-status-broadcast.ts +++ b/src/main/ipc/profiles/orca-profile-auth-status-broadcast.ts @@ -2,6 +2,7 @@ import { BrowserWindow } from 'electron' import { ORCA_PROFILE_AUTH_STATUS_CHANGED_CHANNEL, ORCA_PROFILE_SIGN_IN_PROGRESS_CHANGED_CHANNEL, + type OrcaCloudSignInEnd, type OrcaCloudSignInProgress } from '../../../shared/orca-profiles' @@ -23,7 +24,8 @@ export function broadcastOrcaProfileAuthStatusChanged(): void { } export function broadcastOrcaProfileSignInProgressChanged( - progress: OrcaCloudSignInProgress | null + progress: OrcaCloudSignInProgress | null, + end?: OrcaCloudSignInEnd ): void { - broadcast(ORCA_PROFILE_SIGN_IN_PROGRESS_CHANGED_CHANNEL, progress) + broadcast(ORCA_PROFILE_SIGN_IN_PROGRESS_CHANGED_CHANNEL, progress, end ?? null) } diff --git a/src/main/orca-profiles/profile-cloud-pkce.test.ts b/src/main/orca-profiles/profile-cloud-pkce.test.ts index ca13f97a480..747b3bb3843 100644 --- a/src/main/orca-profiles/profile-cloud-pkce.test.ts +++ b/src/main/orca-profiles/profile-cloud-pkce.test.ts @@ -6,7 +6,11 @@ import { afterEach, describe, expect, it, vi } from 'vitest' vi.mock('electron', () => ({ app: { isPackaged: false }, shell: { openExternal: vi.fn() } })) import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' -import { beginOrcaCloudPkceFlow } from './profile-cloud-pkce' +import { + beginOrcaCloudPkceFlow, + ORCA_CLOUD_SIGN_IN_TIMEOUT_MS, + orcaCloudSignInTimeoutMs +} from './profile-cloud-pkce' const base = 'https://auth.test' const config: OrcaCloudAuthConfig = { @@ -27,6 +31,7 @@ const config: OrcaCloudAuthConfig = { afterEach(() => { delete process.env.ORCA_CLOUD_DEV_OPEN_URL_FILE + delete process.env.ORCA_CLOUD_SIGN_IN_TIMEOUT_MS }) describe('PKCE loopback for cloud setup', () => { @@ -76,3 +81,55 @@ describe('PKCE loopback for cloud setup', () => { expect((await browser).status).toBe(200) }) }) + +describe('PKCE loopback cancel and timeout', () => { + async function start(signal?: AbortSignal): Promise<{ + flow: Promise + redirect: URL + }> { + process.env.ORCA_CLOUD_DEV_OPEN_URL_FILE = join(mkdtempSync(join(tmpdir(), 'pkce-')), 'urls') + let authorize = '' + const flow = beginOrcaCloudPkceFlow(config, 'profile-1', { + onAuthorizeUrl: (url) => (authorize = url), + ...(signal ? { signal } : {}) + }) + flow.catch(() => undefined) + await vi.waitFor(() => expect(authorize).not.toBe('')) + return { flow, redirect: new URL(new URL(authorize).searchParams.get('redirect_uri')!) } + } + + it('Cancel rejects the wait and closes the loopback listener', async () => { + const abort = new AbortController() + const { flow, redirect } = await start(abort.signal) + abort.abort() + await expect(flow).rejects.toThrow('orca_cloud_auth_cancelled') + // A late browser callback finds nothing listening. + await expect(fetch(redirect)).rejects.toThrow() + }) + + it('an already-cancelled attempt never opens a listener', async () => { + const abort = new AbortController() + abort.abort() + const onAuthorizeUrl = vi.fn() + await expect( + beginOrcaCloudPkceFlow(config, 'profile-1', { signal: abort.signal, onAuthorizeUrl }) + ).rejects.toThrow('orca_cloud_auth_cancelled') + expect(onAuthorizeUrl).not.toHaveBeenCalled() + }) + + it('times out a sign-in the browser never finishes', async () => { + process.env.ORCA_CLOUD_SIGN_IN_TIMEOUT_MS = '1000' + const { flow, redirect } = await start() + await expect(flow).rejects.toThrow('orca_cloud_auth_timeout') + await expect(fetch(redirect)).rejects.toThrow() + }) + + it('waits five minutes by default; only unpackaged dev runs may shorten it', () => { + expect(ORCA_CLOUD_SIGN_IN_TIMEOUT_MS).toBe(300_000) + expect(orcaCloudSignInTimeoutMs({}, false)).toBe(300_000) + expect(orcaCloudSignInTimeoutMs({ ORCA_CLOUD_SIGN_IN_TIMEOUT_MS: '60000' }, false)).toBe(60_000) + expect(orcaCloudSignInTimeoutMs({ ORCA_CLOUD_SIGN_IN_TIMEOUT_MS: '60000' }, true)).toBe(300_000) + expect(orcaCloudSignInTimeoutMs({ ORCA_CLOUD_SIGN_IN_TIMEOUT_MS: '10' }, false)).toBe(300_000) + expect(orcaCloudSignInTimeoutMs({ ORCA_CLOUD_SIGN_IN_TIMEOUT_MS: 'x' }, false)).toBe(300_000) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-pkce.ts b/src/main/orca-profiles/profile-cloud-pkce.ts index be85d68036f..43127271205 100644 --- a/src/main/orca-profiles/profile-cloud-pkce.ts +++ b/src/main/orca-profiles/profile-cloud-pkce.ts @@ -24,7 +24,17 @@ export type OrcaCloudAuthorizationCode = { /** How long a held browser tab waits for the caller before it gets the "signed in" page. */ const HOLD_BROWSER_MS = 30_000 -const AUTH_TIMEOUT_MS = 5 * 60 * 1000 +/** A sign-in the browser never answers ends after this, with "Sign-in didn’t finish. Try again." */ +export const ORCA_CLOUD_SIGN_IN_TIMEOUT_MS = 5 * 60 * 1000 + +/** Dev automation only (unpackaged): ORCA_CLOUD_SIGN_IN_TIMEOUT_MS shortens the wait for a test run. */ +export function orcaCloudSignInTimeoutMs( + env: NodeJS.ProcessEnv = process.env, + packaged: boolean = app.isPackaged +): number { + const override = packaged ? Number.NaN : Number(env.ORCA_CLOUD_SIGN_IN_TIMEOUT_MS) + return Number.isFinite(override) && override >= 1_000 ? override : ORCA_CLOUD_SIGN_IN_TIMEOUT_MS +} function base64Url(buffer: Buffer): string { return buffer.toString('base64').replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '') @@ -159,7 +169,7 @@ export function beginOrcaCloudPkceFlow( const timeout = setTimeout(() => { rejectFlow(new Error('orca_cloud_auth_timeout')) - }, AUTH_TIMEOUT_MS) + }, orcaCloudSignInTimeoutMs()) const cancel = (): void => rejectFlow(new Error('orca_cloud_auth_cancelled')) options.signal?.addEventListener('abort', cancel, { once: true }) server.once('close', () => { @@ -167,6 +177,10 @@ export function beginOrcaCloudPkceFlow( options.signal?.removeEventListener('abort', cancel) }) server.once('error', rejectFlow) + if (options.signal?.aborted) { + cancel() + return + } server.listen(0, '127.0.0.1', () => { const address = server.address() if (!address || typeof address === 'string') { diff --git a/src/main/orca-profiles/profile-cloud-service-connect-overlap.test.ts b/src/main/orca-profiles/profile-cloud-service-connect-overlap.test.ts index 04dd63f7e67..4417aad27a3 100644 --- a/src/main/orca-profiles/profile-cloud-service-connect-overlap.test.ts +++ b/src/main/orca-profiles/profile-cloud-service-connect-overlap.test.ts @@ -184,7 +184,8 @@ describe('Orca cloud overlapping connect', () => { redirectUri: 'http://127.0.0.1:4100/auth/callback', state: 'earlier-state' }) - await expect(earlier).resolves.toMatchObject({ status: 'connected' }) + // The later sign-in replaced the earlier one, so the earlier callback can't link anything. + await expect(earlier).resolves.toMatchObject({ status: 'cancelled' }) await expect(signOutCurrentOrcaProfile(userDataPath)).resolves.toMatchObject({ status: 'signed-out' }) @@ -196,7 +197,7 @@ describe('Orca cloud overlapping connect', () => { state: 'later-state' }) await expect(later).resolves.toMatchObject({ status: 'cancelled' }) - expect(exchangeOrcaCloudAuthCodeMock).toHaveBeenCalledTimes(1) + expect(exchangeOrcaCloudAuthCodeMock).not.toHaveBeenCalled() expect(getCurrentOrcaProfileAuthStatus(userDataPath)).toMatchObject({ state: 'local' }) }) }) diff --git a/src/main/orca-profiles/profile-cloud-service-sign-in-cancel.test.ts b/src/main/orca-profiles/profile-cloud-service-sign-in-cancel.test.ts new file mode 100644 index 00000000000..8e590b412bb --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-service-sign-in-cancel.test.ts @@ -0,0 +1,168 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { OrcaCloudSignInEnd, OrcaProfileCloudSummary } from '../../shared/orca-profiles' + +const { beginOrcaCloudPkceFlowMock, exchangeOrcaCloudAuthCodeMock, safeStorageMock } = vi.hoisted( + () => ({ + beginOrcaCloudPkceFlowMock: vi.fn(), + exchangeOrcaCloudAuthCodeMock: vi.fn(), + safeStorageMock: { + decryptString: vi.fn((value: Buffer) => value.toString('utf-8')), + encryptString: vi.fn((value: string) => Buffer.from(value, 'utf-8')), + isEncryptionAvailable: vi.fn(() => true) + } + }) +) + +let userDataPath = '' + +vi.mock('electron', () => ({ + app: { getPath: () => userDataPath }, + safeStorage: safeStorageMock +})) + +vi.mock('./profile-cloud-pkce', () => ({ + beginOrcaCloudPkceFlow: beginOrcaCloudPkceFlowMock +})) + +vi.mock('./profile-cloud-client', () => ({ + createOrcaCloudProfile: vi.fn(), + exchangeOrcaCloudAuthCode: exchangeOrcaCloudAuthCodeMock, + revokeOrcaCloudSession: vi.fn(async () => undefined), + selectOrcaCloudOrg: vi.fn() +})) + +import { connectCurrentOrcaProfile, getCurrentOrcaProfileAuthStatus } from './profile-cloud-service' +import { + cancelOrcaCloudSignIn, + getOrcaCloudSignInProgress, + onOrcaCloudSignInProgressChanged, + resetOrcaCloudSignInProgressForTests +} from './profile-cloud-sign-in-progress' + +const cloud: OrcaProfileCloudSummary = { + cloudProfileId: 'cloud-profile-1', + userId: 'user-1', + email: 'nina@example.com', + displayName: 'Nina', + linkedAt: 10 +} + +const code = { + code: 'the-code', + codeVerifier: 'verifier', + nonce: 'nonce', + redirectUri: 'http://127.0.0.1:4100/auth/callback', + state: 'state' +} + +/** Waits for the browser like the real loopback: rejects when the attempt is aborted. */ +function pendingBrowser(): { + answer: (value: typeof code) => void + fail: (error: Error) => void +} { + const handle = { + answer: (_value: typeof code): void => undefined, + fail: (_error: Error): void => undefined + } + beginOrcaCloudPkceFlowMock.mockImplementationOnce( + (_config: unknown, _profile: string, options: { signal?: AbortSignal }) => + new Promise((resolve, reject) => { + handle.answer = resolve + handle.fail = reject + options.signal?.addEventListener('abort', () => + reject(new Error('orca_cloud_auth_cancelled')) + ) + }) + ) + return handle +} + +describe('Orca Cloud sign-in cancel, supersede and timeout', () => { + beforeEach(() => { + userDataPath = mkdtempSync(join(tmpdir(), 'orca-cloud-sign-in-cancel-')) + beginOrcaCloudPkceFlowMock.mockReset() + exchangeOrcaCloudAuthCodeMock.mockReset() + exchangeOrcaCloudAuthCodeMock.mockResolvedValue({ + accessToken: 'access-token', + refreshToken: 'refresh-token', + expiresAt: Date.now() + 3_600_000, + cloud, + organizations: [], + capabilities: { flags: {}, refreshedAt: 1 } + }) + vi.stubEnv('ORCA_CLOUD_API_URL', 'https://orca-cloud.example') + vi.stubEnv('ORCA_CLOUD_CLIENT_ID', 'desktop-client') + }) + + afterEach(() => { + resetOrcaCloudSignInProgressForTests() + rmSync(userDataPath, { recursive: true, force: true }) + vi.unstubAllEnvs() + }) + + it('Cancel while the browser is open ends the sign-in and clears progress', async () => { + pendingBrowser() + const connect = connectCurrentOrcaProfile(userDataPath) + await vi.waitFor(() => expect(getOrcaCloudSignInProgress()).not.toBeNull()) + cancelOrcaCloudSignIn() + expect(getOrcaCloudSignInProgress()).toBeNull() + await expect(connect).resolves.toMatchObject({ status: 'cancelled' }) + expect(getCurrentOrcaProfileAuthStatus(userDataPath).state).not.toBe('connected') + }) + + it('Cancel after the browser answered still wins: the session is not saved', async () => { + const browser = pendingBrowser() + let finishExchange!: () => void + exchangeOrcaCloudAuthCodeMock.mockImplementationOnce(async () => { + await new Promise((resolve) => (finishExchange = resolve)) + return { + accessToken: 'access-token', + refreshToken: 'refresh-token', + expiresAt: Date.now() + 3_600_000, + cloud, + organizations: [], + capabilities: { flags: {}, refreshedAt: 1 } + } + }) + const connect = connectCurrentOrcaProfile(userDataPath) + await vi.waitFor(() => expect(beginOrcaCloudPkceFlowMock).toHaveBeenCalled()) + browser.answer(code) + await vi.waitFor(() => expect(exchangeOrcaCloudAuthCodeMock).toHaveBeenCalled()) + cancelOrcaCloudSignIn() + finishExchange() + await expect(connect).resolves.toMatchObject({ status: 'cancelled' }) + expect(getCurrentOrcaProfileAuthStatus(userDataPath).state).not.toBe('connected') + }) + + it('a second sign-in replaces the first: the first closes, the second signs in', async () => { + pendingBrowser() + const second = pendingBrowser() + const first = connectCurrentOrcaProfile(userDataPath) + const later = connectCurrentOrcaProfile(userDataPath) + await expect(first).resolves.toMatchObject({ status: 'cancelled' }) + expect(getOrcaCloudSignInProgress()).not.toBeNull() + second.answer(code) + await expect(later).resolves.toMatchObject({ status: 'connected' }) + expect(getOrcaCloudSignInProgress()).toBeNull() + expect(getCurrentOrcaProfileAuthStatus(userDataPath).cloud?.email).toBe('nina@example.com') + }) + + it('a timed-out sign-in clears progress and says it did not finish', async () => { + const ends: (OrcaCloudSignInEnd | undefined)[] = [] + onOrcaCloudSignInProgressChanged((progress, end) => { + if (!progress) { + ends.push(end) + } + }) + const browser = pendingBrowser() + const connect = connectCurrentOrcaProfile(userDataPath) + await vi.waitFor(() => expect(beginOrcaCloudPkceFlowMock).toHaveBeenCalled()) + browser.fail(new Error('orca_cloud_auth_timeout')) + await expect(connect).resolves.toMatchObject({ status: 'timed-out' }) + expect(getOrcaCloudSignInProgress()).toBeNull() + expect(ends).toEqual(['timed-out']) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-service.ts b/src/main/orca-profiles/profile-cloud-service.ts index 4bd70e0412f..804acb76019 100644 --- a/src/main/orca-profiles/profile-cloud-service.ts +++ b/src/main/orca-profiles/profile-cloud-service.ts @@ -39,6 +39,7 @@ import { import { getOrcaProfileAuthStatusFromProfile } from './profile-cloud-auth-status' import { selectCloudOrg } from './profile-cloud-org-selection' import { + cancelOrcaCloudSignIn, endOrcaCloudSignInProgress, setOrcaCloudSignInLink, startOrcaCloudSignInProgress @@ -53,7 +54,8 @@ let linkedCloudConnectAttempt = 0 function invalidateOutstandingCloudConnectAttempts(): void { nextCloudConnectAttempt += 1 linkedCloudConnectAttempt = nextCloudConnectAttempt - endOrcaCloudSignInProgress() + // Also closes the pending loopback listener, so a late browser callback has nowhere to land. + cancelOrcaCloudSignIn() } function activeAuth( @@ -100,23 +102,26 @@ export async function connectCurrentOrcaProfile( } const attempt = ++nextCloudConnectAttempt - const browserWait = new AbortController() - startOrcaCloudSignInProgress(attempt, () => browserWait.abort()) + // Cancel (or a newer attempt) aborts this one at any stage before the session is saved. + const attemptAbort = new AbortController() + const cancelled = (): ConnectCurrentOrcaProfileResult => ({ + status: 'cancelled', + auth: getCurrentOrcaProfileAuthStatus(userDataPath) + }) + let end: 'timed-out' | undefined + startOrcaCloudSignInProgress(attempt, () => attemptAbort.abort()) let finishBrowser: ((location: string | null) => void) | undefined try { const code = await beginOrcaCloudPkceFlow(configState.config, active.profile.id, { - signal: browserWait.signal, + signal: attemptAbort.signal, onAuthorizeUrl: (link) => setOrcaCloudSignInLink(attempt, link), ...(setup ? { authorizeParams: setup.authorizeParams, holdBrowser: true } : {}) }) finishBrowser = code.finishBrowser // The callback listener has closed, so its browser link is dead. setOrcaCloudSignInLink(attempt, null) - if (attempt < linkedCloudConnectAttempt) { - return { - status: 'cancelled', - auth: getCurrentOrcaProfileAuthStatus(userDataPath) - } + if (attempt < linkedCloudConnectAttempt || attemptAbort.signal.aborted) { + return cancelled() } const exchange = await exchangeOrcaCloudAuthCode(configState.config, { code: code.code, @@ -126,11 +131,8 @@ export async function connectCurrentOrcaProfile( state: code.state, localProfileId: active.profile.id }) - if (attempt < linkedCloudConnectAttempt) { - return { - status: 'cancelled', - auth: getCurrentOrcaProfileAuthStatus(userDataPath) - } + if (attempt < linkedCloudConnectAttempt || attemptAbort.signal.aborted) { + return cancelled() } signInCloudSession(active.profile.id, userDataPath, exchange) const list = linkOrcaProfileToCloud(active.profile.id, exchange.cloud, userDataPath) @@ -147,8 +149,12 @@ export async function connectCurrentOrcaProfile( profiles: list.profiles } } catch (error) { + if (attemptAbort.signal.aborted) { + return cancelled() + } const message = error instanceof Error ? error.message : String(error) if (message === 'orca_cloud_auth_timeout' && attempt === nextCloudConnectAttempt) { + end = 'timed-out' return { status: 'timed-out', auth: getCurrentOrcaProfileAuthStatus(userDataPath) @@ -171,7 +177,7 @@ export async function connectCurrentOrcaProfile( } } finally { finishBrowser?.(null) - endOrcaCloudSignInProgress(attempt) + endOrcaCloudSignInProgress(attempt, end) } } diff --git a/src/main/orca-profiles/profile-cloud-sign-in-progress.test.ts b/src/main/orca-profiles/profile-cloud-sign-in-progress.test.ts new file mode 100644 index 00000000000..2e4135c9cb7 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-sign-in-progress.test.ts @@ -0,0 +1,73 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { OrcaCloudSignInEnd, OrcaCloudSignInProgress } from '../../shared/orca-profiles' +import { + cancelOrcaCloudSignIn, + endOrcaCloudSignInProgress, + getOrcaCloudSignInProgress, + onOrcaCloudSignInProgressChanged, + resetOrcaCloudSignInProgressForTests, + setOrcaCloudSignInLink, + startOrcaCloudSignInProgress +} from './profile-cloud-sign-in-progress' + +afterEach(() => resetOrcaCloudSignInProgressForTests()) + +function record(): [OrcaCloudSignInProgress | null, OrcaCloudSignInEnd | undefined][] { + const events: [OrcaCloudSignInProgress | null, OrcaCloudSignInEnd | undefined][] = [] + onOrcaCloudSignInProgressChanged((progress, end) => events.push([progress, end])) + return events +} + +describe('Orca Cloud sign-in progress', () => { + it('Cancel aborts the pending attempt and clears progress at once', () => { + const events = record() + const abort = vi.fn() + startOrcaCloudSignInProgress(1, abort) + setOrcaCloudSignInLink(1, 'https://auth.test/authorize') + cancelOrcaCloudSignIn() + expect(abort).toHaveBeenCalledOnce() + expect(getOrcaCloudSignInProgress()).toBeNull() + expect(events.at(-1)).toEqual([null, undefined]) + // The aborted attempt ending later changes nothing. + endOrcaCloudSignInProgress(1) + expect(events).toHaveLength(3) + }) + + it('clears progress even when aborting throws', () => { + startOrcaCloudSignInProgress(1, () => { + throw new Error('already closed') + }) + expect(() => cancelOrcaCloudSignIn()).not.toThrow() + expect(getOrcaCloudSignInProgress()).toBeNull() + }) + + it('a second sign-in replaces the first and cancels it', () => { + const first = vi.fn() + const second = vi.fn() + startOrcaCloudSignInProgress(1, first) + setOrcaCloudSignInLink(1, 'https://auth.test/one') + startOrcaCloudSignInProgress(2, second) + expect(first).toHaveBeenCalledOnce() + expect(second).not.toHaveBeenCalled() + expect(getOrcaCloudSignInProgress()).toEqual({ link: null }) + // The replaced attempt can neither set its link nor end the newer one. + setOrcaCloudSignInLink(1, 'https://auth.test/stale') + endOrcaCloudSignInProgress(1) + expect(getOrcaCloudSignInProgress()).toEqual({ link: null }) + setOrcaCloudSignInLink(2, 'https://auth.test/two') + expect(getOrcaCloudSignInProgress()).toEqual({ link: 'https://auth.test/two' }) + }) + + it('says when a sign-in timed out', () => { + const events = record() + startOrcaCloudSignInProgress(3, vi.fn()) + endOrcaCloudSignInProgress(3, 'timed-out') + expect(events.at(-1)).toEqual([null, 'timed-out']) + }) + + it('Cancel with nothing pending is a no-op', () => { + const events = record() + cancelOrcaCloudSignIn() + expect(events).toHaveLength(0) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-sign-in-progress.ts b/src/main/orca-profiles/profile-cloud-sign-in-progress.ts index 88cb98cc23d..5c33fb6873c 100644 --- a/src/main/orca-profiles/profile-cloud-sign-in-progress.ts +++ b/src/main/orca-profiles/profile-cloud-sign-in-progress.ts @@ -1,8 +1,9 @@ -import type { OrcaCloudSignInProgress } from '../../shared/orca-profiles' +import type { OrcaCloudSignInEnd, OrcaCloudSignInProgress } from '../../shared/orca-profiles' -type ProgressListener = (progress: OrcaCloudSignInProgress | null) => void +type ProgressListener = (progress: OrcaCloudSignInProgress | null, end?: OrcaCloudSignInEnd) => void -// Only the newest attempt owns progress; late updates from older attempts are ignored. +// One sign-in at a time: a newer attempt cancels the older one (its loopback listener closes), and +// Cancel clears the pending state at once, so nothing can leave the app stuck on "Signing in…". let current: { attempt: number; link: string | null; cancel: () => void } | null = null const listeners = new Set() @@ -10,18 +11,26 @@ function snapshot(): OrcaCloudSignInProgress | null { return current ? { link: current.link } : null } -function update(next: typeof current): void { +function update(next: typeof current, end?: OrcaCloudSignInEnd): void { current = next const progress = snapshot() for (const listener of listeners) { try { - listener(progress) + listener(progress, end) } catch (error) { console.warn('[orca-profiles] Sign-in progress listener failed:', error) } } } +function cancelQuietly(cancel: () => void): void { + try { + cancel() + } catch (error) { + console.warn('[orca-profiles] Cancelling a sign-in failed:', error) + } +} + export function getOrcaCloudSignInProgress(): OrcaCloudSignInProgress | null { return snapshot() } @@ -33,8 +42,13 @@ export function onOrcaCloudSignInProgressChanged(listener: ProgressListener): () } } +/** Starts tracking `attempt`; an older pending attempt is cancelled (a second click supersedes it). */ export function startOrcaCloudSignInProgress(attempt: number, cancel: () => void): void { + const previous = current update({ attempt, link: null, cancel }) + if (previous && previous.attempt !== attempt) { + cancelQuietly(previous.cancel) + } } export function setOrcaCloudSignInLink(attempt: number, link: string | null): void { @@ -43,12 +57,24 @@ export function setOrcaCloudSignInLink(attempt: number, link: string | null): vo } } -export function endOrcaCloudSignInProgress(attempt?: number): void { +export function endOrcaCloudSignInProgress(attempt?: number, end?: OrcaCloudSignInEnd): void { if (current && (attempt === undefined || current.attempt === attempt)) { - update(null) + update(null, end) } } +/** Cancel: aborts the pending attempt (closing its loopback listener) and clears progress now. */ export function cancelOrcaCloudSignIn(): void { - current?.cancel() + const pending = current + if (!pending) { + return + } + update(null) + cancelQuietly(pending.cancel) +} + +/** Test-only. */ +export function resetOrcaCloudSignInProgressForTests(): void { + current = null + listeners.clear() } diff --git a/src/preload/api/orca-profile-api.ts b/src/preload/api/orca-profile-api.ts index 47a945f946b..c8b62b804e8 100644 --- a/src/preload/api/orca-profile-api.ts +++ b/src/preload/api/orca-profile-api.ts @@ -10,6 +10,7 @@ import type { OrcaProfileOrgLeaveArgs } from '../../shared/orca-org-management' import type { + OrcaCloudSignInEnd, OrcaCloudSignInProgress, ConnectCurrentOrcaProfileResult, CreateCloudLinkedOrcaProfileArgs, @@ -67,7 +68,8 @@ export type OrcaProfileApi = { connectCurrent: () => Promise signInProgress: () => Promise onSignInProgressChanged: ( - callback: (progress: OrcaCloudSignInProgress | null) => void + /** `end` says why a sign-in stopped when the UI should tell the user (it timed out). */ + callback: (progress: OrcaCloudSignInProgress | null, end: OrcaCloudSignInEnd | null) => void ) => () => void cancelSignIn: () => Promise refreshAuth: () => Promise diff --git a/src/preload/api/orca-profiles-bridge.ts b/src/preload/api/orca-profiles-bridge.ts index d9f5adb506f..349947683ca 100644 --- a/src/preload/api/orca-profiles-bridge.ts +++ b/src/preload/api/orca-profiles-bridge.ts @@ -3,6 +3,7 @@ import type { PreloadApi } from '../api-types' import { ORCA_PROFILE_AUTH_STATUS_CHANGED_CHANNEL, ORCA_PROFILE_SIGN_IN_PROGRESS_CHANGED_CHANNEL, + type OrcaCloudSignInEnd, type OrcaCloudSignInProgress, type OrcaProfileListResult, type SwitchOrcaProfileResult, @@ -29,10 +30,13 @@ export const orcaProfilesApi = { return () => ipcRenderer.removeListener(ORCA_PROFILE_AUTH_STATUS_CHANGED_CHANNEL, listener) }, onSignInProgressChanged: ( - callback: (progress: OrcaCloudSignInProgress | null) => void + callback: (progress: OrcaCloudSignInProgress | null, end: OrcaCloudSignInEnd | null) => void ): (() => void) => { - const listener = (_event: unknown, progress: OrcaCloudSignInProgress | null): void => - callback(progress) + const listener = ( + _event: unknown, + progress: OrcaCloudSignInProgress | null, + end?: OrcaCloudSignInEnd | null + ): void => callback(progress, end ?? null) ipcRenderer.on(ORCA_PROFILE_SIGN_IN_PROGRESS_CHANGED_CHANNEL, listener) return () => ipcRenderer.removeListener(ORCA_PROFILE_SIGN_IN_PROGRESS_CHANGED_CHANNEL, listener) }, diff --git a/src/renderer/src/components/OrcaSignInProgress.tsx b/src/renderer/src/components/OrcaSignInProgress.tsx index 10caa6e6dae..7d196c2687e 100644 --- a/src/renderer/src/components/OrcaSignInProgress.tsx +++ b/src/renderer/src/components/OrcaSignInProgress.tsx @@ -18,43 +18,46 @@ async function copySignInLink(link: string): Promise { } } +/** + * Stays clickable while a sign-in is pending: another click starts a fresh sign-in in the browser + * and replaces the pending one (main cancels it), so a closed or lost tab never strands the user. + */ export function OrcaSignInButton({ children, - disabled, ...props }: Omit, 'onClick' | 'type'>): React.JSX.Element { - const t = useTranslate() const connect = useAppStore((state) => state.connectCurrentOrcaProfile) - const signingIn = useAppStore((state) => Boolean(state.orcaProfileSignInProgress)) return ( - ) } +function cancelSignIn(): void { + void window.api.orcaProfiles.cancelSignIn().catch(() => {}) +} + export function OrcaSignInWaitNotice({ className }: { className?: string }): React.JSX.Element | null { const t = useTranslate() - const link = useAppStore((state) => state.orcaProfileSignInProgress?.link) - if (!link) { - return null + const progress = useAppStore((state) => state.orcaProfileSignInProgress) + const timedOut = useAppStore((state) => state.orcaProfileSignInEnd === 'timed-out') + const signedIn = useAppStore((state) => state.orcaProfileAuthStatus?.state === 'connected') + if (!progress) { + if (!timedOut || signedIn) { + return null + } + return ( +

    + {t('auto.components.OrcaSignInProgress.didNotFinish', 'Sign-in didn’t finish. Try again.')} +

    + ) } + const link = progress.link return (
    + - {t('auto.components.OrcaSignInProgress.waiting', 'Waiting for sign-in in your browser')} + {link + ? t('auto.components.OrcaSignInProgress.waiting', 'Waiting for sign-in in your browser') + : t('auto.components.OrcaSignInProgress.signingIn', 'Signing in…')} + {link ? ( + <> + · + + + ) : null} · - - · -
    diff --git a/src/renderer/src/components/billing/checkout/use-checkout-flow.ts b/src/renderer/src/components/billing/checkout/use-checkout-flow.ts index 753c6b2afff..b4b983241bf 100644 --- a/src/renderer/src/components/billing/checkout/use-checkout-flow.ts +++ b/src/renderer/src/components/billing/checkout/use-checkout-flow.ts @@ -66,7 +66,7 @@ export function useCheckoutFlow({ onPaid }: { onPaid: (seats: number) => void }) // O1: a plan always lands on a team. The browser makes or picks the team, then Checkout; // the setup session switches this profile to that team when it's there. const started = await startCloudSetupSession({ needs: ['team', 'plan'], chooseTeam: true }) - return started ? { status: 'opened' } : result + return started && 'sessionId' in started ? { status: 'opened' } : result }) .then((result) => { if (id === runId.current) { diff --git a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx index d9dabad6168..d63b115239f 100644 --- a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx +++ b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx @@ -95,6 +95,11 @@ function BrowserWaiting({ flow }: { flow: CloudSetupFlow }): React.JSX.Element { {t('cloudSetupPage.waitingBrowser', 'Waiting for your browser…')} + {flow.signingIn ? ( + + ) : null} {flow.copyLink ? ( diff --git a/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts b/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts index 165dbd03b21..e564ddef6ce 100644 --- a/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts +++ b/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts @@ -3,6 +3,7 @@ // one-trip setup session (#255) with its deep-link return (#257), B2's team switch, and the // tracker's error parsing (#260). Only the UI moved: from a card in the dialog to this page. import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { useAppStore } from '@/store' import { claimOrcaCloudTrial } from '@/components/billing/claim-trial' import { invalidateOrcaCloudBilling, @@ -80,6 +81,13 @@ function useLiveAvailability( export type CloudSetupFlow = CloudSetupPageModel & { /** True from the click until the browser opens or the trial answers. */ busy: boolean + /** This page's browser sign-in is pending: the page offers Cancel and keeps Reopen browser live. */ + signingIn: boolean + /** The last sign-in stopped on its own (it timed out): "Sign-in didn’t finish. Try again." */ + signInDidNotFinish: boolean + cancelSignIn: () => void + /** Leaving setup (Back): cancels a sign-in this page started. */ + abandon: () => void /** The browser trip is open: the current step reads "Waiting for your browser". */ inBrowser: boolean error: ReturnType @@ -166,6 +174,12 @@ export function useCloudSetupFlow( [access, availability] ) + const runRef = useRef(0) + const [startedSignIn, setStartedSignIn] = useState(false) + const signInPending = useAppStore((state) => Boolean(state.orcaProfileSignInProgress)) + const signInTimedOut = useAppStore((state) => state.orcaProfileSignInEnd === 'timed-out') + const signingIn = busy && startedSignIn && signInPending + // One browser trip for everything still open from here (sign-in, team, trial or Checkout, GitHub). const continueInBrowser = useCallback(() => { const needs = sessionNeedsFrom(stepsRef.current) @@ -180,9 +194,19 @@ export function useCloudSetupFlow( fallback() return } + // Each click is a new run. An older run that ends late (its sign-in was replaced or cancelled) + // must not touch the page or open anything. + const run = ++runRef.current + const isCurrent = (): boolean => run === runRef.current setBusy(true) + setBrowserStep(null) + setStartedSignIn(cloudSetupPageModel(stepsRef.current).current?.id === 'account') void start({ repoId: request.repoId, needs }) .then((opened) => { + if (!isCurrent() || (opened && 'cancelled' in opened)) { + // Cancelled, timed out or replaced: back to the step's own button; nothing reopens. + return + } markInBrowser() if (opened) { setSessionId(opened.sessionId) @@ -190,10 +214,31 @@ export function useCloudSetupFlow( fallback() } }) - .catch(() => fallback()) - .finally(() => setBusy(false)) + .catch(() => { + if (isCurrent()) { + fallback() + } + }) + .finally(() => { + if (isCurrent()) { + setBusy(false) + setStartedSignIn(false) + } + }) }, [fallback, markInBrowser, openInstall, request.repoId]) + const cancelSignIn = useCallback(() => { + void window.api.orcaProfiles.cancelSignIn().catch(() => {}) + }, []) + + const abandon = useCallback(() => { + if (busy && startedSignIn) { + // Back means "not now": the tab this page opened must not sign in behind the user's back. + runRef.current++ + cancelSignIn() + } + }, [busy, cancelSignIn, startedSignIn]) + const startTrial = useCallback(() => { setBusy(true) void claimOrcaCloudTrial() @@ -226,7 +271,11 @@ export function useCloudSetupFlow( return { ...model, - busy, + busy: busy && !signingIn, + signingIn, + signInDidNotFinish: !busy && signInTimedOut && model.action === 'sign-in', + cancelSignIn, + abandon, inBrowser: browserStep !== null && (sessionId !== null || model.current?.id === browserStep), error, canManageBilling: access.state === 'no-plan' ? access.canManageBilling : true, diff --git a/src/renderer/src/hooks/ipc-events/orca-profile-auth-ipc-bridge.test.ts b/src/renderer/src/hooks/ipc-events/orca-profile-auth-ipc-bridge.test.ts index ee223e3dd19..bb214773b5c 100644 --- a/src/renderer/src/hooks/ipc-events/orca-profile-auth-ipc-bridge.test.ts +++ b/src/renderer/src/hooks/ipc-events/orca-profile-auth-ipc-bridge.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { OrcaCloudSignInProgress } from '../../../../shared/orca-profiles' +import type { OrcaCloudSignInEnd, OrcaCloudSignInProgress } from '../../../../shared/orca-profiles' import { createTestStore } from '../../store/testing/app-store-test-fixture' type TestStore = ReturnType @@ -11,8 +11,10 @@ const { storeHolder } = vi.hoisted((): { storeHolder: { current: TestStore | nul vi.mock('../../store', () => ({ useAppStore: { getState: () => storeHolder.current?.getState(), - setState: (partial: { orcaProfileSignInProgress: OrcaCloudSignInProgress | null }) => - storeHolder.current?.setState(partial) + setState: (partial: { + orcaProfileSignInProgress: OrcaCloudSignInProgress | null + orcaProfileSignInEnd?: OrcaCloudSignInEnd | null + }) => storeHolder.current?.setState(partial) } })) @@ -23,7 +25,10 @@ vi.mock('sonner', () => ({ import { registerOrcaProfileAuthIpcBridge } from './orca-profile-auth-ipc-bridge' describe('orca profile sign-in progress IPC bridge', () => { - let emitProgress: (progress: OrcaCloudSignInProgress | null) => void + let emitProgress: ( + progress: OrcaCloudSignInProgress | null, + end?: OrcaCloudSignInEnd | null + ) => void const snapshots: ((progress: OrcaCloudSignInProgress | null) => void)[] = [] const WAITING = { link: 'https://login.example/authorize?state=a' } @@ -34,7 +39,10 @@ describe('orca profile sign-in progress IPC bridge', () => { api: { orcaProfiles: { onSignInProgressChanged: ( - callback: (progress: OrcaCloudSignInProgress | null) => void + callback: ( + progress: OrcaCloudSignInProgress | null, + end?: OrcaCloudSignInEnd | null + ) => void ) => { emitProgress = callback return () => {} @@ -59,4 +67,16 @@ describe('orca profile sign-in progress IPC bridge', () => { await new Promise((resolve) => setTimeout(resolve, 0)) expect(progress()).toBeNull() }) + + it('keeps the timed-out note until the next sign-in starts', () => { + registerOrcaProfileAuthIpcBridge([]) + const end = (): OrcaCloudSignInEnd | null => + storeHolder.current?.getState().orcaProfileSignInEnd ?? null + emitProgress(WAITING, null) + emitProgress(null, 'timed-out') + expect(progress()).toBeNull() + expect(end()).toBe('timed-out') + emitProgress({ link: null }, null) + expect(end()).toBeNull() + }) }) diff --git a/src/renderer/src/hooks/ipc-events/orca-profile-auth-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/orca-profile-auth-ipc-bridge.ts index 7d7ba00f5a0..b77d59958ae 100644 --- a/src/renderer/src/hooks/ipc-events/orca-profile-auth-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/orca-profile-auth-ipc-bridge.ts @@ -12,9 +12,13 @@ export function registerOrcaProfileAuthIpcBridge(unsubs: (() => void)[]): void { if (typeof api?.onSignInProgressChanged === 'function') { // Why: a sign-in can already be in flight when this window loads; a later event or teardown wins. let ignoreSnapshot = false - const unsubscribe = api.onSignInProgressChanged((progress) => { + const unsubscribe = api.onSignInProgressChanged((progress, end) => { ignoreSnapshot = true - useAppStore.setState({ orcaProfileSignInProgress: progress }) + // A new sign-in (or one that finished) clears the "didn't finish" note; a timeout sets it. + useAppStore.setState({ + orcaProfileSignInProgress: progress, + orcaProfileSignInEnd: end ?? null + }) }) unsubs.push(() => { ignoreSnapshot = true diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 2785e394006..d8f56eff789 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -1770,7 +1770,8 @@ "7d4bc516ee": "Failed to switch profile", "f518e89aa5": "Project already exists in that profile", "f03ae7f27b": "Failed to transfer project", - "signInTimedOut": "Sign-in timed out" + "signInTimedOut": "Sign-in timed out", + "signInDidNotFinish": "Sign-in didn’t finish. Try again." } }, "runtime": { @@ -20395,7 +20396,8 @@ "copied": "Sign-in link copied", "copyFailed": "Could not copy the link.", "signingIn": "Signing in…", - "cancel": "Cancel" + "cancel": "Cancel", + "didNotFinish": "Sign-in didn’t finish. Try again." }, "plainSshTerminal": { "open": "Open plain SSH terminal", @@ -28047,7 +28049,8 @@ "signIn": { "lead": "Orca Cloud runs your agents in a cloud workspace, so they keep going with your laptop closed. Sign in or create an account in your browser. We’ll make a team for you.", "note": "New teams get a trial with no card needed. This page picks up each step on its own.", - "title": "Sign in to Orca" + "title": "Sign in to Orca", + "didNotFinish": "Sign-in didn’t finish. Try again." }, "starting": "Starting…", "startsAfter": "Starts when setup is done", @@ -28075,6 +28078,7 @@ "lead_other": "{{hours}} sandbox hours to try Orca Cloud. No card needed." }, "untitled": "New cloud workspace", - "waitingBrowser": "Waiting for your browser…" + "waitingBrowser": "Waiting for your browser…", + "cancelSignIn": "Cancel" } } diff --git a/src/renderer/src/lib/orca-cloud/cloud-setup-session-seam.ts b/src/renderer/src/lib/orca-cloud/cloud-setup-session-seam.ts index e92b0addc43..d0ae500d0a3 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-setup-session-seam.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-setup-session-seam.ts @@ -42,8 +42,13 @@ export type CloudSetupStartRequest = { /** The rows still open when the user clicked (account, team, plan, github). */ needs: CloudSetupStep['id'][] } -/** Null when the session couldn't open; the composer then falls back to today's actions. */ -type SessionStarter = (request: CloudSetupStartRequest) => Promise<{ sessionId: string } | null> +/** + * Null when the session couldn't open; the composer then falls back to today's actions. + * `cancelled` when the user cancelled the sign-in: no fallback, nothing else opens. + */ +type SessionStarter = ( + request: CloudSetupStartRequest +) => Promise<{ sessionId: string } | { cancelled: true } | null> let source: SessionSource | null = null let starter: SessionStarter | null = null @@ -71,10 +76,7 @@ export function readCloudSetupSession(sessionId: string | null): CloudSetupSessi // Bumped on every change, so a read is cached per (session, revision): useSyncExternalStore needs // the same object back until something changed. let revision = 0 -const cachedReads = new Map< - string, - { revision: number; value: CloudSetupSessionSnapshot | null } ->() +const cachedReads = new Map() /** Call after each poll so open composers re-read their session. */ export function notifyCloudSetupSessionChanged(): void { diff --git a/src/renderer/src/lib/orca-cloud/cloud-setup-session.test.ts b/src/renderer/src/lib/orca-cloud/cloud-setup-session.test.ts index 0a0c7c08411..4a9b5046fad 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-setup-session.test.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-setup-session.test.ts @@ -126,6 +126,10 @@ describe('cloud setup session (renderer)', () => { it('stops on an expired session and returns null when setup cannot open', async () => { cloudSetupStart.mockResolvedValueOnce({ status: 'signed-out' }) expect(await startCloudSetupSession({ needs: ['plan'] })).toBeNull() + // A cancelled (or timed-out, or replaced) sign-in is not a failure: callers must not fall back + // to another browser trip. + cloudSetupStart.mockResolvedValueOnce({ status: 'cancelled' }) + expect(await startCloudSetupSession({ needs: ['plan'] })).toEqual({ cancelled: true }) cloudSetupGet.mockResolvedValue({ status: 'not-found' }) await refreshCloudSetupSession(ID) diff --git a/src/renderer/src/lib/orca-cloud/cloud-setup-session.ts b/src/renderer/src/lib/orca-cloud/cloud-setup-session.ts index d4bd4812bee..51199abb3fd 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-setup-session.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-setup-session.ts @@ -172,12 +172,18 @@ export function stopWatchingCloudSetupSession(sessionId: string): void { entries.delete(sessionId) } -/** "Set up and start": opens the one browser tab and starts polling. Null when it couldn't. */ +/** + * What "Set up and start" got back: the session it opened, `cancelled` when the user cancelled the + * sign-in (or it timed out, or a newer one replaced it), or null when setup couldn't open. + */ +export type CloudSetupSessionStart = { sessionId: string } | { cancelled: true } | null + +/** "Set up and start": opens the one browser tab and starts polling. */ export async function startCloudSetupSession(request: { repo?: string needs: CloudSetupNeed[] chooseTeam?: boolean -}): Promise<{ sessionId: string } | null> { +}): Promise { let result: CloudSetupStartResult try { result = await window.api.orcaProfiles.cloudSetupStart({ @@ -188,6 +194,10 @@ export async function startCloudSetupSession(request: { } catch { return null } + if (result.status === 'cancelled') { + // The user stopped the sign-in: nothing else may open a browser on their behalf. + return { cancelled: true } + } if (result.status !== 'opened') { return null } diff --git a/src/renderer/src/store/slices/orca-profiles/create-orca-profiles-slice.ts b/src/renderer/src/store/slices/orca-profiles/create-orca-profiles-slice.ts index 8bf623831b0..c87919d7bb4 100644 --- a/src/renderer/src/store/slices/orca-profiles/create-orca-profiles-slice.ts +++ b/src/renderer/src/store/slices/orca-profiles/create-orca-profiles-slice.ts @@ -2,6 +2,7 @@ import type { StateCreator } from 'zustand' import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import type { + OrcaCloudSignInEnd, OrcaCloudSignInProgress, OrcaProfileAuthStatus, OrcaProfileSummary, @@ -20,6 +21,8 @@ export type OrcaProfilesSlice = OrcaProfilesAuthActions & { activeOrcaProfileId: string | null orcaProfileAuthStatus: OrcaProfileAuthStatus | null orcaProfileSignInProgress: OrcaCloudSignInProgress | null + /** Set when the last sign-in stopped without finishing (it timed out); cleared by the next one. */ + orcaProfileSignInEnd: OrcaCloudSignInEnd | null orcaProfilesMultiProfileUi: boolean orcaProfilesLoading: boolean orcaProfileSwitching: boolean @@ -41,6 +44,7 @@ export const createOrcaProfilesSlice: StateCreator Date: Tue, 10 Nov 2026 20:36:46 -0800 Subject: [PATCH 086/149] fix(cloud): the sign-in toast drops a stale button when a phase has none --- .../src/lib/orca-cloud/cloud-agent-not-started-toast.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.ts b/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.ts index 30024fddd20..1cd41968be2 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.ts @@ -168,6 +168,10 @@ export function showCloudAgentNotStartedToast( run: () => void globalThis.window?.api?.orcaCloudAgents?.start({ agent }) } } + if (!view.action) { + // Sonner keeps an updated toast's old button: drop it so a stale action can't linger. + toast.dismiss(TOAST_ID) + } toast.message(view.message, { id: TOAST_ID, ...(view.description ? { description: view.description } : {}), From df3d8e92084845c8587fc062c2b9137ccd045c03 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:40:04 -0800 Subject: [PATCH 087/149] fix(cloud): the sign-in toast always shows the current phase's button (Cancel / Open again) --- .../cloud-agent-not-started-toast.ts | 24 ++++++++++--------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.ts b/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.ts index 1cd41968be2..cfa1e02bdb4 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-agent-not-started-toast.ts @@ -80,18 +80,24 @@ export function cloudAgentSignInView( 'Finish signing in to {{agent}} in your browser…', { agent: name } ), - ...(setup.canReopen + // Every phase has a button: an updated toast keeps the last one otherwise. + action: setup.canReopen ? { - action: { - label: translate('orcaCloudAccounts.openAgain', 'Open again'), - run: () => void api?.reopen({ agent }) - } + label: translate('orcaCloudAccounts.openAgain', 'Open again'), + run: () => void api?.reopen({ agent }) + } + : { + label: translate('orcaCloudAccounts.cancel', 'Cancel'), + run: () => void api?.cancel({ agent }) } - : {}) } case 'preparing': return { - message: translate('orcaCloudAccounts.preparing', 'Getting ChatGPT sign-in ready') + message: translate('orcaCloudAccounts.preparing', 'Getting ChatGPT sign-in ready'), + action: { + label: translate('orcaCloudAccounts.cancel', 'Cancel'), + run: () => void api?.cancel({ agent }) + } } case 'device': return { @@ -168,10 +174,6 @@ export function showCloudAgentNotStartedToast( run: () => void globalThis.window?.api?.orcaCloudAgents?.start({ agent }) } } - if (!view.action) { - // Sonner keeps an updated toast's old button: drop it so a stale action can't linger. - toast.dismiss(TOAST_ID) - } toast.message(view.message, { id: TOAST_ID, ...(view.description ? { description: view.description } : {}), From fe7b20ec1571742b412ba1e4d0cc222086daf55f Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:40:13 -0800 Subject: [PATCH 088/149] fix(cloud-auth): pending Sign in reads Reopen browser and reopens the same link; no timeout toast while the inline note shows (design-squad) --- .../src/components/OrcaSignInProgress.tsx | 31 +++++++++-- .../orca/OrcaAccountSettingsPane.fixture.tsx | 35 +++++++++++- src/renderer/src/i18n/locales/en.json | 3 +- .../orca-cloud/sign-in-notice-visibility.ts | 19 +++++++ ...orca-profiles-auth-actions-timeout.test.ts | 55 +++++++++++++++++++ .../orca-profiles-auth-actions.ts | 5 +- 6 files changed, 137 insertions(+), 11 deletions(-) create mode 100644 src/renderer/src/lib/orca-cloud/sign-in-notice-visibility.ts create mode 100644 src/renderer/src/store/slices/orca-profiles/orca-profiles-auth-actions-timeout.test.ts diff --git a/src/renderer/src/components/OrcaSignInProgress.tsx b/src/renderer/src/components/OrcaSignInProgress.tsx index 7d196c2687e..55fcbd11d2d 100644 --- a/src/renderer/src/components/OrcaSignInProgress.tsx +++ b/src/renderer/src/components/OrcaSignInProgress.tsx @@ -1,5 +1,7 @@ -import { Loader2 } from 'lucide-react' +import { useEffect } from 'react' +import { ExternalLink, Loader2 } from 'lucide-react' import { toast } from 'sonner' +import { registerSignInNotice } from '@/lib/orca-cloud/sign-in-notice-visibility' import { Button } from './ui/button' import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' @@ -19,17 +21,34 @@ async function copySignInLink(link: string): Promise { } /** - * Stays clickable while a sign-in is pending: another click starts a fresh sign-in in the browser - * and replaces the pending one (main cancels it), so a closed or lost tab never strands the user. + * Never disabled by a pending sign-in, so a closed or lost tab can't strand the user. While the + * browser is out it reads "Reopen browser" and reopens the same sign-in link; otherwise a click + * starts a sign-in, replacing any pending one (main cancels it). */ export function OrcaSignInButton({ children, ...props }: Omit, 'onClick' | 'type'>): React.JSX.Element { + const t = useTranslate() const connect = useAppStore((state) => state.connectCurrentOrcaProfile) + const link = useAppStore((state) => state.orcaProfileSignInProgress?.link ?? null) + const onClick = (): void => { + if (!link) { + void connect() + return + } + void window.api.shell.openUrl(link).catch(() => void connect()) + } return ( - ) } @@ -47,6 +66,8 @@ export function OrcaSignInWaitNotice({ const progress = useAppStore((state) => state.orcaProfileSignInProgress) const timedOut = useAppStore((state) => state.orcaProfileSignInEnd === 'timed-out') const signedIn = useAppStore((state) => state.orcaProfileAuthStatus?.state === 'connected') + // While this is on screen a timeout is said here, not in a toast. + useEffect(() => registerSignInNotice(), []) if (!progress) { if (!timedOut || signedIn) { return null diff --git a/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.fixture.tsx b/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.fixture.tsx index 3c5a6bc38fe..623e53f1ad2 100644 --- a/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.fixture.tsx +++ b/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.fixture.tsx @@ -1,13 +1,27 @@ import { defineFixture } from '../../../../component-fixtures/component-fixture' -import type { OrcaProfileAuthStatus } from '../../../../../../shared/orca-profiles' +import type { + OrcaCloudSignInEnd, + OrcaCloudSignInProgress, + OrcaProfileAuthStatus +} from '../../../../../../shared/orca-profiles' import { OrcaAccountSettingsPane } from './OrcaAccountSettingsPane' const width = 760 -function pane(status: OrcaProfileAuthStatus) { +function pane( + status: OrcaProfileAuthStatus, + signIn: { + progress?: OrcaCloudSignInProgress | null + end?: OrcaCloudSignInEnd | null + } = {} +) { return defineFixture({ width, - store: { orcaProfileAuthStatus: status }, + store: { + orcaProfileAuthStatus: status, + orcaProfileSignInProgress: signIn.progress ?? null, + orcaProfileSignInEnd: signIn.end ?? null + }, // The pane re-reads auth status on mount; answer with the same state so the frame holds it. setup: () => { Object.assign(window.api.orcaProfiles, { authStatus: () => Promise.resolve(status) }) @@ -31,3 +45,18 @@ export const reconnectRequired = pane({ state: 'reconnect-required', persistence: 'encrypted' }) + +const signedOutStatus: OrcaProfileAuthStatus = { + activeProfileId: 'default', + configured: true, + state: 'local', + persistence: 'none' +} + +/** Waiting on the browser: the primary stays live as "Reopen browser"; the line offers Cancel. */ +export const signInPending = pane(signedOutStatus, { + progress: { link: 'https://auth.example/v1/desktop/auth/authorize?state=preview' } +}) + +/** The browser never came back: a calm inline note, and Sign in to Orca again. */ +export const signInTimedOut = pane(signedOutStatus, { end: 'timed-out' }) diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index d8f56eff789..6921fa2719b 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -20397,7 +20397,8 @@ "copyFailed": "Could not copy the link.", "signingIn": "Signing in…", "cancel": "Cancel", - "didNotFinish": "Sign-in didn’t finish. Try again." + "didNotFinish": "Sign-in didn’t finish. Try again.", + "reopenBrowser": "Reopen browser" }, "plainSshTerminal": { "open": "Open plain SSH terminal", diff --git a/src/renderer/src/lib/orca-cloud/sign-in-notice-visibility.ts b/src/renderer/src/lib/orca-cloud/sign-in-notice-visibility.ts new file mode 100644 index 00000000000..921f75a1d71 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/sign-in-notice-visibility.ts @@ -0,0 +1,19 @@ +// Whether an inline Orca sign-in notice is on screen. A sign-in that didn't finish is said inline +// where one is shown; the toast is only for sign-ins started from a surface without one. +let mounted = 0 + +/** Call from an inline notice's mount effect; the returned function unregisters it. */ +export function registerSignInNotice(): () => void { + mounted += 1 + let registered = true + return () => { + if (registered) { + registered = false + mounted -= 1 + } + } +} + +export function isSignInNoticeVisible(): boolean { + return mounted > 0 +} diff --git a/src/renderer/src/store/slices/orca-profiles/orca-profiles-auth-actions-timeout.test.ts b/src/renderer/src/store/slices/orca-profiles/orca-profiles-auth-actions-timeout.test.ts new file mode 100644 index 00000000000..d874665ad57 --- /dev/null +++ b/src/renderer/src/store/slices/orca-profiles/orca-profiles-auth-actions-timeout.test.ts @@ -0,0 +1,55 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { + ConnectCurrentOrcaProfileResult, + OrcaProfileAuthStatus +} from '../../../../../shared/orca-profiles' +import { registerSignInNotice } from '@/lib/orca-cloud/sign-in-notice-visibility' +import { createTestStore } from '../../testing/app-store-test-fixture' + +const { toastMock } = vi.hoisted(() => { + const toastMock = Object.assign(vi.fn(), { + error: vi.fn(), + info: vi.fn(), + success: vi.fn(), + warning: vi.fn() + }) + return { toastMock } +}) + +vi.mock('sonner', () => ({ toast: toastMock })) + +const signedOut: OrcaProfileAuthStatus = { + activeProfileId: 'local-default', + configured: true, + state: 'local', + persistence: 'none' +} +const timedOut: ConnectCurrentOrcaProfileResult = { status: 'timed-out', auth: signedOut } +const connectCurrent = vi.fn() + +describe('a sign-in that times out', () => { + beforeEach(() => { + vi.resetAllMocks() + vi.stubGlobal('window', { api: { orcaProfiles: { connectCurrent } } }) + connectCurrent.mockResolvedValue(timedOut) + }) + + it('says so calmly in a toast when no inline notice is on screen', async () => { + const store = createTestStore() + await store.getState().connectCurrentOrcaProfile() + expect(toastMock).toHaveBeenCalledWith('Sign-in didn’t finish. Try again.') + expect(toastMock.error).not.toHaveBeenCalled() + }) + + it('leaves it to the inline notice when one is on screen', async () => { + const unregister = registerSignInNotice() + try { + const store = createTestStore() + await store.getState().connectCurrentOrcaProfile() + expect(toastMock).not.toHaveBeenCalled() + expect(toastMock.error).not.toHaveBeenCalled() + } finally { + unregister() + } + }) +}) diff --git a/src/renderer/src/store/slices/orca-profiles/orca-profiles-auth-actions.ts b/src/renderer/src/store/slices/orca-profiles/orca-profiles-auth-actions.ts index f3c107b54d4..913fd4c684d 100644 --- a/src/renderer/src/store/slices/orca-profiles/orca-profiles-auth-actions.ts +++ b/src/renderer/src/store/slices/orca-profiles/orca-profiles-auth-actions.ts @@ -1,6 +1,7 @@ import type { StateCreator } from 'zustand' import { toast } from 'sonner' import { translate } from '@/i18n/i18n' +import { isSignInNoticeVisible } from '@/lib/orca-cloud/sign-in-notice-visibility' import type { ConnectCurrentOrcaProfileResult, CreateCloudLinkedOrcaProfileResult, @@ -108,8 +109,8 @@ export const createOrcaProfilesAuthActions: StateCreator< description: result.auth.setupMessage } ) - } else if (result.status === 'timed-out' && !alreadyConnected) { - // Calm, not an error: nothing broke, the browser just never came back. + } else if (result.status === 'timed-out' && !alreadyConnected && !isSignInNoticeVisible()) { + // Calm, not an error. Said inline where a sign-in notice is on screen; toast otherwise. toast( translate( 'auto.store.slices.orca.profiles.signInDidNotFinish', From abfc2c2808662aee8bbaf10398d432fd1bf90d44 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:40:29 -0800 Subject: [PATCH 089/149] =?UTF-8?q?fix(cloud):=20design-squad=20=E2=80=94?= =?UTF-8?q?=20W-number=20chip=20copies=20the=20workspace=20link=20only;=20?= =?UTF-8?q?ungrouped=20rows=20read=20'Other=20workspaces'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cloud-workspaces/CloudWorkspaceGroup.tsx | 2 +- .../cloud-workspaces/CloudWorkspaceNumberChip.tsx | 11 ++++------- .../use-cloud-workspace-arrangement.ts | 3 ++- src/renderer/src/i18n/locales/en.json | 3 ++- 4 files changed, 9 insertions(+), 10 deletions(-) diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceGroup.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceGroup.tsx index 712e2d735fb..583906a09d1 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceGroup.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceGroup.tsx @@ -85,7 +85,7 @@ export function CloudWorkspaceGroupView({ const label = group.kind === 'pinned' ? t('auto.components.cloudWorkspaces.pinned', 'Pinned') - : (group.section ?? t('auto.components.cloudWorkspaces.noSection', 'No section')) + : (group.section ?? t('auto.components.cloudWorkspaces.otherWorkspaces', 'Other workspaces')) const count = ( <> {/* The bare number is visual; screen readers get the counted phrase. */} diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceNumberChip.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceNumberChip.tsx index ba526b56884..d75f5a04133 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspaceNumberChip.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspaceNumberChip.tsx @@ -9,7 +9,6 @@ import { cn } from '@/lib/utils' import { useAppStore } from '@/store' import { formatWorkspaceNumber } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' import { sandboxIdForWorktree, useCloudWorkspaceIdentities } from './cloud-workspace-identity' -import { frontCloudChat } from './cloud-workspace-links' import { copyCloudWorkspaceLink } from './open-cloud-workspace' const COPIED_MS = 1_500 @@ -46,12 +45,10 @@ export function CloudWorkspaceNumberChip({
    @@ -71,3 +73,44 @@ export const fallback = defineFixture({ /> ) }) + +/** JA-22: each row says whether a cloud workspace can run it as-is (inside the open menu only). */ +// No status means ready (design-squad): Claude, OpenCode and Copilot carry none here. +const STATUS: ReadonlyMap = new Map([ + ['codex', 'Not set up'], + ['gemini', 'Not set up'], + ['cursor', 'Not set up'] +]) + +export const openWithStatus = defineFixture({ + width: 480, + render: () => , + interact: open +}) + +/** Closed: nothing changes on the button (Neil). */ +export const closedWithStatus = defineFixture({ + width: 480, + render: () => +}) + +/** Orca-account sign-in off here (prod today): Claude and Codex sign in per workspace. */ +export const openPerWorkspace = defineFixture({ + width: 480, + render: () => ( + ([ + ['claude', 'Signs in per workspace'], + ['codex', 'Signs in per workspace'], + ['opencode', 'Not set up'], + ['gemini', 'Not set up'], + ['cursor', 'Not set up'], + ['copilot', 'Not set up'] + ]) + } + /> + ), + interact: open +}) diff --git a/src/renderer/src/components/new-workspace/use-composer-quick-agent.ts b/src/renderer/src/components/new-workspace/use-composer-quick-agent.ts index e8d235303eb..90e0bacc709 100644 --- a/src/renderer/src/components/new-workspace/use-composer-quick-agent.ts +++ b/src/renderer/src/components/new-workspace/use-composer-quick-agent.ts @@ -1,4 +1,5 @@ import { useMemo } from 'react' +import { useOrcaCloudAgentPickerStatusLabels } from '@/lib/orca-cloud/orca-cloud-agent-picker-status' import { useAppStore } from '@/store/index' import { agentChoicePending } from '@/lib/host-chat-program' import { useAgentsOfferedForLaunch } from '@/lib/host-chat-program-acquisition' @@ -82,5 +83,7 @@ export function useComposerQuickAgent( // Orca Cloud adds nothing to the dialog (Neil): an agent it can't run falls back silently; the // picker shows what will start. const agentNotice: string | undefined = undefined - return { orcaCloud, orcaCloudModel, quickAgent, chipAgentIds, agentNotice } + // JA-22: inside the open menu only, which image agents a cloud workspace can run as-is. + const statusLabels = useOrcaCloudAgentPickerStatusLabels(orcaCloud) + return { orcaCloud, orcaCloudModel, quickAgent, chipAgentIds, agentNotice, statusLabels } } diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 5a71a0907a4..3c0a5fcb2a9 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -2325,6 +2325,12 @@ "menu": { "quitApp": "Quit {{appName}}" }, + "orcaCloudAgentPicker": { + "status": { + "ready": "Ready", + "setUp": "Set up" + } + }, "orcaCloudMove": { "confirm": { "changesCount_one": "{{count}} uncommitted change, plus untracked files", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index ec448c98c22..9b54c89ddbe 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -28086,5 +28086,14 @@ }, "untitled": "New cloud workspace", "waitingBrowser": "Waiting for your browser…" + }, + "orcaCloudAgentPicker": { + "status": { + "ready": "Ready", + "setUp": "Set up", + "perWorkspace": "Signs in per workspace", + "notAvailable": "Not available in cloud", + "notSetUp": "Not set up" + } } } diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-store.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-store.ts index 3da5ad97a35..e1b513c1132 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-store.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-agent-accounts-store.ts @@ -25,6 +25,8 @@ export type OrcaCloudAgentAccountsState = { load: OrcaCloudAgentAccountsLoad setups: OrcaCloudAgentSetups keyKinds: Record + /** Names (never values) of the Cloud secrets a new workspace gets; null until read (JA-22). */ + cloudSecretNames?: ReadonlySet | null /** The build sheet's R2 Set up: agents set up in turn; `index` is the one running now. */ queue: { agents: readonly OrcaCloudAccountAgent[]; index: number } } @@ -37,6 +39,7 @@ let state: OrcaCloudAgentAccountsState = { load: { kind: 'loading' }, setups: IDLE_ORCA_CLOUD_AGENT_SETUPS, keyKinds: NO_KEYS, + cloudSecretNames: null, queue: NO_QUEUE } // Set once the queued agent's setup has left idle, so idle afterwards means it finished. @@ -84,7 +87,10 @@ export async function reloadOrcaCloudAgentAccounts(): Promise { : result.error === 'not_configured' ? { kind: 'unavailable' } : { kind: 'failed', error: result.error }, - keyKinds: effective?.ok ? agentKeyKinds(effective.value.secrets) : state.keyKinds + keyKinds: effective?.ok ? agentKeyKinds(effective.value.secrets) : state.keyKinds, + cloudSecretNames: effective?.ok + ? new Set(effective.value.secrets.map((secret) => secret.name)) + : state.cloudSecretNames }) } diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-agent-picker-status.test.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-agent-picker-status.test.ts new file mode 100644 index 00000000000..cbc466e9207 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-agent-picker-status.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from 'vitest' +import type { OrcaCloudAgentsStatus } from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' +import type { Translate } from '@/i18n/use-translate' +import type { OrcaCloudAgentAccountsRead } from './orca-cloud-agent-accounts-model' +import { + orcaCloudAgentPickerStatus, + orcaCloudAgentPickerStatusLabel +} from './orca-cloud-agent-picker-status' + +function status(patch: Partial = {}): OrcaCloudAgentsStatus { + return { + credentials: { + claude: { state: 'none' }, + codex: { state: 'none' }, + providerEnabled: { claude: true, codex: true }, + ...patch + }, + sources: { defaults: {}, coveredByKey: { claude: false, codex: false } } + } +} + +function accounts( + load: OrcaCloudAgentAccountsRead['load'], + names: string[] | null = [] +): OrcaCloudAgentAccountsRead & { cloudSecretNames: ReadonlySet | null } { + return { + load, + keyKinds: { claude: null, codex: null }, + cloudSecretNames: names ? new Set(names) : null + } +} + +describe('orcaCloudAgentPickerStatus (JA-22)', () => { + it('shows nothing until the account is read', () => { + expect(orcaCloudAgentPickerStatus('claude', accounts({ kind: 'loading' }))).toBeNull() + expect(orcaCloudAgentPickerStatus('gemini', accounts({ kind: 'loading' }, null))).toBeNull() + }) + + it('reads Claude and Codex from the Orca account', () => { + const ready = accounts({ kind: 'ready', status: status({ claude: { state: 'active' } }) }) + expect(orcaCloudAgentPickerStatus('claude', ready)).toBe('ready') + expect(orcaCloudAgentPickerStatus('codex', ready)).toBe('setUp') + const expired = accounts({ kind: 'ready', status: status({ claude: { state: 'expired' } }) }) + expect(orcaCloudAgentPickerStatus('claude', expired)).toBe('setUp') + }) + + it('says a paused or never-offered provider signs in per workspace, never "Set up"', () => { + const off = accounts({ + kind: 'ready', + status: status({ + providerEnabled: { claude: false, codex: false }, + providerState: { claude: 'off', codex: 'disabled' } + }) + }) + expect(orcaCloudAgentPickerStatus('claude', off)).toBe('perWorkspace') + expect(orcaCloudAgentPickerStatus('codex', off)).toBe('perWorkspace') + }) + + it('reads API-key agents from Cloud secret names only', () => { + const load = { kind: 'ready', status: status() } as const + expect(orcaCloudAgentPickerStatus('gemini', accounts(load, ['GOOGLE_API_KEY']))).toBe('ready') + expect(orcaCloudAgentPickerStatus('cursor', accounts(load, ['GOOGLE_API_KEY']))).toBe('setUp') + expect(orcaCloudAgentPickerStatus('copilot', accounts(load, ['COPILOT_GITHUB_TOKEN']))).toBe( + 'ready' + ) + expect(orcaCloudAgentPickerStatus('opencode', accounts(load, ['OPENAI_API_KEY']))).toBe('ready') + expect(orcaCloudAgentPickerStatus('opencode', accounts(load, []))).toBe('setUp') + }) + + it('marks agents the image does not ship', () => { + expect(orcaCloudAgentPickerStatus('aider', accounts({ kind: 'loading' }))).toBe('notAvailable') + }) +}) + +describe('orcaCloudAgentPickerStatusLabel (JA-22)', () => { + const t: Translate = (_key, fallback) => fallback + it('says nothing for ready and names the state otherwise', () => { + expect(orcaCloudAgentPickerStatusLabel('ready', t)).toBeNull() + expect(orcaCloudAgentPickerStatusLabel('setUp', t)).toBe('Not set up') + expect(orcaCloudAgentPickerStatusLabel('perWorkspace', t)).toBe('Signs in per workspace') + }) +}) diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-agent-picker-status.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-agent-picker-status.ts new file mode 100644 index 00000000000..d6c8a43726a --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-agent-picker-status.ts @@ -0,0 +1,117 @@ +// JA-22: the status suffix each agent row shows inside the open agent picker when Run on is Orca +// Cloud. Claude and Codex read the Orca account coverage (the shared selector); the API-key agents +// read whether a Cloud secret they use exists. Names only: no secret value ever reaches here. +import { useMemo } from 'react' +import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' +import { + ORCA_CLOUD_IMAGE_AGENTS, + isOrcaCloudImageAgent +} from '../../../../shared/hosted-sandbox/orca-cloud-image-agents' +import { + orcaCloudAgentCoverageFromAccounts, + type OrcaCloudAgentAccountsRead +} from './orca-cloud-agent-accounts-model' +import { useTranslate, type Translate } from '@/i18n/use-translate' +import { useOrcaCloudAgentAccounts } from './orca-cloud-agent-accounts-store' + +export type OrcaCloudAgentPickerStatus = + /** A new cloud workspace can run it with nothing more to do. */ + | 'ready' + /** Not set up yet: the Orca account (Claude, Codex) or a key in Cloud secrets. */ + | 'setUp' + /** Orca-account sign-in is off or paused here: the agent signs in inside each workspace. */ + | 'perWorkspace' + /** The Orca Cloud image doesn't ship it. */ + | 'notAvailable' + +/** + * Cloud secrets that make each API-key agent work in a cloud workspace. Copilot and Cursor read + * their own token; Gemini its Google key; OpenCode any model provider key it supports. + */ +const API_KEY_AGENT_NAMES: Partial> = { + copilot: ['COPILOT_GITHUB_TOKEN', 'COPILOT_PROVIDER_API_KEY', 'COPILOT_PROVIDER_BEARER_TOKEN'], + cursor: ['CURSOR_API_KEY'], + gemini: ['GEMINI_API_KEY', 'GOOGLE_API_KEY', 'GOOGLE_GENERATIVE_AI_API_KEY'], + opencode: [ + 'ANTHROPIC_API_KEY', + 'OPENAI_API_KEY', + 'GEMINI_API_KEY', + 'GOOGLE_GENERATIVE_AI_API_KEY', + 'AI_GATEWAY_API_KEY', + 'OPENROUTER_API_KEY', + 'GROQ_API_KEY', + 'XAI_API_KEY', + 'MISTRAL_API_KEY', + 'DEEPSEEK_API_KEY' + ] +} + +/** Null while the account or Cloud secrets aren't read yet, so the row shows no suffix. */ +export function orcaCloudAgentPickerStatus( + agent: TuiAgent, + accounts: OrcaCloudAgentAccountsRead & { cloudSecretNames?: ReadonlySet | null } +): OrcaCloudAgentPickerStatus | null { + if (!isOrcaCloudImageAgent(agent)) { + return 'notAvailable' + } + if (agent === 'claude' || agent === 'codex') { + const coverage = orcaCloudAgentCoverageFromAccounts(agent, accounts) + switch (coverage?.kind) { + case undefined: + return null + case 'account': + case 'key': + return 'ready' + case 'notSetUp': + case 'expired': + return 'setUp' + case 'killSwitch': + case 'unavailable': + return 'perWorkspace' + } + } + const names = accounts.cloudSecretNames ?? null + if (!names) { + return null + } + return (API_KEY_AGENT_NAMES[agent] ?? []).some((name) => names.has(name)) ? 'ready' : 'setUp' +} + +/** The muted suffix; null for 'ready' (no status means ready, design-squad JA-22). */ +export function orcaCloudAgentPickerStatusLabel( + status: OrcaCloudAgentPickerStatus, + t: Translate +): string | null { + switch (status) { + case 'ready': + return null + case 'setUp': + return t('orcaCloudAgentPicker.status.notSetUp', 'Not set up') + case 'perWorkspace': + return t('orcaCloudAgentPicker.status.perWorkspace', 'Signs in per workspace') + case 'notAvailable': + return t('orcaCloudAgentPicker.status.notAvailable', 'Not available in cloud') + } +} + +/** Status labels for the image agents while Run on is Orca Cloud; undefined otherwise. */ +export function useOrcaCloudAgentPickerStatusLabels( + enabled: boolean +): ReadonlyMap | undefined { + const t = useTranslate() + const accounts = useOrcaCloudAgentAccounts(enabled) + return useMemo(() => { + if (!enabled) { + return undefined + } + const labels = new Map() + for (const agent of ORCA_CLOUD_IMAGE_AGENTS) { + const status = orcaCloudAgentPickerStatus(agent, accounts) + const label = status ? orcaCloudAgentPickerStatusLabel(status, t) : null + if (label) { + labels.set(agent, label) + } + } + return labels + }, [enabled, accounts, t]) +} From 3aec8991bf4345fd0ab0b2924277c9fb5bb109cc Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:46:19 -0800 Subject: [PATCH 093/149] fix(sleep): sleep keeps every tab in place, same order and active tab; pages reload when shown after wake (NEW-01) --- .../orca-cloud/OrcaCloudWorkspaceSurface.tsx | 2 - .../project-move-pause-follower.test.ts | 13 +++- .../sleep/workspace-sleep-follower.ts | 15 ++-- .../desktop-sleep-reopen.test.ts | 74 ------------------- .../desktop-sleep-reopen.ts | 48 ------------ .../open-cloud-remote-desktop.tsx | 17 ----- 6 files changed, 20 insertions(+), 149 deletions(-) delete mode 100644 src/renderer/src/lib/cloud-remote-desktop/desktop-sleep-reopen.test.ts delete mode 100644 src/renderer/src/lib/cloud-remote-desktop/desktop-sleep-reopen.ts diff --git a/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx b/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx index f2223d64523..7b3116d044c 100644 --- a/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx +++ b/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx @@ -1,4 +1,3 @@ -import { useReopenRemoteDesktopAfterWake } from '@/lib/cloud-remote-desktop/desktop-sleep-reopen' import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' import { toast } from 'sonner' import { useAppStore } from '@/store' @@ -224,7 +223,6 @@ function useInertSiblings(cover: React.RefObject, active: bo function CloudSurface({ workspaceId }: { workspaceId: string }): React.JSX.Element | null { const t = useTranslate() const view = useCloudWorkspaceView(workspaceId) - useReopenRemoteDesktopAfterWake(workspaceId, view.state === 'running') const name = useAppStore((state) => findWorktreeById(state, workspaceId)?.displayName ?? null) // Ready means the server answers; the pill stays ("Connecting…") until the pane in front has // re-attached and can take keys. diff --git a/src/renderer/src/components/sidebar/project-move-pause-follower.test.ts b/src/renderer/src/components/sidebar/project-move-pause-follower.test.ts index 8a5776cdf3a..f42f7b6c13d 100644 --- a/src/renderer/src/components/sidebar/project-move-pause-follower.test.ts +++ b/src/renderer/src/components/sidebar/project-move-pause-follower.test.ts @@ -11,6 +11,8 @@ const mocks = vi.hoisted(() => { activeWorktreeId: null, setActiveWorktree: vi.fn(), shutdownWorktreeBrowsers: vi.fn(), + browserTabsByWorktree: {}, + browserPagesByWorkspace: {}, shutdownWorktreeTerminals: vi.fn(), tabsByWorktree, ptyIdsByTabId, @@ -18,9 +20,14 @@ const mocks = vi.hoisted(() => { detectedWorktreesByRepo: {} }, persist: vi.fn(async () => {}), - payload: vi.fn(() => ({})) + payload: vi.fn(() => ({})), + evictGuests: vi.fn() } }) +vi.mock('@/store/slices/browser/cleanup/browser-webview-cleanup', () => ({ + destroyWorktreeBrowserGuests: (_tabs: unknown, _pages: unknown, worktreeId: string) => + mocks.evictGuests(worktreeId) +})) vi.mock('@/store', () => ({ useAppStore: { getState: () => mocks.state, subscribe: () => () => {} } })) @@ -203,7 +210,9 @@ describe('project move renderer completion', () => { records: [] }) await f.persist() - expect(mocks.state.shutdownWorktreeBrowsers).toHaveBeenCalledWith('wt') + // Sleep keeps the tabs (NEW-01); only their pages are dropped. + expect(mocks.state.shutdownWorktreeBrowsers).not.toHaveBeenCalled() + expect(mocks.evictGuests).toHaveBeenCalledWith('wt') expect(f.responses.at(-1)).toMatchObject({ phase: 'error', error: 'project_move_pause_sleep_superseded' diff --git a/src/renderer/src/components/sidebar/workspace-actions/sleep/workspace-sleep-follower.ts b/src/renderer/src/components/sidebar/workspace-actions/sleep/workspace-sleep-follower.ts index ba14d165b55..bb771acf502 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/sleep/workspace-sleep-follower.ts +++ b/src/renderer/src/components/sidebar/workspace-actions/sleep/workspace-sleep-follower.ts @@ -1,5 +1,5 @@ import { useAppStore } from '@/store' -import { noteRemoteDesktopBeforeSleep } from '@/lib/cloud-remote-desktop/desktop-sleep-reopen' +import { destroyWorktreeBrowserGuests } from '@/store/slices/browser/cleanup/browser-webview-cleanup' import { captureWorkspaceSelection, restoreWorkspaceSelection, @@ -56,10 +56,6 @@ export function followWorkspaceSleep( const state = useAppStore.getState() const wasActive = state.activeWorktreeId === worktreeId const selectionBeforeSleep = wasActive ? captureWorkspaceSelection(state) : null - if (!options.keepBrowserTabs) { - // Before the selection clears: whether the desktop tab was in front decides how it comes back. - noteRemoteDesktopBeforeSleep(worktreeId) - } // Why first: clearing the active workspace unmounts its panes, whose exits must not stamp activity. markWorktreeSleepIntent(worktreeId) if (wasActive) { @@ -68,7 +64,14 @@ export function followWorkspaceSleep( restoreSidebarPosition() } if (!options.keepBrowserTabs) { - state.shutdownWorktreeBrowsers(worktreeId) + // Sleep never changes the tab layout (NEW-01): the tabs, their order and the active one stay; + // only their pages are dropped to free memory, and each reloads in place when shown after + // the wake. A remote desktop tab reconnects itself the same way (its chrome). + destroyWorktreeBrowserGuests( + state.browserTabsByWorktree, + state.browserPagesByWorkspace, + worktreeId + ) } let settle!: (stop: HostTerminalStop) => void const hostStop = new Promise((resolve) => (settle = resolve)) diff --git a/src/renderer/src/lib/cloud-remote-desktop/desktop-sleep-reopen.test.ts b/src/renderer/src/lib/cloud-remote-desktop/desktop-sleep-reopen.test.ts deleted file mode 100644 index aae8d67601d..00000000000 --- a/src/renderer/src/lib/cloud-remote-desktop/desktop-sleep-reopen.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const DESKTOP = 'http://localhost:6080/vnc.html?autoconnect=0&reconnect=0&resize=remote' -let state: Record = {} -const reopen = vi.fn(async () => {}) - -vi.mock('@/store', () => ({ useAppStore: { getState: () => state } })) -vi.mock('@/lib/workspace/ownership/workspace-runtime-environment', () => ({ - selectWorkspaceRuntimeEnvironmentId: () => 'env-1', - useWorkspaceRuntimeEnvironmentId: () => 'env-1' -})) -vi.mock('./open-cloud-remote-desktop', () => ({ - reopenCloudRemoteDesktopQuietly: reopen, - openCloudRemoteDesktop: vi.fn() -})) -vi.mock('react', () => ({ - useEffect: (fn: () => void) => fn(), - useMemo: (fn: () => unknown) => fn() -})) - -const { - hasRemoteDesktopToReopen, - noteRemoteDesktopBeforeSleep, - resetRemoteDesktopSleepReopenForTest, - useReopenRemoteDesktopAfterWake -} = await import('./desktop-sleep-reopen') - -describe('remote desktop across sleep', () => { - beforeEach(() => { - resetRemoteDesktopSleepReopenForTest() - reopen.mockClear() - }) - - it('remembers a desktop tab that sleep closes and reopens it once the workspace runs', () => { - state = { - activeWorktreeId: 'w1', - activeTabType: 'browser', - activeBrowserTabId: 'tab-d', - browserTabsByWorktree: { - w1: [ - { id: 'tab-b', url: 'https://example.com' }, - { id: 'tab-d', url: DESKTOP } - ] - } - } - noteRemoteDesktopBeforeSleep('w1') - expect(hasRemoteDesktopToReopen('w1')).toBe(true) - useReopenRemoteDesktopAfterWake('w1', false) - expect(reopen).not.toHaveBeenCalled() - useReopenRemoteDesktopAfterWake('w1', true) - expect(reopen).toHaveBeenCalledWith('w1', 'env-1', true) - // Once only. - useReopenRemoteDesktopAfterWake('w1', true) - expect(reopen).toHaveBeenCalledTimes(1) - }) - - it('reopens a desktop that was behind another tab without bringing it to the front', () => { - state = { - activeWorktreeId: 'w1', - activeTabType: 'terminal', - activeBrowserTabId: null, - browserTabsByWorktree: { w1: [{ id: 'tab-d', url: DESKTOP }] } - } - noteRemoteDesktopBeforeSleep('w1') - useReopenRemoteDesktopAfterWake('w1', true) - expect(reopen).toHaveBeenCalledWith('w1', 'env-1', false) - }) - - it('does nothing for a workspace without a desktop tab', () => { - state = { browserTabsByWorktree: { w1: [{ id: 'tab-b', url: 'http://localhost:3000/' }] } } - noteRemoteDesktopBeforeSleep('w1') - expect(hasRemoteDesktopToReopen('w1')).toBe(false) - }) -}) diff --git a/src/renderer/src/lib/cloud-remote-desktop/desktop-sleep-reopen.ts b/src/renderer/src/lib/cloud-remote-desktop/desktop-sleep-reopen.ts deleted file mode 100644 index 266971a9600..00000000000 --- a/src/renderer/src/lib/cloud-remote-desktop/desktop-sleep-reopen.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { useEffect } from 'react' -import { useAppStore } from '@/store' -import { selectWorkspaceRuntimeEnvironmentId } from '@/lib/workspace/ownership/workspace-runtime-environment' -import { selectRemoteDesktopTabId } from './remote-desktop-tab' -import { reopenCloudRemoteDesktopQuietly } from './open-cloud-remote-desktop' - -// Sleep closes a workspace's browser tabs (workspace-sleep-follower.ts), and the desktop's processes -// stop with the sandbox anyway. A remote desktop tab is remembered here and comes back on its own -// once the workspace is awake, in front again if it was in front. -const sleptWithDesktop = new Map() - -/** Call before sleep tears down the workspace's browser tabs. */ -export function noteRemoteDesktopBeforeSleep(worktreeId: string): void { - const state = useAppStore.getState() - const tabId = selectRemoteDesktopTabId(state, worktreeId) - if (!tabId) { - return - } - sleptWithDesktop.set(worktreeId, { - wasInFront: - state.activeWorktreeId === worktreeId && - state.activeTabType === 'browser' && - state.activeBrowserTabId === tabId - }) -} - -/** Reopens it when the workspace is running again (mounted for the workspace on screen). */ -export function useReopenRemoteDesktopAfterWake(worktreeId: string, running: boolean): void { - useEffect(() => { - const entry = running ? sleptWithDesktop.get(worktreeId) : undefined - if (!entry) { - return - } - sleptWithDesktop.delete(worktreeId) - const environmentId = selectWorkspaceRuntimeEnvironmentId(useAppStore.getState(), worktreeId) - if (environmentId) { - void reopenCloudRemoteDesktopQuietly(worktreeId, environmentId, entry.wasInFront) - } - }, [running, worktreeId]) -} - -export function hasRemoteDesktopToReopen(worktreeId: string): boolean { - return sleptWithDesktop.has(worktreeId) -} - -export function resetRemoteDesktopSleepReopenForTest(): void { - sleptWithDesktop.clear() -} diff --git a/src/renderer/src/lib/cloud-remote-desktop/open-cloud-remote-desktop.tsx b/src/renderer/src/lib/cloud-remote-desktop/open-cloud-remote-desktop.tsx index 3a7d9d69887..61a460b0adc 100644 --- a/src/renderer/src/lib/cloud-remote-desktop/open-cloud-remote-desktop.tsx +++ b/src/renderer/src/lib/cloud-remote-desktop/open-cloud-remote-desktop.tsx @@ -139,23 +139,6 @@ function showDesktopTab( }) } -/** - * Reopens a desktop tab that sleep closed, once the workspace is awake again: no toasts (the tab's - * own state says how it goes) and it only comes to the front if it was in front when it slept. - */ -export function reopenCloudRemoteDesktopQuietly( - worktreeId: string, - environmentId: string, - activate: boolean -): Promise { - return exclusive(worktreeId, async () => { - const result = await requestCloudRemoteDesktop(environmentId) - if (result.ok) { - showDesktopTab(worktreeId, environmentId, result.url, activate) - } - }) -} - /** One open or wake at a time per workspace: a second click while one runs does nothing. */ async function exclusive(worktreeId: string, work: () => Promise): Promise { if (typeof window.api?.ephemeralVm?.openCloudRemoteDesktop !== 'function') { From af0fab19f84227fb3f0a70f6f4b981f71e4ec332 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:47:18 -0800 Subject: [PATCH 094/149] fix(cloud-routines): Run now button matches the run's status; drop redundant queued line; 'just now' --- .../settings/cloud-api/CloudRoutineRow.tsx | 32 +++++++---------- .../cloud-api/CloudRoutinesView.fixture.tsx | 35 +++++++++++++++++++ .../cloud-api/cloud-api-format.test.ts | 10 ++++++ .../settings/cloud-api/cloud-api-format.ts | 4 +++ src/renderer/src/i18n/locales/en.json | 2 -- 5 files changed, 61 insertions(+), 22 deletions(-) diff --git a/src/renderer/src/components/settings/cloud-api/CloudRoutineRow.tsx b/src/renderer/src/components/settings/cloud-api/CloudRoutineRow.tsx index af301a4084e..aad30e0e498 100644 --- a/src/renderer/src/components/settings/cloud-api/CloudRoutineRow.tsx +++ b/src/renderer/src/components/settings/cloud-api/CloudRoutineRow.tsx @@ -127,17 +127,14 @@ export function RoutineRow({ setNotice(null) const failure = await onRunNow() setRunning(false) - setNotice( - failure - ? { tone: 'error', text: failure } - : { - tone: 'ok', - text: t( - 'auto.components.settings.cloudRoutines.queued', - 'Run queued. It shows up in the history below.' - ) - } - ) + if (failure) { + setNotice({ tone: 'error', text: failure }) + return + } + // The new run's status lives in the pill and the history; open the history so it is in view. + if (!expanded) { + onToggleHistory() + } } return ( @@ -218,7 +215,7 @@ export function RoutineRow({ variant="ghost" size="xs" aria-disabled={running && !active} - aria-busy={running || active} + aria-busy={running} aria-expanded={active ? expanded : undefined} aria-controls={active ? historyId : undefined} onClick={() => void runNow()} @@ -246,14 +243,9 @@ export function RoutineRow({ : undefined } > - {running || active ? ( - - ) : ( - - )} - {active - ? t('auto.components.settings.cloudRoutines.runningNow', 'Running…') - : t('auto.components.settings.cloudRoutines.runNow', 'Run now')} + {/* Spins only while the request is in flight; the run's own status is the pill's job. */} + {running ? : } + {t('auto.components.settings.cloudRoutines.runNow', 'Run now')} diff --git a/src/renderer/src/components/settings/cloud-api/CloudRoutinesView.fixture.tsx b/src/renderer/src/components/settings/cloud-api/CloudRoutinesView.fixture.tsx index 6bb25768433..44422f66bdc 100644 --- a/src/renderer/src/components/settings/cloud-api/CloudRoutinesView.fixture.tsx +++ b/src/renderer/src/components/settings/cloud-api/CloudRoutinesView.fixture.tsx @@ -283,6 +283,41 @@ export const runHistory = defineFixture({ render: () => }) +/** Right after Run now: the pill and history say Queued; the button is back to Run now. */ +export const justQueued = defineFixture({ + width: 820, + render: () => ( + + r.id === 'rt_triage' + ? { ...r, lastRun: { id: 'run_q', status: 'queued', finishedAt: null } } + : r + ) + }} + loadRuns={async () => ({ + ok: true, + data: { + runs: [ + run({ + id: 'run_q', + status: 'queued', + trigger: 'manual', + createdAt: NOW - 3_000, + startedAt: null + }), + ...RUNS.runs.slice(1) + ], + nextBefore: null + } + })} + initial={{ historyFor: 'rt_triage' }} + /> + ) +}) + export const runHistoryEmpty = defineFixture({ width: 820, render: () => ( diff --git a/src/renderer/src/components/settings/cloud-api/cloud-api-format.test.ts b/src/renderer/src/components/settings/cloud-api/cloud-api-format.test.ts index 38137b52967..86ef124bba5 100644 --- a/src/renderer/src/components/settings/cloud-api/cloud-api-format.test.ts +++ b/src/renderer/src/components/settings/cloud-api/cloud-api-format.test.ts @@ -10,6 +10,7 @@ import { describeRoutineTrigger, formatCountdown, formatKeyPrefix, + formatRelativeFromNow, formatRunDuration, presetForScopes, scopesForPreset, @@ -65,6 +66,15 @@ describe('formatting', () => { ).toMatch(/^Weekdays at 9:00.* E[SD]T$/) }) + it('says "just now" for the last minute, not "this minute"', () => { + const now = 1_000_000_000 + expect(formatRelativeFromNow(now - 3_000, now, 'en')).toBe('just now') + expect(formatRelativeFromNow(now - 59_000, now, 'en')).toBe('just now') + expect(formatRelativeFromNow(now - 5 * 60_000, now, 'en')).toBe('5 minutes ago') + // Future times (next scheduled run) keep Intl wording. + expect(formatRelativeFromNow(now + 10 * 60_000, now, 'en')).toBe('in 10 minutes') + }) + it('offers the local zone first', () => { const zones = timeZoneOptions('Asia/Tokyo') expect(zones[0]).toBe('Asia/Tokyo') diff --git a/src/renderer/src/components/settings/cloud-api/cloud-api-format.ts b/src/renderer/src/components/settings/cloud-api/cloud-api-format.ts index daa7e17d258..15b98d6df4c 100644 --- a/src/renderer/src/components/settings/cloud-api/cloud-api-format.ts +++ b/src/renderer/src/components/settings/cloud-api/cloud-api-format.ts @@ -51,6 +51,10 @@ export function formatKeyPrefix(prefix: string): string { } export function formatRelativeFromNow(timestamp: number, now: number, intlLocale?: string): string { + // Under a minute ago reads "just now", like the other cloud screens (not Intl's "this minute"). + if (timestamp <= now && now - timestamp < 60_000) { + return translate('auto.components.cloudWorkspaces.justNow', 'just now') + } return formatUiRelativeTime(timestamp - now, intlLocale) } diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 3193a98dc26..48c095bcc1b 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -14599,7 +14599,6 @@ "sectionDescription": "For the Orca Cloud API, the orca CLI and MCP clients. Claude or Codex keys go in Cloud secrets." }, "cloudRoutines": { - "queued": "Run queued. It shows up in the history below.", "pausedSr": "(paused)", "createdByPerson": "by ", "lastRun": "Last run:", @@ -14608,7 +14607,6 @@ "runningShowHistory": "{{routineName}} is running. Show run history", "runNowLabel": "Run {{routineName}} now", "alreadyRunning": "A run is already in progress.", - "runningNow": "Running…", "runNow": "Run now", "more": "More actions for {{routineName}}", "hideHistory": "Hide run history", From 6d3919f4d25e697525f8889680fb800ca5eba062 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:50:52 -0800 Subject: [PATCH 095/149] test(cloud): type the cleanup mock --- src/renderer/src/lib/ephemeral-vm-worktree-creation.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/renderer/src/lib/ephemeral-vm-worktree-creation.test.ts b/src/renderer/src/lib/ephemeral-vm-worktree-creation.test.ts index f94f1ffff1e..0229515e9b3 100644 --- a/src/renderer/src/lib/ephemeral-vm-worktree-creation.test.ts +++ b/src/renderer/src/lib/ephemeral-vm-worktree-creation.test.ts @@ -17,7 +17,7 @@ const { state, gate, cleanup, retry } = vi.hoisted(() => { ] }, gate: vi.fn(), - cleanup: vi.fn(async () => true), + cleanup: vi.fn(async (_request: unknown, _actions?: unknown) => true), retry: vi.fn() } }) From 1c013ed270a9e1d5d97e3a86f1083dffb18c0b43 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:51:15 -0800 Subject: [PATCH 096/149] wip(sidebar): one cloud glyph from the start, no Local Mac chip, no name twice (JA-13, NP-5) --- .../orca-cloud/CloudWorkspaceMarkSlot.tsx | 35 +++++++++++++++++-- .../template/default-workspace-card.json | 4 +-- 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/src/renderer/src/components/orca-cloud/CloudWorkspaceMarkSlot.tsx b/src/renderer/src/components/orca-cloud/CloudWorkspaceMarkSlot.tsx index 4b49ca14368..783b9563ce3 100644 --- a/src/renderer/src/components/orca-cloud/CloudWorkspaceMarkSlot.tsx +++ b/src/renderer/src/components/orca-cloud/CloudWorkspaceMarkSlot.tsx @@ -1,7 +1,26 @@ -import React from 'react' -import { useIsCloudWorkspace } from '@/lib/orca-cloud/orca-cloud-workspace-store' +import React, { useEffect } from 'react' +import { useAppStore } from '@/store' +import { HostGlyph } from '@/components/host-row-icon' +import { + refreshCloudWorkspaceIds, + useIsCloudWorkspace +} from '@/lib/orca-cloud/orca-cloud-workspace-store' +import { isOrcaCloudRuntimeEnvironment } from '../../../../shared/remote-runtime/host-catalog/orca-cloud-environment-name' import { CloudWorkspaceMark } from './CloudWorkspaceMark' +/** The workspace's VM server is an Orca Cloud sandbox: known before the cloud id list catches up. */ +function useRunsOnOrcaCloudSandbox(workspaceId: string): boolean { + return useAppStore((state) => { + const environmentId = + state.ephemeralVmRuntimesByWorkspaceId?.[workspaceId]?.runtimeEnvironmentId + if (!environmentId) { + return false + } + const environment = state.runtimeEnvironments.find((entry) => entry.id === environmentId) + return environment ? isOrcaCloudRuntimeEnvironment(environment) : false + }) +} + /** The card's host mark slot: Orca Cloud workspaces get the live cloud mark, others the fallback. */ export function CloudWorkspaceMarkSlot({ workspaceId, @@ -13,6 +32,18 @@ export function CloudWorkspaceMarkSlot({ onPointerDown?: React.PointerEventHandler }): React.JSX.Element | null { const isCloud = useIsCloudWorkspace(workspaceId) + const onCloudSandbox = useRunsOnOrcaCloudSandbox(workspaceId) + const awaitingId = onCloudSandbox && !isCloud + // A new workspace joins the cloud id list on the next poll; ask now so its live mark arrives. + useEffect(() => { + if (awaitingId) { + void refreshCloudWorkspaceIds() + } + }, [awaitingId]) + if (awaitingId) { + // One glyph from the pending row on (NP-5): the cloud, never the server icon in between. + return + } if (!isCloud) { return <>{fallback} } diff --git a/src/renderer/src/components/sidebar/workspace-card/template/default-workspace-card.json b/src/renderer/src/components/sidebar/workspace-card/template/default-workspace-card.json index e5cfcd52455..35568a74f6f 100644 --- a/src/renderer/src/components/sidebar/workspace-card/template/default-workspace-card.json +++ b/src/renderer/src/components/sidebar/workspace-card/template/default-workspace-card.json @@ -9,12 +9,12 @@ "pinnedRepo": "place.inPinnedSection && repo != null && !place.showProjectName", "inlineRepo": "!vars.classic && repo != null && !place.hideRepoBadge && !vars.folder && !vars.pinnedRepo", "metaRepo": "vars.classic && repo != null && !place.hideRepoBadge && !vars.pinnedRepo", - "hostLabel": "options.show.host ? host.contextLabel : null", + "hostLabel": "options.show.host && host.kind != 'local' ? host.contextLabel : null", "hostBadge": "vars.hostLabel != null && (!vars.compact || place.showProjectName)", "metaRow": "!vars.compact", "detachedInMeta": "vars.metaRow && !vars.folder && ws.detachedHead", "branch": "!vars.folder && len(ws.branch) > 0 && !vars.newStyle && (!vars.compact || ws.branch != ws.name)", - "identityInMeta": "vars.newStyle && options.show.branch && ws.identity != null", + "identityInMeta": "vars.newStyle && options.show.branch && ws.identity != null && ws.identity != trim(ws.title)", "folderInMeta": "vars.newStyle ? options.show.branch && vars.folder && ws.identity != null : vars.folder", "conflict": "git.conflictOperation == 'cherry-pick'", "hasComment": "len(trim(ws.comment)) > 0", From 612269c105a28d067e4f5538e5eabb3caa5a5317 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:51:23 -0800 Subject: [PATCH 097/149] fix(billing): remove the overage item on opt-out once nothing is left to invoice Opting out left the metered overage item on the Stripe subscription, so every later invoice carried a '0 std hour x Orca sandbox overage' $0 line (confirmed on a throwaway test-mode subscription). The item now comes off at once when nothing was metered this Stripe period, or at the first sync after the period rolls over when there is usage still to invoice. Re-opting in within 24h got the removed item's id replayed by Stripe idempotency (also confirmed live); the add now retries under a key naming the removed item. Nothing meters while opted out or with a $0 cap. --- cloud/apps/billing/src/overage.ts | 54 ++++++++++- cloud/apps/billing/src/store.ts | 12 +++ cloud/apps/billing/src/stripe.ts | 5 +- cloud/apps/billing/src/webhook.ts | 12 ++- .../apps/billing/test/overage-opt-out.test.ts | 97 +++++++++++++++++++ 5 files changed, 173 insertions(+), 7 deletions(-) create mode 100644 cloud/apps/billing/test/overage-opt-out.test.ts diff --git a/cloud/apps/billing/src/overage.ts b/cloud/apps/billing/src/overage.ts index 590e00f1d1f..13a24cb725d 100644 --- a/cloud/apps/billing/src/overage.ts +++ b/cloud/apps/billing/src/overage.ts @@ -2,14 +2,23 @@ // Opting in puts exactly one metered overage item, at STRIPE_PRICE_OVERAGE, on the Stripe // subscription: an item still on an older overage price is moved to the current one rather than a // second added (two items on the same meter would bill the same seconds twice). Opting out stops -// metering immediately but leaves the item, so usage already reported is still invoiced. +// metering immediately. The item is removed once it has nothing left to invoice (no meter report +// this Stripe period): at once if none was sent, otherwise at a sync after the period rolls over, +// so usage already reported is still invoiced and no $0 overage line is left on later invoices. import { z } from 'zod' import type { BillingCaller } from './auth' import { OPEN_STATUSES } from './checkout' import type { Env } from './env' import { planCatalog, planForPrice } from './plans' import type { StripeClient, StripeSubscription } from './stripe' -import { accountSettings, currentSubscription, setOverageSettings, upsertSubscription, type SubscriptionRow } from './store' +import { + accountSettings, + currentSubscription, + meterReportsSince, + setOverageSettings, + upsertSubscription, + type SubscriptionRow +} from './store' export const OverageRequestSchema = z .object({ @@ -51,9 +60,35 @@ export async function updateOverage( ? (await accountSettings(env.BILLING_DB, caller.accountId)).spend_cap_cents : request.spendCapCents await setOverageSettings(env.BILLING_DB, caller.accountId, { optIn: request.enabled, spendCapCents }, now) + if (!request.enabled) { + // Best effort: the opt-out already stops metering; a failed removal is retried by the next sync. + await retireOverageItem(env, stripe, subscription, now).catch((error: unknown) => { + console.error(JSON.stringify({ error: 'retire_overage_item', message: error instanceof Error ? error.message.slice(0, 200) : '' })) + }) + } return { ok: true } } +/** + * Removes an opted-out account's overage item once nothing on it is left to invoice: no meter + * report (sent or pending) since the Stripe period began. Returns whether it removed one. + */ +export async function retireOverageItem(env: Env, stripe: StripeClient, subscription: SubscriptionRow, now: number): Promise { + if (!subscription.overage_item_id) { + return false + } + const settings = await accountSettings(env.BILLING_DB, subscription.account_id) + if (settings.overage_opt_in === 1) { + return false + } + if ((await meterReportsSince(env.BILLING_DB, subscription.account_id, subscription.current_period_start)) > 0) { + return false + } + await stripe.deleteSubscriptionItem(subscription.overage_item_id) + await upsertSubscription(env.BILLING_DB, { ...subscription, overage_enabled: 0, overage_item_id: null, updated_at: now }) + return true +} + /** A metered item that is not a seat price and not the current overage price: an older overage price. */ function isStaleOverageItem(env: Env, item: StripeSubscription['items']['data'][number]): boolean { return ( @@ -84,6 +119,17 @@ async function ensureOverageItem(env: Env, stripe: StripeClient, subscription: S } return replace.id } - // Idempotent per subscription+price, so a retried opt-in cannot add a second item. - return (await stripe.addSubscriptionItem({ subscription: subscription.stripe_subscription_id, price: env.STRIPE_PRICE_OVERAGE })).id + // Idempotent per subscription+price, so a retried opt-in cannot add a second item. Opting out + // can remove the item, so a later opt-in may get the removed item's id replayed (Stripe keeps + // idempotent answers for 24 hours): then add again under a key that names the removed item. + let after: string | undefined + for (let attempt = 0; attempt < 3; attempt++) { + const added = await stripe.addSubscriptionItem({ subscription: subscription.stripe_subscription_id, price: env.STRIPE_PRICE_OVERAGE, after }) + const fresh = await stripe.retrieveSubscription(subscription.stripe_subscription_id) + if (fresh.items.data.some((item) => item.id === added.id)) { + return added.id + } + after = added.id + } + throw new Error('overage_item_replayed') } diff --git a/cloud/apps/billing/src/store.ts b/cloud/apps/billing/src/store.ts index af9f27f66eb..a9c8af04233 100644 --- a/cloud/apps/billing/src/store.ts +++ b/cloud/apps/billing/src/store.ts @@ -220,6 +220,18 @@ export async function insertUsage(db: D1Database, usage: UsageInsert): Promise 0 } +/** Meter reports (any status) for usage that ended since `since`, plus any still pending. */ +export async function meterReportsSince(db: D1Database, accountId: string, since: number): Promise { + const row = await db + .prepare( + `SELECT COUNT(*) AS n FROM meter_reports m JOIN usage_events p ON p.usage_id = m.usage_id + WHERE p.account_id = ?1 AND (m.event_timestamp >= ?2 OR m.status = 'pending')` + ) + .bind(accountId, since) + .first<{ n: number }>() + return row?.n ?? 0 +} + /** Overage seconds already metered (billed) in an allowance window. */ export async function meteredSeconds(db: D1Database, accountId: string, windowStart: number): Promise { const row = await db diff --git a/cloud/apps/billing/src/stripe.ts b/cloud/apps/billing/src/stripe.ts index 8d493a6fd58..30b89ef0b15 100644 --- a/cloud/apps/billing/src/stripe.ts +++ b/cloud/apps/billing/src/stripe.ts @@ -143,13 +143,14 @@ export function createStripeClient(env: Env, fetchImpl: typeof fetch = fetch) { idempotencyKey ) }, - addSubscriptionItem(args: { subscription: string; price: string }) { + /** `after`: the id a replayed add returned for an item since removed, so this add is a new one. */ + addSubscriptionItem(args: { subscription: string; price: string; after?: string }) { return request<{ id: string }>( 'POST', '/v1/subscription_items', // Metered: nothing to prorate; usage is billed in arrears. { subscription: args.subscription, price: args.price, proration_behavior: 'none' }, - `overage-item:${args.subscription}:${args.price}` + `overage-item:${args.subscription}:${args.price}${args.after ? `:after:${args.after}` : ''}` ) }, /** Moves an item to another price in place (an older overage price to the current one). */ diff --git a/cloud/apps/billing/src/webhook.ts b/cloud/apps/billing/src/webhook.ts index e4373aecd8a..c2118c32d45 100644 --- a/cloud/apps/billing/src/webhook.ts +++ b/cloud/apps/billing/src/webhook.ts @@ -3,7 +3,8 @@ import type { Env } from './env' import { planForPrice } from './plans' import { allowsLiveMode, type StripeClient, type StripeSubscription } from './stripe' -import { accountForCustomer, claimEvent, customerFor, finishEvent, upsertSubscription } from './store' +import { accountForCustomer, claimEvent, currentSubscription, customerFor, finishEvent, upsertSubscription } from './store' +import { retireOverageItem } from './overage' import { splitSecrets, verifyStripeSignature } from './webhook-signature' const MAX_BODY_BYTES = 512 * 1024 @@ -112,6 +113,15 @@ export async function syncSubscription(env: Env, stripe: StripeClient, subscript // Membership comes from auth, not Stripe: keep the stored count. member_count: null }) + if (overageItemId) { + // An opted-out account's overage item goes once the period it was used in has been invoiced. + const stored = await currentSubscription(db, accountId) + if (stored?.stripe_subscription_id === subscription.id) { + await retireOverageItem(env, stripe, stored, now).catch((error: unknown) => { + console.error(JSON.stringify({ error: 'retire_overage_item', message: error instanceof Error ? error.message.slice(0, 200) : '' })) + }) + } + } } export async function handleStripeWebhook(env: Env, stripe: StripeClient, request: Request, now: number): Promise { diff --git a/cloud/apps/billing/test/overage-opt-out.test.ts b/cloud/apps/billing/test/overage-opt-out.test.ts new file mode 100644 index 00000000000..544550aad18 --- /dev/null +++ b/cloud/apps/billing/test/overage-opt-out.test.ts @@ -0,0 +1,97 @@ +// Opting out of overage: nothing more is metered or billed, and the metered item comes off the +// subscription once nothing on it is left to invoice (no $0 overage line on later invoices). +import { describe, expect, it } from 'vitest' +import { checkoutCompleted, stripeEvent } from './stripe-fake' +import { createHarness } from './harness' + +const HOUR = 3600 +const PERIOD_START = Math.floor(Date.now() / 1000) - 5 * 24 * HOUR +const PERIOD_END = PERIOD_START + 30 * 24 * HOUR + +async function optedInTeam() { + const h = await createHarness() + const token = await h.desktopToken({ sub: 'u1', org: 'o1', orgRole: 'owner', email: 'a@example.com' }) + const auth = { authorization: `Bearer ${token}` } + await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team', seats: 2 }, headers: auth }) + const customer = [...h.stripe.customers.keys()][0]! + const subscription = h.stripe.putSubscription({ + customer, + accountId: 'org:o1', + basePrice: 'price_team_month', + quantity: 2, + periodStart: PERIOD_START, + periodEnd: PERIOD_END + }) + await h.webhook(checkoutCompleted({ customer, subscription: subscription.id, accountId: 'org:o1' })) + const overage = (body: unknown) => h.call('POST', '/v1/billing/overage', { body, headers: auth }) + expect((await overage({ enabled: true })).status).toBe(200) + const prices = () => subscription.items.data.map((item) => item.price.id) + expect(prices()).toEqual(['price_team_month', 'price_overage']) + let n = 0 + const use = (hours: number) => { + const endedAt = Date.now() - 60_000 + return h.controlPlane('/v1/internal/usage', { + usageId: `u-${n++}`, + accountId: 'org:o1', + sandboxId: 'sbx_1', + machineSize: 'standard', + startedAt: endedAt - hours * HOUR * 1000, + endedAt + }) + } + const stored = () => + h.raw.prepare('SELECT overage_enabled, overage_item_id IS NOT NULL AS has_item FROM subscriptions').get() + return { h, auth, subscription, overage, prices, use, stored } +} + +describe('overage opt-out', () => { + it('removes the unused metered item at once, and opting back in adds it again', async () => { + const { h, overage, prices, use, stored } = await optedInTeam() + expect((await overage({ enabled: false })).status).toBe(200) + expect(prices()).toEqual(['price_team_month']) + expect(stored()).toEqual({ overage_enabled: 0, has_item: 0 }) + // Past the included hours with overage off: nothing is metered. + for (let i = 0; i < 6; i++) { + await use(24) + } + expect(h.stripe.meterEvents).toHaveLength(0) + expect(h.raw.prepare('SELECT COUNT(*) AS n FROM meter_reports').get()).toEqual({ n: 0 }) + expect((await overage({ enabled: true })).status).toBe(200) + expect(prices()).toEqual(['price_team_month', 'price_overage']) + }) + + it('a $0 cap never meters, even with overage on', async () => { + const { h, overage, use } = await optedInTeam() + expect((await overage({ enabled: true, spendCapCents: 0 })).status).toBe(200) + for (let i = 0; i < 6; i++) { + await use(24) + } + expect(h.stripe.meterEvents).toHaveLength(0) + expect(h.raw.prepare('SELECT COUNT(*) AS n FROM meter_reports').get()).toEqual({ n: 0 }) + }) + + it('keeps an item with usage to invoice until the period rolls over, then removes it', async () => { + const { h, overage, prices, use, stored, subscription } = await optedInTeam() + for (let i = 0; i < 5; i++) { + await use(24) + } + await use(2) + expect(h.stripe.meterEvents).toHaveLength(1) + expect((await overage({ enabled: false })).status).toBe(200) + // The 2 overage hours still have to be invoiced on this item. + expect(prices()).toEqual(['price_team_month', 'price_overage']) + await use(3) + expect(h.stripe.meterEvents).toHaveLength(1) + // A sync inside the same period keeps it. + await h.webhook(stripeEvent('customer.subscription.updated', subscription)) + expect(prices()).toEqual(['price_team_month', 'price_overage']) + // Renewal: the next period has nothing metered, so the sync takes the item off. + for (const item of subscription.items.data) { + item.current_period_start = PERIOD_END + item.current_period_end = PERIOD_END + 30 * 24 * HOUR + } + await h.webhook(stripeEvent('customer.subscription.updated', subscription)) + expect(prices()).toEqual(['price_team_month']) + expect(stored()).toEqual({ overage_enabled: 0, has_item: 0 }) + }) +}) From 5e5c5353227d1ec681134b20ce092b4b5470de6e Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:52:11 -0800 Subject: [PATCH 098/149] fix(cloud): JA-23 per design-squad: A1 policy stays visible in the Orca Cloud description; only the storage note moves into the info tooltip; Paste a token sits under the detail MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - OrcaCloudAccountsDescription: help line, then the mandatory A1 sentence verbatim (spec §5 item 5), then a focusable info tooltip with 'Kept in your Orca account, never in a sandbox.' (sr-only text). - Used by both the Settings page part and the section's own header. - 'Paste a token instead' is a ghost sm Button under the not-set-up detail. - en.json: notSetUpDetail drops 'on this computer' (core-ui-ra, JA-04). --- .../agent-accounts/OrcaCloudAccountRow.tsx | 34 ++++++++-------- .../agent-accounts/OrcaCloudAccounts.test.tsx | 17 +++++--- .../agent-accounts/OrcaCloudAccounts.tsx | 13 +----- .../OrcaCloudAccountsDescription.tsx | 40 +++++++++++++++++++ .../agent-accounts/OrcaCloudPolicyInfo.tsx | 38 ------------------ ...ngs-orca-cloud-agent-accounts-sections.tsx | 13 +----- .../src/i18n/en-runtime-required.json | 3 -- src/renderer/src/i18n/locales/en.json | 2 +- 8 files changed, 73 insertions(+), 87 deletions(-) create mode 100644 src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountsDescription.tsx delete mode 100644 src/renderer/src/components/settings/agent-accounts/OrcaCloudPolicyInfo.tsx diff --git a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountRow.tsx b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountRow.tsx index 8c36a79fca2..8d3067c05dc 100644 --- a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountRow.tsx +++ b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountRow.tsx @@ -58,24 +58,24 @@ export function AccountRow({ 'One sign-in. Then every cloud workspace can use it.' )} actions={ - <> - {/* The paste path stays reachable without the browser (RA-5), as a real action (JA-23). */} - {agent === 'claude' ? ( - - ) : null} - - + } - /> + > + {/* The paste path stays reachable without the browser (RA-5), as a real action (JA-23). */} + {agent === 'claude' ? ( + + ) : null} + ) break case 'setup': diff --git a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.test.tsx b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.test.tsx index d3d4fd6e622..1aeee6cf3ce 100644 --- a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.test.tsx +++ b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.test.tsx @@ -56,13 +56,18 @@ const NOT_SET_UP: OrcaCloudAccountRow = { kind: 'notSetUp', keyKind: null } describe('OrcaCloudAccountsView', () => { afterEach(cleanup) - it('keeps the policy reachable from a focusable info button and starts setup per agent', () => { + it('keeps the policy visible, the storage note in a tooltip, and starts setup per agent', () => { const handlers = view({ claude: NOT_SET_UP, codex: { kind: 'notSetUp', keyKind: 'team' } }) - // JA-23: the mandatory A1 line moved into a tooltip; its text stays in the accessibility tree. - const info = screen.getByRole('button', { - name: /used only in your own workspaces\. Teammates never use them\./ - }) - expect(info.tagName).toBe('BUTTON') + // JA-23: the mandatory A1 sentence stays visible in the description, verbatim. + expect( + screen.getByText( + /Your Claude and ChatGPT accounts are used only in your own workspaces\. Teammates never use them\./ + ) + ).toBeTruthy() + // Where it's kept moves from every active row into one focusable info button. + expect( + screen.getByRole('button', { name: 'Kept in your Orca account, never in a sandbox.' }) + ).toBeTruthy() expect(screen.getByText('Not set up · using the team key')).toBeTruthy() fireEvent.click(screen.getByRole('button', { name: 'Use my ChatGPT account' })) expect(handlers.start).toHaveBeenCalledWith('codex') diff --git a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.tsx b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.tsx index 580d19ca839..f62dd2096a4 100644 --- a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.tsx +++ b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.tsx @@ -15,7 +15,7 @@ import { SettingsGroupHeader } from '../section-layout/SettingsGroup' import { agentName } from './orca-cloud-accounts-copy' import type { OrcaCloudAccountsViewProps } from './orca-cloud-accounts-types' import { AccountRow } from './OrcaCloudAccountRow' -import { OrcaCloudPolicyInfo } from './OrcaCloudPolicyInfo' +import { OrcaCloudAccountsDescription } from './OrcaCloudAccountsDescription' export type { OrcaCloudAccountsActions, @@ -153,16 +153,7 @@ export function OrcaCloudAccountsView({ {hideHeader ? null : ( - {t( - 'orcaCloudAccounts.help', - 'Set up once on this computer. Every cloud workspace uses it, including new, cloned and restarted ones.' - )}{' '} - {/* Mandatory (spec §5 item 5): the A1 mitigation line, now a focusable tooltip (JA-23). */} - - - } + description={} /> )}
    diff --git a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountsDescription.tsx b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountsDescription.tsx new file mode 100644 index 00000000000..1c2026d1e77 --- /dev/null +++ b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountsDescription.tsx @@ -0,0 +1,40 @@ +// JA-23 (design-squad): the A1 policy stays visible in the Orca Cloud description (spec §5 item 5, +// mandatory copy); only "Kept in your Orca account, never in a sandbox.", which every active row +// used to repeat, moves into a focusable info tooltip. Its text stays in the accessibility tree. +import type React from 'react' +import { Info } from 'lucide-react' +import { useTranslate } from '@/i18n/use-translate' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' + +/** The Orca Cloud section description: the help line, then the A1 policy, verbatim and visible. */ +export function OrcaCloudAccountsDescription(): React.JSX.Element { + const t = useTranslate() + const kept = t('orcaCloudAccounts.activeDetail', 'Kept in your Orca account, never in a sandbox.') + return ( + <> + {t( + 'orcaCloudAccounts.help', + 'Set up once on this computer. Every cloud workspace uses it, including new, cloned and restarted ones.' + )}{' '} + {/* Mandatory (spec §5 item 5): the A1 mitigation depends on this sentence. */} + {t( + 'orcaCloudAccounts.policy', + 'Your Claude and ChatGPT accounts are used only in your own workspaces. Teammates never use them.' + )}{' '} + + + + + + {kept} + + + + ) +} diff --git a/src/renderer/src/components/settings/agent-accounts/OrcaCloudPolicyInfo.tsx b/src/renderer/src/components/settings/agent-accounts/OrcaCloudPolicyInfo.tsx deleted file mode 100644 index c887a8873ab..00000000000 --- a/src/renderer/src/components/settings/agent-accounts/OrcaCloudPolicyInfo.tsx +++ /dev/null @@ -1,38 +0,0 @@ -// The Orca Cloud accounts policy (spec §5 item 5, the A1 mitigation) as a focusable info tooltip next -// to the section heading (JA-23). The text stays in the accessibility tree, so keyboard and -// screen-reader users still get it without opening the tooltip. -import type React from 'react' -import { Info } from 'lucide-react' -import { useTranslate } from '@/i18n/use-translate' -import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' - -export function orcaCloudPolicyText(t: ReturnType): string { - return [ - t('orcaCloudAccounts.activeDetail', 'Kept in your Orca account, never in a sandbox.'), - t( - 'orcaCloudAccounts.policy', - 'Your Claude and ChatGPT accounts are used only in your own workspaces. Teammates never use them.' - ) - ].join(' ') -} - -export function OrcaCloudPolicyInfo(): React.JSX.Element { - const t = useTranslate() - const text = orcaCloudPolicyText(t) - return ( - - - - - - {text} - - - ) -} diff --git a/src/renderer/src/components/settings/page/settings-orca-cloud-agent-accounts-sections.tsx b/src/renderer/src/components/settings/page/settings-orca-cloud-agent-accounts-sections.tsx index 28aac60be36..c8343611998 100644 --- a/src/renderer/src/components/settings/page/settings-orca-cloud-agent-accounts-sections.tsx +++ b/src/renderer/src/components/settings/page/settings-orca-cloud-agent-accounts-sections.tsx @@ -1,6 +1,6 @@ import type { AgentAccountsPart } from '../accounts/AgentAccountsSubsection' import { OrcaCloudAccountsSection } from '../agent-accounts/OrcaCloudAccountsSection' -import { OrcaCloudPolicyInfo } from '../agent-accounts/OrcaCloudPolicyInfo' +import { OrcaCloudAccountsDescription } from '../agent-accounts/OrcaCloudAccountsDescription' import { AgentAccountsOverviewSection } from '../agent-accounts/overview/AgentAccountsOverviewSection' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' @@ -30,16 +30,7 @@ export function orcaCloudAgentAccountsParts( { id: 'accounts-orca-cloud', title: t('orcaCloudAccounts.title', 'Orca Cloud'), - description: ( - <> - {t( - 'orcaCloudAccounts.help', - 'Set up once on this computer. Every cloud workspace uses it, including new, cloned and restarted ones.' - )}{' '} - {/* Mandatory (spec §5 item 5): the A1 mitigation line as a focusable tooltip (JA-23). */} - - - ), + description: , content: } ] diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 9f9faa76362..483741382dd 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -2328,9 +2328,6 @@ "menu": { "quitApp": "Quit {{appName}}" }, - "orcaCloudAccounts": { - "notSetUpDetail": "One sign-in on this computer. Then every cloud workspace can use it." - }, "orcaCloudMove": { "confirm": { "changesCount_one": "{{count}} uncommitted change, plus untracked files", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index ec448c98c22..4da7502960d 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -27779,7 +27779,7 @@ "useChatGPT": "Use my ChatGPT account", "notSetUpKey": "Not set up · using {{key}}", "notSetUp": "Not set up", - "notSetUpDetail": "One sign-in on this computer. Then every cloud workspace can use it.", + "notSetUpDetail": "One sign-in. Then every cloud workspace can use it.", "tryAgain": "Try again", "expired": "Your {{agent}} sign-in expired", "expiredDetail": "Cloud workspaces use {{key}} until you renew. Nothing else changed.", From 35b198929156283c2038c436f5c58831ab807c3b Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:52:53 -0800 Subject: [PATCH 099/149] test(cloud): no cast in the cover store test --- src/renderer/src/lib/orca-cloud/cloud-open-cover-store.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/renderer/src/lib/orca-cloud/cloud-open-cover-store.test.ts b/src/renderer/src/lib/orca-cloud/cloud-open-cover-store.test.ts index 83b6cac5ee9..1cc03247cf9 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-open-cover-store.test.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-open-cover-store.test.ts @@ -23,9 +23,10 @@ describe('cloud open cover', () => { }) it('counts the workspace as open only once one of its terminals has a PTY', () => { + const noPtys: string[] = [] const state = { tabsByWorktree: { w1: [{ id: 't1' }, { id: 't2' }] }, - ptyIdsByTabId: { t1: [] as string[] } + ptyIdsByTabId: { t1: noPtys } } expect(workspaceHasAttachedPty(state, 'w1')).toBe(false) expect( From 09f7f1e245e3ade44efc6771ae458c6e0ffbb008 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:53:05 -0800 Subject: [PATCH 100/149] fix(sleep): browser tabs sleep in place (marked, pages dropped) instead of closing; opening the workspace wakes them (NEW-01) --- .../workspace-lineage-menu-actions.ts | 4 +- .../sleep/browser-tab-sleep.test.ts | 94 +++++++++++++++++++ .../sleep/browser-tab-sleep.ts | 87 +++++++++++++++++ .../sleep/workspace-sleep-follower.ts | 13 +-- .../visible-worktree-activity-inputs.ts | 8 +- .../mobile-terminal-close-ipc-bridge.ts | 3 + .../workspace-activity-shadow.ts | 2 +- .../src/lib/worktree-activity-state.ts | 5 +- src/renderer/src/lib/worktree-status.ts | 11 ++- src/shared/browser-workspace-types.ts | 5 + .../workspace-layout-disk-fields.ts | 4 +- 11 files changed, 216 insertions(+), 20 deletions(-) create mode 100644 src/renderer/src/components/sidebar/workspace-actions/sleep/browser-tab-sleep.test.ts create mode 100644 src/renderer/src/components/sidebar/workspace-actions/sleep/browser-tab-sleep.ts diff --git a/src/renderer/src/components/sidebar/workspace-actions/context-menu/workspace-lineage-menu-actions.ts b/src/renderer/src/components/sidebar/workspace-actions/context-menu/workspace-lineage-menu-actions.ts index 645697c35c3..ae45592fd84 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/context-menu/workspace-lineage-menu-actions.ts +++ b/src/renderer/src/components/sidebar/workspace-actions/context-menu/workspace-lineage-menu-actions.ts @@ -11,7 +11,7 @@ import { getWorkspaceDeleteLineage } from '../deletion/workspace-delete-lineage' type WorkspaceActivityMaps = { tabsByWorktree: Record ptyIdsByTabId: Record - browserTabsByWorktree: Record + browserTabsByWorktree: Record unifiedTabsByWorktree: Record agentStatusByPaneKey: Record structuredChatSleptAtByPaneKey: StructuredChatSleptAtByPaneKey @@ -30,7 +30,7 @@ export function hasSleepableWorkspaceActivity( const tabs = activity.tabsByWorktree[worktreeId] ?? [] return ( tabs.some((tab) => tabHasLivePty(activity.ptyIdsByTabId, tab.id)) || - (activity.browserTabsByWorktree[worktreeId] ?? []).length > 0 || + (activity.browserTabsByWorktree[worktreeId] ?? []).some((tab) => !tab.sleptAt) || // An idle-ended chat still needs Sleep to hide it, even when its legacy tab has no host stamp. (activity.unifiedTabsByWorktree[worktreeId] ?? []).some( (tab) => diff --git a/src/renderer/src/components/sidebar/workspace-actions/sleep/browser-tab-sleep.test.ts b/src/renderer/src/components/sidebar/workspace-actions/sleep/browser-tab-sleep.test.ts new file mode 100644 index 00000000000..5d46053752d --- /dev/null +++ b/src/renderer/src/components/sidebar/workspace-actions/sleep/browser-tab-sleep.test.ts @@ -0,0 +1,94 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { BrowserWorkspace } from '../../../../../../shared/browser-workspace-types' + +type State = { + activeWorktreeId: string | null + browserTabsByWorktree: Record + browserPagesByWorkspace: Record + activeBrowserTabIdByWorktree: Record +} + +const mocks = vi.hoisted(() => { + const listeners = new Set<(state: unknown) => void>() + const store = { + state: {} as Record, + getState: () => store.state, + setState: (change: (state: Record) => Record) => { + store.state = { ...store.state, ...change(store.state) } + for (const listener of listeners) { + listener(store.state) + } + }, + subscribe: (listener: (state: unknown) => void) => { + listeners.add(listener) + return () => listeners.delete(listener) + } + } + return { store, evicted: [] as string[] } +}) +vi.mock('@/store', () => ({ useAppStore: mocks.store })) +vi.mock('@/store/slices/browser/cleanup/browser-webview-cleanup', () => ({ + destroyWorktreeBrowserGuests: (_tabs: unknown, _pages: unknown, worktreeId: string) => + mocks.evicted.push(worktreeId) +})) + +const { sleepWorktreeBrowserTabs, installBrowserTabWakeOnOpen } = await import( + './browser-tab-sleep' +) +const { isInactiveWorkspace } = await import('@/lib/worktree-activity-state') + +const tab = (id: string): BrowserWorkspace => ({ + id, + worktreeId: 'wt', + url: `http://localhost:3000/${id}`, + title: id, + loading: false, + faviconUrl: null, + canGoBack: false, + canGoForward: false, + loadError: null, + createdAt: 1 +}) + +const state = (): State => mocks.store.getState() as unknown as State + +beforeEach(() => { + mocks.evicted.length = 0 + mocks.store.state = { + activeWorktreeId: null, + browserTabsByWorktree: { wt: [tab('a'), tab('b'), tab('c')] }, + browserPagesByWorkspace: {}, + activeBrowserTabIdByWorktree: { wt: 'b' } + } +}) + +describe('sleep keeps browser tabs in place (NEW-01)', () => { + it('keeps every tab, in order, with the same active tab; drops only their pages', () => { + sleepWorktreeBrowserTabs('wt', 42) + expect(mocks.evicted).toEqual(['wt']) + expect(state().browserTabsByWorktree.wt.map((t) => t.id)).toEqual(['a', 'b', 'c']) + expect(state().browserTabsByWorktree.wt.every((t) => t.sleptAt === 42)).toBe(true) + expect(state().activeBrowserTabIdByWorktree.wt).toBe('b') + }) + + it('asleep tabs are not activity, so the workspace still reads as asleep', () => { + const inactive = (): boolean => + isInactiveWorkspace('wt', {}, {}, state().browserTabsByWorktree, new Set()) + expect(inactive()).toBe(false) + sleepWorktreeBrowserTabs('wt', 42) + expect(inactive()).toBe(true) + }) + + it('opening the workspace again wakes its tabs, still in the same order', () => { + const stop = installBrowserTabWakeOnOpen() + sleepWorktreeBrowserTabs('wt', 42) + mocks.store.setState(() => ({ activeWorktreeId: 'wt' })) + expect(state().browserTabsByWorktree.wt.map((t) => [t.id, t.sleptAt])).toEqual([ + ['a', undefined], + ['b', undefined], + ['c', undefined] + ]) + expect(state().activeBrowserTabIdByWorktree.wt).toBe('b') + stop() + }) +}) diff --git a/src/renderer/src/components/sidebar/workspace-actions/sleep/browser-tab-sleep.ts b/src/renderer/src/components/sidebar/workspace-actions/sleep/browser-tab-sleep.ts new file mode 100644 index 00000000000..22c63636083 --- /dev/null +++ b/src/renderer/src/components/sidebar/workspace-actions/sleep/browser-tab-sleep.ts @@ -0,0 +1,87 @@ +// Sleep never changes a workspace's tab layout (NEW-01). Its browser tabs stay where they are, in +// the same order with the same active tab; only their pages are dropped to free memory, and each +// tab is marked asleep so it no longer counts as activity (an asleep workspace still reads as +// asleep and hides with "Hide sleeping"). Opening the workspace again wakes the tabs: each page +// reloads in place when it is shown. A remote desktop tab's own chrome reconnects it after a wake. +import { useAppStore } from '@/store' +import { destroyWorktreeBrowserGuests } from '@/store/slices/browser/cleanup/browser-webview-cleanup' +import type { BrowserWorkspace } from '../../../../../../shared/browser-workspace-types' + +/** Awake tabs are activity; a tab Sleep put to rest is not, until the workspace is opened again. */ +export function isAwakeBrowserTab(tab: { sleptAt?: number | null }): boolean { + return !tab.sleptAt +} + +export function hasAwakeBrowserTab( + tabs: readonly { sleptAt?: number | null }[] | null | undefined +): boolean { + return (tabs ?? []).some(isAwakeBrowserTab) +} + +function stamp( + tabs: readonly BrowserWorkspace[], + sleptAt: number | undefined +): BrowserWorkspace[] | null { + let changed = false + const next = tabs.map((tab) => { + if ((tab.sleptAt ?? undefined) === sleptAt) { + return tab + } + changed = true + const copy: BrowserWorkspace = { ...tab } + if (sleptAt === undefined) { + delete copy.sleptAt + } else { + copy.sleptAt = sleptAt + } + return copy + }) + return changed ? next : null +} + +/** Sleep: drop the pages, keep the tabs, mark them asleep. */ +export function sleepWorktreeBrowserTabs(worktreeId: string, now: number = Date.now()): void { + const state = useAppStore.getState() + destroyWorktreeBrowserGuests( + state.browserTabsByWorktree, + state.browserPagesByWorkspace, + worktreeId + ) + const next = stamp(state.browserTabsByWorktree[worktreeId] ?? [], now) + if (next) { + useAppStore.setState((s) => ({ + browserTabsByWorktree: { ...s.browserTabsByWorktree, [worktreeId]: next } + })) + } +} + +/** The workspace is open again: its tabs count as activity once more (pages reload when shown). */ +export function wakeWorktreeBrowserTabs(worktreeId: string): void { + const tabs = useAppStore.getState().browserTabsByWorktree[worktreeId] + if (!tabs || !tabs.some((tab) => tab.sleptAt)) { + return + } + const next = stamp(tabs, undefined) + if (next) { + useAppStore.setState((s) => ({ + browserTabsByWorktree: { ...s.browserTabsByWorktree, [worktreeId]: next } + })) + } +} + +/** Wakes a workspace's asleep tabs whenever it becomes the active one (also after an app restart). */ +export function installBrowserTabWakeOnOpen(): () => void { + let previous = useAppStore.getState().activeWorktreeId + if (previous) { + wakeWorktreeBrowserTabs(previous) + } + return useAppStore.subscribe((state) => { + if (state.activeWorktreeId === previous) { + return + } + previous = state.activeWorktreeId + if (previous) { + wakeWorktreeBrowserTabs(previous) + } + }) +} diff --git a/src/renderer/src/components/sidebar/workspace-actions/sleep/workspace-sleep-follower.ts b/src/renderer/src/components/sidebar/workspace-actions/sleep/workspace-sleep-follower.ts index bb771acf502..8dabfd1cb24 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/sleep/workspace-sleep-follower.ts +++ b/src/renderer/src/components/sidebar/workspace-actions/sleep/workspace-sleep-follower.ts @@ -1,5 +1,5 @@ import { useAppStore } from '@/store' -import { destroyWorktreeBrowserGuests } from '@/store/slices/browser/cleanup/browser-webview-cleanup' +import { sleepWorktreeBrowserTabs, wakeWorktreeBrowserTabs } from './browser-tab-sleep' import { captureWorkspaceSelection, restoreWorkspaceSelection, @@ -65,13 +65,8 @@ export function followWorkspaceSleep( } if (!options.keepBrowserTabs) { // Sleep never changes the tab layout (NEW-01): the tabs, their order and the active one stay; - // only their pages are dropped to free memory, and each reloads in place when shown after - // the wake. A remote desktop tab reconnects itself the same way (its chrome). - destroyWorktreeBrowserGuests( - state.browserTabsByWorktree, - state.browserPagesByWorkspace, - worktreeId - ) + // only their pages are dropped, and each reloads in place when shown after the wake. + sleepWorktreeBrowserTabs(worktreeId) } let settle!: (stop: HostTerminalStop) => void const hostStop = new Promise((resolve) => (settle = resolve)) @@ -108,6 +103,8 @@ export function followWorkspaceSleep( // A failed sleep leaves the workspace awake and retryable; one the user reopened is theirs. if (!notice.slept || state.activeWorktreeId === worktreeId) { clearWorktreeSleepIntent(worktreeId) + // Still awake: its tabs count as activity again. + wakeWorktreeBrowserTabs(worktreeId) } if (!notice.slept && entry?.selectionBeforeSleep && state.activeWorktreeId === null) { restoreWorkspaceSelection(state, entry.selectionBeforeSleep) diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/visible-worktree-activity-inputs.ts b/src/renderer/src/components/sidebar/worktree-list/listing/visible-worktree-activity-inputs.ts index df576d451e9..33687dbae47 100644 --- a/src/renderer/src/components/sidebar/worktree-list/listing/visible-worktree-activity-inputs.ts +++ b/src/renderer/src/components/sidebar/worktree-list/listing/visible-worktree-activity-inputs.ts @@ -7,7 +7,7 @@ import { createWorktreeTabBucketProjection } from '@/lib/workspace/tabs/worktree import type { StructuredChatSleptAtByPaneKey } from '@/store/slices/agent-status/structured-chat-slept-at' export type TerminalActivityTab = Pick -export type BrowserActivityTab = Pick +export type BrowserActivityTab = Pick export function createVisibleWorktreeTerminalActivityProjection( onInspectBucket?: (worktreeId: string) => void @@ -28,8 +28,10 @@ export function getVisibleWorktreeTerminalActivityTabs( } const browserProjection = createWorktreeTabBucketProjection({ - projectTab: (tab) => ({ id: tab.id }), - isSameProjectedTab: (previousTab, nextTab) => previousTab.id === nextTab.id + // A tab Sleep put to rest is not activity, so its mark is part of the projection. + projectTab: (tab) => (tab.sleptAt ? { id: tab.id, sleptAt: tab.sleptAt } : { id: tab.id }), + isSameProjectedTab: (previousTab, nextTab) => + previousTab.id === nextTab.id && previousTab.sleptAt === nextTab.sleptAt }) export function getVisibleWorktreeBrowserActivityTabs( diff --git a/src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge.ts index cee10a49f5c..1204fc6c808 100644 --- a/src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge.ts @@ -2,6 +2,7 @@ import { createRuntimeFilePositionQueue } from './runtime-file-position' import { applyClosedTerminalLeafNotice } from '@/components/terminal-pane/layout/close/closed-terminal-leaf-notice' import { closeTerminalTab } from '@/components/terminal/terminal-tab-actions' import { detectLanguage } from '../../../../shared/editor-language/editor-language-detect' +import { installBrowserTabWakeOnOpen } from '@/components/sidebar/workspace-actions/sleep/browser-tab-sleep' import { followWorkspaceSleep } from '@/components/sidebar/workspace-actions/sleep/workspace-sleep-follower' import { createProjectMovePauseFollower } from '@/components/sidebar/project-move-pause-follower' import { buildWorkspaceSessionPayload } from '@/lib/workspace/persistence/workspace-session' @@ -218,6 +219,8 @@ export function registerMobileAndTerminalCloseIpcBridge( } else { unsubs.push(window.api.ui.onWorkspaceSleep(followWorkspaceSleep)) } + // Sleep keeps a workspace's browser tabs asleep in place; opening it again wakes them. + unsubs.push(installBrowserTabWakeOnOpen()) unsubs.push( window.api.ui.onResumeSleepingAgents(({ worktreeId }) => { diff --git a/src/renderer/src/lib/sidebar-shadow/workspace-activity-shadow.ts b/src/renderer/src/lib/sidebar-shadow/workspace-activity-shadow.ts index 3b233e81f7d..e65f7d500ba 100644 --- a/src/renderer/src/lib/sidebar-shadow/workspace-activity-shadow.ts +++ b/src/renderer/src/lib/sidebar-shadow/workspace-activity-shadow.ts @@ -55,7 +55,7 @@ export function readWindowWorkspaceActivityFacts( ) ? 'live' : null, - browser: (state.browserTabsByWorktree[id]?.length ?? 0) > 0, + browser: (state.browserTabsByWorktree[id] ?? []).some((tab) => !tab.sleptAt), structuredChat: structuredChatIds.has(id), agent: agentById.get(id) ?? null } diff --git a/src/renderer/src/lib/worktree-activity-state.ts b/src/renderer/src/lib/worktree-activity-state.ts index 1a2c77300ce..43e6796d084 100644 --- a/src/renderer/src/lib/worktree-activity-state.ts +++ b/src/renderer/src/lib/worktree-activity-state.ts @@ -12,7 +12,8 @@ import { } from '../../../shared/sidebar-list/workspace-activity-facts' type TerminalLikeTab = Pick -type BrowserLikeTab = { id: string } +/** `sleptAt`: Sleep kept the tab but dropped its page; it is not activity until reopened. */ +type BrowserLikeTab = { id: string; sleptAt?: number | null } type TabsByWorktree = Record type PtyIdsByTabId = Record @@ -81,7 +82,7 @@ export function hasActiveWorkspaceActivity( const tabs = tabsByWorktree?.[worktreeId] ?? [] const hasLiveTerminal = ptyIdsByTabId != null && tabs.some((tab) => tabHasLivePty(ptyIdsByTabId, tab.id)) - const hasBrowser = (browserTabsByWorktree?.[worktreeId] ?? []).length > 0 + const hasBrowser = (browserTabsByWorktree?.[worktreeId] ?? []).some((tab) => !tab.sleptAt) // Why: a running agent keeps the workspace visible through brief PTY gaps // such as an SSH reconnect or an unmounted remote pane. #7197 const hasLiveAgent = worktreeIdsWithLiveAgent.has(worktreeId) diff --git a/src/renderer/src/lib/worktree-status.ts b/src/renderer/src/lib/worktree-status.ts index 15f033f11c4..3be51c113c7 100644 --- a/src/renderer/src/lib/worktree-status.ts +++ b/src/renderer/src/lib/worktree-status.ts @@ -63,7 +63,7 @@ const STATUS_LABELS: Record = { export function getWorktreeStatus( tabs: readonly Pick[], - browserTabs: readonly { id: string }[], + browserTabs: readonly { id: string; sleptAt?: number | null }[], ptyIdsByTabId: Record, runtimePaneTitlesByTabId: Record> = {}, options: WorktreeStatusHeuristicOptions = {} @@ -84,7 +84,12 @@ export function getWorktreeStatus( if (options.liveAgentStatus === 'monitoring') { return 'monitoring' } - if (liveTabs.length > 0 || browserTabs.length > 0 || options.hasStructuredChat) { + // A tab Sleep put to rest (sleptAt) keeps its place but is not activity. + if ( + liveTabs.length > 0 || + browserTabs.some((tab) => !tab.sleptAt) || + options.hasStructuredChat + ) { // Why: browser-only and chat-only worktrees (no PTY) are still active from the user's point of view. return 'active' } @@ -199,7 +204,7 @@ export function getWorktreeStatusLabel(status: WorktreeStatus): string { */ export function resolveWorktreeStatus(args: { tabs: readonly Pick[] - browserTabs: readonly { id: string }[] + browserTabs: readonly { id: string; sleptAt?: number | null }[] hasStructuredChat?: boolean ptyIdsByTabId: Record runtimePaneTitlesByTabId?: Record> diff --git a/src/shared/browser-workspace-types.ts b/src/shared/browser-workspace-types.ts index 971c3511d19..c10b99a922f 100644 --- a/src/shared/browser-workspace-types.ts +++ b/src/shared/browser-workspace-types.ts @@ -131,6 +131,11 @@ export type BrowserWorkspace = { createdAt: number /** Mirrored from the active page, like the fields above it. */ docLocation?: BrowserPageDocLocation | null + /** + * Set by Sleep: the tab keeps its place but its page was dropped, and it is not activity until + * the workspace is opened again (then cleared, and the page reloads when shown). + */ + sleptAt?: number } export type BrowserSessionProfileScope = 'default' | 'isolated' | 'imported' diff --git a/src/shared/workspace-layout/workspace-layout-disk-fields.ts b/src/shared/workspace-layout/workspace-layout-disk-fields.ts index a9fa8830526..760dfbd9050 100644 --- a/src/shared/workspace-layout/workspace-layout-disk-fields.ts +++ b/src/shared/workspace-layout/workspace-layout-disk-fields.ts @@ -217,7 +217,9 @@ const BROWSER = { canGoBack: own('browserLive', 'canGoBack'), canGoForward: own('browserLive', 'canGoForward'), loadError: own('browserLive', 'loadError'), - docLocation: own('browserLive', 'docLocation') + docLocation: own('browserLive', 'docLocation'), + // Sleep's mark: runtime-only, so a restart starts every tab awake. + sleptAt: 'unwritten' } as const satisfies Record // Write records only for mounted tree panes; derive keys from tab and leaf IDs. From 27baa26cc6ac9d117524ea0784b9d9e5ae55426e Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:53:53 -0800 Subject: [PATCH 101/149] fix(sidebar): no stale port badge on an asleep VM row (JA-13) --- .../controller/use-worktree-card-foundation.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/renderer/src/components/sidebar/workspace-card/controller/use-worktree-card-foundation.ts b/src/renderer/src/components/sidebar/workspace-card/controller/use-worktree-card-foundation.ts index 9af1e13c52a..10d9fd7d89f 100644 --- a/src/renderer/src/components/sidebar/workspace-card/controller/use-worktree-card-foundation.ts +++ b/src/renderer/src/components/sidebar/workspace-card/controller/use-worktree-card-foundation.ts @@ -152,10 +152,12 @@ export function useWorktreeCardFoundation({ }) const conflictOperation = useAppStore((s) => s.gitConflictOperationByWorktree[worktree.id]) const remoteBranchConflict = useAppStore((s) => s.remoteBranchConflictByWorktreeId[worktree.id]) - const workspacePorts = useAppStore( - (s) => - getWorkspacePortsByWorktreeId(s.workspacePortScan?.result).get(worktree.id) ?? - EMPTY_WORKSPACE_PORTS + const workspacePorts = useAppStore((s) => + // An asleep VM serves nothing: the last scan's ports would be a stale badge (JA-13). + s.ephemeralVmRuntimesByWorkspaceId?.[worktree.id]?.status === 'suspended' + ? EMPTY_WORKSPACE_PORTS + : (getWorkspacePortsByWorktreeId(s.workspacePortScan?.result).get(worktree.id) ?? + EMPTY_WORKSPACE_PORTS) ) // Avoid per-card host-qualified scans; twins use direct SSH status for this status-only chip. From f0bf32dd1613290b13125b265e5fa1ab9ffcb684 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:58:00 -0800 Subject: [PATCH 102/149] fix(cloud): Claude (not Claude Code) in the Orca Cloud MCP description; lint scope covers settings-nav copy; catalog cleanup --- .../orca-cloud/OrcaCloudSettings.fixture.tsx | 2 +- ...settings-navigation-orca-cloud-sections.ts | 2 +- .../src/i18n/en-runtime-required.json | 5 --- src/renderer/src/i18n/locales/en.json | 7 ++-- .../orca-cloud/cloud-glossary-allowlist.json | 2 +- .../orca-cloud/cloud-glossary-lint.test.ts | 38 +++++++++++++++---- 6 files changed, 36 insertions(+), 20 deletions(-) diff --git a/src/renderer/src/components/settings/orca-cloud/OrcaCloudSettings.fixture.tsx b/src/renderer/src/components/settings/orca-cloud/OrcaCloudSettings.fixture.tsx index 98e7427cb07..7290725663c 100644 --- a/src/renderer/src/components/settings/orca-cloud/OrcaCloudSettings.fixture.tsx +++ b/src/renderer/src/components/settings/orca-cloud/OrcaCloudSettings.fixture.tsx @@ -100,7 +100,7 @@ function mcpPage(workspaces: OrcaCloudMcpWorkspace[] | null | 'failed'): React.J `${e.path}:${e.line}:${e.term}` From ef5818012bfc741dae3e772a1d67e3b02e50639a Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:58:52 -0800 Subject: [PATCH 103/149] fix(cloud): move announcements name a workspace without a number by its title --- .../cloud-workspaces/use-cloud-workspace-arrangement.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/renderer/src/components/cloud-workspaces/use-cloud-workspace-arrangement.ts b/src/renderer/src/components/cloud-workspaces/use-cloud-workspace-arrangement.ts index 05e5f6855d9..26059499169 100644 --- a/src/renderer/src/components/cloud-workspaces/use-cloud-workspace-arrangement.ts +++ b/src/renderer/src/components/cloud-workspaces/use-cloud-workspace-arrangement.ts @@ -26,10 +26,11 @@ import { } from './cloud-workspace-prefs' import type { GroupDrag } from './CloudWorkspaceGroup' import type { RowArrangement } from './CloudWorkspaceRowMenu' +import { cloudWorkspaceTitle } from './open-cloud-workspace' /** How a screen reader hears a workspace in move confirmations: its number, else its title. */ function spoken(w: CloudWorkspace | undefined): string { - return w?.number ? formatWorkspaceNumber(w.number) : (w?.title ?? '') + return !w ? '' : w.number ? formatWorkspaceNumber(w.number) : cloudWorkspaceTitle(w) } function groupName(group: CloudWorkspaceGroup): string { From 7ce2885149eb2d07f3630692b9283f21ab1299e1 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:32:53 -0800 Subject: [PATCH 104/149] feat(cloud): JA-16 one Orca Cloud settings group led by Agent accounts; Orca account is identity + Sign out --- .../accounts/orca/OrcaAccountSettingsPane.tsx | 83 ++++++++++--------- .../orca-cloud/OrcaCloudSettings.fixture.tsx | 11 --- .../orca-cloud/OrcaCloudSettingsLinks.tsx | 54 ------------ ...tings-setup-workflow-section-renderers.tsx | 5 +- ...settings-navigation-capability-sections.ts | 4 +- ...ngs-navigation-orca-cloud-sections.test.ts | 50 ++++++++++- ...settings-navigation-orca-cloud-sections.ts | 22 +++++ .../hooks/useSettingsNavigationMetadata.ts | 24 ++++-- .../src/i18n/en-runtime-required.json | 3 + src/renderer/src/i18n/locales/en.json | 2 +- 10 files changed, 134 insertions(+), 124 deletions(-) delete mode 100644 src/renderer/src/components/settings/orca-cloud/OrcaCloudSettingsLinks.tsx diff --git a/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx b/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx index f730b1ed4c3..3ed751b6d8c 100644 --- a/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx +++ b/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx @@ -10,7 +10,6 @@ import { useTranslate, type Translate } from '@/i18n/use-translate' import { useAppStore } from '@/store/index' import { OrcaProfileSignOutConfirmDialog } from '../../../orca-profiles/OrcaProfileSignOutConfirmDialog' import { OrcaSignInButton, OrcaSignInWaitNotice } from '../../../OrcaSignInProgress' -import { OrcaCloudSettingsLinks } from '../../orca-cloud/OrcaCloudSettingsLinks' import { useOrcaCloudApiAvailable } from '@/hooks/useOrcaCloudApiAvailability' function accountStatusCopy( @@ -68,7 +67,6 @@ export function OrcaAccountSettingsPane(): React.JSX.Element { const t = useTranslate() const authStatus = useAppStore((state) => state.orcaProfileAuthStatus) const signOut = useAppStore((state) => state.signOutCurrentOrcaProfile) - const openSettingsTarget = useAppStore((state) => state.openSettingsTarget) const cloudAvailable = useOrcaCloudApiAvailable() const [signOutOpen, setSignOutOpen] = useState(false) const [signingOut, setSigningOut] = useState(false) @@ -133,51 +131,54 @@ export function OrcaAccountSettingsPane(): React.JSX.Element { {connected ? null : }
    - {connected && cloudAvailable ? ( - openSettingsTarget({ pane, repoId: null })} /> - ) : null} - -
    - -
    -
    + {/* JA-16: with Orca Cloud the page is identity + Sign out only; plan, team and agents have + their own entries in the Orca Cloud group right beside it. */} + {cloudAvailable ? null : ( +
    + +
    +
    + + +
    + {/* Put the third benefit below at full width so it cannot squeeze the existing pair. */} -
    - {/* Put the third benefit below at full width so it cannot squeeze the existing pair. */} -
    -
    + )}
    {} @@ -197,16 +196,6 @@ export const sessionExpired = defineFixture({ ) }) -/** Settings › Orca account, signed in: the Orca Cloud panes are one click away. */ -export const accountLinks = defineFixture({ - width: 720, - render: () => ( -
    - -
    - ) -}) - /** Settings › Agent API keys header: desktop keys are not for Orca Cloud; link to Cloud secrets. */ export const agentApiKeysHeader = defineFixture({ width: 784, diff --git a/src/renderer/src/components/settings/orca-cloud/OrcaCloudSettingsLinks.tsx b/src/renderer/src/components/settings/orca-cloud/OrcaCloudSettingsLinks.tsx deleted file mode 100644 index d5b204c71f6..00000000000 --- a/src/renderer/src/components/settings/orca-cloud/OrcaCloudSettingsLinks.tsx +++ /dev/null @@ -1,54 +0,0 @@ -import { Boxes, ChevronRight, CreditCard, LockKeyhole, Plug, Users } from 'lucide-react' -import type { LucideIcon } from 'lucide-react' -import { SettingsGroupHeader } from '@/components/settings/section-layout/SettingsGroup' -import { useTranslate } from '@/i18n/use-translate' -import type { SettingsNavTarget } from '@/lib/settings-navigation-types' - -type OrcaCloudLink = { pane: SettingsNavTarget; icon: LucideIcon; label: string } - -/** Settings › Orca account: the Orca Cloud panes live in their own group; this points at them. */ -export function OrcaCloudSettingsLinks({ - onOpen -}: { - onOpen: (pane: SettingsNavTarget) => void -}): React.JSX.Element { - const t = useTranslate() - const links: OrcaCloudLink[] = [ - { - pane: 'cloud-billing', - icon: CreditCard, - label: t('auto.components.billing.title', 'Plan & billing') - }, - { pane: 'cloud-team', icon: Users, label: t('auto.components.billing.team.title', 'Team') }, - { pane: 'cloud-secrets', icon: LockKeyhole, label: t('cloudSecrets.title', 'Cloud secrets') }, - { - pane: 'cloud-environments', - icon: Boxes, - label: t('settings.orcaCloud.environments.title', 'Cloud environments') - }, - { pane: 'cloud-mcp', icon: Plug, label: t('cloudMcpSync.title', 'MCP servers') } - ] - return ( - - ) -} diff --git a/src/renderer/src/components/settings/page/settings-setup-workflow-section-renderers.tsx b/src/renderer/src/components/settings/page/settings-setup-workflow-section-renderers.tsx index 2a10abea1fc..753b0547c30 100644 --- a/src/renderer/src/components/settings/page/settings-setup-workflow-section-renderers.tsx +++ b/src/renderer/src/components/settings/page/settings-setup-workflow-section-renderers.tsx @@ -24,10 +24,7 @@ export function renderOrcaAccountSettingsSection( title={t('auto.components.settings.orcaAccount.title', 'Orca account')} description={ model.orcaCloudApiAvailable - ? t( - 'settings.orcaAccount.descriptionWithCloud', - 'Sign-in, plan, team and Orca Cloud settings.' - ) + ? t('settings.orcaAccount.descriptionIdentity', 'The Orca account you’re signed in with.') : t( 'auto.components.settings.orcaAccount.description', 'Share work instantly and reach your desktop from Orca Mobile wherever you are.' diff --git a/src/renderer/src/hooks/settings-navigation-capability-sections.ts b/src/renderer/src/hooks/settings-navigation-capability-sections.ts index a8f1a273ebc..a15e16d6c54 100644 --- a/src/renderer/src/hooks/settings-navigation-capability-sections.ts +++ b/src/renderer/src/hooks/settings-navigation-capability-sections.ts @@ -170,8 +170,8 @@ export function buildSetupSettingsSections( title: t('auto.components.settings.orcaAccount.title', 'Orca account'), description: isOrcaCloudApiAvailable ? t( - 'settings.orcaAccount.descriptionWithCloud', - 'Sign-in, plan, team and Orca Cloud settings.' + 'settings.orcaAccount.descriptionIdentity', + 'The Orca account you’re signed in with.' ) : t( 'auto.components.settings.orcaAccount.description', diff --git a/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.test.ts b/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.test.ts index de57a415f0f..15b35d93f37 100644 --- a/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.test.ts +++ b/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.test.ts @@ -1,7 +1,12 @@ +import { Bot } from 'lucide-react' +import type { SettingsNavSection } from '@/lib/settings-navigation-types' import { describe, expect, it } from 'vitest' import { buildSetupSettingsSections } from './settings-navigation-capability-sections' import type { SettingsNavigationBuildOptions } from './settings-navigation-build-options' -import { buildOrcaCloudSettingsSections } from './settings-navigation-orca-cloud-sections' +import { + buildOrcaCloudSettingsSections, + gatherOrcaCloudSettingsGroup +} from './settings-navigation-orca-cloud-sections' function options(patch: Partial): SettingsNavigationBuildOptions { return { @@ -45,7 +50,7 @@ describe('Orca Cloud settings group', () => { const setup = buildSetupSettingsSections(options({})) expect(setup.some((section) => section.id.startsWith('cloud-'))).toBe(false) expect(setup.find((section) => section.id === 'orca-account')?.description).toBe( - 'Sign-in, plan, team and Orca Cloud settings.' + 'The Orca account you’re signed in with.' ) const local = buildSetupSettingsSections(options({ isOrcaCloudApiAvailable: false })) expect(local.find((section) => section.id === 'orca-account')?.description).not.toMatch( @@ -53,3 +58,44 @@ describe('Orca Cloud settings group', () => { ) }) }) + +describe('one Orca Cloud group (JA-16)', () => { + const nav = (id: string, group: SettingsNavSection['group']): SettingsNavSection => ({ + id, + title: id, + description: '', + icon: Bot, + searchEntries: [], + group + }) + + const all = [ + nav('agents', 'capabilities'), + nav('accounts', 'capabilities'), + nav('orca-account', 'setup'), + nav('general', 'setup'), + nav('cloud-billing', 'orca-cloud'), + nav('cloud-team', 'orca-cloud'), + nav('automations', 'workflows') + ] + + it('leads the Orca Cloud group with Agent accounts and the Orca account', () => { + const out = gatherOrcaCloudSettingsGroup(all, options({})) + expect(out.map((section) => `${section.group}:${section.id}`)).toEqual([ + 'capabilities:agents', + 'setup:general', + 'orca-cloud:accounts', + 'orca-cloud:orca-account', + 'orca-cloud:cloud-billing', + 'orca-cloud:cloud-team', + 'workflows:automations' + ]) + }) + + it('leaves the upstream grouping alone without Orca Cloud', () => { + expect(gatherOrcaCloudSettingsGroup(all, options({ isOrcaCloudApiAvailable: false }))).toEqual( + all + ) + expect(gatherOrcaCloudSettingsGroup(all, options({ isWebClient: true }))).toEqual(all) + }) +}) diff --git a/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.ts b/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.ts index 8384c60f7d1..a23d3bd819c 100644 --- a/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.ts +++ b/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.ts @@ -104,3 +104,25 @@ export function buildOrcaCloudSettingsSections( } ] } + +/** + * JA-16: in Orca Cloud builds every cloud entry sits in one group, led by Agent accounts and the + * Orca account, instead of being split across AI capabilities, Set up and Orca Cloud. + */ +export function gatherOrcaCloudSettingsGroup( + sections: readonly SettingsNavSection[], + { isWebClient, isOrcaCloudApiAvailable }: SettingsNavigationBuildOptions +): SettingsNavSection[] { + if (isWebClient || !isOrcaCloudApiAvailable) { + return [...sections] + } + const leadIds = ['accounts', 'orca-account'] + const leads = leadIds + .map((id) => sections.find((section) => section.id === id)) + .filter((section): section is SettingsNavSection => section !== undefined) + .map((section) => ({ ...section, group: 'orca-cloud' as const })) + const rest = sections.filter((section) => !leadIds.includes(section.id)) + const firstCloud = rest.findIndex((section) => section.group === 'orca-cloud') + const at = firstCloud === -1 ? rest.length : firstCloud + return [...rest.slice(0, at), ...leads, ...rest.slice(at)] +} diff --git a/src/renderer/src/hooks/useSettingsNavigationMetadata.ts b/src/renderer/src/hooks/useSettingsNavigationMetadata.ts index 5f8a00fc898..8aa97b29d71 100644 --- a/src/renderer/src/hooks/useSettingsNavigationMetadata.ts +++ b/src/renderer/src/hooks/useSettingsNavigationMetadata.ts @@ -31,7 +31,10 @@ import { buildSetupSettingsSections } from './settings-navigation-capability-sections' import type { SettingsNavigationBuildOptions } from './settings-navigation-build-options' -import { buildOrcaCloudSettingsSections } from './settings-navigation-orca-cloud-sections' +import { + buildOrcaCloudSettingsSections, + gatherOrcaCloudSettingsGroup +} from './settings-navigation-orca-cloud-sections' import { buildInterfaceSettingsSections } from './settings-navigation-interface-sections' import { buildRemoteSettingsSections } from './settings-navigation-remote-sections' import { buildWorkflowSettingsSections } from './settings-navigation-workflow-sections' @@ -110,14 +113,17 @@ export function buildSettingsNavigationMetadata( } // Match SETTINGS_NAV_GROUPS order so Settings and Cmd+J keep siblings together. - return [ - ...buildCapabilitySettingsSections(options, t), - ...buildSetupSettingsSections(options, t), - ...buildOrcaCloudSettingsSections(options, t), - ...buildWorkflowSettingsSections(options, terminalPaneSearchEntries, t), - ...buildInterfaceSettingsSections(options, t), - ...buildRemoteSettingsSections(options, runtimeEnvironmentsSearchEntry, reposById, t) - ] + return gatherOrcaCloudSettingsGroup( + [ + ...buildCapabilitySettingsSections(options, t), + ...buildSetupSettingsSections(options, t), + ...buildOrcaCloudSettingsSections(options, t), + ...buildWorkflowSettingsSections(options, terminalPaneSearchEntries, t), + ...buildInterfaceSettingsSections(options, t), + ...buildRemoteSettingsSections(options, runtimeEnvironmentsSearchEntry, reposById, t) + ], + options + ) } export function useSettingsNavigationMetadata(): SettingsNavSection[] { diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 7208c28db92..4c295f6dceb 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -2478,6 +2478,9 @@ "sendingNotConfigured": "sending diagnostics is not configured for this build" } }, + "groups": { + "orcaCloud": "Orca Cloud" + }, "mcp": { "serverCount_one": "{{count}} server", "serverCount_other": "{{count}} servers" diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 37135bf63c2..5b7d5b55ccc 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -1397,7 +1397,7 @@ "orcaCloud": "Orca Cloud" }, "orcaAccount": { - "descriptionWithCloud": "Sign-in, plan, team and Orca Cloud settings." + "descriptionIdentity": "The Orca account you’re signed in with." }, "agentAccounts": { "searchTitle": "Agent accounts", From c2bcbf85291fba7795e6ad4f83fae0bd14a746fe Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 21:01:52 -0800 Subject: [PATCH 105/149] fix(cloud): status popover footer never clips: Move to this computer on its own row, actions wrap (DS-l); test the card's host row (JA-13) --- .../orca-cloud/CloudWorkspaceStatusPanel.tsx | 28 +++--- .../default-workspace-card-host-row.test.tsx | 97 +++++++++++++++++++ 2 files changed, 113 insertions(+), 12 deletions(-) create mode 100644 src/renderer/src/components/sidebar/workspace-card/template/default-workspace-card-host-row.test.tsx diff --git a/src/renderer/src/components/orca-cloud/CloudWorkspaceStatusPanel.tsx b/src/renderer/src/components/orca-cloud/CloudWorkspaceStatusPanel.tsx index 4a2bad51a26..ba1de73ac81 100644 --- a/src/renderer/src/components/orca-cloud/CloudWorkspaceStatusPanel.tsx +++ b/src/renderer/src/components/orca-cloud/CloudWorkspaceStatusPanel.tsx @@ -325,6 +325,20 @@ export function CloudWorkspaceStatusPanel({ ) : null} + {showFooter && actions.onMoveToComputer && canArchive && !restarting ? ( + // Its own row (DS-l): beside Sleep, Archive and Restart it pushed them out of the popover. +
    + +
    + ) : null} {showFooter ? (
    {/* Not a live region: a ticking "ago" would announce itself every few seconds. */} @@ -335,18 +349,8 @@ export function CloudWorkspaceStatusPanel({ }) : null} -
    - {actions.onMoveToComputer && canArchive && !restarting ? ( - - ) : null} + {/* Wraps rather than clips: every action stays reachable at any panel width (DS-l). */} +
    {actions.onSleep && state === 'running' && !restarting ? ( +

    + ) : entitlement ? ( - -
    - ) -} diff --git a/src/renderer/src/components/settings/orca-cloud/OrcaCloudSettingsPanes.tsx b/src/renderer/src/components/settings/orca-cloud/OrcaCloudSettingsPanes.tsx index c6192ceeeee..f40cdaa3d23 100644 --- a/src/renderer/src/components/settings/orca-cloud/OrcaCloudSettingsPanes.tsx +++ b/src/renderer/src/components/settings/orca-cloud/OrcaCloudSettingsPanes.tsx @@ -7,7 +7,7 @@ import { useOrcaProfileAuthStatusRefresh } from '@/hooks/use-orca-profile-auth-s import { useTranslate } from '@/i18n/use-translate' import { useAppStore } from '@/store' import { PlanBillingSection } from '../../billing/PlanBillingSection' -import { TeamSettingsLink } from '../../billing/team/TeamSettingsLink' +import { TeamPageBody } from '../../billing/team/TeamDialogHost' import { CloudEnvironmentSection, useOrcaCloudEnvironmentsAvailability @@ -113,7 +113,19 @@ export function OrcaCloudTeamPane(): React.JSX.Element { {(account) => account.billing ? ( - + // JA-17: members inline (invite field, then the table); seats and invoices stay on + // Plan & billing, linked. Remount per team so row state never carries over. + { + const store = useAppStore.getState() + store.openSettingsTarget({ pane: 'cloud-billing', repoId: null }) + store.openSettingsPage() + } + }} + /> ) : ( Date: Tue, 10 Nov 2026 21:08:10 -0800 Subject: [PATCH 109/149] feat(cloud): MEMBER_REMOVED_TOKEN, a bearer valid only for /v1/internal/org-members/removed Auth pushes PropelAuth offboarding and Orca-side member removals here (stablyai/orca-cloud#739); it should not need the full operator token for that. The operator token is still accepted. --- cloud/apps/sandbox-control/src/env.ts | 6 ++++++ cloud/apps/sandbox-control/src/index.ts | 7 ++++++- .../sandbox-control/test/team-presence.test.ts | 15 +++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/cloud/apps/sandbox-control/src/env.ts b/cloud/apps/sandbox-control/src/env.ts index 08ec6d476de..c0c9c9faa5a 100644 --- a/cloud/apps/sandbox-control/src/env.ts +++ b/cloud/apps/sandbox-control/src/env.ts @@ -132,6 +132,12 @@ export type Env = { /** Operator routes (/v1/internal/*): kill switch, drain, bindings. Secret, >= 32 chars; unset = no routes. */ OPERATOR_TOKEN?: string + /** + * Auth's bearer for POST /v1/internal/org-members/removed only (PropelAuth offboarding and + * Orca-side removals). Secret, >= 32 chars; lets auth push removals without holding the + * operator token. The operator token is still accepted on that route. + */ + MEMBER_REMOVED_TOKEN?: string /** `true` refuses every create/resume/rollover (static kill switch; the D1 flag is the runtime one). */ SANDBOX_CREATES_DISABLED?: string /** Warm pool size (pool.ts); unset or 0 = off. */ diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 5edaae7c49a..8107dfbf757 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -1146,7 +1146,12 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) return await internalInstallUrl(env, deps, url) } if (url.pathname.startsWith('/v1/internal/')) { - if (!(await isOperator(request, env.OPERATOR_TOKEN))) { + // Auth's member-removed push holds a token good for that one route, not the operator token. + const memberRemovedOnly = + url.pathname === '/v1/internal/org-members/removed' && + request.method === 'POST' && + (await isOperator(request, env.MEMBER_REMOVED_TOKEN)) + if (!memberRemovedOnly && !(await isOperator(request, env.OPERATOR_TOKEN))) { return fail('not_found', 404) } const life = await lifecycleDeps(env, deps) diff --git a/cloud/apps/sandbox-control/test/team-presence.test.ts b/cloud/apps/sandbox-control/test/team-presence.test.ts index c8e0c256ddd..8a47fe8e2f7 100644 --- a/cloud/apps/sandbox-control/test/team-presence.test.ts +++ b/cloud/apps/sandbox-control/test/team-presence.test.ts @@ -180,3 +180,18 @@ describe('pokes', () => { expect((await t.req(solo, 'GET', '/v1/team/pokes')).body).toEqual({ enabled: false, pokes: [] }) }) }) + +describe('member-removed token', () => { + it('authorizes only POST /v1/internal/org-members/removed, never other operator routes', async () => { + const MR = 'm'.repeat(40) + const body = { accountId: 'org:acme', userId: 'bob' } + const h = await createHarness({ OPERATOR_TOKEN: 'o'.repeat(40), MEMBER_REMOVED_TOKEN: MR }) + expect((await h.call('POST', '/v1/internal/org-members/removed', { bearer: MR, body })).status).toBe(200) + expect((await h.call('GET', '/v1/internal/status', { bearer: MR })).status).toBe(404) + expect((await h.call('POST', '/v1/internal/members/removed', { bearer: MR, body })).status).toBe(404) + // The operator token still works on the route; a short token is never accepted. + expect((await h.call('POST', '/v1/internal/org-members/removed', { bearer: 'o'.repeat(40), body })).status).toBe(200) + const weak = await createHarness({ OPERATOR_TOKEN: 'o'.repeat(40), MEMBER_REMOVED_TOKEN: 'short' }) + expect((await weak.call('POST', '/v1/internal/org-members/removed', { bearer: 'short', body })).status).toBe(404) + }) +}) From 0335884b8aae55f65d437efa11a9cdf5c5b5fe9d Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 21:10:13 -0800 Subject: [PATCH 110/149] fix(cloud): JA-16 keep Agent accounts in AI capabilities; Orca account leads the Orca Cloud group --- .../hooks/settings-navigation-orca-cloud-sections.test.ts | 4 ++-- .../src/hooks/settings-navigation-orca-cloud-sections.ts | 7 ++++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.test.ts b/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.test.ts index 15b35d93f37..6a649081a17 100644 --- a/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.test.ts +++ b/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.test.ts @@ -79,12 +79,12 @@ describe('one Orca Cloud group (JA-16)', () => { nav('automations', 'workflows') ] - it('leads the Orca Cloud group with Agent accounts and the Orca account', () => { + it('leads the Orca Cloud group with the Orca account; Agent accounts stays in AI capabilities', () => { const out = gatherOrcaCloudSettingsGroup(all, options({})) expect(out.map((section) => `${section.group}:${section.id}`)).toEqual([ 'capabilities:agents', + 'capabilities:accounts', 'setup:general', - 'orca-cloud:accounts', 'orca-cloud:orca-account', 'orca-cloud:cloud-billing', 'orca-cloud:cloud-team', diff --git a/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.ts b/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.ts index a23d3bd819c..0e3c2b78680 100644 --- a/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.ts +++ b/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.ts @@ -106,8 +106,9 @@ export function buildOrcaCloudSettingsSections( } /** - * JA-16: in Orca Cloud builds every cloud entry sits in one group, led by Agent accounts and the - * Orca account, instead of being split across AI capabilities, Set up and Orca Cloud. + * JA-16: in Orca Cloud builds the Orca account leads the one Orca Cloud group instead of sitting in + * Set up. Agent accounts stays in AI capabilities: it covers this computer and hosts as much as + * Orca Cloud, and its Orca Cloud part is deep-linked from every cloud entry point. */ export function gatherOrcaCloudSettingsGroup( sections: readonly SettingsNavSection[], @@ -116,7 +117,7 @@ export function gatherOrcaCloudSettingsGroup( if (isWebClient || !isOrcaCloudApiAvailable) { return [...sections] } - const leadIds = ['accounts', 'orca-account'] + const leadIds = ['orca-account'] const leads = leadIds .map((id) => sections.find((section) => section.id === id)) .filter((section): section is SettingsNavSection => section !== undefined) From 4c1f825eddd2c4b68cc977c99c8d1d71915e828c Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 21:16:48 -0800 Subject: [PATCH 111/149] chore(cloud-auth): JA-02 premerge fixes (drop unused signInTimedOut key, fixed test expiry, service under max-lines) --- ...ofile-cloud-service-sign-in-cancel.test.ts | 7 +++-- .../orca-profiles/profile-cloud-service.ts | 31 +++++++------------ src/renderer/src/i18n/locales/de.json | 3 +- src/renderer/src/i18n/locales/en.json | 1 - src/renderer/src/i18n/locales/es.json | 3 +- src/renderer/src/i18n/locales/fr.json | 3 +- src/renderer/src/i18n/locales/ja.json | 3 +- src/renderer/src/i18n/locales/ko.json | 3 +- src/renderer/src/i18n/locales/pt.json | 3 +- src/renderer/src/i18n/locales/ru.json | 3 +- src/renderer/src/i18n/locales/tr.json | 3 +- src/renderer/src/i18n/locales/zh-Hant.json | 3 +- src/renderer/src/i18n/locales/zh.json | 3 +- 13 files changed, 27 insertions(+), 42 deletions(-) diff --git a/src/main/orca-profiles/profile-cloud-service-sign-in-cancel.test.ts b/src/main/orca-profiles/profile-cloud-service-sign-in-cancel.test.ts index 8e590b412bb..6b7dab91dd5 100644 --- a/src/main/orca-profiles/profile-cloud-service-sign-in-cancel.test.ts +++ b/src/main/orca-profiles/profile-cloud-service-sign-in-cancel.test.ts @@ -50,6 +50,9 @@ const cloud: OrcaProfileCloudSummary = { linkedAt: 10 } +// A fixed far-future expiry: no wall clock in tests. +const EXPIRES_AT = 4_102_444_800_000 + const code = { code: 'the-code', codeVerifier: 'verifier', @@ -88,7 +91,7 @@ describe('Orca Cloud sign-in cancel, supersede and timeout', () => { exchangeOrcaCloudAuthCodeMock.mockResolvedValue({ accessToken: 'access-token', refreshToken: 'refresh-token', - expiresAt: Date.now() + 3_600_000, + expiresAt: EXPIRES_AT, cloud, organizations: [], capabilities: { flags: {}, refreshedAt: 1 } @@ -121,7 +124,7 @@ describe('Orca Cloud sign-in cancel, supersede and timeout', () => { return { accessToken: 'access-token', refreshToken: 'refresh-token', - expiresAt: Date.now() + 3_600_000, + expiresAt: EXPIRES_AT, cloud, organizations: [], capabilities: { flags: {}, refreshedAt: 1 } diff --git a/src/main/orca-profiles/profile-cloud-service.ts b/src/main/orca-profiles/profile-cloud-service.ts index 804acb76019..616151ba594 100644 --- a/src/main/orca-profiles/profile-cloud-service.ts +++ b/src/main/orca-profiles/profile-cloud-service.ts @@ -108,6 +108,7 @@ export async function connectCurrentOrcaProfile( status: 'cancelled', auth: getCurrentOrcaProfileAuthStatus(userDataPath) }) + const stale = (): boolean => attempt < linkedCloudConnectAttempt || attemptAbort.signal.aborted let end: 'timed-out' | undefined startOrcaCloudSignInProgress(attempt, () => attemptAbort.abort()) let finishBrowser: ((location: string | null) => void) | undefined @@ -120,7 +121,7 @@ export async function connectCurrentOrcaProfile( finishBrowser = code.finishBrowser // The callback listener has closed, so its browser link is dead. setOrcaCloudSignInLink(attempt, null) - if (attempt < linkedCloudConnectAttempt || attemptAbort.signal.aborted) { + if (stale()) { return cancelled() } const exchange = await exchangeOrcaCloudAuthCode(configState.config, { @@ -131,7 +132,7 @@ export async function connectCurrentOrcaProfile( state: code.state, localProfileId: active.profile.id }) - if (attempt < linkedCloudConnectAttempt || attemptAbort.signal.aborted) { + if (stale()) { return cancelled() } signInCloudSession(active.profile.id, userDataPath, exchange) @@ -149,26 +150,18 @@ export async function connectCurrentOrcaProfile( profiles: list.profiles } } catch (error) { - if (attemptAbort.signal.aborted) { - return cancelled() - } const message = error instanceof Error ? error.message : String(error) - if (message === 'orca_cloud_auth_timeout' && attempt === nextCloudConnectAttempt) { + if (!stale() && message === 'orca_cloud_auth_timeout' && attempt === nextCloudConnectAttempt) { end = 'timed-out' - return { - status: 'timed-out', - auth: getCurrentOrcaProfileAuthStatus(userDataPath) - } + return { status: 'timed-out', auth: getCurrentOrcaProfileAuthStatus(userDataPath) } } - if ( - message === 'orca_cloud_auth_timeout' || - message === 'orca_cloud_auth_denied' || - message === 'orca_cloud_auth_cancelled' - ) { - return { - status: 'cancelled', - auth: getCurrentOrcaProfileAuthStatus(userDataPath) - } + const stopped = [ + 'orca_cloud_auth_timeout', + 'orca_cloud_auth_denied', + 'orca_cloud_auth_cancelled' + ] + if (attemptAbort.signal.aborted || stopped.includes(message)) { + return cancelled() } return { status: 'failed', diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index da42f7dc588..b9c8e2d53c3 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -1369,8 +1369,7 @@ "76deec8f58": "Organisation konnte nicht gewechselt werden", "7d4bc516ee": "Profil konnte nicht gewechselt werden", "f518e89aa5": "Projekt existiert bereits in diesem Profil", - "f03ae7f27b": "Projekt konnte nicht übertragen werden", - "signInTimedOut": "Zeitüberschreitung bei der Anmeldung" + "f03ae7f27b": "Projekt konnte nicht übertragen werden" } }, "runtime": { diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index d9edcf7a865..b5c95a442ec 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -1770,7 +1770,6 @@ "7d4bc516ee": "Failed to switch profile", "f518e89aa5": "Project already exists in that profile", "f03ae7f27b": "Failed to transfer project", - "signInTimedOut": "Sign-in timed out", "signInDidNotFinish": "Sign-in didn’t finish. Try again." } }, diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 9c1d8875de5..51ebcfac0b7 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -901,8 +901,7 @@ "76deec8f58": "Error al cambiar organización", "7d4bc516ee": "Error al cambiar perfil", "f518e89aa5": "El proyecto ya existe en ese perfil", - "f03ae7f27b": "Error al transferir proyecto", - "signInTimedOut": "Se agotó el tiempo de inicio de sesión" + "f03ae7f27b": "Error al transferir proyecto" } }, "runtime": { diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index f2d2e144ea7..35769520af7 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -1140,8 +1140,7 @@ "76deec8f58": "Échec du changement d'organisation", "7d4bc516ee": "Échec du changement de profil", "f518e89aa5": "Le projet existe déjà dans ce profil", - "f03ae7f27b": "Échec du transfert du projet", - "signInTimedOut": "La connexion a expiré" + "f03ae7f27b": "Échec du transfert du projet" } }, "runtime": { diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 777e8b02ace..0098e96735e 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -893,8 +893,7 @@ "76deec8f58": "組織の切り替えに失敗しました", "7d4bc516ee": "プロファイルの切り替えに失敗しました", "f518e89aa5": "プロジェクトはそのプロファイルに既に存在します", - "f03ae7f27b": "プロジェクトの転送に失敗しました", - "signInTimedOut": "サインインがタイムアウトしました" + "f03ae7f27b": "プロジェクトの転送に失敗しました" } }, "runtime": { diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index c27cc5f9960..a7522f8814a 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -893,8 +893,7 @@ "76deec8f58": "조직을 전환하지 못했습니다", "7d4bc516ee": "프로필을 전환하지 못했습니다", "f518e89aa5": "프로젝트가 해당 프로필에 이미 있습니다", - "f03ae7f27b": "프로젝트를 전송하지 못했습니다", - "signInTimedOut": "로그인 시간이 초과되었습니다" + "f03ae7f27b": "프로젝트를 전송하지 못했습니다" } }, "runtime": { diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index 55eb96f0783..4aaf90509e3 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -2126,8 +2126,7 @@ "76deec8f58": "Falha ao alternar organização", "7d4bc516ee": "Falha ao alternar perfil", "f518e89aa5": "O projeto já existe nesse perfil", - "f03ae7f27b": "Falha ao transferir o projeto", - "signInTimedOut": "O tempo para entrar expirou" + "f03ae7f27b": "Falha ao transferir o projeto" } }, "runtime": { diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json index e5d7a6a5c24..ae46963e936 100644 --- a/src/renderer/src/i18n/locales/ru.json +++ b/src/renderer/src/i18n/locales/ru.json @@ -1413,8 +1413,7 @@ "76deec8f58": "Не удалось переключить организацию", "7d4bc516ee": "Не удалось переключить профиль", "f518e89aa5": "Проект уже есть в этом профиле", - "f03ae7f27b": "Не удалось перенести проект", - "signInTimedOut": "Время ожидания входа истекло" + "f03ae7f27b": "Не удалось перенести проект" } }, "runtime": { diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index cd743b5d284..c177705246a 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -1345,8 +1345,7 @@ "76deec8f58": "Organizasyon değiştirilemedi", "7d4bc516ee": "Profil değiştirilemedi", "f518e89aa5": "Proje bu profilde zaten mevcut", - "f03ae7f27b": "Proje aktarılamadı", - "signInTimedOut": "Oturum açma zaman aşımına uğradı" + "f03ae7f27b": "Proje aktarılamadı" } }, "runtime": { diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index 3601fb61dc4..d95071e08bb 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -1317,8 +1317,7 @@ "76deec8f58": "切換組織失敗", "7d4bc516ee": "切換設定檔失敗", "f518e89aa5": "該專案已存在於那個設定檔中", - "f03ae7f27b": "轉移專案失敗", - "signInTimedOut": "登入逾時" + "f03ae7f27b": "轉移專案失敗" } }, "runtime": { diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 1ec99e797c3..4fba1ecd200 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -893,8 +893,7 @@ "76deec8f58": "切换组织失败", "7d4bc516ee": "切换配置文件失败", "f518e89aa5": "该项目已存在于那个配置文件中", - "f03ae7f27b": "转移项目失败", - "signInTimedOut": "登录超时" + "f03ae7f27b": "转移项目失败" } }, "runtime": { From 4241d8f6e02cc8b5feb9716be413aae2e307da7e Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 21:24:01 -0800 Subject: [PATCH 112/149] fix(sleep): keep the asleep mark outside the layout (asleepBrowserWorktreeIds); sleep writes no layout (NEW-01) --- .../use-worktree-context-menu-model.tsx | 7 +- .../workspace-lineage-menu-actions.ts | 4 +- .../sleep/browser-tab-sleep.test.ts | 50 +++++----- .../sleep/browser-tab-sleep.ts | 93 ++++++++++--------- .../sleep/use-worktree-sleep-state.ts | 4 +- ...e-visible-workspace-kanban-worktree-ids.ts | 3 +- .../activity/use-worktree-activity-status.ts | 7 +- .../use-worktree-activity-statuses.ts | 4 +- .../listing/sleeping-sweep-visibility.ts | 5 +- .../listing/use-visible-worktrees.ts | 5 +- .../visible-worktree-activity-inputs.ts | 8 +- .../visible-worktree-options-from-state.ts | 3 +- .../workspace-activity-shadow.ts | 4 +- .../src/lib/worktree-activity-state.ts | 5 +- src/renderer/src/lib/worktree-status.ts | 11 +-- .../slices/browser/browser-slice-contract.ts | 2 + .../slices/browser/create-browser-slice.ts | 1 + src/shared/browser-workspace-types.ts | 5 - .../workspace-layout-disk-fields.ts | 4 +- 19 files changed, 123 insertions(+), 102 deletions(-) diff --git a/src/renderer/src/components/sidebar/workspace-actions/context-menu/use-worktree-context-menu-model.tsx b/src/renderer/src/components/sidebar/workspace-actions/context-menu/use-worktree-context-menu-model.tsx index 469c7cf90fa..990f23049c5 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/context-menu/use-worktree-context-menu-model.tsx +++ b/src/renderer/src/components/sidebar/workspace-actions/context-menu/use-worktree-context-menu-model.tsx @@ -1,3 +1,4 @@ +import { selectAwakeBrowserTabsByWorktree } from '@/components/sidebar/workspace-actions/sleep/browser-tab-sleep' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useAppStore } from '@/store' import { useRepoById } from '@/store/repos/use-repository-catalog' @@ -107,7 +108,11 @@ export function useWorktreeContextMenuModel({ selectMenuScopedMap(menuOpen, s.ptyIdsByTabId, EMPTY_PTY_IDS_BY_TAB_ID) ) const browserTabsByWorktree = useAppStore((s) => - selectMenuScopedMap(menuOpen, s.browserTabsByWorktree, EMPTY_BROWSER_TABS_BY_WORKTREE) + selectMenuScopedMap( + menuOpen, + selectAwakeBrowserTabsByWorktree(s), + EMPTY_BROWSER_TABS_BY_WORKTREE + ) ) const unifiedTabsByWorktree = useAppStore((s) => selectMenuScopedMap(menuOpen, s.unifiedTabsByWorktree, EMPTY_UNIFIED_TABS_BY_WORKTREE) diff --git a/src/renderer/src/components/sidebar/workspace-actions/context-menu/workspace-lineage-menu-actions.ts b/src/renderer/src/components/sidebar/workspace-actions/context-menu/workspace-lineage-menu-actions.ts index ae45592fd84..645697c35c3 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/context-menu/workspace-lineage-menu-actions.ts +++ b/src/renderer/src/components/sidebar/workspace-actions/context-menu/workspace-lineage-menu-actions.ts @@ -11,7 +11,7 @@ import { getWorkspaceDeleteLineage } from '../deletion/workspace-delete-lineage' type WorkspaceActivityMaps = { tabsByWorktree: Record ptyIdsByTabId: Record - browserTabsByWorktree: Record + browserTabsByWorktree: Record unifiedTabsByWorktree: Record agentStatusByPaneKey: Record structuredChatSleptAtByPaneKey: StructuredChatSleptAtByPaneKey @@ -30,7 +30,7 @@ export function hasSleepableWorkspaceActivity( const tabs = activity.tabsByWorktree[worktreeId] ?? [] return ( tabs.some((tab) => tabHasLivePty(activity.ptyIdsByTabId, tab.id)) || - (activity.browserTabsByWorktree[worktreeId] ?? []).some((tab) => !tab.sleptAt) || + (activity.browserTabsByWorktree[worktreeId] ?? []).length > 0 || // An idle-ended chat still needs Sleep to hide it, even when its legacy tab has no host stamp. (activity.unifiedTabsByWorktree[worktreeId] ?? []).some( (tab) => diff --git a/src/renderer/src/components/sidebar/workspace-actions/sleep/browser-tab-sleep.test.ts b/src/renderer/src/components/sidebar/workspace-actions/sleep/browser-tab-sleep.test.ts index 5d46053752d..c83180025f3 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/sleep/browser-tab-sleep.test.ts +++ b/src/renderer/src/components/sidebar/workspace-actions/sleep/browser-tab-sleep.test.ts @@ -4,27 +4,36 @@ import type { BrowserWorkspace } from '../../../../../../shared/browser-workspac type State = { activeWorktreeId: string | null browserTabsByWorktree: Record - browserPagesByWorkspace: Record + asleepBrowserWorktreeIds: Record + browserPagesByWorkspace: Record activeBrowserTabIdByWorktree: Record } const mocks = vi.hoisted(() => { - const listeners = new Set<(state: unknown) => void>() + const listeners = new Set<(state: State) => void>() + const initial: State = { + activeWorktreeId: null, + browserTabsByWorktree: {}, + asleepBrowserWorktreeIds: {}, + browserPagesByWorkspace: {}, + activeBrowserTabIdByWorktree: {} + } const store = { - state: {} as Record, - getState: () => store.state, - setState: (change: (state: Record) => Record) => { + state: initial, + getState: (): State => store.state, + setState: (change: (state: State) => Partial): void => { store.state = { ...store.state, ...change(store.state) } for (const listener of listeners) { listener(store.state) } }, - subscribe: (listener: (state: unknown) => void) => { + subscribe: (listener: (state: State) => void): (() => void) => { listeners.add(listener) return () => listeners.delete(listener) } } - return { store, evicted: [] as string[] } + const evicted: string[] = [] + return { store, evicted } }) vi.mock('@/store', () => ({ useAppStore: mocks.store })) vi.mock('@/store/slices/browser/cleanup/browser-webview-cleanup', () => ({ @@ -32,9 +41,8 @@ vi.mock('@/store/slices/browser/cleanup/browser-webview-cleanup', () => ({ mocks.evicted.push(worktreeId) })) -const { sleepWorktreeBrowserTabs, installBrowserTabWakeOnOpen } = await import( - './browser-tab-sleep' -) +const { sleepWorktreeBrowserTabs, installBrowserTabWakeOnOpen, selectAwakeBrowserTabsByWorktree } = + await import('./browser-tab-sleep') const { isInactiveWorkspace } = await import('@/lib/worktree-activity-state') const tab = (id: string): BrowserWorkspace => ({ @@ -50,13 +58,16 @@ const tab = (id: string): BrowserWorkspace => ({ createdAt: 1 }) -const state = (): State => mocks.store.getState() as unknown as State +const state = (): State => mocks.store.getState() +const inactive = (): boolean => + isInactiveWorkspace('wt', {}, {}, selectAwakeBrowserTabsByWorktree(state()), new Set()) beforeEach(() => { mocks.evicted.length = 0 mocks.store.state = { activeWorktreeId: null, browserTabsByWorktree: { wt: [tab('a'), tab('b'), tab('c')] }, + asleepBrowserWorktreeIds: {}, browserPagesByWorkspace: {}, activeBrowserTabIdByWorktree: { wt: 'b' } } @@ -64,31 +75,28 @@ beforeEach(() => { describe('sleep keeps browser tabs in place (NEW-01)', () => { it('keeps every tab, in order, with the same active tab; drops only their pages', () => { + const before = state().browserTabsByWorktree sleepWorktreeBrowserTabs('wt', 42) expect(mocks.evicted).toEqual(['wt']) + // The layout itself is untouched: same object, same order, same active tab. + expect(state().browserTabsByWorktree).toBe(before) expect(state().browserTabsByWorktree.wt.map((t) => t.id)).toEqual(['a', 'b', 'c']) - expect(state().browserTabsByWorktree.wt.every((t) => t.sleptAt === 42)).toBe(true) expect(state().activeBrowserTabIdByWorktree.wt).toBe('b') }) it('asleep tabs are not activity, so the workspace still reads as asleep', () => { - const inactive = (): boolean => - isInactiveWorkspace('wt', {}, {}, state().browserTabsByWorktree, new Set()) expect(inactive()).toBe(false) sleepWorktreeBrowserTabs('wt', 42) expect(inactive()).toBe(true) }) - it('opening the workspace again wakes its tabs, still in the same order', () => { + it('opening the workspace again wakes its tabs', () => { const stop = installBrowserTabWakeOnOpen() sleepWorktreeBrowserTabs('wt', 42) mocks.store.setState(() => ({ activeWorktreeId: 'wt' })) - expect(state().browserTabsByWorktree.wt.map((t) => [t.id, t.sleptAt])).toEqual([ - ['a', undefined], - ['b', undefined], - ['c', undefined] - ]) - expect(state().activeBrowserTabIdByWorktree.wt).toBe('b') + expect(state().asleepBrowserWorktreeIds).toEqual({}) + expect(inactive()).toBe(false) + expect(state().browserTabsByWorktree.wt.map((t) => t.id)).toEqual(['a', 'b', 'c']) stop() }) }) diff --git a/src/renderer/src/components/sidebar/workspace-actions/sleep/browser-tab-sleep.ts b/src/renderer/src/components/sidebar/workspace-actions/sleep/browser-tab-sleep.ts index 22c63636083..9502292d619 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/sleep/browser-tab-sleep.ts +++ b/src/renderer/src/components/sidebar/workspace-actions/sleep/browser-tab-sleep.ts @@ -1,45 +1,48 @@ // Sleep never changes a workspace's tab layout (NEW-01). Its browser tabs stay where they are, in -// the same order with the same active tab; only their pages are dropped to free memory, and each -// tab is marked asleep so it no longer counts as activity (an asleep workspace still reads as -// asleep and hides with "Hide sleeping"). Opening the workspace again wakes the tabs: each page -// reloads in place when it is shown. A remote desktop tab's own chrome reconnects it after a wake. +// the same order with the same active tab; only their pages are dropped to free memory, and the +// workspace's tabs are marked asleep so they no longer count as activity (an asleep workspace still +// reads as asleep and hides with "Hide sleeping"). Opening the workspace again wakes them: each +// page reloads in place when it is shown. A remote desktop tab's own chrome reconnects it after a +// wake. The mark lives outside the layout (asleepBrowserWorktreeIds), so sleep writes no layout. import { useAppStore } from '@/store' import { destroyWorktreeBrowserGuests } from '@/store/slices/browser/cleanup/browser-webview-cleanup' import type { BrowserWorkspace } from '../../../../../../shared/browser-workspace-types' -/** Awake tabs are activity; a tab Sleep put to rest is not, until the workspace is opened again. */ -export function isAwakeBrowserTab(tab: { sleptAt?: number | null }): boolean { - return !tab.sleptAt -} +type BrowserTabsByWorktree = Record -export function hasAwakeBrowserTab( - tabs: readonly { sleptAt?: number | null }[] | null | undefined -): boolean { - return (tabs ?? []).some(isAwakeBrowserTab) -} +let cache: { + tabs: BrowserTabsByWorktree + asleep: Record + awake: BrowserTabsByWorktree +} | null = null -function stamp( - tabs: readonly BrowserWorkspace[], - sleptAt: number | undefined -): BrowserWorkspace[] | null { - let changed = false - const next = tabs.map((tab) => { - if ((tab.sleptAt ?? undefined) === sleptAt) { - return tab +/** + * The browser tabs that count as activity: every workspace's, minus those Sleep put to rest. + * Same object back while neither input changes, so store selectors stay stable. + */ +export function selectAwakeBrowserTabsByWorktree(state: { + browserTabsByWorktree: BrowserTabsByWorktree + asleepBrowserWorktreeIds?: Record +}): BrowserTabsByWorktree { + const tabs = state.browserTabsByWorktree + const asleep = state.asleepBrowserWorktreeIds + if (!asleep || Object.keys(asleep).length === 0) { + return tabs + } + if (cache && cache.tabs === tabs && cache.asleep === asleep) { + return cache.awake + } + const awake: BrowserTabsByWorktree = {} + for (const [worktreeId, worktreeTabs] of Object.entries(tabs)) { + if (!asleep[worktreeId]) { + awake[worktreeId] = worktreeTabs } - changed = true - const copy: BrowserWorkspace = { ...tab } - if (sleptAt === undefined) { - delete copy.sleptAt - } else { - copy.sleptAt = sleptAt - } - return copy - }) - return changed ? next : null + } + cache = { tabs, asleep, awake } + return awake } -/** Sleep: drop the pages, keep the tabs, mark them asleep. */ +/** Sleep: drop the pages, keep the tabs, mark the workspace's tabs asleep. */ export function sleepWorktreeBrowserTabs(worktreeId: string, now: number = Date.now()): void { const state = useAppStore.getState() destroyWorktreeBrowserGuests( @@ -47,29 +50,27 @@ export function sleepWorktreeBrowserTabs(worktreeId: string, now: number = Date. state.browserPagesByWorkspace, worktreeId ) - const next = stamp(state.browserTabsByWorktree[worktreeId] ?? [], now) - if (next) { - useAppStore.setState((s) => ({ - browserTabsByWorktree: { ...s.browserTabsByWorktree, [worktreeId]: next } - })) + if ((state.browserTabsByWorktree[worktreeId] ?? []).length === 0) { + return } + useAppStore.setState((s) => ({ + asleepBrowserWorktreeIds: { ...s.asleepBrowserWorktreeIds, [worktreeId]: now } + })) } /** The workspace is open again: its tabs count as activity once more (pages reload when shown). */ export function wakeWorktreeBrowserTabs(worktreeId: string): void { - const tabs = useAppStore.getState().browserTabsByWorktree[worktreeId] - if (!tabs || !tabs.some((tab) => tab.sleptAt)) { + if (!useAppStore.getState().asleepBrowserWorktreeIds?.[worktreeId]) { return } - const next = stamp(tabs, undefined) - if (next) { - useAppStore.setState((s) => ({ - browserTabsByWorktree: { ...s.browserTabsByWorktree, [worktreeId]: next } - })) - } + useAppStore.setState((s) => { + const next = { ...s.asleepBrowserWorktreeIds } + delete next[worktreeId] + return { asleepBrowserWorktreeIds: next } + }) } -/** Wakes a workspace's asleep tabs whenever it becomes the active one (also after an app restart). */ +/** Wakes a workspace's asleep tabs whenever it becomes the active one. */ export function installBrowserTabWakeOnOpen(): () => void { let previous = useAppStore.getState().activeWorktreeId if (previous) { diff --git a/src/renderer/src/components/sidebar/workspace-actions/sleep/use-worktree-sleep-state.ts b/src/renderer/src/components/sidebar/workspace-actions/sleep/use-worktree-sleep-state.ts index f60b120aefa..f434606caa5 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/sleep/use-worktree-sleep-state.ts +++ b/src/renderer/src/components/sidebar/workspace-actions/sleep/use-worktree-sleep-state.ts @@ -18,6 +18,8 @@ type SleepStateInput = { tabsByWorktree?: Record | null ptyIdsByTabId?: Record | null browserTabsByWorktree?: Record | null + /** Workspaces whose browser tabs Sleep put to rest: those tabs are not activity. */ + asleepBrowserWorktreeIds?: Record unifiedTabsByWorktree?: Record | null structuredChatSleptAtByPaneKey?: StructuredChatSleptAtByPaneKey } @@ -70,7 +72,7 @@ export function selectIsSleepingWorktree(state: SleepStateInput, worktreeId: str worktreeId, state.tabsByWorktree, state.ptyIdsByTabId, - state.browserTabsByWorktree, + state.asleepBrowserWorktreeIds?.[worktreeId] ? null : state.browserTabsByWorktree, selectWorktreeIdsWithLiveAgent(state), getWorktreeIdsWithStructuredChat( state.unifiedTabsByWorktree, diff --git a/src/renderer/src/components/sidebar/workspace-board/surface/use-visible-workspace-kanban-worktree-ids.ts b/src/renderer/src/components/sidebar/workspace-board/surface/use-visible-workspace-kanban-worktree-ids.ts index 936433e3ba7..cda31867815 100644 --- a/src/renderer/src/components/sidebar/workspace-board/surface/use-visible-workspace-kanban-worktree-ids.ts +++ b/src/renderer/src/components/sidebar/workspace-board/surface/use-visible-workspace-kanban-worktree-ids.ts @@ -1,3 +1,4 @@ +import { selectAwakeBrowserTabsByWorktree } from '@/components/sidebar/workspace-actions/sleep/browser-tab-sleep' import { useMemo, useState } from 'react' import { useAppStore } from '@/store' import { getAgentStatusEpochNow } from '@/lib/agent-status/evidence/agent-status-epoch-clock' @@ -52,7 +53,7 @@ export function useVisibleWorkspaceKanbanWorktreeIds({ const tabsByWorktree = useAppStore((s) => (!showSleepingWorkspaces ? s.tabsByWorktree : null)) const ptyIdsByTabId = useAppStore((s) => (!showSleepingWorkspaces ? s.ptyIdsByTabId : null)) const browserTabsByWorktree = useAppStore((s) => - !showSleepingWorkspaces ? s.browserTabsByWorktree : null + !showSleepingWorkspaces ? selectAwakeBrowserTabsByWorktree(s) : null ) const worktreeIdsWithStructuredChat = useAppStore((s) => getStructuredChatWorktreeIds( diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.ts b/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.ts index a3902e3bac9..f77a9d28fd2 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.ts +++ b/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.ts @@ -62,7 +62,12 @@ export function selectWorktreeActivityPtyIds( export function useWorktreeActivityStatus(worktreeId: string): WorktreeStatus { const tabs = useAppStore((s) => s.tabsByWorktree[worktreeId] ?? EMPTY_TABS) - const browserTabs = useAppStore((s) => s.browserTabsByWorktree[worktreeId] ?? EMPTY_BROWSER_TABS) + // Tabs Sleep put to rest stay in the layout but are not activity (NEW-01). + const browserTabs = useAppStore((s) => + s.asleepBrowserWorktreeIds?.[worktreeId] + ? EMPTY_BROWSER_TABS + : (s.browserTabsByWorktree[worktreeId] ?? EMPTY_BROWSER_TABS) + ) const hasStructuredChat = useAppStore((s) => hasAwakeStructuredChat(s.unifiedTabsByWorktree[worktreeId], s.structuredChatSleptAtByPaneKey) ) diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-statuses.ts b/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-statuses.ts index b6fc9e5a473..1ddf10432e9 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-statuses.ts +++ b/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-statuses.ts @@ -35,7 +35,9 @@ export function selectWorktreeActivityStatuses( worktreeId, resolveWorktreeStatus({ tabs: statusInputs.tabsByWorktree[worktreeId] ?? EMPTY_TABS, - browserTabs: statusInputs.browserTabsByWorktree[worktreeId] ?? EMPTY_BROWSER_TABS, + browserTabs: statusInputs.asleepBrowserWorktreeIds?.[worktreeId] + ? EMPTY_BROWSER_TABS + : (statusInputs.browserTabsByWorktree[worktreeId] ?? EMPTY_BROWSER_TABS), hasStructuredChat: hasAwakeStructuredChat( statusInputs.unifiedTabsByWorktree[worktreeId], statusInputs.structuredChatSleptAtByPaneKey diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/sleeping-sweep-visibility.ts b/src/renderer/src/components/sidebar/worktree-list/listing/sleeping-sweep-visibility.ts index dbb9ad4bcf6..300bd07cc4d 100644 --- a/src/renderer/src/components/sidebar/worktree-list/listing/sleeping-sweep-visibility.ts +++ b/src/renderer/src/components/sidebar/worktree-list/listing/sleeping-sweep-visibility.ts @@ -1,3 +1,4 @@ +import { selectAwakeBrowserTabsByWorktree } from '@/components/sidebar/workspace-actions/sleep/browser-tab-sleep' import type { AppState } from '@/store/types' import type { Worktree } from '../../../../../../shared/worktree/types' import { isSleepingSweepExempt } from '../../../../../../shared/workspace-view/workspace-row-filters' @@ -15,7 +16,9 @@ export function createSleepingSweepHiddenCheck( exemptWorktreeIds?: ReadonlySet ): (worktree: Worktree) => boolean { const tabsByWorktree = getVisibleWorktreeTerminalActivityTabs(state.tabsByWorktree) - const browserTabsByWorktree = getVisibleWorktreeBrowserActivityTabs(state.browserTabsByWorktree) + const browserTabsByWorktree = getVisibleWorktreeBrowserActivityTabs( + selectAwakeBrowserTabsByWorktree(state) + ) const liveAgentWorktrees = getWorktreeIdsWithLiveAgent( state.agentStatusByPaneKey, tabsByWorktree, diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/use-visible-worktrees.ts b/src/renderer/src/components/sidebar/worktree-list/listing/use-visible-worktrees.ts index c33f953ca27..4f3de102ea5 100644 --- a/src/renderer/src/components/sidebar/worktree-list/listing/use-visible-worktrees.ts +++ b/src/renderer/src/components/sidebar/worktree-list/listing/use-visible-worktrees.ts @@ -1,3 +1,4 @@ +import { selectAwakeBrowserTabsByWorktree } from '@/components/sidebar/workspace-actions/sleep/browser-tab-sleep' import { selectSidebarLineageParentIdentities } from '@/store/slices/worktrees/metadata/cross-store-lineage-parents' import { useMemo, useState } from 'react' import { shallow } from 'zustand/shallow' @@ -93,7 +94,9 @@ export function useVisibleSidebarWorktrees(args: { ) const ptyIdsByTabId = useAppStore((s) => (needsActivityMaps ? s.ptyIdsByTabId : null)) const browserTabsByWorktree = useAppStore((s) => - !showSleepingWorkspaces ? getVisibleWorktreeBrowserActivityTabs(s.browserTabsByWorktree) : null + !showSleepingWorkspaces + ? getVisibleWorktreeBrowserActivityTabs(selectAwakeBrowserTabsByWorktree(s)) + : null ) const worktreeIdsWithStructuredChat = useAppStore((s) => getStructuredChatWorktreeIds( diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/visible-worktree-activity-inputs.ts b/src/renderer/src/components/sidebar/worktree-list/listing/visible-worktree-activity-inputs.ts index 33687dbae47..df576d451e9 100644 --- a/src/renderer/src/components/sidebar/worktree-list/listing/visible-worktree-activity-inputs.ts +++ b/src/renderer/src/components/sidebar/worktree-list/listing/visible-worktree-activity-inputs.ts @@ -7,7 +7,7 @@ import { createWorktreeTabBucketProjection } from '@/lib/workspace/tabs/worktree import type { StructuredChatSleptAtByPaneKey } from '@/store/slices/agent-status/structured-chat-slept-at' export type TerminalActivityTab = Pick -export type BrowserActivityTab = Pick +export type BrowserActivityTab = Pick export function createVisibleWorktreeTerminalActivityProjection( onInspectBucket?: (worktreeId: string) => void @@ -28,10 +28,8 @@ export function getVisibleWorktreeTerminalActivityTabs( } const browserProjection = createWorktreeTabBucketProjection({ - // A tab Sleep put to rest is not activity, so its mark is part of the projection. - projectTab: (tab) => (tab.sleptAt ? { id: tab.id, sleptAt: tab.sleptAt } : { id: tab.id }), - isSameProjectedTab: (previousTab, nextTab) => - previousTab.id === nextTab.id && previousTab.sleptAt === nextTab.sleptAt + projectTab: (tab) => ({ id: tab.id }), + isSameProjectedTab: (previousTab, nextTab) => previousTab.id === nextTab.id }) export function getVisibleWorktreeBrowserActivityTabs( diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/visible-worktree-options-from-state.ts b/src/renderer/src/components/sidebar/worktree-list/listing/visible-worktree-options-from-state.ts index cdfb00e5052..cc31b9b8cc8 100644 --- a/src/renderer/src/components/sidebar/worktree-list/listing/visible-worktree-options-from-state.ts +++ b/src/renderer/src/components/sidebar/worktree-list/listing/visible-worktree-options-from-state.ts @@ -1,3 +1,4 @@ +import { selectAwakeBrowserTabsByWorktree } from '@/components/sidebar/workspace-actions/sleep/browser-tab-sleep' import { selectSidebarLineageParentIdentities } from '@/store/slices/worktrees/metadata/cross-store-lineage-parents' import type { Repo } from '../../../../../../shared/repo-types' import { getSettingsFocusedExecutionHostId } from '../../../../../../shared/execution-host' @@ -20,7 +21,7 @@ export function buildVisibleWorktreeOptionsFromState( showSleepingWorkspaces: state.showSleepingWorkspaces, tabsByWorktree: state.tabsByWorktree, ptyIdsByTabId: state.ptyIdsByTabId, - browserTabsByWorktree: state.browserTabsByWorktree, + browserTabsByWorktree: selectAwakeBrowserTabsByWorktree(state), worktreeIdsWithLiveAgent: getWorktreeIdsWithLiveAgent( state.agentStatusByPaneKey, state.tabsByWorktree, diff --git a/src/renderer/src/lib/sidebar-shadow/workspace-activity-shadow.ts b/src/renderer/src/lib/sidebar-shadow/workspace-activity-shadow.ts index e65f7d500ba..4d93f604c34 100644 --- a/src/renderer/src/lib/sidebar-shadow/workspace-activity-shadow.ts +++ b/src/renderer/src/lib/sidebar-shadow/workspace-activity-shadow.ts @@ -26,6 +26,7 @@ export function readWindowWorkspaceActivityFacts( | 'tabsByWorktree' | 'ptyIdsByTabId' | 'browserTabsByWorktree' + | 'asleepBrowserWorktreeIds' | 'unifiedTabsByWorktree' | 'agentStatusByPaneKey' > & @@ -55,7 +56,8 @@ export function readWindowWorkspaceActivityFacts( ) ? 'live' : null, - browser: (state.browserTabsByWorktree[id] ?? []).some((tab) => !tab.sleptAt), + browser: + !state.asleepBrowserWorktreeIds?.[id] && (state.browserTabsByWorktree[id]?.length ?? 0) > 0, structuredChat: structuredChatIds.has(id), agent: agentById.get(id) ?? null } diff --git a/src/renderer/src/lib/worktree-activity-state.ts b/src/renderer/src/lib/worktree-activity-state.ts index 43e6796d084..1a2c77300ce 100644 --- a/src/renderer/src/lib/worktree-activity-state.ts +++ b/src/renderer/src/lib/worktree-activity-state.ts @@ -12,8 +12,7 @@ import { } from '../../../shared/sidebar-list/workspace-activity-facts' type TerminalLikeTab = Pick -/** `sleptAt`: Sleep kept the tab but dropped its page; it is not activity until reopened. */ -type BrowserLikeTab = { id: string; sleptAt?: number | null } +type BrowserLikeTab = { id: string } type TabsByWorktree = Record type PtyIdsByTabId = Record @@ -82,7 +81,7 @@ export function hasActiveWorkspaceActivity( const tabs = tabsByWorktree?.[worktreeId] ?? [] const hasLiveTerminal = ptyIdsByTabId != null && tabs.some((tab) => tabHasLivePty(ptyIdsByTabId, tab.id)) - const hasBrowser = (browserTabsByWorktree?.[worktreeId] ?? []).some((tab) => !tab.sleptAt) + const hasBrowser = (browserTabsByWorktree?.[worktreeId] ?? []).length > 0 // Why: a running agent keeps the workspace visible through brief PTY gaps // such as an SSH reconnect or an unmounted remote pane. #7197 const hasLiveAgent = worktreeIdsWithLiveAgent.has(worktreeId) diff --git a/src/renderer/src/lib/worktree-status.ts b/src/renderer/src/lib/worktree-status.ts index 3be51c113c7..15f033f11c4 100644 --- a/src/renderer/src/lib/worktree-status.ts +++ b/src/renderer/src/lib/worktree-status.ts @@ -63,7 +63,7 @@ const STATUS_LABELS: Record = { export function getWorktreeStatus( tabs: readonly Pick[], - browserTabs: readonly { id: string; sleptAt?: number | null }[], + browserTabs: readonly { id: string }[], ptyIdsByTabId: Record, runtimePaneTitlesByTabId: Record> = {}, options: WorktreeStatusHeuristicOptions = {} @@ -84,12 +84,7 @@ export function getWorktreeStatus( if (options.liveAgentStatus === 'monitoring') { return 'monitoring' } - // A tab Sleep put to rest (sleptAt) keeps its place but is not activity. - if ( - liveTabs.length > 0 || - browserTabs.some((tab) => !tab.sleptAt) || - options.hasStructuredChat - ) { + if (liveTabs.length > 0 || browserTabs.length > 0 || options.hasStructuredChat) { // Why: browser-only and chat-only worktrees (no PTY) are still active from the user's point of view. return 'active' } @@ -204,7 +199,7 @@ export function getWorktreeStatusLabel(status: WorktreeStatus): string { */ export function resolveWorktreeStatus(args: { tabs: readonly Pick[] - browserTabs: readonly { id: string; sleptAt?: number | null }[] + browserTabs: readonly { id: string }[] hasStructuredChat?: boolean ptyIdsByTabId: Record runtimePaneTitlesByTabId?: Record> diff --git a/src/renderer/src/store/slices/browser/browser-slice-contract.ts b/src/renderer/src/store/slices/browser/browser-slice-contract.ts index fe5f62d6496..8b28afd32ee 100644 --- a/src/renderer/src/store/slices/browser/browser-slice-contract.ts +++ b/src/renderer/src/store/slices/browser/browser-slice-contract.ts @@ -116,6 +116,8 @@ export type BrowserCookieImportExecutionResult = BrowserCookieImportResult & { export type BrowserSlice = { browserTabsByWorktree: Record + /** Workspaces whose tabs Sleep put to rest (when): kept in the layout, not activity (NEW-01). */ + asleepBrowserWorktreeIds: Record browserPagesByWorkspace: Record browserCertificateFailuresByPageId: Record /** May precede the page record (client-hosted pages); main's false on guest teardown clears it. */ diff --git a/src/renderer/src/store/slices/browser/create-browser-slice.ts b/src/renderer/src/store/slices/browser/create-browser-slice.ts index 080e4561564..519b168186f 100644 --- a/src/renderer/src/store/slices/browser/create-browser-slice.ts +++ b/src/renderer/src/store/slices/browser/create-browser-slice.ts @@ -23,6 +23,7 @@ import { createBrowserHistoryActions } from './history/browser-history-actions' export const createBrowserSlice: StateCreator = (set, get) => ({ browserTabsByWorktree: {}, + asleepBrowserWorktreeIds: {}, browserPagesByWorkspace: {}, browserCertificateFailuresByPageId: {}, browserAudiblePageIds: {}, diff --git a/src/shared/browser-workspace-types.ts b/src/shared/browser-workspace-types.ts index c10b99a922f..971c3511d19 100644 --- a/src/shared/browser-workspace-types.ts +++ b/src/shared/browser-workspace-types.ts @@ -131,11 +131,6 @@ export type BrowserWorkspace = { createdAt: number /** Mirrored from the active page, like the fields above it. */ docLocation?: BrowserPageDocLocation | null - /** - * Set by Sleep: the tab keeps its place but its page was dropped, and it is not activity until - * the workspace is opened again (then cleared, and the page reloads when shown). - */ - sleptAt?: number } export type BrowserSessionProfileScope = 'default' | 'isolated' | 'imported' diff --git a/src/shared/workspace-layout/workspace-layout-disk-fields.ts b/src/shared/workspace-layout/workspace-layout-disk-fields.ts index 760dfbd9050..a9fa8830526 100644 --- a/src/shared/workspace-layout/workspace-layout-disk-fields.ts +++ b/src/shared/workspace-layout/workspace-layout-disk-fields.ts @@ -217,9 +217,7 @@ const BROWSER = { canGoBack: own('browserLive', 'canGoBack'), canGoForward: own('browserLive', 'canGoForward'), loadError: own('browserLive', 'loadError'), - docLocation: own('browserLive', 'docLocation'), - // Sleep's mark: runtime-only, so a restart starts every tab awake. - sleptAt: 'unwritten' + docLocation: own('browserLive', 'docLocation') } as const satisfies Record // Write records only for mounted tree panes; derive keys from tab and leaf IDs. From 653e870475422891649de2be8aac8db2ceb6dc5d Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 21:25:23 -0800 Subject: [PATCH 113/149] fix(cloud-api): teammates show as a display name only, never a raw id; audit keeps it in a tooltip --- .../cloud-api/CloudApiKeysSections.tsx | 2 +- .../settings/cloud-api/PersonName.test.tsx | 26 +++++++++ .../settings/cloud-api/PersonName.tsx | 53 ++++++++++++------- src/renderer/src/i18n/locales/en.json | 1 + 4 files changed, 61 insertions(+), 21 deletions(-) create mode 100644 src/renderer/src/components/settings/cloud-api/PersonName.test.tsx diff --git a/src/renderer/src/components/settings/cloud-api/CloudApiKeysSections.tsx b/src/renderer/src/components/settings/cloud-api/CloudApiKeysSections.tsx index c217e1546be..9e4060a6536 100644 --- a/src/renderer/src/components/settings/cloud-api/CloudApiKeysSections.tsx +++ b/src/renderer/src/components/settings/cloud-api/CloudApiKeysSections.tsx @@ -274,7 +274,7 @@ function ActorLabel({ return mine ? ( <>{sentence} ) : ( - + ) } diff --git a/src/renderer/src/components/settings/cloud-api/PersonName.test.tsx b/src/renderer/src/components/settings/cloud-api/PersonName.test.tsx new file mode 100644 index 00000000000..08c92d0b5e3 --- /dev/null +++ b/src/renderer/src/components/settings/cloud-api/PersonName.test.tsx @@ -0,0 +1,26 @@ +// @vitest-environment happy-dom +import { cleanup, render } from '@testing-library/react' +import { afterEach, expect, it } from 'vitest' +import { PersonName, PersonSentence } from './PersonName' + +afterEach(cleanup) + +it('shows the display name only, never the raw id inline', () => { + const { container } = render() + expect(container.textContent).toBe('Grace Hopper') + expect(container.querySelector('[title]')).toBeNull() +}) + +it('says "Former member" when nobody can name the person', () => { + const { container } = render() + expect(container.textContent).toBe('Former member') + expect(container.innerHTML).not.toContain('u_7f3k') +}) + +it('keeps the id one hover away in the audit log only', () => { + const { container } = render( + + ) + expect(container.textContent).toBe('Former member via API key') + expect(container.querySelector('[title]')?.getAttribute('title')).toBe('u_7f3k') +}) diff --git a/src/renderer/src/components/settings/cloud-api/PersonName.tsx b/src/renderer/src/components/settings/cloud-api/PersonName.tsx index 68750ee0fff..f777d2957c1 100644 --- a/src/renderer/src/components/settings/cloud-api/PersonName.tsx +++ b/src/renderer/src/components/settings/cloud-api/PersonName.tsx @@ -1,32 +1,43 @@ import { Trans } from 'react-i18next' -import { i18n } from '@/i18n/i18n' +import { i18n, translate } from '@/i18n/i18n' +import { useAppStore } from '@/store' +import { useOrgRoster } from '../../billing/team/use-org-roster' + +/** The name the control plane sent, else the team roster's (the directory Home uses), else null. */ +function useMemberName(name: string | null | undefined, id: string): string | null { + const orgId = useAppStore((s) => s.orcaProfileAuthStatus?.cloud?.activeOrgId ?? null) + const known = name?.trim() || null + // Only read the shared roster when the server could not name this person. + const roster = useOrgRoster(known ? null : orgId) + if (known) { + return known + } + if (roster.result?.status === 'ok') { + const member = roster.result.roster.members.find((m) => m.userId === id) + return member?.displayName?.trim() || member?.email || null + } + return null +} /** - * A teammate as the control plane knows them: "Ada Lovelace · u_ada" (name, then the id as - * secondary text), or the id alone when no name is known. Never a vague "a teammate". + * A teammate as a display name only, never a raw id inline; "Former member" when nobody can + * name them. `idInTooltip` (audit log only) keeps the id one hover away for admins investigating. */ export function PersonName({ name, - id + id, + idInTooltip = false }: { name: string | null | undefined id: string + idInTooltip?: boolean }): React.JSX.Element { - const display = name?.trim() - if (!display) { - return ( - - {id} - - ) - } + const display = + useMemberName(name, id) ?? + translate('auto.components.settings.cloudApi.formerMember', 'Former member') return ( - - {display} - - {' · '} - {id} - + + {display} ) } @@ -38,17 +49,19 @@ export function PersonName({ export function PersonSentence({ sentence, name, - id + id, + idInTooltip }: { sentence: string name: string | null | undefined id: string + idInTooltip?: boolean }): React.JSX.Element { return ( }} + components={{ person: }} /> ) } diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 4e6be059af3..824a19f310a 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -14405,6 +14405,7 @@ "description_other": "Starts waking a sleeping sandbox when you point at its workspace or come back to Orca, so it's ready sooner. If you don't open it, it goes back to sleep after {{count}} minutes idle. Early wakes count toward your sandbox hours." }, "cloudApi": { + "formerMember": "Former member", "keys": { "createdMine": "Created {{time}}", "createdByPerson": "Created by {{time}}", From 759672bab36aa432ae8d7bccd8303acec9d8b61e Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 21:25:39 -0800 Subject: [PATCH 114/149] fix(sleep): visibility options read the asleep mark too (NEW-01) --- .../worktree-list/listing/compute-visible-worktrees.ts | 2 ++ .../worktree-list/listing/desktop-workspace-row-facts.ts | 3 ++- .../listing/visible-worktree-options-from-state.ts | 4 ++-- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/compute-visible-worktrees.ts b/src/renderer/src/components/sidebar/worktree-list/listing/compute-visible-worktrees.ts index 5539a3a3193..c7fa50c2a9a 100644 --- a/src/renderer/src/components/sidebar/worktree-list/listing/compute-visible-worktrees.ts +++ b/src/renderer/src/components/sidebar/worktree-list/listing/compute-visible-worktrees.ts @@ -19,6 +19,8 @@ export type VisibleWorktreeOptions = { tabsByWorktree: Record[]> | null ptyIdsByTabId: Record | null browserTabsByWorktree?: Record | null + /** Workspaces whose browser tabs Sleep put to rest: those tabs are not activity (NEW-01). */ + asleepBrowserWorktreeIds?: Record worktreeIdsWithLiveAgent: ReadonlySet worktreeIdsWithStructuredChat?: ReadonlySet hideDefaultBranchWorkspace: boolean diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/desktop-workspace-row-facts.ts b/src/renderer/src/components/sidebar/worktree-list/listing/desktop-workspace-row-facts.ts index bbf8798e922..e0fe22d7fe3 100644 --- a/src/renderer/src/components/sidebar/worktree-list/listing/desktop-workspace-row-facts.ts +++ b/src/renderer/src/components/sidebar/worktree-list/listing/desktop-workspace-row-facts.ts @@ -23,6 +23,7 @@ export type DesktopWorkspaceRowFactInputs = { tabsByWorktree: Record[]> | null ptyIdsByTabId: Record | null browserTabsByWorktree?: Record | null + asleepBrowserWorktreeIds?: Record worktreeIdsWithLiveAgent: ReadonlySet worktreeIdsWithStructuredChat?: ReadonlySet /** Rows in a PTY-rebind grace window; read as unverifiable, never as asleep (#15996). */ @@ -54,7 +55,7 @@ export function buildDesktopWorkspaceRowFactReader( worktree.id, inputs.tabsByWorktree, inputs.ptyIdsByTabId, - inputs.browserTabsByWorktree, + inputs.asleepBrowserWorktreeIds?.[worktree.id] ? null : inputs.browserTabsByWorktree, inputs.worktreeIdsWithLiveAgent, inputs.worktreeIdsWithStructuredChat ) diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/visible-worktree-options-from-state.ts b/src/renderer/src/components/sidebar/worktree-list/listing/visible-worktree-options-from-state.ts index cc31b9b8cc8..c3500996b40 100644 --- a/src/renderer/src/components/sidebar/worktree-list/listing/visible-worktree-options-from-state.ts +++ b/src/renderer/src/components/sidebar/worktree-list/listing/visible-worktree-options-from-state.ts @@ -1,4 +1,3 @@ -import { selectAwakeBrowserTabsByWorktree } from '@/components/sidebar/workspace-actions/sleep/browser-tab-sleep' import { selectSidebarLineageParentIdentities } from '@/store/slices/worktrees/metadata/cross-store-lineage-parents' import type { Repo } from '../../../../../../shared/repo-types' import { getSettingsFocusedExecutionHostId } from '../../../../../../shared/execution-host' @@ -21,7 +20,8 @@ export function buildVisibleWorktreeOptionsFromState( showSleepingWorkspaces: state.showSleepingWorkspaces, tabsByWorktree: state.tabsByWorktree, ptyIdsByTabId: state.ptyIdsByTabId, - browserTabsByWorktree: selectAwakeBrowserTabsByWorktree(state), + browserTabsByWorktree: state.browserTabsByWorktree, + asleepBrowserWorktreeIds: state.asleepBrowserWorktreeIds, worktreeIdsWithLiveAgent: getWorktreeIdsWithLiveAgent( state.agentStatusByPaneKey, state.tabsByWorktree, From ae6c918bd5a877968f15646ab66c39e368dc8567 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 21:25:48 -0800 Subject: [PATCH 115/149] fix(cloud): Move to this computer uses the ghost variant's own color (DS-l) --- .../src/components/orca-cloud/CloudWorkspaceStatusPanel.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/renderer/src/components/orca-cloud/CloudWorkspaceStatusPanel.tsx b/src/renderer/src/components/orca-cloud/CloudWorkspaceStatusPanel.tsx index ba1de73ac81..498cb3d7437 100644 --- a/src/renderer/src/components/orca-cloud/CloudWorkspaceStatusPanel.tsx +++ b/src/renderer/src/components/orca-cloud/CloudWorkspaceStatusPanel.tsx @@ -331,7 +331,7 @@ export function CloudWorkspaceStatusPanel({ + ) : ( +
    {title}
    + )} + + {status.running + ? t('cloudSkillsSync.syncing', 'Syncing skills and commands…') + : error + ? null + : summary} + + + {hasRows && status.error !== 'host-outdated' && !cloudSkillsErrorRetryable(status.error) ? ( + + ) : null} +
    + {error ? ( + + ) : null} + {!autoSync && hasRows ? ( +

    + {t('cloudSkillsSync.manualOnly', 'Not synced automatically. Sync now copies them once.')} +

    + ) : null} + +
    + ) +} diff --git a/src/renderer/src/components/settings/orca-cloud/cloud-skills/OrcaCloudSkillsPane.fixture.tsx b/src/renderer/src/components/settings/orca-cloud/cloud-skills/OrcaCloudSkillsPane.fixture.tsx new file mode 100644 index 00000000000..120ec082f8b --- /dev/null +++ b/src/renderer/src/components/settings/orca-cloud/cloud-skills/OrcaCloudSkillsPane.fixture.tsx @@ -0,0 +1,188 @@ +import type { + AgentConfigSyncRow, + AgentConfigSyncStatus, + CloudAgentConfigSyncPreferences +} from '../../../../../../shared/agent-config-sync/agent-config-sync-contract' +import { defineFixture } from '../../../../component-fixtures/component-fixture' +import { SettingsSection } from '../../section-layout/SettingsSection' +import type { OrcaCloudMcpWorkspace } from '../OrcaCloudMcpServersPane' +import { CloudSkillsSyncPanel, CloudSkillsSyncSkeleton } from './CloudSkillsSyncPanel' +import { CloudSkillsSyncSettingsView, OrcaCloudSkillsWorkspacesView } from './OrcaCloudSkillsPane' + +const noop = (): void => {} + +function row( + kind: AgentConfigSyncRow['kind'], + name: string, + patch: Partial = {} +): AgentConfigSyncRow { + const scope = patch.scope ?? 'user' + return { + key: `${scope}:${kind}:${name}`, + scope, + kind, + name, + bytes: 2048, + fileCount: 1, + withheldFiles: 0, + included: true, + state: 'synced', + outcome: 'added', + ...patch + } +} + +const ROWS: AgentConfigSyncRow[] = [ + row('claude-skill', 'deploy-preview', { fileCount: 3 }), + row('claude-skill', 'release-notes', { withheldFiles: 1 }), + row('claude-command', 'review'), + row('claude-command', 'frontend/component', { outcome: 'unchanged' }), + row('agents-skill', 'playwright-cli'), + row('codex-prompt', 'fix-ci', { outcome: 'unchanged' }), + row('agents-skill', 'deploy-preview', { convertedFrom: 'user:claude-skill:deploy-preview' }), + row('claude-skill', 'local-notes', { scope: 'project' }), + row('claude-skill', 'scratch', { + state: 'skipped', + outcome: undefined, + skipReason: 'turned-off' + }), + row('claude-skill', 'design-system', { + scope: 'project', + state: 'skipped', + outcome: undefined, + skipReason: 'in-repo' + }), + row('claude-skill', 'vendor-keys', { + state: 'skipped', + outcome: undefined, + skipReason: 'secret' + }), + row('claude-skill', 'datasets', { + state: 'skipped', + outcome: undefined, + skipReason: 'too-large' + }), + row('claude-command', 'ship', { state: 'skipped', outcome: 'kept-host' }) +] + +const STATUS: AgentConfigSyncStatus = { + environmentId: 'env-1', + running: false, + lastSyncedAt: Date.UTC(2026, 10, 10, 16, 42), + error: null, + rows: ROWS +} +const EXCLUDED = new Set(['user:claude-skill:scratch']) + +const ON: CloudAgentConfigSyncPreferences = { + autoSync: true, + shareAcrossAgents: true, + excluded: [] +} +const OFF: CloudAgentConfigSyncPreferences = { + autoSync: false, + shareAcrossAgents: false, + excluded: [] +} + +const ONE: OrcaCloudMcpWorkspace[] = [ + { runtimeId: 'rt-1', name: 'acme/web · fix-login', environmentId: 'env-1' } +] + +function page( + preferences: CloudAgentConfigSyncPreferences, + workspaces: OrcaCloudMcpWorkspace[] | null | 'failed', + status: AgentConfigSyncStatus = STATUS, + expanded = true +): React.JSX.Element { + return ( +
    + +
    + + ( + + )} + /> +
    +
    +
    + ) +} + +export const synced = defineFixture({ width: 784, render: () => page(ON, ONE) }) +export const collapsed = defineFixture({ width: 784, render: () => page(ON, ONE, STATUS, false) }) +export const offNotSynced = defineFixture({ + width: 784, + render: () => + page( + OFF, + ONE, + { + ...STATUS, + lastSyncedAt: null, + rows: ROWS.filter((entry) => !entry.convertedFrom).map((entry) => + entry.state === 'synced' ? { ...entry, state: 'pending', outcome: undefined } : entry + ) + }, + true + ) +}) +export const syncing = defineFixture({ + width: 784, + render: () => page(ON, ONE, { ...STATUS, running: true }, false) +}) +export const hostOutdated = defineFixture({ + width: 784, + render: () => + page( + ON, + ONE, + { + ...STATUS, + lastSyncedAt: null, + error: 'host-outdated', + rows: ROWS.map((entry) => + entry.state === 'synced' ? { ...entry, state: 'pending', outcome: undefined } : entry + ) + }, + false + ) +}) +export const hostUnreachable = defineFixture({ + width: 784, + render: () => page(ON, ONE, { ...STATUS, error: 'host-unreachable' }, false) +}) +export const noneFound = defineFixture({ + width: 784, + render: () => page(ON, ONE, { ...STATUS, rows: [], lastSyncedAt: null }, false) +}) +export const noneRunning = defineFixture({ width: 784, render: () => page(OFF, []) }) +export const loadingWorkspaces = defineFixture({ width: 784, render: () => page(ON, null) }) +export const loadFailed = defineFixture({ width: 784, render: () => page(ON, 'failed') }) +export const panelLoading = defineFixture({ + width: 640, + render: () => ( +
    + +
    + ) +}) diff --git a/src/renderer/src/components/settings/orca-cloud/cloud-skills/OrcaCloudSkillsPane.tsx b/src/renderer/src/components/settings/orca-cloud/cloud-skills/OrcaCloudSkillsPane.tsx new file mode 100644 index 00000000000..248dffb3797 --- /dev/null +++ b/src/renderer/src/components/settings/orca-cloud/cloud-skills/OrcaCloudSkillsPane.tsx @@ -0,0 +1,263 @@ +import { useCallback, useEffect, useId, useMemo, useState } from 'react' +import { BookOpenText } from 'lucide-react' +import { toast } from 'sonner' +import { InlineError } from '@/components/ui/inline-error' +import { Label } from '@/components/ui/label' +import { Skeleton } from '@/components/ui/skeleton' +import { Switch } from '@/components/ui/switch' +import { useTranslate } from '@/i18n/use-translate' +import { cn } from '@/lib/utils' +import { + setCloudAgentConfigItemIncluded, + setCloudAgentConfigSyncPreferences, + syncCloudAgentConfigNow, + useCloudAgentConfigSyncPreferences, + useCloudAgentConfigSyncStatus +} from '@/lib/cloud-agent-config-sync/cloud-agent-config-sync-client' +import { useAppStore } from '@/store' +import type { CloudAgentConfigSyncPreferences } from '../../../../../../shared/agent-config-sync/agent-config-sync-contract' +import { CloudApiEmptyState } from '../../cloud-api/cloud-api-parts' +import { SettingsGroup } from '../../section-layout/SettingsGroup' +import { + runningOrcaCloudMcpWorkspaces, + type OrcaCloudMcpWorkspace +} from '../OrcaCloudMcpServersPane' +import { CloudSkillsSyncPanel, CloudSkillsSyncSkeleton } from './CloudSkillsSyncPanel' + +function SwitchRow({ + title, + description, + checked, + disabled = false, + onChange +}: { + title: string + description: string + checked: boolean + disabled?: boolean + onChange: (next: boolean) => void +}): React.JSX.Element { + const labelId = useId() + const hintId = useId() + return ( +
    +
    + +

    + {description} +

    +
    + +
    + ) +} + +export function CloudSkillsSyncSettingsView({ + preferences, + onChange +}: { + preferences: CloudAgentConfigSyncPreferences + onChange: (next: Partial>) => void +}): React.JSX.Element { + const t = useTranslate() + return ( + + onChange({ autoSync })} + /> + onChange({ shareAcrossAgents })} + /> + + ) +} + +function CloudSkillsSyncSection({ + environmentId, + excluded, + autoSync, + defaultExpanded +}: { + environmentId: string + excluded: ReadonlySet + autoSync: boolean + defaultExpanded: boolean +}): React.JSX.Element | null { + const t = useTranslate() + const status = useCloudAgentConfigSyncStatus(environmentId) + const [expanded, setExpanded] = useState(defaultExpanded) + if (status === undefined) { + return + } + if (!status) { + return null + } + const syncNow = (): void => { + void syncCloudAgentConfigNow(environmentId).catch(() => + toast.error(t('cloudSkillsSync.startFailed', 'Couldn’t start the sync.')) + ) + } + return ( + setExpanded((value) => !value)} + onSyncNow={syncNow} + onToggleItem={(key, included) => { + // Main re-syncs every workspace that already synced; a first sync is still the user's call. + void setCloudAgentConfigItemIncluded(key, included).catch(() => + toast.error(t('cloudSkillsSync.saveFailed', 'Couldn’t save the change.')) + ) + }} + /> + ) +} + +export function OrcaCloudSkillsWorkspacesView({ + workspaces, + renderSync, + onRetry +}: { + workspaces: OrcaCloudMcpWorkspace[] | null | 'failed' + renderSync: (workspace: OrcaCloudMcpWorkspace, onlyOne: boolean) => React.ReactNode + onRetry: () => void +}): React.JSX.Element { + const t = useTranslate() + if (workspaces === 'failed') { + return ( + + ) + } + if (workspaces === null) { + return ( +
    + + {t('cloudSkillsSync.loading', 'Loading skills and commands…')} + + +
    + ) + } + if (workspaces.length === 0) { + return ( + + + + ) + } + return ( +
    + {workspaces.map((workspace) => { + const name = workspace.name ?? t('settings.orcaCloud.mcp.unnamed', 'Cloud workspace') + return ( + +
    +

    {name}

    + {renderSync(workspace, workspaces.length === 1)} +
    +
    + ) + })} +
    + ) +} + +/** Settings › Orca Cloud › Skills & commands. */ +export function OrcaCloudSkillsPane(): React.JSX.Element { + const t = useTranslate() + const preferences = useCloudAgentConfigSyncPreferences() + const [workspaces, setWorkspaces] = useState(null) + const [attempt, setAttempt] = useState(0) + const lifecycle = useAppStore((s) => s.ephemeralVmRuntimesByWorkspaceId) + useEffect(() => { + const listRuntimes = window.api.ephemeralVm?.listRuntimes + if (!listRuntimes) { + setWorkspaces([]) + return + } + let disposed = false + void listRuntimes() + .then((records) => !disposed && setWorkspaces(runningOrcaCloudMcpWorkspaces(records))) + .catch(() => !disposed && setWorkspaces('failed')) + return () => { + disposed = true + } + }, [lifecycle, attempt]) + const retry = useCallback(() => { + setWorkspaces(null) + setAttempt((value) => value + 1) + }, []) + const excluded = useMemo(() => new Set(preferences?.excluded ?? []), [preferences]) + if (preferences === undefined) { + return + } + if (preferences === null) { + return ( + + ) + } + return ( +
    + + void setCloudAgentConfigSyncPreferences(next).catch(() => + toast.error(t('cloudSkillsSync.saveFailed', 'Couldn’t save the change.')) + ) + } + /> + ( + + )} + /> +
    + ) +} diff --git a/src/renderer/src/components/settings/orca-cloud/cloud-skills/cloud-skills-sync-copy.ts b/src/renderer/src/components/settings/orca-cloud/cloud-skills/cloud-skills-sync-copy.ts new file mode 100644 index 00000000000..971e5dded5e --- /dev/null +++ b/src/renderer/src/components/settings/orca-cloud/cloud-skills/cloud-skills-sync-copy.ts @@ -0,0 +1,234 @@ +import { translate } from '@/i18n/i18n' +import type { Translate } from '@/i18n/use-translate' +import { + agentOfKind, + isSkillKind, + type AgentConfigSyncRow, + type AgentConfigSyncStatus +} from '../../../../../../shared/agent-config-sync/agent-config-sync-contract' + +// Glossary: the agent is "Claude" in UI copy, never "Claude Code". +export const AGENT_LABEL = { claude: 'Claude', codex: 'Codex' } as const + +/** What the user types: `/frontend:review` for a namespaced Claude command, `/prompts:x` in Codex. */ +export function cloudSkillsDisplayName(row: Pick): string { + if (row.kind === 'claude-command') { + return `/${row.name.split('/').join(':')}` + } + if (row.kind === 'codex-prompt') { + return `/prompts:${row.name}` + } + return row.name +} + +export function cloudSkillsKindLabel(row: AgentConfigSyncRow, t: Translate = translate): string { + const agent = AGENT_LABEL[agentOfKind(row.kind)] + const kind = isSkillKind(row.kind) + ? t('cloudSkillsSync.kind.skill', '{{agent}} skill', { agent }) + : row.kind === 'codex-prompt' + ? t('cloudSkillsSync.kind.prompt', 'Codex prompt') + : t('cloudSkillsSync.kind.command', '{{agent}} command', { agent }) + return row.scope === 'project' + ? t('cloudSkillsSync.kind.project', '{{kind}}, this project', { kind }) + : kind +} + +/** Rows the user's switches apply to: a copy for the other agent follows its original. */ +export function cloudSkillsRowIncluded( + row: AgentConfigSyncRow, + excluded: ReadonlySet +): boolean { + return !excluded.has(row.convertedFrom ?? row.key) +} + +export function cloudSkillsCounts(status: AgentConfigSyncStatus): { + synced: number + skipped: number +} { + const synced = status.rows.filter((row) => row.state === 'synced').length + return { synced, skipped: status.rows.length - synced } +} + +export function cloudSkillsSummary( + status: AgentConfigSyncStatus, + t: Translate = translate +): string { + if (status.rows.length === 0) { + return t('cloudSkillsSync.summary.none', 'None found in Claude or Codex on this computer') + } + if (status.lastSyncedAt === null) { + return t('cloudSkillsSync.summary.notSynced', '{{count}} found, not synced yet', { + count: status.rows.length, + defaultValue_one: '{{count}} found, not synced yet' + }) + } + const counts = cloudSkillsCounts(status) + const synced = t('cloudSkillsSync.summary.synced', '{{count}} synced', { + count: counts.synced, + defaultValue_one: '{{count}} synced' + }) + if (counts.skipped === 0) { + return synced + } + const skipped = t('cloudSkillsSync.summary.skipped', '{{count}} not synced', { + count: counts.skipped, + defaultValue_one: '{{count}} not synced' + }) + return t('cloudSkillsSync.summary.pair', '{{synced}}, {{skipped}}', { synced, skipped }) +} + +export function cloudSkillsErrorRetryable(error: AgentConfigSyncStatus['error']): boolean { + return error === 'host-unreachable' || error === 'failed' +} + +export function cloudSkillsErrorText( + error: AgentConfigSyncStatus['error'], + t: Translate = translate +): string | null { + const copy: Record, string> = { + 'host-outdated': t( + 'cloudSkillsSync.error.hostOutdated', + 'This workspace was created before skills sync. Create a new workspace to use it.' + ), + 'host-unreachable': t( + 'cloudSkillsSync.error.hostUnreachable', + 'Couldn’t reach the sandbox. Skills already there still work.' + ), + failed: t( + 'cloudSkillsSync.error.failed', + 'The last sync didn’t finish. Skills already in the sandbox still work.' + ) + } + return error ? copy[error] : null +} + +/** Why an item is not in the sandbox, or a caveat for one that is. */ +export function cloudSkillsRowNote( + row: AgentConfigSyncRow, + t: Translate = translate +): string | null { + if (row.state === 'synced' && row.withheldFiles > 0) { + return t( + 'cloudSkillsSync.row.withheld', + 'Synced without {{count}} files that look like keys or credentials', + { + count: row.withheldFiles, + defaultValue_one: 'Synced without 1 file that looks like a key or credential' + } + ) + } + if (row.state !== 'skipped') { + return row.convertedFrom + ? t('cloudSkillsSync.row.converted', 'Copied from {{agent}} so both agents have it', { + agent: AGENT_LABEL[agentOfKind(row.kind) === 'claude' ? 'codex' : 'claude'] + }) + : null + } + const key = row.outcome ?? row.skipReason + switch (key) { + case 'turned-off': + return t('cloudSkillsSync.row.turnedOff', 'Turned off') + case 'in-repo': + return t('cloudSkillsSync.row.inRepo', 'Committed to the repo, so the sandbox already has it') + case 'too-large': + return t('cloudSkillsSync.row.tooLarge', 'Too large to sync (256 KB a file, 512 KB a skill)') + case 'over-limit': + return t('cloudSkillsSync.row.overLimit', 'Over the 8 MB a workspace can receive') + case 'secret': + return t( + 'cloudSkillsSync.row.secret', + 'Looks like it contains a key or token, so it stays on this computer' + ) + case 'invalid': + return t('cloudSkillsSync.row.invalid', 'Its name or files can’t be copied') + case 'kept-host': + return t( + 'cloudSkillsSync.row.keptHost', + 'The sandbox has its own {{name}}, so it’s left alone', + { name: cloudSkillsDisplayName(row) } + ) + case 'no-project': + return t('cloudSkillsSync.row.noProject', 'The sandbox has no project checkout for it') + case 'failed': + return t('cloudSkillsSync.row.failed', 'Couldn’t write it in the sandbox') + case 'added': + case 'updated': + case 'unchanged': + case 'needed': + case undefined: + return null + } +} + +const FIXED_SKIPS: ReadonlySet = new Set([ + 'in-repo', + 'too-large', + 'secret', + 'invalid', + 'kept-host', + 'no-project' +]) + +/** A copy follows its original's switch; fixed skips can't be changed from here. */ +export function cloudSkillsRowToggleable(row: AgentConfigSyncRow): boolean { + if (row.convertedFrom) { + return false + } + const key = row.outcome ?? row.skipReason + return !key || !FIXED_SKIPS.has(key) +} + +export type CloudSkillsEntry = { row: AgentConfigSyncRow; copies: AgentConfigSyncRow[] } +export type CloudSkillsGroups = { + synced: CloudSkillsEntry[] + pending: CloudSkillsEntry[] + notSynced: CloudSkillsEntry[] +} + +const byName = (a: AgentConfigSyncRow, b: AgentConfigSyncRow): number => + cloudSkillsDisplayName(a).localeCompare(cloudSkillsDisplayName(b)) || a.key.localeCompare(b.key) + +/** Synced, ready (never synced yet) and not synced; each copy for the other agent sits under its original. */ +export function cloudSkillsGroupRows(rows: readonly AgentConfigSyncRow[]): CloudSkillsGroups { + const originals = new Set(rows.filter((row) => !row.convertedFrom).map((row) => row.key)) + const copies = new Map() + for (const row of rows) { + if (row.convertedFrom && originals.has(row.convertedFrom)) { + copies.set(row.convertedFrom, [...(copies.get(row.convertedFrom) ?? []), row]) + } + } + const groups: CloudSkillsGroups = { synced: [], pending: [], notSynced: [] } + for (const row of [...rows].sort(byName)) { + if (row.convertedFrom && originals.has(row.convertedFrom)) { + continue + } + const entry = { row, copies: (copies.get(row.key) ?? []).sort(byName) } + const group = + row.state === 'synced' + ? groups.synced + : row.state === 'pending' + ? groups.pending + : groups.notSynced + group.push(entry) + } + // Ones a switch can turn back on come before skips nothing here can fix. + groups.notSynced.sort( + (a, b) => + Number(!cloudSkillsRowToggleable(a.row)) - Number(!cloudSkillsRowToggleable(b.row)) || + byName(a.row, b.row) + ) + return groups +} + +export function cloudSkillsRowStateLabel( + row: AgentConfigSyncRow, + included: boolean, + t: Translate = translate +): string { + if (row.state === 'synced') { + return t('cloudSkillsSync.state.synced', 'Synced') + } + return row.state === 'pending' && included + ? t('cloudSkillsSync.state.pending', 'Not synced yet') + : t('cloudSkillsSync.state.skipped', 'Not synced') +} diff --git a/src/renderer/src/components/settings/orca-cloud/orca-cloud-settings-search.ts b/src/renderer/src/components/settings/orca-cloud/orca-cloud-settings-search.ts index 41619f41ea1..eb0f85e0a50 100644 --- a/src/renderer/src/components/settings/orca-cloud/orca-cloud-settings-search.ts +++ b/src/renderer/src/components/settings/orca-cloud/orca-cloud-settings-search.ts @@ -81,3 +81,20 @@ export const getOrcaCloudMcpSearchEntries = createLocalizedCatalog(() => [ ] } ]) + +export const getOrcaCloudSkillsSearchEntries = createLocalizedCatalog(() => [ + { + title: translate('cloudSkillsSync.title', 'Skills & commands'), + description: translate( + 'settings.orcaCloud.skills.searchDescription', + 'Sync Claude and Codex skills and slash commands from this computer to your cloud workspaces.' + ), + keywords: [ + ...translateSearchKeyword('settings.orcaCloud.skills.keywordSkills', 'skills'), + ...translateSearchKeyword('settings.orcaCloud.skills.keywordCommands', 'slash commands'), + ...translateSearchKeyword('settings.orcaCloud.skills.keywordPrompts', 'prompts'), + ...translateSearchKeyword('settings.orcaCloud.mcp.keywordSync', 'sync'), + ...translateSearchKeyword('settings.orcaCloud.mcp.keywordCloud', 'cloud') + ] + } +]) diff --git a/src/renderer/src/components/settings/page/settings-orca-cloud-section-renderers.tsx b/src/renderer/src/components/settings/page/settings-orca-cloud-section-renderers.tsx index 840d6004b42..11fa6961816 100644 --- a/src/renderer/src/components/settings/page/settings-orca-cloud-section-renderers.tsx +++ b/src/renderer/src/components/settings/page/settings-orca-cloud-section-renderers.tsx @@ -3,6 +3,7 @@ import { OrcaCloudEnvironmentsPane, OrcaCloudMcpPane, OrcaCloudSecretsPane, + OrcaCloudSkillsSyncPane, OrcaCloudTeamPane } from '../orca-cloud/OrcaCloudSettingsPanes' import { SettingsSection } from '../section-layout/SettingsSection' @@ -26,6 +27,7 @@ export function renderOrcaCloudSettingsSections( { id: 'cloud-billing', pane: }, { id: 'cloud-team', pane: }, { id: 'cloud-secrets', pane: }, + { id: 'cloud-skills', pane: }, { id: 'cloud-environments', pane: }, { id: 'cloud-mcp', pane: } ] diff --git a/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.test.ts b/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.test.ts index 1ad94723849..95ced781757 100644 --- a/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.test.ts +++ b/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.test.ts @@ -33,6 +33,7 @@ describe('Orca Cloud settings group', () => { 'cloud-billing', 'cloud-team', 'cloud-secrets', + 'cloud-skills', 'cloud-environments', 'cloud-mcp', 'cloud-api-keys' diff --git a/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.ts b/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.ts index 50a35d44cb6..1af181a9330 100644 --- a/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.ts +++ b/src/renderer/src/hooks/settings-navigation-orca-cloud-sections.ts @@ -6,13 +6,23 @@ import { getOrcaCloudBillingSearchEntries, getOrcaCloudEnvironmentsSearchEntries, getOrcaCloudMcpSearchEntries, + getOrcaCloudSkillsSearchEntries, getOrcaCloudSecretsSearchEntries, getOrcaCloudTeamSearchEntries } from '@/components/settings/orca-cloud/orca-cloud-settings-search' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' import type { SettingsNavSection } from '@/lib/settings-navigation-types' -import { Boxes, CreditCard, KeySquare, LockKeyhole, Plug, Users, Workflow } from 'lucide-react' +import { + BookOpenText, + Boxes, + CreditCard, + KeySquare, + LockKeyhole, + Plug, + Users, + Workflow +} from 'lucide-react' import type { SettingsNavigationBuildOptions } from './settings-navigation-build-options' import { CLOUD_ROUTINES_UI_ENABLED } from '../../../shared/cloud-api/cloud-routines-ui' @@ -59,6 +69,17 @@ export function buildOrcaCloudSettingsSections( searchEntries: getOrcaCloudSecretsSearchEntries(), group }, + { + id: 'cloud-skills', + title: t('cloudSkillsSync.title', 'Skills & commands'), + description: t( + 'settings.orcaCloud.skills.description', + 'Skills and slash commands from Claude and Codex on this computer, synced to your cloud workspaces.' + ), + icon: BookOpenText, + searchEntries: getOrcaCloudSkillsSearchEntries(), + group + }, { id: 'cloud-environments', title: t('settings.orcaCloud.environments.title', 'Cloud environments'), diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 0d7802b65b5..323af92fd2d 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -1585,6 +1585,20 @@ "lead_other": "{{hours}} sandbox hours to try Orca Cloud. No card needed." } }, + "cloudSkillsSync": { + "row": { + "withheld_one": "Synced without 1 file that looks like a key or credential", + "withheld_other": "Synced without {{count}} files that look like keys or credentials" + }, + "summary": { + "notSynced_one": "{{count}} found, not synced yet", + "notSynced_other": "{{count}} found, not synced yet", + "skipped_one": "{{count}} not synced", + "skipped_other": "{{count}} not synced", + "synced_one": "{{count}} synced", + "synced_other": "{{count}} synced" + } + }, "codeHost": { "bitbucketConnect": { "accessTokenRequired": "Enter an access token.", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 045e45d1476..9fabdd850cd 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -1391,6 +1391,13 @@ "keywordUsage": "usage", "keywordOverage": "overage", "description": "Your Orca Cloud plan, sandbox hours and payment." + }, + "skills": { + "searchDescription": "Sync Claude and Codex skills and slash commands from this computer to your cloud workspaces.", + "keywordSkills": "skills", + "keywordCommands": "slash commands", + "keywordPrompts": "prompts", + "description": "Skills and slash commands from Claude and Codex on this computer, synced to your cloud workspaces." } }, "groups": { @@ -28225,5 +28232,71 @@ "description": "Set up Claude and Codex once. Every cloud workspace uses them, including new, cloned and restarted ones.", "footerLabel": "Related settings", "allAccounts": "All agent accounts" + }, + "cloudSkillsSync": { + "title": "Skills & commands", + "appliesEverywhere": "Applies to every cloud workspace", + "toggleItem": "Sync {{name}} ({{kind}}) to cloud workspaces", + "loading": "Loading skills and commands…", + "syncedAgo": "synced {{time}}", + "syncing": "Syncing skills and commands…", + "syncingShort": "Syncing…", + "syncNow": "Sync now", + "syncAgain": "Sync again", + "manualOnly": "Not synced automatically. Sync now copies them once.", + "group": { + "synced": "Synced", + "pending": "Not synced yet", + "notSynced": "Not synced" + }, + "autoSync": "Sync when a workspace starts or wakes", + "autoSyncHint": "Copies your Claude and Codex skills and slash commands into each cloud workspace. Anything that looks like a key stays on this computer, and nothing made in the sandbox is overwritten.", + "shareAcrossAgents": "Share between Claude and Codex", + "shareAcrossAgentsHint": "In cloud workspaces, Codex also gets your Claude skills and commands, and Claude gets your Codex skills and prompts. An agent keeps its own if it has one with that name.", + "startFailed": "Couldn’t start the sync.", + "saveFailed": "Couldn’t save the change.", + "emptyBody": "Skills and commands sync to a cloud workspace while it runs. Start or wake one to see what it gets.", + "workspaceLabel": "Skills and commands in {{name}}", + "unavailable": "Skill sync isn’t available in this build.", + "kind": { + "skill": "{{agent}} skill", + "prompt": "Codex prompt", + "command": "{{agent}} command", + "project": "{{kind}}, this project" + }, + "summary": { + "none": "None found in Claude or Codex on this computer", + "notSynced_one": "{{count}} found, not synced yet", + "notSynced_other": "{{count}} found, not synced yet", + "synced_one": "{{count}} synced", + "synced_other": "{{count}} synced", + "skipped_one": "{{count}} not synced", + "skipped_other": "{{count}} not synced", + "pair": "{{synced}}, {{skipped}}" + }, + "error": { + "hostOutdated": "This workspace was created before skills sync. Create a new workspace to use it.", + "hostUnreachable": "Couldn’t reach the sandbox. Skills already there still work.", + "failed": "The last sync didn’t finish. Skills already in the sandbox still work." + }, + "row": { + "withheld_one": "Synced without 1 file that looks like a key or credential", + "withheld_other": "Synced without {{count}} files that look like keys or credentials", + "converted": "Copied from {{agent}} so both agents have it", + "turnedOff": "Turned off", + "inRepo": "Committed to the repo, so the sandbox already has it", + "tooLarge": "Too large to sync (256 KB a file, 512 KB a skill)", + "overLimit": "Over the 8 MB a workspace can receive", + "secret": "Looks like it contains a key or token, so it stays on this computer", + "invalid": "Its name or files can’t be copied", + "keptHost": "The sandbox has its own {{name}}, so it’s left alone", + "noProject": "The sandbox has no project checkout for it", + "failed": "Couldn’t write it in the sandbox" + }, + "state": { + "synced": "Synced", + "pending": "Not synced yet", + "skipped": "Not synced" + } } } diff --git a/src/renderer/src/lib/cloud-agent-config-sync/cloud-agent-config-sync-client.ts b/src/renderer/src/lib/cloud-agent-config-sync/cloud-agent-config-sync-client.ts new file mode 100644 index 00000000000..cc61c862d99 --- /dev/null +++ b/src/renderer/src/lib/cloud-agent-config-sync/cloud-agent-config-sync-client.ts @@ -0,0 +1,110 @@ +import { useEffect, useSyncExternalStore } from 'react' +import type { + AgentConfigSyncStatus, + CloudAgentConfigSyncPreferences +} from '../../../../shared/agent-config-sync/agent-config-sync-contract' + +// Main owns status and preferences; this mirrors its broadcasts for every open panel. +const statuses = new Map() +// Bumped by every broadcast so a slower reply can't overwrite newer state. +const versions = new Map() +let preferences: CloudAgentConfigSyncPreferences | null | undefined +let preferencesVersion = 0 +const listeners = new Set<() => void>() +let subscribedToMain = false + +function emit(): void { + for (const listener of listeners) { + listener() + } +} + +function storeStatus(status: AgentConfigSyncStatus): void { + statuses.set(status.environmentId, status) + versions.set(status.environmentId, (versions.get(status.environmentId) ?? 0) + 1) + emit() +} + +function storePreferences(next: CloudAgentConfigSyncPreferences): void { + preferences = next + preferencesVersion += 1 + emit() +} + +function subscribe(listener: () => void): () => void { + listeners.add(listener) + if (!subscribedToMain) { + subscribedToMain = true + const api = window.api.runtimeEnvironments + api.onAgentConfigSyncChanged?.(storeStatus) + api.onAgentConfigSyncPreferencesChanged?.(storePreferences) + } + return () => { + listeners.delete(listener) + } +} + +async function refreshStatus(environmentId: string): Promise { + const asked = versions.get(environmentId) ?? 0 + const status = await window.api.runtimeEnvironments + .getAgentConfigSyncStatus?.(environmentId) + .catch(() => undefined) + if (status === undefined || (versions.get(environmentId) ?? 0) !== asked) { + return + } + statuses.set(environmentId, status) + emit() +} + +async function refreshPreferences(): Promise { + const asked = preferencesVersion + const next = await window.api.runtimeEnvironments + .getAgentConfigSyncPreferences?.() + .catch(() => undefined) + if (next === undefined || preferencesVersion !== asked) { + return + } + preferences = next + emit() +} + +/** Undefined until main answers; null for hosts that are not Orca Cloud workspaces. */ +export function useCloudAgentConfigSyncStatus( + environmentId: string +): AgentConfigSyncStatus | null | undefined { + const status = useSyncExternalStore(subscribe, () => statuses.get(environmentId)) + useEffect(() => { + void refreshStatus(environmentId) + }, [environmentId]) + return status +} + +/** Undefined while loading; null in builds without Orca Cloud. */ +export function useCloudAgentConfigSyncPreferences(): + | CloudAgentConfigSyncPreferences + | null + | undefined { + const value = useSyncExternalStore(subscribe, () => preferences) + useEffect(() => { + void refreshPreferences() + }, []) + return value +} + +/** Main broadcasts every state this passes through, so the replies are not stored here. */ +export async function syncCloudAgentConfigNow(environmentId: string): Promise { + await window.api.runtimeEnvironments.syncAgentConfigNow?.(environmentId) +} + +export async function setCloudAgentConfigSyncPreferences( + next: Partial> +): Promise { + await window.api.runtimeEnvironments.setAgentConfigSyncPreferences?.(next) +} + +export async function setCloudAgentConfigItemIncluded( + key: string, + included: boolean +): Promise { + await window.api.runtimeEnvironments.setAgentConfigItemIncluded?.(key, included) +} diff --git a/src/renderer/src/lib/settings-navigation-types.ts b/src/renderer/src/lib/settings-navigation-types.ts index fe2c5ee41a5..3ef52130d40 100644 --- a/src/renderer/src/lib/settings-navigation-types.ts +++ b/src/renderer/src/lib/settings-navigation-types.ts @@ -51,6 +51,7 @@ const SETTINGS_NAV_TARGETS = [ 'cloud-secrets', 'cloud-environments', 'cloud-mcp', + 'cloud-skills', 'cloud-api-keys', 'cloud-routines', 'linear', diff --git a/src/shared/agent-config-sync/agent-config-sync-contract.ts b/src/shared/agent-config-sync/agent-config-sync-contract.ts new file mode 100644 index 00000000000..352b9085c0f --- /dev/null +++ b/src/shared/agent-config-sync/agent-config-sync-contract.ts @@ -0,0 +1,222 @@ +import { z } from 'zod' + +/** + * Skills and slash commands this computer copies into an Orca Cloud workspace's agent configs. + * The desktop reads them; the host (orcad in the sandbox) writes them and owns only what it wrote. + */ + +/** Where an item lives, on this computer and in the sandbox (the same place on both). */ +export const AgentConfigItemKind = z.enum([ + /** ~/.claude/skills// or /.claude/skills// */ + 'claude-skill', + /** ~/.claude/commands/.md or /.claude/commands/.md; `a/b` is the /a:b command. */ + 'claude-command', + /** ~/.agents/skills// or /.agents/skills//: the skills folder Codex reads. */ + 'agents-skill', + /** ~/.codex/skills//: Codex's older skills folder. */ + 'codex-skill', + /** ~/.codex/prompts/.md: Codex custom prompts (its slash commands). */ + 'codex-prompt' +]) +export type AgentConfigItemKind = z.infer + +export const AgentConfigItemScope = z.enum(['user', 'project']) +export type AgentConfigItemScope = z.infer + +export const AGENT_CONFIG_FILE_KINDS: ReadonlySet = new Set([ + 'claude-command', + 'codex-prompt' +]) +/** Kinds Claude Code or Codex reads from a project checkout. */ +export const AGENT_CONFIG_PROJECT_KINDS: ReadonlySet = new Set([ + 'claude-skill', + 'claude-command', + 'agents-skill' +]) + +export type AgentConfigAgent = 'claude' | 'codex' +export const agentOfKind = (kind: AgentConfigItemKind): AgentConfigAgent => + kind === 'claude-skill' || kind === 'claude-command' ? 'claude' : 'codex' +export const isSkillKind = (kind: AgentConfigItemKind): boolean => + !AGENT_CONFIG_FILE_KINDS.has(kind) + +const SEGMENT = '[A-Za-z0-9_][A-Za-z0-9._-]{0,63}' +/** A skill folder name. */ +export const AGENT_CONFIG_SKILL_NAME = new RegExp(`^${SEGMENT}$`) +/** A command name, up to two namespace folders deep (`frontend/review` is /frontend:review). */ +export const AGENT_CONFIG_COMMAND_NAME = new RegExp(`^${SEGMENT}(/${SEGMENT}){0,2}$`) +const FILE_SEGMENT = '[A-Za-z0-9_][A-Za-z0-9._ +@-]{0,127}' +/** A file inside a skill folder: relative, no dot-segments, no hidden files. */ +export const AGENT_CONFIG_FILE_PATH = new RegExp(`^${FILE_SEGMENT}(/${FILE_SEGMENT}){0,7}$`) +/** The one file of a command or prompt item. */ +export const AGENT_CONFIG_SELF_PATH = '.' + +export const AGENT_CONFIG_LIMITS = { + /** One file in a skill, or one command. */ + fileBytes: 256 * 1024, + /** One skill folder; also bounds one put call (base64 stays well under the 1 MiB RPC frame). */ + itemBytes: 512 * 1024, + filesPerItem: 200, + /** Everything one sync sends to a sandbox. */ + totalBytes: 8 * 1024 * 1024, + items: 256, + /** Items per put call (each call also stays under itemBytes). */ + putItems: 32 +} as const + +export const agentConfigItemKey = ( + scope: AgentConfigItemScope, + kind: AgentConfigItemKind, + name: string +): string => `${scope}:${kind}:${name}` + +const Digest = z.string().regex(/^[a-f0-9]{64}$/) +const Syncer = z.string().regex(/^[A-Za-z0-9_-]{1,64}$/) + +const ItemRef = z + .object({ + scope: AgentConfigItemScope, + kind: AgentConfigItemKind, + name: z.string().max(200), + digest: Digest + }) + .strict() + .refine((item) => item.scope === 'user' || AGENT_CONFIG_PROJECT_KINDS.has(item.kind), { + message: 'This kind has no project scope.' + }) + .refine( + (item) => + (isSkillKind(item.kind) ? AGENT_CONFIG_SKILL_NAME : AGENT_CONFIG_COMMAND_NAME).test( + item.name + ), + { message: 'Invalid name.' } + ) +export type AgentConfigItemRef = z.infer + +/** The complete set this computer manages; anything it wrote before and no longer sends is removed. */ +export const AgentConfigSyncPlanParams = z + .object({ + syncer: Syncer, + items: z.array(ItemRef).max(AGENT_CONFIG_LIMITS.items) + }) + .strict() +export type AgentConfigSyncPlanParams = z.infer + +export const AgentConfigPlanOutcome = z.enum([ + /** Not there, or this computer's older copy: send it. */ + 'needed', + 'unchanged', + /** The host has its own (or an edited) item of that name; it wins and is never touched. */ + 'kept-host', + /** Project item, but this host has no workspace checkout. */ + 'no-project' +]) +export type AgentConfigPlanOutcome = z.infer + +export const AgentConfigSyncPlanResult = z.object({ + items: z.record(z.string(), AgentConfigPlanOutcome), + removed: z.number().int().nonnegative() +}) +export type AgentConfigSyncPlanResult = z.infer + +const FilePayload = z + .object({ + path: z + .string() + .max(600) + .refine((path) => path === AGENT_CONFIG_SELF_PATH || AGENT_CONFIG_FILE_PATH.test(path)), + executable: z.boolean(), + base64: z.string().max(Math.ceil(AGENT_CONFIG_LIMITS.fileBytes / 3) * 4 + 4) + }) + .strict() +export type AgentConfigFilePayload = z.infer + +export const AgentConfigSyncPutParams = z + .object({ + syncer: Syncer, + items: z + .array( + z + .object({ + scope: AgentConfigItemScope, + kind: AgentConfigItemKind, + name: z.string().max(200), + digest: Digest, + files: z.array(FilePayload).min(1).max(AGENT_CONFIG_LIMITS.filesPerItem) + }) + .strict() + ) + .min(1) + .max(AGENT_CONFIG_LIMITS.putItems) + }) + .strict() +export type AgentConfigSyncPutParams = z.infer +export type AgentConfigItemPayload = AgentConfigSyncPutParams['items'][number] + +export const AgentConfigPutOutcome = z.enum([ + 'added', + 'updated', + 'kept-host', + 'no-project', + /** Payload did not match its digest or broke a limit. */ + 'invalid', + 'failed' +]) +export type AgentConfigPutOutcome = z.infer + +export const AgentConfigSyncPutResult = z.object({ + items: z.record(z.string(), AgentConfigPutOutcome) +}) +export type AgentConfigSyncPutResult = z.infer + +export const AGENT_CONFIG_SYNC_PLAN_METHOD = 'agentConfig.planSkillSync' +export const AGENT_CONFIG_SYNC_PUT_METHOD = 'agentConfig.putSkills' + +/** Why this computer does not send an item; each row shows one. */ +export type AgentConfigSkipReason = + | 'turned-off' + /** Project item that git tracks: the sandbox's clone already has it. */ + | 'in-repo' + | 'too-large' + | 'over-limit' + /** The skill's main file (or the command) looks like it holds a key or token. */ + | 'secret' + | 'invalid' + +/** One item as the UI sees it: never file contents. */ +export type AgentConfigSyncRow = { + key: string + scope: AgentConfigItemScope + kind: AgentConfigItemKind + name: string + bytes: number + fileCount: number + /** Files kept on this computer because they look like keys or credentials. */ + withheldFiles: number + /** Set on a copy made for the other agent: the key of the item it came from. */ + convertedFrom?: string + included: boolean + state: 'synced' | 'skipped' | 'pending' + skipReason?: AgentConfigSkipReason + outcome?: AgentConfigPlanOutcome | AgentConfigPutOutcome +} + +export type AgentConfigSyncStatus = { + environmentId: string + running: boolean + lastSyncedAt: number | null + error: 'host-outdated' | 'host-unreachable' | 'failed' | null + rows: AgentConfigSyncRow[] +} + +export type CloudAgentConfigSyncPreferences = { + /** Sync on every connect (create and wake) to an Orca Cloud workspace. */ + autoSync: boolean + /** Also give Codex the Claude Code skills and commands, and Claude Code the Codex ones. */ + shareAcrossAgents: boolean + /** Item keys the user turned off. */ + excluded: string[] +} + +export const CLOUD_AGENT_CONFIG_SYNC_CHANGED_CHANNEL = 'cloudAgentConfigSync:changed' +export const CLOUD_AGENT_CONFIG_SYNC_PREFERENCES_CHANNEL = 'cloudAgentConfigSync:preferences' diff --git a/src/shared/rpc-contract/rpc-params-catalog.generated.ts b/src/shared/rpc-contract/rpc-params-catalog.generated.ts index c2ecacbccc1..41616bde191 100644 --- a/src/shared/rpc-contract/rpc-params-catalog.generated.ts +++ b/src/shared/rpc-contract/rpc-params-catalog.generated.ts @@ -1,6 +1,10 @@ // GENERATED by config/scripts/generate-rpc-params-catalog.mjs. Do not edit; // run `pnpm run generate:rpc-params-catalog`. import type { z } from 'zod' +import { + AgentConfigSyncPlanParams, + AgentConfigSyncPutParams +} from '../agent-config-sync/agent-config-sync-contract' import { HostAccountLaunchEnvParams } from '../agent-launch/startup/host-account-launch-env' import { AgentMcpSyncParams } from '../agent-mcp-sync/mcp-sync-contract' import { AgentSkillShareRequestSchema } from '../agent-skill-sharing-contract' @@ -850,6 +854,8 @@ export const RPC_PARAMS_BY_METHOD = { 'agent.launchReplay': AgentLaunchReplay, 'agentActivity.clear': AgentActivityClearParams, 'agentActivity.setRead': AgentActivitySetReadParams, + 'agentConfig.planSkillSync': AgentConfigSyncPlanParams, + 'agentConfig.putSkills': AgentConfigSyncPutParams, 'agentConfig.syncMcpServers': AgentMcpSyncParams, 'agentHooks.prepareCodexForWslPane': PrepareCodexForWslPaneParams, 'agentSession.accountUsage': OptionsParams, From 58ddf6858413bcbae841fdf2aab7379558fd8665 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 22:51:22 -0800 Subject: [PATCH 147/149] fix(cloud): cloud-workspaces IPC under max-lines after integration merge (combine not-configured/invalid guards) --- src/main/ipc/cloud-workspaces.ts | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/src/main/ipc/cloud-workspaces.ts b/src/main/ipc/cloud-workspaces.ts index da43814f0d0..1024b3da202 100644 --- a/src/main/ipc/cloud-workspaces.ts +++ b/src/main/ipc/cloud-workspaces.ts @@ -173,11 +173,8 @@ export function registerCloudWorkspacesHandlers( handle('cloudWorkspaces:list', async (args) => { const query = ListQuery.safeParse(args ?? {}) const s = await getService() - if (!s) { - return NOT_CONFIGURED - } - if (!query.success) { - return INVALID + if (!s || !query.success) { + return !s ? NOT_CONFIGURED : INVALID } const result = await s.list(query.data) // Each successful refresh also checks this device's pairings (throttled, in the background). @@ -250,11 +247,8 @@ export function registerCloudWorkspacesHandlers( handle('cloudWorkspaces:destroy', async (args) => { const parsed = z.object({ id: Id }).safeParse(args) const s = await getService() - if (!s) { - return NOT_CONFIGURED - } - if (!parsed.success) { - return INVALID + if (!s || !parsed.success) { + return !s ? NOT_CONFIGURED : INVALID } const result = await s.destroy(parsed.data.id) // Deleted from here: its pairing, server and projects go now, not at the next list. From ab7bde85ba4fe70fccb0c4f01353ccc57a2da617 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 22:57:06 -0800 Subject: [PATCH 148/149] fix(cloud): closeMissingRemotePage depends on browserTab.worktreeId (exhaustive-deps) --- .../stream-remote/use-remote-browser-page-lifecycle.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-lifecycle.ts b/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-lifecycle.ts index b567d06920e..7d894746866 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-lifecycle.ts +++ b/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-lifecycle.ts @@ -178,6 +178,7 @@ export function useRemoteBrowserPageLifecycle({ [ browserTab.id, browserTab.workspaceId, + browserTab.worktreeId, clearStreamFrame, closeBrowserPage, closeBrowserTab, From de561419a5acc31883a98f1a9a3206c10dbc4a48 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 23:02:10 -0800 Subject: [PATCH 149/149] chore(i18n): regenerate the runtime English catalog without the footnote (JA-23) --- src/renderer/src/i18n/en-runtime-required.json | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index d99efd0b610..323af92fd2d 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -17,9 +17,6 @@ } } }, - "agentAccountsOverview": { - "footnote": "“Signed in” means the host confirmed it in the last minute. Orca Cloud comes from your Orca account, so there’s nothing to check per sandbox. Orca doesn’t wake a sandbox just to check sign-ins." - }, "agentHostPanel": { "recipeEnvDetailNoKeys_one": "{{count}} variable, none that look like keys. The recipe decides what reaches the VM.", "recipeEnvDetailNoKeys_other": "{{count}} variables, none that look like keys. The recipe decides what reaches the VM.",