From f337f81eb212c3f8dacb4d28fdb3b5593f94cc66 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Mon, 9 Nov 2026 07:15:23 -0800 Subject: [PATCH 01/69] =?UTF-8?q?fix(w3):=20glossary=20pass=20for=20ports?= =?UTF-8?q?=20(sandbox=20asleep=20=C2=B7=20Wake,=20'in=20use=20on=20this?= =?UTF-8?q?=20computer')=20(#79)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/components/right-sidebar/PortsPanel.tsx | 1 + .../local-workspace-ports-panel.tsx | 7 +++++-- .../runtime-port-forward-status.fixture.tsx | 16 ++++++++++++++++ .../runtime-port-forward-status.tsx | 17 ++++++++++++----- .../use-runtime-port-row-forwarding.tsx | 17 +++++++++++++++-- src/renderer/src/i18n/locales/en.json | 14 ++++++++++++-- 6 files changed, 61 insertions(+), 11 deletions(-) diff --git a/src/renderer/src/components/right-sidebar/PortsPanel.tsx b/src/renderer/src/components/right-sidebar/PortsPanel.tsx index 311dc61c71a..f776316f708 100644 --- a/src/renderer/src/components/right-sidebar/PortsPanel.tsx +++ b/src/renderer/src/components/right-sidebar/PortsPanel.tsx @@ -62,6 +62,7 @@ export default function PortsPanel({ isVisible }: { isVisible: boolean }): React runtimeTarget={host.target} sshForwardTargetId={sshForwardTargetId} portMenuItems={shareAvailable ? sharePortMenuItems : undefined} + isSandbox={shareAvailable} footer={(activePorts) => ( React.ReactNode /** Host-specific sections below the ports (Orca Cloud: shared links), given the listening ports. */ footer?: (activePorts: readonly WorkspacePort[]) => React.ReactNode + /** An Orca Cloud sandbox: copy says "sandbox" and offers Wake. */ + isSandbox?: boolean }): React.JSX.Element { const t = useTranslate() const activeWorktree = useActiveWorktree() @@ -66,7 +69,7 @@ export function LocalWorkspacePortsPanel({ }) const scanKey = runtimeTarget ? `${workspacePortRuntimeTargetKey(runtimeTarget)}:all` : null - const runtimeForwarding = useRuntimePortRowForwarding(runtimeTarget, portMenuItems) + const runtimeForwarding = useRuntimePortRowForwarding(runtimeTarget, portMenuItems, isSandbox) const refresh = useCallback(() => { if (!activeRepoId || !runtimeTarget || !scanKey) { diff --git a/src/renderer/src/components/right-sidebar/runtime-port-forward-status.fixture.tsx b/src/renderer/src/components/right-sidebar/runtime-port-forward-status.fixture.tsx index 1eded1a1395..b3f0505276c 100644 --- a/src/renderer/src/components/right-sidebar/runtime-port-forward-status.fixture.tsx +++ b/src/renderer/src/components/right-sidebar/runtime-port-forward-status.fixture.tsx @@ -144,3 +144,19 @@ export const unreachable = defineFixture({ ) }) + +export const sandboxAsleep = defineFixture({ + width: 300, + render: () => ( +
+ {}} + onOpenLocal={() => {}} + onReconnect={() => {}} + /> +
+ ) +}) diff --git a/src/renderer/src/components/right-sidebar/runtime-port-forward-status.tsx b/src/renderer/src/components/right-sidebar/runtime-port-forward-status.tsx index f5a82fdcf80..beef4ebd57f 100644 --- a/src/renderer/src/components/right-sidebar/runtime-port-forward-status.tsx +++ b/src/renderer/src/components/right-sidebar/runtime-port-forward-status.tsx @@ -21,8 +21,11 @@ export function RuntimePortForwardStatus({ state, onForward, onOpenLocal, - onReconnect + onReconnect, + isSandbox = false }: { + /** Orca Cloud: says "sandbox" and offers Wake instead of Reconnect. */ + isSandbox?: boolean remotePort: number state: RuntimePortForwardRowState onForward: () => void @@ -36,7 +39,9 @@ export function RuntimePortForwardStatus({ const unreachable = !offline && Boolean(forward.lastError) const remapped = forward.localPort !== remotePort const note = offline - ? t('auto.components.right.sidebar.RuntimePortForward.hostOfflineNote', 'Host offline') + ? isSandbox + ? t('auto.components.right.sidebar.RuntimePortForward.sandboxAsleep', 'Sandbox is asleep') + : t('auto.components.right.sidebar.RuntimePortForward.hostOfflineNote', 'Host offline') : unreachable ? t( 'auto.components.right.sidebar.RuntimePortForward.notAnswering', @@ -45,8 +50,8 @@ export function RuntimePortForwardStatus({ ) : remapped ? t( - 'auto.components.right.sidebar.RuntimePortForward.remappedInUseHere', - '({{value0}} in use here)', + 'auto.components.right.sidebar.RuntimePortForward.remappedInUseOnComputer', + '({{value0}} in use on this computer)', { value0: remotePort } ) : null @@ -101,7 +106,9 @@ export function RuntimePortForwardStatus({ ) : null} {offline && onReconnect ? ( ) : null} diff --git a/src/renderer/src/components/right-sidebar/use-runtime-port-row-forwarding.tsx b/src/renderer/src/components/right-sidebar/use-runtime-port-row-forwarding.tsx index 1fb9ceafcd3..1bffd0d3471 100644 --- a/src/renderer/src/components/right-sidebar/use-runtime-port-row-forwarding.tsx +++ b/src/renderer/src/components/right-sidebar/use-runtime-port-row-forwarding.tsx @@ -55,7 +55,9 @@ export type RuntimePortRowForwarding = { export function useRuntimePortRowForwarding( runtimeTarget: RuntimeClientTarget | null, /** Host actions after the forward items (Orca Cloud: Share…). */ - extraMenuItems?: (port: WorkspacePort) => ReactNode + extraMenuItems?: (port: WorkspacePort) => ReactNode, + /** Orca Cloud: copy says "sandbox", and offline offers Wake. */ + isSandbox = false ): RuntimePortRowForwarding | null { const t = useTranslate() const environmentId = runtimeTarget?.kind === 'environment' ? runtimeTarget.environmentId : null @@ -124,6 +126,7 @@ export function useRuntimePortRowForwarding( void forward(port)} onReconnect={ environmentId ? () => void wakeRuntimePortForwardHost(environmentId) : undefined @@ -199,7 +202,17 @@ export function useRuntimePortRowForwarding( return existing ? `localhost:${existing.localPort}` : undefined } } - }, [environmentId, extraMenuItems, failures, forward, forwardFor, hostOffline, pending, t]) + }, [ + environmentId, + extraMenuItems, + failures, + forward, + forwardFor, + hostOffline, + isSandbox, + pending, + t + ]) if (!environmentId || !runtimePortForwardingAvailable()) { return null diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 3f0d4c6d99e..762b5e96ab2 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -2181,6 +2181,13 @@ "failedAnnouncement": "Couldn't forward :{{value0}}. {{value1}}", "busyInUseHere": "localhost:{{value0}} in use on this computer", "listenFailedRetry": "Couldn't listen on this computer. Retry or pick another port" + }, + "orcaCloudTransfer": { + "waking": "Waking the workspace…", + "done": "Moved to this computer", + "leftovers": "Some changes did not apply cleanly; they were saved to {{dir}}.", + "summary": "Branch {{branch}} with your uncommitted changes and agent chats ({{count}}). The cloud workspace is unchanged.", + "failed": "Could not move the workspace" } }, "hooks": { @@ -6961,7 +6968,8 @@ "copyPathOption": "Path", "copyNameOption": "Worktree Name", "lineageSubmenu": "Parent & Children", - "projectGroupSubmenu": "Project Group" + "projectGroupSubmenu": "Project Group", + "moveToThisComputer": "Move to this computer" }, "WorktreeList": { "7a8b9c0d1e": "Update required", @@ -15678,7 +15686,9 @@ "actionLabel": "{{value0}} for port {{value1}}", "copyLocalUrl": "Copy local URL", "stopAndSkip": "Stop and don't auto-forward :{{value0}}", - "remappedInUseHere": "({{value0}} in use here)" + "sandboxAsleep": "Sandbox is asleep", + "remappedInUseOnComputer": "({{value0}} in use on this computer)", + "wake": "Wake" }, "CloudShare": { "alreadyShared": "Already shared", From e141a74eada055bd3b4f88e765fa46b7a0d8b76d Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Mon, 9 Nov 2026 07:15:51 -0800 Subject: [PATCH 02/69] feat(cloud): one idle-sleep constant (ORCA_CLOUD_IDLE_SLEEP_MINUTES = 15) for control plane, desktop scheduler, billing plans and toasts; GET /v1/config serves it (#80) Plans said 15 minutes, the desktop slept at 20. The shared wire module now owns the value; the control plane serves it at GET /v1/config (public product constants), the desktop driver's idleStopMs, billing's Team plan idleSleepMinutes and the billing fixtures read the constant, and the idle-sleep toast already prints the scheduler's value from the event. --- cloud/apps/billing/src/plans.ts | 4 +++- cloud/apps/sandbox-control/src/index.ts | 5 +++++ cloud/apps/sandbox-control/test/config.test.ts | 18 ++++++++++++++++++ .../hosted-sandbox/hosted-sandbox-driver.ts | 3 ++- .../billing/plan-billing-fixtures.ts | 3 ++- .../src/lib/orca-cloud-session-events.ts | 2 +- .../hosted-sandbox/hosted-sandbox-wire.ts | 12 ++++++++++++ 7 files changed, 43 insertions(+), 4 deletions(-) create mode 100644 cloud/apps/sandbox-control/test/config.test.ts diff --git a/cloud/apps/billing/src/plans.ts b/cloud/apps/billing/src/plans.ts index 854b1d5f75a..86f9062f85f 100644 --- a/cloud/apps/billing/src/plans.ts +++ b/cloud/apps/billing/src/plans.ts @@ -6,6 +6,7 @@ // included hour is one hour on the Standard 4 vCPU / 8 GB box and a Large box burns 2x. // Included hours are a MONTHLY per-seat allowance pooled across the org, for annual plans too. import { z } from 'zod' +import { ORCA_CLOUD_IDLE_SLEEP_MINUTES } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire' import type { Env } from './env' export const PLAN_IDS = ['team'] as const @@ -65,7 +66,8 @@ export const DEFAULT_PLANS: PlanCatalog = { includedHoursPerSeat: 60, concurrentSandboxesPerSeat: 3, machineSizes: ['standard', 'large'], - idleSleepMinutes: 15, + // Same constant the control plane enforces and serves (GET /v1/config); never a literal here. + idleSleepMinutes: ORCA_CLOUD_IDLE_SLEEP_MINUTES, overageCentsPerHour: 75, defaultSpendCapCents: 2500, maxSpendCapCents: 500_000, diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 28c2f13fcb6..91dcaf9e9a6 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -30,6 +30,7 @@ // Operator (OPERATOR_TOKEN): /v1/internal/* (see operator.ts) // Public share links (src/share-gateway.ts): /s//*, plus the root-path cookie fallback // Vercel network-policy forwardURL target (Vercel sandbox OIDC): /v1/egress/proxy +import { ORCA_CLOUD_IDLE_SLEEP_MINUTES } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire' import { z } from 'zod' import { maintainPool, poolConfigFromEnv } from './pool' import { authenticateDesktop } from './auth' @@ -751,6 +752,10 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) })) ?? fail('not_found', 404) ) } + if (url.pathname === '/v1/config' && request.method === 'GET') { + // Public product constants (no auth): every client reads these instead of hardcoding them. + return json({ idleSleepMinutes: ORCA_CLOUD_IDLE_SLEEP_MINUTES }) + } if (url.pathname === '/v1/github/dev-connect' && env.SANDBOX_ENV !== 'prod') { // Dev-only, link-shareable start of the user flow: mints a fresh 10-min state per click for a dev: // account (desktop builds call POST /v1/github/connect instead). diff --git a/cloud/apps/sandbox-control/test/config.test.ts b/cloud/apps/sandbox-control/test/config.test.ts new file mode 100644 index 00000000000..1d43a6d9da1 --- /dev/null +++ b/cloud/apps/sandbox-control/test/config.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest' +import { + HostedSandboxConfigResponseSchema, + ORCA_CLOUD_IDLE_SLEEP_MINUTES +} from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire' +import { DEFAULT_PLANS } from '../../billing/src/plans' +import { createHarness } from './harness' + +describe('GET /v1/config', () => { + it('serves the idle-sleep minutes every client reads; billing advertises the same constant', async () => { + const h = await createHarness() + const res = await h.send(new Request('https://sandbox.test/v1/config')) + expect(res.status).toBe(200) + const body = HostedSandboxConfigResponseSchema.parse(await res.json()) + expect(body.idleSleepMinutes).toBe(ORCA_CLOUD_IDLE_SLEEP_MINUTES) + expect(DEFAULT_PLANS.team.idleSleepMinutes).toBe(ORCA_CLOUD_IDLE_SLEEP_MINUTES) + }) +}) diff --git a/src/main/hosted-sandbox/hosted-sandbox-driver.ts b/src/main/hosted-sandbox/hosted-sandbox-driver.ts index 2882ecb4e41..b77dbbab561 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-driver.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-driver.ts @@ -2,6 +2,7 @@ // Which provider runs the VM (Vercel today) is a control-plane detail the desktop never sees. import { HOSTED_SANDBOX_MACHINE_SIZES, + ORCA_CLOUD_IDLE_SLEEP_MINUTES, type HostedSandboxMachineSize, type HostedSandboxReadyResponse, type HostedSandboxView @@ -30,7 +31,7 @@ export const HOSTED_SANDBOX_CAPABILITIES: HostedEnvironmentCapabilities = Object maxSessionMs: 24 * 60 * 60_000, fsPersistOnStop: true, egressInjection: true, - idleStopMs: 20 * 60_000 + idleStopMs: ORCA_CLOUD_IDLE_SLEEP_MINUTES * 60_000 }) const STATUS: Record = { diff --git a/src/renderer/src/components/billing/plan-billing-fixtures.ts b/src/renderer/src/components/billing/plan-billing-fixtures.ts index 396ba70166d..ec3dc45cb75 100644 --- a/src/renderer/src/components/billing/plan-billing-fixtures.ts +++ b/src/renderer/src/components/billing/plan-billing-fixtures.ts @@ -1,5 +1,6 @@ // Shared sample entitlements for billing tests and component fixtures. import type { OrcaBillingEntitlement, OrcaBillingOffers } from '../../../../shared/orca-billing' +import { ORCA_CLOUD_IDLE_SLEEP_MINUTES } from '../../../../shared/hosted-sandbox/hosted-sandbox-wire' const HOUR = 3600 @@ -13,7 +14,7 @@ export const sampleOffers: OrcaBillingOffers = { largeMachineWeight: 2, includedHoursPerSeat: 60, concurrentSandboxesPerSeat: 3, - idleSleepMinutes: 15, + idleSleepMinutes: ORCA_CLOUD_IDLE_SLEEP_MINUTES, overageCentsPerHour: 75, defaultSpendCapCents: 2500 }, diff --git a/src/renderer/src/lib/orca-cloud-session-events.ts b/src/renderer/src/lib/orca-cloud-session-events.ts index 723b8e3bd0b..8bece89fa77 100644 --- a/src/renderer/src/lib/orca-cloud-session-events.ts +++ b/src/renderer/src/lib/orca-cloud-session-events.ts @@ -87,7 +87,7 @@ export function showOrcaCloudPlanUpsell(message: string): void { }) } -/** " slept after 20 minutes idle · Wake": the quiet receipt for an automatic sleep. */ +/** " slept after {{n}} minutes idle · Wake" (n = ORCA_CLOUD_IDLE_SLEEP_MINUTES, via the event): the quiet receipt for an automatic sleep. */ export function showIdleSleepNotice( workspaceId: string, name: string, diff --git a/src/shared/hosted-sandbox/hosted-sandbox-wire.ts b/src/shared/hosted-sandbox/hosted-sandbox-wire.ts index b075d8b4295..133f36be511 100644 --- a/src/shared/hosted-sandbox/hosted-sandbox-wire.ts +++ b/src/shared/hosted-sandbox/hosted-sandbox-wire.ts @@ -2,6 +2,18 @@ // The Worker's tests parse its responses with these schemas, so either side drifting fails a test. import { z } from 'zod' +/** + * Minutes of no agent work and no input before a cloud sandbox sleeps. The one source for every + * surface: the control plane serves it (GET /v1/config), the desktop scheduler enforces it, billing's + * plan card and the idle-sleep toast print it. Never write the number anywhere else. + */ +export const ORCA_CLOUD_IDLE_SLEEP_MINUTES = 15 + +/** GET /v1/config: product constants clients (desktop, mobile, CLI, marketing) must not hardcode. */ +export const HostedSandboxConfigResponseSchema = z.object({ + idleSleepMinutes: z.number().int().positive() +}) + // Billing sells exactly these; larger boxes need a Vercel Enterprise plan. export const HOSTED_SANDBOX_MACHINE_SIZES = ['standard', 'large'] as const export type HostedSandboxMachineSize = (typeof HOSTED_SANDBOX_MACHINE_SIZES)[number] From 2e76ad5592976e2b14cedc2849da35f6db517f89 Mon Sep 17 00:00:00 2001 From: Neil Date: Mon, 9 Nov 2026 05:06:42 -0800 Subject: [PATCH 03/69] feat(cloud): Orca Cloud API keys + routines settings (private builds) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Main-process /v1 client (zod-validated, token never leaves main, errors mapped to stable codes), IPC + preload bridge, Settings → API Keys (create with scope presets, one-time secret, revoke, MCP approve-an-app code, docs/MCP links, vmCliEnabled org toggle, admin activity log) and Settings → Routines (list, editor for schedule/GitHub/webhook triggers, run now, history, delete), gated on a configured Orca Cloud control plane. Component fixtures + unit tests. --- src/main/cloud-api/cloud-api-client.test.ts | 151 ++++++ src/main/cloud-api/cloud-api-client.ts | 206 ++++++++ src/main/cloud-api/cloud-api-ipc.test.ts | 79 +++ src/main/cloud-api/cloud-api-ipc.ts | 86 ++++ src/main/cloud-api/cloud-api-service.ts | 81 ++++ src/main/startup/main-window-core-services.ts | 2 + src/preload/api-types.ts | 3 + src/preload/api/cloud-api-bridge.ts | 73 +++ src/preload/index.ts | 2 + .../settings/cloud-api/ApproveAppDialog.tsx | 226 +++++++++ .../settings/cloud-api/CloudApiKeysPane.tsx | 116 +++++ .../cloud-api/CloudApiKeysSections.tsx | 283 +++++++++++ .../cloud-api/CloudApiKeysView.fixture.tsx | 235 +++++++++ .../settings/cloud-api/CloudApiKeysView.tsx | 310 ++++++++++++ .../cloud-api/CloudApiSignedOutNotice.tsx | 33 ++ .../settings/cloud-api/CloudConfirmDialog.tsx | 91 ++++ .../settings/cloud-api/CloudRoutinesPane.tsx | 139 ++++++ .../cloud-api/CloudRoutinesView.fixture.tsx | 305 ++++++++++++ .../settings/cloud-api/CloudRoutinesView.tsx | 453 ++++++++++++++++++ .../settings/cloud-api/CreateApiKeyDialog.tsx | 406 ++++++++++++++++ .../cloud-api/RoutineAgentSection.tsx | 177 +++++++ .../cloud-api/RoutineEditorDialog.tsx | 409 ++++++++++++++++ .../settings/cloud-api/RoutineRunHistory.tsx | 213 ++++++++ .../cloud-api/RoutineTriggerFields.tsx | 314 ++++++++++++ .../cloud-api/RoutineWebhookParts.tsx | 191 ++++++++ .../settings/cloud-api/cloud-api-copy.ts | 170 +++++++ .../cloud-api/cloud-api-format.test.ts | 85 ++++ .../settings/cloud-api/cloud-api-format.ts | 156 ++++++ .../settings/cloud-api/cloud-api-parts.tsx | 257 ++++++++++ .../settings/cloud-api/cloud-api-search.ts | 40 ++ .../settings/cloud-api/cloud-load-state.ts | 20 + .../settings/cloud-api/routine-draft.test.ts | 150 ++++++ .../settings/cloud-api/routine-draft.ts | 241 ++++++++++ .../settings-cloud-api-section-renderers.tsx | 47 ++ .../settings/page/settings-page-renderer.tsx | 2 + .../settings/page/use-settings-store-model.ts | 4 + .../settings-navigation-build-options.ts | 2 + ...settings-navigation-capability-sections.ts | 36 +- .../src/hooks/useOrcaCloudApiAvailability.ts | 48 ++ .../hooks/useSettingsNavigationMetadata.ts | 7 + .../src/lib/settings-navigation-types.ts | 2 + src/shared/cloud-api/cloud-api-types.ts | 334 +++++++++++++ 42 files changed, 6183 insertions(+), 2 deletions(-) create mode 100644 src/main/cloud-api/cloud-api-client.test.ts create mode 100644 src/main/cloud-api/cloud-api-client.ts create mode 100644 src/main/cloud-api/cloud-api-ipc.test.ts create mode 100644 src/main/cloud-api/cloud-api-ipc.ts create mode 100644 src/main/cloud-api/cloud-api-service.ts create mode 100644 src/preload/api/cloud-api-bridge.ts create mode 100644 src/renderer/src/components/settings/cloud-api/ApproveAppDialog.tsx create mode 100644 src/renderer/src/components/settings/cloud-api/CloudApiKeysPane.tsx create mode 100644 src/renderer/src/components/settings/cloud-api/CloudApiKeysSections.tsx create mode 100644 src/renderer/src/components/settings/cloud-api/CloudApiKeysView.fixture.tsx create mode 100644 src/renderer/src/components/settings/cloud-api/CloudApiKeysView.tsx create mode 100644 src/renderer/src/components/settings/cloud-api/CloudApiSignedOutNotice.tsx create mode 100644 src/renderer/src/components/settings/cloud-api/CloudConfirmDialog.tsx create mode 100644 src/renderer/src/components/settings/cloud-api/CloudRoutinesPane.tsx create mode 100644 src/renderer/src/components/settings/cloud-api/CloudRoutinesView.fixture.tsx create mode 100644 src/renderer/src/components/settings/cloud-api/CloudRoutinesView.tsx create mode 100644 src/renderer/src/components/settings/cloud-api/CreateApiKeyDialog.tsx create mode 100644 src/renderer/src/components/settings/cloud-api/RoutineAgentSection.tsx create mode 100644 src/renderer/src/components/settings/cloud-api/RoutineEditorDialog.tsx create mode 100644 src/renderer/src/components/settings/cloud-api/RoutineRunHistory.tsx create mode 100644 src/renderer/src/components/settings/cloud-api/RoutineTriggerFields.tsx create mode 100644 src/renderer/src/components/settings/cloud-api/RoutineWebhookParts.tsx create mode 100644 src/renderer/src/components/settings/cloud-api/cloud-api-copy.ts create mode 100644 src/renderer/src/components/settings/cloud-api/cloud-api-format.test.ts create mode 100644 src/renderer/src/components/settings/cloud-api/cloud-api-format.ts create mode 100644 src/renderer/src/components/settings/cloud-api/cloud-api-parts.tsx create mode 100644 src/renderer/src/components/settings/cloud-api/cloud-api-search.ts create mode 100644 src/renderer/src/components/settings/cloud-api/cloud-load-state.ts create mode 100644 src/renderer/src/components/settings/cloud-api/routine-draft.test.ts create mode 100644 src/renderer/src/components/settings/cloud-api/routine-draft.ts create mode 100644 src/renderer/src/components/settings/page/settings-cloud-api-section-renderers.tsx create mode 100644 src/renderer/src/hooks/useOrcaCloudApiAvailability.ts create mode 100644 src/shared/cloud-api/cloud-api-types.ts diff --git a/src/main/cloud-api/cloud-api-client.test.ts b/src/main/cloud-api/cloud-api-client.test.ts new file mode 100644 index 00000000000..2ded8374dc4 --- /dev/null +++ b/src/main/cloud-api/cloud-api-client.test.ts @@ -0,0 +1,151 @@ +import { describe, expect, it, vi } from 'vitest' +import { CloudApiError, classifyCloudApiResponse, createCloudApiClient } from './cloud-api-client' + +const KEY = { + id: 'key_1', + name: 'CI', + prefix: 'orca_sk_Ab3x', + scopes: ['workspaces:read', 'future:scope'], + createdBy: 'u1', + createdAt: 1, + lastUsedAt: null, + expiresAt: null +} + +function respond(status: number, body: unknown, headers: Record = {}) { + return new Response(body === undefined ? null : JSON.stringify(body), { + status, + headers: { 'content-type': 'application/json', ...headers } + }) +} + +function client(fetchImpl: typeof fetch, getAccessToken = async () => 'tok_secret') { + return createCloudApiClient({ + controlPlaneUrl: 'https://cp.example.dev/', + getAccessToken, + fetchImpl + }) +} + +async function codeOf(promise: Promise): Promise { + try { + await promise + } catch (error) { + if (error instanceof CloudApiError) { + return error.code + } + throw error + } + return 'ok' +} + +describe('createCloudApiClient', () => { + it('sends the bearer token, JSON body and query, and validates the answer', async () => { + const fetchImpl = vi.fn(async () => + respond(200, { keys: [KEY], availableScopes: ['audit:read'] }) + ) + const keys = await client(fetchImpl as unknown as typeof fetch).listApiKeys() + expect(keys.keys[0]?.prefix).toBe('orca_sk_Ab3x') + // Unknown scopes from a newer server are dropped, not fatal. + expect(keys.keys[0]?.scopes).toEqual(['workspaces:read']) + const [url, init] = fetchImpl.mock.calls[0] as unknown as [string, RequestInit] + expect(url).toBe('https://cp.example.dev/v1/api-keys') + expect((init.headers as Record).authorization).toBe('Bearer tok_secret') + expect(init.redirect).toBe('error') + + const created = vi.fn(async () => + respond(201, { key: KEY, secret: `orca_sk_${'a'.repeat(32)}` }) + ) + await client(created as unknown as typeof fetch).createApiKey({ + name: 'CI', + scopes: ['workspaces:read'] + }) + const [, createInit] = created.mock.calls[0] as unknown as [string, RequestInit] + expect(createInit.method).toBe('POST') + expect(JSON.parse(String(createInit.body))).toEqual({ name: 'CI', scopes: ['workspaces:read'] }) + + const runs = vi.fn(async () => respond(200, { runs: [], nextBefore: null })) + await client(runs as unknown as typeof fetch).listRoutineRuns('rt/1', { limit: 20, before: 99 }) + expect((runs.mock.calls[0] as unknown as [string])[0]).toBe( + 'https://cp.example.dev/v1/routines/rt%2F1/runs?limit=20&before=99' + ) + }) + + it('rejects a malformed answer as invalid-response', async () => { + const fetchImpl = vi.fn(async () => respond(200, { keys: 'nope' })) + expect(await codeOf(client(fetchImpl as unknown as typeof fetch).listApiKeys())).toBe( + 'invalid-response' + ) + const badSecret = vi.fn(async () => respond(201, { key: KEY, secret: 'not-a-key' })) + expect( + await codeOf( + client(badSecret as unknown as typeof fetch).createApiKey({ + name: 'x', + scopes: ['audit:read'] + }) + ) + ).toBe('invalid-response') + }) + + it('maps network and token failures without leaking the token', async () => { + const offline = vi.fn(async () => { + throw new TypeError('fetch failed tok_secret') + }) + const error = await client(offline as unknown as typeof fetch) + .me() + .catch((caught: unknown) => caught) + expect(error).toBeInstanceOf(CloudApiError) + expect((error as CloudApiError).code).toBe('network') + expect(String((error as CloudApiError).message)).not.toContain('tok_secret') + + const noToken = client(vi.fn() as unknown as typeof fetch, async () => { + throw new Error('signed out') + }) + expect(await codeOf(noToken.me())).toBe('signed-out') + }) + + it('treats a missing routines route as not-available but a missing routine as not-found', async () => { + const missing = vi.fn(async () => respond(404, { error: 'not_found' })) + const c = client(missing as unknown as typeof fetch) + expect(await codeOf(c.listRoutines())).toBe('not-available') + expect(await codeOf(c.getRoutine('rt_1'))).toBe('not-found') + }) + + it('carries retry-after on rate limits and accepts empty DELETE bodies', async () => { + const limited = vi.fn(async () => + respond(429, { error: 'rate_limited' }, { 'retry-after': '7' }) + ) + const error = (await client(limited as unknown as typeof fetch) + .listApiKeys() + .catch((caught: unknown) => caught)) as CloudApiError + expect(error.code).toBe('rate-limited') + expect(error.retryAfterSeconds).toBe(7) + + const deleted = vi.fn(async () => new Response(null, { status: 200 })) + await expect( + client(deleted as unknown as typeof fetch).revokeApiKey('key_1') + ).resolves.toBeUndefined() + }) +}) + +describe('classifyCloudApiResponse', () => { + it.each([ + [401, { error: 'unauthorized' }, 'signed-out'], + [403, { error: 'forbidden', reason: 'admin_required' }, 'admin-required'], + [403, { error: 'forbidden', reason: 'admin_scope:audit:read' }, 'admin-required'], + [403, { error: 'insufficient_scope', reason: 'routines:write' }, 'forbidden'], + [400, { error: 'invalid_request', reason: 'name: Too small' }, 'invalid-request'], + [503, { error: 'not_configured' }, 'not-available'], + [500, null, 'server'], + [502, { error: 'workspace_unavailable' }, 'server'] + ])('%i %j → %s', (status, body, code) => { + expect(classifyCloudApiResponse(status, body).code).toBe(code) + }) + + it('keeps the server validation reason as detail, truncated', () => { + expect(classifyCloudApiResponse(400, { reason: 'name: Too small' }).detail).toBe( + 'name: Too small' + ) + expect(classifyCloudApiResponse(400, { reason: 'x'.repeat(1000) }).detail).toHaveLength(200) + }) +}) diff --git a/src/main/cloud-api/cloud-api-client.ts b/src/main/cloud-api/cloud-api-client.ts new file mode 100644 index 00000000000..aaba7de4660 --- /dev/null +++ b/src/main/cloud-api/cloud-api-client.ts @@ -0,0 +1,206 @@ +// HTTP client for the Orca Cloud control plane's public /v1 API, used by the desktop's API keys and +// routines settings. Pure (fetch + token source injected) so it is testable without Electron. The +// bearer token never leaves this module: callers get validated data or a CloudApiError code. +import { z } from 'zod' +import { + CloudApiApprovalSchema, + CloudApiAuditPageSchema, + CloudApiCreatedKeySchema, + CloudApiInstallationListSchema, + CloudApiKeyListSchema, + CloudApiMeSchema, + CloudApiProjectListSchema, + CloudApiSettingsSchema, + RoutineCreatedSchema, + RoutineEnvelopeSchema, + RoutineListSchema, + RoutineRunEnvelopeSchema, + RoutineRunPageSchema, + RoutineWebhookSchema, + type CloudApiErrorCode, + type CreateCloudApiApprovalInput, + type CreateCloudApiKeyInput, + type RoutineInput, + type RoutinePatch, + type RoutineRunsQuery +} from '../../shared/cloud-api/cloud-api-types' + +const REQUEST_TIMEOUT_MS = 20_000 +const MAX_DETAIL_CHARS = 200 + +export class CloudApiError extends Error { + constructor( + readonly code: CloudApiErrorCode, + /** Server-provided reason (e.g. a validation message), safe to show; never a secret. */ + readonly detail?: string, + readonly retryAfterSeconds?: number + ) { + super(detail ? `${code}: ${detail}` : code) + this.name = 'CloudApiError' + } +} + +export type CloudApiClientDeps = { + controlPlaneUrl: string + getAccessToken: () => Promise + fetchImpl?: typeof fetch + /** Maps a token-source failure (signed out, auth down) to an error code. */ + classifyTokenError?: (error: unknown) => CloudApiErrorCode +} + +type RequestOptions = { + body?: unknown + query?: Record + /** A 404 on this route means the deployment predates it, not a missing record. */ + notFoundMeansUnavailable?: boolean +} + +function readServerError(body: unknown): { error?: string; reason?: string } { + if (typeof body !== 'object' || body === null) { + return {} + } + const record = body as Record + const pick = (value: unknown): string | undefined => + typeof value === 'string' ? value.slice(0, MAX_DETAIL_CHARS) : undefined + return { error: pick(record.error), reason: pick(record.reason) } +} + +/** Maps a non-2xx control-plane answer to a stable code the renderer can word. */ +export function classifyCloudApiResponse( + status: number, + body: unknown, + options: { notFoundMeansUnavailable?: boolean } = {} +): { code: CloudApiErrorCode; detail?: string } { + const { error, reason } = readServerError(body) + if (status === 401) { + return { code: 'signed-out' } + } + if (status === 403) { + if (reason === 'admin_required' || reason?.startsWith('admin_scope:')) { + return { code: 'admin-required' } + } + return { code: 'forbidden', ...(reason ? { detail: reason } : {}) } + } + if (status === 404) { + return { code: options.notFoundMeansUnavailable ? 'not-available' : 'not-found' } + } + if (status === 400 || status === 409 || status === 422) { + return { code: 'invalid-request', ...(reason ? { detail: reason } : {}) } + } + if (status === 429) { + return { code: 'rate-limited' } + } + if (status === 503 && error === 'not_configured') { + return { code: 'not-available' } + } + return { code: 'server', detail: error ?? `HTTP ${status}` } +} + +export function createCloudApiClient(deps: CloudApiClientDeps) { + const fetchImpl = deps.fetchImpl ?? fetch + const base = `${deps.controlPlaneUrl.replace(/\/+$/, '')}/` + + async function request( + method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE', + path: string, + schema: S, + options: RequestOptions = {} + ): Promise> { + let token: string + try { + token = await deps.getAccessToken() + } catch (error) { + throw new CloudApiError(deps.classifyTokenError?.(error) ?? 'signed-out') + } + const url = new URL(path.replace(/^\//, ''), base) + for (const [name, value] of Object.entries(options.query ?? {})) { + if (value !== undefined) { + url.searchParams.set(name, String(value)) + } + } + let response: Response + try { + response = await fetchImpl(url.toString(), { + method, + headers: { + authorization: `Bearer ${token}`, + accept: 'application/json', + ...(options.body !== undefined ? { 'content-type': 'application/json' } : {}) + }, + ...(options.body !== undefined ? { body: JSON.stringify(options.body) } : {}), + redirect: 'error', + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) + }) + } catch { + throw new CloudApiError('network') + } + const body: unknown = await response.json().catch(() => null) + if (!response.ok) { + const { code, detail } = classifyCloudApiResponse(response.status, body, options) + const retryAfter = Number(response.headers.get('retry-after')) + throw new CloudApiError( + code, + detail, + code === 'rate-limited' && Number.isFinite(retryAfter) && retryAfter > 0 + ? retryAfter + : undefined + ) + } + const parsed = schema.safeParse(body) + if (!parsed.success) { + throw new CloudApiError('invalid-response') + } + return parsed.data + } + + const routinePath = (id: string, sub = ''): string => + `v1/routines/${encodeURIComponent(id)}${sub}` + + return { + me: () => request('GET', 'v1/me', CloudApiMeSchema), + listApiKeys: () => request('GET', 'v1/api-keys', CloudApiKeyListSchema), + createApiKey: (input: CreateCloudApiKeyInput) => + request('POST', 'v1/api-keys', CloudApiCreatedKeySchema, { body: input }), + revokeApiKey: async (id: string): Promise => { + await request('DELETE', `v1/api-keys/${encodeURIComponent(id)}`, z.unknown()) + }, + createApproval: (input: CreateCloudApiApprovalInput = {}) => + request('POST', 'v1/oauth-approvals', CloudApiApprovalSchema, { + body: input, + notFoundMeansUnavailable: true + }), + getSettings: () => request('GET', 'v1/settings', CloudApiSettingsSchema), + putSettings: (settings: { vmCliEnabled: boolean }) => + request('PUT', 'v1/settings', CloudApiSettingsSchema, { body: settings }), + listAudit: (query: { limit?: number; before?: number } = {}) => + request('GET', 'v1/audit', CloudApiAuditPageSchema, { query }), + listProjects: () => request('GET', 'v1/projects', CloudApiProjectListSchema), + listInstallations: () => + request('GET', 'v1/github/installations', CloudApiInstallationListSchema, { + notFoundMeansUnavailable: true + }), + listRoutines: () => + request('GET', 'v1/routines', RoutineListSchema, { notFoundMeansUnavailable: true }), + getRoutine: (id: string) => request('GET', routinePath(id), RoutineEnvelopeSchema), + createRoutine: (input: RoutineInput) => + request('POST', 'v1/routines', RoutineCreatedSchema, { body: input }), + updateRoutine: (id: string, patch: RoutinePatch) => + request('PATCH', routinePath(id), RoutineEnvelopeSchema, { body: patch }), + deleteRoutine: async (id: string): Promise => { + await request('DELETE', routinePath(id), z.unknown()) + }, + runRoutine: (id: string) => request('POST', routinePath(id, '/run'), RoutineRunEnvelopeSchema), + rotateRoutineWebhook: (id: string) => + request('POST', routinePath(id, '/rotate-webhook'), RoutineWebhookSchema), + listRoutineRuns: (id: string, query: RoutineRunsQuery = {}) => + request('GET', routinePath(id, '/runs'), RoutineRunPageSchema, { query }), + getRoutineRun: (id: string, runId: string) => + request( + 'GET', + routinePath(id, `/runs/${encodeURIComponent(runId)}`), + RoutineRunEnvelopeSchema + ) + } +} + +export type CloudApiClient = ReturnType diff --git a/src/main/cloud-api/cloud-api-ipc.test.ts b/src/main/cloud-api/cloud-api-ipc.test.ts new file mode 100644 index 00000000000..517f6ecf9a5 --- /dev/null +++ b/src/main/cloud-api/cloud-api-ipc.test.ts @@ -0,0 +1,79 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const callCloudApi = vi.fn(async (run: (client: unknown) => Promise) => ({ + ok: true, + data: await run(fakeClient) +})) +const fakeClient = { + createApiKey: vi.fn(async (input: unknown) => ({ echoed: input })), + revokeApiKey: vi.fn(async () => undefined), + createRoutine: vi.fn(async (input: unknown) => ({ echoed: input })) +} + +vi.mock('electron', () => ({ ipcMain: { handle: vi.fn(), removeHandler: vi.fn() } })) +vi.mock('./cloud-api-service', () => ({ + callCloudApi: (run: (client: unknown) => Promise) => callCloudApi(run), + getCloudApiAvailability: () => ({ status: 'unconfigured' }) +})) + +const { cloudApiHandlerFor, CLOUD_API_CHANNELS } = await import('./cloud-api-ipc') + +describe('cloud API IPC', () => { + beforeEach(() => { + callCloudApi.mockClear() + }) + + it('rejects malformed renderer input before any network call', async () => { + const create = cloudApiHandlerFor('cloudApi:createApiKey')! + expect(await create({ name: '', scopes: ['workspaces:read'] })).toEqual({ + ok: false, + error: 'invalid-request' + }) + expect(await create({ name: 'x', scopes: ['root:all'] })).toEqual({ + ok: false, + error: 'invalid-request' + }) + expect(await create({ name: 'x', scopes: ['audit:read'], extra: 1 })).toEqual({ + ok: false, + error: 'invalid-request' + }) + expect(await cloudApiHandlerFor('cloudApi:revokeApiKey')!(42)).toEqual({ + ok: false, + error: 'invalid-request' + }) + expect( + await cloudApiHandlerFor('cloudApi:createRoutine')!({ + name: 'r', + repo: { url: 'http://insecure.example/repo' }, + trigger: { kind: 'webhook' }, + agent: 'claude', + prompt: 'p', + postResults: 'none' + }) + ).toEqual({ ok: false, error: 'invalid-request' }) + expect(callCloudApi).not.toHaveBeenCalled() + }) + + it('passes validated input through to the client', async () => { + const result = await cloudApiHandlerFor('cloudApi:createApiKey')!({ + name: ' CI ', + scopes: ['workspaces:read'], + expiresInDays: 30 + }) + expect(result).toEqual({ + ok: true, + data: { echoed: { name: 'CI', scopes: ['workspaces:read'], expiresInDays: 30 } } + }) + }) + + it('registers every channel the preload bridge uses', () => { + expect(CLOUD_API_CHANNELS).toEqual( + expect.arrayContaining([ + 'cloudApi:availability', + 'cloudApi:createApproval', + 'cloudApi:listRoutineRuns', + 'cloudApi:rotateRoutineWebhook' + ]) + ) + }) +}) diff --git a/src/main/cloud-api/cloud-api-ipc.ts b/src/main/cloud-api/cloud-api-ipc.ts new file mode 100644 index 00000000000..baf2da5176e --- /dev/null +++ b/src/main/cloud-api/cloud-api-ipc.ts @@ -0,0 +1,86 @@ +import { ipcMain } from 'electron' +import { z } from 'zod' +import { + CreateCloudApiApprovalInputSchema, + CreateCloudApiKeyInputSchema, + RoutineInputSchema, + RoutinePatchSchema, + RoutineRunsQuerySchema, + type CloudApiResult +} from '../../shared/cloud-api/cloud-api-types' +import type { CloudApiClient } from './cloud-api-client' +import { callCloudApi, getCloudApiAvailability } from './cloud-api-service' + +const Id = z.string().min(1).max(128) +const AuditQuery = z + .object({ + limit: z.number().int().min(1).max(200).optional(), + before: z.number().int().nonnegative().optional() + }) + .strict() +const SettingsInput = z.object({ vmCliEnabled: z.boolean() }).strict() + +type Handler = (...args: unknown[]) => Promise> + +/** Validates renderer input before it reaches the network; bad input never leaves main. */ +function call( + schemas: { [K in keyof A]: z.ZodType }, + run: (client: CloudApiClient, ...args: A) => Promise +): Handler { + return async (...raw) => { + const parsed: unknown[] = [] + for (const [index, schema] of schemas.entries()) { + const result = schema.safeParse(raw[index]) + if (!result.success) { + return { ok: false, error: 'invalid-request' } + } + parsed.push(result.data) + } + return callCloudApi((client) => run(client, ...(parsed as A))) + } +} + +const HANDLERS: Record = { + 'cloudApi:me': call([], (c) => c.me()), + 'cloudApi:listApiKeys': call([], (c) => c.listApiKeys()), + 'cloudApi:createApiKey': call([CreateCloudApiKeyInputSchema], (c, input) => + c.createApiKey(input) + ), + 'cloudApi:revokeApiKey': call([Id], (c, id) => c.revokeApiKey(id)), + 'cloudApi:createApproval': call([CreateCloudApiApprovalInputSchema.optional()], (c, input) => + c.createApproval(input ?? {}) + ), + 'cloudApi:getSettings': call([], (c) => c.getSettings()), + 'cloudApi:putSettings': call([SettingsInput], (c, input) => c.putSettings(input)), + 'cloudApi:listAudit': call([AuditQuery.optional()], (c, q) => c.listAudit(q ?? {})), + 'cloudApi:listProjects': call([], (c) => c.listProjects()), + 'cloudApi:listInstallations': call([], (c) => c.listInstallations()), + 'cloudApi:listRoutines': call([], (c) => c.listRoutines()), + 'cloudApi:createRoutine': call([RoutineInputSchema], (c, input) => c.createRoutine(input)), + 'cloudApi:updateRoutine': call([Id, RoutinePatchSchema], (c, id, patch) => + c.updateRoutine(id, patch) + ), + 'cloudApi:deleteRoutine': call([Id], (c, id) => c.deleteRoutine(id)), + 'cloudApi:runRoutine': call([Id], (c, id) => c.runRoutine(id)), + 'cloudApi:rotateRoutineWebhook': call([Id], (c, id) => c.rotateRoutineWebhook(id)), + 'cloudApi:listRoutineRuns': call([Id, RoutineRunsQuerySchema.optional()], (c, id, q) => + c.listRoutineRuns(id, q ?? {}) + ) +} + +export const CLOUD_API_CHANNELS = ['cloudApi:availability', ...Object.keys(HANDLERS)] + +/** Exposed for tests: the validated handler behind a channel. */ +export function cloudApiHandlerFor(channel: string): Handler | undefined { + return HANDLERS[channel] +} + +export function registerCloudApiHandlers(): void { + for (const channel of CLOUD_API_CHANNELS) { + ipcMain.removeHandler(channel) + } + ipcMain.handle('cloudApi:availability', () => getCloudApiAvailability()) + for (const [channel, handler] of Object.entries(HANDLERS)) { + ipcMain.handle(channel, (_event, ...args: unknown[]) => handler(...args)) + } +} diff --git a/src/main/cloud-api/cloud-api-service.ts b/src/main/cloud-api/cloud-api-service.ts new file mode 100644 index 00000000000..284bd04d5cb --- /dev/null +++ b/src/main/cloud-api/cloud-api-service.ts @@ -0,0 +1,81 @@ +import { app } from 'electron' +// Orca Cloud API access for the desktop settings. Uses the same hosted control plane + session +// token as Orca Cloud sandboxes, so it is only on in builds that configure ORCA_CLOUD_SANDBOX_URL. +// Every call resolves to a CloudApiResult value; nothing throws across IPC and no token is returned. +import type { + CloudApiAvailability, + CloudApiErrorCode, + CloudApiResult +} from '../../shared/cloud-api/cloud-api-types' +import { withCloudBuildDefaults } from '../cloud-build-defaults' +import { EnvironmentProviderError } from '../environment-providers/environment-provider-driver' +import { getHostedSandboxConfig } from '../hosted-sandbox/hosted-sandbox-config' +import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' +import { CloudApiError, createCloudApiClient, type CloudApiClient } from './cloud-api-client' + +let cached: { key: string; client: CloudApiClient; controlPlaneUrl: string } | null = null + +export function classifyTokenError(error: unknown): CloudApiErrorCode { + if (error instanceof EnvironmentProviderError) { + return error.code === 'unauthorized' ? 'signed-out' : 'network' + } + return 'signed-out' +} + +function resolveClient(): { client: CloudApiClient; controlPlaneUrl: string } | null { + const userDataPath = app.getPath('userData') + // Token caches are per profile: switching profiles must never reuse another account's token. + const profileKey = ensureActiveOrcaProfile(userDataPath).profile.id + if (cached?.key === profileKey) { + return cached + } + const config = getHostedSandboxConfig( + userDataPath, + withCloudBuildDefaults(process.env), + app.isPackaged + ) + if (!config) { + cached = null + return null + } + cached = { + key: profileKey, + controlPlaneUrl: config.controlPlaneUrl, + client: createCloudApiClient({ + controlPlaneUrl: config.controlPlaneUrl, + getAccessToken: () => config.getAccessToken(), + classifyTokenError + }) + } + return cached +} + +export function getCloudApiAvailability(): CloudApiAvailability { + const resolved = resolveClient() + return resolved + ? { status: 'ready', controlPlaneUrl: resolved.controlPlaneUrl } + : { status: 'unconfigured' } +} + +export async function callCloudApi( + run: (client: CloudApiClient) => Promise +): Promise> { + const resolved = resolveClient() + if (!resolved) { + return { ok: false, error: 'unconfigured' } + } + try { + return { ok: true, data: await run(resolved.client) } + } catch (error) { + if (error instanceof CloudApiError) { + return { + ok: false, + error: error.code, + ...(error.detail ? { detail: error.detail } : {}), + ...(error.retryAfterSeconds ? { retryAfterSeconds: error.retryAfterSeconds } : {}) + } + } + // Unknown failures stay generic: their messages could carry request internals. + return { ok: false, error: 'server' } + } +} diff --git a/src/main/startup/main-window-core-services.ts b/src/main/startup/main-window-core-services.ts index 463c0a58d89..b8c20424b64 100644 --- a/src/main/startup/main-window-core-services.ts +++ b/src/main/startup/main-window-core-services.ts @@ -1,6 +1,7 @@ import { app, type BrowserWindow } from 'electron' import { registerAgentApiKeyHandlers } from '../agent-api-keys/agent-api-key-ipc' import { registerCloudWorkspacesHandlers } from '../ipc/cloud-workspaces' +import { registerCloudApiHandlers } from '../cloud-api/cloud-api-ipc' import { registerCoreHandlers } from '../ipc/register-core-handlers/register-core-handlers' import { attachMainWindowServices } from '../window/attach-main-window-services' import { initTccPromptNotice } from '../macos-permissions/macos-tcc-prompt-notice' @@ -69,6 +70,7 @@ export function attachMainWindowCoreServices( holdLaunchReconnectOptOuts(store.getSshTargets()) registerAgentApiKeyHandlers(app.getPath('userData')) registerCloudWorkspacesHandlers() + registerCloudApiHandlers() registerCoreHandlers( store, runtime, diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 70a84da0739..bbfe0c45305 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -1,4 +1,5 @@ import type { AgentApiKeysApi } from './api/agent-api-keys-bridge' +import type { CloudApiBridge } from './api/cloud-api-bridge' import type { ClaudeAccountsApi, CodexAccountsApi, @@ -178,6 +179,8 @@ export type PreloadApi = { plainSsh?: PlainSshTerminalApi /** Desktop only: the API keys Orca hands to agent launches. */ agentApiKeys?: AgentApiKeysApi + /** Desktop only: Orca Cloud API keys, org settings and routines (hosted builds). */ + cloudApi?: CloudApiBridge /** COMPAT(legacy-relay-bridge): desktop-only, revisit 2027-01-15. */ legacyRelayBridge?: LegacyRelayBridgeApi automations: AutomationsApi diff --git a/src/preload/api/cloud-api-bridge.ts b/src/preload/api/cloud-api-bridge.ts new file mode 100644 index 00000000000..be9e0bf7784 --- /dev/null +++ b/src/preload/api/cloud-api-bridge.ts @@ -0,0 +1,73 @@ +import { ipcRenderer } from 'electron' +import type { + CloudApiApproval, + CloudApiAuditPage, + CloudApiAvailability, + CloudApiCreatedKey, + CloudApiInstallation, + CloudApiKeyList, + CloudApiMe, + CloudApiProject, + CloudApiResult, + CloudApiSettings, + CreateCloudApiApprovalInput, + CreateCloudApiKeyInput, + Routine, + RoutineCreated, + RoutineInput, + RoutinePatch, + RoutineRun, + RoutineRunPage, + RoutineRunsQuery +} from '../../shared/cloud-api/cloud-api-types' + +/** Desktop only: Orca Cloud API keys, org settings, audit and routines. The session token stays in main. */ +export type CloudApiBridge = { + availability: () => Promise + me: () => Promise> + listApiKeys: () => Promise> + createApiKey: (input: CreateCloudApiKeyInput) => Promise> + revokeApiKey: (id: string) => Promise> + createApproval: (input?: CreateCloudApiApprovalInput) => Promise> + getSettings: () => Promise> + putSettings: (input: { vmCliEnabled: boolean }) => Promise> + listAudit: (query?: { + limit?: number + before?: number + }) => Promise> + listProjects: () => Promise> + listInstallations: () => Promise> + listRoutines: () => Promise> + createRoutine: (input: RoutineInput) => Promise> + updateRoutine: (id: string, patch: RoutinePatch) => Promise> + deleteRoutine: (id: string) => Promise> + runRoutine: (id: string) => Promise> + rotateRoutineWebhook: (id: string) => Promise> + listRoutineRuns: (id: string, query?: RoutineRunsQuery) => Promise> +} + +const invoke = + (channel: string) => + (...args: unknown[]) => + ipcRenderer.invoke(channel, ...args) + +export const cloudApiBridge: CloudApiBridge = { + availability: invoke('cloudApi:availability'), + me: invoke('cloudApi:me'), + listApiKeys: invoke('cloudApi:listApiKeys'), + createApiKey: invoke('cloudApi:createApiKey'), + revokeApiKey: invoke('cloudApi:revokeApiKey'), + createApproval: invoke('cloudApi:createApproval'), + getSettings: invoke('cloudApi:getSettings'), + putSettings: invoke('cloudApi:putSettings'), + listAudit: invoke('cloudApi:listAudit'), + listProjects: invoke('cloudApi:listProjects'), + listInstallations: invoke('cloudApi:listInstallations'), + listRoutines: invoke('cloudApi:listRoutines'), + createRoutine: invoke('cloudApi:createRoutine'), + updateRoutine: invoke('cloudApi:updateRoutine'), + deleteRoutine: invoke('cloudApi:deleteRoutine'), + runRoutine: invoke('cloudApi:runRoutine'), + rotateRoutineWebhook: invoke('cloudApi:rotateRoutineWebhook'), + listRoutineRuns: invoke('cloudApi:listRoutineRuns') +} diff --git a/src/preload/index.ts b/src/preload/index.ts index fe2d93e21ee..c1de3d55d5c 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -91,6 +91,7 @@ import { cursorAccountsApi } from './api/cursor-accounts-bridge' import { sshApi } from './api/ssh-bridge' import { plainSshTerminalApi } from './api/plain-ssh-terminal-bridge' import { agentApiKeysApi } from './api/agent-api-keys-bridge' +import { cloudApiBridge } from './api/cloud-api-bridge' import { legacyRelayBridgeApi } from './api/legacy-relay-bridge-api' import { automationsApi } from './api/automations-bridge' import { e2eApi } from './api/e2e-bridge' @@ -202,6 +203,7 @@ const api = { ssh: sshApi, plainSsh: plainSshTerminalApi, agentApiKeys: agentApiKeysApi, + cloudApi: cloudApiBridge, legacyRelayBridge: legacyRelayBridgeApi, automations: automationsApi, e2e: e2eApi, diff --git a/src/renderer/src/components/settings/cloud-api/ApproveAppDialog.tsx b/src/renderer/src/components/settings/cloud-api/ApproveAppDialog.tsx new file mode 100644 index 00000000000..b972037a036 --- /dev/null +++ b/src/renderer/src/components/settings/cloud-api/ApproveAppDialog.tsx @@ -0,0 +1,226 @@ +import { useEffect, useId, useState } from 'react' +import { Loader2, ShieldCheck, TimerOff } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle +} from '@/components/ui/dialog' +import { Input } from '@/components/ui/input' +import { useTranslate } from '@/i18n/use-translate' +import { cn } from '@/lib/utils' +import type { + CloudApiApproval, + CloudApiResult, + CloudApiScope, + CreateCloudApiApprovalInput +} from '../../../../../shared/cloud-api/cloud-api-types' +import { SettingsSegmentedControl } from '../form-controls/SettingsFormControls' +import { cloudApiErrorCopy } from './cloud-api-copy' +import { formatCountdown, scopesForPreset } from './cloud-api-format' +import { CloudApiErrorNotice, CopyValueButton, ScopeChip } from './cloud-api-parts' + +/** "Approve an app": a one-time code an MCP client's consent page accepts instead of an API key. */ +export function ApproveAppDialog({ + open, + onOpenChange, + availableScopes, + onCreate, + initialApproval, + nowForFixture +}: { + open: boolean + onOpenChange: (open: boolean) => void + availableScopes: readonly CloudApiScope[] + onCreate: (input: CreateCloudApiApprovalInput) => Promise> + initialApproval?: CloudApiApproval + /** Fixtures pin the clock so the countdown is deterministic. */ + nowForFixture?: number +}): React.JSX.Element { + const t = useTranslate() + const ids = useId() + const [access, setAccess] = useState<'read' | 'full'>('full') + const [approval, setApproval] = useState(initialApproval ?? null) + const [busy, setBusy] = useState(false) + const [error, setError] = useState(null) + const [now, setNow] = useState(() => nowForFixture ?? Date.now()) + + useEffect(() => { + if (!approval || nowForFixture !== undefined) { + return + } + const timer = setInterval(() => setNow(Date.now()), 1000) + return () => clearInterval(timer) + }, [approval, nowForFixture]) + + const remaining = approval ? approval.expiresAt - now : 0 + const expired = approval !== null && remaining <= 0 + + const change = (next: boolean): void => { + if (!next) { + // A code never outlives the dialog that showed it. + setApproval(null) + setError(null) + } + onOpenChange(next) + } + + const generate = async (): Promise => { + setBusy(true) + setError(null) + const result = await onCreate( + access === 'full' ? {} : { scopes: scopesForPreset('read', availableScopes) } + ) + setBusy(false) + if (result.ok) { + setNow(Date.now()) + setApproval(result.data) + } else { + setError(cloudApiErrorCopy(result.error, t, result)) + } + } + + return ( + + event.preventDefault() : undefined} + > + + + {t('auto.components.settings.cloudApi.approve.title', 'Approve an app')} + + + {t( + 'auto.components.settings.cloudApi.approve.description', + 'When Claude, Cursor or another MCP client opens the Orca Cloud approval page, paste a one-time code from here instead of an API key.' + )} + + + + {approval ? ( +
+
+ + event.currentTarget.select()} + /> + {expired ? null : ( + + )} +
+

+ {expired ? ( + + ) : ( + + )} + {expired + ? t( + 'auto.components.settings.cloudApi.approve.expired', + 'This code expired. Generate a new one.' + ) + : t( + 'auto.components.settings.cloudApi.approve.expires', + 'Works once and expires in {{value0}}. Orca will not show it again.', + { value0: formatCountdown(remaining) } + )} +

+
+ {approval.scopes.map((scope) => ( + + ))} +
+
+ ) : ( +
+

+ {t('auto.components.settings.cloudApi.approve.access', 'The app may')} +

+ + size="sm" + equalWidth + value={access} + onChange={setAccess} + ariaLabelledBy={`${ids}-access`} + options={[ + { + value: 'read', + label: t('auto.components.settings.cloudApi.approve.read', 'Look, not touch') + }, + { + value: 'full', + label: t('auto.components.settings.cloudApi.approve.full', 'Do anything you can') + } + ]} + /> +

+ {access === 'read' + ? t( + 'auto.components.settings.cloudApi.approve.readHint', + 'List workspaces, projects and routines. It cannot start, change or delete anything.' + ) + : t( + 'auto.components.settings.cloudApi.approve.fullHint', + 'Start and stop workspaces, message agents and manage routines as you.' + )} +

+
+ )} + + {error ? : null} + + + {approval && !expired ? ( + + ) : ( + <> + + + + )} + +
+
+ ) +} diff --git a/src/renderer/src/components/settings/cloud-api/CloudApiKeysPane.tsx b/src/renderer/src/components/settings/cloud-api/CloudApiKeysPane.tsx new file mode 100644 index 00000000000..f7e11d47e09 --- /dev/null +++ b/src/renderer/src/components/settings/cloud-api/CloudApiKeysPane.tsx @@ -0,0 +1,116 @@ +import { useCallback, useEffect, useState } from 'react' +import { useTranslate } from '@/i18n/use-translate' +import type { + CloudApiAuditPage, + CloudApiKeyList, + CloudApiMe, + CloudApiSettings +} from '../../../../../shared/cloud-api/cloud-api-types' +import { CloudApiKeysView } from './CloudApiKeysView' +import { toCloudLoadState, type CloudLoadState } from './cloud-load-state' +import { CloudApiSignedOutNotice } from './CloudApiSignedOutNotice' +import { cloudApiErrorCopy } from './cloud-api-copy' +import { useOrcaCloudApiAvailability } from '@/hooks/useOrcaCloudApiAvailability' + +export function CloudApiKeysPane(): React.JSX.Element | null { + const t = useTranslate() + const availability = useOrcaCloudApiAvailability() + const api = window.api.cloudApi + const [viewer, setViewer] = useState(null) + const [signedOut, setSignedOut] = useState(false) + const [keys, setKeys] = useState>({ status: 'loading' }) + const [settings, setSettings] = useState>({ status: 'loading' }) + const [audit, setAudit] = useState>({ status: 'loading' }) + const [now, setNow] = useState(() => Date.now()) + + const word = useCallback( + (failure: { + error: Parameters[0] + detail?: string + retryAfterSeconds?: number + }) => cloudApiErrorCopy(failure.error, t, failure), + [t] + ) + + const load = useCallback(async (): Promise => { + if (!api) { + return + } + setKeys({ status: 'loading' }) + setSettings({ status: 'loading' }) + const [me, list, current] = await Promise.all([api.me(), api.listApiKeys(), api.getSettings()]) + setSignedOut(!me.ok && me.error === 'signed-out') + setViewer(me.ok ? me.data : null) + setKeys(toCloudLoadState(list, word)) + setSettings(toCloudLoadState(current, word)) + setNow(Date.now()) + }, [api, word]) + + const loadAudit = useCallback(async (): Promise => { + if (!api) { + return + } + setAudit({ status: 'loading' }) + setAudit(toCloudLoadState(await api.listAudit({ limit: 25 }), word)) + setNow(Date.now()) + }, [api, word]) + + useEffect(() => { + if (availability?.status === 'ready') { + void load() + } + }, [availability?.status, load]) + + if (!api || availability?.status !== 'ready') { + return null + } + if (signedOut) { + return void load()} /> + } + return ( + void load()} + onCreate={async (input) => { + const result = await api.createApiKey(input) + if (result.ok) { + // Refresh the list behind the dialog; the secret stays only in the dialog's state. + void api.listApiKeys().then((next) => setKeys(toCloudLoadState(next, word))) + } + return result + }} + onRevoke={async (key) => { + const result = await api.revokeApiKey(key.id) + if (!result.ok && result.error !== 'not-found') { + return word(result) + } + setKeys((current) => + current.status === 'ok' + ? { + status: 'ok', + data: { ...current.data, keys: current.data.keys.filter((k) => k.id !== key.id) } + } + : current + ) + return null + }} + onToggleVmCli={async (vmCliEnabled) => { + const result = await api.putSettings({ vmCliEnabled }) + if (!result.ok) { + return word(result) + } + setSettings({ status: 'ok', data: result.data }) + return null + }} + onLoadAudit={() => void loadAudit()} + onCreateApproval={(input) => api.createApproval(input)} + /> + ) +} diff --git a/src/renderer/src/components/settings/cloud-api/CloudApiKeysSections.tsx b/src/renderer/src/components/settings/cloud-api/CloudApiKeysSections.tsx new file mode 100644 index 00000000000..6784fddd5d9 --- /dev/null +++ b/src/renderer/src/components/settings/cloud-api/CloudApiKeysSections.tsx @@ -0,0 +1,283 @@ +import { useState } from 'react' +import { ExternalLink, History, ShieldCheck } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Switch } from '@/components/ui/switch' +import { useIntlLocale, useTranslate, type Translate } from '@/i18n/use-translate' +import type { + CloudApiAuditEntry, + CloudApiAuditPage, + CloudApiMe, + CloudApiSettings +} from '../../../../../shared/cloud-api/cloud-api-types' +import { SettingsGroup } from '../section-layout/SettingsGroup' +import { formatAbsoluteTime, formatRelativeFromNow } from './cloud-api-format' +import { CloudApiErrorNotice, CloudApiSkeletonRows, CopyValueButton } from './cloud-api-parts' +import type { CloudLoadState } from './cloud-load-state' + +function LinkRow({ + label, + description, + url, + copyLabel, + openLabel, + extra +}: { + label: string + description: string + url: string + copyLabel: string + openLabel?: string + extra?: React.ReactNode +}): React.JSX.Element { + return ( +
+
+

{label}

+

{description}

+ + {url} + +
+
+ {extra} + {openLabel ? ( + + ) : null} + +
+
+ ) +} + +export function AccessLinks({ + controlPlaneUrl, + onApprove +}: { + controlPlaneUrl: string + onApprove: () => void +}): React.JSX.Element { + const t = useTranslate() + const base = controlPlaneUrl.replace(/\/+$/, '') + return ( + + + + + {t('auto.components.settings.cloudApi.links.approve', 'Approve an app…')} + + } + /> + + ) +} + +export function OrgSettings({ + settings, + onToggle +}: { + settings: CloudLoadState + onToggle: (enabled: boolean) => Promise +}): React.JSX.Element { + const t = useTranslate() + const [pending, setPending] = useState(null) + const [error, setError] = useState(null) + const labelId = 'cloud-api-vm-cli-label' + const descriptionId = 'cloud-api-vm-cli-description' + const current = settings.status === 'ok' ? settings.data.settings.vmCliEnabled : false + const canEdit = settings.status === 'ok' && settings.data.canEdit + const toggle = async (next: boolean): Promise => { + setPending(next) + setError(null) + const failure = await onToggle(next) + setPending(null) + setError(failure) + } + return ( + +
+
+

+ {t( + 'auto.components.settings.cloudApi.org.vmCli', + 'Let agents in cloud workspaces create workspaces' + )} +

+

+ {t( + 'auto.components.settings.cloudApi.org.vmCliBody', + 'Agents get a short-lived token for the orca CLI inside their VM, so they can start sibling workspaces and hand work to other agents. Turning this off revokes every outstanding token at once.' + )} + {settings.status === 'ok' && !canEdit + ? ` ${t( + 'auto.components.settings.cloudApi.org.adminOnly', + 'Only org owners and admins can change this.' + )}` + : null} +

+ {settings.status === 'error' ? ( +

{settings.message}

+ ) : null} + {error ? ( +

+ {error} +

+ ) : null} +
+ void toggle(next)} + /> +
+
+ ) +} + +function actorLabel(entry: CloudApiAuditEntry, viewer: CloudApiMe | null, t: Translate): string { + const who = + entry.actor.userId && entry.actor.userId === viewer?.userId + ? t('auto.components.settings.cloudApi.audit.you', 'You') + : (entry.actor.userId ?? entry.actor.id) + if (entry.actor.type === 'api_key') { + return t('auto.components.settings.cloudApi.audit.viaKey', '{{value0}} via API key', { + value0: who + }) + } + if (entry.actor.type === 'mcp') { + return t('auto.components.settings.cloudApi.audit.viaMcp', '{{value0}} via MCP', { + value0: who + }) + } + if (entry.actor.type === 'workspace_token') { + return t('auto.components.settings.cloudApi.audit.viaAgent', 'Agent in a cloud workspace') + } + return who +} + +export function AuditLog({ + audit, + now, + viewer, + initiallyOpen, + onLoad +}: { + audit: CloudLoadState + now: number + viewer: CloudApiMe | null + initiallyOpen: boolean + onLoad: () => void +}): React.JSX.Element { + const t = useTranslate() + const locale = useIntlLocale() + const [open, setOpen] = useState(initiallyOpen) + return ( + { + if (!open) { + onLoad() + } + setOpen(!open) + }} + > + + {open + ? t('auto.components.settings.cloudApi.audit.hide', 'Hide') + : t('auto.components.settings.cloudApi.audit.show', 'Show activity')} + + } + bodyClassName={open ? undefined : 'hidden'} + > + {!open ? null : audit.status === 'loading' ? ( + + ) : audit.status === 'error' ? ( +
+ +
+ ) : audit.data.entries.length === 0 ? ( +

+ {t('auto.components.settings.cloudApi.audit.empty', 'Nothing has happened yet.')} +

+ ) : ( +
    + {audit.data.entries.slice(0, 25).map((entry) => ( +
  • + + {entry.action} + + + {actorLabel(entry, viewer, t)} + {entry.target?.id ? ` · ${entry.target.id}` : ''} + + + {formatRelativeFromNow(entry.createdAt, now, locale)} + +
  • + ))} +
+ )} +
+ ) +} diff --git a/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.fixture.tsx b/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.fixture.tsx new file mode 100644 index 00000000000..2c1d8f3ee02 --- /dev/null +++ b/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.fixture.tsx @@ -0,0 +1,235 @@ +import { defineFixture } from '../../../component-fixtures/component-fixture' +import type { + CloudApiAuditPage, + CloudApiKeyList, + CloudApiMe, + CloudApiSettings +} from '../../../../../shared/cloud-api/cloud-api-types' +import { CLOUD_API_SCOPES } from '../../../../../shared/cloud-api/cloud-api-types' +import { CloudApiKeysView, type CloudApiKeysViewProps } from './CloudApiKeysView' + +const NOW = Date.UTC(2026, 10, 9, 15, 0) +const MIN = 60_000 +const DAY = 86_400_000 + +const ADMIN: CloudApiMe = { + accountId: 'org:acme', + userId: 'u_ada', + orgId: 'acme', + role: 'admin', + scopes: [...CLOUD_API_SCOPES] +} +const MEMBER: CloudApiMe = { + ...ADMIN, + userId: 'u_linus', + role: 'member', + scopes: CLOUD_API_SCOPES.filter((s) => s !== 'audit:read') +} + +const KEYS: CloudApiKeyList = { + availableScopes: [...CLOUD_API_SCOPES], + keys: [ + { + id: 'key_ci', + name: 'GitHub Actions deploy', + prefix: 'orca_sk_Ab3x', + scopes: ['workspaces:read', 'workspaces:write', 'messages:write'], + createdBy: 'u_ada', + createdAt: NOW - 3 * DAY, + lastUsedAt: NOW - 5 * MIN, + expiresAt: NOW + 87 * DAY + }, + { + id: 'key_dash', + name: 'Grafana dashboard', + prefix: 'orca_sk_Q9zL', + scopes: ['workspaces:read', 'projects:read', 'routines:read'], + createdBy: 'grace@acme.dev', + createdAt: NOW - 40 * DAY, + lastUsedAt: NOW - 2 * 3_600_000, + expiresAt: null + }, + { + id: 'key_old', + name: 'Laptop script', + prefix: 'orca_sk_m2Pe', + scopes: [...CLOUD_API_SCOPES], + createdBy: 'u_ada', + createdAt: NOW - 85 * DAY, + lastUsedAt: null, + expiresAt: NOW + 4 * DAY + } + ] +} + +const SETTINGS: CloudApiSettings = { settings: { vmCliEnabled: true }, canEdit: true } +const AUDIT: CloudApiAuditPage = { + nextBefore: null, + entries: [ + { + id: 'a1', + actor: { type: 'user', id: 'u_ada', userId: 'u_ada' }, + action: 'api_key.create', + target: { type: 'api_key', id: 'key_ci' }, + createdAt: NOW - 3 * DAY + }, + { + id: 'a2', + actor: { type: 'api_key', id: 'key_ci', userId: 'u_ada' }, + action: 'workspace.create', + target: { type: 'workspace', id: 'sbx_7Hq2' }, + createdAt: NOW - 5 * MIN + }, + { + id: 'a3', + actor: { type: 'workspace_token', id: 'key_ws', userId: 'u_ada' }, + action: 'workspace.message', + target: { type: 'workspace', id: 'sbx_7Hq2' }, + createdAt: NOW - 2 * MIN + } + ] +} + +const base: CloudApiKeysViewProps = { + controlPlaneUrl: 'https://api.orca.dev', + viewer: ADMIN, + keys: { status: 'ok', data: KEYS }, + settings: { status: 'ok', data: SETTINGS }, + audit: { status: 'ok', data: AUDIT }, + now: NOW, + onRefresh: () => {}, + onCreate: async () => ({ ok: false, error: 'server' }), + onRevoke: async () => null, + onToggleVmCli: async () => null, + onLoadAudit: () => {}, + onCreateApproval: async () => ({ ok: false, error: 'server' }) +} + +export const list = defineFixture({ + width: 760, + render: () => +}) + +export const listWithActivity = defineFixture({ + width: 760, + render: () => +}) + +export const empty = defineFixture({ + width: 760, + render: () => ( + + ) +}) + +export const loading = defineFixture({ + width: 760, + render: () => ( + + ) +}) + +export const error = defineFixture({ + width: 760, + render: () => ( + + ) +}) + +export const memberView = defineFixture({ + width: 760, + render: () => ( + + ) +}) + +export const createDialog = defineFixture({ + width: 760, + render: () => +}) + +export const createDialogMemberCustom = defineFixture({ + width: 760, + render: () => ( + + ), + interact: async () => { + const custom = [...document.querySelectorAll('[role="radio"]')].find( + (button) => button.textContent === 'Custom' + ) + custom?.click() + } +}) + +export const justCreated = defineFixture({ + width: 760, + render: () => ( + + ) +}) + +export const revokeConfirm = defineFixture({ + width: 760, + render: () => +}) + +export const approveAppCode = defineFixture({ + width: 760, + render: () => ( + + ) +}) diff --git a/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.tsx b/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.tsx new file mode 100644 index 00000000000..94aaf2a2a7e --- /dev/null +++ b/src/renderer/src/components/settings/cloud-api/CloudApiKeysView.tsx @@ -0,0 +1,310 @@ +import { useState } from 'react' +import { KeyRound, Plus, RefreshCw, Trash2 } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { useIntlLocale, useTranslate, type Translate } from '@/i18n/use-translate' +import { cn } from '@/lib/utils' +import type { + CloudApiApproval, + CloudApiAuditPage, + CloudApiCreatedKey, + CloudApiKey, + CloudApiKeyList, + CloudApiMe, + CloudApiResult, + CloudApiSettings, + CreateCloudApiApprovalInput, + CreateCloudApiKeyInput +} from '../../../../../shared/cloud-api/cloud-api-types' +import { SettingsGroup } from '../section-layout/SettingsGroup' +import { ApproveAppDialog } from './ApproveAppDialog' +import { AccessLinks, AuditLog, OrgSettings } from './CloudApiKeysSections' +import { CloudConfirmDialog } from './CloudConfirmDialog' +import type { CloudLoadState } from './cloud-load-state' +import { CreateApiKeyDialog } from './CreateApiKeyDialog' +import { formatAbsoluteTime, formatKeyPrefix, formatRelativeFromNow } from './cloud-api-format' +import { + CloudApiEmptyState, + CloudApiErrorNotice, + CloudApiSkeletonRows, + ScopeChip +} from './cloud-api-parts' + +const EXPIRY_WARNING_MS = 7 * 86_400_000 + +export type CloudApiKeysViewProps = { + controlPlaneUrl: string + viewer: CloudApiMe | null + keys: CloudLoadState + settings: CloudLoadState + /** Null hides the activity log (members cannot read it). */ + audit: CloudLoadState | null + now: number + onRefresh: () => void + onCreate: (input: CreateCloudApiKeyInput) => Promise> + /** Resolves to an error message or null. */ + onRevoke: (key: CloudApiKey) => Promise + onToggleVmCli: (enabled: boolean) => Promise + onLoadAudit: () => void + onCreateApproval: ( + input: CreateCloudApiApprovalInput + ) => Promise> + /** Fixtures: start with a dialog open (and a pinned clock for countdowns). */ + initial?: { + create?: boolean + created?: CloudApiCreatedKey + revokeKeyId?: string + auditOpen?: boolean + approve?: boolean + approval?: CloudApiApproval + } +} + +function isAdmin(viewer: CloudApiMe | null): boolean { + return viewer !== null && viewer.role !== 'member' +} + +export function CloudApiKeysView(props: CloudApiKeysViewProps): React.JSX.Element { + const t = useTranslate() + const { keys, viewer, initial } = props + const [createOpen, setCreateOpen] = useState(Boolean(initial?.create || initial?.created)) + // The target outlives the open flag so the title does not blank out during the close animation. + const [revoking, setRevoking] = useState(() => + initial?.revokeKeyId && keys.status === 'ok' + ? (keys.data.keys.find((key) => key.id === initial.revokeKeyId) ?? null) + : null + ) + const [revokeOpen, setRevokeOpen] = useState(revoking !== null) + const [approveOpen, setApproveOpen] = useState(Boolean(initial?.approve || initial?.approval)) + const available = keys.status === 'ok' ? keys.data.availableScopes : (viewer?.scopes ?? []) + const orgAdmin = Boolean(viewer?.orgId) && isAdmin(viewer) + + const createButton = ( + + ) + + return ( +
+ + + {keys.status === 'ok' && keys.data.keys.length > 0 ? createButton : null} +
+ } + > + {keys.status === 'loading' ? ( + + ) : keys.status === 'error' ? ( +
+ +
+ ) : keys.data.keys.length === 0 ? ( + + ) : ( +
    + {keys.data.keys.map((key) => ( + { + setRevoking(key) + setRevokeOpen(true) + }} + /> + ))} +
+ )} + + + setApproveOpen(true)} /> + + + + {props.audit ? ( + + ) : null} + + + + + {t( + 'auto.components.settings.cloudApi.revoke.body', + 'Anything using {{value0}} stops working immediately. This cannot be undone.', + { value0: revoking ? formatKeyPrefix(revoking.prefix) : '' } + )} +

