From 3e5fa71c071c2ad196d9e18342f92e5f86b6cef5 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 19:16:39 -0800 Subject: [PATCH 1/5] =?UTF-8?q?fix(cloud):=20one=20post-create=20agent=20p?= =?UTF-8?q?rompt=20=E2=80=94=20exact=20copy,=20names=20the=20workspace=20a?= =?UTF-8?q?fter=20a=20switch,=20clears=20when=20the=20account=20turns=20ac?= =?UTF-8?q?tive?= 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 2/5] =?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 3/5] 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 6bb8b95dc41c7dcb5f334d9556b9ce916e31dc2a Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 20:36:46 -0800 Subject: [PATCH 4/5] 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 5/5] 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 } : {}),