From 1ebdef8df603e27e887e135cba9520ae607bf9d9 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 08:45:38 -0800 Subject: [PATCH 1/3] =?UTF-8?q?feat(cloud):=20NP-3=20build-sheet=20Agents?= =?UTF-8?q?=20row=20(spec=20v4=20=C2=A75b):=20fixed=20height=20at=20mount,?= =?UTF-8?q?=20zero=20layout=20shift?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - One row from the Orca account, never the sandbox: 32 px ready line when every agent is ready at mount, otherwise 48 px; every later state renders inside that height (Playwright: measured layout shift 0, logs toggle never moves). - R2 Set up runs S0's setup inline for each agent in turn; device code, browser, paste, failed, expired, kill switch (per-workspace sign-in, queued until the sandbox answers), A6 desktop key. - ⋯ menu: Source per agent in this workspace (new per-workspace setWorkspaceSource / workspaceSources IPC; main resolves the sandbox id from its own runtime records), Manage agent accounts. - Removes the v3 'Add an agent' build step and the per-sandbox Cloud sign-in row from the sheet. --- src/main/cloud-secrets/cloud-secrets-ipc.ts | 20 +- .../hosted-sandbox/orca-cloud-sandbox-id.ts | 21 + .../agent-credentials-client.test.ts | 19 + .../agent-credentials-client.ts | 25 +- .../orca-cloud-agents-ipc.ts | 29 +- .../orca-cloud-agents-service.test.ts | 5 + .../orca-cloud-agents-service.ts | 14 +- src/preload/api/orca-cloud-agents-bridge.ts | 13 + .../CloudAgentSetup.fixture.tsx | 134 +----- .../VmBuildCloudAgentStep.tsx | 410 ------------------ .../cloud-agent-setup-focus.test.tsx | 67 +-- .../VmBuildSheet.fixture.tsx | 3 + .../worktree-creation/VmBuildSheet.tsx | 24 +- .../VmBuildCloudAgentsMenu.tsx | 145 +++++++ .../VmBuildCloudAgentsRow.tsx | 197 +++++++++ .../VmBuildCloudAgentsRowView.tsx | 371 ++++++++++++++++ .../cloud-agents-row/build-agents-row-copy.ts | 174 ++++++++ .../use-inline-setup-queue.ts | 77 ++++ .../vm-build-sheet-agents-fixtures.tsx | 232 ++++++++++ .../vm-build-sheet-fixture-support.tsx | 4 +- src/renderer/src/i18n/locales/en.json | 54 +++ .../orca-cloud-build-agents-row.test.ts | 128 ++++++ .../orca-cloud/orca-cloud-build-agents-row.ts | 170 ++++++++ .../vm-build-cloud-agents-row.spec.ts | 124 ++++++ 24 files changed, 1817 insertions(+), 643 deletions(-) create mode 100644 src/main/hosted-sandbox/orca-cloud-sandbox-id.ts delete mode 100644 src/renderer/src/components/cloud-agent-setup/VmBuildCloudAgentStep.tsx create mode 100644 src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsMenu.tsx create mode 100644 src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRow.tsx create mode 100644 src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRowView.tsx create mode 100644 src/renderer/src/components/worktree-creation/cloud-agents-row/build-agents-row-copy.ts create mode 100644 src/renderer/src/components/worktree-creation/cloud-agents-row/use-inline-setup-queue.ts create mode 100644 src/renderer/src/components/worktree-creation/vm-build-sheet-agents-fixtures.tsx create mode 100644 src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.test.ts create mode 100644 src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.ts create mode 100644 tests/component-fixtures/vm-build-cloud-agents-row.spec.ts diff --git a/src/main/cloud-secrets/cloud-secrets-ipc.ts b/src/main/cloud-secrets/cloud-secrets-ipc.ts index 7a002a8522c..5c936e5d704 100644 --- a/src/main/cloud-secrets/cloud-secrets-ipc.ts +++ b/src/main/cloud-secrets/cloud-secrets-ipc.ts @@ -8,11 +8,9 @@ import { type CloudSecretsResult, type CloudSecretsStatus } from '../../shared/cloud-secrets/cloud-secrets-wire' -import { listEphemeralVmRuntimes } from '../../shared/ephemeral-vm-runtime-store' -import { environmentHandleFromRecipeResult } from '../environment-providers/environment-provider-recipe-adapter' import { withCloudBuildDefaults } from '../cloud-build-defaults' import { getHostedSandboxConfig } from '../hosted-sandbox/hosted-sandbox-config' -import { HOSTED_SANDBOX_DRIVER_ID } from '../hosted-sandbox/hosted-sandbox-driver' +import { orcaCloudSandboxIdFor } from '../hosted-sandbox/orca-cloud-sandbox-id' import { getOrcaCloudAvailability } from '../hosted-sandbox/hosted-sandbox-install' import { isTuiAgent } from '../../shared/agent-launch/catalog/tui-agent-config' import { @@ -92,18 +90,6 @@ async function attempt( } } -function sandboxIdFor(userDataPath: string, runtimeEnvironmentId: string): string | null { - const runtime = listEphemeralVmRuntimes(userDataPath).find( - (record) => - record.runtimeEnvironmentId === runtimeEnvironmentId && - record.recipe?.provider === 'orca-cloud' - ) - const handle = runtime?.recipeResult - ? environmentHandleFromRecipeResult(runtime.recipeResult, HOSTED_SANDBOX_DRIVER_ID) - : null - return handle?.environmentId ?? null -} - export function registerCloudSecretsHandlers(userDataPath: string): void { setCloudDesktopKeysUserDataPath(userDataPath) // Packaged integration builds read no shell env; their control-plane URL is baked in. @@ -197,7 +183,7 @@ export function registerCloudSecretsHandlers(userDataPath: string): void { if (!request.success) { return invalid } - const sandboxId = sandboxIdFor(userDataPath, request.data.runtimeEnvironmentId) + const sandboxId = orcaCloudSandboxIdFor(userDataPath, request.data.runtimeEnvironmentId) return sandboxId ? attempt(client, (c) => c.workspaceSharing(sandboxId)) : { ok: false, error: 'not_found' } @@ -207,7 +193,7 @@ export function registerCloudSecretsHandlers(userDataPath: string): void { if (!request.success) { return invalid } - const sandboxId = sandboxIdFor(userDataPath, request.data.runtimeEnvironmentId) + const sandboxId = orcaCloudSandboxIdFor(userDataPath, request.data.runtimeEnvironmentId) return sandboxId ? attempt(client, (c) => c.refreshEnv(sandboxId)) : { ok: false, error: 'not_found' } diff --git a/src/main/hosted-sandbox/orca-cloud-sandbox-id.ts b/src/main/hosted-sandbox/orca-cloud-sandbox-id.ts new file mode 100644 index 00000000000..d312c200e1a --- /dev/null +++ b/src/main/hosted-sandbox/orca-cloud-sandbox-id.ts @@ -0,0 +1,21 @@ +// The Orca Cloud sandbox id (the control plane's workspaceId) behind a runtime environment on this +// computer. Only an Orca Cloud runtime this desktop provisioned resolves, so the renderer can't name +// an arbitrary sandbox. +import { listEphemeralVmRuntimes } from '../../shared/ephemeral-vm-runtime-store' +import { environmentHandleFromRecipeResult } from '../environment-providers/environment-provider-recipe-adapter' +import { HOSTED_SANDBOX_DRIVER_ID } from './hosted-sandbox-driver' + +export function orcaCloudSandboxIdFor( + userDataPath: string, + runtimeEnvironmentId: string +): string | null { + const runtime = listEphemeralVmRuntimes(userDataPath).find( + (record) => + record.runtimeEnvironmentId === runtimeEnvironmentId && + record.recipe?.provider === 'orca-cloud' + ) + const handle = runtime?.recipeResult + ? environmentHandleFromRecipeResult(runtime.recipeResult, HOSTED_SANDBOX_DRIVER_ID) + : null + return handle?.environmentId ?? null +} diff --git a/src/main/orca-cloud-agents/agent-credentials-client.test.ts b/src/main/orca-cloud-agents/agent-credentials-client.test.ts index 136a74f6c3c..75d83775e35 100644 --- a/src/main/orca-cloud-agents/agent-credentials-client.test.ts +++ b/src/main/orca-cloud-agents/agent-credentials-client.test.ts @@ -142,4 +142,23 @@ describe('createAgentCredentialsClient', () => { body: JSON.stringify({ agent: 'claude', source: 'sign-in' }) }) }) + + it('reads and writes one workspace’s Source by its sandbox id', async () => { + const { client, seen } = fakeControlPlane(() => + Response.json({ + defaults: {}, + effective: { codex: { source: 'key' } }, + coveredByKey: { claude: false, codex: true }, + sharedWorkspace: false + }) + ) + const read = await client.sources(undefined, 'sbx_41d9') + expect(read.effective?.codex?.source).toBe('key') + await client.setWorkspaceSource('codex', 'key', 'sbx_41d9') + expect(seen[0]?.url).toContain('/v1/agent-sources?workspaceId=sbx_41d9') + expect(seen[1]).toMatchObject({ + method: 'PUT', + body: JSON.stringify({ agent: 'codex', source: 'key', workspaceId: 'sbx_41d9' }) + }) + }) }) diff --git a/src/main/orca-cloud-agents/agent-credentials-client.ts b/src/main/orca-cloud-agents/agent-credentials-client.ts index 20a1ebc981d..ae25831114c 100644 --- a/src/main/orca-cloud-agents/agent-credentials-client.ts +++ b/src/main/orca-cloud-agents/agent-credentials-client.ts @@ -23,11 +23,18 @@ import { export type AgentCredentialsClient = { credentials(signal?: AbortSignal): Promise - sources(signal?: AbortSignal): Promise + /** With a workspaceId (sandbox id), `effective` and `sharedWorkspace` describe that workspace. */ + sources(signal?: AbortSignal, workspaceId?: string): Promise /** Main only, right after setup-token on this computer or a paste. */ putClaude(token: string, label?: string): Promise remove(agent: OrcaCloudAccountAgent): Promise setDefaultSource(agent: OrcaCloudAccountAgent, source: AgentSource): Promise + /** The Source for one workspace (sandbox id); the reply describes that workspace. */ + setWorkspaceSource( + agent: OrcaCloudAccountAgent, + source: AgentSource, + workspaceId: string + ): Promise startCodexBroker(): Promise codexBrokerStatus(brokerId: string): Promise cancelCodexBroker(brokerId: string): Promise @@ -54,8 +61,15 @@ export function createAgentCredentialsClient( kind: 'control', signal }), - sources: (signal) => - call('GET', 'v1/agent-sources', AgentSourcesResponseSchema, { kind: 'control', signal }), + sources: (signal, workspaceId) => + call( + 'GET', + workspaceId + ? `v1/agent-sources?${new URLSearchParams({ workspaceId })}` + : 'v1/agent-sources', + AgentSourcesResponseSchema, + { kind: 'control', signal } + ), putClaude: (token, label) => call('PUT', 'v1/agent-credentials/claude', AgentCredentialsResponseSchema, { body: label ? { token, label } : { token }, @@ -70,6 +84,11 @@ export function createAgentCredentialsClient( body: { agent, source }, kind: 'control' }), + setWorkspaceSource: (agent, source, workspaceId) => + call('PUT', 'v1/agent-sources', AgentSourcesResponseSchema, { + body: { agent, source, workspaceId }, + kind: 'control' + }), startCodexBroker: () => call('POST', 'v1/agent-credentials/codex/broker', CodexBrokerStartResponseSchema, { body: {}, diff --git a/src/main/orca-cloud-agents/orca-cloud-agents-ipc.ts b/src/main/orca-cloud-agents/orca-cloud-agents-ipc.ts index e4db0f700cd..8051f811b90 100644 --- a/src/main/orca-cloud-agents/orca-cloud-agents-ipc.ts +++ b/src/main/orca-cloud-agents/orca-cloud-agents-ipc.ts @@ -8,6 +8,7 @@ import { } from '../../shared/orca-cloud-agents/orca-cloud-agents-wire' import { withCloudBuildDefaults } from '../cloud-build-defaults' import { getHostedSandboxConfig } from '../hosted-sandbox/hosted-sandbox-config' +import { orcaCloudSandboxIdFor } from '../hosted-sandbox/orca-cloud-sandbox-id' import { claudeStateFile, readClaudeFolderLogin } from '../claude-accounts/claude-account-folder' import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' import { getOrcaProfileIndexGeneration } from '../orca-profiles/profile-index-generation' @@ -25,6 +26,10 @@ const AgentRequest = z.object({ agent: Agent }) // Bounded well above a real token; the service checks the exact shape. const PasteRequest = z.object({ token: z.string().min(1).max(1024) }) const SourceRequest = z.object({ agent: Agent, source: z.enum(['sign-in', 'key']).nullable() }) +// A runtime environment, never a raw sandbox id: main resolves only sandboxes this desktop made. +const RuntimeEnvironment = z.string().min(1).max(256) +const WorkspaceRequest = z.object({ runtimeEnvironmentId: RuntimeEnvironment }) +const WorkspaceSourceRequest = SourceRequest.extend({ runtimeEnvironmentId: RuntimeEnvironment }) const CHANNELS = [ 'orcaCloudAgents:status', @@ -36,7 +41,9 @@ const CHANNELS = [ 'orcaCloudAgents:pasteClaudeToken', 'orcaCloudAgents:acknowledge', 'orcaCloudAgents:remove', - 'orcaCloudAgents:setDefaultSource' + 'orcaCloudAgents:setDefaultSource', + 'orcaCloudAgents:workspaceSources', + 'orcaCloudAgents:setWorkspaceSource' ] as const function broadcast(setups: OrcaCloudAgentSetups): void { @@ -148,4 +155,24 @@ export function registerOrcaCloudAgentsHandlers(userDataPath: string): void { ? service.setDefaultSource(request.data.agent, request.data.source) : invalid }) + // Before the sandbox exists there is no workspace to name: the reply is not_found. + const notFound = { ok: false, error: 'not_found' } as const + ipcMain.handle('orcaCloudAgents:workspaceSources', (_event, raw: unknown) => { + const request = WorkspaceRequest.safeParse(raw) + if (!request.success) { + return invalid + } + const workspaceId = orcaCloudSandboxIdFor(userDataPath, request.data.runtimeEnvironmentId) + return workspaceId ? service.workspaceSources(workspaceId) : notFound + }) + ipcMain.handle('orcaCloudAgents:setWorkspaceSource', (_event, raw: unknown) => { + const request = WorkspaceSourceRequest.safeParse(raw) + if (!request.success) { + return invalid + } + const workspaceId = orcaCloudSandboxIdFor(userDataPath, request.data.runtimeEnvironmentId) + return workspaceId + ? service.setWorkspaceSource(request.data.agent, request.data.source, workspaceId) + : notFound + }) } diff --git a/src/main/orca-cloud-agents/orca-cloud-agents-service.test.ts b/src/main/orca-cloud-agents/orca-cloud-agents-service.test.ts index 72142dd61bb..fda0ea62b67 100644 --- a/src/main/orca-cloud-agents/orca-cloud-agents-service.test.ts +++ b/src/main/orca-cloud-agents/orca-cloud-agents-service.test.ts @@ -46,6 +46,11 @@ function fakeClient(overrides: Partial = {}): AgentCrede defaults: { claude: 'sign-in' as const }, coveredByKey: { claude: true, codex: false } })), + setWorkspaceSource: vi.fn(async () => ({ + defaults: {}, + effective: { claude: { source: 'key' as const } }, + coveredByKey: { claude: true, codex: false } + })), startCodexBroker: vi.fn(), codexBrokerStatus: vi.fn(), cancelCodexBroker: vi.fn(async () => {}), diff --git a/src/main/orca-cloud-agents/orca-cloud-agents-service.ts b/src/main/orca-cloud-agents/orca-cloud-agents-service.ts index e37e4dc648f..5b0922cd54d 100644 --- a/src/main/orca-cloud-agents/orca-cloud-agents-service.ts +++ b/src/main/orca-cloud-agents/orca-cloud-agents-service.ts @@ -323,6 +323,18 @@ export function createOrcaCloudAgentsService(deps: OrcaCloudAgentsServiceDeps) { agent: OrcaCloudAccountAgent, source: AgentSource ): Promise> => - attempt((client) => client.setDefaultSource(agent, source)) + attempt((client) => client.setDefaultSource(agent, source)), + + /** One workspace's Sources (sandbox id), for the build sheet's ⋯ menu. */ + workspaceSources: (workspaceId: string): Promise> => + attempt((client) => client.sources(undefined, workspaceId)), + + /** The per-workspace override (S1-b). It applies at the next request (D10). */ + setWorkspaceSource: ( + agent: OrcaCloudAccountAgent, + source: AgentSource, + workspaceId: string + ): Promise> => + attempt((client) => client.setWorkspaceSource(agent, source, workspaceId)) } } diff --git a/src/preload/api/orca-cloud-agents-bridge.ts b/src/preload/api/orca-cloud-agents-bridge.ts index 42726defe87..046b04a2c00 100644 --- a/src/preload/api/orca-cloud-agents-bridge.ts +++ b/src/preload/api/orca-cloud-agents-bridge.ts @@ -27,6 +27,16 @@ export type OrcaCloudAgentsApi = { agent: OrcaCloudAccountAgent source: AgentSource }) => Promise> + /** One workspace's Sources; not_found until the sandbox exists. */ + workspaceSources: (request: { + runtimeEnvironmentId: string + }) => Promise> + /** The per-workspace override (S1-b); the reply describes that workspace. */ + setWorkspaceSource: (request: { + agent: OrcaCloudAccountAgent + source: AgentSource + runtimeEnvironmentId: string + }) => Promise> onSetupChanged: (listener: (setups: OrcaCloudAgentSetups) => void) => () => void } @@ -41,6 +51,9 @@ export const orcaCloudAgentsApi: OrcaCloudAgentsApi = { acknowledge: (request) => ipcRenderer.invoke('orcaCloudAgents:acknowledge', request), remove: (request) => ipcRenderer.invoke('orcaCloudAgents:remove', request), setDefaultSource: (request) => ipcRenderer.invoke('orcaCloudAgents:setDefaultSource', request), + workspaceSources: (request) => ipcRenderer.invoke('orcaCloudAgents:workspaceSources', request), + setWorkspaceSource: (request) => + ipcRenderer.invoke('orcaCloudAgents:setWorkspaceSource', request), onSetupChanged: (listener) => { const handler = (_event: Electron.IpcRendererEvent, setups: OrcaCloudAgentSetups): void => listener(setups) diff --git a/src/renderer/src/components/cloud-agent-setup/CloudAgentSetup.fixture.tsx b/src/renderer/src/components/cloud-agent-setup/CloudAgentSetup.fixture.tsx index e83b8aa2745..002a7b795cf 100644 --- a/src/renderer/src/components/cloud-agent-setup/CloudAgentSetup.fixture.tsx +++ b/src/renderer/src/components/cloud-agent-setup/CloudAgentSetup.fixture.tsx @@ -1,79 +1,11 @@ -import React, { useEffect, useState } from 'react' +import React from 'react' import { defineFixture } from '../../component-fixtures/component-fixture' -import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation' -import { VmBuildSheet } from '../worktree-creation/VmBuildSheet' import type { CloudAgentReadiness } from './cloud-agent-readiness' import type { CloudAgentSetupFailure, CloudAgentSetupOption } from './cloud-agent-setup-choices' import { CloudAgentSetupSavedNotice, CloudAgentSetupView } from './CloudAgentSetupView' -import { - VmBuildCloudAgentStepView, - type VmBuildCloudAgentStepMode, - type VmBuildCloudAgentStepModel -} from './VmBuildCloudAgentStep' const NONE: CloudAgentReadiness = { claude: null, codex: null } const noop = (): void => {} -const actions = { - onSave: async () => null, - // The Gemini key fails so one sheet shows both row outcomes. - onSaveDesktopKey: async (key: { envName: string }) => - key.envName === 'GEMINI_API_KEY' ? ('unavailable' as const) : null, - onDone: noop, - onSignIn: noop, - onCancelSignIn: noop, - onLater: noop -} - -const ENTRY: PendingWorktreeCreation = { - creationId: 'fixture', - phase: 'provisioning-vm', - status: 'creating', - startedAt: 0, - indeterminate: false, - loaderVisible: true, - provisioningLog: 'Creating Orca Cloud sandbox…\nCloning acme/web…', - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the sheet reads only name and ephemeralVmRecipe from the request. - request: { - name: 'fix-login', - ephemeralVmRecipe: { - sourceRepoId: 'repo', - recipeId: 'cloud', - projectId: 'p', - provider: 'orca-cloud' - } - } as PendingWorktreeCreation['request'] -} - -function sheet( - model: VmBuildCloudAgentStepModel, - initialMode?: VmBuildCloudAgentStepMode, - interact?: (frame: HTMLElement) => Promise -) { - return defineFixture({ - width: 760, - render: () => ( -
- - } - /> -
- ), - interact - }) -} - const settle = (): Promise => new Promise((resolve) => setTimeout(resolve, 50)) function typeInto(input: HTMLInputElement | null, value: string): void { @@ -84,75 +16,11 @@ function typeInto(input: HTMLInputElement | null, value: string): void { input.dispatchEvent(new Event('input', { bubbles: true })) } -export const buildOffer = sheet({ readiness: NONE, canShare: false }) - -export const buildKeysAdmin = sheet({ readiness: NONE, canShare: true }, { kind: 'keys' }) - -export const buildSignInPending = sheet({ readiness: NONE, canShare: false }, { kind: 'signIn' }) - -export const buildSkipped = sheet({ readiness: NONE, canShare: false }, { kind: 'skipped' }) - -export const buildSaved = sheet( - { readiness: NONE, canShare: true }, - { kind: 'saved', saved: { agents: ['claude'], scope: 'org' } } -) - const DESKTOP_KEYS = [ { id: 'k1', agent: 'claude', envName: 'ANTHROPIC_API_KEY', hint: 'x4Qa' }, { id: 'k2', agent: 'gemini', envName: 'GEMINI_API_KEY', hint: '9fZk' } ] as const -/** This computer has Agent API Keys: the key form offers each one as a Cloud secret. */ -export const buildKeysWithDesktopKeys = sheet( - { readiness: NONE, canShare: false, desktopKeys: [...DESKTOP_KEYS] }, - { kind: 'keys' } -) - -/** The same step after saving both: Claude's key saved, Gemini's failed and can be tried again. */ -export const buildKeysDesktopKeysSavedAndFailed = sheet( - { readiness: NONE, canShare: false, desktopKeys: [...DESKTOP_KEYS] }, - { kind: 'keys' }, - async (frame) => { - for (const button of frame.querySelectorAll('[aria-label^="Save "]')) { - button.click() - await settle() - } - } -) - -export const buildReadyTeam = sheet({ - readiness: { claude: 'team', codex: 'team' }, - canShare: false -}) - -/** The sandbox reports in while the user is on the queued sign-in row: the row stays, focused. */ -function HandedOffStep(): React.JSX.Element { - const [handedOff, setHandedOff] = useState(false) - useEffect(() => { - document.querySelector('[data-vm-build-cloud-agent]')?.focus() - setHandedOff(true) - }, []) - return ( - - ) -} - -export const buildSignInHandedOff = defineFixture({ - width: 760, - render: () => ( -
-
    - -
-
- ) -}) - function Dialogish({ children }: { children: React.ReactNode }): React.JSX.Element { return (
diff --git a/src/renderer/src/components/cloud-agent-setup/VmBuildCloudAgentStep.tsx b/src/renderer/src/components/cloud-agent-setup/VmBuildCloudAgentStep.tsx deleted file mode 100644 index c29d1c24cd6..00000000000 --- a/src/renderer/src/components/cloud-agent-setup/VmBuildCloudAgentStep.tsx +++ /dev/null @@ -1,410 +0,0 @@ -import React, { useEffect, useRef, useState, useSyncExternalStore } from 'react' -import { CircleCheck, KeyRound } from 'lucide-react' -import { useAppStore } from '@/store' -import { useTranslate } from '@/i18n/use-translate' -import { Button } from '@/components/ui/button' -import { startVmBuildAgentSignIn } from '@/lib/agent-sign-in/vm-build-agent-sign-in' -import { - readHostAgentSignInReport, - subscribeHostAgentSignInReports -} from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client' -import { HOST_AGENT_SIGN_IN_AGENTS } from '../../../../shared/host-agent-sign-in-status' -import { ORCA_CLOUD_RECIPE_ID } from '../../../../shared/hosted-sandbox/orca-cloud-recipe-id' -import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation' -import { cloudSecretRepoKey } from '../settings/cloud-secrets/cloud-secret-repos' -import { - isCloudAgentReady, - type CloudAgentReadiness, - type CloudOfferableDesktopKey -} from './cloud-agent-readiness' -import { - CloudAgentSetupView, - cloudAgentReadinessSummary, - cloudAgentSavedSummary, - type CloudAgentSetupSaved, - type CloudAgentSetupViewProps -} from './CloudAgentSetupView' -import { useCloudAgentSetup } from './use-cloud-agent-setup' - -export type VmBuildCloudAgentStepModel = { - readiness: CloudAgentReadiness - canShare: boolean - desktopKeys?: readonly CloudOfferableDesktopKey[] -} - -export type VmBuildCloudAgentStepMode = - | { kind: 'offer' } - | { kind: 'keys' } - | { kind: 'signIn' } - | { kind: 'saved'; saved: CloudAgentSetupSaved } - | { kind: 'skipped' } - -export type VmBuildCloudAgentStepActions = { - onSave: CloudAgentSetupViewProps['onSave'] - onSaveDesktopKey?: CloudAgentSetupViewProps['onSaveDesktopKey'] - /** The step is done (saved, signing in, or skipped); remember that it ran. */ - onDone: () => void - onSignIn: () => void - onCancelSignIn: () => void - onLater: () => void -} - -function Row({ - icon, - title, - detail, - actions -}: { - icon: React.ReactNode - title: React.ReactNode - detail: string - actions?: React.ReactNode -}): React.JSX.Element { - return ( -
- {icon} -
- {title} - {detail} -
- {actions ?
{actions}
: null} -
- ) -} - -const OFFER: VmBuildCloudAgentStepMode = { kind: 'offer' } -const KEY_ICON = -const DONE_ICON = - -/** - * One checklist row, never a gate: "Agents ready" when access is already covered, otherwise an - * optional "Add an agent" with in-VM sign-in first and keys one click away. - */ -export function VmBuildCloudAgentStepView({ - model, - actions, - handedOff = false, - initialMode = OFFER -}: { - model: VmBuildCloudAgentStepModel - actions: VmBuildCloudAgentStepActions - /** The sandbox reported in and the checklist's own sign-in row took over. */ - handedOff?: boolean - /** Fixtures only. */ - initialMode?: VmBuildCloudAgentStepMode -}): React.JSX.Element | null { - const t = useTranslate() - const [mode, setMode] = useState(initialMode) - const ready = isCloudAgentReady(model.readiness) - // The button that opened the key form: "Use a key", or "Change" when agents were already ready. - const offerRef = useRef(null) - const signInRef = useRef(null) - const rowRef = useRef(null) - // A handed-off row stays while it holds focus, so focus is never dropped on under the user. - const [focusInside, setFocusInside] = useState(false) - // Every swap unmounts the button that had focus; move focus to the new row (or its action) and - // announce the change, so keyboard and screen-reader users are not dropped on . - const [announcement, setAnnouncement] = useState('') - const go = ( - next: VmBuildCloudAgentStepMode, - focus: 'row' | 'offer' | 'signIn' | 'none', - say = '' - ): void => { - setMode(next) - setAnnouncement(say) - requestAnimationFrame(() => { - const target = - focus === 'row' - ? rowRef.current - : focus === 'offer' - ? (offerRef.current ?? rowRef.current) - : focus === 'signIn' - ? (signInRef.current ?? rowRef.current) - : null - target?.focus({ preventScroll: true }) - }) - } - - if (handedOff && !focusInside) { - return null - } - - const signIn = (): void => { - actions.onSignIn() - actions.onDone() - go( - { kind: 'signIn' }, - 'row', - t('cloudAgentSetup.signInQueued', 'Agent sign-in will open when the sandbox is ready') - ) - } - - let body: React.ReactNode - if (mode.kind === 'skipped') { - body = ( - - ) - } else if (mode.kind === 'saved') { - body = ( - - ) - } else if (mode.kind === 'signIn') { - body = ( - { - actions.onCancelSignIn() - go(OFFER, 'signIn', t('cloudAgentSetup.signInCancelled', 'Sign-in cancelled')) - }} - > - {t('cloudAgentSetup.skipSignIn', 'Don’t sign in')} - - ) - } - /> - ) - } else if (ready && mode.kind === 'offer') { - body = ( - go({ kind: 'keys' }, 'none')} - > - {t('cloudAgentSetup.change', 'Change')} - - } - /> - ) - } else { - body = ( - <> - - {t('cloudAgentSetup.title', 'Add an agent')} - - {' · '} - {t('vmBuildAgentSignIn.optional', 'optional')} - - - } - detail={t('cloudAgentSetup.subtitleBuild', 'Give your agents access in Orca Cloud.')} - actions={ - mode.kind === 'offer' ? ( - <> - - - - - ) : null - } - /> - {mode.kind === 'keys' ? ( -
- { - actions.onDone() - go({ kind: 'saved', saved }, 'row', cloudAgentSavedSummary(saved, t)) - }} - onCancel={() => go(OFFER, 'offer')} - onSignIn={signIn} - /> -
- ) : null} - - ) - } - - const state = - ready && mode.kind === 'offer' ? 'ready' : mode.kind === 'signIn' ? 'sign-in' : mode.kind - return ( -
  • setFocusInside(true)} - onBlur={(event) => { - // Switching to another app blurs too; focus comes back here, so the row must stay. - if (document.hasFocus() && !event.currentTarget.contains(event.relatedTarget)) { - setFocusInside(false) - } - }} - > - {/* One status region for every state, so a swap never takes the announcement with it. */} - - {announcement} - - {body} -
  • - ) -} - -/** Starts the in-VM sign-in once the VM has reported which agents are signed out. */ -function useSignInWhenReady( - creationId: string, - environmentId: string | null, - requested: boolean -): boolean { - const report = useSyncExternalStore(subscribeHostAgentSignInReports, () => - environmentId ? readHostAgentSignInReport(environmentId) : null - ) - const hostLabel = useAppStore( - (s) => s.runtimeEnvironments.find((environment) => environment.id === environmentId)?.name - ) - const started = useRef(false) - const states = report - ? HOST_AGENT_SIGN_IN_AGENTS.map( - (agent) => report.agents.find((entry) => entry.agent === agent)?.state ?? 'unknown' - ) - : null - // Not latched while any agent is still being checked, so a later report can start it. - const settled = states !== null && !states.includes('unknown') - - useEffect(() => { - if (!requested || started.current || !environmentId || !report || !settled) { - return - } - started.current = true - const signedOut = HOST_AGENT_SIGN_IN_AGENTS.filter( - (agent) => report.agents.find((entry) => entry.agent === agent)?.state === 'signedOut' - ) - if (signedOut.length > 0) { - void startVmBuildAgentSignIn(creationId, environmentId, hostLabel ?? environmentId, signedOut) - } - }, [requested, environmentId, report, settled, creationId, hostLabel]) - - // Once the VM has answered, the checklist's own sign-in row takes over. - return requested && settled -} - -/** - * "Add an agent" before the first Orca Cloud workspace. Runs beside provisioning, never in front of it, - * and only once: when agents are already covered it is a one-line confirmation instead. - */ -export function VmBuildCloudAgentStep({ - creationId, - entry -}: { - creationId: string - entry: PendingWorktreeCreation -}): React.JSX.Element | null { - const done = useAppStore((s) => s.cloudAgentSetupDone) - const markDone = useAppStore((s) => s.markCloudAgentSetupDone) - // Decided once per build, so finishing the step mid-build does not yank its confirmation away. - const [eligible] = useState(() => !done) - const [signInRequested, setSignInRequested] = useState(false) - const isCloud = entry.request.ephemeralVmRecipe?.recipeId === ORCA_CLOUD_RECIPE_ID - const repoKey = useAppStore((s) => { - const repo = s.repos.find((candidate) => candidate.id === entry.request.repoId) - return repo ? cloudSecretRepoKey(repo) : null - }) - const environmentId = entry.vmEnvironmentId ?? null - const { model, save, saveDesktopKey } = useCloudAgentSetup({ - repo: repoKey, - runtimeEnvironmentId: environmentId, - enabled: isCloud && eligible - }) - const handedToSignInRow = useSignInWhenReady(creationId, environmentId, signInRequested) - const alreadyReady = model.status === 'ready' && isCloudAgentReady(model.readiness) - - useEffect(() => { - if (alreadyReady) { - markDone() - } - }, [alreadyReady, markDone]) - - if (!isCloud || !eligible || model.status === 'loading' || entry.status === 'error') { - return null - } - return ( - setSignInRequested(true), - onCancelSignIn: () => setSignInRequested(false), - onLater: markDone - }} - /> - ) -} diff --git a/src/renderer/src/components/cloud-agent-setup/cloud-agent-setup-focus.test.tsx b/src/renderer/src/components/cloud-agent-setup/cloud-agent-setup-focus.test.tsx index cb165e2e2b5..f30830d8049 100644 --- a/src/renderer/src/components/cloud-agent-setup/cloud-agent-setup-focus.test.tsx +++ b/src/renderer/src/components/cloud-agent-setup/cloud-agent-setup-focus.test.tsx @@ -1,8 +1,7 @@ // @vitest-environment happy-dom -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' import { CloudAgentSetupView } from './CloudAgentSetupView' -import { VmBuildCloudAgentStepView } from './VmBuildCloudAgentStep' const NONE = { claude: null, codex: null } @@ -13,70 +12,6 @@ function keyInput(): HTMLInputElement { } return input } -const actions = { - onSave: async () => null, - onDone: vi.fn(), - onSignIn: vi.fn(), - onCancelSignIn: vi.fn(), - onLater: vi.fn() -} - -function step(props: Partial> = {}) { - return ( -
      - -
    1. - -
    2. -
    - ) -} - -describe('VmBuildCloudAgentStepView', () => { - afterEach(cleanup) - - it('returns focus to Change after Cancel when agents were already ready', async () => { - render(step({ model: { readiness: { claude: 'team', codex: 'team' }, canShare: false } })) - fireEvent.click(screen.getByRole('button', { name: 'Change' })) - fireEvent.click(screen.getByRole('button', { name: 'Cancel' })) - await waitFor(() => - expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Change' })) - ) - }) - - it('keeps one status region across states so announcements survive the swap', () => { - render(step()) - const region = screen.getByRole('status') - fireEvent.click(screen.getByRole('button', { name: 'Later' })) - expect(screen.getByRole('status')).toBe(region) - expect(region.textContent).toBe('Agent setup skipped') - }) - - it('keeps a handed-off row while it holds focus, then lets it go', async () => { - const { rerender } = render(step({ initialMode: { kind: 'signIn' } })) - const row = document.querySelector('[data-vm-build-cloud-agent]') - row?.focus() - rerender(step({ initialMode: { kind: 'signIn' }, handedOff: true })) - expect(document.querySelector('[data-vm-build-cloud-agent]')).toBe(row) - expect(document.activeElement).toBe(row) - const next = screen.getByRole('button', { name: 'next row' }) - if (!row) { - throw new Error('no row') - } - fireEvent.blur(row, { relatedTarget: next }) - await waitFor(() => expect(document.querySelector('[data-vm-build-cloud-agent]')).toBeNull()) - }) - - it('renders nothing once handed off when focus is elsewhere', () => { - render(step({ initialMode: { kind: 'signIn' }, handedOff: true })) - expect(document.querySelector('[data-vm-build-cloud-agent]')).toBeNull() - }) -}) - describe('CloudAgentSetupView Escape', () => { afterEach(cleanup) diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheet.fixture.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheet.fixture.tsx index 85d1dc516f5..18bf721473d 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheet.fixture.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheet.fixture.tsx @@ -378,3 +378,6 @@ 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 4481ca6cb25..e91800493c8 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx @@ -19,7 +19,7 @@ import { VmBuildStepRow } from './VmBuildStepRow' import { firstBuildLogErrorLine, VmBuildLog } from './VmBuildLog' import { VmBuildFailureCard } from './VmBuildFailureCard' import { VmBuildAgentSignInRow } from './VmBuildAgentSignInRow' -import { VmBuildCloudAgentStep } from '../cloud-agent-setup/VmBuildCloudAgentStep' +import { VmBuildCloudAgentsRow } from './cloud-agents-row/VmBuildCloudAgentsRow' import { VmBuildSecretsRow } from '../cloud-secrets-ask/VmBuildSecretsRow' import { OrcaCloudQueuedPrompt } from '@/components/orca-cloud/OrcaCloudQueuedPrompt' import { @@ -93,7 +93,7 @@ export function VmBuildSheet({ onReturnToComposer, onEditRecipe, agentSignInRow, - cloudAgentStep, + cloudAgentsRow, secretsRow, stepTimings }: { @@ -111,8 +111,8 @@ 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 "Add an agent" step (null for none) in place of the live one. */ - cloudAgentStep?: 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. */ @@ -246,13 +246,17 @@ export function VmBuildSheet({ t={t} /> ))} - {cloudAgentStep !== undefined ? ( - cloudAgentStep - ) : ( - - )} + {/* 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} {agentSignInRow ?? - (entry.vmEnvironmentId ? ( + (!cloud && entry.vmEnvironmentId ? ( + 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 new file mode 100644 index 00000000000..9542b69d172 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRow.tsx @@ -0,0 +1,197 @@ +// 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, useState } from 'react' +import { toast } from 'sonner' +import { useAppStore } from '@/store' +import { useTranslate } from '@/i18n/use-translate' +import { + reloadOrcaCloudAgentAccounts, + 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' +import { useInlineSetupQueue } from './use-inline-setup-queue' + +function openSettings(pane: 'agent-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 { queue, run, cancel, clear } = useInlineSetupQueue(accounts.setups) + const model = buildAgentsRow({ accounts, desktopKeys, queue }) + // 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, queued until the sandbox answers (R3). + const [queuedAgent, setQueuedAgent] = useState(null) + const hostLabel = useAppStore( + (s) => s.runtimeEnvironments.find((environment) => environment.id === environmentId)?.name + ) + useEffect(() => { + if (queuedAgent && environmentId) { + setQueuedAgent(null) + void startVmBuildAgentSignIn(creationId, environmentId, hostLabel ?? environmentId, [ + queuedAgent + ]) + } + }, [queuedAgent, environmentId, creationId, hostLabel]) + 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('agent-accounts', 'orca-cloud')} + onUseKey={() => openSettings('cloud-secrets')} + /> + ) + return ( + <> + + run( + model.kind === 'failed' && queue[0] === model.agent + ? queue + : buildAgentsToSetUp(model) + ), + cancel, + 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) => { + clear() + void api?.acknowledge({ agent }) + }, + retryLoad: () => void reloadOrcaCloudAgentAccounts(), + manage: () => openSettings('agent-accounts', 'orca-cloud'), + saveDesktopKey: saveKey, + signInHere: (agent) => setQueuedAgent(agent), + cancelSignInHere: () => setQueuedAgent(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 new file mode 100644 index 00000000000..4a7fad779ed --- /dev/null +++ b/src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRowView.tsx @@ -0,0 +1,371 @@ +// 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/cloud-agents-row/build-agents-row-copy.ts b/src/renderer/src/components/worktree-creation/cloud-agents-row/build-agents-row-copy.ts new file mode 100644 index 00000000000..1c753e78041 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/cloud-agents-row/build-agents-row-copy.ts @@ -0,0 +1,174 @@ +// Words for the cloud build sheet's Agents row (spec §5b, redesign §5). Catalog names only. +import type { Translate } from '@/i18n/use-translate' +import { formatAgentTypeLabel } from '../../../../../shared/agent-status/presentation/agent-type-label' +import type { + BuildAgentVia, + BuildAgentsRowModel +} from '@/lib/orca-cloud/orca-cloud-build-agents-row' +import type { OrcaCloudAccountAgent } from '../../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' +import { + agentName, + keySourceLabel, + productName, + setupFailureCopy +} from '../../settings/agent-accounts/orca-cloud-accounts-copy' + +/** "Claude and Codex" in the user's language (Intl.ListFormat, never concatenation). */ +export function agentList(agents: readonly OrcaCloudAccountAgent[], t: Translate): string { + const names = agents.map((agent) => agentName(agent, t)) + try { + return new Intl.ListFormat(undefined, { style: 'long', type: 'conjunction' }).format(names) + } catch { + return names.join(', ') + } +} + +function viaLabel(via: BuildAgentVia, t: Translate): string { + return via === 'account' + ? t('vmBuildAgents.fromAccount', 'from your Orca account') + : keySourceLabel(via, t) +} + +/** + * R1: "Claude and Codex · from your Orca account". Mixed sources read per source group in one line: + * "Claude · from your Orca account · Codex · team key". + */ +export function readyLine( + model: Extract, + t: Translate +): string { + const groups = new Map() + for (const entry of model.covered) { + groups.set(entry.via, [...(groups.get(entry.via) ?? []), entry.agent]) + } + const parts = [...groups].map(([via, agents]) => + t('vmBuildAgents.group', '{{agents}} · {{source}}', { + agents: agentList(agents, t), + source: viaLabel(via, t) + }) + ) + if (model.label) { + parts.push(model.label) + } + return parts.join(t('vmBuildAgents.separator', ' · ')) +} + +export type BuildAgentsRowText = { title: string; tag?: string; detail: string } + +function setupText( + model: Extract, + t: Translate +): BuildAgentsRowText { + const agent = agentName(model.agent, t) + const tag = + model.of > 1 + ? t('vmBuildAgents.stepOf', '{{step}} of {{of}}', { step: model.step, of: model.of }) + : undefined + const title = t('vmBuildAgents.settingUp', 'Setting up {{agent}}', { agent }) + switch (model.setup.phase) { + case 'browser': + return { + title, + tag, + detail: t('vmBuildAgents.finishInBrowser', 'Finish in your browser') + } + case 'preparing': + return { + title, + tag, + detail: t('vmBuildAgents.preparing', 'Getting {{product}} sign-in ready…', { + product: productName(model.agent, t) + }) + } + case 'device': + return { + title, + tag, + detail: t('vmBuildAgents.deviceGuard', 'Only continue if you started this sign-in in Orca.') + } + case 'paste': + return { + title: t('vmBuildAgents.pasteTitle', 'Paste a {{agent}} setup token', { agent }), + tag, + detail: t('vmBuildAgents.pasteDetail', 'Paste it in Settings → Agent accounts.') + } + case 'saving': + return { + title: t('vmBuildAgents.saving', 'Saving to your Orca account…'), + tag, + detail: t('vmBuildAgents.savingDetail', 'Every cloud workspace will use it.') + } + } +} + +/** Line 1 (title + tag) and line 2 for every state but loading, ready and the device code. */ +export function buildAgentsRowText( + model: Exclude, + t: Translate +): BuildAgentsRowText { + switch (model.kind) { + case 'offer': + return { + title: t('vmBuildAgents.signIn', 'Agent sign-in'), + tag: t('vmBuildAgents.optionalOnce', 'optional · one time'), + detail: t( + 'vmBuildAgents.offerDetail', + 'Sign in to {{agents}} once. Every cloud workspace uses it.', + { agents: agentList(model.agents, t) } + ) + } + case 'setup': + return setupText(model, t) + case 'failed': + return { + title: setupFailureCopy(model.agent, model.error, t).title, + detail: t('vmBuildAgents.stillOpens', 'The workspace still opens.') + } + case 'expired': + return { + title: t('vmBuildAgents.expired', 'Your {{agent}} sign-in for Orca Cloud expired', { + agent: agentName(model.agent, t) + }), + detail: t( + 'vmBuildAgents.expiredDetail', + 'Sign in again once. Every cloud workspace picks it up.' + ) + } + case 'killSwitch': + return { + title: t('vmBuildAgents.agentSignIn', '{{agent}} sign-in', { + agent: agentName(model.agent, t) + }), + tag: t('vmBuildAgents.paused', 'Orca account sign-in is paused'), + detail: t('vmBuildAgents.pausedDetail', 'This sign-in stays with this workspace') + } + case 'desktopKey': + return { + title: t( + 'cloudAgentSetup.desktopKeys.row', + '{{agent}}: your API key ••••{{hint}} is only on this computer', + { agent: formatAgentTypeLabel(model.key.agent), hint: model.key.hint } + ), + detail: t( + 'cloudAgentSetup.desktopKeys.detail', + 'Save it to your Orca account to use it in cloud workspaces. It stays outside the sandbox.' + ) + } + case 'error': + return { + title: t('vmBuildAgents.error', 'Couldn’t check agent sign-in'), + detail: t( + 'vmBuildAgents.errorDetail', + 'The workspace still opens. Agents can sign in later.' + ) + } + } +} + +export function deviceHost(url: string): string { + try { + return new URL(url).hostname + } catch { + return url + } +} diff --git a/src/renderer/src/components/worktree-creation/cloud-agents-row/use-inline-setup-queue.ts b/src/renderer/src/components/worktree-creation/cloud-agents-row/use-inline-setup-queue.ts new file mode 100644 index 00000000000..3abbe01e4a7 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/cloud-agents-row/use-inline-setup-queue.ts @@ -0,0 +1,77 @@ +// R2's Set up: runs S0's one-time setup for each agent in turn, inside the build sheet's row. +// Main owns each setup; this only starts the next agent once the previous one is stored. +import { useCallback, useEffect, useRef, useState } from 'react' +import type { + OrcaCloudAccountAgent, + OrcaCloudAgentSetups +} from '../../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' + +export function useInlineSetupQueue(setups: OrcaCloudAgentSetups): { + queue: readonly OrcaCloudAccountAgent[] + run: (agents: readonly OrcaCloudAccountAgent[]) => void + cancel: (agent: OrcaCloudAccountAgent) => void + /** Stops the queue without touching main (a dismissed failure). */ + clear: () => void +} { + const [queue, setQueue] = useState([]) + const [cursor, setCursor] = useState(0) + // Set once the current agent's setup has left idle, so idle afterwards means it finished. + const started = useRef(false) + + const start = useCallback((agent: OrcaCloudAccountAgent) => { + started.current = false + void window.api.orcaCloudAgents?.start({ agent }) + }, []) + + const run = useCallback( + (agents: readonly OrcaCloudAccountAgent[]) => { + const [first] = agents + if (!first) { + return + } + setQueue(agents) + setCursor(0) + start(first) + }, + [start] + ) + + const cancel = useCallback((agent: OrcaCloudAccountAgent) => { + setQueue([]) + void window.api.orcaCloudAgents?.cancel({ agent }) + }, []) + + const clear = useCallback(() => setQueue([]), []) + + const current = queue[cursor] + const phase = current ? setups[current].phase : 'idle' + useEffect(() => { + if (!current) { + return + } + if (phase === 'failed') { + // Try again restarts from this agent; the ones after it wait. + if (cursor > 0) { + setQueue(queue.slice(cursor)) + setCursor(0) + } + return + } + if (phase !== 'idle') { + started.current = true + return + } + if (!started.current) { + return + } + const next = queue[cursor + 1] + setCursor(cursor + 1) + if (next) { + start(next) + } else { + setQueue([]) + } + }, [current, phase, queue, cursor, start]) + + return { queue, run, cancel, clear } +} 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 new file mode 100644 index 00000000000..334e4bbfc8e --- /dev/null +++ b/src/renderer/src/components/worktree-creation/vm-build-sheet-agents-fixtures.tsx @@ -0,0 +1,232 @@ +// 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' }) +export const agentsKillSwitchQueued = agents( + { kind: 'killSwitch', agent: 'claude' }, + { 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 2584f6ec8f9..1017ce7fa08 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 @@ -56,7 +56,7 @@ export function sheet( error: string | null, now: number, agentSignInRow?: React.ReactNode, - options: { cloudAgentStep?: React.ReactNode; secretsRow?: React.ReactNode } = {} + options: { cloudAgentsRow?: React.ReactNode; secretsRow?: React.ReactNode } = {} ) { return (
    @@ -73,7 +73,7 @@ export function sheet( onEditRecipe={() => {}} agentSignInRow={agentSignInRow} stepTimings={FIXTURE_STEP_TIMINGS} - cloudAgentStep={options.cloudAgentStep ?? null} + cloudAgentsRow={options.cloudAgentsRow ?? null} secretsRow={options.secretsRow ?? null} />
    diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index bb2bf16b956..81d94d749a7 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -27701,5 +27701,59 @@ "personal": "your API key" }, "copyAndOpen": "Copy code and open" + }, + "vmBuildAgents": { + "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", + "signInAgain": "Sign in again", + "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", + "fromAccount": "from your Orca account", + "group": "{{agents}} · {{source}}", + "separator": " · ", + "stepOf": "{{step}} of {{of}}", + "settingUp": "Setting up {{agent}}", + "finishInBrowser": "Finish in your browser", + "preparing": "Getting {{product}} sign-in ready…", + "deviceGuard": "Only continue if you started this sign-in in Orca.", + "pasteTitle": "Paste a {{agent}} setup token", + "pasteDetail": "Paste it in Settings → Agent accounts.", + "saving": "Saving to your Orca account…", + "savingDetail": "Every cloud workspace will use it.", + "signIn": "Agent sign-in", + "optionalOnce": "optional · one time", + "offerDetail": "Sign in to {{agents}} once. Every cloud workspace uses it.", + "stillOpens": "The workspace still opens.", + "expired": "Your {{agent}} sign-in for Orca Cloud expired", + "expiredDetail": "Sign in again once. Every cloud workspace picks it up.", + "agentSignIn": "{{agent}} sign-in", + "paused": "Orca account sign-in is paused", + "pausedDetail": "This sign-in stays with this workspace", + "error": "Couldn’t check agent sign-in", + "errorDetail": "The workspace still opens. Agents can sign in later." } } diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.test.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.test.ts new file mode 100644 index 00000000000..7a79e253c5b --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.test.ts @@ -0,0 +1,128 @@ +import { describe, expect, it } from 'vitest' +import { + IDLE_ORCA_CLOUD_AGENT_SETUPS, + type OrcaCloudAgentsStatus +} from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' +import { + buildAgentsRow, + buildAgentsRowDensity, + buildAgentsToSetUp +} from './orca-cloud-build-agents-row' +import type { OrcaCloudAgentAccountsState } from './orca-cloud-agent-accounts-store' + +const NONE: OrcaCloudAgentsStatus = { + credentials: { + claude: { state: 'none' }, + codex: { state: 'none' }, + providerEnabled: { claude: true, codex: true } + }, + sources: { defaults: {}, coveredByKey: { claude: false, codex: false } } +} + +function accounts( + status: OrcaCloudAgentsStatus, + patch: Partial = {} +): OrcaCloudAgentAccountsState { + return { + load: { kind: 'ready', status }, + setups: IDLE_ORCA_CLOUD_AGENT_SETUPS, + keyKinds: { claude: null, codex: null }, + ...patch + } +} + +function withClaude( + state: OrcaCloudAgentsStatus['credentials']['claude']['state'], + patch: Partial = {} +): OrcaCloudAgentsStatus { + return { + ...NONE, + credentials: { ...NONE.credentials, claude: { state, label: 'me@x.dev' }, ...patch } + } +} + +const row = (a: OrcaCloudAgentAccountsState) => + buildAgentsRow({ accounts: a, desktopKeys: [], queue: [] }) + +describe('buildAgentsRow', () => { + it('offers the one-time setup when nothing covers any agent (R2), two lines at mount', () => { + const model = row(accounts(NONE)) + expect(model).toEqual({ kind: 'offer', agents: ['claude', 'codex'] }) + expect(buildAgentsRowDensity(model)).toBe('twoLine') + expect(buildAgentsToSetUp(model)).toEqual(['claude', 'codex']) + }) + + it('is a ready line naming each covered agent, without prompting for the rest', () => { + const status: OrcaCloudAgentsStatus = { + ...withClaude('active'), + sources: { defaults: {}, coveredByKey: { claude: false, codex: true } } + } + const model = row(accounts(status, { keyKinds: { claude: null, codex: 'team' } })) + expect(model).toEqual({ + kind: 'ready', + covered: [ + { agent: 'claude', via: 'account' }, + { agent: 'codex', via: 'team' } + ], + label: null, + expiring: null + }) + expect(buildAgentsRowDensity(model)).toBe('line') + }) + + it('names the account when it covers every agent, and offers Renew when it is expiring', () => { + const model = row(accounts(withClaude('expiring'))) + expect(model).toMatchObject({ kind: 'ready', label: 'me@x.dev', expiring: 'claude' }) + expect(buildAgentsToSetUp(model)).toEqual(['claude']) + }) + + it('puts the kill switch first, then an expiry, both only when no key covers the agent', () => { + const paused = withClaude('active', { providerEnabled: { claude: false, codex: true } }) + expect(row(accounts(paused))).toEqual({ kind: 'killSwitch', agent: 'claude' }) + expect(row(accounts(withClaude('revoked')))).toEqual({ kind: 'expired', agent: 'claude' }) + const keyed = { + ...paused, + sources: { defaults: {}, coveredByKey: { claude: true, codex: false } } + } + expect(row(accounts(keyed, { keyKinds: { claude: 'personal', codex: null } }))).toMatchObject({ + kind: 'ready', + covered: [{ agent: 'claude', via: 'personal' }] + }) + }) + + it('shows a running or failed setup over everything else, with its place in the queue', () => { + const running = accounts(NONE, { + setups: { claude: { phase: 'idle' }, codex: { phase: 'preparing', startedAt: 1 } } + }) + expect( + buildAgentsRow({ accounts: running, desktopKeys: [], queue: ['claude', 'codex'] }) + ).toMatchObject({ + kind: 'setup', + agent: 'codex', + step: 2, + of: 2 + }) + const failed = accounts(NONE, { + setups: { claude: { phase: 'failed', error: 'denied' }, codex: { phase: 'idle' } } + }) + expect(row(failed)).toEqual({ kind: 'failed', agent: 'claude', error: 'denied' }) + }) + + it('offers saving a key only on this computer before the setup (S1-c)', () => { + const key = { id: 'k1', agent: 'claude', envName: 'ANTHROPIC_API_KEY', hint: 'x4Qa' } as const + expect(buildAgentsRow({ accounts: accounts(NONE), desktopKeys: [key], queue: [] })).toEqual({ + kind: 'desktopKey', + key + }) + }) + + it('loads, fails and hides from the account read alone, never the sandbox', () => { + const base = accounts(NONE) + expect(row({ ...base, load: { kind: 'loading' } })).toEqual({ kind: 'loading' }) + expect(row({ ...base, load: { kind: 'failed', error: 'unavailable' } })).toEqual({ + kind: 'error' + }) + expect(row({ ...base, load: { kind: 'unavailable' } })).toEqual({ kind: 'hidden' }) + expect(buildAgentsRowDensity({ kind: 'loading' })).toBe('twoLine') + }) +}) diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.ts new file mode 100644 index 00000000000..320e773ebe5 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.ts @@ -0,0 +1,170 @@ +// The cloud build sheet's Agents row (agent-accounts spec §5b S1, redesign §5 R1–R12): how each +// agent will authenticate in this workspace, known at mount from the Orca account, never from the +// sandbox. Pure: the component decides the row's height once and renders whatever this returns. +import { + ORCA_CLOUD_ACCOUNT_AGENTS, + type AgentKeyKind, + type OrcaCloudAccountAgent, + type OrcaCloudAgentSetup, + type OrcaCloudAgentSetupFailure +} from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' +import type { CloudOfferableDesktopKey } from '@/components/cloud-agent-setup/cloud-agent-readiness' +import { + orcaCloudAgentCoverage, + type OrcaCloudAgentCoverage +} from './orca-cloud-agent-accounts-model' +import type { OrcaCloudAgentAccountsState } from './orca-cloud-agent-accounts-store' + +export type BuildAgentVia = 'account' | AgentKeyKind + +export type BuildAgentsRunningSetup = Exclude< + OrcaCloudAgentSetup, + { phase: 'idle' | 'saved' | 'failed' } +> + +export type BuildAgentsRowModel = + | { kind: 'hidden' } + | { kind: 'loading' } + /** R1/R1c/Q2: every covered agent and where its credential comes from. */ + | { + kind: 'ready' + covered: readonly { agent: OrcaCloudAccountAgent; via: BuildAgentVia }[] + /** The Orca-account label (the vendor email), when one account covers every agent. */ + label: string | null + /** An account credential within its renewal window: a quiet Renew. */ + expiring: OrcaCloudAccountAgent | null + } + /** R2: nothing covers any agent yet; Set up runs S0 inline, once ever. */ + | { kind: 'offer'; agents: readonly OrcaCloudAccountAgent[] } + /** R4–R6: the one-time setup is running on this computer. `step` is 1-based. */ + | { + kind: 'setup' + agent: OrcaCloudAccountAgent + setup: BuildAgentsRunningSetup + step: number + of: number + } + /** R9: the setup stopped; the workspace still opens. */ + | { kind: 'failed'; agent: OrcaCloudAccountAgent; error: OrcaCloudAgentSetupFailure } + /** R10 / R1b: the account credential expired or was revoked and no key covers the agent. */ + | { kind: 'expired'; agent: OrcaCloudAccountAgent } + /** R12 (§5c): the provider's Orca-account path is off and no key covers the agent. */ + | { kind: 'killSwitch'; agent: OrcaCloudAccountAgent } + /** S1-c (A5/A6): a key only in this computer's vault; it never reaches the sandbox unasked. */ + | { kind: 'desktopKey'; key: CloudOfferableDesktopKey } + /** Couldn't read the Orca account; the workspace still opens. */ + | { kind: 'error' } + +function covered(coverage: OrcaCloudAgentCoverage): BuildAgentVia | null { + switch (coverage.kind) { + case 'account': + return 'account' + case 'key': + return coverage.keyKind + case 'notSetUp': + case 'expired': + case 'killSwitch': + return null + } +} + +export function buildAgentsRow(args: { + accounts: Pick + /** This computer's keys no Cloud secret covers (A6); empty until read. */ + desktopKeys: readonly CloudOfferableDesktopKey[] + /** The agents this row's Set up queued, in order; drives "1 of 2". */ + queue: readonly OrcaCloudAccountAgent[] +}): BuildAgentsRowModel { + const { load, setups, keyKinds } = args.accounts + for (const agent of ORCA_CLOUD_ACCOUNT_AGENTS) { + const setup = setups[agent] + if (setup.phase === 'failed') { + return { kind: 'failed', agent, error: setup.error } + } + if (setup.phase !== 'idle' && setup.phase !== 'saved') { + const index = args.queue.indexOf(agent) + return { + kind: 'setup', + agent, + setup, + step: index === -1 ? 1 : index + 1, + of: Math.max(args.queue.length, 1) + } + } + } + switch (load.kind) { + case 'unavailable': + return { kind: 'hidden' } + case 'loading': + return { kind: 'loading' } + case 'failed': + return { kind: 'error' } + case 'ready': + break + } + const status = load.status + const coverage = ORCA_CLOUD_ACCOUNT_AGENTS.map((agent) => ({ + agent, + coverage: orcaCloudAgentCoverage(agent, status, keyKinds[agent]) + })) + const paused = coverage.find((entry) => entry.coverage.kind === 'killSwitch') + if (paused) { + return { kind: 'killSwitch', agent: paused.agent } + } + const expired = coverage.find((entry) => entry.coverage.kind === 'expired') + if (expired) { + return { kind: 'expired', agent: expired.agent } + } + const ready = coverage.flatMap(({ agent, coverage: c }) => { + const via = covered(c) + return via ? [{ agent, via }] : [] + }) + if (ready.length === 0) { + const key = args.desktopKeys.find((candidate) => + ORCA_CLOUD_ACCOUNT_AGENTS.some((agent) => agent === candidate.agent) + ) + return key + ? { kind: 'desktopKey', key } + : { kind: 'offer', agents: coverage.map((entry) => entry.agent) } + } + const viaAccount = ready.filter((entry) => entry.via === 'account') + const labels = new Set( + viaAccount.map((entry) => status.credentials[entry.agent].label?.trim() || null) + ) + const [onlyLabel] = labels + return { + kind: 'ready', + covered: ready, + label: viaAccount.length === ready.length && labels.size === 1 ? (onlyLabel ?? null) : null, + expiring: + viaAccount.find((entry) => status.credentials[entry.agent].state === 'expiring')?.agent ?? + null + } +} + +/** The row's height class, decided once at mount (redesign §5): a line only when ready then. */ +export type BuildAgentsRowDensity = 'line' | 'twoLine' + +export function buildAgentsRowDensity(model: BuildAgentsRowModel): BuildAgentsRowDensity { + return model.kind === 'ready' ? 'line' : 'twoLine' +} + +/** The agents R2's Set up runs, in order: each one that nothing covers yet. */ +export function buildAgentsToSetUp(model: BuildAgentsRowModel): readonly OrcaCloudAccountAgent[] { + switch (model.kind) { + case 'offer': + return model.agents + case 'expired': + case 'failed': + return [model.agent] + case 'ready': + return model.expiring ? [model.expiring] : [] + case 'hidden': + case 'loading': + case 'setup': + case 'killSwitch': + case 'desktopKey': + case 'error': + return [] + } +} diff --git a/tests/component-fixtures/vm-build-cloud-agents-row.spec.ts b/tests/component-fixtures/vm-build-cloud-agents-row.spec.ts new file mode 100644 index 00000000000..ba391fc1d7b --- /dev/null +++ b/tests/component-fixtures/vm-build-cloud-agents-row.spec.ts @@ -0,0 +1,124 @@ +import { expect, test, type Page } from '@playwright/test' + +// AC-3 (agent-accounts spec §5b, redesign §5): the cloud build sheet's Agents row keeps the height +// it mounted with through every later state, so nothing below it moves. Measured layout shift is 0. + +type Model = Record & { kind: string } + +const ACCOUNT: Model = { + kind: 'ready', + covered: [ + { agent: 'claude', via: 'account' }, + { agent: 'codex', via: 'account' } + ], + label: 'nw@stably.ai', + expiring: null +} +const BROWSER: Model = { + kind: 'setup', + agent: 'claude', + setup: { phase: 'browser', startedAt: 0, canReopen: true }, + step: 1, + of: 2 +} +const DEVICE: Model = { + kind: 'setup', + agent: 'codex', + setup: { + phase: 'device', + startedAt: 0, + userCode: 'K7QF-2M9D', + verificationUrl: 'https://auth.openai.com/codex/device', + expiresAt: 0 + }, + step: 2, + of: 2 +} + +// Every state the row can move to after mount, from either height class. +const LATER: readonly Model[] = [ + { kind: 'offer', agents: ['claude', 'codex'] }, + BROWSER, + DEVICE, + { kind: 'setup', agent: 'codex', setup: { phase: 'preparing', startedAt: 0 }, step: 2, of: 2 }, + { kind: 'setup', agent: 'claude', setup: { phase: 'saving' }, step: 1, of: 1 }, + { kind: 'failed', agent: 'claude', error: 'denied' }, + { kind: 'expired', agent: 'claude' }, + { kind: 'killSwitch', agent: 'claude' }, + { + kind: 'desktopKey', + key: { id: 'k1', agent: 'claude', envName: 'ANTHROPIC_API_KEY', hint: 'x4Qa' } + }, + { kind: 'error' }, + { ...ACCOUNT, expiring: 'claude' }, + ACCOUNT +] + +async function open(page: Page, id: string): Promise { + await page.goto(`/fixtures.html?id=worktree-creation/VmBuildSheet:${id}`) + await expect(page.locator('html')).toHaveAttribute('data-fixture-state', 'ready') + // Count every layout shift from here on, input or not. + await page.evaluate(() => { + document.documentElement.dataset.layoutShift = '0' + new PerformanceObserver((list) => { + for (const entry of list.getEntries()) { + const value = 'value' in entry && typeof entry.value === 'number' ? entry.value : 0 + const total = Number(document.documentElement.dataset.layoutShift) + value + document.documentElement.dataset.layoutShift = String(total) + } + }).observe({ type: 'layout-shift', buffered: false }) + }) +} + +async function geometry(page: Page) { + const row = await page.locator('[data-vm-build-cloud-agents-density]').boundingBox() + // By attribute: an open menu hides the rest of the page from the accessibility tree. + const logs = await page + .locator('[data-vm-build-sheet] button[aria-controls]:not([aria-haspopup])') + .boundingBox() + if (!row || !logs) { + throw new Error('Agents row or logs toggle has no bounds') + } + return { rowHeight: row.height, rowY: row.y, logsY: logs.y } +} + +async function step(page: Page, model: Model): Promise { + await page.evaluate((detail) => { + window.dispatchEvent(new CustomEvent('orca-fixture-agents', { detail })) + }, model) + await expect(page.locator('[data-vm-build-cloud-agents]')).toHaveAttribute( + 'data-vm-build-cloud-agents', + model.kind + ) + // Two frames: layout and any shift entry land before the next measure. + await page.evaluate( + () => + new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())) + ) + ) +} + +for (const [id, height] of [ + ['agentsSteppedFromLoading', 48], + ['agentsSteppedFromReady', 32] +] as const) { + test(`${id}: the row stays ${height}px and nothing below it moves`, async ({ page }) => { + await open(page, id) + const mounted = await geometry(page) + expect(mounted.rowHeight).toBe(height) + for (const model of LATER) { + await step(page, model) + expect(await geometry(page), `after ${model.kind}`).toEqual(mounted) + } + await expect(page.locator('html')).toHaveAttribute('data-layout-shift', '0') + }) +} + +test('the open ⋯ menu overlays the sheet instead of pushing it', async ({ page }) => { + await open(page, 'agentsSteppedFromReady') + const before = await geometry(page) + await page.getByRole('button', { name: 'Agent sign-in options' }).click() + await expect(page.getByRole('menuitem', { name: 'Manage agent accounts…' })).toBeVisible() + expect(await geometry(page)).toEqual(before) +}) From 5c09e047d13fca5575b857482defbdc3b6b03361 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 08:49:14 -0800 Subject: [PATCH 2/3] fix(cloud): NP-3 row: R2 setup queue lives in the accounts store (no state set in effects); kill-switch sign-in is per request; UI-locale list format; drop the removed build step's catalog keys --- .../VmBuildCloudAgentsRow.tsx | 53 +++++++------ .../cloud-agents-row/build-agents-row-copy.ts | 5 +- .../use-inline-setup-queue.ts | 77 ------------------- src/renderer/src/i18n/locales/en.json | 19 +---- .../orca-cloud-agent-accounts-store.ts | 59 +++++++++++++- .../orca-cloud-build-agents-row.test.ts | 13 ++-- .../orca-cloud/orca-cloud-build-agents-row.ts | 10 +-- 7 files changed, 104 insertions(+), 132 deletions(-) delete mode 100644 src/renderer/src/components/worktree-creation/cloud-agents-row/use-inline-setup-queue.ts 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 index 9542b69d172..c38850f0594 100644 --- a/src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRow.tsx +++ b/src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRow.tsx @@ -1,12 +1,14 @@ // 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, useState } from 'react' +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 { @@ -29,7 +31,6 @@ import { cloudSecretRepoKey } from '../../settings/cloud-secrets/cloud-secret-re import { VmBuildAgentSignInRow } from '../VmBuildAgentSignInRow' import { VmBuildCloudAgentsMenu, type WorkspaceSourcesLoad } from './VmBuildCloudAgentsMenu' import { VmBuildCloudAgentsRowView, type DesktopKeySave } from './VmBuildCloudAgentsRowView' -import { useInlineSetupQueue } from './use-inline-setup-queue' function openSettings(pane: 'agent-accounts' | 'cloud-secrets', sectionId?: string): void { const store = useAppStore.getState() @@ -58,8 +59,7 @@ export function VmBuildCloudAgentsRow({ runtimeEnvironmentId: environmentId }) const desktopKeys = keysModel.status === 'ready' ? keysModel.desktopKeys : [] - const { queue, run, cancel, clear } = useInlineSetupQueue(accounts.setups) - const model = buildAgentsRow({ accounts, desktopKeys, queue }) + const model = buildAgentsRow({ accounts, desktopKeys }) // Decided on the first render and never re-derived (redesign §5, AC-3). const [density] = useState(() => buildAgentsRowDensity(model)) @@ -78,19 +78,27 @@ export function VmBuildCloudAgentsRow({ }) }, [model, saveDesktopKey]) - // §5c: a per-workspace sign-in, queued until the sandbox answers (R3). - const [queuedAgent, setQueuedAgent] = useState(null) + // §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 (queuedAgent && environmentId) { - setQueuedAgent(null) - void startVmBuildAgentSignIn(creationId, environmentId, hostLabel ?? environmentId, [ - queuedAgent - ]) + if (!signInHere || !environmentId || startedRequest.current === signInHere.request) { + return } - }, [queuedAgent, environmentId, creationId, hostLabel]) + 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' }) @@ -159,16 +167,10 @@ export function VmBuildCloudAgentsRow({ density={density} menu={menu} desktopKeySave={desktopKeySave} - queued={queuedAgent !== null} + queued={queued} actions={{ - // After a failure the queue still starts at the failed agent: Try again resumes it. - setUp: () => - run( - model.kind === 'failed' && queue[0] === model.agent - ? queue - : buildAgentsToSetUp(model) - ), - cancel, + setUp: () => runOrcaCloudAgentSetups(buildAgentsToSetUp(model)), + cancel: (agent) => stopOrcaCloudAgentSetups(agent), reopen: (agent) => void api?.reopen({ agent }), copyCodeAndOpen: (agent, code) => { void window.api.ui @@ -178,14 +180,17 @@ export function VmBuildCloudAgentsRow({ void api?.reopen({ agent }) }, dismissFailure: (agent) => { - clear() + stopOrcaCloudAgentSetups() void api?.acknowledge({ agent }) }, retryLoad: () => void reloadOrcaCloudAgentAccounts(), manage: () => openSettings('agent-accounts', 'orca-cloud'), saveDesktopKey: saveKey, - signInHere: (agent) => setQueuedAgent(agent), - cancelSignInHere: () => setQueuedAgent(null) + 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. */} diff --git a/src/renderer/src/components/worktree-creation/cloud-agents-row/build-agents-row-copy.ts b/src/renderer/src/components/worktree-creation/cloud-agents-row/build-agents-row-copy.ts index 1c753e78041..a070c0c8193 100644 --- a/src/renderer/src/components/worktree-creation/cloud-agents-row/build-agents-row-copy.ts +++ b/src/renderer/src/components/worktree-creation/cloud-agents-row/build-agents-row-copy.ts @@ -1,5 +1,6 @@ // Words for the cloud build sheet's Agents row (spec §5b, redesign §5). Catalog names only. import type { Translate } from '@/i18n/use-translate' +import { getIntlLocale } from '@/i18n/i18n' import { formatAgentTypeLabel } from '../../../../../shared/agent-status/presentation/agent-type-label' import type { BuildAgentVia, @@ -17,7 +18,9 @@ import { export function agentList(agents: readonly OrcaCloudAccountAgent[], t: Translate): string { const names = agents.map((agent) => agentName(agent, t)) try { - return new Intl.ListFormat(undefined, { style: 'long', type: 'conjunction' }).format(names) + return new Intl.ListFormat(getIntlLocale(), { style: 'long', type: 'conjunction' }).format( + names + ) } catch { return names.join(', ') } diff --git a/src/renderer/src/components/worktree-creation/cloud-agents-row/use-inline-setup-queue.ts b/src/renderer/src/components/worktree-creation/cloud-agents-row/use-inline-setup-queue.ts deleted file mode 100644 index 3abbe01e4a7..00000000000 --- a/src/renderer/src/components/worktree-creation/cloud-agents-row/use-inline-setup-queue.ts +++ /dev/null @@ -1,77 +0,0 @@ -// R2's Set up: runs S0's one-time setup for each agent in turn, inside the build sheet's row. -// Main owns each setup; this only starts the next agent once the previous one is stored. -import { useCallback, useEffect, useRef, useState } from 'react' -import type { - OrcaCloudAccountAgent, - OrcaCloudAgentSetups -} from '../../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' - -export function useInlineSetupQueue(setups: OrcaCloudAgentSetups): { - queue: readonly OrcaCloudAccountAgent[] - run: (agents: readonly OrcaCloudAccountAgent[]) => void - cancel: (agent: OrcaCloudAccountAgent) => void - /** Stops the queue without touching main (a dismissed failure). */ - clear: () => void -} { - const [queue, setQueue] = useState([]) - const [cursor, setCursor] = useState(0) - // Set once the current agent's setup has left idle, so idle afterwards means it finished. - const started = useRef(false) - - const start = useCallback((agent: OrcaCloudAccountAgent) => { - started.current = false - void window.api.orcaCloudAgents?.start({ agent }) - }, []) - - const run = useCallback( - (agents: readonly OrcaCloudAccountAgent[]) => { - const [first] = agents - if (!first) { - return - } - setQueue(agents) - setCursor(0) - start(first) - }, - [start] - ) - - const cancel = useCallback((agent: OrcaCloudAccountAgent) => { - setQueue([]) - void window.api.orcaCloudAgents?.cancel({ agent }) - }, []) - - const clear = useCallback(() => setQueue([]), []) - - const current = queue[cursor] - const phase = current ? setups[current].phase : 'idle' - useEffect(() => { - if (!current) { - return - } - if (phase === 'failed') { - // Try again restarts from this agent; the ones after it wait. - if (cursor > 0) { - setQueue(queue.slice(cursor)) - setCursor(0) - } - return - } - if (phase !== 'idle') { - started.current = true - return - } - if (!started.current) { - return - } - const next = queue[cursor + 1] - setCursor(cursor + 1) - if (next) { - start(next) - } else { - setQueue([]) - } - }, [current, phase, queue, cursor, start]) - - return { queue, run, cancel, clear } -} diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 81d94d749a7..395cb5ae00e 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -26977,8 +26977,7 @@ "saved": { "team": "{{agent}} key saved · shared with your team", "personal": "{{agent}} key saved · personal", - "detail": "New terminals and agents in running cloud workspaces get it within seconds, no rebuild.", - "short": "Hidden from now on" + "detail": "New terminals and agents in running cloud workspaces get it within seconds, no rebuild." }, "option": { "signIn": "Subscription", @@ -26997,22 +26996,9 @@ "gotIt": "Got it", "save": "Save", "done": "Done", - "later": "Later", - "skippedTitle": "Agent setup skipped", - "signInPending": "Agent sign-in", - "signInPendingDetail": "Opens when the sandbox is ready. Keep Orca open until then.", - "signInCancelled": "Sign-in cancelled", - "skipSignIn": "Don’t sign in", - "readyTitle": "Agents ready", - "readyOne": "{{agent}} ready", - "change": "Change", - "signInQueued": "Agent sign-in will open when the sandbox is ready", - "subtitleBuild": "Give your agents access in Orca Cloud.", - "useKey": "Use a key", "discardQuestion": "Discard the key you typed?", "discard": "Discard", "keepEditing": "Keep editing", - "signInHandedOff": "Continues in the Agent sign-in row below.", "desktopKeys": { "title": "Keys on this computer", "detail": "Save it to your Orca account to use it in cloud workspaces. It stays outside the sandbox.", @@ -27025,8 +27011,7 @@ "rowSaved": "{{agent}}: your API key ••••{{hint}}", "scopeNote": "Not used in Orca Cloud. Save a key to your Orca account to use it in cloud workspaces." }, - "gatewayModelDefaultHint": "Leave empty to use the gateway’s default model.", - "skippedDetailCloudGroup": "Set it up any time from Settings → Orca Cloud → Cloud secrets." + "gatewayModelDefaultHint": "Leave empty to use the gateway’s default model." }, "cloudSecrets": { "editor": { 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 d55ead579fe..fb0c6762ebf 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,15 +25,22 @@ export type OrcaCloudAgentAccountsState = { load: OrcaCloudAgentAccountsLoad setups: OrcaCloudAgentSetups keyKinds: Record + /** The build sheet's R2 Set up: agents set up in turn; `index` is the one running now. */ + queue: { agents: readonly OrcaCloudAccountAgent[]; index: number } } +const NO_QUEUE: OrcaCloudAgentAccountsState['queue'] = { agents: [], index: 0 } + const NO_KEYS: OrcaCloudAgentAccountsState['keyKinds'] = { claude: null, codex: null } let state: OrcaCloudAgentAccountsState = { load: { kind: 'loading' }, setups: IDLE_ORCA_CLOUD_AGENT_SETUPS, - keyKinds: NO_KEYS + keyKinds: NO_KEYS, + queue: NO_QUEUE } +// Set once the queued agent's setup has left idle, so idle afterwards means it finished. +let queuedStarted = false const listeners = new Set<() => void>() let started = false let generation = 0 @@ -97,6 +104,7 @@ function start(): void { ) api.onSetupChanged((setups) => { set({ setups }) + advanceQueue(setups) // A finished setup changes the stored credential: read it, then let main go back to idle. for (const agent of ORCA_CLOUD_ACCOUNT_AGENTS) { if (setups[agent].phase === 'saved') { @@ -106,6 +114,55 @@ function start(): void { }) } +function startQueued(agent: OrcaCloudAccountAgent): void { + queuedStarted = false + void bridge()?.start({ agent }) +} + +/** Moves R2's queue on when the running agent's setup finishes; a failure holds it for Try again. */ +function advanceQueue(setups: OrcaCloudAgentSetups): void { + const { agents, index } = state.queue + const current = agents[index] + if (!current) { + return + } + const phase = setups[current].phase + if (phase !== 'idle') { + queuedStarted = phase !== 'failed' || queuedStarted + return + } + if (!queuedStarted) { + return + } + const next = agents[index + 1] + set({ queue: next ? { agents, index: index + 1 } : NO_QUEUE }) + if (next) { + startQueued(next) + } +} + +/** R2's Set up (and Try again): S0's setup for each agent in turn, inside the build sheet's row. */ +export function runOrcaCloudAgentSetups(agents: readonly OrcaCloudAccountAgent[]): void { + const { agents: queued, index } = state.queue + // Try again after a failure resumes the queue at the failed agent. + const resume = queued[index] !== undefined && queued[index] === agents[0] + const queue = resume ? state.queue : { agents, index: 0 } + const first = queue.agents[queue.index] + if (!first) { + return + } + set({ queue }) + startQueued(first) +} + +/** Cancel stops the agent running now and drops the rest; a dismissed failure only drops them. */ +export function stopOrcaCloudAgentSetups(cancel?: OrcaCloudAccountAgent): void { + set({ queue: NO_QUEUE }) + if (cancel) { + void bridge()?.cancel({ agent: cancel }) + } +} + function subscribe(listener: () => void): () => void { start() listeners.add(listener) diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.test.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.test.ts index 7a79e253c5b..159f33ea80e 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.test.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.test.ts @@ -27,6 +27,7 @@ function accounts( load: { kind: 'ready', status }, setups: IDLE_ORCA_CLOUD_AGENT_SETUPS, keyKinds: { claude: null, codex: null }, + queue: { agents: [], index: 0 }, ...patch } } @@ -41,8 +42,7 @@ function withClaude( } } -const row = (a: OrcaCloudAgentAccountsState) => - buildAgentsRow({ accounts: a, desktopKeys: [], queue: [] }) +const row = (a: OrcaCloudAgentAccountsState) => buildAgentsRow({ accounts: a, desktopKeys: [] }) describe('buildAgentsRow', () => { it('offers the one-time setup when nothing covers any agent (R2), two lines at mount', () => { @@ -92,11 +92,10 @@ describe('buildAgentsRow', () => { it('shows a running or failed setup over everything else, with its place in the queue', () => { const running = accounts(NONE, { - setups: { claude: { phase: 'idle' }, codex: { phase: 'preparing', startedAt: 1 } } + setups: { claude: { phase: 'idle' }, codex: { phase: 'preparing', startedAt: 1 } }, + queue: { agents: ['claude', 'codex'], index: 1 } }) - expect( - buildAgentsRow({ accounts: running, desktopKeys: [], queue: ['claude', 'codex'] }) - ).toMatchObject({ + expect(row(running)).toMatchObject({ kind: 'setup', agent: 'codex', step: 2, @@ -110,7 +109,7 @@ describe('buildAgentsRow', () => { it('offers saving a key only on this computer before the setup (S1-c)', () => { const key = { id: 'k1', agent: 'claude', envName: 'ANTHROPIC_API_KEY', hint: 'x4Qa' } as const - expect(buildAgentsRow({ accounts: accounts(NONE), desktopKeys: [key], queue: [] })).toEqual({ + expect(buildAgentsRow({ accounts: accounts(NONE), desktopKeys: [key] })).toEqual({ kind: 'desktopKey', key }) diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.ts index 320e773ebe5..f00767d675e 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-build-agents-row.ts @@ -69,26 +69,26 @@ function covered(coverage: OrcaCloudAgentCoverage): BuildAgentVia | null { } export function buildAgentsRow(args: { - accounts: Pick + /** `queue` is R2's Set up, in order; it drives "1 of 2". */ + accounts: Pick /** This computer's keys no Cloud secret covers (A6); empty until read. */ desktopKeys: readonly CloudOfferableDesktopKey[] - /** The agents this row's Set up queued, in order; drives "1 of 2". */ - queue: readonly OrcaCloudAccountAgent[] }): BuildAgentsRowModel { const { load, setups, keyKinds } = args.accounts + const queue = args.accounts.queue.agents for (const agent of ORCA_CLOUD_ACCOUNT_AGENTS) { const setup = setups[agent] if (setup.phase === 'failed') { return { kind: 'failed', agent, error: setup.error } } if (setup.phase !== 'idle' && setup.phase !== 'saved') { - const index = args.queue.indexOf(agent) + const index = queue.indexOf(agent) return { kind: 'setup', agent, setup, step: index === -1 ? 1 : index + 1, - of: Math.max(args.queue.length, 1) + of: Math.max(queue.length, 1) } } } From aaa19210946a50c8b855b46761bd9587ecd73c21 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 10 Nov 2026 08:53:17 -0800 Subject: [PATCH 3/3] =?UTF-8?q?fix(cloud):=20NP-3=20design-squad=20wording?= =?UTF-8?q?:=20one=20'=C2=B7'=20between=20source=20groups=20('Claude=20fro?= =?UTF-8?q?m=20your=20Orca=20account=20=C2=B7=20Codex=20with=20the=20team?= =?UTF-8?q?=20key');=20full=20text=20in=20title=20for=20truncated=20lines?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../VmBuildCloudAgentsRowView.tsx | 10 +++++++--- .../cloud-agents-row/build-agents-row-copy.ts | 20 ++++++++----------- src/renderer/src/i18n/locales/en.json | 6 +++--- 3 files changed, 18 insertions(+), 18 deletions(-) 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 index 4a7fad779ed..ce11db5c3e4 100644 --- a/src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRowView.tsx +++ b/src/renderer/src/components/worktree-creation/cloud-agents-row/VmBuildCloudAgentsRowView.tsx @@ -238,7 +238,9 @@ function Lines({ const text = readyLine(model, t) return ( <> - {text} + + {text} + {line ? null : ( {t('vmBuildAgents.readyDetail', 'Every cloud workspace uses it. Nothing to do here.')} @@ -259,7 +261,7 @@ function Lines({ const device = model.kind === 'setup' && model.setup.phase === 'device' ? model.setup : null return ( <> - + {device ? ( <> {t('vmBuildAgents.deviceEnter', 'Enter')}{' '} @@ -278,7 +280,9 @@ function Lines({ {line ? ( {detail} ) : ( - {detail} + + {detail} + )} ) diff --git a/src/renderer/src/components/worktree-creation/cloud-agents-row/build-agents-row-copy.ts b/src/renderer/src/components/worktree-creation/cloud-agents-row/build-agents-row-copy.ts index a070c0c8193..83ad1fef93c 100644 --- a/src/renderer/src/components/worktree-creation/cloud-agents-row/build-agents-row-copy.ts +++ b/src/renderer/src/components/worktree-creation/cloud-agents-row/build-agents-row-copy.ts @@ -9,7 +9,7 @@ import type { import type { OrcaCloudAccountAgent } from '../../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' import { agentName, - keySourceLabel, + keyPhrase, productName, setupFailureCopy } from '../../settings/agent-accounts/orca-cloud-accounts-copy' @@ -26,15 +26,16 @@ export function agentList(agents: readonly OrcaCloudAccountAgent[], t: Translate } } -function viaLabel(via: BuildAgentVia, t: Translate): string { +/** One source group: "Claude and Codex from your Orca account" / "Codex with the team key". */ +function groupLabel(via: BuildAgentVia, agents: string, t: Translate): string { return via === 'account' - ? t('vmBuildAgents.fromAccount', 'from your Orca account') - : keySourceLabel(via, t) + ? t('vmBuildAgents.groupAccount', '{{agents}} from your Orca account', { agents }) + : t('vmBuildAgents.groupKey', '{{agents}} with {{key}}', { agents, key: keyPhrase(via, t) }) } /** - * R1: "Claude and Codex · from your Orca account". Mixed sources read per source group in one line: - * "Claude · from your Orca account · Codex · team key". + * R1: "Claude and Codex from your Orca account · nw@stably.ai". Mixed sources: one group per + * source, and the "·" separates groups only: "Claude from your Orca account · Codex with the team key". */ export function readyLine( model: Extract, @@ -44,12 +45,7 @@ export function readyLine( for (const entry of model.covered) { groups.set(entry.via, [...(groups.get(entry.via) ?? []), entry.agent]) } - const parts = [...groups].map(([via, agents]) => - t('vmBuildAgents.group', '{{agents}} · {{source}}', { - agents: agentList(agents, t), - source: viaLabel(via, t) - }) - ) + const parts = [...groups].map(([via, agents]) => groupLabel(via, agentList(agents, t), t)) if (model.label) { parts.push(model.label) } diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 395cb5ae00e..93a58f4cdfb 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -27717,8 +27717,6 @@ "deviceEnter": "Enter", "deviceOn": "on {{host}}", "manage": "Manage", - "fromAccount": "from your Orca account", - "group": "{{agents}} · {{source}}", "separator": " · ", "stepOf": "{{step}} of {{of}}", "settingUp": "Setting up {{agent}}", @@ -27739,6 +27737,8 @@ "paused": "Orca account sign-in is paused", "pausedDetail": "This sign-in stays with this workspace", "error": "Couldn’t check agent sign-in", - "errorDetail": "The workspace still opens. Agents can sign in later." + "errorDetail": "The workspace still opens. Agents can sign in later.", + "groupAccount": "{{agents}} from your Orca account", + "groupKey": "{{agents}} with {{key}}" } }