+ } + confirmLabel={t('auto.components.settings.cloudApi.revoke.confirm', 'Revoke key')} + onConfirm={async () => (revoking ? props.onRevoke(revoking) : null)} + /> + + ) +} + +function creatorLabel(key: CloudApiKey, viewer: CloudApiMe | null, t: Translate): string { + return viewer?.userId === key.createdBy + ? t('auto.components.settings.cloudApi.keys.createdByYou', 'you') + : key.createdBy +} + +function KeyRow({ + apiKey, + viewer, + now, + onRevoke +}: { + apiKey: CloudApiKey + viewer: CloudApiMe | null + now: number + onRevoke: () => void +}): React.JSX.Element { + const t = useTranslate() + const locale = useIntlLocale() + const expiresSoon = apiKey.expiresAt !== null && apiKey.expiresAt - now < EXPIRY_WARNING_MS + return ( +
  • +
    + +
    +
    +
    +

    {apiKey.name}

    + + {formatKeyPrefix(apiKey.prefix)} + +
    +
    + {apiKey.scopes.map((scope) => ( + + ))} +
    +

    + + {t( + 'auto.components.settings.cloudApi.keys.created', + 'Created by {{value0}} {{value1}}', + { + value0: creatorLabel(apiKey, viewer, t), + value1: formatRelativeFromNow(apiKey.createdAt, now, locale) + } + )} + + · + + {apiKey.lastUsedAt + ? t('auto.components.settings.cloudApi.keys.lastUsed', 'Last used {{value0}}', { + value0: formatRelativeFromNow(apiKey.lastUsedAt, now, locale) + }) + : t('auto.components.settings.cloudApi.keys.neverUsed', 'Never used')} + + {apiKey.expiresAt !== null ? ( + <> + · + + {apiKey.expiresAt <= now + ? t('auto.components.settings.cloudApi.keys.expired', 'Expired') + : t('auto.components.settings.cloudApi.keys.expires', 'Expires {{value0}}', { + value0: formatRelativeFromNow(apiKey.expiresAt, now, locale) + })} + + + ) : null} +

    +
    + +
  • + ) +} diff --git a/src/renderer/src/components/settings/cloud-api/CloudApiSignedOutNotice.tsx b/src/renderer/src/components/settings/cloud-api/CloudApiSignedOutNotice.tsx new file mode 100644 index 00000000000..e68314b4a45 --- /dev/null +++ b/src/renderer/src/components/settings/cloud-api/CloudApiSignedOutNotice.tsx @@ -0,0 +1,33 @@ +import { CircleUserRound, RefreshCw } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { useTranslate } from '@/i18n/use-translate' +import { OrcaSignInButton } from '../../OrcaSignInProgress' +import { SettingsGroup } from '../section-layout/SettingsGroup' +import { CloudApiEmptyState } from './cloud-api-parts' + +export function CloudApiSignedOutNotice({ onRetry }: { onRetry: () => void }): React.JSX.Element { + const t = useTranslate() + return ( + + + + {t('auto.components.settings.cloudApi.signedOut.signIn', 'Sign in to Orca')} + + + + } + /> + + ) +} diff --git a/src/renderer/src/components/settings/cloud-api/CloudConfirmDialog.tsx b/src/renderer/src/components/settings/cloud-api/CloudConfirmDialog.tsx new file mode 100644 index 00000000000..b3dedcc0224 --- /dev/null +++ b/src/renderer/src/components/settings/cloud-api/CloudConfirmDialog.tsx @@ -0,0 +1,91 @@ +import { useState } from 'react' +import { Loader2 } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle +} from '@/components/ui/dialog' +import { useTranslate } from '@/i18n/use-translate' +import { CloudApiErrorNotice } from './cloud-api-parts' + +/** A destructive confirmation that stays open (with the error) when the action fails. */ +export function CloudConfirmDialog({ + open, + onOpenChange, + title, + description, + confirmLabel, + onConfirm, + destructive = true +}: { + open: boolean + onOpenChange: (open: boolean) => void + title: string + description: React.ReactNode + confirmLabel: string + /** Resolves to an error message, or null on success (the dialog then closes). */ + onConfirm: () => Promise + destructive?: boolean +}): React.JSX.Element { + const t = useTranslate() + const [busy, setBusy] = useState(false) + const [error, setError] = useState(null) + const change = (next: boolean): void => { + if (busy) { + return + } + if (!next) { + setError(null) + } + onOpenChange(next) + } + const confirm = async (): Promise => { + setBusy(true) + setError(null) + const failure = await onConfirm() + setBusy(false) + if (failure) { + setError(failure) + return + } + onOpenChange(false) + } + return ( + + + + {title} + +
    {description}
    +
    +
    + {error ? : null} + + + + +
    +
    + ) +} diff --git a/src/renderer/src/components/settings/cloud-api/CloudRoutinesPane.tsx b/src/renderer/src/components/settings/cloud-api/CloudRoutinesPane.tsx new file mode 100644 index 00000000000..5bbb2a13347 --- /dev/null +++ b/src/renderer/src/components/settings/cloud-api/CloudRoutinesPane.tsx @@ -0,0 +1,139 @@ +import { useCallback, useEffect, useMemo, useState } from 'react' +import { useTranslate } from '@/i18n/use-translate' +import type { + CloudApiInstallation, + CloudApiProject, + Routine +} from '../../../../../shared/cloud-api/cloud-api-types' +import { CloudApiSignedOutNotice } from './CloudApiSignedOutNotice' +import { CloudRoutinesView } from './CloudRoutinesView' +import { cloudApiErrorCopy } from './cloud-api-copy' +import { localTimeZone } from './cloud-api-format' +import { toCloudLoadState, type CloudApiFailure, type CloudLoadState } from './cloud-load-state' +import { useOrcaCloudApiAvailability } from '@/hooks/useOrcaCloudApiAvailability' + +const RUNS_PAGE_SIZE = 20 + +export function CloudRoutinesPane(): React.JSX.Element | null { + const t = useTranslate() + const availability = useOrcaCloudApiAvailability() + const api = window.api.cloudApi + const [routines, setRoutines] = useState>({ status: 'loading' }) + const [projects, setProjects] = useState([]) + const [installations, setInstallations] = useState(null) + const [now, setNow] = useState(() => Date.now()) + const timezone = useMemo(() => localTimeZone(), []) + const word = useCallback( + (failure: CloudApiFailure) => cloudApiErrorCopy(failure.error, t, failure), + [t] + ) + + const load = useCallback(async (): Promise => { + if (!api) { + return + } + setRoutines({ status: 'loading' }) + const [list, projectList, installs] = await Promise.all([ + api.listRoutines(), + api.listProjects(), + api.listInstallations() + ]) + setRoutines(toCloudLoadState(list.ok ? { ok: true, data: list.data.routines } : list, word)) + setProjects(projectList.ok ? projectList.data.projects : []) + setInstallations(installs.ok ? installs.data.installations : null) + setNow(Date.now()) + }, [api, word]) + + // Stable identity: the run history reloads whenever this function changes. + const loadRuns = useCallback( + (routineId: string, before?: number | string) => + api + ? api.listRoutineRuns(routineId, { + limit: RUNS_PAGE_SIZE, + ...(before !== undefined ? { before } : {}) + }) + : Promise.resolve({ ok: false as const, error: 'unconfigured' as const }), + [api] + ) + + useEffect(() => { + if (availability?.status === 'ready') { + void load() + } + }, [availability?.status, load]) + + const replace = (routine: Routine): void => + setRoutines((current) => + current.status === 'ok' + ? { status: 'ok', data: current.data.map((r) => (r.id === routine.id ? routine : r)) } + : current + ) + + if (!api || availability?.status !== 'ready') { + return null + } + if (routines.status === 'error' && routines.code === 'signed-out') { + return void load()} /> + } + return ( + void load()} + onCreate={async (input) => { + const result = await api.createRoutine(input) + if (result.ok) { + setRoutines((current) => + current.status === 'ok' + ? { status: 'ok', data: [result.data.routine, ...current.data] } + : current + ) + } + return result + }} + onUpdate={async (id, patch) => { + const result = await api.updateRoutine(id, patch) + if (result.ok) { + replace(result.data.routine) + } + return result + }} + onToggle={async (routine, enabled) => { + const result = await api.updateRoutine(routine.id, { enabled }) + if (!result.ok) { + return word(result) + } + replace(result.data.routine) + return null + }} + onRunNow={async (routine) => { + const result = await api.runRoutine(routine.id) + if (!result.ok) { + return word(result) + } + replace({ + ...routine, + lastRun: { id: result.data.run.id, status: result.data.run.status, finishedAt: null } + }) + return null + }} + onDelete={async (routine) => { + const result = await api.deleteRoutine(routine.id) + if (!result.ok && result.error !== 'not-found') { + return word(result) + } + setRoutines((current) => + current.status === 'ok' + ? { status: 'ok', data: current.data.filter((r) => r.id !== routine.id) } + : current + ) + return null + }} + onRotateWebhook={(routine) => api.rotateRoutineWebhook(routine.id)} + loadRuns={loadRuns} + /> + ) +} diff --git a/src/renderer/src/components/settings/cloud-api/CloudRoutinesView.fixture.tsx b/src/renderer/src/components/settings/cloud-api/CloudRoutinesView.fixture.tsx new file mode 100644 index 00000000000..371e479cffa --- /dev/null +++ b/src/renderer/src/components/settings/cloud-api/CloudRoutinesView.fixture.tsx @@ -0,0 +1,305 @@ +import { defineFixture } from '../../../component-fixtures/component-fixture' +import type { + CloudApiProject, + Routine, + RoutineRun, + RoutineRunPage +} from '../../../../../shared/cloud-api/cloud-api-types' +import { CloudRoutinesView, type CloudRoutinesViewProps } from './CloudRoutinesView' +import type { LoadRoutineRuns } from './RoutineRunHistory' + +const NOW = Date.UTC(2026, 10, 9, 15, 0) +const MIN = 60_000 +const HOUR = 3_600_000 + +const PROJECTS: CloudApiProject[] = [ + { id: 'prj_api', name: 'acme/api', repo: { url: 'https://github.com/acme/api', ref: 'main' } }, + { id: 'prj_web', name: 'acme/web', repo: { url: 'https://github.com/acme/web', ref: null } } +] + +const base = { + createdBy: 'u_ada', + createdAt: NOW - 20 * 24 * HOUR, + updatedAt: NOW - 2 * HOUR, + machineSize: 'standard', + maxRuntimeMinutes: 30 +} + +const ROUTINES: Routine[] = [ + { + ...base, + id: 'rt_triage', + name: 'Triage new issues', + projectId: 'prj_api', + repo: null, + enabled: true, + trigger: { kind: 'schedule', cron: '0 9 * * 1-5', timezone: 'America/New_York' }, + agent: 'claude', + prompt: 'Label and summarize every issue opened since yesterday.', + postResults: 'comment', + nextRunAt: NOW + 3 * HOUR, + lastRun: { id: 'run_1', status: 'succeeded', finishedAt: NOW - 21 * HOUR } + }, + { + ...base, + id: 'rt_review', + name: 'Review PRs labeled orca', + projectId: null, + repo: { url: 'https://github.com/acme/web', ref: null }, + enabled: true, + trigger: { kind: 'github', events: ['pull_request.labeled'], labels: ['orca'] }, + agent: 'codex', + prompt: 'Review the pull request for bugs and missing tests.', + postResults: 'comment', + nextRunAt: null, + lastRun: { id: 'run_2', status: 'running', finishedAt: null } + }, + { + ...base, + id: 'rt_fix', + name: 'Fix flaky test from CI', + projectId: 'prj_api', + repo: null, + enabled: false, + trigger: { kind: 'webhook', urlHint: '…/hooks/rt_fix/••••Qz8' }, + agent: 'claude', + prompt: 'Reproduce the failing test from the payload and open a PR with a fix.', + postResults: 'pr', + nextRunAt: null, + lastRun: { id: 'run_3', status: 'failed', finishedAt: NOW - 3 * 24 * HOUR } + }, + { + ...base, + id: 'rt_weekly', + name: 'Weekly dependency bump', + projectId: 'prj_web', + repo: null, + enabled: true, + trigger: { kind: 'schedule', cron: '30 6 * * 1', timezone: 'Europe/Berlin' }, + agent: 'claude', + prompt: 'Update minor dependencies and open a PR if tests pass.', + postResults: 'pr', + nextRunAt: NOW + 2 * 24 * HOUR, + lastRun: null + } +] + +const run = (partial: Partial & Pick): RoutineRun => ({ + routineId: 'rt_triage', + trigger: 'schedule', + triggerDetail: null, + workspaceId: null, + result: null, + error: null, + createdAt: NOW - HOUR, + startedAt: NOW - HOUR, + finishedAt: null, + durationMs: null, + ...partial +}) + +const RUNS: RoutineRunPage = { + nextBefore: NOW - 5 * 24 * HOUR, + runs: [ + run({ + id: 'r6', + status: 'running', + trigger: 'manual', + startedAt: NOW - 2 * MIN, + workspaceId: 'sbx_7Hq2Lm' + }), + run({ + id: 'r5', + status: 'posting', + trigger: 'github', + triggerDetail: 'acme/web#482 labeled orca', + startedAt: NOW - 9 * MIN, + workspaceId: 'sbx_P0wQ1e' + }), + run({ + id: 'r4', + status: 'succeeded', + startedAt: NOW - 21 * HOUR, + durationMs: 4 * MIN + 12_000, + workspaceId: 'sbx_c8Rk2a', + result: { + summary: 'Labeled 6 issues, closed 2 duplicates and asked for repro steps on #311.', + commentUrl: 'https://github.com/acme/api/issues/311#issuecomment-1' + } + }), + run({ + id: 'r3', + status: 'succeeded', + trigger: 'webhook', + triggerDetail: 'POST from ci.acme.dev', + startedAt: NOW - 30 * HOUR, + durationMs: 11 * MIN + 3_000, + result: { prUrl: 'https://github.com/acme/api/pull/512' } + }), + run({ + id: 'r2', + status: 'failed', + startedAt: NOW - 45 * HOUR, + durationMs: 38_000, + error: + 'The agent could not clone acme/api: the Orca Cloud GitHub App is not installed on this repository.' + }), + run({ id: 'r1', status: 'timed_out', startedAt: NOW - 69 * HOUR, durationMs: 30 * MIN }), + run({ + id: 'r0', + status: 'cancelled', + trigger: 'manual', + startedAt: NOW - 70 * HOUR, + durationMs: 15_000 + }) + ] +} + +const loadRuns: LoadRoutineRuns = async () => ({ ok: true, data: RUNS }) +const loadNoRuns: LoadRoutineRuns = async () => ({ ok: true, data: { runs: [], nextBefore: null } }) +const loadRunsFailing: LoadRoutineRuns = async () => ({ ok: false, error: 'network' }) + +const props: CloudRoutinesViewProps = { + routines: { status: 'ok', data: ROUTINES }, + projects: PROJECTS, + installations: [{ installationId: '1', account: 'acme', accountType: 'Organization' }], + now: NOW, + localTimezone: 'America/New_York', + onRefresh: () => {}, + onCreate: async () => ({ ok: false, error: 'server' }), + onUpdate: async () => ({ ok: false, error: 'server' }), + onToggle: async () => null, + onRunNow: async () => null, + onDelete: async () => null, + onRotateWebhook: async () => ({ + ok: true, + data: { url: 'https://api.orca.dev/hooks/rt_fix/n3wS3cr3tQz8xK' } + }), + loadRuns +} + +export const list = defineFixture({ width: 820, render: () => }) + +export const empty = defineFixture({ + width: 820, + render: () => +}) + +export const loading = defineFixture({ + width: 820, + render: () => +}) + +export const error = defineFixture({ + width: 820, + render: () => ( + + ) +}) + +export const notAvailable = defineFixture({ + width: 820, + render: () => ( + + ) +}) + +export const runHistory = defineFixture({ + width: 820, + render: () => +}) + +export const runHistoryEmpty = defineFixture({ + width: 820, + render: () => ( + + ) +}) + +export const runHistoryError = defineFixture({ + width: 820, + render: () => ( + + ) +}) + +export const editorSchedule = defineFixture({ + width: 820, + render: () => +}) + +export const editorCustomCron = defineFixture({ + width: 820, + render: () => ( + + ) +}) + +export const editorGithub = defineFixture({ + width: 820, + render: () => +}) + +export const editorWebhook = defineFixture({ + width: 820, + render: () => +}) + +export const editorValidation = defineFixture({ + width: 820, + render: () => ( + + ), + interact: async () => { + document + .querySelector('[data-routine-editor] button[type="submit"]') + ?.click() + } +}) + +export const webhookCreated = defineFixture({ + width: 820, + render: () => ( + + ) +}) + +export const deleteConfirm = defineFixture({ + width: 820, + render: () => +}) diff --git a/src/renderer/src/components/settings/cloud-api/CloudRoutinesView.tsx b/src/renderer/src/components/settings/cloud-api/CloudRoutinesView.tsx new file mode 100644 index 00000000000..1a688e54777 --- /dev/null +++ b/src/renderer/src/components/settings/cloud-api/CloudRoutinesView.tsx @@ -0,0 +1,453 @@ +import { useState } from 'react' +import { + CalendarClock, + ChevronDown, + Github, + Loader2, + MoreHorizontal, + Pencil, + Play, + Plus, + RefreshCw, + Trash2, + Webhook +} from 'lucide-react' +import { Button } from '@/components/ui/button' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger +} from '@/components/ui/dropdown-menu' +import { Switch } from '@/components/ui/switch' +import { useIntlLocale, useTranslate } from '@/i18n/use-translate' +import { cn } from '@/lib/utils' +import type { + CloudApiInstallation, + CloudApiProject, + CloudApiResult, + Routine, + RoutineCreated, + RoutineInput, + RoutinePatch +} from '../../../../../shared/cloud-api/cloud-api-types' +import { SettingsBadge } from '../form-controls/SettingsFormControls' +import { SettingsGroup } from '../section-layout/SettingsGroup' +import { CloudConfirmDialog } from './CloudConfirmDialog' +import { RoutineEditorDialog } from './RoutineEditorDialog' +import { RoutineRunHistory, type LoadRoutineRuns } from './RoutineRunHistory' +import { + describeRoutineTrigger, + formatAbsoluteTime, + formatRelativeFromNow +} from './cloud-api-format' +import { + CloudApiEmptyState, + CloudApiErrorNotice, + CloudApiSkeletonRows, + RoutineRunStatusPill +} from './cloud-api-parts' +import type { CloudLoadState } from './cloud-load-state' +import type { RoutineDraft } from './routine-draft' + +export type CloudRoutinesViewProps = { + routines: CloudLoadState + projects: readonly CloudApiProject[] + installations: readonly CloudApiInstallation[] | null + now: number + localTimezone: string + onRefresh: () => void + onCreate: (input: RoutineInput) => Promise> + onUpdate: (id: string, patch: RoutinePatch) => Promise> + /** Each resolves to an error message or null. */ + onToggle: (routine: Routine, enabled: boolean) => Promise + onRunNow: (routine: Routine) => Promise + onDelete: (routine: Routine) => Promise + onRotateWebhook: (routine: Routine) => Promise> + loadRuns: LoadRoutineRuns + /** Fixtures: start with the editor, history or delete confirmation open. */ + initial?: { + editor?: { routineId: string | null; draft?: Partial; webhookUrl?: string } + historyFor?: string + deleteId?: string + } +} + +export function CloudRoutinesView(props: CloudRoutinesViewProps): React.JSX.Element { + const t = useTranslate() + const { routines, initial } = props + const list = routines.status === 'ok' ? routines.data : [] + const find = (id: string | null | undefined): Routine | null => + list.find((routine) => routine.id === id) ?? null + + const [editorOpen, setEditorOpen] = useState(Boolean(initial?.editor)) + const [editing, setEditing] = useState(() => find(initial?.editor?.routineId)) + const [deleting, setDeleting] = useState(() => find(initial?.deleteId)) + const [deleteOpen, setDeleteOpen] = useState(Boolean(initial?.deleteId)) + const [expanded, setExpanded] = useState(initial?.historyFor ?? null) + const [historyRefresh, setHistoryRefresh] = useState(0) + + const openEditor = (routine: Routine | null): void => { + setEditing(routine) + setEditorOpen(true) + } + const newButton = ( + + ) + const unavailable = routines.status === 'error' && routines.code === 'not-available' + + return ( +
    + + + {routines.status === 'ok' && list.length > 0 ? newButton : null} +
    + ) + } + > + {routines.status === 'loading' ? ( + + ) : unavailable ? ( + + ) : routines.status === 'error' ? ( +
    + +
    + ) : list.length === 0 ? ( + + ) : ( +
      + {list.map((routine) => ( + setExpanded(expanded === routine.id ? null : routine.id)} + onEdit={() => openEditor(routine)} + onDelete={() => { + setDeleting(routine) + setDeleteOpen(true) + }} + onToggle={(enabled) => props.onToggle(routine, enabled)} + onRunNow={async () => { + const failure = await props.onRunNow(routine) + if (!failure) { + setExpanded(routine.id) + setHistoryRefresh((value) => value + 1) + } + return failure + }} + /> + ))} +
    + )} + + + + + {t( + 'auto.components.settings.cloudRoutines.delete.body', + 'It stops running and its run history is deleted. Workspaces it already started are not affected.' + )} +

    + } + confirmLabel={t('auto.components.settings.cloudRoutines.delete.confirm', 'Delete routine')} + onConfirm={async () => (deleting ? props.onDelete(deleting) : null)} + /> + + ) +} + +function TriggerIcon({ kind }: { kind: Routine['trigger']['kind'] }): React.JSX.Element { + const Icon = kind === 'schedule' ? CalendarClock : kind === 'github' ? Github : Webhook + return ( +
    + +
    + ) +} + +function RoutineRow({ + routine, + projects, + now, + expanded, + historyRefresh, + loadRuns, + onToggleHistory, + onEdit, + onDelete, + onToggle, + onRunNow +}: { + routine: Routine + projects: readonly CloudApiProject[] + now: number + expanded: boolean + historyRefresh: number + loadRuns: LoadRoutineRuns + onToggleHistory: () => void + onEdit: () => void + onDelete: () => void + onToggle: (enabled: boolean) => Promise + onRunNow: () => Promise +}): React.JSX.Element { + const t = useTranslate() + const locale = useIntlLocale() + const [enabled, setEnabled] = useState(null) + const [running, setRunning] = useState(false) + const [notice, setNotice] = useState<{ tone: 'ok' | 'error'; text: string } | null>(null) + const historyId = `routine-history-${routine.id}` + const where = + (routine.projectId + ? projects.find((project) => project.id === routine.projectId)?.name + : null) ?? + routine.repo?.url.replace(/^https:\/\/(www\.)?(github\.com\/)?/, '') ?? + null + const isOn = enabled ?? routine.enabled + + const toggle = async (next: boolean): Promise => { + setEnabled(next) + setNotice(null) + const failure = await onToggle(next) + setEnabled(null) + if (failure) { + setNotice({ tone: 'error', text: failure }) + } + } + const runNow = async (): Promise => { + setRunning(true) + setNotice(null) + const failure = await onRunNow() + setRunning(false) + setNotice( + failure + ? { tone: 'error', text: failure } + : { + tone: 'ok', + text: t( + 'auto.components.settings.cloudRoutines.queued', + 'Run queued. It shows up in the history below.' + ) + } + ) + } + + return ( +
  • +
    + +
    +
    +

    + {routine.name} +

    + {!isOn ? ( + + {t('auto.components.settings.cloudRoutines.paused', 'Paused')} + + ) : null} +
    +

    + {describeRoutineTrigger(routine.trigger, t, locale)} +

    +

    + {where ? {where} : null} + {where ? · : null} + {routine.agent === 'codex' ? 'Codex' : 'Claude Code'} + {isOn && routine.nextRunAt ? ( + <> + · + + {t('auto.components.settings.cloudRoutines.nextRun', 'Next run {{value0}}', { + value0: formatRelativeFromNow(routine.nextRunAt, now, locale) + })} + + + ) : null} +

    +
    +
    + {routine.lastRun ? ( + + + {t('auto.components.settings.cloudRoutines.lastRun', 'Last run:')}{' '} + + + + ) : ( + + {t('auto.components.settings.cloudRoutines.neverRun', 'Never run')} + + )} + + + + + + + + + + {t('auto.components.settings.cloudRoutines.edit', 'Edit')} + + + + + {t('auto.components.settings.cloudRoutines.deleteItem', 'Delete…')} + + + + void toggle(next)} + aria-label={t( + 'auto.components.settings.cloudRoutines.enableLabel', + 'Enable {{value0}}', + { value0: routine.name } + )} + /> +
    +
    +

    + {notice?.text ?? ''} +

    + {expanded ? ( +
    + +
    + ) : null} +
  • + ) +} diff --git a/src/renderer/src/components/settings/cloud-api/CreateApiKeyDialog.tsx b/src/renderer/src/components/settings/cloud-api/CreateApiKeyDialog.tsx new file mode 100644 index 00000000000..254e7db094b --- /dev/null +++ b/src/renderer/src/components/settings/cloud-api/CreateApiKeyDialog.tsx @@ -0,0 +1,406 @@ +import { useId, useState } from 'react' +import { KeyRound, Loader2, ShieldAlert } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Checkbox } from '@/components/ui/checkbox' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle +} from '@/components/ui/dialog' +import { Input } from '@/components/ui/input' +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue +} from '@/components/ui/select' +import { useTranslate } from '@/i18n/use-translate' +import { cn } from '@/lib/utils' +import { + CLOUD_API_SCOPES, + type CloudApiCreatedKey, + type CloudApiResult, + type CloudApiScope, + type CreateCloudApiKeyInput +} from '../../../../../shared/cloud-api/cloud-api-types' +import { SettingsSegmentedControl } from '../form-controls/SettingsFormControls' +import { cloudApiErrorCopy, cloudApiScopeDescription } from './cloud-api-copy' +import { isAdminScope, scopesForPreset, type ScopePreset } from './cloud-api-format' +import { CloudApiErrorNotice, CopyValueButton, FormField, ScopeChip } from './cloud-api-parts' + +const EXPIRY_OPTIONS = ['never', '7', '30', '90', '365'] as const +type Expiry = (typeof EXPIRY_OPTIONS)[number] + +export type CreateApiKeyDialogProps = { + open: boolean + onOpenChange: (open: boolean) => void + /** Scopes this viewer may grant (members cannot grant admin-only scopes). */ + availableScopes: readonly CloudApiScope[] + onCreate: (input: CreateCloudApiKeyInput) => Promise> + /** Fixtures: open straight on the one-time secret. */ + initialCreated?: CloudApiCreatedKey +} + +export function CreateApiKeyDialog(props: CreateApiKeyDialogProps): React.JSX.Element { + const { open, onOpenChange } = props + const [created, setCreated] = useState(props.initialCreated ?? null) + // Each open starts fresh; the secret must not survive a close and reopen. + const handleOpenChange = (next: boolean): void => { + if (!next) { + setCreated(null) + } + onOpenChange(next) + } + return ( + + event.preventDefault() : undefined} + > + {created ? ( + handleOpenChange(false)} /> + ) : ( + handleOpenChange(false)} /> + )} + + + ) +} + +function FormStep({ + availableScopes, + onCreate, + onCreated, + onCancel +}: CreateApiKeyDialogProps & { + onCreated: (created: CloudApiCreatedKey) => void + onCancel: () => void +}): React.JSX.Element { + const t = useTranslate() + const ids = useId() + const [name, setName] = useState('') + const [preset, setPreset] = useState('read') + const [custom, setCustom] = useState>( + () => new Set(scopesForPreset('read', availableScopes)) + ) + const [expiry, setExpiry] = useState('90') + const [submitting, setSubmitting] = useState(false) + const [error, setError] = useState(null) + const [nameTouched, setNameTouched] = useState(false) + + const scopes = preset === 'custom' ? [...custom] : scopesForPreset(preset, availableScopes) + const nameMissing = name.trim().length === 0 + const canSubmit = !nameMissing && scopes.length > 0 && !submitting + const restricted = CLOUD_API_SCOPES.filter((scope) => !availableScopes.includes(scope)) + + const submit = async (event: React.FormEvent): Promise => { + event.preventDefault() + setNameTouched(true) + if (!canSubmit) { + return + } + setSubmitting(true) + setError(null) + const result = await onCreate({ + name: name.trim(), + // Keep the canonical order so lists read the same everywhere. + scopes: CLOUD_API_SCOPES.filter((scope) => scopes.includes(scope)), + ...(expiry === 'never' ? {} : { expiresInDays: Number(expiry) }) + }) + setSubmitting(false) + if (result.ok) { + onCreated(result.data) + } else { + setError(cloudApiErrorCopy(result.error, t, result)) + } + } + + const toggle = (scope: CloudApiScope, on: boolean): void => { + setCustom((current) => { + const next = new Set(current) + if (on) { + next.add(scope) + } else { + next.delete(scope) + } + return next + }) + } + + return ( +
    void submit(event)} className="grid gap-5" noValidate> + + + {t('auto.components.settings.cloudApi.create.title', 'Create API key')} + + + {t( + 'auto.components.settings.cloudApi.create.description', + 'Keys act as you inside your Orca Cloud account. Give each script or service its own key so you can revoke it alone.' + )} + + + + + setName(event.target.value)} + onBlur={() => setNameTouched(true)} + /> + + +
    +

    + {t('auto.components.settings.cloudApi.create.permissions', 'Permissions')} +

    + + value={preset} + onChange={(next) => { + if (next === 'custom' && preset !== 'custom') { + setCustom(new Set(scopesForPreset(preset, availableScopes))) + } + setPreset(next) + }} + ariaLabelledBy={`${ids}-perm`} + size="sm" + equalWidth + options={[ + { + value: 'read', + label: t('auto.components.settings.cloudApi.create.readOnly', 'Read only') + }, + { + value: 'full', + label: t('auto.components.settings.cloudApi.create.full', 'Full access') + }, + { + value: 'custom', + label: t('auto.components.settings.cloudApi.create.custom', 'Custom') + } + ]} + /> + {preset === 'custom' ? ( +
    + + {t('auto.components.settings.cloudApi.create.scopesLegend', 'Scopes')} + + {CLOUD_API_SCOPES.map((scope) => { + const locked = !availableScopes.includes(scope) + const id = `${ids}-scope-${scope}` + return ( + + ) + })} +
    + ) : ( +
    + {scopes.map((scope) => ( + + ))} +
    + )} + {restricted.length > 0 ? ( +

    + + {t( + 'auto.components.settings.cloudApi.create.restricted', + 'Only org owners and admins can grant {{value0}}. Ask one of them if a script needs it.', + { value0: restricted.join(', ') } + )} +

    + ) : null} + {preset === 'custom' && scopes.length === 0 ? ( +

    + {t( + 'auto.components.settings.cloudApi.create.scopeRequired', + 'Pick at least one scope.' + )} +

    + ) : null} +
    + + + + + + {error ? : null} + + + + + + + ) +} + +function SecretStep({ + created, + onDone +}: { + created: CloudApiCreatedKey + onDone: () => void +}): React.JSX.Element { + const t = useTranslate() + const ids = useId() + const [copied, setCopied] = useState(false) + return ( +
    + + + {t('auto.components.settings.cloudApi.secret.title', 'Copy your new key')} + + + {t( + 'auto.components.settings.cloudApi.secret.description', + '“{{value0}}” is ready to use.', + { + value0: created.key.name + } + )} + + + +
    + +

    + + {t( + 'auto.components.settings.cloudApi.secret.onceTitle', + 'This is the only time Orca shows this key.' + )} + {' '} + {t( + 'auto.components.settings.cloudApi.secret.onceBody', + 'Store it in a password manager or your CI secrets now. If you lose it, revoke it and create a new one.' + )} +

    +
    + +
    + +
    + event.currentTarget.select()} + /> + setCopied(true)} + /> +
    +
    + + + + +
    + ) +} diff --git a/src/renderer/src/components/settings/cloud-api/RoutineAgentSection.tsx b/src/renderer/src/components/settings/cloud-api/RoutineAgentSection.tsx new file mode 100644 index 00000000000..e6fd97b72b3 --- /dev/null +++ b/src/renderer/src/components/settings/cloud-api/RoutineAgentSection.tsx @@ -0,0 +1,177 @@ +import { useId } from 'react' +import { Input } from '@/components/ui/input' +import { Textarea } from '@/components/ui/textarea' +import { translate } from '@/i18n/i18n' +import { useTranslate, type Translate } from '@/i18n/use-translate' +import { SettingsSegmentedControl } from '../form-controls/SettingsFormControls' +import { FormField } from './cloud-api-parts' +import type { RoutineDraft, RoutineDraftField } from './routine-draft' + +export function routineFieldError( + code: string | undefined, + field: RoutineDraftField, + t: Translate = translate +): string | null { + if (!code) { + return null + } + switch (field) { + case 'name': + return t( + 'auto.components.settings.cloudRoutines.editor.nameRequired', + 'Give the routine a name.' + ) + case 'source': + return t('auto.components.settings.cloudRoutines.editor.projectRequired', 'Pick a project.') + case 'repoUrl': + return code === 'required' + ? t( + 'auto.components.settings.cloudRoutines.editor.repoRequired', + 'Enter the repository URL.' + ) + : t( + 'auto.components.settings.cloudRoutines.editor.repoInvalid', + 'Use an https URL, like https://github.com/acme/api.' + ) + case 'customCron': + return code === 'required' + ? t( + 'auto.components.settings.cloudRoutines.editor.cronRequired', + 'Enter a five-field cron.' + ) + : t( + 'auto.components.settings.cloudRoutines.editor.cronInvalid', + 'That cron expression is not valid.' + ) + case 'githubEvents': + return t( + 'auto.components.settings.cloudRoutines.editor.eventsRequired', + 'Pick at least one event.' + ) + case 'prompt': + return t( + 'auto.components.settings.cloudRoutines.editor.promptRequired', + 'Tell the agent what to do.' + ) + case 'maxRuntimeMinutes': + return t( + 'auto.components.settings.cloudRoutines.editor.runtimeInvalid', + 'Use a whole number from 1 to 720.' + ) + } +} + +/** Agent, prompt, what happens with the result, and the time limit. */ +export function RoutineAgentSection({ + draft, + update, + errors +}: { + draft: RoutineDraft + update: (patch: Partial) => void + errors: Partial> +}): React.JSX.Element { + const t = useTranslate() + const ids = useId() + const err = (field: RoutineDraftField): string | null => + routineFieldError(errors[field], field, t) + return ( +
    +

    + {t('auto.components.settings.cloudRoutines.editor.what', 'What the agent does')} +

    +
    +

    + {t('auto.components.settings.cloudRoutines.editor.agent', 'Agent')} +

    + + size="sm" + value={draft.agent} + onChange={(agent) => update({ agent })} + ariaLabelledBy={`${ids}-agent`} + options={[ + { value: 'claude', label: 'Claude Code' }, + { value: 'codex', label: 'Codex' } + ]} + /> +
    + +